问:
Looping javascript function on time intervals
I a script, in JavaScript, that makes a typewriting effect. I've tried to loop it, so that it executes in a loop after 10 seconds from the end of execution. In other words there is a typewriting effect and when the text is written after ten second code will execute once again. I've tried with setTimeout(), however it did not work.

Thanks for help in advance.

```<code>function setupTypewriter(t) {
  var HTML = t.innerHTML;

  t.innerHTML = "";

  var cursorPosition = 0,
      tag = "",
      writingTag = false,
      tagOpen = false,
      typeSpeed = 50,
      tempTypeSpeed = 0;

  var type = function() {

    if (writingTag === true) {
      tag += HTML[cursorPosition];
    }

    if (HTML[cursorPosition] === "<") {
      tempTypeSpeed = 0;
      if (tagOpen) {
        tagOpen = false;
        writingTag = true;
      } else {
        tag = "";
        tagOpen = true;
        writingTag = true;
        tag += HTML[cursorPosition];
      }
    }
    if (!writingTag && tagOpen) {
      tag.innerHTML += HTML[cursorPosition];
    }
    if (!writingTag && !tagOpen) {
      if (HTML[cursorPosition] === " ") {
        tempTypeSpeed = 0;
      }
      else {
        tempTypeSpeed = (Math.random() * typeSpeed) + 50;
      }
      t.innerHTML += HTML[cursorPosition];
    }
    if (writingTag === true && HTML[cursorPosition] === ">") {
      tempTypeSpeed = (Math.random() * typeSpeed) + 50;
      writingTag = false;
      if (tagOpen) {
        var newSpan = document.createElement("span");
        t.appendChild(newSpan);
        newSpan.innerHTML = tag;
        tag = newSpan.firstChild;
      }
    }

    cursorPosition += 1;
    if (cursorPosition < HTML.length - 1) {
      setTimeout(type, tempTypeSpeed);
    }

  };

  return {
    type: type
  };
}

var typer = document.getElementById('typewriter');

typewriter = setupTypewriter(typewriter);

typewriter.type();
</code>```

答:
You want setInterval.

setInterval(function(){ alert("Hello"); }, 3000);

This code will run every three seconds.

Full documentation, examples etc. here (including how to stop it):

https://www.w3schools.com/jsref/met_win_setinterval.asp

Body:
I a script, in JavaScript, that makes a typewriting effect. I've tried to loop it, so that it executes in a loop after 10 seconds from the end of execution. In other words there is a typewriting effect and when the text is written after ten second code will execute once again. I've tried with setTimeout(), however it did not work.

Thanks for help in advance.

function setupTypewriter(t) {
  var HTML = t.innerHTML;

  t.innerHTML = "";

  var cursorPosition = 0,
      tag = "",
      writingTag = false,
      tagOpen = false,
      typeSpeed = 50,
      tempTypeSpeed = 0;

  var type = function() {

    if (writingTag === true) {
      tag += HTML[cursorPosition];
    }

    if (HTML[cursorPosition] === "<") {
      tempTypeSpeed = 0;
      if (tagOpen) {
        tagOpen = false;
        writingTag = true;
      } else {
        tag = "";
        tagOpen = true;
        writingTag = true;
        tag += HTML[cursorPosition];
      }
    }
    if (!writingTag && tagOpen) {
      tag.innerHTML += HTML[cursorPosition];
    }
    if (!writingTag && !tagOpen) {
      if (HTML[cursorPosition] === " ") {
        tempTypeSpeed = 0;
      }
      else {
        tempTypeSpeed = (Math.random() * typeSpeed) + 50;
      }
      t.innerHTML += HTML[cursorPosition];
    }
    if (writingTag === true && HTML[cursorPosition] === ">") {
      tempTypeSpeed = (Math.random() * typeSpeed) + 50;
      writingTag = false;
      if (tagOpen) {
        var newSpan = document.createElement("span");
        t.appendChild(newSpan);
        newSpan.innerHTML = tag;
        tag = newSpan.firstChild;
      }
    }

    cursorPosition += 1;
    if (cursorPosition < HTML.length - 1) {
      setTimeout(type, tempTypeSpeed);
    }

  };

  return {
    type: type
  };
}

var typer = document.getElementById('typewriter');

typewriter = setupTypewriter(typewriter);

typewriter.type();


来源: stackexchange

问:
CSR for iPage site with Third Party SSL
after recently setting up a website on iPage I have come across an issue not listen on their website. You cannot get a CSR code from them, and so you cannot easily use a Third Partly SSL. So I am simply wondering how I could generate my own CSR code that will work with a site hosted on iPage.

Any help is greatly appreciated.

答: You can generate your csr using csr.ninja. It's easy and will send you a copy by mail.</p>

ContentLicense: CC BY-SA 3.0

Title: CSR for iPage site with Third Party SSL


问:
Snackbar$SnackbarLayout.onFinishInflate issue
I face issue while I am trying to use Snackbar in Xamarin.Android

here is error stack

```<code>Java.Lang.ClassCastException: android.support.v7.widget.AppCompatTextView cannot be cast to android.widget.Button
</code>```

any one can guide me why this issue raised

my xml code

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/login_layout">
    <android.support.v7.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/pumpkin_orange"
        android:id="@+id/loginToolBar">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <ReadyApps.Xamarin.Framework.Droid.Controls.ExtImageView
                android:id="@+id/closeImageView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:srcCompat="@drawable/ic_arrow_back_white_24dp"
                android:layout_centerVertical="true" />
            <ReadyApps.Xamarin.Framework.Droid.Controls.ExtTextView
                android:id="@+id/toolbarTitle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                style="@style/TextStyle7"
                android:layout_toRightOf="@+id/closeImageView"
                android:layout_toEndOf="@+id/closeImageView"
                android:layout_marginLeft="25dp"
                android:layout_marginStart="25dp"
                android:text="@string/signin"
                android:layout_centerVertical="true" />
        </RelativeLayout>
    </android.support.v7.widget.Toolbar>
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white"
        android:layout_gravity="center_horizontal">
        <ReadyApps.Xamarin.Framework.Droid.Controls.ExtImageView
            android:src="@drawable/ic_launcher"
            android:layout_width="wrap_content"
            android:layout_height="150dp"
            android:id="@+id/imageView1"
            android:layout_centerHorizontal="true" />
        <LinearLayout
            android:id="@+id/layout"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="40dp"
            android:layout_marginRight="40dp"
            android:layout_below="@+id/imageView1">
            <android.support.design.widget.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textColorHint="@color/orange_two">
                <ReadyApps.Xamarin.Framework.Droid.Controls.ExtEditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="13.3sp"
                    android:hint="@string/storecode"
                    android:id="@+id/login_storeCode"
                    android:drawablePadding="7.3dp"
                    android:tag="Required" />
            </android.support.design.widget.TextInputLayout>
            <android.support.design.widget.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textColorHint="@color/orange_two">
                <ReadyApps.Xamarin.Framework.Droid.Controls.ExtEditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="13.3sp"
                    android:hint="@string/username_email"
                    android:id="@+id/login_userName"
                    android:tag="Required"
                    android:drawablePadding="7.3dp" />
            </android.support.design.widget.TextInputLayout>
            <android.support.design.widget.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textColorHint="@color/orange_two">
                <ReadyApps.Xamarin.Framework.Droid.Controls.ExtEditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="13.3sp"
                    android:inputType="textPassword"
                    android:hint="@string/password"
                    android:id="@+id/login_password"
                    android:tag="Required"
                    android:drawablePadding="7.3dp" />
            </android.support.design.widget.TextInputLayout>
        </LinearLayout>
        <ReadyApps.Xamarin.Framework.Droid.Controls.ExtTextView
            android:text="@string/signin"
            android:layout_marginTop="50dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/signIn"
            android:layout_below="@+id/layout"
            android:textAllCaps="true"
            android:layout_centerHorizontal="true"
            android:textSize="14.7sp"
            android:padding="5dp"
            style="@style/TextStyle11" />

      <RelativeLayout
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:layout_marginTop="50dp"
           android:layout_marginLeft="40dp"
           android:layout_marginRight="40dp"
           android:layout_below="@+id/signIn">
        <ReadyApps.Xamarin.Framework.Droid.Controls.ExtTextView
            android:id="@+id/login_forgetpassword"
            android:text="@string/forgetpassword"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/TextStyle12" />
        <ReadyApps.Xamarin.Framework.Droid.Controls.ExtTextView
              android:id="@+id/login_signUp"
              android:text="@string/signup"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
               android:textAllCaps="true"
              android:layout_alignParentRight="true"
              android:layout_alignParentEnd="true"
              style="@style/TextStyle12"
                />
      </RelativeLayout>
    </RelativeLayout>
