问:
Laravel Passport - Guest Token
Let's assume there is an application with 10 dynamic pages (probably forms) out of which, 8 pages are restricted (requires user to login in application) and 2 pages are available for anonymous users.

My front end application is in Angular 2 and back-end API is developed in Laravel 5.4. I'm more fascinated towards JWT tokens and found that, laravel has in-built support through passport.

Questions:

I can easily use password grant tokens for those 8 restricted page. But how do I give guest token to my Angular app for accessing those 2 pages

How can I restrict guest user for accessing API features of 8 restricted page. (Or how do I check if visited user is guest or logged in user at API end)

Note: I cannot use Personal Access Tokens as it will allow my app to
  use any restricted API feature.

答:
I've used JWT approach here. In my case, I created JWT token from my API. For those who wants to use JWT feature, they can take a look at this package. I added new payload called "Guest" and assigned boolean value to it. In my database, I added new user (called anonymous user) and stored the id of it in my laravel configuration.

Next, I created new middleware VerifyJwtToken, which validates the user, extracts it's payload (with base64_decode) and identify if it is guest. Now all of my Laravel routes are inside this middleware.

Next, I stored this token in laravel session as well as localStorage (for accessing it through angular).

Now, I can easily access this token from localStorage. In the Angular end i used Angular2Jwt package which helps extracting the token and identifying if it is guest or logged in user. I also created HTTP Interceptor in Angular 4 which adds JWT token as header in every API requests.

Title: Laravel Passport - Guest Token


来源: stackexchange

问:
My UIStackView Frames is getting stacked on each other
i have created a UIStackview file that set up some frames with Stackview. in those frames i have defined 2 levels with each its StackView frame view

```<code>    class Stages: UIStackView {
    override init(frame: CGRect) {
    super.init(frame: frame)
    SetupImages()
    SetUpStageOne()
    if scorenum == 1 {
        SetupImages()
        SetUpStageTwo()
    }
}

required init(coder: NSCoder) {
    super.init(coder: coder)
    SetupImages()
    SetUpStageOne()
    if scorenum == 1 {
        SetupImages()
        SetUpStageTwo()
    }

}
</code>```

}

if the score is equal to == 1
i want the frame of SetUpStageTwo() to update

the problem however is that the frame of SetUpStageOne() is getting stacked up on top ofSetUpStageOne()

答:
i have found a solution for this question. turns out i needed to delete my arrays before reuse them again by

removefromsuperview(array)

if anyone have a better idea or some improvement to the code above, please post ahead

ContentLicense: CC BY-SA 3.0

Body:
i have created a UIStackview file that set up some frames with Stackview. in those frames i have defined 2 levels with each its StackView frame view

    class Stages: UIStackView {
    override init(frame: CGRect) {
    super.init(frame: frame)
    SetupImages()
    SetUpStageOne()
    if scorenum == 1 {
        SetupImages()
        SetUpStageTwo()
    }
}

required init(coder: NSCoder) {
    super.init(coder: coder)
    SetupImages()
    SetUpStageOne()
    if scorenum == 1 {
        SetupImages()
        SetUpStageTwo()
    }

}

}

if the score is equal to == 1
i want the frame of SetUpStageTwo() to update

the problem however is that the frame of SetUpStageOne() is getting stacked up on top ofSetUpStageOne()


问:
Operations in php variables
I have the following code;

```<code>$sel_referrals1="SELECT SUM(amount) as da_sum
  FROM topup WHERE user_id IN ( SELECT t1.referree
  FROM referrals AS t1
  LEFT JOIN referrals AS t2 ON t2.referrer = t1.referree
  LEFT JOIN referrals AS t3 ON t3.referrer = t2.referree
  LEFT JOIN referrals AS t4 ON t4.referrer = t3.referree
  LEFT JOIN referrals AS t5 ON t5.referrer = t4.referree
  LEFT JOIN referrals AS t6 ON t6.referrer = t5.referree
  LEFT JOIN referrals AS t7 ON t7.referrer = t6.referree
  LEFT JOIN referrals AS t8 ON t8.referrer = t7.referree
  LEFT JOIN referrals AS t9 ON t9.referrer = t8.referree
  LEFT JOIN referrals AS t10 ON t10.referrer = t9.referree
  LEFT JOIN referrals AS t11 ON t11.referrer = t10.referree
WHERE t1.referrer = '{$_SESSION['user']}')
AND YEAR(date_time) = YEAR(CURRENT_DATE())
AND MONTH(date_time) = MONTH(CURRENT_DATE())";

$selected1=mysqli_query($conn,$sel_referrals1);
$sel_level1_array=mysqli_fetch_row($selected1);
$level1=number_format($sel_level1_array[0],2);

$curYear = date('Y');
$curMonth = date('F');
$rate1 = 0.02;
$rate2 = 0.008;
$rate3 = 0.004;
$level11 = 1260.00;
$total=$level1 * $rate1;

echo $total;
</code>```

$level1 returns 1260.00

I have another variable $rate1 which i declared as $rate1=0.02

I need to multiply $level1 with $rate1. When I do $level1*$rate1 I get 0.02,

My expected result is 25.02. What am I doing wrongly?

答:
number_format returns a string

```<code>$level1=number_format($sel_level1_array[0],2);
</code>```

Use floatval

```<code>$level1 = floatval($sel_level1_array[0]);
</code>```

Title: Operations in php variables

Body:
I have the following code;

$sel_referrals1="SELECT SUM(amount) as da_sum
  FROM topup WHERE user_id IN ( SELECT t1.referree
  FROM referrals AS t1
  LEFT JOIN referrals AS t2 ON t2.referrer = t1.referree
  LEFT JOIN referrals AS t3 ON t3.referrer = t2.referree
  LEFT JOIN referrals AS t4 ON t4.referrer = t3.referree
  LEFT JOIN referrals AS t5 ON t5.referrer = t4.referree
  LEFT JOIN referrals AS t6 ON t6.referrer = t5.referree
  LEFT JOIN referrals AS t7 ON t7.referrer = t6.referree
  LEFT JOIN referrals AS t8 ON t8.referrer = t7.referree
  LEFT JOIN referrals AS t9 ON t9.referrer = t8.referree
  LEFT JOIN referrals AS t10 ON t10.referrer = t9.referree
  LEFT JOIN referrals AS t11 ON t11.referrer = t10.referree
WHERE t1.referrer = '{$_SESSION['user']}')
AND YEAR(date_time) = YEAR(CURRENT_DATE())
AND MONTH(date_time) = MONTH(CURRENT_DATE())";

$selected1=mysqli_query($conn,$sel_referrals1);
$sel_level1_array=mysqli_fetch_row($selected1);
$level1=number_format($sel_level1_array[0],2);

$curYear = date('Y');
$curMonth = date('F');
$rate1 = 0.02;
$rate2 = 0.008;
$rate3 = 0.004;
$level11 = 1260.00;
$total=$level1 * $rate1;

echo $total;

$level1 returns 1260.00

I have another variable $rate1 which i declared as $rate1=0.02

I need to multiply $level1 with $rate1. When I do $level1*$rate1 I get 0.02,

My expected result is 25.02. What am I doing wrongly?

Body:
number_format returns a string

$level1=number_format($sel_level1_array[0],2);

Use floatval

$level1 = floatval($sel_level1_array[0]);


问:
With HTML5 canvas, how to calculate the final point coordinates with an offset?
On a HTML5 canvas object, I have to subtract a distance from a destination point, to give the final destination on the same line.

So, first I have calculated the distance between the source and target points, with the Pythagorean theorem, but my memories of Thales's theorem are too faulty to find the final point (on same line), with the right x and y attributes.

```<code>function getDistance (from, to){
    return Math.hypot(to.x - from.x, to.y - from.y);
}
function getFinalTo (from, to, distanceToSubstract){

    //with Pythagore we obtain the distance between the 2 points
    var originalDistance = getDistance(from, to);
    var finalDistance = originalDistance - distanceToSubstract;

    //Now, I was thinking about Thales but all my tries are wrong
    //Here some of ones, I need to get finalTo properties to draw an arrow to a node without

    var finalTo = new Object;
    finalTo.x = ((1 - finalDistance) * from.x) + (finalDistance * to.x);
    finalTo.y = ((1 - finalDistance) * from.y) + (finalDistance * to.y);

    return finalTo;
}
</code>```

Indeed, the arrowhead be hidden by the round node that can be about 100 pixels of radius, so I try to get the final point.

Thanks a lot.
Regards,

答:
Will depend on the line cap. For "butt" there is no change, for "round" and "square" you the line extends by half the width at each end

The following function shortens the line to fit depending on the line cap.

```<code>drawLine(x1,y1,x2,y2){
    // get vector from start to end
    var x = x2-x1;
    var y = y2-y1;
    // get length
    const len = Math.hypot(x,y) * 2;  // *2 because we want half the width
    // normalise vector
    x /= len;
    y /= len;
    if(ctx.lineCap !== "butt"){
        // shorten both ends to fit the length
        const lw = ctx.lineWidth;
        x1 += x * lw;
        y1 += y * lw;
        x2 -= x * lw;
        y2 -= y * lw;
    }
    ctx.beginPath()
    ctx.lineTo(x1,y1);
    ctx.lineTo(x2,y2);
    ctx.stroke();
 }
</code>```

For miter joins the following answer will help https://stackoverflow.com/a/41184052/3877726

Body:
On a HTML5 canvas object, I have to subtract a distance from a destination point, to give the final destination on the same line.

So, first I have calculated the distance between the source and target points, with the Pythagorean theorem, but my memories of Thales's theorem are too faulty to find the final point (on same line), with the right x and y attributes.

