getting error when using FirebaseRecyclerView, No static method zza(Landroid/app/Application;)V in class Lcom/google/android/gms/internal/zzaac;

Question: I am making a blog app using Firebase for Android.
But I am getting an error when application starts. My code is fully right, but I am still getting this error.
Here is the catlog error
 java.lang.NoSuchMethodError: No static method zza(Landroid/app/Application;)V in class Lcom/google/android/gms/internal/zzaac; or its super classes (declaration of 'com.google.android.gms.internal.zzaac' appears in /data/app/com.a000webhostapp.androidgrid.devtips-1/split_lib_dependencies_apk.apk)
                                                                                at com.google.firebase.FirebaseApp.zzcl(Unknown Source)
                                                                                at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                                                                                at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                                                                                at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                                                                                at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown Source)
                                                                                at android.content.ContentProvider.attachInfo(ContentProvider.java:1751)
                                                                                at android.content.ContentProvider.attachInfo(ContentProvider.java:1726)
                                                                                at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
                                                                                at android.app.ActivityThread.installProvider(ActivityThread.java:5853)
                                                                                at android.app.ActivityThread.installContentProviders(ActivityThread.java:5445)
                                                                                at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5384)
                                                                                at android.app.ActivityThread.-wrap2(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1545)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Here's my model Blog.java
public class Blog {

private String title;
private String desc;

public Blog(){

}

public Blog(String title, String desc) {
    this.title = title;
    this.desc = desc;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getDesc() {
    return desc;
}

public void setDesc(String desc) {
    this.desc = desc;
}

}
Here's my MainActivity.java
public class MainActivity extends AppCompatActivity {
private RecyclerView recycleView;
private DatabaseReference fDatabase;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    fDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");

    recycleView = (RecyclerView) findViewById(R.id.recyleView);
    recycleView.setHasFixedSize(true);
    recycleView.setLayoutManager(new LinearLayoutManager(this));
}

@Override
protected void onStart() {
    super.onStart();

    FirebaseRecyclerAdapter<Blog, BlogViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>(
            Blog.class,
            R.layout.post_list_layout,
            BlogViewHolder.class,
            fDatabase
    ) {
        @Override
        protected void populateViewHolder(BlogViewHolder viewHolder, Blog model, int position) {

            viewHolder.setTitle(model.getTitle());
            viewHolder.setDesc(model.getDesc());

        }
    };

    recycleView.setAdapter(firebaseRecyclerAdapter);
}

public static class BlogViewHolder extends RecyclerView.ViewHolder {

    View mView;
    public BlogViewHolder(View itemView){
        super(itemView);

        mView = itemView;
    }

    public void setTitle(String title){
        TextView post_title = (TextView) mView.findViewById(R.id.txtBlogTitle);

        post_title.setText(title);

    }

    public void setDesc(String desc){
        TextView post_desc = (TextView) mView.findViewById(R.id.txtBlogDesc);

        post_desc.setText(desc);
    }

}

}
Thanks in advance...
Answer: Do change all the firebase and Google-play-services library versions to the same in your dependencies under app.gradle file.


Calculating operator (matrix) norms using eigenvalues?

Question: A remark that went unproven in class.
It was said that the operator norm of a real linear transformation (real matrix) is the square root of the abs value of the max eigenvalue of $A^T*A$ (or maybe $A*A^T$?).
If $A$ is symmetric (and therefore orthonormally diagonalizable) everything is straightforward...
But the same calculation for $A^T*A$ only yields the norm of $A^T*A$....
So I want to prove the following lemmas, but they might not be true:
1. The norm of $A$ equals the norm of its transpose.
2. Multiplicative property of the norm when restricting to $A^T*A$
Are any of these true, and why?
If not, how can I prove the original claim?
Comment: Consider bilinear form $x,y\mapsto (Ax,y)$ where $(u,v)=\sum_ju_jv_j$. Show that $\lVert A\rVert=\sup_{\lVert x\rVert,\lVert y\rVert\le1}\lvert(Ax,y)\rvert$. Note that $(Ax,y)=(A,A^Ty)$, and conclude that $\lVert A\rVert=\lVert A^T\rVert$. Now we have $\lVert A^TA\rVert\le\lVert A\rVert^2$. For the opposite inequality, just recall the definition that $\lVert A\rVert^2=\sup_{\lVert x\rVert\le1}(Ax,Ax)=\sup_{\lVert x\rVert\le1}(x,A^TAx)$.
Comment: Another proof by polar decomposition (which should be left as an exercise) is also instructive: suppose first that $A$ is invertible, then $A^TA$ is positive definite, then there exists positive definite $B$ such that $A^TA=B^2$. hence $A=OB$ for some orthogonal matrix $O$, which holds even if $A$ isn't invertible. Now $\lVert A^TA\rVert=\lVert B\rVert^2=\lVert A\rVert^2$. Most steps aren't that direct for beginners, hence are exercises.
Comment: $*$ means matrix multiplication? Usually we don't add $*$.
Comment: yes, matrix mult'.
Answer: The fact you need is that, for the operator norm, $\|AB\|\leq\|A\|\,\|B\|$. With this,:
\begin{align}
\|A\|^2&=\sup\{\|Ax\|^2:\ \|x\|=1\}=\sup\{(Ax)^TAx:\ \|x\|=1\}
=\sup\{x^TA^TAx:\ \|x\|=1\}\\
&\leq\sup\{\|A^TAx\|\,\|x\|:\ \|x\|=1\}=\sup\{\|A^TAx\|:\ \|x\|=1\}\\
&\leq\|A^TA\|,
\end{align}
where the first inequality is Cauchy-Schwarz and the second one is just by definition of the supremum norm.
Then
$$
\|A\|^2\leq\|A^TA\|\leq\|A^T\|\,\|A\|,
$$
from where we obtain $\|A^T\|\leq\|A\|$. But we can apply this last inequality to $A^T$, and so $\|A^T\|=\|A\|$, and $\|A\|^2=\|A^TA\|$.
Answer:
The norm you talking about is a matrix $L_2$ norm  which is defined as following
$$\|A\|_2=\sqrt{\max_n\lambda_n(AA^t)}
$$
where $\lambda_n(B)$ is a n'th eigenvalue of matrix $B$.

This norm is induced from a vector $L_2$ norm given by
$$\|v\|_2=\sqrt{\sum_i |v_i|^2}$$

A matrix norm induced from a vector norm is defined by
$$\|A\|=\max_{v}\frac{\|Av\|}{\|v\|}$$
however this is not the only way to get matrix norm (there are norms which aren't induced from a vector norm, e.g. Frobineous norm).
The property $\|A\|=\|A^T\|$ is not always true, for example for
$L_1$ and $L_\infty$ for matrices the following is true
$\|A\|_1=\|A^T\|_\infty$
For a quadratic matrices we have $\|AB\|\le \|A\|\|B\|$


android camera2 api MediaRecorder stop() error

Question: I am very new in android and I am trying to create a simple video recorder app using android camera2 api. By following a tutorial on youtube I managed to preview the camera in a TextureView and start capturing with MediaRecorder, but I am having trouble on stopping the recorder and saving the video to my device storage.
This error appears on MediaRecorder.stop()

W/Adreno-EGLSUB: : dequeue native buffer fail: No such device, buffer=0x0, handle=0x0
  W/Adreno-EGL: : EGL_BAD_SURFACE
  E/CameraDeviceGLThread-0: Received exception on GL render thread:
                            java.lang.IllegalStateException: swapBuffers: EGL error: 0x300d
                                at android.hardware.camera2.legacy.SurfaceTextureRenderer.checkEglError(SurfaceTextureRenderer.java:544)
                                at android.hardware.camera2.legacy.SurfaceTextureRenderer.swapBuffers(SurfaceTextureRenderer.java:537)
                                at android.hardware.camera2.legacy.SurfaceTextureRenderer.drawIntoSurfaces(SurfaceTextureRenderer.java:741)
                                at android.hardware.camera2.legacy.GLThreadManager$1.handleMessage(GLThreadManager.java:105)
                                at android.os.Handler.dispatchMessage(Handler.java:98)
                                at android.os.Looper.loop(Looper.java:148)
                                at android.os.HandlerThread.run(HandlerThread.java:61)
  I/CameraDeviceState: Legacy camera service transitioning to state ERROR

I am using an Android 6.0 api23 device to run the app.
Thanks
EDIT:
Here is the stopRecording function.
<code>                try{
                    previewSession.stopRepeating();
                    previewSession.abortCaptures();
                }catch(CameraAccessException e){
                    e.printStackTrace();
                }
                recorder.stop();
                recorder.reset();
                isRecording = false;
                Toast.makeText(getApplicationContext(),"Recording Stopped",Toast.LENGTH_SHORT).show();
</code>
...based on @NewOne's answer, I included the try catch before the recorder.stop() then I have a new error

--------- beginning of crash E/AndroidRuntime: FATAL EXCEPTION: main
                    Process: com.tingker.daryl.camera2, PID: 9014
                    Theme: themes:{default=overlay:com.cyngn.hexo, iconPack:com.cyngn.hexo, fontPkg:com.cyngn.hexo,
  com.android.systemui=overlay:com.cyngn.hexo,
  com.android.systemui.navbar=overlay:com.cyngn.hexo}
                    java.lang.IllegalStateException: Session has been closed; further changes are illegal.
                        at android.hardware.camera2.impl.CameraCaptureSessionImpl.checkNotClosed(CameraCaptureSessionImpl.java:606)
                        at android.hardware.camera2.impl.CameraCaptureSessionImpl.stopRepeating(CameraCaptureSessionImpl.java:272)
                        at com.tingker.daryl.camera2.MainActivity$2.onClick(MainActivity.java:121)
                        at android.view.View.performClick(View.java:5204)
                        at android.view.View$PerformClick.run(View.java:21158)
                        at android.os.Handler.handleCallback(Handler.java:739)
                        at android.os.Handler.dispatchMessage(Handler.java:95)
                        at android.os.Looper.loop(Looper.java:148)
                        at android.app.ActivityThread.main(ActivityThread.java:5461)
                        at java.lang.reflect.Method.invoke(Native Method)
                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Answer: I don't know, currently, what is there in your stop recording method. If you could share, may be I can help better. Anyways make sure you have the below lines of code before you call the stop method.
<code>private void stopRecording()) {

        .....

        try {
            preview.stopRepeating();
            preview.abortCaptures();
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }

        try{
           mediaRecorder.stop();
        }catch(RuntimeException e){
           //handle the exception
        }
        mediaRecorder.reset();

        ......
    }
</code>
Check this link. You may catch the exception if you are stopping the recorder immediately after starting it.
Comment: hey thanks, I found out that there were two CameraCaptureSession that were set in my code - on the setup of camera preview and the other one on starting the media recorder. The one I used on the stopRecording() was the session of the camera preview which caused the new error.
..Now I tried to use the session set when starting the media recorder then it all went okay and problem solved.

Thanks man, I marked your answer as the correct one.
Comment: Are you calling stop method immediately after starting the recorder? This is from android developer website: Note that a RuntimeException is intentionally thrown to the application, if no valid audio/video data has been received when stop() is called. This happens if stop() is called immediately after start(). The failure lets the application take action accordingly to clean up the output file (delete the output file, for instance), since the output file is not properly constructed when this happens. Please see my edited answer
Comment: Happy to know that your problem has been fixed.
Comment: @Handsum you said `the session set when starting the media recorder` on above comment. I wish could please can explain bit more.