</LinearLayout>
</code>```

my code

```<code>public class LoginActivity : BaseActivity<LoginActivityLogic>
    {

     private ExtEditText et_vendorCode, et_userName, et_password;
    private ExtTextView tv_forgetpassword , tv_signUp , bt_signIn;
    private LinearLayout login_layout;
    private string vendorCode;

      protected override void OnCreate(Bundle savedInstanceState)
      {
       SetContentView(Resource.Layout.Login);
       base.OnCreate(savedInstanceState);

      initView();
       }

    private void initView()
    {
        login_layout = FindViewById<LinearLayout>(Resource.Id.login_layout);
        tv_signUp = FindViewById<ExtTextView>(Resource.Id.login_signUp);
        bt_signIn = FindViewById<ExtTextView>(Resource.Id.signIn);
        tv_forgetpassword = FindViewById<ExtTextView>(Resource.Id.login_forgetpassword);
        et_vendorCode = FindViewById<ExtEditText>(Resource.Id.login_storeCode);
        et_userName = FindViewById<ExtEditText>(Resource.Id.login_userName);

        et_password = FindViewById<ExtEditText>(Resource.Id.login_password);

        tv_forgetpassword.Click += Tv_forgetpassword_Click;
        bt_signIn.Click += Bt_signIn_Click;
        et_vendorCode.Text = vendorCode;

        tv_signUp.Click += Tv_signUp_Click;

        ExtImageView iv_Close = FindViewById<ExtImageView>(Resource.Id.closeImageView);
        iv_Close.Click += delegate { Finish(); };

        // android: drawableLeft = "@drawable/ic_business_bluey_grey_24dp"
        et_vendorCode.SetCompoundDrawablesWithIntrinsicBounds(Resource.Drawable.ic_business_bluey_grey_24dp , 0 , 0 , 0);

        //android: drawableLeft = "@drawable/ic_account_blue_grey_24dp"
        et_userName.SetCompoundDrawablesWithIntrinsicBounds(Resource.Drawable.ic_account_blue_grey_24dp, 0, 0, 0);

        //android: drawableLeft = "@drawable/ic_lock_blue_grey_24dp"
        et_password.SetCompoundDrawablesWithIntrinsicBounds(Resource.Drawable.ic_lock_blue_grey_24dp, 0, 0, 0);

    }

// I call it in method

 Snackbar.Make(login_layout, "mystring", Snackbar.LengthShort).Show();

}
</code>```

but I got error

my error log

```<code>java.lang.ClassCastException: android.support.v7.widget.AppCompatTextView cannot be cast to android.widget.Button
android.support.design.widget.Snackbar$SnackbarLayout.onFinishInflate()Snackbar.java:696
android.view.LayoutInflater.rInflate()LayoutInflater.java:814
android.view.LayoutInflater.inflate()LayoutInflater.java:504
android.view.LayoutInflater.inflate()LayoutInflater.java:414
android.support.design.widget.Snackbar.<init>()Snackbar.java:188
android.support.design.widget.Snackbar.make()Snackbar.java:215
mono.java.lang.RunnableImplementor.n_run(Native Method)
mono.java.lang.RunnableImplementor.run()RunnableImplementor.java:30
android.os.Handler.handleCallback()Handler.java:739
android.os.Handler.dispatchMessage()Handler.java:95
android.os.Looper.loop()Looper.java:135
android.app.ActivityThread.main()ActivityThread.java:5221
java.lang.reflect.Method.invoke(Native Method)
java.lang.reflect.Method.invoke()Method.java:372
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run()ZygoteInit.java:899
com.android.internal.os.ZygoteInit.main()ZygoteInit.java:694
Xamarin caused by: Java.Lang.ClassCastException: android.support.v7.widget.AppCompatTextView cannot be cast to android.widget.Button
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()exceptionservicescommon.cs:143
Java.Interop.JniEnvironment.StaticMethods.CallStaticObjectMethod(JniObjectReference type, JniMethodInfo method, JniArgumentValue* args)JniEnvironment.g.cs:12649
Android.Runtime.JNIEnv.CallStaticObjectMethod(IntPtr jclass, IntPtr jmethod, JValue* parms)JNIEnv.g.cs:562
Android.Support.Design.Widget.Snackbar.Make(View view, ICharSequence text, int duration)<0d997552ddad494094d94e2a353b2022>:0
Android.Support.Design.Widget.Snackbar.Make(View view, string text, int duration)<0d997552ddad494094d94e2a353b2022>:0
DSP.Droid.Activities.Orders.LoginActivity.AfterSaveResponse(object sender, EventArgs args)
DSP.Core.UILogic.Orders.LoginActivityLogic.<SignIn>d__1.MoveNext()
Android.App.SyncContext.<Post>c__AnonStorey0.<>m__0()SyncContext.cs:18
Java.Lang.Thread.RunnableImplementor.Run()Thread.cs:36
Java.Lang.IRunnableInvoker.n_Run(IntPtr jnienv, IntPtr native__this)Java.Lang.IRunnable.cs:81
at (wrapper dynamic-method) System.Object:4ae9575e-e099-4bc0-bb97-0bb4377e913d (intptr,intptr)
--- End of managed Java.Lang.ClassCastException stack trace ---
java.lang.ClassCastException: android.support.v7.widget.AppCompatTextView cannot be cast to android.widget.Button
android.support.design.widget.Snackbar$SnackbarLayout.onFinishInflate()Snackbar.java:696
android.view.LayoutInflater.rInflate()LayoutInflater.java:814
android.view.LayoutInflater.inflate()LayoutInflater.java:504
android.view.LayoutInflater.inflate()LayoutInflater.java:414
android.support.design.widget.Snackbar.<init>()Snackbar.java:188
android.support.design.widget.Snackbar.make()Snackbar.java:215
mono.java.lang.RunnableImplementor.n_run(Native Method)
mono.java.lang.RunnableImplementor.run()RunnableImplementor.java:30
android.os.Handler.handleCallback()Handler.java:739
android.os.Handler.dispatchMessage()Handler.java:95
android.os.Looper.loop()Looper.java:135
android.app.ActivityThread.main()ActivityThread.java:5221
java.lang.reflect.Method.invoke(Native Method)
java.lang.reflect.Method.invoke()Method.java:372
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run()ZygoteInit.java:899
com.android.internal.os.ZygoteInit.main()ZygoteInit.java:694
</code>```

答:
This random error raised in run time you will face with old version

How to fix it ? Upgrade to support library v25 or above

Body:
I face issue while I am trying to use Snackbar in Xamarin.Android

here is error stack

Java.Lang.ClassCastException: android.support.v7.widget.AppCompatTextView cannot be cast to android.widget.Button

any one can guide me why this issue raised

my xml code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/login_layout">
    <android.support.v7.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/pumpkin_orange"
        android:id="@+id/loginToolBar">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <ReadyApps.Xamarin.Framework.Droid.Controls.ExtImageView
                android:id="@+id/closeImageView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:srcCompat="@drawable/ic_arrow_back_white_24dp"
                android:layout_centerVertical="true" />
            <ReadyApps.Xamarin.Framework.Droid.Controls.ExtTextView
                android:id="@+id/toolbarTitle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                style="@style/TextStyle7"
                android:layout_toRightOf="@+id/closeImageView"
                android:layout_toEndOf="@+id/closeImageView"
                android:layout_marginLeft="25dp"
                android:layout_marginStart="25dp"
                android:text="@string/signin"
                android:layout_centerVertical="true" />
        </RelativeLayout>
    </android.support.v7.widget.Toolbar>
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white"
        android:layout_gravity="center_horizontal">
        <ReadyApps.Xamarin.Framework.Droid.Controls.ExtImageView
            android:src="@drawable/ic_launcher"
            android:layout_width="wrap_content"
            android:layout_height="150dp"
            android:id="@+id/imageView1"
            android:layout_centerHorizontal="true" />
        <LinearLayout
            android:id="@+id/layout"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="40dp"
            android:layout_marginRight="40dp"
            android:layout_below="@+id/imageView1">
            <android.support.design.widget.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textColorHint="@color/orange_two">
                <ReadyApps.Xamarin.Framework.Droid.Controls.ExtEditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="13.3sp"
                    android:hint="@string/storecode"
                    android:id="@+id/login_storeCode"
                    android:drawablePadding="7.3dp"
                    android:tag="Required" />
            </android.support.design.widget.TextInputLayout>
            <android.support.design.widget.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textColorHint="@color/orange_two">
                <ReadyApps.Xamarin.Framework.Droid.Controls.ExtEditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="13.3sp"
                    android:hint="@string/username_email"
                    android:id="@+id/login_userName"
                    android:tag="Required"
                    android:drawablePadding="7.3dp" />
            </android.support.design.widget.TextInputLayout>
            <android.support.design.widget.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textColorHint="@color/orange_two">
                <ReadyApps.Xamarin.Framework.Droid.Controls.ExtEditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="13.3sp"
                    android:inputType="textPassword"
                    android:hint="@string/password"
                    android:id="@+id/login_password"
                    android:tag="Required"
                    android:drawablePadding="7.3dp" />
            </android.support.design.widget.TextInputLayout>
        </LinearLayout>
        <ReadyApps.Xamarin.Framework.Droid.Controls.ExtTextView
            android:text="@string/signin"
            android:layout_marginTop="50dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/signIn"
            android:layout_below="@+id/layout"
            android:textAllCaps="true"
            android:layout_centerHorizontal="true"
            android:textSize="14.7sp"
            android:padding="5dp"
            style="@style/TextStyle11" />

      <RelativeLayout
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:layout_marginTop="50dp"
           android:layout_marginLeft="40dp"
           android:layout_marginRight="40dp"
           android:layout_below="@+id/signIn">
        <ReadyApps.Xamarin.Framework.Droid.Controls.ExtTextView
            android:id="@+id/login_forgetpassword"
            android:text="@string/forgetpassword"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/TextStyle12" />
        <ReadyApps.Xamarin.Framework.Droid.Controls.ExtTextView
              android:id="@+id/login_signUp"
              android:text="@string/signup"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
               android:textAllCaps="true"
              android:layout_alignParentRight="true"
              android:layout_alignParentEnd="true"
              style="@style/TextStyle12"
                />
      </RelativeLayout>
    </RelativeLayout>
</LinearLayout>

my code

public class LoginActivity : BaseActivity<LoginActivityLogic>
    {

     private ExtEditText et_vendorCode, et_userName, et_password;
    private ExtTextView tv_forgetpassword , tv_signUp , bt_signIn;
    private LinearLayout login_layout;
    private string vendorCode;

      protected override void OnCreate(Bundle savedInstanceState)
      {
       SetContentView(Resource.Layout.Login);
       base.OnCreate(savedInstanceState);

      initView();
       }

    private void initView()
    {
        login_layout = FindViewById<LinearLayout>(Resource.Id.login_layout);
        tv_signUp = FindViewById<ExtTextView>(Resource.Id.login_signUp);
        bt_signIn = FindViewById<ExtTextView>(Resource.Id.signIn);
        tv_forgetpassword = FindViewById<ExtTextView>(Resource.Id.login_forgetpassword);
        et_vendorCode = FindViewById<ExtEditText>(Resource.Id.login_storeCode);
        et_userName = FindViewById<ExtEditText>(Resource.Id.login_userName);

        et_password = FindViewById<ExtEditText>(Resource.Id.login_password);

        tv_forgetpassword.Click += Tv_forgetpassword_Click;
        bt_signIn.Click += Bt_signIn_Click;
        et_vendorCode.Text = vendorCode;

        tv_signUp.Click += Tv_signUp_Click;

        ExtImageView iv_Close = FindViewById<ExtImageView>(Resource.Id.closeImageView);
        iv_Close.Click += delegate { Finish(); };

        // android: drawableLeft = "@drawable/ic_business_bluey_grey_24dp"
        et_vendorCode.SetCompoundDrawablesWithIntrinsicBounds(Resource.Drawable.ic_business_bluey_grey_24dp , 0 , 0 , 0);

        //android: drawableLeft = "@drawable/ic_account_blue_grey_24dp"
        et_userName.SetCompoundDrawablesWithIntrinsicBounds(Resource.Drawable.ic_account_blue_grey_24dp, 0, 0, 0);

        //android: drawableLeft = "@drawable/ic_lock_blue_grey_24dp"
        et_password.SetCompoundDrawablesWithIntrinsicBounds(Resource.Drawable.ic_lock_blue_grey_24dp, 0, 0, 0);

    }

// I call it in method

 Snackbar.Make(login_layout, "mystring", Snackbar.LengthShort).Show();

}

but I got error

my error log

java.lang.ClassCastException: android.support.v7.widget.AppCompatTextView cannot be cast to android.widget.Button
android.support.design.widget.Snackbar$SnackbarLayout.onFinishInflate()Snackbar.java:696
android.view.LayoutInflater.rInflate()LayoutInflater.java:814
android.view.LayoutInflater.inflate()LayoutInflater.java:504
android.view.LayoutInflater.inflate()LayoutInflater.java:414
android.support.design.widget.Snackbar.<init>()Snackbar.java:188
android.support.design.widget.Snackbar.make()Snackbar.java:215
mono.java.lang.RunnableImplementor.n_run(Native Method)
mono.java.lang.RunnableImplementor.run()RunnableImplementor.java:30
android.os.Handler.handleCallback()Handler.java:739
android.os.Handler.dispatchMessage()Handler.java:95
android.os.Looper.loop()Looper.java:135
android.app.ActivityThread.main()ActivityThread.java:5221
java.lang.reflect.Method.invoke(Native Method)
java.lang.reflect.Method.invoke()Method.java:372
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run()ZygoteInit.java:899
com.android.internal.os.ZygoteInit.main()ZygoteInit.java:694
Xamarin caused by: Java.Lang.ClassCastException: android.support.v7.widget.AppCompatTextView cannot be cast to android.widget.Button
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()exceptionservicescommon.cs:143
Java.Interop.JniEnvironment.StaticMethods.CallStaticObjectMethod(JniObjectReference type, JniMethodInfo method, JniArgumentValue* args)JniEnvironment.g.cs:12649
Android.Runtime.JNIEnv.CallStaticObjectMethod(IntPtr jclass, IntPtr jmethod, JValue* parms)JNIEnv.g.cs:562
Android.Support.Design.Widget.Snackbar.Make(View view, ICharSequence text, int duration)<0d997552ddad494094d94e2a353b2022>:0
Android.Support.Design.Widget.Snackbar.Make(View view, string text, int duration)<0d997552ddad494094d94e2a353b2022>:0
DSP.Droid.Activities.Orders.LoginActivity.AfterSaveResponse(object sender, EventArgs args)
DSP.Core.UILogic.Orders.LoginActivityLogic.<SignIn>d__1.MoveNext()
Android.App.SyncContext.<Post>c__AnonStorey0.<>m__0()SyncContext.cs:18
Java.Lang.Thread.RunnableImplementor.Run()Thread.cs:36
Java.Lang.IRunnableInvoker.n_Run(IntPtr jnienv, IntPtr native__this)Java.Lang.IRunnable.cs:81
at (wrapper dynamic-method) System.Object:4ae9575e-e099-4bc0-bb97-0bb4377e913d (intptr,intptr)
--- End of managed Java.Lang.ClassCastException stack trace ---
java.lang.ClassCastException: android.support.v7.widget.AppCompatTextView cannot be cast to android.widget.Button
android.support.design.widget.Snackbar$SnackbarLayout.onFinishInflate()Snackbar.java:696
android.view.LayoutInflater.rInflate()LayoutInflater.java:814
android.view.LayoutInflater.inflate()LayoutInflater.java:504
android.view.LayoutInflater.inflate()LayoutInflater.java:414
android.support.design.widget.Snackbar.<init>()Snackbar.java:188
android.support.design.widget.Snackbar.make()Snackbar.java:215
mono.java.lang.RunnableImplementor.n_run(Native Method)
mono.java.lang.RunnableImplementor.run()RunnableImplementor.java:30
android.os.Handler.handleCallback()Handler.java:739
android.os.Handler.dispatchMessage()Handler.java:95
android.os.Looper.loop()Looper.java:135
android.app.ActivityThread.main()ActivityThread.java:5221
java.lang.reflect.Method.invoke(Native Method)
java.lang.reflect.Method.invoke()Method.java:372
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run()ZygoteInit.java:899
com.android.internal.os.ZygoteInit.main()ZygoteInit.java:694


问:
How to separate a picture to color groups?
Let's say I have an image of a ball like this one:

I want to separate the colors of the ball to the color groups. In this case I should have 2 main color groups - "brown" and "white". The "brown" group will have all the brown pixels and the "white" group will have all the white pixels.
I'm using matlab for this task. The way that I thought to do is:

to look at the RGB channels. I used scatter to look if I could clearly see some groups, but I didn't.

to look at the bayer vales. But couldn't see any groups either.

to run an edge detector. Then, in each enclosed area I'll find the mean of the pixels. The areas that will have similar mean values (within a certain threshold) will belong to the same group. It seemed to sort of to work but in many case it didn't

Any other ideas?

答:
While image segmentation would be the correct way to treat color separation, if your image is simple, you can try to do it brute-force.

Here, converting to HSV would be easier to handle with the image.

For the white parts of the image:

```<code>I=imread('ball.jpg');
H=rgb2hsv(I);
% separate dimensions
h=H(:,:,1);
s=H(:,:,2);
v=H(:,:,3);