function getDistance (from, to){
    return Math.hypot(to.x - from.x, to.y - from.y);
}
function getFinalTo (from, to, distanceToSubstract){

    //with Pythagore we obtain the distance between the 2 points
    var originalDistance = getDistance(from, to);
    var finalDistance = originalDistance - distanceToSubstract;

    //Now, I was thinking about Thales but all my tries are wrong
    //Here some of ones, I need to get finalTo properties to draw an arrow to a node without

    var finalTo = new Object;
    finalTo.x = ((1 - finalDistance) * from.x) + (finalDistance * to.x);
    finalTo.y = ((1 - finalDistance) * from.y) + (finalDistance * to.y);

    return finalTo;
}

Indeed, the arrowhead be hidden by the round node that can be about 100 pixels of radius, so I try to get the final point.

Thanks a lot.
Regards,

Body:
Will depend on the line cap. For "butt" there is no change, for "round" and "square" you the line extends by half the width at each end

The following function shortens the line to fit depending on the line cap.

drawLine(x1,y1,x2,y2){
    // get vector from start to end
    var x = x2-x1;
    var y = y2-y1;
    // get length
    const len = Math.hypot(x,y) * 2;  // *2 because we want half the width
    // normalise vector
    x /= len;
    y /= len;
    if(ctx.lineCap !== "butt"){
        // shorten both ends to fit the length
        const lw = ctx.lineWidth;
        x1 += x * lw;
        y1 += y * lw;
        x2 -= x * lw;
        y2 -= y * lw;
    }
    ctx.beginPath()
    ctx.lineTo(x1,y1);
    ctx.lineTo(x2,y2);
    ctx.stroke();
 }

For miter joins the following answer will help https://stackoverflow.com/a/41184052/3877726


问:
Updating hash table values in a 'foreach' loop in PowerShell
I'm trying to loop through a hash table and set the value of each key to 5 and PowerShell gives an error:

```<code>$myHash = @{}
$myHash["a"] = 1
$myHash["b"] = 2
$myHash["c"] = 3

foreach($key in $myHash.keys){
    $myHash[$key] = 5
}
</code>```

An error occurred while enumerating through a collection:

```<code>Collection was modified; enumeration operation may not execute..
At line:1 char:8
+ foreach <<<< ($key in $myHash.keys){
    + CategoryInfo          : InvalidOperation: (System.Collecti...tableEnumer
   ator:HashtableEnumerator) [], RuntimeException
    + FullyQualifiedErrorId : BadEnumeration
</code>```

What gives and how do I resolve this problem?

答:
You do not need to clone the whole hashtable for this example. Just enumerating the key collection by forcing it to an array @(...) is enough:

```<code>foreach($key in @($myHash.keys)) {...
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to loop through a hash table and set the value of each key to 5 and PowerShell gives an error:

$myHash = @{}
$myHash["a"] = 1
$myHash["b"] = 2
$myHash["c"] = 3

foreach($key in $myHash.keys){
    $myHash[$key] = 5
}

An error occurred while enumerating through a collection:

Collection was modified; enumeration operation may not execute..
At line:1 char:8
+ foreach <<<< ($key in $myHash.keys){
    + CategoryInfo          : InvalidOperation: (System.Collecti...tableEnumer
   ator:HashtableEnumerator) [], RuntimeException
    + FullyQualifiedErrorId : BadEnumeration

What gives and how do I resolve this problem?

Body:
You do not need to clone the whole hashtable for this example. Just enumerating the key collection by forcing it to an array @(...) is enough:

foreach($key in @($myHash.keys)) {...


问:
How to save and get data in other components using Angular
I am using JSON object in all components. Is there any global declaration and reuse JSON object in Angular?

Otherwise same object we will load in all components?

Where should I declare that object and how can I call it in other components?

I am maintaining onload functions in  HomePage components and I am using in home.html.

I am maintaining the WebserviceProvider for getting values.

But where will I declare and store JSON object and how to re-use other components?

答:
I have created AppCommonService and i have used saveCateogry in home.ts and i have used retrieveCategory in my other component. Below code working fine for me.

```<code>import { Injectable } from '@angular/core';
</code>```

@Injectable()
export class AppCommonService {

```<code>categoryType : any[] = [];
constructor() {

}
saveCateogry(cat:any){
    this.categoryType= cat;
}
retrieveCategory(){
    return this.categoryType;
}
</code>```

}

Body:
I have created AppCommonService and i have used saveCateogry in home.ts and i have used retrieveCategory in my other component. Below code working fine for me.

import { Injectable } from '@angular/core';

@Injectable()
export class AppCommonService {

categoryType : any[] = [];
constructor() {

}
saveCateogry(cat:any){
    this.categoryType= cat;
}
retrieveCategory(){
    return this.categoryType;
}

}


问:
How to loop through all the elements returned from getElementsByTagName
I am trying to loop through all the elements retruned from getElementsByTagName("input") using forEach. Any ideas why this does not work in FF, Chrome or IE?

```<code><html>
    <head>
    </head>
    <body>
        <input type="text" value="" />
        <input type="text" value="" />
        <script>
            function ShowResults(value, index, ar) {
                alert(index);
            }
            var input = document.getElementsByTagName("input");
            alert(input.length);
            input.forEach(ShowResults);
    </script>
    </body>
</html>
</code>```

答:
The reason, this does not work is because 'getElementsByTagName' returns an array - like Object rather than an actual array. In case you are not aware, here's how both of them look like :-

```<code>var realArray = ['a', 'b', 'c'];
var arrayLike = {
  0: 'a',
  1: 'b',
  2: 'c',
  length: 3
};
</code>```

Thus, since Array-like objects inherit from 'Object.prototype' instead of 'Array.prototype', this means that Array-like Objects can't access common Array prototype methods like forEach(), push(), map(), filter(), and slice().

Hope that helps!

Body:
I am trying to loop through all the elements retruned from getElementsByTagName("input") using forEach. Any ideas why this does not work in FF, Chrome or IE?

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

Body:
The reason, this does not work is because 'getElementsByTagName' returns an array - like Object rather than an actual array. In case you are not aware, here's how both of them look like :-

var realArray = ['a', 'b', 'c'];
var arrayLike = {
  0: 'a',
  1: 'b',
  2: 'c',
  length: 3
};

Thus, since Array-like objects inherit from 'Object.prototype' instead of 'Array.prototype', this means that Array-like Objects can't access common Array prototype methods like forEach(), push(), map(), filter(), and slice().

Hope that helps!


问:
RecyclerView not shown
I used techniques given in other answers like downgrading the versions of dependencies to 24... and 25.0.1.Did not work.I have width and height of RecyclerView as match_parent.
Following is the code.I am using RecyclerView for post title and post description in a blog app:

```<code>package com.awani.pocketblog;

import android.content.ClipData;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import org.w3c.dom.Text;

public class MainActivity extends AppCompatActivity {

private RecyclerView mBlogList;
private DatabaseReference mDatabase;

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

    mBlogList = (RecyclerView) findViewById(R.id.blog_list);
    mBlogList.setHasFixedSize(true);
    mBlogList.setLayoutManager(new LinearLayoutManager(this));
    mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
}

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

    FirebaseRecyclerAdapter<Blog,BlogViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>( Blog.class,
            R.layout.blog_row,
            BlogViewHolder.class,
            mDatabase

    ) {
        @Override
        protected void populateViewHolder(BlogViewHolder viewHolder, Blog model, int position) {
            viewHolder.setTitle(model.getTitle());//model means Blog class over here
            viewHolder.setDesc(model.getDesc());

        }
    };

    mBlogList.setAdapter(firebaseRecyclerAdapter);
}

//holder for the recyclerView
public static class BlogViewHolder extends RecyclerView.ViewHolder{

    View mView;

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

        mView = itemView;
    }

    public void setTitle(String title){

        TextView post_title = (TextView) mView.findViewById(R.id.post_title);
        post_title.setText(title);

    }

    public void setDesc(String desc){

        TextView post_description = (TextView) mView.findViewById(R.id.post_description);
        post_description.setText(desc);
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main_menu,menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(item.getItemId()==R.id.action_add){
        startActivity(new Intent(MainActivity.this,PostActivity.class));
    }

    return super.onOptionsItemSelected(item);
}
}
</code>```

log cat statement which might be causing this..

```<code>07-08 17:22:10.761 23308-23308/com.awani.pocketblog W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
</code>```

this is activity_main.xml code:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.widget.RelativeLayout     xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.awani.pocketblog.MainActivity">

<android.support.v7.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/blog_list">
</android.support.v7.widget.RecyclerView>

</android.widget.RelativeLayout>
</code>```

My android studio version is 2.3.2 and he dependencies are 25.3.1
and firebase dependencies are 10.0.1
firebase ui dependency 1.1.1

答:
Check this out. I am using this code to print saved news
You can check this out for reference
Although I used fragment you can change your code accordingly for Activity.