Linking from an activity to a fragment activity with a button using actionBarSherlock

Question: I made a project wherein when you click a button from the MainActivity, it will lead to a fragment activity. But I can't seem to make it work.
Here's a snippet of my code for the button in MainActivity:
Button button2 = (Button) findViewById(R.id.button2);
    button2.setOnClickListener(new OnClickListener () {

        public void onClick(View v) {

            Intent intent = new Intent (v.getContext(), page3.class);
            startActivityForResult(intent, 0);
        }
    }) ;

Here's my snippet for page3 where the button from MainActivity leads to:
package com.example.pixelapp3;

import android.os.Bundle;
import android.support.v4.view.ViewPager;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;

public class page3 extends SherlockFragmentActivity {

private ViewPager mViewPager;
private TabsAdapter mTabsAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mViewPager = new ViewPager(this);
    mViewPager.setId(R.id.pager);
    setContentView(mViewPager);

    final ActionBar bar = getSupportActionBar();
    bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    mTabsAdapter = new TabsAdapter(this, mViewPager);
    mTabsAdapter.addTab(bar.newTab().setText("Fragment 1"), page3a.class, null);
    mTabsAdapter.addTab(bar.newTab().setText("Fragment 2"), page3b.class, null);
    mTabsAdapter.addTab(bar.newTab().setText("Fragment 3"), page3c.class, null);
    mTabsAdapter.addTab(bar.newTab().setText("Fragment 4"), page3d.class, null);
}

}
Here's the page3.xml snippet:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".mainActivity" >

<android.support.v4.view.ViewPager
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/pager"/>

</RelativeLayout>

Here's page3a.java:
package com.example.pixelapp3;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.actionbarsherlock.app.SherlockFragmentActivity;

public class page3a extends SherlockFragmentActivity {

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    return inflater.inflate(R.layout.page3a, null);
}

}

Here's the logCat when I click the button that doesn't work:
  06-04 10:46:14.871: I/ActionBarSherlock(907): Registering ActionBarSherlockCompat with qualifier @com.actionbarsherlock.ActionBarSherlock$Implementation(api=7, dpi=-1)
06-04 10:46:14.871: I/ActionBarSherlock(907): Registering ActionBarSherlockNative with qualifier @com.actionbarsherlock.ActionBarSherlock$Implementation(api=14, dpi=-1)
06-04 10:46:14.971: I/ActionBarSherlock(907): Using implementation: ActionBarSherlockNative
06-04 10:46:14.971: D/ActionBarSherlock(907): [<ctor>] activity: com.example.pixelapp3.page3@41219338, flags: 1
06-04 10:46:14.971: D/ActionBarSherlock(907): [setContentView] view: android.support.v4.view.ViewPager@4121c920
06-04 10:46:14.971: D/ActionBarSherlock(907): [setContentView] view: android.support.v4.view.ViewPager@4121c920, params: android.view.ViewGroup$LayoutParams@4122b4f0
06-04 10:46:15.212: D/ActionBarSherlock(907): [getActionBar]
06-04 10:46:15.222: D/ActionBarSherlock(907): [getActionBar]
06-04 10:46:15.361: V/21st Polling:(907): clicked
06-04 10:46:15.671: D/dalvikvm(907): GC_CONCURRENT freed 178K, 4% free 8234K/8519K, paused 74ms+88ms, total 260ms
06-04 10:46:15.671: D/AndroidRuntime(907): Shutting down VM
06-04 10:46:15.681: W/dalvikvm(907): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
06-04 10:46:15.761: E/AndroidRuntime(907): FATAL EXCEPTION: main
06-04 10:46:15.761: E/AndroidRuntime(907): java.lang.ClassCastException: com.example.pixelapp3.page3a cannot be cast to android.support.v4.app.Fragment
06-04 10:46:15.761: E/AndroidRuntime(907):  at android.support.v4.app.Fragment.instantiate(Fragment.java:394)
06-04 10:46:15.761: E/AndroidRuntime(907):  at com.example.pixelapp3.TabsAdapter.getItem(TabsAdapter.java:97)
06-04 10:46:15.761: E/AndroidRuntime(907):  at android.support.v4.app.FragmentPagerAdapter.instantiateItem(FragmentPagerAdapter.java:97)
06-04 10:46:15.761: E/AndroidRuntime(907):  at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:829)
06-04 10:46:15.761: E/AndroidRuntime(907):  at android.support.v4.view.ViewPager.populate(ViewPager.java:979)
06-04 10:46:15.761: E/AndroidRuntime(907):  at android.support.v4.view.ViewPager.populate(ViewPager.java:911)
06-04 10:46:15.761: E/AndroidRuntime(907):  at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1432)
06-04 10:46:15.761: E/AndroidRuntime(907):  at android.view.View.measure(View.java:15172)
06-04 10:46:15.761: E/AndroidRuntime(907):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4816)
06-04 10:46:15.761: E/AndroidRuntime(907):  at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
06-04 10:46:15.761: E/AndroidRuntime(907):  at android.view.View.measure(View.java:15172)
06-04 10:46:15.761: E/AndroidRuntime(907):  at android.widget.LinearLayout.measureVertical(LinearLayout.java:833)
06-04 10:46:15.761: E/AndroidRuntime(907):  at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
06-04 10:46:15.761: E/AndroidRuntime(907):  at android.view.View.measure(View.java:15172)
06-04 10:46:15.761: E/AndroidRuntime(907):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4816)
06-04 10:46:15.761: E/AndroidRuntime(907):  at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
06-04 10:46:15.761: E/AndroidRuntime(907):  at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2148)
06-04 10:46:15.761: E/AndroidRuntime(907):  at android.view.View.measure(View.java:15172)
06-04 10:46:15.761: E/AndroidRuntime(907):  at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1850)
06-04 10:46:15.761: E/AndroidRuntime(907):  at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1102)
06-04 10:46:15.761: E/AndroidRuntime(907):  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1275)
06-04 10:46:15.761: E/AndroidRuntime(907):  at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
06-04 10:46:15.761: E/AndroidRuntime(907):  at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4214)
06-04 10:46:15.761: E/AndroidRuntime(907):  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
06-04 10:46:15.761: E/AndroidRuntime(907):  at android.view.Choreographer.doCallbacks(Choreographer.java:555)
06-04 10:46:15.761: E/AndroidRuntime(907):  at android.view.Choreographer.doFrame(Choreographer.java:525)
06-04 10:46:15.761: E/AndroidRuntime(907):  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
06-04 10:46:15.761: E/AndroidRuntime(907):  at android.os.Handler.handleCallback(Handler.java:615)
06-04 10:46:15.761: E/AndroidRuntime(907):  at android.os.Handler.dispatchMessage(Handler.java:92)
06-04 10:46:15.761: E/AndroidRuntime(907):  at android.os.Looper.loop(Looper.java:137)
06-04 10:46:15.761: E/AndroidRuntime(907):  at android.app.ActivityThread.main(ActivityThread.java:4745)
06-04 10:46:15.761: E/AndroidRuntime(907):  at java.lang.reflect.Method.invokeNative(Native Method)
06-04 10:46:15.761: E/AndroidRuntime(907):  at java.lang.reflect.Method.invoke(Method.java:511)
06-04 10:46:15.761: E/AndroidRuntime(907):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
06-04 10:46:15.761: E/AndroidRuntime(907):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
06-04 10:46:15.761: E/AndroidRuntime(907):  at dalvik.system.NativeStart.main(Native Method)

Here's the MainActivity
Here's the page3(including page3a to page3d fragments
I've been stuck here for days. Any type of help is appreciated. Thanks in advance!
Comment: Can't really interpret logCat errors that much. Thanks!
Answer: Try using this button implementation instead :
 in your layout :
       <Button
        android:id="@+id/btnLogin"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="yourmethod"
        android:text="button2" />

your code :

     public void yourmethod(View v){
   //do somthing on button press
    }

Comment: Thanks!

we have basically the same button layout, the only difference is that my text="@string/button2" when I use your syntax, the button shows errors that somehow runs the program on some Android platforms and crashes on others.

Really appreciate it!
Comment: What is the usual code to use to open a new activity? It's using intents right? Here's what I have used in by clickButton action:

public void onClick(View v) {

          Intent intent = new Intent (v.getContext(), page5.class);
          startActivityForResult(intent, 0);
         }
Comment: yes its using intent but when your using fragment you will use it this way :
Intent intent=new Intent(getActivity().getBaseContext(),page5.class);
startActivity(intent);
use getActivity().getBaseContext() instead of v.getContext() and double check that your activity is defined in your minifest
Comment: I tried doing so with this code:
Intent intent = new Intent(getActivity().getBaseContext(),page3.class);

but is having an error:
method getActivity() is undefined for the type new View.OnClickListener(){}

and yes, the activity is defined in my manifest. Is this how you have it in mind?
Comment: correction it the manifest code should be this:
Comment: yes its right , i think i missed something my solution was if you have the button in the fragment but if you have the button in the main activity the correct way to start an activity using intent would be:
Intent Intent = new Intent( MainActivity.this,page3.class );
startActivity(Intent);
Comment: Thanks, I made the code like so:

Intent intent = new Intent(MainActivity.this,page3.class);
          startActivity(intent);

No errors or warnings, but when I run the app on the emulator and click the button, the fragment would still not load.

Am I missing something on my page3.java file?
Comment: The code you gave works on other pages, the problem is with opening the fragment page/s.
Comment: can you try to run it in a device instead of the Emulater ?
are you using the button implementation i gave you or the old one using  button2.setOnClickListene .. ?
Comment: I ran the app on the emulator, on a Samsung S Duos, as well as an S3 Mini. Both of their OS are compatible with the app.
Comment: in page3 class you can use normal setContentView(R.layout.page3);
exactly like a normal activity
Comment: Tried it. Works, BUT, it doesn't show the other fragment pages.
Comment: you mean that you want to show a fragment each time you click in a tab ?
Comment: if i answered the main question and it works can you mark my answer as accepted :) and as for the inflating fragments in tab click you need to implement
ActionBar.TabListener as you can see in this answer :)
http://stackoverflow.com/questions/12721949/implementing-a-tablistener-using-the-support-library
Comment: I've edited and included images in the original question, that's what I was trying to ask about in general.
Comment: I already have my tabs and fragments readied, the only problem is when the button is clicked, it does not load the fragment.
Comment: all the layouts and functions are working quite ok already, and the only remaining problem is to allow proper linking from the activity through the button to the fragments. Once done, I can fix the ui, design and layout then there's my first android app :)

Btw, I really really appreciate your help. Thank you once again. :)
Comment: try to edit the question and add the code for page3a.class that supposed to be one of the fragments ..
Comment: Hi, I have included the page3a.java codes in the original question right before the logCat.
Comment: If you like, I could send you my project files so that it would be much easier to explain
Answer: The interesting (to you) part is what follows FATAL EXCEPTION
You appear to be setting up a ViewPager and at some point in this process you are trying to cast an object of type com.example.pixelapp3.page3a to a Fragment class. As the object is not a fragment, it is throwing an exception.
That is as much as I can tell from the code you provided.
I would try to get the simple stuff working before attempting to complicate matters with tabs and ViewPager's
Comment: Thanks! Here's my code for page3a:

package com.example.pixelapp3;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.actionbarsherlock.app.SherlockFragmentActivity;

public class page3a extends SherlockFragmentActivity {

 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
  return inflater.inflate(R.layout.page3a, null);
 }

}

Could you help me with what went wrong?
Comment: Your code is too complex to diagnose from tiny snippets but nowhere do I see you actually create a fragment and pass it into your actionbar. Have a look at the many examples on the internet such as http://arvid-g.de/12/android-4-actionbar-with-tabs-example


Video streaming

Question: anyone that can help would be greatly appreciated.
I want to setup a video streaming service from my server. I want to store videos on this. Now I was thinking of streaming the video through some form of player (e.g. JWPlayer) and (a) allowing users to step through the video frame by frame (b) tagging the video by associating text (data) with any frame (time) in the video (c) being able to jump to these tags (d) use the tags to reference the video.
What are the best components for achieving this with say up to 100 concurrent users?
Max.
Comment: Is the server you are streaming from Windows or Apache?
Answer: I'm not sure about the server architecture you'd use for this, but definitely look into:
http://flowplayer.org/index.html as a supplement
Comment: JW player is also an option. And is free.

Video streaming


Probability: Rolling two dice (find pmf)

Question: Two fair dice are rolled. Let X and Y denote the largest and smallest
values obtained, respectively. Compute the conditional mass function of Y given
X = i, i = 1, 2, 3, 4, 5, 6. Are X and Y independent? Why?
I am stuck on this question. Well I know that the conditional probability is
$$ P(X|Y) = \frac{P\{ X=x, Y=y\}}{P\{Y=y\}} $$ but I'm not really sure what to do with in this question. I think we let j the the values of Y so we have j < i, and I dont know how to continue.
Comment: The pmf of Y is uniformly distributed between the points available. These are clearly not independent, consider when $X=1$
Answer: Suppose for instance that $X=2$. Then the possible outcomes of the two rolls of the dice are $(1,2),(2,1)$, and $(2,2)$, all with equal probability.
This tells us that the possible values of $Y$ (given that $X=2$) are 1 and 2, and that $\mathbb{P}(Y=1|X=2)=\frac{2}{3}$, while $\mathbb{P}(Y=2|X=2)=\frac{1}{3}$. The same method works for the other values of $X$.
To elaborate on my answer, if $X=i$ then there are $2i-1$ outcomes, namely the $2i-2$ pairs $(i,j)$ and $(j,i)$ for $j<i$ and the outcome $(i,i)$. Each of these outcomes has equal probability. Therefore $\mathbb{P}(Y=j|X=i)=\frac{2}{2i-1}$ if $1\leq j<i$, and $\mathbb{P}(Y=i|X=i)=\frac{1}{2i-1}$.
Comment: could you provide a few more pointers? So I noticed that for $X = i$ there are  $i$*$n - 1$ possible outcomes. And $Y$ has $i$ possible values. Should I try to think how to relate this to $P\{X=i,Y=j\} $?


Find a general formula for a tangent to a cubic which, is also normal to the cubic at the second intersection

Question: Let me preface by saying that I am not a professional mathematician, I just like to do some math in my spare time.
I assume someone has tried this before but I can't find the right words to type into a search engine to get me what I want.
As the title says, I would like some way to find the point on a general cubic such that a tangent at that point intersects the cubic once more at right angles.
I'd like to attempt it myself, and I've outlined a plan of attack:

Let there exist a cubic polynomial $f(x)=ax^3+bx^2+cx+d$
Set up the equation of the tangent at $x=x_T$. This would be $g(x)=f'(x_T)(x-x_T)+f(x_T)$
Find the second intersection point of $g(x)$ and $f(x)$ in terms of $x_T$, call it $x_N$
Let $f'(x_N)=-\frac{1}{f'(x_T)}$
Solve for $x_T$ in terms of $a$, $b$, $c$, and $d$

Problems:

Not all cubics would have this property. At the very least they should have two turning points, for which I know $b^2 > 3ac$, but I still don't think that's sufficient
I have to solve a general cubic equation which I know has a formula but it's horrendous
I don't even know if my plan of attack makes sense