% color conditions
v(v<0.8 | s>0.7 | h>0.7 )=NaN;
h(isnan(v))=NaN;
s(isnan(v))=NaN;

% convert image back
W=cat(3,h,s,v);
White_image=hsv2rgb(W);
figure; imagesc(White_image);
</code>```

And for the brown parts:

```<code>% separate dimensions
h=H(:,:,1);
s=H(:,:,2);
v=H(:,:,3);

% color conditions
v(s<0.6 | v>0.8 )=NaN;
h(isnan(v))=NaN;
s(isnan(v))=NaN;

% convert image back
B=cat(3,h,s,v);
Brown_image=hsv2rgb(B);
figure; imagesc(Brown_image); axis off
</code>```

Body:
While image segmentation would be the correct way to treat color separation, if your image is simple, you can try to do it brute-force.

Here, converting to HSV would be easier to handle with the image.

For the white parts of the image:

I=imread('ball.jpg');
H=rgb2hsv(I);
% separate dimensions
h=H(:,:,1);
s=H(:,:,2);
v=H(:,:,3);

% color conditions
v(v<0.8 | s>0.7 | h>0.7 )=NaN;
h(isnan(v))=NaN;
s(isnan(v))=NaN;

% convert image back
W=cat(3,h,s,v);
White_image=hsv2rgb(W);
figure; imagesc(White_image);

And for the brown parts:

% separate dimensions
h=H(:,:,1);
s=H(:,:,2);
v=H(:,:,3);

% color conditions
v(s<0.6 | v>0.8 )=NaN;
h(isnan(v))=NaN;
s(isnan(v))=NaN;

% convert image back
B=cat(3,h,s,v);
Brown_image=hsv2rgb(B);
figure; imagesc(Brown_image); axis off


问:
How do i copy the columns from a table and insert it into another table with a sequenced column?(PostgreSQ
I have a table called test_pois and i want to copy the columns code and fclass to the columns on the table test_fclass.

But the problem is, that the table test_fclass has a column named fid, which is a sequenced column. So i want the copied columns just for once. I'm using PostgreSQL. How could i realize it ? I thought of writing a function , but maybe there is an easier way.

In the end , i want to create a foreign key on the table test_pois which reduces 2 columns into 1 with an id.

Maybe you would say, make it by writing some inserts, but there is a lot of data in it.

I used the following insert into statement to copy the data from the test_pois table :

```<code>insert into test_fclass (fcode, fclass) select code, fclass from test_pois;
</code>```

The output:

As you can see the ids 4-7 are assigned for code 2907. But I want a uniqe id for code 2907.

答:
I made it with a plpgsql function.

```<code>    CREATE or replace FUNCTION populate() RETURNS void AS $$
DECLARE
    anzahl integer;
    zahl integer;
    zahl2 integer;
    text varchar(20);
    count integer;
    varcode smallint;
    var integer;
    varclass character varying(20);
    curse CURSOR FOR SELECT fcode FROM fclass;

    poiscurse cursor for select code from test_pois;
BEGIN

var := 0;
anzahl:= 0;
zahl := 0;
for v_anzahl in poiscurse
loop

var := var +1;
--raise notice '%',var;
text := v_anzahl::text;
SELECT substring(text FROM '[0-9]+') into zahl;
select code,fclass into varcode,varclass
from test_pois
where code = zahl;
if var = 1 then
insert into fclass (fcode, fclass) values (varcode,varclass);
raise notice '% and % inserted',varcode,varclass;
end if;
anzahl := 0;
for v_zahl in curse
loop
text := v_zahl::text;
SELECT substring(text FROM '[0-9]+') into zahl2;
if zahl = zahl2 then
anzahl := anzahl +1;
exit;
end if;
end loop;
if anzahl = 0 then
insert into fclass (fcode, fclass) values (varcode,varclass);
raise notice '% und % eingefügt',varcode,varclass;
end if;
end loop;
end;