```<code>import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.example.student.newsapp.R;
import com.firebase.client.Firebase;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class show extends AppCompatActivity {

RecyclerView recyclerView;
FirebaseDatabase firebaseDatabase;
DatabaseReference myRef;
FirebaseAuth firebaseauth;
private FirebaseRecyclerAdapter<show_items, ShowDataViewHolder> mFirebaseAdapter;
private ProgressDialog progressDialog;

public show() {
    // Required empty public constructor
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.rvforbookmarks);
    Firebase.setAndroidContext(this);
    progressDialog = new ProgressDialog(this);
    progressDialog.setMessage("Please wait..");
    progressDialog.show();

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle("Bookmarks");

    firebaseDatabase = FirebaseDatabase.getInstance();

    firebaseauth = FirebaseAuth.getInstance();
    final String userid =firebaseauth.getCurrentUser().getUid();

    // myRef = firebaseDatabase.getReference("User_Details");
    myRef = FirebaseDatabase.getInstance().getReference("User_Details").child(userid);

    recyclerView = (RecyclerView)findViewById(R.id.rv);
    recyclerView.setLayoutManager(new LinearLayoutManager(show.this));

}

//View Holder For Recycler View
public static class ShowDataViewHolder extends RecyclerView.ViewHolder {
    private final TextView image_title  ;
    private final ImageView image_url;
    private TextView imge_des;
    private ImageView btn_delete;
    private TextView nobookmark;

    public ShowDataViewHolder(final View itemView)
    {
        super(itemView);
        image_url = (ImageView) itemView.findViewById(R.id.fetch_image);
        image_title = (TextView) itemView.findViewById(R.id.fetch_image_title);
        imge_des = (TextView) itemView.findViewById(R.id.fetch_description);
        btn_delete = (ImageView) itemView.findViewById(R.id.btn_delete);
        nobookmark = (TextView) itemView.findViewById(R.id.nobookmark);

    }

    private void Image_Title(String title)
    {
        image_title.setText(title);
    }

    private void Image_URL(String title)
    {
        // image_url.setImageResource(R.drawable.loading);
        Glide.with(itemView.getContext())
                .load(title)
                .crossFade()
                .placeholder(R.drawable.loading)
                .thumbnail(0.1f)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(image_url);
    }

    public void Image_Des(String title) {
        imge_des.setText(title);

    }
}

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

    mFirebaseAdapter = new FirebaseRecyclerAdapter<show_items, ShowDataViewHolder>(show_items.class, R.layout.showbookamrks, ShowDataViewHolder.class, myRef) {
        public void populateViewHolder(final ShowDataViewHolder viewHolder, show_items model, final int position) {
            viewHolder.Image_URL(model.getImage_URL());
            viewHolder.Image_Title(model.getImage_Title());
            viewHolder.Image_Des(model.getImage_des());

            //OnClick Item
            viewHolder.btn_delete.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(final View v) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(show.this);
                    builder.setMessage("Do you want to Delete this data ?").setCancelable(false)
                            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    int selectedItems = position;
                                    mFirebaseAdapter.getRef(selectedItems).removeValue();
                                    mFirebaseAdapter.notifyItemRemoved(selectedItems);
                                    recyclerView.invalidate();
                                    onStart();
                                }
                            })
                            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.cancel();
                                }
                            });
                    AlertDialog dialog = builder.create();
                    dialog.setTitle("Confirm");
                    dialog.show();
                }
            });

                progressDialog.dismiss();
        }

    };

    recyclerView.setAdapter(mFirebaseAdapter);

}

}
</code>```

Hope it helps
Thankyou

Title: RecyclerView not shown

Body:
I used techniques given in other answers like downgrading the versions of dependencies to 24... and 25.0.1.Did not work.I have width and height of RecyclerView as match_parent.
Following is the code.I am using RecyclerView for post title and post description in a blog app:

package com.awani.pocketblog;

import android.content.ClipData;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import org.w3c.dom.Text;

public class MainActivity extends AppCompatActivity {

private RecyclerView mBlogList;
private DatabaseReference mDatabase;

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

    mBlogList = (RecyclerView) findViewById(R.id.blog_list);
    mBlogList.setHasFixedSize(true);
    mBlogList.setLayoutManager(new LinearLayoutManager(this));
    mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
}

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

    FirebaseRecyclerAdapter<Blog,BlogViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>( Blog.class,
            R.layout.blog_row,
            BlogViewHolder.class,
            mDatabase

    ) {
        @Override
        protected void populateViewHolder(BlogViewHolder viewHolder, Blog model, int position) {
            viewHolder.setTitle(model.getTitle());//model means Blog class over here
            viewHolder.setDesc(model.getDesc());

        }
    };

    mBlogList.setAdapter(firebaseRecyclerAdapter);
}

//holder for the recyclerView
public static class BlogViewHolder extends RecyclerView.ViewHolder{

    View mView;

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

        mView = itemView;
    }

    public void setTitle(String title){

        TextView post_title = (TextView) mView.findViewById(R.id.post_title);
        post_title.setText(title);

    }

    public void setDesc(String desc){

        TextView post_description = (TextView) mView.findViewById(R.id.post_description);
        post_description.setText(desc);
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main_menu,menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(item.getItemId()==R.id.action_add){
        startActivity(new Intent(MainActivity.this,PostActivity.class));
    }

    return super.onOptionsItemSelected(item);
}
}

log cat statement which might be causing this..

07-08 17:22:10.761 23308-23308/com.awani.pocketblog W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView

this is activity_main.xml code:

<?xml version="1.0" encoding="utf-8"?>
<android.widget.RelativeLayout     xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.awani.pocketblog.MainActivity">

<android.support.v7.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/blog_list">
</android.support.v7.widget.RecyclerView>

</android.widget.RelativeLayout>

My android studio version is 2.3.2 and he dependencies are 25.3.1
and firebase dependencies are 10.0.1
firebase ui dependency 1.1.1

Body:
Check this out. I am using this code to print saved news
You can check this out for reference
Although I used fragment you can change your code accordingly for Activity.

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.example.student.newsapp.R;
import com.firebase.client.Firebase;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class show extends AppCompatActivity {

RecyclerView recyclerView;
FirebaseDatabase firebaseDatabase;
DatabaseReference myRef;
FirebaseAuth firebaseauth;
private FirebaseRecyclerAdapter<show_items, ShowDataViewHolder> mFirebaseAdapter;
private ProgressDialog progressDialog;

public show() {
    // Required empty public constructor
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.rvforbookmarks);
    Firebase.setAndroidContext(this);
    progressDialog = new ProgressDialog(this);
    progressDialog.setMessage("Please wait..");
    progressDialog.show();

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle("Bookmarks");

    firebaseDatabase = FirebaseDatabase.getInstance();

    firebaseauth = FirebaseAuth.getInstance();
    final String userid =firebaseauth.getCurrentUser().getUid();

    // myRef = firebaseDatabase.getReference("User_Details");
    myRef = FirebaseDatabase.getInstance().getReference("User_Details").child(userid);

    recyclerView = (RecyclerView)findViewById(R.id.rv);
    recyclerView.setLayoutManager(new LinearLayoutManager(show.this));

}

//View Holder For Recycler View
public static class ShowDataViewHolder extends RecyclerView.ViewHolder {
    private final TextView image_title  ;
    private final ImageView image_url;
    private TextView imge_des;
    private ImageView btn_delete;
    private TextView nobookmark;

    public ShowDataViewHolder(final View itemView)
    {
        super(itemView);
        image_url = (ImageView) itemView.findViewById(R.id.fetch_image);
        image_title = (TextView) itemView.findViewById(R.id.fetch_image_title);
        imge_des = (TextView) itemView.findViewById(R.id.fetch_description);
        btn_delete = (ImageView) itemView.findViewById(R.id.btn_delete);
        nobookmark = (TextView) itemView.findViewById(R.id.nobookmark);

    }

    private void Image_Title(String title)
    {
        image_title.setText(title);
    }

    private void Image_URL(String title)
    {
        // image_url.setImageResource(R.drawable.loading);
        Glide.with(itemView.getContext())
                .load(title)
                .crossFade()
                .placeholder(R.drawable.loading)
                .thumbnail(0.1f)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(image_url);
    }

    public void Image_Des(String title) {
        imge_des.setText(title);

    }
}

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

    mFirebaseAdapter = new FirebaseRecyclerAdapter<show_items, ShowDataViewHolder>(show_items.class, R.layout.showbookamrks, ShowDataViewHolder.class, myRef) {
        public void populateViewHolder(final ShowDataViewHolder viewHolder, show_items model, final int position) {
            viewHolder.Image_URL(model.getImage_URL());
            viewHolder.Image_Title(model.getImage_Title());
            viewHolder.Image_Des(model.getImage_des());

            //OnClick Item
            viewHolder.btn_delete.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(final View v) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(show.this);
                    builder.setMessage("Do you want to Delete this data ?").setCancelable(false)
                            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    int selectedItems = position;
                                    mFirebaseAdapter.getRef(selectedItems).removeValue();
                                    mFirebaseAdapter.notifyItemRemoved(selectedItems);
                                    recyclerView.invalidate();
                                    onStart();
                                }
                            })
                            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.cancel();
                                }
                            });
                    AlertDialog dialog = builder.create();
                    dialog.setTitle("Confirm");
                    dialog.show();
                }
            });

                progressDialog.dismiss();
        }

    };

    recyclerView.setAdapter(mFirebaseAdapter);

}

}

Hope it helps
Thankyou


问:
Sending Html as parameter in translate decorator in angularjs
When I try to send html as parameter in translate decorator my html code is displayed as text and not as html. Like in code under:

```<code><!doctype html>
<html ng-app="myApp">
  <head>
<script src="https://cdn.rawgit.com/SlexAxton/messageformat.js/v1.0.2/messageformat.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular-animate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular-cookies.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular-sanitize.js"></script>
<script src="https://cdn.rawgit.com/angular-translate/bower-angular-translate/2.15.2/angular-translate.js"></script>
<script src="https://cdn.rawgit.com/angular-translate/bower-angular-translate-interpolation-messageformat/2.15.2/angular-translate-interpolation-messageformat.js"></script>
<script src="https://cdn.rawgit.com/angular-translate/bower-angular-translate-storage-cookie/2.15.2/angular-translate-storage-cookie.js"></script>
<script src="https://cdn.rawgit.com/angular-translate/bower-angular-translate-storage-local/2.15.2/angular-translate-storage-local.js"></script>
<script src="https://cdn.rawgit.com/angular-translate/bower-angular-translate-loader-url/2.15.2/angular-translate-loader-url.js"></script>
<script src="https://cdn.rawgit.com/angular-translate/bower-angular-translate-loader-static-files/2.15.2/angular-translate-loader-static-files.js"></script>
<script src="https://cdn.rawgit.com/angular-translate/bower-angular-translate-handler-log/2.15.2/angular-translate-handler-log.js"></script>
<script src="script.js"></script>
 </head>
  <body>

<div ng-controller="Ctrl">
  <p>{{ 'HEADLINE' | translate }}</p>
  <p>{{ 'PARAGRAPH' | translate }}</p>
</div>

  </body>
</code>```