Any help at all would be appreciated.
Note this is not a homework problem, just something I'm interested in solving.
Thank you.
Comment: Just some comments that might help. Just like in the derivation of how to obtain roots for a third order polynomial, you can simplify your problem by first making $b = 0$ (this is done by considering a substitution of the form $x' = x - m$ for an appropriate $m$)
Comment: Also, I think you can assume that $a = 1$. This would be achieved by making a second change of variable $x'' = \frac{x'}{\sqrt[3]{a}}$. Notice that the translation I suggested does not change shapes, but this homothety does change shapes. However, since homotheties do not change angles, you might be ok.
Comment: Finally, I strongly suggest you to watch a recent video of the [Mathologer channel](https://www.youtube.com/watch?v=N-KXStupwsc) that talks precisely about the derivation of solutions to a cubic polynomial.
Answer: No reason to consider any curve other than $y = x^3 - px,$ where $p > 0$ is constant.
Hard enough for $y = x^3 - 3 x.$ The point where we take the tangent is at $x=a,$ with
$$ a = - \sqrt{ \frac{45 + \sqrt{585}}{72}} \; \; \approx \; \; -0.9802690478532443368005527022 $$
The tangent line at $(a, a^3 - 3a)$intersects the curve again when $x = -2a \; \; \approx \; \; 1.960538095706488673601105404$
The slope of the tangent line at $a$ is $-0.1172177814626812934541733462$
The slope of the tangent line at $-2a$ is $8.531128874149274826183306615 $
The product of these two slopes is $-1$ meaning the first tangent, at $a,$ is orthogonal to the curve at $-2a$

Need to check more, it is possible that $x=b,$ with
$ b = - \sqrt{ \frac{45 - \sqrt{585}}{72}} \; \; \approx \; \; -0.5376547161709769327639370480 $ also works. I can see, this $b$ also works!

For your own pictures, the two tangent lines are $y$ set to
$$    -0.1172177814626812934541733462 x + 1.883934787022560496398167095  $$
$$    -2.132782218537318706545826654 x + 0.3108424867671614744956344943  $$
Friday: if my $p$ is less than or equal to zero, a tangent to the graph of $y = x^3 - p x$ probably does intersect the curve again. However, a normal line to the curve never again intersects the curve. Below is a picture for $y=x^3$

Well, why not. Given real $\delta > 0,$ the slope of $y = x^3 + \delta x$ is $3x^2 + \delta$ and always positive. Any curve $y = g(x)$ that joins two distinct points of the cubic must have a point with positive slope, by the Mean Value Theorem. However, a normal line to the cubic has negative slope, therefore cannot intersect $y = x^3 + \delta x$ a second time.
Comment: The graph has the origin as center of symmetry so it should work also for the symmetric points. Also, if the cubic has rational coefficients the  absolute Galois group of $\mathbb{Q}$ acts on these points.
Comment: @OrestBucicovschi thanks for your comments. I built in the rotational symmetry, of course. I note the other answer allows for my $p \leq 0,$ but I claim that a line normal to the graph $y = x^3$ does not intersect the graph again (with real coordinates, I guess).
Answer: Here's an approach that starts at the point $(a, f(a))$ of intersection of degree $1$, rather than at the point $(x_T, f(x_T))$ at which the line is tangent.
Rescaling (changing coordinates by $(x, y) \rightsquigarrow (\tilde x, \tilde y) = (\lambda x, \lambda y)$, $\lambda > 0$), reflecting across the $x$-axis ($(x, y) \rightsquigarrow (-x, y)$) and translating ($(x, y) \rightsquigarrow (x - h, y + k)$ for constants $h, k$) preserve tangency and orthogonality of curves, so we may use the freedom of those coordinate changes to reduce the problem to the case $$f(x) = x^3 - C x .$$
Now, the line orthogonal to the graph of $f$ at $x = a$ is the graph of
$$O(x) = f(a) - \frac{1}{f'(a)} (x - a) = a^3 - C a - \frac{x - a}{3 a^2 - C}$$ (except, if $C > 0$, where $a = \pm \sqrt\frac{C}{3}$, where the line is vertical, and hence does not intersect the graph of $f$ anywhere else).
Now, $f$ and $O$ have an intersection of multiplicity $1$ at $(a, f(a))$, so $O$ is tangent to $f$ if and only if $f - O$ has a multiple root. But a polynomial has a multiple root iff its discriminant $\Delta$ is zero. By construction, $f - O$ is a depressed cubic (that is, its quadratic coefficient is zero, so that it has the form $x \mapsto x^3 + p x + q$), so $$\Delta = -4 p^3 - 27 q^2 = \frac{[9 a^4 - 15 C a^2 + (4 C^2 + 4)][9 a^4 - 6 C a^2 + (C^2 + 1)]}{(-3 a^2 + C)^3} .$$
The second factor in the numerator is $(3 a^2 - C)^2 + 1 > 0$, so $\Delta = 0$ iff $$\phantom{(ast)} \qquad 9 a^4 - 15 C a^2 + (4 C^2 + 4) = 0 . \qquad (\ast)$$

(Solutions $(C, a)$.)
If $C < 0$, then the left-hand side is $(3 a^2)^2 + (\sqrt{- 15 C} a)^2 + 4 C^2 + 4 > 0,$ so there are no solutions---this recovers exactly the necessary condition $C \geq 0$ on the discriminant observed in the question statement (and specialized to our normal form for $f$).
Now, $(\ast)$ is a biquadratic equation in $a$, and completing the square in $a^2$, rearranging, and clearing denominators gives the equivalent equation
$$(6 a^2 - 5 C)^2 = 9 C^2 - 16 .$$
We can now directly solve for $a$ as a function of $C$. In particular, we see that a necessary (and, one can see directly, sufficient) condition for the existence of a line satisfying the criteria is $C \geq \frac{4}{3}$. Moreover, we can see that:

If $C > \frac{4}{3}$ there are four solutions, given by
$$a = \pm \frac{1}{6} \sqrt{30 C \pm' 6 \sqrt{9 C^2 - 16}} .$$

(Typical generic case, $C = 2$)

In the critical case $C = \frac{4}{3}$ there are two solutions,
$$a = \pm \frac{\sqrt{10}}{3} .$$

(Critical case, $C = \frac{4}{3}$.)
Remark 1 Applying as appropriate a reflection, a rescaling, and a translation to bring the general form $f(x) = a x^3 + b x^2 + c x + d$ to our normal form $f(x) = x^3 - C x$, we see that the condition $C \geq \frac{4}{3}$ for the existence of solutions corresponds to the inequality $b^2 - 3 a c \geq 4 |a|$, which again is strictly stronger than the condition $b^2 - 3 a c \geq 0$ in the original question statement.
Remark 2 An interesting feature of this situation is that as $C \to \infty$, the horizontal spacing of the four orthogonal intercepts approaches $1 : 2 : 1$, and since this ratio is preserved by the applied transformations, the conclusion also applies to $f$ of the general form. Indeed, the asymptotic behaviors of the four solutions are
$$\pm \sqrt{\frac{C}{3}}, \quad \pm 2 \sqrt{\frac{C}{3}} \pmod {O(C^{-3 / 2})} .$$
Answer:
As recommended by others, consider the cubic
$$y(x)=x^3-bx$$
The slope of the line joining $x_1,y(x_1)$ to $x_2,y(x_2)$ is
$$\frac{x_1^3-x_2^3-b(x_1-x_2)}{(x_1-x_2)}=x_1^2+x_1x_2+x_2^2-b$$
If this is also the slope of the tangent at $x_1$ we have
$$x_1^2+x_1x_2+x_2^2-b=3x_1^2-b$$
 which has the solution $x_2=x_1$ and the less trivial $x_2=-2x_1$. The condition that the tangents at $x_1,x_2$ are orthogonal is
$$(3x_1^2-b)(3x_2^2-b)=-1$$
CORRECTION Inserting the previous result, we have
$$(3x_1^2-b)(12x_1^2-b)=-1$$
$$\rightarrow 36x_1^4-15bx_1^2+b^2+1=0$$
$$\rightarrow x_1^2=\frac{5b\pm\sqrt{9b^2-16}}{24}$$
It can be easily shown that there are two real, positive, solutions for $x_1^2$ iff $b>4/3$. The illustration is for b=2.
Nice problem!
Comment: @Will Jagy Sure, the absolute values in my answer were erroneous. They have been removed.
Comment: if your $b \leq 0$ a normal line to $y = x^3 - b x$ never again intersects the curve.
Comment: I added a picture of lines normal to $y = x^3$ at the end of my answer.
Answer: COMMENT.- A matter of principle must be stated: that the three real constants a, b, c are different, is equivalent to the cubic being elliptical: is of genus 1. When two or three of these constants are equal, the cubics are rational or of genus zero and there are three different classes of them:
$$y^2=(x-a)(x-b)^2,\quad P=(b,0)\text { is a nodal point }.\\y^2=(x-a)^2(x-b,)\quad P=(a,0)\text { is a isolated point }.\\y^2=(x-a)^3,\quad P=(a,0)\text { is a cuspidal point }. $$ A curious fact is that for the curves with isolated point the plotters (Desmos and Wolfram, I don't know if other) do not put this point  in their graphs.In the attached figure the black point $(1,0)$ is a point of both curves but it is not considered by the plotters.

What I want to add is that the more $b$ grows in relation to $a$, the cubic tends to be more and more "vertical" so it is a clear example that your problem has no solution for these kind of curves.


Estrutura de repetição dentro da seleção no visualg

Question: Função :Escreva um programa que crie um vetor inicialmente zerado e insira um valor no vetor, numa posição informada. Por exemplo, para o vetor vazio v = { }, posição 4 e valor 10, o programa deve gerar v={ , , ,10}. Se a posição for 2 e o valor 5, o vetor ficara v = { , 5, ,10}. E assim, sucessivamente. Caso a posição esteja ocupada, os valores devem ser remanejados, de modo a deixar a posição escolhida, livre para a inserção do novo valor, o vetor ficara v = { , 23, 5, ,10}. Mostre o vetor após as inserções.
parada<-"s"
para cont de 1 ate 5 faca
   x[cont]<-0
fimpara
enquanto (parada="s") faca
   escreva("Digite uma posição até 4 que queira alterar: ")
   leia(posi)
   enquanto (posi>4) faca
      escreva("Digite uma posição até 4 que queira alterar: ")
      leia(posi)
   fimenquanto
   escreva("Digite o valor que deseja inserir nessa posição: ")
   leia(valor)
   posi2<-posi+1
   se (x[posi]=0)entao
      x[posi]<-valor
   senao
      para cont de 5 ate posi2 faca
cont2<-(cont-1)
         x[cont]<-x[cont2]
      fimpara
      x[posi]<-valor
   fimse
   repita
      escreva("Deseja continuar?('S'/'N'): ")
      leia(parada)
   ate (parada="s") ou (parada="n")
fimenquanto
escreval("==============Resultado das alterações=================")
para cont de 1 ate 5 faca
   escreval(x[cont]," na posição ",cont)
fimpara

essa parte em negrito e a parte em vermelho na imagem o visualg não lê, ele pula direto pro "x[posi]<-valor" em baixo do fimpara e eu preciso dessa repetição pra alterar os valores da posição. Eu fiz dessa forma, alguem sabe se está incorreto ou se tem outra forma de fazer esse exercicio??
Answer: PROBLEMA RESOLVIDO
para cont de 5 ate posi2 passo-1 faca
cont2<-(cont-1)
x[cont]<-x[cont2]
fimpara
era o comando passo-1 que estava faltando, com ele a estrutura para consegue fazer a contagem em ordem regressiva.


SSIS Data flow task and "mixed" select

Question: Can't get following to work. Notice it worked just fine using SQL Server 2000 DTS package.
AXDB is external server (SQL Server 2000 Enterprise) and OLAP being the local database, SQL Server 2008 R2 standard (olap is used select statement getting the date to pass on the external SQL Server). Adding server name doesn't help.
Servers are linked if it matters, probably not.
If I just write the date there instead of trying to get it via select statement it works fine as expected.
How to achieve what I want here, notice I have about 100 such packages.
Pics are here:

Error:
Answer: Remove the <code>'</code> ticks from around the sub-select:
<code>...AND DATEPHYSICAL <= (SELECT lkpv FROM OLAP.dbo.laadimisaeg)
</code>
Right now your select is being read as a string, and that string is trying to be compared to a date.
Comment: @user1371966 Two things.. First, removing the `'` ticks will solve your error in question, so you shouldn't need that convert (assumging `lkpv` is a date type).  Second, instead of using the server path `eetll-bi-srv\eetllbisrv`, use the linked server name that you set it up as, from the AXDB SSMS.  Since you're executing this on the AXDB server.
Comment: @user1371966 I highly recommend testing the query from SSMS while connected to AXDB.  That is how SSIS will execute the query, and your error messages will probably make more sense if you take that approach to testing. :)
Comment: Hi,

thx for the recommendation, unfortunately this doesn't work also. Modified a bit the select more.Access denied basically is the result, eetll-bi-srv\eetllbisrv is the local sql server instance where i'm running the query.

Any recommendations how to get same logic working in some other ways ?
I want to use masterdata table, i don't want to write the dates in those selects and modify them all the time.

[see the result][1]

  [1]: https://i.stack.imgur.com/4fKzV.png

SSIS Data flow task and "mixed" select


Calculo de Sobra VISUALG

Question: Boa noite, Colegas!
Estou com esse problema e não consigo encontrar uma solução inclusive na documentação da IDE. Gostaria de saber qual comando usar para Pegar a sobra de uma divisão para utilizar-la nas instruções abaixo dela. Sei basicamente que o comando é MOD OU % só não sei como usar isso dentro da formula.
var

N,N2,N3,N4,N5,N6,N7: INTEIRO
inicio
  Leia(N)
  N2 <- N/100 % 100
  Escreval (N2)
  Escreval //Quero usar a sobra da divisão aqui em baixo para outra conta, imaginando que o valor da variável N1 é 576

fimalgoritmo
Comment: N2 <- N % 100 atribuirá à variável N2 o resto da divisão de N por 100. O que você fez não tem muito sentido.
Comment: Então pensando muito aqui, ficou sem sentido! Porém consegui fazer colocar na resposta
Answer: Ficou assim:
algoritmo "EXERCICIO 18"

var
N,N2,N3,N4,N5,N6,N7,N8: INTEIRO
inicio
  Leia(N)
  N2 <- N % 100
  ESCREVAL (N/100 MOD 100," nota(s)", " de", " R$ ", "100,00")
  N3 <- N2 % 50
  ESCREVAL (N2/50 MOD 50," nota(s)", " de", " R$ ", "50,00")
  N4 <- N3 % 20
  ESCREVAL (N3/20 MOD 20," nota(s)", " de", " R$ ", "20,00")
  N5 <- N4 % 10
  ESCREVAL (N4/10 MOD 10," nota(s)", " de", " R$ ", "10,00")
  N6 <- N5 % 5
  ESCREVAL (N5/5 MOD 5," nota(s)", " de", " R$ ", "5,00")
  N7 <- N6 % 2
  ESCREVAL (N6/2 MOD 2," nota(s)", " de", " R$ ", "2,00")
  N8 <- N7 % 1
  ESCREVAL (N7/1," nota(s)", " de", " R$ ", "1,00")

fimalgoritmo
Comment: Creio que você deva dar uma estudada no significado do operador resto da divisão (MOD ou %).

Calculo de Sobra VISUALG


Log all outgoing mail created by php

Question: I have Debian Linux server which serves several PHP sites. Today I received mail from Datacenter where they say my server is sending spam and attached spam message. This was really message from my server and I managed to find it in exim4 mainlog.
Question: how to identify where is the vulnerability in PHP code and which site (i have 3) send this mail?
I've chrooted one site already and disabled php mail and all exec,system etc. functions for it but i'm not sure taht it is site sending mail.
Any way to log message body for all outgoing mail?
Comment: You are sure is a problem with PHP and not with your apache proxy ?
Comment: 100% php. I can see headers in message indicating that it was PHP who send this message
Answer: You could write & configure a wrapper around sendmail that does more logging
in php.ini:
sendmail_path = /usr/sbin/sendmail -t -i

change to:
sendmail_path = /usr/local/bin/myscript

Or in your php code, you could write your own mail function that acts as a wrapper around php mail that does the logging. Remember to validate all input.
Comment: OK. But what is the format of the wrapper? Any example (in any language in any form)?
Comment: Suggest you do the 2nd option, if you are running php sites you should be able to write it.
Comment: Look like it is what i need http://www.iezzi.ch/archives/217
Comment: yes, that looks good

Log all outgoing mail created by php


ios keychain query record without additional prompt

Question: i've got a question regarding touch-id and how to use it with KeyChain. I am currently developing an app, where the user is able to retrieve a token from the keychain and login with said token (if it is valid ofc).
Currently, i'm doing it somewhat like this:
<code> var accessTokenRecord = new SecRecord(SecKind.GenericPassword)
                    {
                        Account = username,
                        Service = AccessTokenIdentifier,
                    };
                    var matchingAccessTokenRecord =
                    SecKeyChain.QueryAsRecord(accessTokenRecord, out SecStatusCode accessTokenStatusCode);
                    if (accessTokenStatusCode == SecStatusCode.Success)
                    {
                        var accessToken = new JwtSecurityToken(matchingAccessTokenRecord.ValueData.ToString());
                        var tokenString = matchingAccessTokenRecord.ValueData.ToString();
                        if (accessToken.ValidTo.CompareTo(DateTime.Now) < 0)
                        {
                            // accesstoken ran out/expired, neet to refresh
                            var refreshTokenRecord = new SecRecord(SecKind.GenericPassword)
                            {
                                Account = username,
                                Service = RefreshTokenIdentifier,
                            };
                            var matchingRefreshTokenRecord =
                                SecKeyChain.QueryAsRecord(refreshTokenRecord, out var refreshTokenStatusCodes);
                            if (refreshTokenStatusCodes == SecStatusCode.Success)
                            {
                                var newTokenInformation =
                                    await LoginWithRefreshToken(matchingAccessTokenRecord.ValueData.ToString(),
                                        matchingRefreshTokenRecord.ValueData.ToString());
                                var result =
                                    StoreAccessAndRefreshTokenForUser(newTokenInformation, username,
                                        ShowFailureInfo);
                                if (result)
                                {
                                    tokenString = newTokenInformation.TokenString;
                                }
                            }

                        }
                        // login with token
                        LoginWithToken(tokenString);
                    }
</code>
My Problem now is that the QueryAsRecord Method triggeres the touch-id prompt everytime it is used. I feel like it's not very user friendly to ask the user twice in case the accesstoken ran out and a new one needs to be requested with the refreshtoken.
I didn't find any way around this, does someone else may have a suggestion how the additional prompt can be averted?
Answer: Since there doesn't seem to be a way around it, I just placed both tokens in the same entry.


javascript regular expression for cross browser opacity

Question: I'm reading through a JS book and I came across the following regex in an example.
(parseFloat(filter.match(/opacity=([^)]+/)[1]) / 100)

Where filter="alpha(opacity=50)". I understand what the code is doing and that the returned match to be parsed is the second index in the array, which is the capture ([^), but I don't understand how that capture makes any sense. How does ([^)]+ match the opacity value? From what I understand if a caret is used as the first character then it will match a string that begins with whatever follows, or if it's used in a character class it will match anything except what's in the class, such as [^abc].
However in this situation it looks like the caret isn't doing either of those things because the right square bracket is outside the parentheses. Suffice to say, I'm rather perplexed.
Comment: It's missing the group closing `)`. Because `[1]` refers to what's captured inside the first parenthesized group  (capture group). the `[^)]` is a [negated](http://www.regular-expressions.info/charclass.html#negated) `)` correct regex should look [like this](https://regex101.com/r/kF5gD7/1): `/opacity=([^)]+)/` [see fiddle](https://jsfiddle.net/7Lw4fz7b/).
Comment: So it *is* a typo! I knew something was off. I blame Manning Publications :-P Thanks @Jonny5!
Comment: If unsure, you can always [paste your regex in regex101](https://regex101.com/r/sQ9bY4/2). It shows errors, for this: `( Unbalanced group`
Answer: [^)]+ is getting any sequence of characters that is not a close parenthesis ).
As @jonny points out, there is a missing closing parenthesis. and should be /opacity=([^)]+)/.
The pattern is / opacity=([^)]+) / where opacity= are all literal characters and [^)]+ should match the value you need. Focus on the square brackets, not the parenthesis.
With that, I believe the filter.match( /opacity([^)]+)/ ) will return opacity=50 in position [0] and 50 in position [1].
filter.match(/opacity=([^)]+/) )[1] returns the portion in the array position [1].
Then the parseFloat kicks in and converts the string 50 into a number which is finally divided by 100.
Comment: But those parentheses create a capture so how can I ignore them? If what you say is the case then `)` is part of the expression inside the square brackets AND the close of a capture? If so, then how does the capture contain `"50"` when what's inside them is `[^`?
Comment: @AndrewJensen—the capture group is defined by the outer brackets `([^)]+)`, so it's capturing all characters after  `opacity=` up to, but not including, a `)`. It assumes there is at least one such character. If there isn't, the expression returns NaN.


Persist Marker state on point click -Treemap - Highchart

Question: I am working on TreeMap where I am able to give borderColor on Hover of a particular datapoint. The same in this fiddle link --> http://jsfiddle.net/vgnshs/z8ncv2d5/.
But I am in need of requirement where I should get same kind of borderColor on click of a particular dataPoint (saying to user that the Point is selected) and borderColor should persist until I click on the same point again or somewhere outside plotArea. (I see this feature is available in Bubble chart, same needed in TreeMap). Also I should be able to select multiple points and all selected points should have the same borderColor.
Currently, TreeMap's select event fills the entire point with a different color which I don't want to. Only borderColor should be changed. How can I achieve this in TreeMap?

$(function () {

    $('#container').highcharts({
        "chart": {
            "width": 640,
                "height": 480
        },
            "colorAxis": {
            "minColor": "#202020",
                "maxColor": "#B0B0B0"
        },
            "title": {
            "text": "Datalabel Sample"
        },
            "subtitle": {
            "text": null
        },
            "credits": {
            "enabled": false
        },
            "tooltip": {
            "enabled": false
        },
            "plotOptions": {
            "series": {
                "states": {
                    "hover": {
                        "borderColor": "#0000FF",
                            "borderWidth": 1
                    }
                }
            }
        },
            "legend": {
            "align": "right",
                "layout": "vertical",
                "verticalAlign": "middle",
                "symbolHeight": 380,
                "enabled": true
        },
            "series": [{
            "type": "treemap",
                "layoutAlgorithm": "squarified",
                "allowDrillToNode": true,
                "dataLabels": {
                "enabled": false
            },
                "levels": [{
                "level": 1,
                    "dataLabels": {
                    "enabled": true,
                        "color": "#FFFFFF",
                        "allowOverlap": false,
                        "align": "center",
                        "style": {
                        "fontWeight": "normal",
                            "fontSize": "24px",
                            "fontStyle": "normal",
                            "fontFamily": "'Open Sans', Arial, Helvetica, sans-serif",
                            "textShadow": null
                    },
                        "overflow": false
                },
                    "borderWidth": 1
            }],
                "data": [ {
                "id": "Apparel",
                    "name": "Apparel",
                    "value": 130.1,
                    "colorValue": 130.1,
                    "expanded": false,
                    "canexpand": false
            }, {
                "id": "Footwear",
                    "name": "Footwear",
                    "value": 90.7,
                    "colorValue": 90.7,
                    "expanded": false,
                    "canexpand": true
            }, {
                "id": "Accessories",
                    "name": "Accessories",
                    "value": 180.5,
                    "colorValue": 180.5,
                    "expanded": false,
                    "canexpand": true
            }]
        }]

    });

});
#container {
    min-width: 300px;
    max-width: 600px;
    margin: 0 auto;
}