$$ LANGUAGE plpgsql
</code>```

And the output:

Thanks for the answers by the way.

Body:
I have a table called test_pois and i want to copy the columns code and fclass to the columns on the table test_fclass.

But the problem is, that the table test_fclass has a column named fid, which is a sequenced column. So i want the copied columns just for once. I'm using PostgreSQL. How could i realize it ? I thought of writing a function , but maybe there is an easier way.

In the end , i want to create a foreign key on the table test_pois which reduces 2 columns into 1 with an id.

Maybe you would say, make it by writing some inserts, but there is a lot of data in it.

I used the following insert into statement to copy the data from the test_pois table :

insert into test_fclass (fcode, fclass) select code, fclass from test_pois;

The output:

As you can see the ids 4-7 are assigned for code 2907. But I want a uniqe id for code 2907.

Body:
I made it with a plpgsql function.

    CREATE or replace FUNCTION populate() RETURNS void AS $$
DECLARE
    anzahl integer;
    zahl integer;
    zahl2 integer;
    text varchar(20);
    count integer;
    varcode smallint;
    var integer;
    varclass character varying(20);
    curse CURSOR FOR SELECT fcode FROM fclass;

    poiscurse cursor for select code from test_pois;
BEGIN

var := 0;
anzahl:= 0;
zahl := 0;
for v_anzahl in poiscurse
loop

var := var +1;
--raise notice '%',var;
text := v_anzahl::text;
SELECT substring(text FROM '[0-9]+') into zahl;
select code,fclass into varcode,varclass
from test_pois
where code = zahl;
if var = 1 then
insert into fclass (fcode, fclass) values (varcode,varclass);
raise notice '% and % inserted',varcode,varclass;
end if;
anzahl := 0;
for v_zahl in curse
loop
text := v_zahl::text;
SELECT substring(text FROM '[0-9]+') into zahl2;
if zahl = zahl2 then
anzahl := anzahl +1;
exit;
end if;
end loop;
if anzahl = 0 then
insert into fclass (fcode, fclass) values (varcode,varclass);
raise notice '% und % eingefügt',varcode,varclass;
end if;
end loop;
end;

$$ LANGUAGE plpgsql

And the output:

Thanks for the answers by the way.


问:
MONGO_QUERY_BLACKLIST doesn't work
I'm using python-eve with default settings where

```<code>'MONGO_QUERY_BLACKLIST': ['$where', '$regex']
</code>```

But it appears that I still can use 'where'-parameter in queries to Eve.

```<code>import requests

params = {'where': '{"username":"Alex"}'}
response = requests.get('http://localhost/users', params)
print response.content
print response.status_code
</code>```

{"_items": [{"username": "Alex", ... }], ...}

200

答:
@Stennie is correct that QUERY_MONGO_BLACKLIST refers to actual query parameters, not the lookup keyword itself. However, if you want to disable filtering altogether just set ALLOWED_FILTERS = [].

Also, you can use QUERY_WHERE to pick another keyword if you do not want where:

```<code># disable filters
ALLOWED_FILTERS = []
# replace the default 'where' with 'find'
QUERY_WHERE = 'find'
</code>```

Title: MONGO_QUERY_BLACKLIST doesn't work

Body:
I'm using python-eve with default settings where

'MONGO_QUERY_BLACKLIST': ['$where', '$regex']

But it appears that I still can use 'where'-parameter in queries to Eve.

import requests

params = {'where': '{"username":"Alex"}'}
response = requests.get('http://localhost/users', params)
print response.content
print response.status_code

{"_items": [{"username": "Alex", ... }], ...}

200

Body:
@Stennie is correct that QUERY_MONGO_BLACKLIST refers to actual query parameters, not the lookup keyword itself. However, if you want to disable filtering altogether just set ALLOWED_FILTERS = [].

Also, you can use QUERY_WHERE to pick another keyword if you do not want where:

# disable filters
ALLOWED_FILTERS = []
# replace the default 'where' with 'find'
QUERY_WHERE = 'find'


问:
Getting a website with urllib results in HTTP 405 error
Im learning beautifulsoup and was trying to write a small script to find houses on a dutch real estate website. When I try to get the website's content, I'm immediately getting an HTTP405 error:

```<code>  File "funda.py", line 2, in <module>
    html = urlopen("http://www.funda.nl")
  File "<folders>request.py", line 223, in urlopen
    return opener.open(url, data, timeout)
  File "<folders>request.py", line 532, in open
    response = meth(req, response)
  File "<folders>request.py", line 642, in http_response
    'http', request, response, code, msg, hdrs)
  File "<folders>request.py", line 570, in error
    return self._call_chain(*args)
  File "<folders>request.py", line 504, in _call_chain
    result = func(*args)
  File "<folders>request.py", line 650, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 405: Not Allowed
</code>```

What im trying to execute:

```<code>from urllib.request import urlopen
html = urlopen("http://www.funda.nl")
</code>```

Any idea why this is resulting in HTTP405? Im just doing a GET request, right?

答:
Possible duplicate of HTTPError: HTTP Error 403: Forbidden. You need to fake that you are a regular visitor. This is generally (varies from site to site) done by using a common / regular User-Agent HTTP header.

```<code>>>> url = "http://www.funda.nl"
>>> import urllib.request
>>> req = urllib.request.Request(
...     url,
...     data=None,
...     headers={
...         'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'
...     }
... )
>>> f = urllib.request.urlopen(req)
>>> f.status, f.msg
(200, 'OK')
</code>```

Using the requests library -

```<code>>>> import requests
>>> response = requests.get(
...     url,
...     headers={
...         'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'
...     }
... )
>>> response.status_code
200
</code>```

Body:
Im learning beautifulsoup and was trying to write a small script to find houses on a dutch real estate website. When I try to get the website's content, I'm immediately getting an HTTP405 error:

  File "funda.py", line 2, in <module>
    html = urlopen("http://www.funda.nl")
  File "<folders>request.py", line 223, in urlopen
    return opener.open(url, data, timeout)
  File "<folders>request.py", line 532, in open
    response = meth(req, response)
  File "<folders>request.py", line 642, in http_response
    'http', request, response, code, msg, hdrs)
  File "<folders>request.py", line 570, in error
    return self._call_chain(*args)
  File "<folders>request.py", line 504, in _call_chain
    result = func(*args)
  File "<folders>request.py", line 650, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 405: Not Allowed

What im trying to execute:

from urllib.request import urlopen
html = urlopen("http://www.funda.nl")

Any idea why this is resulting in HTTP405? Im just doing a GET request, right?

Body:
Possible duplicate of HTTPError: HTTP Error 403: Forbidden. You need to fake that you are a regular visitor. This is generally (varies from site to site) done by using a common / regular User-Agent HTTP header.

>>> url = "http://www.funda.nl"
>>> import urllib.request
>>> req = urllib.request.Request(
...     url,
...     data=None,
...     headers={
...         'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'
...     }
... )
>>> f = urllib.request.urlopen(req)
>>> f.status, f.msg
(200, 'OK')

Using the requests library -

>>> import requests
>>> response = requests.get(
...     url,
...     headers={
...         'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'
...     }
... )
>>> response.status_code
200


问:
Proto deserialization from json will fail on new fields or unknown enum values
proto is designed so that introduction of new fields should not break your code that runs on older version.

But if you're using json conversion in java using protobuf-java-util then your old code will break on new fields or new enum values unknown to existing code...

I've opened an issue on github but it does not get any attention. I hope to get some answers here.

Given message like this

```<code>message Msg {
    required string sender = 1;
    required string message = 2;
}
</code>```

if we convert this to json and print using

```<code>JsonFormat.printer().print(msg)
</code>```

we will have this result

```<code>{
  "sender": "me",
  "message": "message"
}
</code>```

if we decode this json to Msg using its builder

```<code>JsonFormat.parser().merge(json, builder)
</code>```

we will get expected result... But if we try to decode similar json with additional extra field

```<code>{
  "sender": "me",
  "message": "message",
  "extra" : "some extra stuff"
}
</code>```

we will fail with this exception

```<code>com.google.protobuf.InvalidProtocolBufferException: Cannot find field: extra in message proto.Msg
</code>```

How is that nobody cares about this problem? So far my only solution to this is to write a parser from scratch that will ignore unknown fields and unknown enum values when parsing...

Is there something i overlooked or people simply dont use backwards compatibility features?

答: This is already fixed by google, the builder provides option to ignore unknown fields.</p>

Body:
proto is designed so that introduction of new fields should not break your code that runs on older version.

But if you're using json conversion in java using protobuf-java-util then your old code will break on new fields or new enum values unknown to existing code...

I've opened an issue on github but it does not get any attention. I hope to get some answers here.

Given message like this

message Msg {
    required string sender = 1;
    required string message = 2;
}

if we convert this to json and print using

JsonFormat.printer().print(msg)

we will have this result

{
  "sender": "me",
  "message": "message"
}

if we decode this json to Msg using its builder

JsonFormat.parser().merge(json, builder)

we will get expected result... But if we try to decode similar json with additional extra field

{
  "sender": "me",
  "message": "message",
  "extra" : "some extra stuff"
}

we will fail with this exception

com.google.protobuf.InvalidProtocolBufferException: Cannot find field: extra in message proto.Msg

How is that nobody cares about this problem? So far my only solution to this is to write a parser from scratch that will ignore unknown fields and unknown enum values when parsing...

Is there something i overlooked or people simply dont use backwards compatibility features?


问:
How to generate equal amount of different strings
I have this now:

```<code>var generateIcons = function(playtime, players) {
var count = playtime / 2;
icons = [];
for (var i = 1; i <= count; i++) {
    if (i % 8 === 0 && players === 8) {
        icons.push("cyan");
    }
    else if (i % 7 === 0 && players >= 7) {
        icons.push("violet");
    }
    else if (i % 6 === 0 && players >= 6) {
        icons.push("orange");
    }
    else if (i % 5 === 0 && players >= 5) {
        icons.push("black");
    }
    else if (i % 4 === 0 && players >= 4) {
        icons.push("gold");
    }
    else if (i % 3 === 0 && players >= 3) {
        icons.push("red");
    }
    else if (i % 2 === 0 && players >= 2) {
        icons.push("blue");
    }
    else {
        icons.push("green");
    }
}
};
</code>```

The problem is that, I get much more green than blue for example with: generateIcons(60,4);
How to get ~equal amount of green, blue, red, gold?

答:
Check If that solution satisfies you :)</p>

```<code>var generateIcons = function(playtime, players) {
            var count = playtime / 2;
            icons = [];
            var randomNumber;

            for (var i = 1; i <= count; i++) {
                randomNumber = Math.floor((Math.random() *  players) + 1); //generate random number from <1, players> probability for each color should be ~equal ;)
                if(randomNumber == 1)
                {
                    icons.push("green");
                }
                else if (randomNumber == 2)
                {
                    icons.push("blue");
                }
                else if (randomNumber == 3)
                {
                    icons.push("red");
                }
                else if (randomNumber == 4)
                {
                    icons.push("gold");
                }
                else if (randomNumber == 5)
                {
                    icons.push("black");
                }
                else if (randomNumber == 6)
                {
                    icons.push("orange");
                }
                else if (randomNumber == 7)
                {
                    icons.push("violet");
                }
                else
                {
                    icons.push("cyan");
                }

            }

        }

generateIcons(60,4);