```<code>var translations = {
  HEADLINE: 'What an awesome module!',
  PARAGRAPH: 'This is cool link <a href="http://google.com">test</a> Check it out!'
};

var app = angular.module('myApp', ['pascalprecht.translate']);

app.config(['$translateProvider', function ($translateProvider) {
  // add translation table
  $translateProvider.translations('en', translations);
   $translateProvider.preferredLanguage('en');
 }]);

app.controller('Ctrl', ['$scope', function ($scope) {

}]);
</code>```

As a result I get:

```<code>This is cool link <a href="http://google.com">test</a> Check it out!
</code>```

html code it self in browser instead of anchor html representation.
I want anchor to be processed as html tag.

Anybody has a suggestion?

答:
In order to actually process the HTML instead of outputting it as characters, you can use the ng-bind-html directive. In your case, it will look like this:

```<code><p ng-bind-html="'PARAGRAPH' | translate"></p>
</code>```

Body:
When I try to send html as parameter in translate decorator my html code is displayed as text and not as html. Like in code under:

<!doctype html>

{{ 'HEADLINE' | translate }}

{{ 'PARAGRAPH' | translate }}

var translations = {
  HEADLINE: 'What an awesome module!',
  PARAGRAPH: 'This is cool link test Check it out!'
};

var app = angular.module('myApp', ['pascalprecht.translate']);

app.config(['$translateProvider', function ($translateProvider) {
  // add translation table
  $translateProvider.translations('en', translations);
   $translateProvider.preferredLanguage('en');
 }]);

app.controller('Ctrl', ['$scope', function ($scope) {

}]);

As a result I get:

This is cool link test Check it out!

html code it self in browser instead of anchor html representation.
I want anchor to be processed as html tag.

Anybody has a suggestion?

Body:
In order to actually process the HTML instead of outputting it as characters, you can use the ng-bind-html directive. In your case, it will look like this:

<p ng-bind-html="'PARAGRAPH' | translate"></p>


问:
Subprocess.call ffmpeg making empty file
I am trying to convert video from one format to other.

```<code>extension = '.avi'
extension_less_url = '../uploads/video'
import subprocess
subprocess.call(['ffmpeg', '-i', extension_less_url + extension, extension_less_url + '.mp4'])
</code>```

But above produces an empty file named 'video.mp4'.
How to correct?
This is the error I am getting:

```<code>The encoder 'aac' is experimental but experimental codecs are not enabled, add '-strict -2' if you want to use it.
</code>```

答:
This problem is for '.mp4'. try something else like '.mkv' for the target format of your video.
I've done this and the problem is solved</p>

Body:
I am trying to convert video from one format to other.

extension = '.avi'
extension_less_url = '../uploads/video'
import subprocess
subprocess.call(['ffmpeg', '-i', extension_less_url + extension, extension_less_url + '.mp4'])

But above produces an empty file named 'video.mp4'.
How to correct?
This is the error I am getting:

The encoder 'aac' is experimental but experimental codecs are not enabled, add '-strict -2' if you want to use it.


问:
How can I suppress a notice error in codeigniter?
I want to suppress notices in the codeigniter error log during a certain cronjob. I've tried using the @ in front of the line, but it still prints the notice in the log:

This is the row that is generating the notice:

```<code>@$resultarray[1][2]++;
</code>```

The notice: ... Severity: Notice  --> Undefined offset: 1 ...

What am I doing wrong here?

(I'm using it well overthought, so please no messages claiming not to use @, thanks :) )

答:
In system/core/Common.php

```<code>function _exception_handler($severity, $message, $filepath, $line)
{
     // We don't bother with "strict" notices since they tend to fill up
     // the log file with excess information that isn't normally very helpful.
     // For example, if you are running PHP 5 and you use version 4 style
     // class functions (without prefixes like "public", "private", etc.)
     // you'll get notices telling you that these have been deprecated.
    if ($severity == E_STRICT || !error_reporting()) // <-- add || !error_reporting()
    {
        return;
    }

    $_error =& load_class('Exceptions', 'core');

    // Should we display the error? We'll get the current error_reporting
    // level and add its bits with the severity bits to find out.
    if (($severity & error_reporting()) == $severity)
    {
        $_error->show_php_error($severity, $message, $filepath, $line);
    }

    // Should we log the error?  No?  We're done...
    if (config_item('log_threshold') == 0)
    {
        return;
    }

    $_error->log_exception($severity, $message, $filepath, $line);
}

}
</code>```

Add || !error_reporting() and expressions with error control operator @ will not be logged by CodeIgniter.

Body:
I want to suppress notices in the codeigniter error log during a certain cronjob. I've tried using the @ in front of the line, but it still prints the notice in the log:

This is the row that is generating the notice:

@$resultarray[1][2]++;

The notice: ... Severity: Notice  --> Undefined offset: 1 ...

What am I doing wrong here?

(I'm using it well overthought, so please no messages claiming not to use @, thanks :) )

Body:
In system/core/Common.php

function _exception_handler($severity, $message, $filepath, $line)
{
     // We don't bother with "strict" notices since they tend to fill up
     // the log file with excess information that isn't normally very helpful.
     // For example, if you are running PHP 5 and you use version 4 style
     // class functions (without prefixes like "public", "private", etc.)
     // you'll get notices telling you that these have been deprecated.
    if ($severity == E_STRICT || !error_reporting()) // <-- add || !error_reporting()
    {
        return;
    }

    $_error =& load_class('Exceptions', 'core');

    // Should we display the error? We'll get the current error_reporting
    // level and add its bits with the severity bits to find out.
    if (($severity & error_reporting()) == $severity)
    {
        $_error->show_php_error($severity, $message, $filepath, $line);
    }

    // Should we log the error?  No?  We're done...
    if (config_item('log_threshold') == 0)
    {
        return;
    }

    $_error->log_exception($severity, $message, $filepath, $line);
}

}

Add || !error_reporting() and expressions with error control operator @ will not be logged by CodeIgniter.


问:
Nginx SSL issue - specific port
I migrated to Nginx, but i cannot find the solution for my problem.
On apache, I had 1 virutal host with ssl and specific port.

The apache config seems like this:

```<code><VirtualHost *:443>
    ServerAdmin info@example.com
    ServerName example.in
    DocumentRoot /paht/to/web/files

    SSLEngine on
    SSLCertificateFile /ssl/certificate
    SSLCertificateKeyFile /ssl/key_file
    SSLCACertificateFile /ssl/ca.cer

</VirtualHost>

# intermediate configuration, tweak to your needs
SSLProtocol             all -SSLv2 -SSLv3
SSLCipherSuite          ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECD$
SSLHonorCipherOrder     on

<Directory /path/to/my/web>
  Options FollowSymLinks Includes ExecCGI
  AllowOverride All
  Order allow,deny
  Allow from all
  Require all granted
</Directory>

<VirtualHost *:9092>
    ServerAdmin info@example.com
    ServerName example.in
    DocumentRoot /paht/to/web/files

    DocumentRoot /another/path/to/api

    SSLEngine on
    SSLCertificateFile /path/to/webcer
    SSLCertificateKeyFile /path/to/webkey
    SSLCACertificateFile /path/to/ca.cer

       <Directory /another/path/to/api>
           Options Indexes FollowSymLinks MultiViews ExecCGI
           AllowOverride All
           Require all granted
        </Directory>

        ErrorLog ${APACHE_LOG_DIR}/api_cable_error.log
        CustomLog ${APACHE_LOG_DIR}/api_cable_access.log combined
</code>```

When I openend https://example.in:9092, it worked without any troubles.
But when I set this up in nginx configuration, i am still getting 'certificate is not valid' error on HTTPS. The Nginx config seems to be:

```<code>server {
    listen      80;
    listen      9092;
    server_name example.com;
    rewrite     ^   https://$server_name$request_uri? permanent;
}

server {
    listen 443 ssl http2;
    listen              [::]:443 ssl http2;
    keepalive_timeout   70;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers 'ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS';
    ssl_prefer_server_ciphers on;
    ssl_certificate     /my/letsencrypt/cert
    ssl_certificate_key /my/letsencrypt/key;
    ssl_stapling        on;
    ssl_stapling_verify off;
    ssl_dhparam         /my/dhparam.pem;
    ssl_session_cache   shared:SSL:10m;
    ssl_session_timeout 10m;
    server_name example.com;

    root /path/to/web/example/com;

    index index.html index.php;
    client_max_body_size 1024M;

    try_files $uri $uri/ /index.php?$args;

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass php-handler;
        fastcgi_index index.php;

        fastcgi_split_path_info ^((?U).+\.php)(/?.+)$;
        fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
        fastcgi_param PATH_TRANSLATED $document_root/$fastcgi_path_info;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }

}

server {
    listen 9092 ssl http2;
    listen              [::]:9092 ssl http2;
    keepalive_timeout   70;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers 'ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-S$
    ssl_prefer_server_ciphers on;
    ssl_certificate     /path/to/cert
    ssl_certificate_key path/to/key
    ssl_stapling        on;
    ssl_stapling_verify off;
    ssl_dhparam         /my/dhparam.pem;
    ssl_session_cache   shared:SSL:10m;
    ssl_session_timeout 10m;
    server_name example.com;

    root /another/path/to/files;

    index index.html index.php;
    client_max_body_size 1024M;

    try_files $uri $uri/ /index.php?$args;

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass php-handler;
        fastcgi_index index.php;

        fastcgi_split_path_info ^((?U).+\.php)(/?.+)$;
        fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
        fastcgi_param PATH_TRANSLATED $document_root/$fastcgi_path_info;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }

}
</code>```

Does anyone have experiences how to get this working?
Thanks.

答:
disable all

```<code>  #ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
   # ssl_ciphers 'ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS';
   # ssl_prefer_server_ciphers on;
    ssl_certificate     /my/letsencrypt/cert
    ssl_certificate_key /my/letsencrypt/key;
    #ssl_stapling        on;
    #ssl_stapling_verify off;
    #ssl_dhparam         /my/dhparam.pem;
   # ssl_session_cache   shared:SSL:10m;
    #ssl_session_timeout 10m;
</code>```

and make sure

```<code> ssl_certificate     /my/letsencrypt/cert
 ssl_certificate_key /my/letsencrypt/key;
</code>```

/my/letsencrypt/cert  and /my/letsencrypt/key  ssl files at right place  and there valid

Title: Nginx SSL issue - specific port

Body:
I migrated to Nginx, but i cannot find the solution for my problem.
On apache, I had 1 virutal host with ssl and specific port.

The apache config seems like this:

<VirtualHost *:443>
    ServerAdmin info@example.com
    ServerName example.in
    DocumentRoot /paht/to/web/files

    SSLEngine on
    SSLCertificateFile /ssl/certificate
    SSLCertificateKeyFile /ssl/key_file
    SSLCACertificateFile /ssl/ca.cer

</VirtualHost>

# intermediate configuration, tweak to your needs
SSLProtocol             all -SSLv2 -SSLv3
SSLCipherSuite          ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECD$
SSLHonorCipherOrder     on

<Directory /path/to/my/web>
  Options FollowSymLinks Includes ExecCGI
  AllowOverride All
  Order allow,deny
  Allow from all
  Require all granted
</Directory>

<VirtualHost *:9092>
    ServerAdmin info@example.com
    ServerName example.in
    DocumentRoot /paht/to/web/files

    DocumentRoot /another/path/to/api

    SSLEngine on
    SSLCertificateFile /path/to/webcer
    SSLCertificateKeyFile /path/to/webkey
    SSLCACertificateFile /path/to/ca.cer

       <Directory /another/path/to/api>
           Options Indexes FollowSymLinks MultiViews ExecCGI
           AllowOverride All
           Require all granted
        </Directory>

        ErrorLog ${APACHE_LOG_DIR}/api_cable_error.log
        CustomLog ${APACHE_LOG_DIR}/api_cable_access.log combined

When I openend https://example.in:9092, it worked without any troubles.
But when I set this up in nginx configuration, i am still getting 'certificate is not valid' error on HTTPS. The Nginx config seems to be:

server {
    listen      80;
    listen      9092;
    server_name example.com;
    rewrite     ^   https://$server_name$request_uri? permanent;
}

server {
    listen 443 ssl http2;
    listen              [::]:443 ssl http2;
    keepalive_timeout   70;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers 'ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS';
    ssl_prefer_server_ciphers on;
    ssl_certificate     /my/letsencrypt/cert
    ssl_certificate_key /my/letsencrypt/key;
    ssl_stapling        on;
    ssl_stapling_verify off;
    ssl_dhparam         /my/dhparam.pem;
    ssl_session_cache   shared:SSL:10m;
    ssl_session_timeout 10m;
    server_name example.com;

    root /path/to/web/example/com;

    index index.html index.php;
    client_max_body_size 1024M;

    try_files $uri $uri/ /index.php?$args;

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass php-handler;
        fastcgi_index index.php;

        fastcgi_split_path_info ^((?U).+\.php)(/?.+)$;
        fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
        fastcgi_param PATH_TRANSLATED $document_root/$fastcgi_path_info;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }

}