Answer: You can set select state and configure color as false. Next step is configure datalabels, by setting useHTML as true and zIndex as 30.
Example: http://jsfiddle.net/z8ncv2d5/3/
Comment: Thanks a lot Sebastian. Will investigate the sane. Thanks a lot. Love the response speed from Highcharts guys. :) You Guys Rock.
Comment: That works cool. But forgot to mention one more point in the above question. Is it possible to dim out other dataPoints that are not selected ? (something like changing opacity of unselected datapoints, so that focus in on only selected dataPoints). If this is also possible in addition to above reply, my requirement is fulfilled :) Thanks in advance.
Comment: Well you can set for all series custom colors (by rgba(122,122,122,0.5)) where last param is opacity. For select state set a color  rgba(122,122,122,1)
Comment: (http://jsfiddle.net/vgnshs/z8ncv2d5/) I am able to change opacity of selected points. But I need other way round. I need to reduce opacity of unselected points, so that user focuses on selected point only. While other unselected points opacity is reduced, selected points should have a blue border to indicate thats selected.
Comment: You can only use a workaround by setting a color of series by rgba.


$\frac{da}{dt} \leq f(a(t))$ and $\frac{db}{dt}=f(b(t))$ imply $a(t) \leq b(t)$?

Question: Let $a(t)$ and $b(t)$ be nonnegative real-valued differentiable functions and $f$ be a strictly positive continuous function.
If $a(0)=b(0)$, $\frac{da}{dt} \leq f(a(t))$ and $\frac{db}{dt}=f(b(t))$ for $t \geq 0$. Then how do I show that $a(t) \leq b(t)$ for $t \geq 0$?
It seems intuitively clear but very tricky to prove....I cannot compare $f(a(t))$ and $f(b(t))$ directly. Could anyone help me?
Answer: See
https://users.math.msu.edu/users/sen/Math_848/lec_6s.pdf
Inequality of differential equation implies inequality of functions.
Comment: Could you help me with the problem in the link as well?
Comment: https://math.stackexchange.com/questions/3632210/invariant-interval-for-ode-implies-invariant-interval-for-parabolic-pde
Comment: I'm afraid not...


Reducing variables and correlated variables in a dataset

Question: I am attempting to produce models on a dataset with approximately 60 variables and 800 subjects. Other datasets are also being considered for use.
The datasets were not originally constructed for this type of analysis.
The dataset also comprises a mixture of variables. Some are continuous and some discrete. Also some of these are correlated with one another as can be seen on a correlation matrix and also just by eye/common sense.
Currently clustering variables has been used with the aim to remove any correlated components being used to generate models to avoid over-fitting and reduce the number of variables. By choosing the most representative variable from each cluster however I am unclear if this is being done correctly and not confident this is correct and will result in incorrect models.
Previously what has been done is to just load all the variables into the platform and produce a cluster summary. The most representative member variable is picked out of each cluster and models made. In many clusters there is a variable present that shows a low R squared with the cluster it is in, yet it has been included. The variable also does not show correlation to the other group members on reference to the correlation matrix. It's almost as if it has been forced in where it will fit best rather than left on its own. (Sometimes a cluster does include 1 variable.) Also, sometimes two separate clusters appear to contain variables which are correlated.
Thus I feel at times correlated variables are being used for models and at the same time uncorrelated variables are being missed.
I am very new to this level of stats and I am struggling with wrapping my head around eigenvalues etc. It was implied that this is an aspect of PCA but I have found that this is not really the case.
Information on the web tends to get into some quite complex math on the subject.
Here is my understanding, it may well be off.
I understand that PCA is a transformation of the dataset so that the first component explains the most variation in the variables, the second PC is orthogonal to this (uncorrelated) and that there is one PC for each variable. Each PCA is given a total eigenvalue that = number of variables (due to the transformation of the original axis where the variance of the data is made to =1 and mean =0).  The PC that explains most of the variation in the data takes the greatest share of this followed by the second etc. This is due to variable weighting coefficients where each variable is given a weighting in respect to its influence on that PC. Eigenvectors are where I fall apart!!
Clustering involves looking at all the variables and performing iterative splits. A split involves a PCA analysis on the cluster members? then.. from a guide..
 'the cluster with the largest second eigenvalue is chosen to be split into two new clusters'
Again I fall apart due to not really understanding eigenvalues.
I think the tools I have been using have been suggested to perform a dump and click solution which I can't really believe..but I cannot argue the case due to limited understanding.
Long post, but I'm getting a bit lost!
Answer: This should probably go as a comment but I cannot add it there because of low reputation. However, I think it can also partly serve as an answer to the OP's question.
As @NickCox alluded to, you should tackle this piecemeal. Read through the theory, work with a small number of variables and try to develop an intuitive sense of what is happening, although to develop this intuitive understanding will take some time, it will be worth it when you are trying to interpret the results of your principal component analysis.
If you look at the link @NickCox suggested and scroll down to whuber's answer you will find a good geometric explanation for what eigenvectors and eigenvalues mean and will give you a visual feel of what you are looking at. I will add to that answer - if you collapse his ellipsoid into a two dimensional space i.e look at only the first two principal components, you will get an ellipse with one major and one minor axis. The major axis is the "direction" which explains most of the variance of your data. It is represented by the first eigenvector and its length is the first eigenvalue (when you arrange the eigenvalues in descending order). It is also the linear combination of all the variables in your dataset, more specifically it is that linear combination which most explains the variance in your data.
Now, going back to your data you should look into textbooks on multivariate methods for methods of analyzing the covariance structure of your dataset. I am afraid I cannot point to anything specific but I think any intermediate level book would do. Additionally, I remember reading about applied principal component analysis from the book Statistical Methods in the Atmospheric Sciences by Daniel Wilks. If you get a hold of this book, you will find that it gives a good overview of the methodology in Chapter 11 (atmospheric scientists call PCA as Empirical Orthogonal Functions and it is the same thing). The author works with multi-variate data so it is structurally similar to what you have.
Lastly, in addition to clustering and PCA you can also look into Canonical Correlation Analysis (CCA). It is also used in reducing the dimensionality of one's dataset but it looks at the relationship between pairs of data. I cannot say whether it would be applicable in your case.
Answer: For doing PCA, why don't you just use an existing library, if you don't manage to compute the Eigenvectors yourself?
Note that however, the covariance matrix (and thus PCA) has $60^2 = 3600$ degrees of freedom. Since you only have 800 subjects, the PCA results may overfit. As a rule of thumb, for PCA you should have much more than $d^2$ instances. Best is something like $d^3$.
Maybe you should first try some feature selection approaches that are more significant when you have low sample sizes.
Answer: It sounds like you need to perform a principal components analysis or exploratory factor analysis. Based on either of these analyses, you can use what variables are most important (i.e., are most predictive of your components/factors) and ignore the others.
Comment: Sympathies that you are confused, but adding extra questions in the comments to an already broad question is not the way to go. http://stats.stackexchange.com/questions/2691/making-sense-of-principal-component-analysis-eigenvectors-eigenvalues offers various perspectives on eigenvalues and eigenvectors, which seems to be what you want to understand first.
Comment: Yes, that's what i think. is the output newly constructed variables? Ie a platform output would be new variable 1..2..3 rather than height, length etc due to transformation?..Bascially i do not trust what i am getting out atm using the clustering. Seeing as this is the foundation of the models i do not want to get it wrong
Comment: By definition, principal components are orthogonal to one another, so they will be uncorrelated with each other. You may also want to look into lasso regression, which is a method that sets some coefficients to zero (i.e. removes some variables from the model).
Comment: On a typical PCA output, how would the PC from the original variables be displayed? Im using software with so many options its a bit daunting. It looks as if they are called 'Eigenvalues' on the software i am using
Comment: I had found that thread previously. Apologies for asking multiple questions. I guess i need to know (1) how eigenvalues work and relate to PCA.  (2) how to dissect a PCA output in respect to reformed varibles and (3) why i am getting what seem to me as incorrect results in variable clustering. ..i will start look to start new topics


how to remove everything after [/img] with regex?

Question: I have text as:
[img]http://cimislia.net/uploads/posts/2013-07/1373995142_vrc.png[/img]

[color=#3333FF]Дата выхода: 26 октября 2012
Жанр: Racing, Simulator, 3D
Разработчик: SCS Software
Издательство: Excalibur Publishing

I want to remove everything after [/img] so above text will be:
[img]http://cimislia.net/uploads/posts/2013-07/1373995142_vrc.png[/img]

Can somebody help please? How to do this with regex?
Comment: Have you tried anything yet? Where are you using this?
Answer: This regex
\[img\].*\[/img\]

will match only [img] tags and everything between.
How to use it depends on the programming language you are using.
Example in C#:
var text = @"[img]http://cimislia.net/uploads/posts/2013-07/1373995142_vrc.png[/img]

[color=#3333FF]Дата выхода: 26 октября 2012
Жанр: Racing, Simulator, 3D
Разработчик: SCS Software
Издательство: Excalibur Publishing
";

Regex regex = new Regex("\\[img\\].*\\[/img\\]");

var imgOnly = regex.Match(text).Value;

Comment: This doesn't do what the OP asks, but what the OP asks might not really be what the OP wants anyway. The OP asks to remove everything after `[/img]`, but doesn't say anything about removing anything before `[img]` like you've effectively done. Also, for the text `[img]a[/img]b[img]c[/img]`, the whole string will be matched: `.*` will match `a[/img]b[img]c` without any problem.
Comment: Because the regex is not removing but matching the content you want to keep, you can use it to extract the [img] tags
Comment: @HalilIbrahimUslu Your comment doesn't make sense. Are you searching for this regex, and removing its matches? This regex attempts to match what you asked for, so rather than removing the results, the results are what you should keep.
Comment: not working, it delete only everything between the images tag, but thats the only text i want to keep
Answer: you can search for \[/img\](.|\n)* and replace with [/img]


How can I validate Enum Type in C#

Question: I have a method that takes an Enum value as a parameter, but not all enums are valid.
I want to do something like this
<code>public void Method<T>(T type) where T : Enum, IValidEnum{}

public enum ValidEnum1 : IValidEnum{}
public enum ValidEnum2 : IValidEnum{}
public enum NotValidEnum{}

Method(ValidEnum1.Value) // ok
Method(ValidEnum2.Value) // ok
Method(NotValidEnum.Value) // Exeption
</code>
but enums cannot use inheritance. Any advice, please
Comment: You can use the built-in [Enum.IsDefined](https://learn.microsoft.com/en-us/dotnet/api/system.enum.isdefined?redirectedfrom=MSDN&view=net-7.0#System_Enum_IsDefined_System_Type_System_Object_) method. Enums are essentially aliases for integral types. An `int` based enum is still an int, there's no inheritance involved
Comment: You cannot declare a method that takes an open-ended number of enums that must still be from a limited set (as you can with classes). Depending on your scenario you can use overloads, or validate that `T` is an enum you are willing to accept at runtime (for example, by checking its originating assembly or a custom attribute defined on the enum). Because enums are themselves fairly weak syntactic sugar over integers, and nothing prevents you from casting any integral value to any enum, the usefulness of such things is limited.
Comment: What do you mean by "valid" and "invalid"?
Comment: If you need to constrain to a specific type, then do not use generics at all, but use that specific enum type. If you are using `[Flags]` enums then you might be able to validate using bitmasks. If the dup doesn't help you then you will need to explain more about the scenario and show the possible variations that you want to support and those that you want to prevent.
Comment: The edit didn't clarify anything. Enums are named values, not types. You can't specify that `ValidEnum1` and `ValidEnum2` contain all the values of `ValidEnum`. You'll have to enter these manually. If `ValidEnum` is a subset of both `ValidEnum1` and `ValidEnum2` you can use `Enum.IsDefined()` with *any* value.
Comment: c# doesn't support interfaces for enums.  You can add attributes, but [there is no way to add use an attribute as a generic constraint](https://stackoverflow.com/q/4146674).  See [Constraints on type parameters (C# Programming Guide)](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters).  For some workarounds see [Behaviour to simulate an enum implementing an interface](https://stackoverflow.com/q/3007596).
Comment: For fast generic solutions you can use [this](https://www.nuget.org/packages/KGySoft.CoreLibraries) library (disclaimer: written by me). It offers a couple of extension methods that can be used like `mySimpleEnum.IsDedined()` or `myFlagsEnum.AllFlagsDefined()`. See an online example [here](https://dotnetfiddle.net/PITQFg).
Answer: You are trying to do processing based on values coming from multiple different enum types? I think of each enum type defined in code as being an exhaustive distinct set for what that enum is for. You can't have the same value twice in an enum, but you could have the same value from 2 separate enum s and this is what breaks the way you are trying to use them with inheritance. There is nothing actually being inherited, nor is there any spec being implemented.
Perhaps some more context of what you are trying to do would help. Are these preexisting enums you are trying to incorporate into new app logic?

How can I validate Enum Type in C#


Custom editable, translatable email templates

Question: I need to send many different emails to drupal users. How can i add custom editable & translatable email templates? Something like user emails?
I have tried "Mail Editor" module, but i don't know how to add custom emails. Perhaps this is not the right solution?
thanks in advance
Answer: Using Mail Editor you can add custom emails by going to admin/config/system/mail-edit
Did you try doing that?
Regarding translation at - /admin/config/regional/language/configure there is a 'Follow the user's language preference.' option.
Comment: i can't add new mail there. I can only add language translations.


String replace in Android

Question: To try string replace in Android, I wrote a small snippet:
public class cs{
 public static void main(String[] args){
   String a,c;
   int b;
   b=1;
   c="12345";
   a="12345,54321";
   a.replace(c,String.valueOf(b));
   System.out.println(a);
}
}

Expected Output: 12345,54321 changes to 1,54321
Actual Output: 12345,54321
。Please help。
Answer: Is the . in c.String.valueOf(b) a typo for a comma, separating two parameters? Because it doesn't make much sense as stated. replace accepts two parameters, and furthermore, it doesn't change the string it's executed on, it merely returns a new one, so you need to pick up that return value and reassign it to the variable:
a = a.replace(c, String.valueOf(b));

Answer: If you expect output 1,54321 you need to write
a.replace("12345", c.String.valueOf(b));

String replace in Android


What is a zombie process and how do I kill it?

Question: Virtual Shotguns?
Answer: Zombie process (actually now they're called <defunct>) isn't really a process. It's only entry in the process table, so the parent process can do wait() syscall.
You shouldn't worry about them. They do not occupy any resources, they will disappear either when their parent calls wait() on when the parent itself dies.
Comment: They *still* keep some resources, and take a slot in the processes table. Better to *wait()* them and see them disappear forever...
Answer: Oh, god! No no no.  Don't use kill -9.
It doesn't give the process a chance to cleanly:

shut down socket connections
clean up temp files
inform its children that it is going away
reset its terminal characteristics and so on and so on and so on.

Generally, send 15, and wait a second or two, and if that doesn't work, send 2, and if that doesn't work, send 1.  If that doesn't, REMOVE THE BINARY because the program is badly behaved!
Don't use kill -9.  Don't bring out the combine harvester just to tidy up the flower pot.
Comment: kill -9 won't kill zombies. You have to kill their parent, look at pstree.
Comment: @LapTop006: In that case they're more like vampires; kill the head vampire to stop the invasion.
Comment: This answer is wrong in just about every way.  The process is complete; it has already shut down its connections, cleaned up temp files, etc. etc.  There is no actual process anymore, just an entry in the process table.
 Do not remove the child binary - it is not behaving badly.  It just means that the parent hasn't held a proper funeral for its child yet.
Answer: There is already an accepted answer, however: you CAN kill the zombie process. Attach with the debugger to the parent process and call waitpid function. E.g.:
- let's assume that the parent has PID=100, the zombie process has PID=200
$ gdb -p 100
(gdb) call waitpid(200, 0, 0)
(gdb) quit

Comment: Interesting. I will try this.
Comment: (Many years later) I made this a one-liner:
`zombiekill() { gdb -p $(ps -oppid= -q $1) -q -ex "call waitpid($1,0,0)" -ex detach -ex quit; }`
Answer: It's a process that has been completely deallocated but still exists in the process table.  Contrast this with an orphan process, whose parent has died but is still executing.
Here's some advice on getting rid of them.
Answer: A zombie process has no resources allocated to it whatsoever, other than the entry in the process tree.  This happens when a process completes, however the parent process has not yet reaped it, (i.e., waited on it).
You can try and force the parent to do this if you want by sending it a SIGCHLD (kill -20), to the parent, but there's no guarantee that the parent will honor it.
You'll often see them for short periods of time (for example while viewing the process tree using top) - this is normal; In the time slice between the time that a child process completes, and the parent polls for it - the child process will appear as a zombie.
If you see zombie processes that continually exist however - which is not normal - there is still no need to be concerned - again as there is not resource allocated to a dead process - it generally means that the application is poorly written by crappy developers.
The only time that you should be concerned from zombie processes, is when you see lots and lots of them, for example if the same crappy application mentioned above is placed under load.
We have alot of crappy developers where I work, and so I have the privilege of dealing with such issues and learning all sorts of useless stuff while doing so.  In fact - my team often resorts to using the crappy shell scripts written by out crappy developers in interviews - if the candidate can pick that the script is indeed crapy, and tell us why it's crappy, he has a good foot in the door.
Answer: As for the virtual shotgun...

$ shoot <pid>

#!/bin/sh
victim=`ps -e -o pid,ppid | egrep "^\s*$1\b" | awk '{print $2}'`
victim\_name=`ps -e -o pid,cmd | egrep "^\s*${victim}\b" | head -n 1 | awk '{print $2}'`
#kill ${victim}
echo "Killed ${victim_name}."

And remember: always shoot them in the head.
Comment: I'm sorry but for the record, this script has a typo "victim_name" and is going to kill the parent of the PID given on $1 , in any case considers if PID is the only zombie or if he has some siblings, it just kills the father and with it all the family will perish.
Answer: A zombie process is a process that has finished executing, but is still listed in the process table.
kill -9 [parent process_name] will put it down, with extreme prejudice.
Comment: No, kill -9 on *THE PARENT* will kill the parent, making init it's parent, which *WILL* reap the child's return code.
Comment: kill -9 will not kill a zombie process - that's one reason they're called zombies.  A zombie "process" will not go away until its return code is reaped by a parent process.


How can I explain $0.999\ldots=1$?

Question:
Possible Duplicate:
Does .99999… = 1?

I have to explain $0.999\ldots=1$ to people who don't know limit.
How can I explain $0.999\ldots=1$?
The common procedure is as follows
\begin{align}
x&=0.999\ldots\\
10x&=9.999\ldots
\end{align}
$9x=9$ so $x=1$.
Comment: what you show is a false 'proof' because you didn't write what 0.999... means and why 9.9999...-0.9999... = 9. To explain you need limit, otherwise don't explain. Giving someone a false proof is not necessarily better than leaving him with a doubt.
Answer: Between every two distinct real numbers, there exists a third real number distinct from the others. The contrapositive says that if no real numbers intermediate between $a$ and $b$, then $a$ equals $b$. So assume for a contradiction that a number intermediates between $0.9999...$ and $1$. For concreteness, lets say this number is $0.9981383...$ Well there is a first digit in this number that is not a 9. Thus $0.9981383...<0.99999...$. This contradicts the assumption that this number intermediates. Thus no number intermediates between $0.9999....$ and $1$.
Comment: This made me understand why ``0.999...`` admits a finite-decimal representation, while ``0.333...`` does not!
Answer: What I always find the most simple explanation is:
$$
\frac{1}{3} = 0.333\ldots \quad \Longrightarrow \quad 1 = 3 \cdot \frac{1}{3} = 3 \cdot 0.333\ldots = 0.999\ldots
$$
Comment: It's a circular argument.
Comment: @Jack What was the point of that edit?
Comment: @TMM: I wanted to retreat my downvote. That's it. Happy holidays `:-)`
Answer: We know that if $a - b  =0, ~~ a = b.$ So, we can do this:\begin{align}1 - 0.999\cdots & = 0.000\cdots \tag{1} \\ &  = 0 \end{align}Rewriting $(1)$,$$1 = \underbrace{0.000\cdots}_0 + 0.999\cdots \\ 1 = 0.999\cdots$$
Answer: What do we understand when we see the number $0.999\ldots$? I understand the limit of sequence $(q_n)$ given by
$$
q_n=0.\underbrace{9\cdots9}_{n \text{ times}},\quad n\geq 1.
$$
For a given $n$ the distance between $q_n$ and $1$ is
$$
|1-q_n|=0.\!\!\underbrace{0\cdots 0}_{n-1\text{ times}}\!\!1
$$
which obvously goes to $0$ when $n$ tends to infinity. Hence $0.999\ldots =\lim_{n\to\infty}q_n=1$.
Comment: This only implies that $(q_n)_{n\in \mathbb{N}}$ converges to $1$ whereas there seems to be no "meaning" to the symbol $0.999\ldots$ (unless, of course you define it to be "equal" to $1$, in which case there is nothing to prove).
Comment: @user170039: I defined $0.999\ldots$ as the limit of the sequence $(q_n)$ as is written in the beginning of my post. Or you could say that $0.999\ldots$ is the number satisfying $0.999\ldots\leqslant 1$ and $0.999\ldots\geqslant q_n$ for all $n$ from which it follows that it's $1$.
Comment: My point is that you can only define $0.999\ldots$ to be the limit of $(q_n)$ if you know that it is a real number. What's the proof that it indeed is a real number?
Comment: @user170039: If it's not given that it should be a real number, then you tell me how one should define or characterize it. That would be like saying 'Here is a quantity I'll call $x$, but I'm not willing to say anything about it. Now you tell me what it is'.
Comment: By defining it to be equal to $1$. In fact, this was the philosophy for [this post](http://math.stackexchange.com/questions/1600940/does-it-make-any-sense-to-prove-0-999-ldots-1).
Comment: @user170039: Sure, you could also define to be equal to $3$. In my post I define to be the limit of the sequence $(q_n)$ or alternatively the number being $\leqslant 1$ and $\geqslant q_n$ for all $n$, and hence implicitly assuming that it's a real number. But so do you when you define to be equal to $1$. So what exactly is your point?
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/33868/discussion-between-user-170039-and-stefan-hansen).

How can I explain $0.999\ldots=1$?


NotImplementedError: Layers with arguments in `__init__` must override `get_config`

Question: I'm trying to save my TensorFlow model using model.save(), however - I am getting this error.
The model summary is provided here:
Model Summary
The code for the transformer model:
def transformer(vocab_size, num_layers, units, d_model, num_heads, dropout, name="transformer"):
    inputs = tf.keras.Input(shape=(None,), name="inputs")
    dec_inputs = tf.keras.Input(shape=(None,), name="dec_inputs")

    enc_padding_mask = tf.keras.layers.Lambda(
        create_padding_mask, output_shape=(1, 1, None),
        name='enc_padding_mask')(inputs)
    # mask the future tokens for decoder inputs at the 1st attention block
    look_ahead_mask = tf.keras.layers.Lambda(
        create_look_ahead_mask,
        output_shape=(1, None, None),
        name='look_ahead_mask')(dec_inputs)
    # mask the encoder outputs for the 2nd attention block
    dec_padding_mask = tf.keras.layers.Lambda(
        create_padding_mask, output_shape=(1, 1, None),
        name='dec_padding_mask')(inputs)

    enc_outputs = encoder(
        vocab_size=vocab_size,
        num_layers=num_layers,
        units=units,
        d_model=d_model,
        num_heads=num_heads,
        dropout=dropout,
    )(inputs=[inputs, enc_padding_mask])

    dec_outputs = decoder(
        vocab_size=vocab_size,
        num_layers=num_layers,
        units=units,
        d_model=d_model,
        num_heads=num_heads,
        dropout=dropout,
    )(inputs=[dec_inputs, enc_outputs, look_ahead_mask, dec_padding_mask])

    outputs = tf.keras.layers.Dense(units=vocab_size, name="outputs")(dec_outputs)

    return tf.keras.Model(inputs=[inputs, dec_inputs], outputs=outputs, name=name)

I don't understand why it's giving this error since the model trains perfectly fine.
Any help would be appreciated.
My saving code for reference:
print("Saving the model.")
saveloc = "C:/tmp/solar.h5"
model.save(saveloc)
print("Model saved to: " + saveloc + " succesfully.")

Comment: i think this has changed with tensorflow 2.2.0 .. so now you wont run into this error
Answer: It's not a bug, it's a feature.
This error lets you know that TF can't save your model, because it won't be able to load it.
Specifically, it won't be able to reinstantiate your custom Layer classes: encoder and decoder.
To solve this, just override their get_config method according to the new arguments you've added.

A layer config is a Python dictionary (serializable) containing the configuration of a layer. The same layer can be reinstantiated later (without its trained weights) from this configuration.

For example, if your encoder class looks something like this:
class encoder(tf.keras.layers.Layer):

    def __init__(
        self,
        vocab_size, num_layers, units, d_model, num_heads, dropout,
        **kwargs,
    ):
        super().__init__(**kwargs)
        self.vocab_size = vocab_size
        self.num_layers = num_layers
        self.units = units
        self.d_model = d_model
        self.num_heads = num_heads
        self.dropout = dropout

    # Other methods etc.

then you only need to override this method:
    def get_config(self):

        config = super().get_config().copy()
        config.update({
            'vocab_size': self.vocab_size,
            'num_layers': self.num_layers,
            'units': self.units,
            'd_model': self.d_model,
            'num_heads': self.num_heads,
            'dropout': self.dropout,
        })
        return config

When TF sees this (for both classes), you will be able to save the model.
Because now when the model is loaded, TF will be able to reinstantiate the same layer from config.

Layer.from_config's source code may give a better sense of how it works:
@classmethod
def from_config(cls, config):
  return cls(**config)

Comment: I'll try this. Shouldn't this be done by default using the parameters from the class construction?
Comment: @Mee **1.** Yes: https://www.tensorflow.org/guide/keras/custom_layers_and_models#you_can_optionally_enable_serialization_on_your_layers  **2.** Because serializing standard parts of the model already works out of the box. But for custom layers like Encoder and Decoder, you need to define it.  **3.** I'm not sure, you may want to ask this as a separate question. But why not just put your function's logic into a Layer subclass?
Comment: This *could* have been done, but consider the case where not all parameters need to be saved, and just their derivatives are enough. For example the `mean` and `std` of `x_train`. In that case, the layer can accept either `x_train` or `(mean, std)` to construct. When building the model you'll use `x_train` and save `self.mean, self.std`, then save only `mean, std` to `config` to reinstantiate, without the entire `x_train`.
Comment: I did not get it very well. is there any sources to read more about it? Also, why should we over write the encoder layer and not the encoder itself? Also, what if the encoder layer is a function not a class?
Comment: Thank you for you reply. I did put it in a sepearte question. May you please check it? https://stackoverflow.com/questions/59796343/transformer-model-not-able-to-be-saved
Comment: Is this overriding `config` still needed to be done manually? I seem to be able to save my custom layer (adds arguments in __init__) with tf.saved_model but, run into warning same as the error described by op if i try to use tensorboard on it
Comment: Yes, post a new question and link to it here.
Comment: #EliaDL - Sure! Here is link to the question https://stackoverflow.com/questions/61947226/in-tensorflow-for-custom-layers-that-need-arguments-at-instantialion-does-the .. Looking forward to hearing form you there! Thank you tons in advance
Answer: This problem is caused by mixing imports between the keras and tf.keras libraries, which is not supported.
Use tf.keras.models or usr keras.models everywhere
You should never mix imports between these libraries, as it will not work and produces all kinds of strange error messages. These errors change with versions of keras and tensorflow.
Comment: Even if my problem was not exactly the same as OP, I was getting exactly the same error. John's answer did the magic for me,  I let my VSCode auto import Dropout when I wrote: model.add(Dropout()). It imported it : from tensorflow.python.keras.layers.core import Dropout and thus creating the above error.
Proper import is : from tensorflow.keras.layers import Dropout
Answer: I suggest You try the following:
model = tf.keras.Model(...)
model.save_weights("some_path")
...
model.load_weights("some_path")

Answer: I think simple solution is to install the tensorflow==2.4.2 for gpu tensorflow-gpu==2.4.2 , i faced the issue and debug the whole day but it was not resolved. finally i installed the older stable version and error is gone
Answer: Adding save_format='tf' parameter solved it for me:
model.save(MODEL_PATH, save_format='tf')

Answer: We have 2 model save formats:
Either TensorFlow SavedModel or HDF5
1/SavedModel saves the execution graph. Thus, SavedModels are able to save custom objects like subclassed models and custom layers without requiring the original code.
If you only supply the name of the saved model, e.g. model.save('my_model'), then the saved model format will be TF savedmodel as default.
2/To save custom objects with HDF5 format:
You have get_config method in your object, and optionally a from_config classmethod etc. (see the documentation)
If you supply the H5 file extension, e.g. model.save('my_model.h5'), then the saved model format will be HDF5.
I used the first method (saved model format) and it worked for me without errors.


How to send bulk SMS with twilio API

Question: I want to sending bulk SMS with Twilio is this possible with Twilio exists API. I have searching few hours with google, but can't find acceptable answers. So, I decide to asking at here. Thanks in advance.
Comment: You haven't mentioned platform for which you want to use this API
Answer: SMS and MMS Quickstart Tutorial
This sample is using a dictionary to send messages to group of people, see at following sample code in above link.
// make an associative array of people we know, indexed by phone number
    var people = new Dictionary<string,string>() {
        {"+14158675309","Curious George"},
        {"+14158675310","Boots"},
        {"+14158675311","Virgil"}
    };

More Over as You have mentioned BULK Messaging I would like you to have a look at their policy of Do's and Dont's also at this link
and look for section Sending mass marketing or bulk messaging using Twilio long code phone numbers
Have a look at

REST API: Short Codes
REST API: Messages
Answer: Yes and no, yes you can send 'batch' MMS by iterating thru a list of numbers you want to send to, but if you plan on sending a lot, you are going to want to lease a short-code (for about $1000/month) in order to qualify for the higher sending limits.
With a regular number you can send at most one message per second. With a shortcode, you can up that to 30 messages per second.
You might be able to get away with low-level 'bulk' sms on a regular twilio number, but don't be surprised if you get shut down if you are spamming or violating the terms of use (see Boosters post above for the link).
Comment: Just to be clear, you can make requests to the Twilio REST API as fast as you want, however, Twilio will queue outbound sms messages and release them at a rate of one per second.
Comment: @shasikanth, you can use periodic polling to check on the status of the individual messages using the API, or you can use the `statusCallback` webhook which will be called whenever the status changes.
Comment: Is it possible to know the status of each of the sms messages sent with the REST API, if i attach a **statusCallback** in my request ?

How to send bulk SMS with twilio API


Finding Fourier transform of $\frac{x}{(x^2 + 4)^2}$

Question: So I have this function
$$
f(x) = \frac{x}{(x^2 + 4)^2}
$$
and I have to find its Fourier transform.
This is however much harder than what I have done before so I don't have a clue where to start. I have stared at it for 2 hours and come up with nothing.
I know that
$$
\mathfrak{F}(\xi) = \int_{-\infty}^{\infty}e^{-i \xi x} f(x) dx
$$
but this is as far as I get. Thankful for any help!
Comment: If you are familiar with complex integration & residues, this question: (http://math.stackexchange.com/questions/369276/use-the-contour-integral-to-show-a-fourier-transformation) might be useful.
Answer: We can use residue calculus here to find the integral value:
$$
\int_{-\infty}^{\infty}e^{-i \xi x}f(x)dx = \int_\gamma e^{-i \xi z} \cdot \frac{z}{(z^2 + 4)^2}dz
$$
which have double poles at $z = \pm 2i \Rightarrow z_1 = (z-2i)^{-2}, z_2 = (z + 2i)^{-2}$.
We need to find the residues for
$$
e^{-i \xi z}f(z) = (z - 2i)^{-2}ze^{-i \xi z}(z + 2i)^{-2} = (z - 2i)^{-2}g(z)
$$
where we let
$$
g(z) = e^{-i \xi z}(z+2i)^{-2}z
$$
differentiation yields
$$
g'(z) = e^{-i \xi z}((z+2i)^{-2} - i \xi z(z + 2i)^{-2} - 2z(z + 2i)^{-3})
$$
insertion of $z = 2i$ yields
$$
e^{2 \xi}((4i)^{-2} + 2 \xi(4i)^{-2} - 2\cdot 2i(4i)^{-3}) = -\frac{1}{8} \xi e^{2 \xi}
$$
thus
$$
Res_{z = 2i}(e^{-i \xi z}f(z)) = \frac{g'(2i)}{1!} = -\frac{1}{8} \xi e^{2 \xi}
$$
and equally
$$
Res_{z = -2i}(e^{-i \xi z}f(z)) = \frac{g'(2i)}{1!} = \frac{1}{8} \xi e^{-2 \xi}
$$
and finally the Fourier transform is given by
$$
\mathfrak{F}(\xi) = \left\{
  \begin{array}{l l}
    2 \pi i (- \frac{1}{8} \xi e^{2 \xi}) = - i \xi \frac{\pi}{4} e^{2 \xi}, & \xi \lt 0\\
    -2 \pi i (\frac{1}{8} \xi e^{-2 \xi}) = - i \xi \frac{\pi}{4} e^{-2 \xi}, & \xi \gt 0
  \end{array} \right.
$$
and to conclude
$$
\mathfrak{F}(\xi) = -i \xi \frac{\pi}{4} e^{-2 |\xi|}
$$
Comment: Very thorough and helpful, thanks!
Answer: One can rather easily compute the integral by residues. For example, for $\xi\geq0$ we can write
\begin{align*}
\mathfrak{F}(\xi)=-2\pi i\cdot \operatorname{res}_{z=-2i}\frac{ze^{-i\xi z}}{(z-2i)^2(z+2i)^2}
=-2\pi i \cdot\left(\frac{ze^{-i\xi z}}{(z-2i)^2}\right)'_{z=-2i}=-\frac{\pi i}{4}\xi\, e^{-2\xi}.
\end{align*}
But since the answer should be an odd function of $\xi$ (why?), the general result for $\xi\in\mathbb{R}$ is given by
$$\boxed{\displaystyle\mathfrak{F}(\xi)=-\frac{\pi i}{4}\xi\, e^{-2|\xi|}}$$
Comment: Thanks for your answer, it seems that I have some reading to do! =)
Answer: The function ${\displaystyle {x \over (x^2 + 4)^2}}$ is ${\displaystyle -{1 \over 2}}$ times the derivative of ${\displaystyle {1 \over x^2 + 4}}$, so its Fourier transform will be ${\displaystyle -{i \xi \over 2}}$ times the fourier transform of ${\displaystyle {1 \over x^2 + 4}}$. This one is standard and is given by ${\displaystyle {\pi \over 2} e^{-2|\xi|}}$. (To verify this, you can just compute the inverse Fourier transform directly using basic calculus).
Thus the desired Fourier transform is ${\displaystyle -{i \xi \over 2}}$ times ${\displaystyle {\pi \over 2} e^{-2|\xi|} = {-{i \xi\pi \over 4} e^{-2|\xi|}}}$.


Intuitive reason why the Fisher Information of Binomial is inversely proportional to $p(1-p)$

Question: It confuses/blows my mind that the Binomial has variance proportional to $p(1-p)$. Equivalently, the Fisher information is proportional to $\frac{1}{p(1-p)}$. What is the reason for this? Why is the Fisher Information minimized at $p=0.5$? That is, why is inference most difficult at $p=0.5$?
Context:
I'm working on a sample size calculator, and the formula for $N$, the sample size needed, is an increasing factor of $p(1-p)$, the result of a variance estimation in the derivation.
Comment: The variance of a _Bernoulli_ random variable with parameter $p$ is $p(1-p)$ and the binomial random variable, being the sum of $N$ independent Bernoulli random variables, has variance $Np(1-p)$, which is the sum of the $N$ variances. With regard to _why_ $p(1-p)$, consider variance as the moment of inertia about the center of mass of masses $p$ and $1-p$ at $1$ and $0$ respectively.
Comment: Yes, I said proportional to $p(1-p)$, ignore the $N$. Can you elaborate on your second part, it seems like an interesting perspective.
Answer: To see, in an intuitive way, that the variance is maximised at $p = 0.5$, take $p$ equals to $0.99$ (resp. $p = 0.01$). Then a sample from $X \sim \text{Bernoulli}(p)$ will likely contain many $1$'s (resp. $0$'s) and just a few $0$'s (resp. $1$'s). There is not much variation there.
Comment: Again in a very intuitive way: the more variation, the more information you need.
Comment: That's true. Perhaps what I should be asking is *Why is the Fisher Information minimized at $p=0.5$?*, i.e. why is inference most difficult at $p=0.5$? I'll update my question to reflect that.
Answer: The inference is "hard" for $p$ 'in the middle, because an sample with $\hat p$ near the middle is consistent with a wider range of $p$. Near the ends, it can't be so far away - because of the ends being "barriers" beyond which $p$ cannot go.
I think the intuition is easier when looked at in variance terms, though.
The intuition about the variance of a binomial being large in the middle and small at the ends is rather straightforward: near the endpoints there isn't room for the data to "spread out". Consider $p$ small  -- because the mean is close to 0, the variation can't be large -- for the data to average $p$ it can only get so far from the mean.
Let's consider the variance of a sample proportion in a series of Bernoulli trials. Here $\text{Var}(\hat p) = p(1-p)/n$. So holding $n$ fixed, and varying $p$, the variation is much smaller for $p$ near 0:
Sample proportion in binomial samples -- here $y$ is just random uniform; the blue case has mean 0.03, the black mean 0.5 (some jitter added so the points don't pile up too much and lose detail)

The corresponding probability functions:

In each case pay attention to the lines marking the mean. As the mean line becomes more 'jammed up' against the barrier, points below the mean can only get a small way below.
As a result, points above the mean can't typically get too far above the mean (because otherwise the mean would shift!). Near $p = \frac{1}{2}$ the endpoints don't really "push it up" the same way it does when there's a barrier there.

We see at the same time why the distribution must be skewed at the ends; for the random variable $\hat p$ to be even some of the time to be more than $p$ above the mean, there must be correspondingly more probability squished about as far below the mean as it can go. That looming barrier at 0 gives both a limit on the variability and leads to skewness.
[This form of intuition doesn't tell us why it takes that exact functional form, but it does make it clear why the variance must be small near the ends, and get smaller the closer to the ends you go.]
Comment: *As a result, points above the mean can't typically get too far above the mean (because otherwise the mean would shift!). Near p=12 the endpoints don't really "push it up" the same way.*

Too perfect. This is a great explanation.
Answer: The Fisher information is the variance of the score function. And it is related to entropy. For a Bernoulli trial we are getting one bit for each trial. So this Fisher Information has similar properties as the Shannon Entropy, as we would expect. In particular the entropy has a maximum at 1/2 and the information has a minimum at 1/2.
Comment: Ah, another great perspective. I hadn't thought about this from the entropic point-of-view!