console.log(icons);
</code>```

Body:
I have this now:

var generateIcons = function(playtime, players) {
var count = playtime / 2;
icons = [];
for (var i = 1; i <= count; i++) {
    if (i % 8 === 0 && players === 8) {
        icons.push("cyan");
    }
    else if (i % 7 === 0 && players >= 7) {
        icons.push("violet");
    }
    else if (i % 6 === 0 && players >= 6) {
        icons.push("orange");
    }
    else if (i % 5 === 0 && players >= 5) {
        icons.push("black");
    }
    else if (i % 4 === 0 && players >= 4) {
        icons.push("gold");
    }
    else if (i % 3 === 0 && players >= 3) {
        icons.push("red");
    }
    else if (i % 2 === 0 && players >= 2) {
        icons.push("blue");
    }
    else {
        icons.push("green");
    }
}
};

The problem is that, I get much more green than blue for example with: generateIcons(60,4);
How to get ~equal amount of green, blue, red, gold?

Body:
Check If that solution satisfies you :)

var generateIcons = function(playtime, players) {
            var count = playtime / 2;
            icons = [];
            var randomNumber;

            for (var i = 1; i <= count; i++) {
                randomNumber = Math.floor((Math.random() *  players) + 1); //generate random number from <1, players> probability for each color should be ~equal ;)
                if(randomNumber == 1)
                {
                    icons.push("green");
                }
                else if (randomNumber == 2)
                {
                    icons.push("blue");
                }
                else if (randomNumber == 3)
                {
                    icons.push("red");
                }
                else if (randomNumber == 4)
                {
                    icons.push("gold");
                }
                else if (randomNumber == 5)
                {
                    icons.push("black");
                }
                else if (randomNumber == 6)
                {
                    icons.push("orange");
                }
                else if (randomNumber == 7)
                {
                    icons.push("violet");
                }
                else
                {
                    icons.push("cyan");
                }

            }

        }

generateIcons(60,4);

console.log(icons);


问:
How to use hibernate query on two tables (join table)?
I have these tables: cont(id_cont, user, pass)
                      emp(emp_id, name, cont_id_cont (fk))

```<code>@Entity
@Table(name = "emp", catalog = "", uniqueConstraints = {
      @UniqueConstraint(columnNames = "cont_id_cont") })
public class Emp implements java.io.Serializable{
  private int id_emp;
  private ContUser contUser;
  private String name;
</code>```

and

```<code>@Entity
@Table(name = "cont", catalog = "", uniqueConstraints = {
        @UniqueConstraint(columnNames = "pass") })
public class Cont implements java.io.Serializable{

    private int id_cont;
    private String user;
    private String pass;
private Set<Emp> empForCont = new HashSet<Emp>(0);
}
</code>```

Now: I want this query:
select cont.user, emp.name, emp.cont_id_cont from cont
inner join emp on cont.id_cont= emp.cont_id_cont where cont.user = 'gbs04405';

答:
This style of accessing data is not what ORM is intended for. If you are using Hibernate, you should (usually) access data through objects. To make this work, instead of embedding SQL like constraints, define relations @OneToMany, @ManyToOne, and/or @ManyToMany between objects where necessary.

In addition, you should consider using HQL (or JPQL) instead of pure SQL, to achieve what you want.

It should be something like this:

```<code>SELECT e FROM Emp e JOIN e.contUser u WHERE u.user = :userstring
</code>```

You can check here for further JPQL syntax.

Body:
I have these tables: cont(id_cont, user, pass)
                      emp(emp_id, name, cont_id_cont (fk))

@Entity
@Table(name = "emp", catalog = "", uniqueConstraints = {
      @UniqueConstraint(columnNames = "cont_id_cont") })
public class Emp implements java.io.Serializable{
  private int id_emp;
  private ContUser contUser;
  private String name;

and

@Entity
@Table(name = "cont", catalog = "", uniqueConstraints = {
        @UniqueConstraint(columnNames = "pass") })
public class Cont implements java.io.Serializable{

    private int id_cont;
    private String user;
    private String pass;
private Set<Emp> empForCont = new HashSet<Emp>(0);
}

Now: I want this query:
select cont.user, emp.name, emp.cont_id_cont from cont
inner join emp on cont.id_cont= emp.cont_id_cont where cont.user = 'gbs04405';

Body:
This style of accessing data is not what ORM is intended for. If you are using Hibernate, you should (usually) access data through objects. To make this work, instead of embedding SQL like constraints, define relations @OneToMany, @ManyToOne, and/or @ManyToMany between objects where necessary.

In addition, you should consider using HQL (or JPQL) instead of pure SQL, to achieve what you want.

It should be something like this:

SELECT e FROM Emp e JOIN e.contUser u WHERE u.user = :userstring

You can check here for further JPQL syntax.


问:
netty: WARNING: An exceptionCaught() event was fired, and it reached at the tail of the pipeline
I wrote service for my client to deal with multiple client it was working fine but last few days load of clients has been increased and now server code is generating exception and I am failing to understand what is it happening.

My code is:

```<code>    public void run() throws Exception {

    //System.setProperty("org.jboss.netty.epollBugWorkaround", "true");
    EventLoopGroup bossPool = new NioEventLoopGroup(BOSS_THREADS);
    EventLoopGroup workerPool = new NioEventLoopGroup(MAX_WORKER_THREADS);

    try {

        ServerBootstrap boot = new ServerBootstrap();
        boot.group(bossPool, workerPool);
        boot.channel(NioServerSocketChannel.class);
        boot.childHandler(new Pipeline());
        boot.option(ChannelOption.TCP_NODELAY, true);
        boot.option(ChannelOption.SO_KEEPALIVE, true);
        boot.option(ChannelOption.SO_REUSEADDR, true);
        boot.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 6000);
        boot.option(ChannelOption.SO_TIMEOUT, 6);
        boot.option(ChannelOption.SO_BACKLOG, 2048);

        //System.out.println("Server started listening at port : " + port);
        boot.bind(port).sync().channel().closeFuture().sync();

    } catch (InterruptedException e) {
    } finally {
        workerPool.shutdownGracefully();
        bossPool.shutdownGracefully();
    }
}
</code>```

Pipeline code is:

```<code>    public class Pipeline extends ChannelInitializer<Channel> {
    @Override
    protected void initChannel(Channel ch) throws Exception {
        // ch.pipeline().addLast("joiner", new JoinRequest());
        ch.pipeline().addLast("decoder", new ByteArrayDecoder());
        ch.pipeline().addLast("encoder", new StringEncoder());
        ch.pipeline().addLast("myHelper", new RequestHandler());
       }
    }
</code>```

and here is detailed error log I am getting on daily basis:

```<code>1006465:54:21:10-16-03-2017Mar 16, 2017 10:21:54 AM         io.netty.channel.DefaultChannelPipeline$TailContext exceptionCaught
WARNING: An exceptionCaught() event was fired, and it reached at the tail of the pipeline. It usually means the last handler in the pipeline did not handle the exception.
java.io.IOException: Too many open files
    at sun.nio.ch.ServerSocketChannelImpl.accept0(Native Method)
    at sun.nio.ch.ServerSocketChannelImpl.accept(ServerSocketChannelImpl.java:422)
    at sun.nio.ch.ServerSocketChannelImpl.accept(ServerSocketChannelImpl.java:250)
    at io.netty.channel.socket.nio.NioServerSocketChannel.doReadMessages(NioServerSocketChannel.java:135)
    at io.netty.channel.nio.AbstractNioMessageChannel$NioMessageUnsafe.read(AbstractNioMessageChannel.java:69)
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:514)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:471)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:385)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:351)
    at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:116)
    at io.netty.util.internal.chmv8.ForkJoinTask$RunnableExecuteAction.exec(ForkJoinTask.java:1412)
    at io.netty.util.internal.chmv8.ForkJoinTask.doExec(ForkJoinTask.java:280)
    at io.netty.util.internal.chmv8.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:877)
    at io.netty.util.internal.chmv8.ForkJoinPool.scan(ForkJoinPool.java:1706)
    at io.netty.util.internal.chmv8.ForkJoinPool.runWorker(ForkJoinPool.java:1661)
    at io.netty.util.internal.chmv8.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:126)

com.idea.builders.RequestHandler oprationSelector
SEVERE: null
java.io.FileNotFoundException: config.dat (Too many open files)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileInputStream.<init>(FileInputStream.java:93)
    at java.io.FileReader.<init>(FileReader.java:58)
    at com.idea.builders.RequestHandler.oprationSelector(RequestHandler.java:175)
    at com.idea.builders.RequestHandler.messageReceived(RequestHandler.java:97)
    at com.idea.builders.RequestHandler.messageReceived(RequestHandler.java:35)
    at io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:105)
    at io.netty.channel.ChannelHandlerInvokerUtil.invokeChannelReadNow(ChannelHandlerInvokerUtil.java:84)
    at io.netty.channel.DefaultChannelHandlerInvoker.invokeChannelRead(DefaultChannelHandlerInvoker.java:153)
    at io.netty.channel.PausableChannelEventExecutor.invokeChannelRead(PausableChannelEventExecutor.java:86)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:389)
    at io.netty.handler.codec.MessageToMessageDecoder.channelRead(MessageToMessageDecoder.java:103)
    at io.netty.channel.ChannelHandlerInvokerUtil.invokeChannelReadNow(ChannelHandlerInvokerUtil.java:84)
    at io.netty.channel.DefaultChannelHandlerInvoker.invokeChannelRead(DefaultChannelHandlerInvoker.java:153)
    at io.netty.channel.PausableChannelEventExecutor.invokeChannelRead(PausableChannelEventExecutor.java:86)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:389)
    at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:956)
    at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:127)
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:514)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:471)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:385)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:351)
    at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:116)
    at io.netty.util.internal.chmv8.ForkJoinTask$RunnableExecuteAction.exec(ForkJoinTask.java:1412)
    at io.netty.util.internal.chmv8.ForkJoinTask.doExec(ForkJoinTask.java:280)
    at io.netty.util.internal.chmv8.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:877)
    at io.netty.util.internal.chmv8.ForkJoinPool.scan(ForkJoinPool.java:1706)
    at io.netty.util.internal.chmv8.ForkJoinPool.runWorker(ForkJoinPool.java:1661)
    at io.netty.util.internal.chmv8.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:126)