server {
    listen 9092 ssl http2;
    listen              [::]:9092 ssl http2;
    keepalive_timeout   70;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers 'ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-S$
    ssl_prefer_server_ciphers on;
    ssl_certificate     /path/to/cert
    ssl_certificate_key path/to/key
    ssl_stapling        on;
    ssl_stapling_verify off;
    ssl_dhparam         /my/dhparam.pem;
    ssl_session_cache   shared:SSL:10m;
    ssl_session_timeout 10m;
    server_name example.com;

    root /another/path/to/files;

    index index.html index.php;
    client_max_body_size 1024M;

    try_files $uri $uri/ /index.php?$args;

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass php-handler;
        fastcgi_index index.php;

        fastcgi_split_path_info ^((?U).+\.php)(/?.+)$;
        fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
        fastcgi_param PATH_TRANSLATED $document_root/$fastcgi_path_info;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }

}

Does anyone have experiences how to get this working?
Thanks.

Body:
disable all

  #ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
   # ssl_ciphers 'ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS';
   # ssl_prefer_server_ciphers on;
    ssl_certificate     /my/letsencrypt/cert
    ssl_certificate_key /my/letsencrypt/key;
    #ssl_stapling        on;
    #ssl_stapling_verify off;
    #ssl_dhparam         /my/dhparam.pem;
   # ssl_session_cache   shared:SSL:10m;
    #ssl_session_timeout 10m;

and make sure

 ssl_certificate     /my/letsencrypt/cert
 ssl_certificate_key /my/letsencrypt/key;

/my/letsencrypt/cert  and /my/letsencrypt/key  ssl files at right place  and there valid


问:
Database to create a database
I'm using Sqlite with android to develop and app which can be customizable (for the dev) in the future. I have created a database with the data which is then to be used to create the database for the application. So if any changes need to be made in the future or I write an app for somebody else in the future then all I have to do is change this original database. The idea behind this is the dev's database will set up all the UI and everything to do with the app.

I am stuck on what to do next I have the database I need in the app as the dev fully populated. My idea was to create another DBHelper class and within that reference the original DBHelper class and query within the new DB Class. So this is the second DBHelper class that i'm trying to create a database from a previous database:

```<code>public class appDbHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "library.db"; //database name
    Cursor all, tables, options, ui_type;
    SQLiteDatabase database;

    public appDbHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
        DBHandler databaseHelper = new DBHandler(context);
        database = databaseHelper.getReadableDatabase();
        all = database.rawQuery("SELECT * FROM config", null);
        tables = database.rawQuery("SELECT * FROM table_names", null);
        options = database.rawQuery("SELECT * FROM options", null);
        ui_type = database.rawQuery("SELECT * FROM ui_type", null);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        for(int i=0; i<tables.getCount(); i++){
            tables.moveToPosition(i+1);
            String sql = "";
            for(int j = 0; i < all.getCount(); j++){
                if (all.moveToFirst()) {
                    do{
                        sql = ", " + all.getString(2) + " " + all.getString(5).toUpperCase();
                    }
                    while (all.moveToNext());
                }
            }
            Log.v("DatabaseSQL", sql);
            database.execSQL( "CREATE TABLE " + tables.getString(1) + "(_id INTEGER PRIMARY KEY AUTOINCREMENT"+sql+");");
        }
    }
</code>```

But I have a feeling this is not the way to go about what I need to do. Any help will be greatly appreciated.

答:
I think you do it wrong and to complicated. You provide a database to read data from where you could easily just create some inserts and your configuration will be implemented.

Two solutions:

From my own project: DatabaseAdapter.onCreate()

There you should see the database setup and the filling of the database with data. The data itself are added with simple inserts which contains data based on constants. So a programmer can easily change the data by changing the constants.

With that you don't have to handle 2 databases, you don't need to provide another database and read them.

As android supports database locations you could also skip this all and just open an sqlite database file you provide in your res/raw or asset folder or anywhere on the sdcard.

I recommend to do one of the two ways mentioned above.

ContentLicense: CC BY-SA 2.5

Title: Database to create a database

Body:
I'm using Sqlite with android to develop and app which can be customizable (for the dev) in the future. I have created a database with the data which is then to be used to create the database for the application. So if any changes need to be made in the future or I write an app for somebody else in the future then all I have to do is change this original database. The idea behind this is the dev's database will set up all the UI and everything to do with the app.

I am stuck on what to do next I have the database I need in the app as the dev fully populated. My idea was to create another DBHelper class and within that reference the original DBHelper class and query within the new DB Class. So this is the second DBHelper class that i'm trying to create a database from a previous database:

public class appDbHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "library.db"; //database name
    Cursor all, tables, options, ui_type;
    SQLiteDatabase database;

    public appDbHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
        DBHandler databaseHelper = new DBHandler(context);
        database = databaseHelper.getReadableDatabase();
        all = database.rawQuery("SELECT * FROM config", null);
        tables = database.rawQuery("SELECT * FROM table_names", null);
        options = database.rawQuery("SELECT * FROM options", null);
        ui_type = database.rawQuery("SELECT * FROM ui_type", null);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        for(int i=0; i<tables.getCount(); i++){
            tables.moveToPosition(i+1);
            String sql = "";
            for(int j = 0; i < all.getCount(); j++){
                if (all.moveToFirst()) {
                    do{
                        sql = ", " + all.getString(2) + " " + all.getString(5).toUpperCase();
                    }
                    while (all.moveToNext());
                }
            }
            Log.v("DatabaseSQL", sql);
            database.execSQL( "CREATE TABLE " + tables.getString(1) + "(_id INTEGER PRIMARY KEY AUTOINCREMENT"+sql+");");
        }
    }

But I have a feeling this is not the way to go about what I need to do. Any help will be greatly appreciated.


问:
How correctly to register namespace and id in the data scheme?
I registered the id and namespace in the data schema and after that the releationships stopped working. How to fix it?

```<code>// Fiddle.model.User
schema: {
    id: 'fiddle',
    namespace: "Fiddle.model",
    ...
</code>```

Fiddle: https://fiddle.sencha.com/#view/editor&fiddle/22pc

Here's the error message:
VM775 app.js: 13 Uncaught TypeError: user.setAddress is not a function

答:
You need to add namespace and id in one model and extend that model.
Fiddle :https://fiddle.sencha.com/#view/editor&fiddle/22rm</p>