Mar 16, 2017 10:21:54 AM com.idea.builders.RequestHandler oprationSelector
SEVERE: null
java.io.FileNotFoundException: config.dat (Too many open files)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileInputStream.<init>(FileInputStream.java:93)
    at java.io.FileReader.<init>(FileReader.java:58)
    at com.idea.builders.RequestHandler.oprationSelector(RequestHandler.java:175)
    at com.idea.builders.RequestHandler.messageReceived(RequestHandler.java:97)
    at com.idea.builders.RequestHandler.messageReceived(RequestHandler.java:35)
</code>```

What should I do I have to restart my server on daily basis?

答:
You should override exceptionCaught method in one of your handlers.

The message means that netty caugth exception but you didn't handle it in any of your handlers. Exceptions just reach the last pipeline handler and disappear. You probably should handle it in your request handler.

And yes close all streams after you finish working with files. And also you should release sockets and other resources on exceptions or unregistered events.

Body:
I wrote service for my client to deal with multiple client it was working fine but last few days load of clients has been increased and now server code is generating exception and I am failing to understand what is it happening.

My code is:

    public void run() throws Exception {

    //System.setProperty("org.jboss.netty.epollBugWorkaround", "true");
    EventLoopGroup bossPool = new NioEventLoopGroup(BOSS_THREADS);
    EventLoopGroup workerPool = new NioEventLoopGroup(MAX_WORKER_THREADS);

    try {

        ServerBootstrap boot = new ServerBootstrap();
        boot.group(bossPool, workerPool);
        boot.channel(NioServerSocketChannel.class);
        boot.childHandler(new Pipeline());
        boot.option(ChannelOption.TCP_NODELAY, true);
        boot.option(ChannelOption.SO_KEEPALIVE, true);
        boot.option(ChannelOption.SO_REUSEADDR, true);
        boot.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 6000);
        boot.option(ChannelOption.SO_TIMEOUT, 6);
        boot.option(ChannelOption.SO_BACKLOG, 2048);

        //System.out.println("Server started listening at port : " + port);
        boot.bind(port).sync().channel().closeFuture().sync();

    } catch (InterruptedException e) {
    } finally {
        workerPool.shutdownGracefully();
        bossPool.shutdownGracefully();
    }
}

Pipeline code is:

    public class Pipeline extends ChannelInitializer<Channel> {
    @Override
    protected void initChannel(Channel ch) throws Exception {
        // ch.pipeline().addLast("joiner", new JoinRequest());
        ch.pipeline().addLast("decoder", new ByteArrayDecoder());
        ch.pipeline().addLast("encoder", new StringEncoder());
        ch.pipeline().addLast("myHelper", new RequestHandler());
       }
    }

and here is detailed error log I am getting on daily basis:

1006465:54:21:10-16-03-2017Mar 16, 2017 10:21:54 AM         io.netty.channel.DefaultChannelPipeline$TailContext exceptionCaught
WARNING: An exceptionCaught() event was fired, and it reached at the tail of the pipeline. It usually means the last handler in the pipeline did not handle the exception.
java.io.IOException: Too many open files
    at sun.nio.ch.ServerSocketChannelImpl.accept0(Native Method)
    at sun.nio.ch.ServerSocketChannelImpl.accept(ServerSocketChannelImpl.java:422)
    at sun.nio.ch.ServerSocketChannelImpl.accept(ServerSocketChannelImpl.java:250)
    at io.netty.channel.socket.nio.NioServerSocketChannel.doReadMessages(NioServerSocketChannel.java:135)
    at io.netty.channel.nio.AbstractNioMessageChannel$NioMessageUnsafe.read(AbstractNioMessageChannel.java:69)
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:514)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:471)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:385)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:351)
    at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:116)
    at io.netty.util.internal.chmv8.ForkJoinTask$RunnableExecuteAction.exec(ForkJoinTask.java:1412)
    at io.netty.util.internal.chmv8.ForkJoinTask.doExec(ForkJoinTask.java:280)
    at io.netty.util.internal.chmv8.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:877)
    at io.netty.util.internal.chmv8.ForkJoinPool.scan(ForkJoinPool.java:1706)
    at io.netty.util.internal.chmv8.ForkJoinPool.runWorker(ForkJoinPool.java:1661)
    at io.netty.util.internal.chmv8.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:126)

com.idea.builders.RequestHandler oprationSelector
SEVERE: null
java.io.FileNotFoundException: config.dat (Too many open files)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileInputStream.<init>(FileInputStream.java:93)
    at java.io.FileReader.<init>(FileReader.java:58)
    at com.idea.builders.RequestHandler.oprationSelector(RequestHandler.java:175)
    at com.idea.builders.RequestHandler.messageReceived(RequestHandler.java:97)
    at com.idea.builders.RequestHandler.messageReceived(RequestHandler.java:35)
    at io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:105)
    at io.netty.channel.ChannelHandlerInvokerUtil.invokeChannelReadNow(ChannelHandlerInvokerUtil.java:84)
    at io.netty.channel.DefaultChannelHandlerInvoker.invokeChannelRead(DefaultChannelHandlerInvoker.java:153)
    at io.netty.channel.PausableChannelEventExecutor.invokeChannelRead(PausableChannelEventExecutor.java:86)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:389)
    at io.netty.handler.codec.MessageToMessageDecoder.channelRead(MessageToMessageDecoder.java:103)
    at io.netty.channel.ChannelHandlerInvokerUtil.invokeChannelReadNow(ChannelHandlerInvokerUtil.java:84)
    at io.netty.channel.DefaultChannelHandlerInvoker.invokeChannelRead(DefaultChannelHandlerInvoker.java:153)
    at io.netty.channel.PausableChannelEventExecutor.invokeChannelRead(PausableChannelEventExecutor.java:86)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:389)
    at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:956)
    at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:127)
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:514)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:471)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:385)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:351)
    at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:116)
    at io.netty.util.internal.chmv8.ForkJoinTask$RunnableExecuteAction.exec(ForkJoinTask.java:1412)
    at io.netty.util.internal.chmv8.ForkJoinTask.doExec(ForkJoinTask.java:280)
    at io.netty.util.internal.chmv8.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:877)
    at io.netty.util.internal.chmv8.ForkJoinPool.scan(ForkJoinPool.java:1706)
    at io.netty.util.internal.chmv8.ForkJoinPool.runWorker(ForkJoinPool.java:1661)
    at io.netty.util.internal.chmv8.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:126)

Mar 16, 2017 10:21:54 AM com.idea.builders.RequestHandler oprationSelector
SEVERE: null
java.io.FileNotFoundException: config.dat (Too many open files)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileInputStream.<init>(FileInputStream.java:93)
    at java.io.FileReader.<init>(FileReader.java:58)
    at com.idea.builders.RequestHandler.oprationSelector(RequestHandler.java:175)
    at com.idea.builders.RequestHandler.messageReceived(RequestHandler.java:97)
    at com.idea.builders.RequestHandler.messageReceived(RequestHandler.java:35)

What should I do I have to restart my server on daily basis?


问:
firebase notification not receive from local server
I am developing demo for firebase notification using localhost.

I configure the firebase using android studio and add server key into my php file and I got the Token in my Phpmyadmin(Wamp server) but when I send notification using html file then I can not get a notification.

I am android Developer so I don't know about php api. I think it might be a problem in send_ntification.php file.

But I tested using firebase console it works fine.

Here are my php files

init.php

```<code><?php

$host = "localhost";
$db_user = "root";
$db_password = "";
$db_name = "fcm_db";

$con = mysqli_connect($host,$db_user,$db_password,$db_name);

if($con)
    echo "Connection Success";
else
   echo"Connection Error.....";

?>
</code>```

fcm_insert.php

```<code><?php

require "init.php";
$fcm_token = $_POST["fcm_token"];
$sql = "insert into fcm_info values('".$fcm_token."');";
mysqli_query($con,$sql);
mysqli_close($con)

?>
</code>```

send_notification.php

```<code><?php

include_once("init.php");

$message =$_POST['message'];

$title = $_POST['title'];
$path_to_fcm = "https://fcm.googleapis.com/fcm/send";
$server_key = "MY SERVER KEY";
$sql = "select fcm_token from fcm_info";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_row($result);
$key = $row[0];

$headers = array(
'Authorization:key=' .$server_key,
'Content-Type:application/json'
);

$fields = array('to'=>$key,
                'notification'=>array('title'=>$title,'body'=>$message));

$payload = json_encode($fields);

$curl_session = curl_init();
curl_setopt($curl_session, CURLOPT_URL, $path_to_fcm);
curl_setopt($curl_session, CURLOPT_POST, true);
curl_setopt($curl_session, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_session, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_session, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
curl_setopt($curl_session, CURLOPT_POSTFIELDS, $payload);

$result = curl_exec($curl_session);

curl_close($curl_session);
mysqli_close($con);

?>
</code>```

send_notificatiion.html

```<code><html>

<body>

<form action="send_notification.php" method="post">
<table>
<tr>
<td> Title : </td> <td><input type="text" name="title"/></td>
<tr>

<tr>
<td>Message : <td><td><input type="text" name="message"/></td>
</tr>

<td><input type="submit" value="submit"/></td>
</tr>

</table>

</form>

</body>

</html>
</code>```

HERE IS MY ANDROID CODE

FcmInstenceIdService.java

```<code>public class FcmInstenceIdService extends FirebaseInstanceIdService {

    @Override
    public void onTokenRefresh() {

        String recent_token = FirebaseInstanceId.getInstance().getToken();
        Log.e(TAG, "onTokenRefresh: token = "+recent_token );

        SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(getString(R.string.FCM_PREF), Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(getString(R.string.FCM_TOKEN),recent_token);
        editor.apply();
    }
}
</code>```

FcmMessagingService.java

```<code>public class FcmMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        String title = remoteMessage.getNotification().getTitle();
        String message = remoteMessage.getNotification().getBody();

        Intent intent = new Intent(this,MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setContentTitle(title);
        builder.setContentText(message);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setAutoCancel(true);
        builder.setContentIntent(pendingIntent);
        NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0,builder.build());

        super.onMessageReceived(remoteMessage);
    }
}
</code>```

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {

    SharedPreferences sharedPreferences ;

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

    }

    public void SendTokenToServer(View view) {

        sharedPreferences = getApplicationContext().getSharedPreferences(getString(R.string.FCM_PREF), Context.MODE_PRIVATE);

        Log.i("Notificatioin", "SendTokenToServer: token = "+sharedPreferences.getString(getString(R.string.FCM_TOKEN), ""));
        new GetData().execute();

    }

    public class GetData extends AsyncTask<Void, Void, Void> {

        ProgressDialog progressDialog;
        String responseString;

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

            progressDialog = new ProgressDialog(MainActivity.this);
            progressDialog.setMessage("Please wait....");
            progressDialog.setCancelable(true);
            progressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... voids) {

            sharedPreferences.getString(getString(R.string.FCM_TOKEN), "");

            OkHttpClient client = new OkHttpClient();
            RequestBody formBody = new FormBody.Builder()
                    .add("fcm_token", sharedPreferences.getString(getString(R.string.FCM_TOKEN), ""))
                    .build();
            Request request = new Request.Builder()
//                    .url("http://192.168.1.104/fcmtest/fcm_insert.php")
                    .url("http://192.168.0.102/fcmtest/fcm_insert.php")
                    .post(formBody)
                    .build();

            try {

                Response response = client.newCall(request).execute();
                if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
                {

                    responseString = response.body().string();
                    System.out.println(responseString);
                    response.body().close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            progressDialog.dismiss();

        }
    }

}
</code>```

androidmanifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.production.hometech.fcmdemo">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name=".FcmInstenceIdService"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>

        <service android:name=".FcmMessagingService"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>

    </application>

</manifest>
</code>```

I don't understand where is the problem please help me. Any help will much appreciated.  I spent my 3 hours for finding the solution.

答:
Well, I faced the same issue with FCM because of little bit misunderstanding between Server key and Legacy server key.

For FCM always use Server key. By mistake we generally takes Legacy server key because of its length; we were using that short web API key in GCM.

You need to use your Sender ID with your back-end system in order to send push notification; we never used Sender ID in back-end for GCM.

Follow these two steps, hope you would receive push notification from FCM.

Body:
I am developing demo for firebase notification using localhost.

I configure the firebase using android studio and add server key into my php file and I got the Token in my Phpmyadmin(Wamp server) but when I send notification using html file then I can not get a notification.

I am android Developer so I don't know about php api. I think it might be a problem in send_ntification.php file.

But I tested using firebase console it works fine.

Here are my php files

init.php

<?php

$host = "localhost";
$db_user = "root";
$db_password = "";
$db_name = "fcm_db";

$con = mysqli_connect($host,$db_user,$db_password,$db_name);

if($con)
    echo "Connection Success";
else
   echo"Connection Error.....";

?>

fcm_insert.php

<?php

require "init.php";
$fcm_token = $_POST["fcm_token"];
$sql = "insert into fcm_info values('".$fcm_token."');";
mysqli_query($con,$sql);
mysqli_close($con)

?>

send_notification.php

<?php

include_once("init.php");

$message =$_POST['message'];

$title = $_POST['title'];
$path_to_fcm = "https://fcm.googleapis.com/fcm/send";
$server_key = "MY SERVER KEY";
$sql = "select fcm_token from fcm_info";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_row($result);
$key = $row[0];

$headers = array(
'Authorization:key=' .$server_key,
'Content-Type:application/json'
);

$fields = array('to'=>$key,
                'notification'=>array('title'=>$title,'body'=>$message));

$payload = json_encode($fields);

$curl_session = curl_init();
curl_setopt($curl_session, CURLOPT_URL, $path_to_fcm);
curl_setopt($curl_session, CURLOPT_POST, true);
curl_setopt($curl_session, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_session, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_session, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
curl_setopt($curl_session, CURLOPT_POSTFIELDS, $payload);

$result = curl_exec($curl_session);

curl_close($curl_session);
mysqli_close($con);

?>

send_notificatiion.html

<form action="send_notification.php" method="post">

 Title : 	 <input type="text" name="title"/>

Message : <input type="text" name="message"/>

<input type="submit" value="submit"/>

</form>

HERE IS MY ANDROID CODE

FcmInstenceIdService.java

public class FcmInstenceIdService extends FirebaseInstanceIdService {

    @Override
    public void onTokenRefresh() {

        String recent_token = FirebaseInstanceId.getInstance().getToken();
        Log.e(TAG, "onTokenRefresh: token = "+recent_token );

        SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(getString(R.string.FCM_PREF), Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(getString(R.string.FCM_TOKEN),recent_token);
        editor.apply();
    }
}

FcmMessagingService.java

public class FcmMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        String title = remoteMessage.getNotification().getTitle();
        String message = remoteMessage.getNotification().getBody();

        Intent intent = new Intent(this,MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setContentTitle(title);
        builder.setContentText(message);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setAutoCancel(true);
        builder.setContentIntent(pendingIntent);
        NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0,builder.build());

        super.onMessageReceived(remoteMessage);
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {

    SharedPreferences sharedPreferences ;

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

    }

    public void SendTokenToServer(View view) {

        sharedPreferences = getApplicationContext().getSharedPreferences(getString(R.string.FCM_PREF), Context.MODE_PRIVATE);

        Log.i("Notificatioin", "SendTokenToServer: token = "+sharedPreferences.getString(getString(R.string.FCM_TOKEN), ""));
        new GetData().execute();

    }

    public class GetData extends AsyncTask<Void, Void, Void> {

        ProgressDialog progressDialog;
        String responseString;

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

            progressDialog = new ProgressDialog(MainActivity.this);
            progressDialog.setMessage("Please wait....");
            progressDialog.setCancelable(true);
            progressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... voids) {

            sharedPreferences.getString(getString(R.string.FCM_TOKEN), "");

            OkHttpClient client = new OkHttpClient();
            RequestBody formBody = new FormBody.Builder()
                    .add("fcm_token", sharedPreferences.getString(getString(R.string.FCM_TOKEN), ""))
                    .build();
            Request request = new Request.Builder()
//                    .url("http://192.168.1.104/fcmtest/fcm_insert.php")
                    .url("http://192.168.0.102/fcmtest/fcm_insert.php")
                    .post(formBody)
                    .build();

            try {

                Response response = client.newCall(request).execute();
                if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
                {

                    responseString = response.body().string();
                    System.out.println(responseString);
                    response.body().close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            progressDialog.dismiss();

        }
    }

}

androidmanifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.production.hometech.fcmdemo">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name=".FcmInstenceIdService"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>

        <service android:name=".FcmMessagingService"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>

    </application>

</manifest>

I don't understand where is the problem please help me. Any help will much appreciated.  I spent my 3 hours for finding the solution.


问:
BLAS library incompatible with Fortran 77 compiler settings
I'm trying to install Octave-3.6.2 from source on Ubuntu 12.04 with KDE desktop but when I run the Octave configure script I get this error

```<code>BLAS library was detected but found incompatible with your Fortran 77
compiler settings
</code>```

I used ./configure F77=gfortran as was suggested by numerous web searches and I've ensured that the alternatives system F77 files are moved out of harms way as per the comments in this SO post. The installed BLAS libraries are those installed by the package manager.

What does the error mean and how do I remedy it?

答:
I was compiling octave-4.0.1 on openSUSE-12.3_x86-64 and met this problem. Before this, the blas lib (libblas3) was already installed. Then I installed the 32bit lib (libblas3-32bit), nothing changed. Then I installed the package named "blas-devel", it's resolved.

That package includes these files:

```<code>/usr/lib64/libblas.a
/usr/lib64/libblas.so
/usr/lib64/libblas_pic.a
</code>```

Body:
I'm trying to install Octave-3.6.2 from source on Ubuntu 12.04 with KDE desktop but when I run the Octave configure script I get this error

BLAS library was detected but found incompatible with your Fortran 77
compiler settings

I used ./configure F77=gfortran as was suggested by numerous web searches and I've ensured that the alternatives system F77 files are moved out of harms way as per the comments in this SO post. The installed BLAS libraries are those installed by the package manager.

What does the error mean and how do I remedy it?

Body:
I was compiling octave-4.0.1 on openSUSE-12.3_x86-64 and met this problem. Before this, the blas lib (libblas3) was already installed. Then I installed the 32bit lib (libblas3-32bit), nothing changed. Then I installed the package named "blas-devel", it's resolved.

That package includes these files:

/usr/lib64/libblas.a
/usr/lib64/libblas.so
/usr/lib64/libblas_pic.a


问:
online stream to my own website
Hello I am looking for solution that lets to stream video from my webcam to others from my own website.I am using node.js for backend, but the closest npm I found was only simple npm that opens users webcam on website, but in my case I want not to open webcam when I enter webpage, but to see my own stream.I thought about using services like twitch or ustream, but what I need simple stream without play/stop, fullscreen options, that those services provide.</p>

答: You can look webRTC to get clear picture of P2P videochat applications. You can find sample app here.</p>

Title: online stream to my own website


问:
Parse one field from nested Json to String Value
i have one field nested JSON in my API response :

```<code>"ratingBest": 10,
"reviewCount": 1,
"coordinate": {
    "latitude": "-7.2768",
    "longitude": "112.7927"
},
...
</code>```

I save above data to Android local DB using ORMLite, but i want just one field coordinate to be String. Cause Gson automatically convert in specific type.

I already try to use a class field type as String. But still not work

Any workaround for that?

Thank you

答:
I'm assuming you're not going to process the latitude/longitude pair in any way, since you made no mentions on it, and your "row" is supposed to be something like:

final class Location {

    final int ratingBest = Integer.valueOf(0);

    final int reviewCount = Integer.valueOf(0);

    @JsonAdapter(PackedCoordinateTypeAdapter.class)
    final String coordinate = null;

}
```

<p>Take a look at the <code>@JsonAdapter</code> annotation that binds a specific type adapter to the field. The type adapter may look like this:</p>