```<code>Ext.define('Fiddle.model.Address', {
    extend: 'Ext.data.Model',
      schema: {

        // I registered the id and namespace in the data schema and after
        // that the releationships stopped working.
        id: 'fiddle',
        namespace: "Fiddle.model",

        proxy: {
            type: 'ajax',
            url: 'Users.json',
            reader: {
                rootProperty: 'result.ResultItems'
            }
        }
    },
    fields: [{
        name: 'street',
        type: 'string'
    }]
});
Ext.define('Fiddle.model.User', {
    extend: 'Fiddle.model.Address',

    fields: [{
        name: 'id',
        type: 'int'
    }, {
        name: 'name',
        type: 'string'
    }],
    hasOne: {
        role: 'address',
        association: "MassOperationTypeBySendMassNotificationsRequest",
        type: 'Fiddle.model.Address',
        reader: {
            rootProperty: 'address'
        },
        inverse: { role: "sendMassNotificationsRequest" }
    },
    hasMany: [{
        type: 'Fiddle.model.Order',
        role: 'orderList',
        reader: {
            rootProperty: 'OrderList'
        },
        inverse: {
            role: 'user'
        }
    }]
});
</code>```

Body:
I registered the id and namespace in the data schema and after that the releationships stopped working. How to fix it?

// Fiddle.model.User
schema: {
    id: 'fiddle',
    namespace: "Fiddle.model",
    ...

Fiddle: https://fiddle.sencha.com/#view/editor&fiddle/22pc

Here's the error message:
VM775 app.js: 13 Uncaught TypeError: user.setAddress is not a function

Body:
You need to add namespace and id in one model and extend that model.
Fiddle :https://fiddle.sencha.com/#view/editor&fiddle/22rm

Ext.define('Fiddle.model.Address', {
    extend: 'Ext.data.Model',
      schema: {

        // I registered the id and namespace in the data schema and after
        // that the releationships stopped working.
        id: 'fiddle',
        namespace: "Fiddle.model",

        proxy: {
            type: 'ajax',
            url: 'Users.json',
            reader: {
                rootProperty: 'result.ResultItems'
            }
        }
    },
    fields: [{
        name: 'street',
        type: 'string'
    }]
});
Ext.define('Fiddle.model.User', {
    extend: 'Fiddle.model.Address',

    fields: [{
        name: 'id',
        type: 'int'
    }, {
        name: 'name',
        type: 'string'
    }],
    hasOne: {
        role: 'address',
        association: "MassOperationTypeBySendMassNotificationsRequest",
        type: 'Fiddle.model.Address',
        reader: {
            rootProperty: 'address'
        },
        inverse: { role: "sendMassNotificationsRequest" }
    },
    hasMany: [{
        type: 'Fiddle.model.Order',
        role: 'orderList',
        reader: {
            rootProperty: 'OrderList'
        },
        inverse: {
            role: 'user'
        }
    }]
});


问:
Setting a target or multiplefile for a grunt task with sass and autoprefixer?
I'm setting a grunt file for a task. My goal is to create a css file from a sass file (scss) and add an autoprefix to all the proprieties which require so. Initially I used the propriety multifiles but it didn't work, so now I'm using the target propriety that works fine, but my problem is, even if I target the very same file, it will create another file in my folder where I put all my sass files.

So far my file is the following:

```<code>module.exports = function (grunt) {

    grunt.initConfig({

        pkg: grunt.file.readJSON('package.json'),

        sass: {
            dev: {
                options: {
                    style: 'expanded',
                    sourcemap: 'none',
                },
                files: {
                    '../style.css': 'scss/style.scss'
                }
            },
            dist: {
                options: {
                    style: 'compressed',
                    sourcemap: 'none',
                },
                files: {
                    '../style-min.css': 'scss/style.scss'
                }
            }
        },
        autoprefixer: {
            options: {
                browsers: ['last 6 versions']
            },
            target: {
                expand: true,
                flatten: true,
                src: '../style.css',
                dest: ''
            }
        },
        watch: {
            css: {
                files: '**/*.scss',
                tasks: ['sass', 'autoprefixer']
            }
        },
    });

    grunt.loadNpmTasks('grunt-contrib-sass');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-autoprefixer');
    grunt.registerTask('default', ['watch']);
}
</code>```

My goal is to set up a global task for all my css files, like so:

```<code>target: {
    expand: true,
    flatten: true,
    src: '*.css',
    dest: ''
}
</code>```

but it is not working even if I try something like:

```<code>target: {
        expand: true,
        flatten: true,
        src: '../*.css',
        dest: ''
    }
</code>```

Does anyone know why?

答:
Use cwd (stands for current working directory) which is the path where grunt looks for the files matching the pattern in src. Also define the dest so that it would create the destination file in the same folder.

```<code>target: {
    expand: true,
    flatten: true,
    cwd: '../',
    src: [ '**/*.css' ],
    dest: '../'
}
</code>```

Body:
I'm setting a grunt file for a task. My goal is to create a css file from a sass file (scss) and add an autoprefix to all the proprieties which require so. Initially I used the propriety multifiles but it didn't work, so now I'm using the target propriety that works fine, but my problem is, even if I target the very same file, it will create another file in my folder where I put all my sass files.

So far my file is the following:

module.exports = function (grunt) {

    grunt.initConfig({

        pkg: grunt.file.readJSON('package.json'),

        sass: {
            dev: {
                options: {
                    style: 'expanded',
                    sourcemap: 'none',
                },
                files: {
                    '../style.css': 'scss/style.scss'
                }
            },
            dist: {
                options: {
                    style: 'compressed',
                    sourcemap: 'none',
                },
                files: {
                    '../style-min.css': 'scss/style.scss'
                }
            }
        },
        autoprefixer: {
            options: {
                browsers: ['last 6 versions']
            },
            target: {
                expand: true,
                flatten: true,
                src: '../style.css',
                dest: ''
            }
        },
        watch: {
            css: {
                files: '**/*.scss',
                tasks: ['sass', 'autoprefixer']
            }
        },
    });

    grunt.loadNpmTasks('grunt-contrib-sass');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-autoprefixer');
    grunt.registerTask('default', ['watch']);
}

My goal is to set up a global task for all my css files, like so:

target: {
    expand: true,
    flatten: true,
    src: '*.css',
    dest: ''
}

but it is not working even if I try something like:

target: {
        expand: true,
        flatten: true,
        src: '../*.css',
        dest: ''
    }

Does anyone know why?

Body:
Use cwd (stands for current working directory) which is the path where grunt looks for the files matching the pattern in src. Also define the dest so that it would create the destination file in the same folder.

target: {
    expand: true,
    flatten: true,
    cwd: '../',
    src: [ '**/*.css' ],
    dest: '../'
}


问:
Sqlx "missing destination name" for struct tag through pointer
I have a model like this:

```<code>type Course struct {
    Name string `db:"course_name"`
}

type Group struct {
    Course *Course
}
type Groups []Group
</code>```

And when i try to do sqlx.Select for Groups with a query like this:

```<code>SELECT c.name as course_name FROM courses as c;
</code>```

I get

missing destination name course_name in *main.Groups

error.

What is the issue with this code?

答:
I changed Course *Course to Course Course - no effect.
When i made it embedded like this:

```<code>type Group struct {
    Course
}
</code>```

it worked.

This is also valid:

```<code>type Group struct {
    *Course
}
</code>```

Looks like sqlx doesn't understand anything except embedded fields.

Body:
I have a model like this:

type Course struct {
    Name string `db:"course_name"`
}

type Group struct {
    Course *Course
}
type Groups []Group

And when i try to do sqlx.Select for Groups with a query like this:

SELECT c.name as course_name FROM courses as c;

I get

missing destination name course_name in *main.Groups

error.

What is the issue with this code?

Body:
I changed Course *Course to Course Course - no effect.
When i made it embedded like this:

type Group struct {
    Course
}

it worked.

This is also valid:

type Group struct {
    *Course
}

Looks like sqlx doesn't understand anything except embedded fields.


问:
How empty input value when success submit in jquery
I want to clear the input values when the form is submitted correctly, But there is a problem, if not inserted, the inputs are erased.
I will be grateful for help me.
This is my code:

```<code>$(document).ready(function(){
    $("#Insert").click(function(){
        var email = $("#email").val();
        var title = $("title").val();
        var text = $("text").val();
        var cSend = true;
$.post("ajax.php",{email:email,title:title,text:text,cSend:cSend},function(data){
        $("#contactResualt").html(data);

        });
    });
});
</code>```

//ajax.php

```<code>if(isset($_POST['cSend'])){
  if (empty($_POST['email']) || empty($_POST['title']) || empty($_POST['text'])){
    echo '<div class="alert alert-warning">Fill empty fields</div>';
}
else{
    $email = $_POST['email'];
    $title = $_POST['title'];
    $text = $_POST['text'];
    $Contactus = new Contactus();
    $resualt = $Contactus->SendPM($email,$title,$text);
        if($resualt){
        echo '<div class="alert alert-success">Insertion was successful</div>';
        }
        else{
        echo '<div class="alert alert-warning">Insertion failed</div>';
        }
    }
}
</code>```

So, I just want the information to be correctly inserted, Inputs will be cleared.

答:
If you only want to erase the fields when the insert was successful, you can put an indicator attribute into the response HTML:

if($resualt) {
  echo '
Insertion was successful
';
}
else {
  echo '
Insertion failed
';
}
```

<p>Then use the indicator in the AJAX callback to determine whether you should reset the form:</p>

```$.post("ajax.php", {
  email: email,
  title: title,
  text: text,
  cSend: cSend
}, function(data) {
  $("#contactResualt").html(data);
  if($("#contactResualt [data-success]").attr("data-success") === "true") {
    $("#email, #title, #text").val("");
  }
});
```

Body:
I want to clear the input values when the form is submitted correctly, But there is a problem, if not inserted, the inputs are erased.
I will be grateful for help me.
This is my code:

$(document).ready(function(){
    $("#Insert").click(function(){
        var email = $("#email").val();
        var title = $("title").val();
        var text = $("text").val();
        var cSend = true;
$.post("ajax.php",{email:email,title:title,text:text,cSend:cSend},function(data){
        $("#contactResualt").html(data);

        });
    });
});

//ajax.php

if(isset($_POST['cSend'])){
  if (empty($_POST['email']) || empty($_POST['title']) || empty($_POST['text'])){
    echo '
Fill empty fields
';
}
else{
    $email = $_POST['email'];
    $title = $_POST['title'];
    $text = $_POST['text'];
    $Contactus = new Contactus();
    $resualt = $Contactus->SendPM($email,$title,$text);
        if($resualt){
        echo '
Insertion was successful
';
        }
        else{
        echo '
Insertion failed
';
        }
    }
}

So, I just want the information to be correctly inserted, Inputs will be cleared.

Body:
If you only want to erase the fields when the insert was successful, you can put an indicator attribute into the response HTML:

if($resualt) {
  echo '<div class="alert alert-success" data-success="true">Insertion was successful</div>';
}
else {
  echo '<div class="alert alert-warning" data-success="false">Insertion failed</div>';
}

Then use the indicator in the AJAX callback to determine whether you should reset the form:

$.post("ajax.php", {
  email: email,
  title: title,
  text: text,
  cSend: cSend
}, function(data) {
  $("#contactResualt").html(data);
  if($("#contactResualt [data-success]").attr("data-success") === "true") {
    $("#email, #title, #text").val("");
  }
});


问:
React architecture for a huge business application
So we've recently picked up React in our company as the front-end technology to build our huge business web application. By saying recently, I mean we don't have any previous experience with React (we have a huge background of AngularJS), and by saying huge application, I mean it's really huge and very dynamic with lots and lots of different pieces and functionality.

Because we will have a lot of huge components that all play a very important role and have complex logic inside them, and because we want them to be easily pluggable and reusable, we want them to be as isolated as possible from the outside world and other parts of our application, because otherwise because of their size and complex functionality it would be pretty much impossible to develop and maintain them. That's the reason why we have decided NOT to use Redux, at least in the beginning, while we are developing just the separate components themselves, because it compromises component isolation and makes the whole application data flow logic impossible to understand when there are so many complex components. Although I believe our choice could be wrong, because as I've already mentioned, we have no experience with React.

As I've already mentioned, the application is very dynamic. By that I mean that components are actually rendered by data. We use various configuration provider classes that interacts with our API endpoints to get the pieces of our application's configuration, like configurations of navigation, pages, various forms, lists, etc., and then try to render components that are read from that configuration.

The problem is, after a couple of weeks struggling to get the momentum with React and discover the right patterns and common solutions to our problems, we've been talking in our crew, that maybe React is not the right technology for us, as it's a UI library, not event a framework, and it doesn't help us a lot, but just adds its rendering rules that we have to break at times to achieve the dynamics and component independence we want.

Considering the component isolation and data flow management, I personally have heard that there is a language for front-end development Elm that has pretty robust data flow architecture where each component has its own model that is separate from others, but I don't know whether it's worth a try, as it may fall behind our big requirements pretty soon too.

The reason I'm writing this question here is that I hope to get an insight from people that have a solid background on working with huge front-end applications. I'd like to know whether it's possible to develop such an application with React, whether React is suitable for such complexity and dynamics, whether we really need Redux or something else, what path, practices, ideologies should we follow. If you understood my question correctly, it's more the architecture side that we are struggling with, than the technological. Maybe we are just walking the path that leads to more and more struggle and complexity but not towards production.

答:
I'm at the similar situation right now. I have a background in large desktop applications (ERP, LOB - WinForms, WPF) - 1000+ modules, very dynamic (more than 70% of the UI was generated by input data/configuration), adding new functionality was just about extending some configuration (without touching source code).

I'm deeply investigating current web technologies and I'm more and more convinced that React is not a good fit for that. React really shines in small/middle size applications where you (and other team members) develop every page/component 'manually' (not dynamically generated) and you want to have one global state. But it doesn't help you with building large scale application out of the box - it is only UI library (so no support for modules, routing, forms, binding, http requests, static typing (typescript), etc.) and to my surprise, there is no support for style shadowing/encapsulation (you have to integrate, for example, CSS Modules, by your own). And at the end, you have to constantly bother with libraries versioning (to make them always work together is truly time and energy consuming).

I have a great experience with Angular 2/4+ and I think, for now, it is the best technology for that kind of the applications (if you know WPF, it is very similar). It is a full framework, which is prepared to the scaling out of the box. You can split your app into independent modules (specifying which components will be visible to the outside world), every component has public api (statically typed, inputs/outputs) and encapsulated css styles (there is no interference between others).
For the global state (logged in user, global configuration, etc.), you can still use library ngrx/store (which implements Redux pattern and comes with extra nice things, like 'effects' and integrates really well into Angular ecosystem).

I tried to do in Angular really crazy stuff (dynamically generating the whole application from backend configuration) and everything worked perfectly, as expected.


问:
What's the difference between a 302 and a 307 redirect?
What's the difference between a 302 FOUND and a 307 TEMPORARY REDIRECT HTTP response?

The W3 spec seems to indicate that they're both used for temporary redirects, and neither can be cached unless the response specifically allows it.

答:
In some use cases, 307 redirects might be abused by an attacker to learn the victim's credentials.

Further information can be found in section 3.1 of A Comprehensive Formal Security Analysis of OAuth 2.0.

The authors of the above paper suggest the following:

Fix. Contrary to the current wording in the OAuth standard, the exact method of the redirect is not an implementation detail but essential for the security of OAuth. In the HTTP standard (RFC 7231), only the 303 redirect is defined unambigiously to drop the body of an HTTP POST request. All other HTTP redirection status codes, including the most commonly used 302, leave the browser the option to preserve the POST request and the form data. In practice, browsers typically rewrite to a GET request, thereby dropping the form data, except for 307 redirects. Therefore, the OAuth standard should require 303 redirects for the steps mentioned above in order to fix this problem.


问:
Turn URL into Anchor tag using Regular Expression
I want the following different input types to be converted into the following anchor tag:

```<code>http://www.stackoverflow.com
https://www.stackoverflow.com
www.stackoverflow.com
</code>```

Replaced with:

```<code><a href='http(s)://www.stackoverflow.com' title='Link opens in new window' target='_blank'>www.stackoverflow.com</a>
</code>```

I think I could probably write something similar myself, but I'd like to know if there is a standard script for doing this which has been throughly tested?

Many Thanks!

答:
Found this function:</p>

```<code>   Public Shared Function ConvertUrlsToLinks(ByVal msg As String) As String
        Dim regex As String = "((www\.|(http|https|ftp|news|file)+\:\/\/)[_.a-z0-9-]+\.[a-z0-9\/_:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])"
        Dim r As New Regex(regex, RegexOptions.IgnoreCase)
        Return r.Replace(msg, "<a href=""$1"" title=""Click to open in a new window or tab"" target=""_blank"">$1</a>").Replace("href=""www", "href=""http://www")
    End Function
</code>```

Body:
I want the following different input types to be converted into the following anchor tag:

http://www.stackoverflow.com
https://www.stackoverflow.com
www.stackoverflow.com

Replaced with:

www.stackoverflow.com

I think I could probably write something similar myself, but I'd like to know if there is a standard script for doing this which has been throughly tested?

Many Thanks!

Body:
Found this function:

   Public Shared Function ConvertUrlsToLinks(ByVal msg As String) As String
        Dim regex As String = "((www\.|(http|https|ftp|news|file)+\:\/\/)[&#95;.a-z0-9-]+\.[a-z0-9\/&#95;:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])"
        Dim r As New Regex(regex, RegexOptions.IgnoreCase)
        Return r.Replace(msg, "<a href=""$1"" title=""Click to open in a new window or tab"" target=""&#95;blank"">$1</a>").Replace("href=""www", "href=""http://www")
    End Function


问:
Heroku login and logout does not work?
My account on heroku is suspended, and I am trying delete it on "cmd or git bash"; however, in my program, I cannot logout from that account.

This is the error I receive:

```<code>$ heroku logout
C:/Users/Romantiku/.heroku/client/lib/heroku/cli.rb:30:in `rescue in start': und
efined method `styled_error' for Heroku::CLI:Class (NoMethodError)
        from C:/Users/Romantiku/.heroku/client/lib/heroku/cli.rb:16:in `start'
        from c:/Program Files (x86)/Heroku/bin/heroku:25:in `<main>'
</code>```

答:
I just logged in again as another account.

This handled logging out as I did not see a clear cut way from the command line on how to logout

```<code>heroku login
Email: new@email.account
Password: ******
</code>```

Title: Heroku login and logout does not work?

Body:
My account on heroku is suspended, and I am trying delete it on "cmd or git bash"; however, in my program, I cannot logout from that account.

This is the error I receive:

$ heroku logout
C:/Users/Romantiku/.heroku/client/lib/heroku/cli.rb:30:in `rescue in start': und
efined method `styled_error' for Heroku::CLI:Class (NoMethodError)
        from C:/Users/Romantiku/.heroku/client/lib/heroku/cli.rb:16:in `start'
        from c:/Program Files (x86)/Heroku/bin/heroku:25:in `'

Body:
I just logged in again as another account.

This handled logging out as I did not see a clear cut way from the command line on how to logout

heroku login
Email: new@email.account
Password: ******


问:
Using sed command how can I replace Linux path to Windows path
I want to change the Linux path to a Windows Path, using "sed" command, for example:

Linux path: /opt/test/dash/apps/tomcat to Windows Path:
  c:\\test\\dash\\apps\\tomcat

I tried with:

```<code>sed -i 's|'/opt/test/dash/apps/tomcat'|'c:\\\\\\\test\\\\\\\dash\\\\\\\apps\\\\\\\tomcat'|g' /filename - But no luck!!
</code>```

What I exactly want all /opt/ should replace by c:\\ and rest of the "/" should be replace by "\\".

NOTE: I am executing this command remotely using ssh2_exec, All "sed" commands are working except the above.

Thanks in advance!!

答:
I would do it in two steps:

```<code>$>echo '/opt/test/dash/apps/tomcat' | sed 's#/opt#c:#g'|sed 's#/#\\\\#g'
c:\\test\\dash\\apps\\tomcat
</code>```

First changing the /opt with c:, then change the / with \ that you have to escape

Body:
I want to change the Linux path to a Windows Path, using "sed" command, for example:

Linux path: /opt/test/dash/apps/tomcat to Windows Path:
  c:\\test\\dash\\apps\\tomcat

I tried with:

sed -i 's|'/opt/test/dash/apps/tomcat'|'c:\\\\\\\test\\\\\\\dash\\\\\\\apps\\\\\\\tomcat'|g' /filename - But no luck!!

What I exactly want all /opt/ should replace by c:\\ and rest of the "/" should be replace by "\\".

NOTE: I am executing this command remotely using ssh2_exec, All "sed" commands are working except the above.

Thanks in advance!!

Body:
I would do it in two steps:

$>echo '/opt/test/dash/apps/tomcat' | sed 's#/opt#c:#g'|sed 's#/#\\\\#g'
c:\\test\\dash\\apps\\tomcat

First changing the /opt with c:, then change the / with \ that you have to escape


问:
Working of malloc in C
I am a beginner with C. I am wondering, how's malloc working.
Here is a sample code, I wrote on while trying to understand it's working.

CODE:

```<code>#include<stdio.h>
#include<stdlib.h>
int main() {
  int i;
  int *array = malloc(sizeof *array);
  for (i = 0; i < 5; i++) {
    array[i] = i+1;
  }
  printf("\nArray is: \n");
  for (i = 0; i < 5; i++) {
    printf("%d ", array[i]);
  }
  free(array);
  return 0;
}
</code>```

OUTPUT:

```<code>Array is:
1 2 3 4 5
</code>```

In the program above, I have only allocated space for 1 element, but the array now holds 5 elements. So as the programs runs smoothly without any error, what is the purpose of realloc().

Could anybody explain why?

Thanks in advance.

答:
So as the programs runs smoothly without any error

That's just because you were lucky. Keep running this program and you might segfault soon. You were relying on undefined behaviour (UB), which is always A Bad Thing™.

What is the purpose of realloc()?

From the man pages:

```<code>void *realloc(void *ptr, size_t size);
</code>```

The realloc() function changes the size of the memory block pointed to
  by ptr to size bytes.  The contents will be unchanged in  the  range
  from  the  start  of  the region up to the minimum of the old and new sizes.  If the new size is larger than the old size, the added
  memory
         will not be initialized.  If ptr is NULL, then the call is equivalent to malloc(size), for all values of size; if size is  equal
  to  zero,
         and  ptr  is not NULL, then the call is equivalent to free(ptr).  Unless ptr is NULL, it must have been returned by an
  earlier call to malloc(), calloc() or realloc().  If the area pointed to was moved, a free(ptr) is done.

Title: Working of malloc in C

Body:
I am a beginner with C. I am wondering, how's malloc working.
Here is a sample code, I wrote on while trying to understand it's working.

CODE:

#include<stdio.h>
#include<stdlib.h>
int main() {
  int i;
  int *array = malloc(sizeof *array);
  for (i = 0; i < 5; i++) {
    array[i] = i+1;
  }
  printf("\nArray is: \n");
  for (i = 0; i < 5; i++) {
    printf("%d ", array[i]);
  }
  free(array);
  return 0;
}

OUTPUT:

Array is:
1 2 3 4 5

In the program above, I have only allocated space for 1 element, but the array now holds 5 elements. So as the programs runs smoothly without any error, what is the purpose of realloc().

Could anybody explain why?

Thanks in advance.

Body:
So as the programs runs smoothly without any error

That's just because you were lucky. Keep running this program and you might segfault soon. You were relying on undefined behaviour (UB), which is always A Bad Thing™.

What is the purpose of realloc()?

From the man pages:

void *realloc(void *ptr, size_t size);

The realloc() function changes the size of the memory block pointed to
  by ptr to size bytes.  The contents will be unchanged in  the  range
  from  the  start  of  the region up to the minimum of the old and new sizes.  If the new size is larger than the old size, the added
  memory
         will not be initialized.  If ptr is NULL, then the call is equivalent to malloc(size), for all values of size; if size is  equal
  to  zero,
         and  ptr  is not NULL, then the call is equivalent to free(ptr).  Unless ptr is NULL, it must have been returned by an
  earlier call to malloc(), calloc() or realloc().  If the area pointed to was moved, a free(ptr) is done.


问:
Where can I find the primefaces tag library documentation?
Where can I find primefaces tag library documentation such as this: http://primefaces.prime.com.tr/docs/tag/index.html ?

I already have the jar, the sources of the primefaces. The apidoc supplied is "primefaces 2.2.RC2 API", not the "Tag Library Documentation Generator - Generated Documentation"

Maybe I should try generating it from the source, or maybe from the JAR (although I think the javadocs are not in the bytecodes) ?

答:
There's a separate JAR on the download page that contains the source code, and you could use the taglibrarydoc tool to generate the documentation from that.

I don't think you'll find a premade tag library documentation for an RC (release candidate) version.


问:
Could not Send SMS to mobiles with mobile numbers fetched from database in codeigniter
This is my code which is used to send SMS. I could send sms to multiple numbers but when I select one number SMS is not send. So I put an if else condition to check if there is only one number selected, then it should not have comma else it should seperate with commas. but now SMS is not sending to any numbers. What could have gone wrong. Please help me.</p>

```<code>      $college = $this->input->post('college');
      $count = count($college);
      if($count == 1){
 $mobiles = implode("" , $_POST['college']);
} else {
$mobiles = implode("," , $_POST['college']);
 }
$data = array(
          'sms_date' => date('Y-m-d H:i:s'),
          'sender' => 'Some Addresss',
          'receiver' => $mobiles,
          'sms_message' => $this->input->post('message')
    );
 function curl($url)
  {
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $url);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
 $data = curl_exec($ch);
 curl_close($ch);
 return $data;
 }
   //$mobile = $mobiles;
    $username = "*****"; //your username
    $password = "*****"; //your password
    $sender = "****"; //Your senderid
    $username = urlencode($username);
    $password = urlencode($password);
     $sender = urlencode($sender);
     $messagecontent = $this->input->post('message'); //Type Of Your Message
   $message = urlencode($messagecontent);
   $url="http://****.com/sendsms?uname=".$username."&pwd=".$password."&senderid=".$sender."&to=".$mobiles."&msg=".$message."&route=T";
  $response = curl($url);
</code>```

答:
You have created but not used the $college variable.  Change this:

```<code>if($count == 1){
   $mobiles = implode("" , $college);
} else {
  $mobiles = implode("," , $college);
}
</code>```

to this:

```<code>if($count == 1){
   $mobiles = implode("" , $_POST['college']);
} else {
  $mobiles = implode("," , $_POST['college']);
}
</code>```

Also, if that was really your password, you should change it. :)

Body:
This is my code which is used to send SMS. I could send sms to multiple numbers but when I select one number SMS is not send. So I put an if else condition to check if there is only one number selected, then it should not have comma else it should seperate with commas. but now SMS is not sending to any numbers. What could have gone wrong. Please help me.

      $college = $this->input->post('college');
      $count = count($college);
      if($count == 1){
 $mobiles = implode("" , $_POST['college']);
} else {
$mobiles = implode("," , $_POST['college']);
 }
$data = array(
          'sms_date' => date('Y-m-d H:i:s'),
          'sender' => 'Some Addresss',
          'receiver' => $mobiles,
          'sms_message' => $this->input->post('message')
    );
 function curl($url)
  {
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $url);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
 $data = curl_exec($ch);
 curl_close($ch);
 return $data;
 }
   //$mobile = $mobiles;
    $username = "*****"; //your username
    $password = "*****"; //your password
    $sender = "****"; //Your senderid
    $username = urlencode($username);
    $password = urlencode($password);
     $sender = urlencode($sender);
     $messagecontent = $this->input->post('message'); //Type Of Your Message
   $message = urlencode($messagecontent);
   $url="http://****.com/sendsms?uname=".$username."&pwd=".$password."&senderid=".$sender."&to=".$mobiles."&msg=".$message."&route=T";
  $response = curl($url);

Body:
You have created but not used the $college variable.  Change this:

if($count == 1){
   $mobiles = implode("" , $college);
} else {
  $mobiles = implode("," , $college);
}

to this:

if($count == 1){
   $mobiles = implode("" , $_POST['college']);
} else {
  $mobiles = implode("," , $_POST['college']);
}

Also, if that was really your password, you should change it. :)


问:
Detect very early crashes
An app I published crashes on certain specific devices. I keep receiving messages from the users that just "can't open" the app. This of course lowers the rating on Google Play.

On Android Vitals there's no reference of these crashes, all crashes I receive are managed and happen after the app start, but if I filter for device model or Android version looking for those that tell me that the app didn't open, I find absolutely NOTHING.

I installed crashlytics, and I was astonished by the fact that I received completely different error communications, so Android Vitals seems just partial?
And anyway, still NOTHING about early crashes.

I tried to install the app on the official Samsung online emulator for some devices that are suspected to crash, and still... guess... NOTHING. So I can't even test it and I'm completely helpless.

How can I do to stop this bad app behaviour, that reduces the number of my happy users? I need a really reliable way to detect ALL crashes.

thank you.

答:
Use a Crash Reporting Tool such as Firebase Crash Reporting. Everyone professional uses such tool

https://firebase.google.com/docs/crash/

Title: Detect very early crashes