<pre class="lang-java prettyprint-override"><code>final class PackedCoordinateTypeAdapter
        extends TypeAdapter<String> {

    private static final String DELIMITER = " ";
    private static final String LATITUDE = "latitude";
    private static final String LONGITUDE = "longitude";

    private static final Pattern delimiterPattern = compile(DELIMITER);

    // Keep private stuff private as much possible, Gson can access it
    private PackedCoordinateTypeAdapter() {
    }

    @Override
    @SuppressWarnings("resource")
    public void write(final JsonWriter out, final String packedLatitudeLongitude)
            throws IOException {
        final String[] split = decode(packedLatitudeLongitude);
        out.beginObject();
        out.name(LATITUDE);
        out.value(split[0]);
        out.name(LONGITUDE);
        out.value(split[1]);
        out.endObject();
    }

    @Override
    public String read(final JsonReader in)
            throws IOException {
        String latitude = null;
        String longitude = null;
        in.beginObject();
        while ( in.hasNext() ) {
            final String name = in.nextName();
            switch ( name ) {
            case LATITUDE:
                latitude = in.nextString();
                break;
            case LONGITUDE:
                longitude = in.nextString();
                break;
            default:
                throw new MalformedJsonException("Unexpected: " + name);
            }
        }
        in.endObject();
        return encode(latitude, longitude);
    }

    private static String encode(final String latitude, final String longitude)
            throws MalformedJsonException {
        if ( latitude == null ) {
            throw new MalformedJsonException("latitude not set");
        }
        if ( longitude == null ) {
            throw new MalformedJsonException("longitude not set");
        }
        return latitude + DELIMITER + longitude;
    }

    private static String[] decode(final String packedLatitudeLongitude)
            throws IllegalArgumentException {
        final String[] split = delimiterPattern.split(packedLatitudeLongitude);
        if ( split.length != 2 ) {
            throw new IllegalArgumentException("Cannot parse: " + packedLatitudeLongitude);
        }
        return split;
    }

}
</code>```

Demo:

final Location response = gson.fromJson("{\"ratingBest\":10,\"reviewCount\":1,\"coordinate\":{\"latitude\":\"-7.2768\",\"longitude\":\"112.7927\"}}", Location.class);
System.out.println(response.coordinate);
System.out.println(gson.toJson(response));
```

Output:

-7.2768 112.7927

  {"ratingBest":10,"reviewCount":1,"coordinate":{"latitude":"-7.2768","longitude":"112.7927"}}

Body:
i have one field nested JSON in my API response :

"ratingBest": 10,
"reviewCount": 1,
"coordinate": {
    "latitude": "-7.2768",
    "longitude": "112.7927"
},
...

I save above data to Android local DB using ORMLite, but i want just one field coordinate to be String. Cause Gson automatically convert in specific type.

I already try to use a class field type as String. But still not work

Any workaround for that?

Thank you

Body:
I'm assuming you're not going to process the latitude/longitude pair in any way, since you made no mentions on it, and your "row" is supposed to be something like:

final class Location {

    final int ratingBest = Integer.valueOf(0);

    final int reviewCount = Integer.valueOf(0);

    @JsonAdapter(PackedCoordinateTypeAdapter.class)
    final String coordinate = null;

}

Take a look at the @JsonAdapter annotation that binds a specific type adapter to the field. The type adapter may look like this:

final class PackedCoordinateTypeAdapter
        extends TypeAdapter<String> {

    private static final String DELIMITER = " ";
    private static final String LATITUDE = "latitude";
    private static final String LONGITUDE = "longitude";

    private static final Pattern delimiterPattern = compile(DELIMITER);

    // Keep private stuff private as much possible, Gson can access it
    private PackedCoordinateTypeAdapter() {
    }

    @Override
    @SuppressWarnings("resource")
    public void write(final JsonWriter out, final String packedLatitudeLongitude)
            throws IOException {
        final String[] split = decode(packedLatitudeLongitude);
        out.beginObject();
        out.name(LATITUDE);
        out.value(split[0]);
        out.name(LONGITUDE);
        out.value(split[1]);
        out.endObject();
    }

    @Override
    public String read(final JsonReader in)
            throws IOException {
        String latitude = null;
        String longitude = null;
        in.beginObject();
        while ( in.hasNext() ) {
            final String name = in.nextName();
            switch ( name ) {
            case LATITUDE:
                latitude = in.nextString();
                break;
            case LONGITUDE:
                longitude = in.nextString();
                break;
            default:
                throw new MalformedJsonException("Unexpected: " + name);
            }
        }
        in.endObject();
        return encode(latitude, longitude);
    }

    private static String encode(final String latitude, final String longitude)
            throws MalformedJsonException {
        if ( latitude == null ) {
            throw new MalformedJsonException("latitude not set");
        }
        if ( longitude == null ) {
            throw new MalformedJsonException("longitude not set");
        }
        return latitude + DELIMITER + longitude;
    }

    private static String[] decode(final String packedLatitudeLongitude)
            throws IllegalArgumentException {
        final String[] split = delimiterPattern.split(packedLatitudeLongitude);
        if ( split.length != 2 ) {
            throw new IllegalArgumentException("Cannot parse: " + packedLatitudeLongitude);
        }
        return split;
    }

}

Demo:

final Location response = gson.fromJson("{\"ratingBest\":10,\"reviewCount\":1,\"coordinate\":{\"latitude\":\"-7.2768\",\"longitude\":\"112.7927\"}}", Location.class);
System.out.println(response.coordinate);
System.out.println(gson.toJson(response));

Output:

-7.2768 112.7927

  {"ratingBest":10,"reviewCount":1,"coordinate":{"latitude":"-7.2768","longitude":"112.7927"}}


问:
In Rust, what exactly are mutable and immutable borrows?
I'm stuck with the Rust concepts of borrowing and mutable:

```<code>#[derive(Debug)]
struct Rectangle {
    height: u32,
    width: u32,
}

fn mut_area(rect_mut: &mut Rectangle) -> u32 {
    rect_mut.width /= 2;
    rect_mut.height * rect_mut.width
}

fn mut_string(s: &mut String) -> &str {
    s.push_str("!");
    let len = s.len();
    &s[0..len / 2]
}

fn main() {
    let mut rect = Rectangle {
        height: 50,
        width: 40,
    };
    println!("original rect: {:?}", rect);
    let a = mut_area(&mut rect);
    println!("area of rect: {}", a);
    println!("now rect: {:?}", rect);

    let mut s = String::from("helloworld");
    println!("original s: {}", s);
    let half = mut_string(&mut s);
    println!("half of the modified string: {}", half);
    println!("modified s: {}", s);
}
</code>```

When I tried to compile it, the compiler told me:

error[E0502]: cannot borrow `s` as immutable because it is also borrowed as mutable
  --> <anon>:32:32
   |
30 |     let half = mut_string(&mut s);
   |                                - mutable borrow occurs here
31 |     println!("half of the modified string: {}", half);
32 |     println!("modified s: {}", s);
   |                                ^ immutable borrow occurs here
33 | }
   | - mutable borrow ends here
```

I know there's a rule about mutable reference:

you can only have one mutable reference to a particular piece of data in a particular scope.

But why can rect be borrowed but s cannot be? And how do I achieve what I want here - to print the modified string after the function call?

答:
The reason why you can print a after calling a function with a mutable reference to rect is that it returns a u32 which is Copyable - there is no need to restrict further uses of rect because it is no longer borrowed after mut_area is called.

Your mut_string, on the other hand, returns a reference to its argument, so the mutable borrow remains in force as long as half is in scope. That's why you may not borrow s immutably for the purpose of println!().

In order to achieve what you are after I would mutate s outside of the mut_string function (a slightly different name would be a good idea now) so there is no mutable borrow in force - its argument can be borrowed immutably instead:

```<code>fn mut_string(s: &str) -> &str {
    let len = s.len();
    &s[0..len / 2]
}

fn main() {
    let mut rect = Rectangle {
        height: 50,
        width: 40,
    };
    println!("original rect: {:?}", rect);
    let a = mut_area(&mut rect); // rect's mutable borrow expires after this assignment
    println!("area of rect: {}", a);
    println!("now rect: {:?}", rect);

    let mut s = String::from("helloworld");
    println!("original s: {}", s);
    s.push_str("!"); // s is mutated here
    let half = mut_string(&s); // s is borrowed immutably
    println!("half of the modified string: {}", half);
    println!("modified s: {}", s); // another immutable borrow of s
}
</code>```

Body:
I'm stuck with the Rust concepts of borrowing and mutable:

#[derive(Debug)]
struct Rectangle {
    height: u32,
    width: u32,
}

fn mut_area(rect_mut: &mut Rectangle) -> u32 {
    rect_mut.width /= 2;
    rect_mut.height * rect_mut.width
}

fn mut_string(s: &mut String) -> &str {
    s.push_str("!");
    let len = s.len();
    &s[0..len / 2]
}

fn main() {
    let mut rect = Rectangle {
        height: 50,
        width: 40,
    };
    println!("original rect: {:?}", rect);
    let a = mut_area(&mut rect);
    println!("area of rect: {}", a);
    println!("now rect: {:?}", rect);

    let mut s = String::from("helloworld");
    println!("original s: {}", s);
    let half = mut_string(&mut s);
    println!("half of the modified string: {}", half);
    println!("modified s: {}", s);
}

When I tried to compile it, the compiler told me:

error[E0502]: cannot borrow `s` as immutable because it is also borrowed as mutable
  --> <anon>:32:32
   |
30 |     let half = mut_string(&mut s);
   |                                - mutable borrow occurs here
31 |     println!("half of the modified string: {}", half);
32 |     println!("modified s: {}", s);
   |                                ^ immutable borrow occurs here
33 | }
   | - mutable borrow ends here

I know there's a rule about mutable reference:

you can only have one mutable reference to a particular piece of data in a particular scope.

But why can rect be borrowed but s cannot be? And how do I achieve what I want here - to print the modified string after the function call?

Body:
The reason why you can print a after calling a function with a mutable reference to rect is that it returns a u32 which is Copyable - there is no need to restrict further uses of rect because it is no longer borrowed after mut_area is called.

Your mut_string, on the other hand, returns a reference to its argument, so the mutable borrow remains in force as long as half is in scope. That's why you may not borrow s immutably for the purpose of println!().

In order to achieve what you are after I would mutate s outside of the mut_string function (a slightly different name would be a good idea now) so there is no mutable borrow in force - its argument can be borrowed immutably instead:

fn mut_string(s: &str) -> &str {
    let len = s.len();
    &s[0..len / 2]
}

fn main() {
    let mut rect = Rectangle {
        height: 50,
        width: 40,
    };
    println!("original rect: {:?}", rect);
    let a = mut_area(&mut rect); // rect's mutable borrow expires after this assignment
    println!("area of rect: {}", a);
    println!("now rect: {:?}", rect);

    let mut s = String::from("helloworld");
    println!("original s: {}", s);
    s.push_str("!"); // s is mutated here
    let half = mut_string(&s); // s is borrowed immutably
    println!("half of the modified string: {}", half);
    println!("modified s: {}", s); // another immutable borrow of s
}