问:
Trying to get property of non-object Laravel 5.4
Hi Guy's Im always getting an error from laravel 5.4.
Im creating a list of members... but when i use @foreach it says

```<code>ErrorException in 6163a8b030c7474bc8eaad359ab99eb61ebdb127.php line 38:
Trying to get property of non-object (View: E:\wamp64\www\gplspring2017\resources\views\admin\memberlist.blade.php)
</code>```

Here's my controller

```<code>public function listmember(Request $request, $idteam)
{
    $teams = DB::table('gpl_team')->where('gpl_team_id', $idteam)->first();
    $count = count($teams);

    if (!$count) {
        return redirect('404');
    } else {
        return view('/admin/memberlist', ['team' => $teams]);
    }
}
</code>```

and here's my view code:

```<code><table class="table table-striped">
    <tr>
        <td style="width:15%;"></td>
        <td style="width:25%;">Summoners Name</td>
        <td style="width:25%;">Name</td>
        <td style="width:25%;">Role</td>
        <td style="width:10%;"></td>
    </tr>
    <?php
    $qmember = DB::table('team_member')->where('gpl_team_id', $team->gpl_team_id)->first();

    $counting = count($qmember);

    ?>
    @if (! $counting)
    <tr>
        <td colspan="4"> No Recored! </td>
    </tr>
    @else
    @foreach($qmember as $get_member)
    <tr>
        <td><img src="{{ $get_member->member_pic }}" /></td>
        <td></td>
        <td></td>
        <td></td>
        <td>
            <a href="" data-toggle="tooltip" title="Edit Team"><div class="glyphicon glyphicon-pencil"></div></a> |
            <a href="" data-toggle="tooltip" title="Delete Team"><div class="glyphicon glyphicon-trash"></div></a>
        </td>
    </tr>
    @endforeach
    @endif
</table>
</code>```

When i remove the foreach the code is working.. but i try to add the @foreach($qmember as $get_member) it not working anymore...

答:
Check this line:

```<code>$qmember = DB::table('team_member')->where('gpl_team_id', $team->gpl_team_id)->first();
</code>```

when you are using first() then it does not return an Std Class object. If you want it so then use get()

Body:
Hi Guy's Im always getting an error from laravel 5.4.
Im creating a list of members... but when i use @foreach it says

ErrorException in 6163a8b030c7474bc8eaad359ab99eb61ebdb127.php line 38:
Trying to get property of non-object (View: E:\wamp64\www\gplspring2017\resources\views\admin\memberlist.blade.php)

Here's my controller

public function listmember(Request $request, $idteam)
{
    $teams = DB::table('gpl_team')->where('gpl_team_id', $idteam)->first();
    $count = count($teams);

    if (!$count) {
        return redirect('404');
    } else {
        return view('/admin/memberlist', ['team' => $teams]);
    }
}

and here's my view code:

        Summoners Name
        Name
        Role

    <?php
    $qmember = DB::table('team_member')->where('gpl_team_id', $team->gpl_team_id)->first();

    $counting = count($qmember);

    ?>
    @if (! $counting)

         No Recored!

    @else
    @foreach($qmember as $get_member)

        member_pic }}" />

 |

    @endforeach
    @endif

When i remove the foreach the code is working.. but i try to add the @foreach($qmember as $get_member) it not working anymore...

Body:
Check this line:

$qmember = DB::table('team_member')->where('gpl_team_id', $team->gpl_team_id)->first();

when you are using first() then it does not return an Std Class object. If you want it so then use get()


来源: stackexchange

问:
Is it any way possible to do text shadows with current IE9 beta CSS?
So text shadows in FF and Chrome are grate. For example I have simple web page for simple video streaming server.. no shadows in IE9 for me(

my css code is like

```<code>p{color: #000;text-shadow: 0px 1px 1px #fff;padding-bottom:1em}
</code>```

so I wonder - may be there is some JS of special CSS way for creating text shadows for IE?

答:
```<code>filter: Shadow(Color=#666666,
            Direction=135,
            Strength=5);
</code>```

Try this for ie

ContentLicense: CC BY-SA 2.5

Body:
So text shadows in FF and Chrome are grate. For example I have simple web page for simple video streaming server.. no shadows in IE9 for me(

my css code is like

p{color: #000;text-shadow: 0px 1px 1px #fff;padding-bottom:1em}

so I wonder - may be there is some JS of special CSS way for creating text shadows for IE?

Body:
filter: Shadow(Color=#666666,
            Direction=135,
            Strength=5);

Try this for ie


问:
Adding a

```

<p>This action will load a jquery, who loads content in the main index:</p>

```$("#page7").click(function(){
        $('#result').load('./docu2_files/docs/software.html');
       });
```

<p>CSS</p>

```#fixed {
    position: fixed;
    top: 0;
    right: 0;
    width: 200px;
    border: 3px solid black;
    background-color: red;
    color: white;
    text-align: center;
}
```

<p>The script</p>

```<script type="text/javascript">
    var d=new Date()
    var weekday=new Array("Dimanche - Domingo","Lundi - Lunes","Mardi - Martes","Mercredi - Mi?oles","Jeudi - Jueves",
                "Vendredi - Viernes","Samedi S?do")
    document.write("Hoy es: " + weekday[d.getDay()])
</script>
```

答:
The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML.

document.getElementById('fixed').innerHTML = "Hoy es: " + weekday[d.getDay()];

ContentLicense: CC BY-SA 3.0

Title: Adding a <script> to the document causes it not to load the rest of the document

Body:
I have added a script to the document, the script shows the name of the day of the week in French, if I add the script it will not load the whole document, just the result of the script, removing the script content restores the document function.

Update:

This is a HTML document, the users clicks on the menus:

Software

This calls a inner script:

This action will load a jquery, who loads content in the main index:

$("#page7").click(function(){
        $('#result').load('./docu2_files/docs/software.html');
       });

CSS

#fixed {
    position: fixed;
    top: 0;
    right: 0;
    width: 200px;
    border: 3px solid black;
    background-color: red;
    color: white;
    text-align: center;
}

The script


问:
Can Apache Ignite Continuous Queries miss some update?
We are testing Apache Ignite Continuous Queries and during the tests, we have noticed that some continuous queries misses some updates of the cache.
Our use case is the following one:

we have a feeder (that is part of the server nodes) and that feeds 1000 caches with data every seconds

we have a client program (that is part of the server nodes) that opens 1000 continuous queries, 1 continuous query per cache

So, some of these continuous queries misses from times to times few updates of the cache. We were wondering whether the fact that a continuous query misses some updates of the cache was "normal".

We have also performed the test with 500, 250, 100 caches and have the same results.

Besides, we are also wondering how many caches and continuous queries can be created? Does Apache Ignite support hundred thousands of creation of caches and continuous queries?

答:
Got the answer with the Ignite mailing-list (http://apache-ignite-users.70518.x6.nabble.com/Can-a-Continuous-Queries-miss-some-updates-order-td11620.html#a11623):

Continuous Query (CQ) garanties that the order for events will be preserved per entry. For example:

```<code>cache.put(key1, 100);
cache.put(key2, 100);
cache.put(key1, 200);
cache.put(key2, 200);
</code>```

CQ guarantees that for key1 events will be received in the following order (1, 100) --> (1, 200) but you can got event for key2 early than for key1.
  Ignite doesn't have limitation on count of caches and CQ.

Thanks Nikolai Tikhonov!

ContentLicense: CC BY-SA 4.0

Body:
Got the answer with the Ignite mailing-list (http://apache-ignite-users.70518.x6.nabble.com/Can-a-Continuous-Queries-miss-some-updates-order-td11620.html#a11623):

Continuous Query (CQ) garanties that the order for events will be preserved per entry. For example:

cache.put(key1, 100);
cache.put(key2, 100);
cache.put(key1, 200);
cache.put(key2, 200);

CQ guarantees that for key1 events will be received in the following order (1, 100) --> (1, 200) but you can got event for key2 early than for key1.
  Ignite doesn't have limitation on count of caches and CQ.

Thanks Nikolai Tikhonov!


问:
Can't implement javascript in android webview
I have an android webapp and its using a different format from the other webview clients I've been using. However, it doesn't execute javascript which is needed for the file upload button. The default chrome browser can handle the uploads but the previous webview clients cannot, Thats why I chose to use this project.

I will give you the whole MainAvivity.java file.

```import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.NotificationCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

    //Permission variables
    static boolean ASWP_JSCRIPT     = true;     //enable JavaScript for webview
    static boolean ASWP_FUPLOAD     = true;     //upload file from webview
    static boolean ASWP_CAMUPLOAD   = true;     //enable upload from camera for photos
    static boolean ASWP_MULFILE     = false;    //upload multiple files in webview
    static boolean ASWP_LOCATION    = true;     //track GPS locations
    static boolean ASWP_RATINGS     = true;     //show ratings dialog; auto configured, edit method get_rating() for customizations
    static boolean ASWP_PBAR        = true;     //show progress bar in app
    static boolean ASWP_ZOOM        = false;    //zoom in webview
    static boolean ASWP_SFORM       = false;    //save form cache and auto-fill information
    static boolean ASWP_OFFLINE     = true;     //whether the loading webpages are offline or online
    static boolean ASWP_EXTURL      = true;     //open external url with default browser instead of app webview

    //Configuration variables
    private static String ASWV_URL      = "http://example.com"; //complete URL of your website or webpage
    private static String ASWV_F_TYPE   = "*/*";  //to upload any file type using "*/*"; check file type references for more
    public static String ASWV_HOST      = aswm_host(ASWV_URL);

    //Careful with these variable names if altering
    WebView asw_view;
    ProgressBar asw_progress;
    TextView asw_loading_text;
    NotificationManager asw_notification;
    Notification asw_notification_new;

    private String asw_cam_message;
    private ValueCallback<Uri> asw_file_message;
    private ValueCallback<Uri[]> asw_file_path;
    private final static int asw_file_req = 1;

    private final static int loc_perm = 1;
    private final static int file_perm = 2;

    private SecureRandom random = new SecureRandom();

    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (Build.VERSION.SDK_INT >= 21) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimary));
            Uri[] results = null;
            if (resultCode == Activity.RESULT_OK) {
                if (requestCode == asw_file_req) {
                    if (null == asw_file_path) {
                        return;
                    }
                    if (intent == null) {
                        if (asw_cam_message != null) {
                            results = new Uri[]{Uri.parse(asw_cam_message)};
                        }
                    } else {
                        String dataString = intent.getDataString();
                        if (dataString != null) {
                            results = new Uri[]{ Uri.parse(dataString) };
                        }
                    }
                }
            }
            asw_file_path.onReceiveValue(results);
            asw_file_path = null;
        } else {
            if (requestCode == asw_file_req) {
                if (null == asw_file_message) return;
                Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
                asw_file_message.onReceiveValue(result);
                asw_file_message = null;
            }
        }
    }

    @SuppressLint({"SetJavaScriptEnabled", "WrongViewCast"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (ASWP_PBAR) {
            asw_progress = (ProgressBar) findViewById(R.id.msw_progress);
        } else {
            findViewById(R.id.msw_progress).setVisibility(View.GONE);
        }
        asw_loading_text = (TextView) findViewById(R.id.msw_loading_text);
        Handler handler = new Handler();

        //Launching app rating request
        if (ASWP_RATINGS) {
            handler.postDelayed(new Runnable() { public void run() { get_rating(); }}, 1000 * 60); //running request after few moments
        }

        //Getting basic device information
        get_info();

        //Getting GPS location of device if given permission
        get_location();

        asw_view = (WebView) findViewById(R.id.msw_view);

        //Webview settings; defaults are customized for best performance
        WebSettings webSettings = asw_view.getSettings();

        if(!ASWP_OFFLINE){
            webSettings.setJavaScriptEnabled(ASWP_JSCRIPT);
        }
        webSettings.setSaveFormData(ASWP_SFORM);
        webSettings.setSupportZoom(ASWP_ZOOM);
        webSettings.setGeolocationEnabled(ASWP_LOCATION);
        webSettings.setAllowFileAccess(true);
        webSettings.setAllowFileAccessFromFileURLs(true);
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);

        if (Build.VERSION.SDK_INT >= 21) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
            asw_view.setLayerType(View.LAYER_TYPE_HARDWARE, null);
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        } else if (Build.VERSION.SDK_INT >= 19) {
            asw_view.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        } else if (Build.VERSION.SDK_INT >= 16 && Build.VERSION.SDK_INT < 19) {
            asw_view.requestFocus();
            asw_view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
        asw_view.setVerticalScrollBarEnabled(false);
        asw_view.setWebViewClient(new Callback());

        //Rendering the default URL
        aswm_view(ASWV_URL, false);

        asw_view.setWebChromeClient(new WebChromeClient() {
            //Handling input[type="file"] requests for android API 16+
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
                if(ASWP_FUPLOAD) {
                    asw_file_message = uploadMsg;
                    Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                    i.addCategory(Intent.CATEGORY_OPENABLE);
                    i.setType(ASWV_F_TYPE);
                    startActivityForResult(Intent.createChooser(i, "File Chooser"), asw_file_req);
                }
            }
            //Handling input[type="file"] requests for android API 21+
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,WebChromeClient.FileChooserParams fileChooserParams){
                get_file();
                if(ASWP_FUPLOAD) {
                    if (asw_file_path != null) {
                        asw_file_path.onReceiveValue(null);
                    }
                    asw_file_path = filePathCallback;
                    Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
                    contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
                    contentSelectionIntent.setType(ASWV_F_TYPE);
                    Intent[] intentArray;
                    if (ASWP_CAMUPLOAD) {
                        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        if (takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null) {
                            File photoFile = null;
                            try {
                                photoFile = create_image();
                                takePictureIntent.putExtra("PhotoPath", asw_cam_message);
                            } catch (IOException ex) {
                                Log.e(TAG, "Image file creation failed", ex);
                            }
                            if (photoFile != null) {
                                asw_cam_message = "file:" + photoFile.getAbsolutePath();
                                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                            } else {
                                takePictureIntent = null;
                            }
                        }
                        if (takePictureIntent != null) {
                            intentArray = new Intent[]{takePictureIntent};
                        } else {
                            intentArray = new Intent[0];
                        }
                    } else {
                        intentArray = new Intent[0];
                    }
                    Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
                    chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
                    chooserIntent.putExtra(Intent.EXTRA_TITLE, "File Chooser");
                    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
                    startActivityForResult(chooserIntent, asw_file_req);
                }
                return true;
            }

            //Getting webview rendering progress
            @Override
            public void onProgressChanged(WebView view, int p) {
                if (ASWP_PBAR) {
                    asw_progress.setProgress(p);
                    if (p == 100) {
                        asw_progress.setProgress(0);
                    }
                }
            }
        });
        if (getIntent().getData() != null) {
            String path     = getIntent().getDataString();
            /*
            If you want to check or use specific directories or schemes or hosts

            Uri data        = getIntent().getData();
            String scheme   = data.getScheme();
            String host     = data.getHost();
            List<String> pr = data.getPathSegments();
            String param1   = pr.get(0);
            */
            aswm_view(path, false);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //Coloring the "recent apps" tab header; doing it onResume, as an insurance
        if (Build.VERSION.SDK_INT >= 23) {
            Bitmap bm = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
            ActivityManager.TaskDescription taskDesc = null;
            taskDesc = new ActivityManager.TaskDescription(getString(R.string.app_name), bm, getColor(R.color.colorPrimary));
            MainActivity.this.setTaskDescription(taskDesc);
        }
        get_location();
    }

    //Setting activity layout visibility
    private class Callback extends WebViewClient {
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            get_location();
        }

        public void onPageFinished(WebView view, String url) {
            findViewById(R.id.msw_welcome).setVisibility(View.GONE);
            findViewById(R.id.msw_view).setVisibility(View.VISIBLE);
        }
        //For android below API 23
        @SuppressWarnings("deprecation")
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            Toast.makeText(getApplicationContext(), "Something Went Wrong!", Toast.LENGTH_SHORT).show();
            aswm_view("file:///android_res/raw/error.html", false);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            Toast.makeText(getApplicationContext(), "Something Went Wrong!", Toast.LENGTH_SHORT).show();
            aswm_view("file:///android_res/raw/error.html", false);
        }

        //Overriding webview URLs
        @SuppressWarnings("deprecation")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return url_actions(view, url);
        }

        //Overriding webview URLs for API 23+ [suggested by github.com/JakePou]
        @TargetApi(Build.VERSION_CODES.N)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return url_actions(view, request.getUrl().toString());
        }
    }

    //Random ID creation function to help get fresh cache every-time webview reloaded
    public String random_id() {
        return new BigInteger(130, random).toString(32);
    }

    //Opening URLs inside webview with request
    void aswm_view(String url, Boolean tab) {
        if (tab) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(url));
            startActivity(intent);
        } else {
            asw_view.loadUrl(url+"?rid="+random_id());
        }
    }

    //Actions based on shouldOverrideUrlLoading
    public boolean url_actions(WebView view, String url){
        boolean a = true;
        //Show toast error if not connected to the network
        if (!ASWP_OFFLINE && !DetectConnection.isInternetAvailable(MainActivity.this)) {
            Toast.makeText(getApplicationContext(), "Please check your Network Connection!", Toast.LENGTH_SHORT).show();

            //Use this in a hyperlink to redirect back to default URL :: href="refresh:android"
        } else if (url.startsWith("refresh:")) {
            aswm_view(ASWV_URL, false);

            //Use this in a hyperlink to launch default phone dialer for specific number :: href="tel:+919876543210"
        } else if (url.startsWith("tel:")) {
            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
            startActivity(intent);

            //Use this to open your apps page on google play store app :: href="rate:android"
        } else if (url.startsWith("rate:")) {
            final String app_package = getPackageName(); //requesting app package name from Context or Activity object
            try {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + app_package)));
            } catch (ActivityNotFoundException anfe) {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + app_package)));
            }

            //Sharing content from your webview to external apps :: href="share:URL" and remember to place the URL you want to share after share:___
        } else if (url.startsWith("share:")) {
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_SUBJECT, view.getTitle());
            intent.putExtra(Intent.EXTRA_TEXT, view.getTitle()+"\nVisit: "+(Uri.parse(url).toString()).replace("share:",""));
            startActivity(Intent.createChooser(intent, "Share with your Friends"));

            //Use this in a hyperlink to exit your app :: href="exit:android"
        } else if (url.startsWith("exit:")) {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);

            //Opening external URLs in android default web browser
        } else if (ASWP_EXTURL && aswm_host(ASWV_URL)!=ASWV_HOST) {
            aswm_view(url,true);

        } else {
            a = false;
        }
        return a;
    }

    //Getting host name
    public static String aswm_host(String url){
        if (url == null || url.length() == 0) {
            return "";
        }
        int dslash = url.indexOf("//");
        if (dslash == -1) {
            dslash = 0;
        } else {
            dslash += 2;
        }
        int end = url.indexOf('/', dslash);
        end = end >= 0 ? end : url.length();
        int port = url.indexOf(':', dslash);
        end = (port > 0 && port < end) ? port : end;
        Log.w("URL Host: ",url.substring(dslash, end));
        return url.substring(dslash, end);
    }

    //Getting device basic information
    public void get_info(){
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.setCookie(ASWV_URL, "DEVICE=android");
        cookieManager.setCookie(ASWV_URL, "DEV_API=" + Build.VERSION.SDK_INT);
    }

    //Checking permission for storage and camera for writing and uploading images
    public void get_file(){
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};

        //Checking for storage permission to write images for upload
        if (ASWP_FUPLOAD && ASWP_CAMUPLOAD && !check_permission(2) && !check_permission(3)) {
            ActivityCompat.requestPermissions(MainActivity.this, perms, file_perm);

        //Checking for WRITE_EXTERNAL_STORAGE permission
        } else if (ASWP_FUPLOAD && !check_permission(2)) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, file_perm);

        //Checking for CAMERA permissions
        } else if (ASWP_CAMUPLOAD && !check_permission(3)) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, file_perm);
        }
    }

    //Using cookies to update user locations
    public void get_location(){
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        if(ASWP_LOCATION) {
            //Checking for location permissions
            if (Build.VERSION.SDK_INT >= 23 && !check_permission(1)) {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, loc_perm);
                show_notification(2, 2);

            } else {
                GPSTrack gps;
                gps = new GPSTrack(MainActivity.this);
                double latitude = gps.getLatitude();
                double longitude = gps.getLongitude();
                if (gps.canGetLocation()) {
                    if (latitude != 0 || longitude != 0) {
                        cookieManager.setCookie(ASWV_URL, "lat=" + latitude);
                        cookieManager.setCookie(ASWV_URL, "long=" + longitude);
                        //Log.w("New Updated Location:", latitude + "," + longitude);  //enable to test dummy latitude and longitude
                    } else {
                        Log.w("New Updated Location:", "NULL");
                    }
                } else {
                    show_notification(1, 1);
                    Log.w("New Updated Location:", "FAIL");
                }
            }
        }
    }

    //Checking if particular permission is given or not
    public boolean check_permission(int permission){
        switch(permission){
            case 1:
                return ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;

            case 2:
                return ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;

            case 3:
                return ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;

        }
        return false;
    }

    //Creating image file for upload
    private File create_image() throws IOException {
        @SuppressLint("SimpleDateFormat")
        String file_name    = new SimpleDateFormat("yyyy_mm_ss").format(new Date());
        String new_name     = "file_"+file_name+"_";
        File sd_directory   = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        return File.createTempFile(new_name, ".jpg", sd_directory);
    }

    //Launching app rating dialoge [developed by github.com/hotchemi]
    public void get_rating() {
        if (DetectConnection.isInternetAvailable(MainActivity.this)) {
            AppRate.with(this)
                .setStoreType(StoreType.GOOGLEPLAY)     //default is Google Play, other option is Amazon App Store
                .setInstallDays(3)                      //after how many days would you like to show the dialoge
                .setLaunchTimes(10)                     //overall request launch times being ignored
                .setRemindInterval(2)                   //reminding users to rate after days interval
                .setTitle(R.string.rate_dialog_title)
                .setMessage(R.string.rate_dialog_message)
                .setTextLater(R.string.rate_dialog_cancel)
                .setTextNever(R.string.rate_dialog_no)
                .setTextRateNow(R.string.rate_dialog_ok)
                .monitor();
            AppRate.showRateDialogIfMeetsConditions(this);
        }
        //for more customizations, edit AppRate and DialogOptions
    }

    //Creating custom notifications with IDs
    public void show_notification(int type, int id) {
        long when = System.currentTimeMillis();
        asw_notification = (NotificationManager) MainActivity.this.getSystemService(Context.NOTIFICATION_SERVICE);
        Intent i = new Intent();
        if (type == 1) {
            i.setClass(MainActivity.this, MainActivity.class);
        } else if (type == 2) {
            i.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        } else {
            i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            i.addCategory(Intent.CATEGORY_DEFAULT);
            i.setData(Uri.parse("package:" + MainActivity.this.getPackageName()));
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        }
        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(MainActivity.this);
        switch(type){
            case 1:
                builder.setTicker(getString(R.string.app_name));
                builder.setContentTitle(getString(R.string.loc_fail));
                builder.setContentText(getString(R.string.loc_fail_text));
                builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getString(R.string.loc_fail_more)));
                builder.setVibrate(new long[]{350,350,350,350,350});
                builder.setSmallIcon(R.mipmap.ic_launcher);
            break;

            case 2:
                builder.setTicker(getString(R.string.app_name));
                builder.setContentTitle(getString(R.string.app_name));
                builder.setContentText(getString(R.string.loc_perm_text));
                builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getString(R.string.loc_perm_more)));
                builder.setVibrate(new long[]{350, 700, 350, 700, 350});
                builder.setSound(alarmSound);
                builder.setSmallIcon(R.mipmap.ic_launcher);
            break;
        }
        builder.setOngoing(false);
        builder.setAutoCancel(true);
        builder.setContentIntent(pendingIntent);
        builder.setWhen(when);
        builder.setContentIntent(pendingIntent);
        asw_notification_new = builder.getNotification();
        asw_notification.notify(id, asw_notification_new);
    }

    //Checking if users allowed the requested permissions or not
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults){
        switch (requestCode){
            case 1: {
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    get_location();
                }else{
                    show_notification(2, 2);
                    Toast.makeText(MainActivity.this, R.string.loc_req, Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    //Action on back key tap/click
    @Override
    public boolean onKeyDown(int keyCode, @NonNull KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (keyCode) {
                case KeyEvent.KEYCODE_BACK:
                    if (asw_view.canGoBack()) {
                        asw_view.goBack();
                    } else {
                        finish();
                    }
                    return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

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

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState ){
        super.onSaveInstanceState(outState);
        asw_view.saveState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState){
        super.onRestoreInstanceState(savedInstanceState);
        asw_view.restoreState(savedInstanceState);
    }
}
```

答:
This is a full solution for all android versions, I had a hard time with this too.

```<code>public class MyWb extends Activity {
/** Called when the activity is first created. */

WebView web;
ProgressBar progressBar;

private ValueCallback<Uri> mUploadMessage;
 private final static int FILECHOOSER_RESULTCODE=1;

 @Override
 protected void onActivityResult(int requestCode, int resultCode,
                                    Intent intent) {
  if(requestCode==FILECHOOSER_RESULTCODE)
  {
   if (null == mUploadMessage) return;
            Uri result = intent == null || resultCode != RESULT_OK ? null
                    : intent.getData();
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
  }
  }

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    web = (WebView) findViewById(R.id.webview01);
    progressBar = (ProgressBar) findViewById(R.id.progressBar1);

    web = new WebView(this);
    web.getSettings().setJavaScriptEnabled(true);
    web.loadUrl("http://www.script-tutorials.com/demos/199/index.html");
    web.setWebViewClient(new myWebClient());
    web.setWebChromeClient(new WebChromeClient()
    {
           //The undocumented magic method override
           //Eclipse will swear at you if you try to put @Override here
        // For Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {

            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            MyWb.this.startActivityForResult(Intent.createChooser(i,"File Chooser"), FILECHOOSER_RESULTCODE);

           }

        // For Android 3.0+
           public void openFileChooser( ValueCallback uploadMsg, String acceptType ) {
           mUploadMessage = uploadMsg;
           Intent i = new Intent(Intent.ACTION_GET_CONTENT);
           i.addCategory(Intent.CATEGORY_OPENABLE);
           i.setType("*/*");
           MyWb.this.startActivityForResult(
           Intent.createChooser(i, "File Browser"),
           FILECHOOSER_RESULTCODE);
           }

        //For Android 4.1
           public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
               mUploadMessage = uploadMsg;
               Intent i = new Intent(Intent.ACTION_GET_CONTENT);
               i.addCategory(Intent.CATEGORY_OPENABLE);
               i.setType("image/*");
               MyWb.this.startActivityForResult( Intent.createChooser( i, "File Chooser" ), MyWb.FILECHOOSER_RESULTCODE );

           }

    });

    setContentView(web);

}

public class myWebClient extends WebViewClient
{
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        // TODO Auto-generated method stub
        super.onPageStarted(view, url, favicon);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // TODO Auto-generated method stub

        view.loadUrl(url);
        return true;

    }

    @Override
    public void onPageFinished(WebView view, String url) {
        // TODO Auto-generated method stub
        super.onPageFinished(view, url);

        progressBar.setVisibility(View.GONE);
    }
}

//flipscreen not loading again
@Override
public void onConfigurationChanged(Configuration newConfig){
    super.onConfigurationChanged(newConfig);
}

// To handle "Back" key press event for WebView to go back to previous screen.
/*@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if ((keyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) {
        web.goBack();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}*/
}
</code>```

Also I want to add that the "upload page" like the one in this example, wont work on < 4 versions, since it has an image preview feature, if you want to make it work use a simple php upload without preview.

Update:

Please find the solution for lollipop devices here and thanks for gauntface

Update 2:

Found complete solution for all android devices including marshmallow here see its github project for more.

Body:
I have an android webapp and its using a different format from the other webview clients I've been using. However, it doesn't execute javascript which is needed for the file upload button. The default chrome browser can handle the uploads but the previous webview clients cannot, Thats why I chose to use this project.

I will give you the whole MainAvivity.java file.

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.NotificationCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

    //Permission variables
    static boolean ASWP_JSCRIPT     = true;     //enable JavaScript for webview
    static boolean ASWP_FUPLOAD     = true;     //upload file from webview
    static boolean ASWP_CAMUPLOAD   = true;     //enable upload from camera for photos
    static boolean ASWP_MULFILE     = false;    //upload multiple files in webview
    static boolean ASWP_LOCATION    = true;     //track GPS locations
    static boolean ASWP_RATINGS     = true;     //show ratings dialog; auto configured, edit method get_rating() for customizations
    static boolean ASWP_PBAR        = true;     //show progress bar in app
    static boolean ASWP_ZOOM        = false;    //zoom in webview
    static boolean ASWP_SFORM       = false;    //save form cache and auto-fill information
    static boolean ASWP_OFFLINE     = true;     //whether the loading webpages are offline or online
    static boolean ASWP_EXTURL      = true;     //open external url with default browser instead of app webview

    //Configuration variables
    private static String ASWV_URL      = "http://example.com"; //complete URL of your website or webpage
    private static String ASWV_F_TYPE   = "*/*";  //to upload any file type using "*/*"; check file type references for more
    public static String ASWV_HOST      = aswm_host(ASWV_URL);

    //Careful with these variable names if altering
    WebView asw_view;
    ProgressBar asw_progress;
    TextView asw_loading_text;
    NotificationManager asw_notification;
    Notification asw_notification_new;

    private String asw_cam_message;
    private ValueCallback<Uri> asw_file_message;
    private ValueCallback<Uri[]> asw_file_path;
    private final static int asw_file_req = 1;

    private final static int loc_perm = 1;
    private final static int file_perm = 2;

    private SecureRandom random = new SecureRandom();

    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (Build.VERSION.SDK_INT >= 21) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimary));
            Uri[] results = null;
            if (resultCode == Activity.RESULT_OK) {
                if (requestCode == asw_file_req) {
                    if (null == asw_file_path) {
                        return;
                    }
                    if (intent == null) {
                        if (asw_cam_message != null) {
                            results = new Uri[]{Uri.parse(asw_cam_message)};
                        }
                    } else {
                        String dataString = intent.getDataString();
                        if (dataString != null) {
                            results = new Uri[]{ Uri.parse(dataString) };
                        }
                    }
                }
            }
            asw_file_path.onReceiveValue(results);
            asw_file_path = null;
        } else {
            if (requestCode == asw_file_req) {
                if (null == asw_file_message) return;
                Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
                asw_file_message.onReceiveValue(result);
                asw_file_message = null;
            }
        }
    }

    @SuppressLint({"SetJavaScriptEnabled", "WrongViewCast"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (ASWP_PBAR) {
            asw_progress = (ProgressBar) findViewById(R.id.msw_progress);
        } else {
            findViewById(R.id.msw_progress).setVisibility(View.GONE);
        }
        asw_loading_text = (TextView) findViewById(R.id.msw_loading_text);
        Handler handler = new Handler();

        //Launching app rating request
        if (ASWP_RATINGS) {
            handler.postDelayed(new Runnable() { public void run() { get_rating(); }}, 1000 * 60); //running request after few moments
        }

        //Getting basic device information
        get_info();

        //Getting GPS location of device if given permission
        get_location();

        asw_view = (WebView) findViewById(R.id.msw_view);

        //Webview settings; defaults are customized for best performance
        WebSettings webSettings = asw_view.getSettings();

        if(!ASWP_OFFLINE){
            webSettings.setJavaScriptEnabled(ASWP_JSCRIPT);
        }
        webSettings.setSaveFormData(ASWP_SFORM);
        webSettings.setSupportZoom(ASWP_ZOOM);
        webSettings.setGeolocationEnabled(ASWP_LOCATION);
        webSettings.setAllowFileAccess(true);
        webSettings.setAllowFileAccessFromFileURLs(true);
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);

        if (Build.VERSION.SDK_INT >= 21) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
            asw_view.setLayerType(View.LAYER_TYPE_HARDWARE, null);
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        } else if (Build.VERSION.SDK_INT >= 19) {
            asw_view.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        } else if (Build.VERSION.SDK_INT >= 16 && Build.VERSION.SDK_INT < 19) {
            asw_view.requestFocus();
            asw_view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
        asw_view.setVerticalScrollBarEnabled(false);
        asw_view.setWebViewClient(new Callback());

        //Rendering the default URL
        aswm_view(ASWV_URL, false);

        asw_view.setWebChromeClient(new WebChromeClient() {
            //Handling input[type="file"] requests for android API 16+
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
                if(ASWP_FUPLOAD) {
                    asw_file_message = uploadMsg;
                    Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                    i.addCategory(Intent.CATEGORY_OPENABLE);
                    i.setType(ASWV_F_TYPE);
                    startActivityForResult(Intent.createChooser(i, "File Chooser"), asw_file_req);
                }
            }
            //Handling input[type="file"] requests for android API 21+
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,WebChromeClient.FileChooserParams fileChooserParams){
                get_file();
                if(ASWP_FUPLOAD) {
                    if (asw_file_path != null) {
                        asw_file_path.onReceiveValue(null);
                    }
                    asw_file_path = filePathCallback;
                    Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
                    contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
                    contentSelectionIntent.setType(ASWV_F_TYPE);
                    Intent[] intentArray;
                    if (ASWP_CAMUPLOAD) {
                        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        if (takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null) {
                            File photoFile = null;
                            try {
                                photoFile = create_image();
                                takePictureIntent.putExtra("PhotoPath", asw_cam_message);
                            } catch (IOException ex) {
                                Log.e(TAG, "Image file creation failed", ex);
                            }
                            if (photoFile != null) {
                                asw_cam_message = "file:" + photoFile.getAbsolutePath();
                                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                            } else {
                                takePictureIntent = null;
                            }
                        }
                        if (takePictureIntent != null) {
                            intentArray = new Intent[]{takePictureIntent};
                        } else {
                            intentArray = new Intent[0];
                        }
                    } else {
                        intentArray = new Intent[0];
                    }
                    Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
                    chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
                    chooserIntent.putExtra(Intent.EXTRA_TITLE, "File Chooser");
                    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
                    startActivityForResult(chooserIntent, asw_file_req);
                }
                return true;
            }

            //Getting webview rendering progress
            @Override
            public void onProgressChanged(WebView view, int p) {
                if (ASWP_PBAR) {
                    asw_progress.setProgress(p);
                    if (p == 100) {
                        asw_progress.setProgress(0);
                    }
                }
            }
        });
        if (getIntent().getData() != null) {
            String path     = getIntent().getDataString();
            /*
            If you want to check or use specific directories or schemes or hosts

            Uri data        = getIntent().getData();
            String scheme   = data.getScheme();
            String host     = data.getHost();
            List<String> pr = data.getPathSegments();
            String param1   = pr.get(0);
            */
            aswm_view(path, false);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //Coloring the "recent apps" tab header; doing it onResume, as an insurance
        if (Build.VERSION.SDK_INT >= 23) {
            Bitmap bm = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
            ActivityManager.TaskDescription taskDesc = null;
            taskDesc = new ActivityManager.TaskDescription(getString(R.string.app_name), bm, getColor(R.color.colorPrimary));
            MainActivity.this.setTaskDescription(taskDesc);
        }
        get_location();
    }

    //Setting activity layout visibility
    private class Callback extends WebViewClient {
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            get_location();
        }

        public void onPageFinished(WebView view, String url) {
            findViewById(R.id.msw_welcome).setVisibility(View.GONE);
            findViewById(R.id.msw_view).setVisibility(View.VISIBLE);
        }
        //For android below API 23
        @SuppressWarnings("deprecation")
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            Toast.makeText(getApplicationContext(), "Something Went Wrong!", Toast.LENGTH_SHORT).show();
            aswm_view("file:///android_res/raw/error.html", false);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            Toast.makeText(getApplicationContext(), "Something Went Wrong!", Toast.LENGTH_SHORT).show();
            aswm_view("file:///android_res/raw/error.html", false);
        }

        //Overriding webview URLs
        @SuppressWarnings("deprecation")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return url_actions(view, url);
        }

        //Overriding webview URLs for API 23+ [suggested by github.com/JakePou]
        @TargetApi(Build.VERSION_CODES.N)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return url_actions(view, request.getUrl().toString());
        }
    }

    //Random ID creation function to help get fresh cache every-time webview reloaded
    public String random_id() {
        return new BigInteger(130, random).toString(32);
    }

    //Opening URLs inside webview with request
    void aswm_view(String url, Boolean tab) {
        if (tab) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(url));
            startActivity(intent);
        } else {
            asw_view.loadUrl(url+"?rid="+random_id());
        }
    }

    //Actions based on shouldOverrideUrlLoading
    public boolean url_actions(WebView view, String url){
        boolean a = true;
        //Show toast error if not connected to the network
        if (!ASWP_OFFLINE && !DetectConnection.isInternetAvailable(MainActivity.this)) {
            Toast.makeText(getApplicationContext(), "Please check your Network Connection!", Toast.LENGTH_SHORT).show();

            //Use this in a hyperlink to redirect back to default URL :: href="refresh:android"
        } else if (url.startsWith("refresh:")) {
            aswm_view(ASWV_URL, false);

            //Use this in a hyperlink to launch default phone dialer for specific number :: href="tel:+919876543210"
        } else if (url.startsWith("tel:")) {
            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
            startActivity(intent);

            //Use this to open your apps page on google play store app :: href="rate:android"
        } else if (url.startsWith("rate:")) {
            final String app_package = getPackageName(); //requesting app package name from Context or Activity object
            try {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + app_package)));
            } catch (ActivityNotFoundException anfe) {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + app_package)));
            }

            //Sharing content from your webview to external apps :: href="share:URL" and remember to place the URL you want to share after share:___
        } else if (url.startsWith("share:")) {
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_SUBJECT, view.getTitle());
            intent.putExtra(Intent.EXTRA_TEXT, view.getTitle()+"\nVisit: "+(Uri.parse(url).toString()).replace("share:",""));
            startActivity(Intent.createChooser(intent, "Share with your Friends"));

            //Use this in a hyperlink to exit your app :: href="exit:android"
        } else if (url.startsWith("exit:")) {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);

            //Opening external URLs in android default web browser
        } else if (ASWP_EXTURL && aswm_host(ASWV_URL)!=ASWV_HOST) {
            aswm_view(url,true);

        } else {
            a = false;
        }
        return a;
    }

    //Getting host name
    public static String aswm_host(String url){
        if (url == null || url.length() == 0) {
            return "";
        }
        int dslash = url.indexOf("//");
        if (dslash == -1) {
            dslash = 0;
        } else {
            dslash += 2;
        }
        int end = url.indexOf('/', dslash);
        end = end >= 0 ? end : url.length();
        int port = url.indexOf(':', dslash);
        end = (port > 0 && port < end) ? port : end;
        Log.w("URL Host: ",url.substring(dslash, end));
        return url.substring(dslash, end);
    }

    //Getting device basic information
    public void get_info(){
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.setCookie(ASWV_URL, "DEVICE=android");
        cookieManager.setCookie(ASWV_URL, "DEV_API=" + Build.VERSION.SDK_INT);
    }

    //Checking permission for storage and camera for writing and uploading images
    public void get_file(){
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};

        //Checking for storage permission to write images for upload
        if (ASWP_FUPLOAD && ASWP_CAMUPLOAD && !check_permission(2) && !check_permission(3)) {
            ActivityCompat.requestPermissions(MainActivity.this, perms, file_perm);

        //Checking for WRITE_EXTERNAL_STORAGE permission
        } else if (ASWP_FUPLOAD && !check_permission(2)) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, file_perm);

        //Checking for CAMERA permissions
        } else if (ASWP_CAMUPLOAD && !check_permission(3)) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, file_perm);
        }
    }

    //Using cookies to update user locations
    public void get_location(){
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        if(ASWP_LOCATION) {
            //Checking for location permissions
            if (Build.VERSION.SDK_INT >= 23 && !check_permission(1)) {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, loc_perm);
                show_notification(2, 2);

            } else {
                GPSTrack gps;
                gps = new GPSTrack(MainActivity.this);
                double latitude = gps.getLatitude();
                double longitude = gps.getLongitude();
                if (gps.canGetLocation()) {
                    if (latitude != 0 || longitude != 0) {
                        cookieManager.setCookie(ASWV_URL, "lat=" + latitude);
                        cookieManager.setCookie(ASWV_URL, "long=" + longitude);
                        //Log.w("New Updated Location:", latitude + "," + longitude);  //enable to test dummy latitude and longitude
                    } else {
                        Log.w("New Updated Location:", "NULL");
                    }
                } else {
                    show_notification(1, 1);
                    Log.w("New Updated Location:", "FAIL");
                }
            }
        }
    }

    //Checking if particular permission is given or not
    public boolean check_permission(int permission){
        switch(permission){
            case 1:
                return ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;

            case 2:
                return ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;

            case 3:
                return ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;

        }
        return false;
    }

    //Creating image file for upload
    private File create_image() throws IOException {
        @SuppressLint("SimpleDateFormat")
        String file_name    = new SimpleDateFormat("yyyy_mm_ss").format(new Date());
        String new_name     = "file_"+file_name+"_";
        File sd_directory   = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        return File.createTempFile(new_name, ".jpg", sd_directory);
    }

    //Launching app rating dialoge [developed by github.com/hotchemi]
    public void get_rating() {
        if (DetectConnection.isInternetAvailable(MainActivity.this)) {
            AppRate.with(this)
                .setStoreType(StoreType.GOOGLEPLAY)     //default is Google Play, other option is Amazon App Store
                .setInstallDays(3)                      //after how many days would you like to show the dialoge
                .setLaunchTimes(10)                     //overall request launch times being ignored
                .setRemindInterval(2)                   //reminding users to rate after days interval
                .setTitle(R.string.rate_dialog_title)
                .setMessage(R.string.rate_dialog_message)
                .setTextLater(R.string.rate_dialog_cancel)
                .setTextNever(R.string.rate_dialog_no)
                .setTextRateNow(R.string.rate_dialog_ok)
                .monitor();
            AppRate.showRateDialogIfMeetsConditions(this);
        }
        //for more customizations, edit AppRate and DialogOptions
    }

    //Creating custom notifications with IDs
    public void show_notification(int type, int id) {
        long when = System.currentTimeMillis();
        asw_notification = (NotificationManager) MainActivity.this.getSystemService(Context.NOTIFICATION_SERVICE);
        Intent i = new Intent();
        if (type == 1) {
            i.setClass(MainActivity.this, MainActivity.class);
        } else if (type == 2) {
            i.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        } else {
            i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            i.addCategory(Intent.CATEGORY_DEFAULT);
            i.setData(Uri.parse("package:" + MainActivity.this.getPackageName()));
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        }
        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(MainActivity.this);
        switch(type){
            case 1:
                builder.setTicker(getString(R.string.app_name));
                builder.setContentTitle(getString(R.string.loc_fail));
                builder.setContentText(getString(R.string.loc_fail_text));
                builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getString(R.string.loc_fail_more)));
                builder.setVibrate(new long[]{350,350,350,350,350});
                builder.setSmallIcon(R.mipmap.ic_launcher);
            break;

            case 2:
                builder.setTicker(getString(R.string.app_name));
                builder.setContentTitle(getString(R.string.app_name));
                builder.setContentText(getString(R.string.loc_perm_text));
                builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getString(R.string.loc_perm_more)));
                builder.setVibrate(new long[]{350, 700, 350, 700, 350});
                builder.setSound(alarmSound);
                builder.setSmallIcon(R.mipmap.ic_launcher);
            break;
        }
        builder.setOngoing(false);
        builder.setAutoCancel(true);
        builder.setContentIntent(pendingIntent);
        builder.setWhen(when);
        builder.setContentIntent(pendingIntent);
        asw_notification_new = builder.getNotification();
        asw_notification.notify(id, asw_notification_new);
    }

    //Checking if users allowed the requested permissions or not
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults){
        switch (requestCode){
            case 1: {
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    get_location();
                }else{
                    show_notification(2, 2);
                    Toast.makeText(MainActivity.this, R.string.loc_req, Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    //Action on back key tap/click
    @Override
    public boolean onKeyDown(int keyCode, @NonNull KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (keyCode) {
                case KeyEvent.KEYCODE_BACK:
                    if (asw_view.canGoBack()) {
                        asw_view.goBack();
                    } else {
                        finish();
                    }
                    return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

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

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState ){
        super.onSaveInstanceState(outState);
        asw_view.saveState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState){
        super.onRestoreInstanceState(savedInstanceState);
        asw_view.restoreState(savedInstanceState);
    }
}

Body:
This is a full solution for all android versions, I had a hard time with this too.

public class MyWb extends Activity {
/** Called when the activity is first created. */

WebView web;
ProgressBar progressBar;

private ValueCallback<Uri> mUploadMessage;
 private final static int FILECHOOSER_RESULTCODE=1;

 @Override
 protected void onActivityResult(int requestCode, int resultCode,
                                    Intent intent) {
  if(requestCode==FILECHOOSER_RESULTCODE)
  {
   if (null == mUploadMessage) return;
            Uri result = intent == null || resultCode != RESULT_OK ? null
                    : intent.getData();
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
  }
  }

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    web = (WebView) findViewById(R.id.webview01);
    progressBar = (ProgressBar) findViewById(R.id.progressBar1);

    web = new WebView(this);
    web.getSettings().setJavaScriptEnabled(true);
    web.loadUrl("http://www.script-tutorials.com/demos/199/index.html");
    web.setWebViewClient(new myWebClient());
    web.setWebChromeClient(new WebChromeClient()
    {
           //The undocumented magic method override
           //Eclipse will swear at you if you try to put @Override here
        // For Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {

            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            MyWb.this.startActivityForResult(Intent.createChooser(i,"File Chooser"), FILECHOOSER_RESULTCODE);

           }

        // For Android 3.0+
           public void openFileChooser( ValueCallback uploadMsg, String acceptType ) {
           mUploadMessage = uploadMsg;
           Intent i = new Intent(Intent.ACTION_GET_CONTENT);
           i.addCategory(Intent.CATEGORY_OPENABLE);
           i.setType("*/*");
           MyWb.this.startActivityForResult(
           Intent.createChooser(i, "File Browser"),
           FILECHOOSER_RESULTCODE);
           }

        //For Android 4.1
           public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
               mUploadMessage = uploadMsg;
               Intent i = new Intent(Intent.ACTION_GET_CONTENT);
               i.addCategory(Intent.CATEGORY_OPENABLE);
               i.setType("image/*");
               MyWb.this.startActivityForResult( Intent.createChooser( i, "File Chooser" ), MyWb.FILECHOOSER_RESULTCODE );

           }

    });

    setContentView(web);

}

public class myWebClient extends WebViewClient
{
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        // TODO Auto-generated method stub
        super.onPageStarted(view, url, favicon);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // TODO Auto-generated method stub

        view.loadUrl(url);
        return true;

    }

    @Override
    public void onPageFinished(WebView view, String url) {
        // TODO Auto-generated method stub
        super.onPageFinished(view, url);

        progressBar.setVisibility(View.GONE);
    }
}

//flipscreen not loading again
@Override
public void onConfigurationChanged(Configuration newConfig){
    super.onConfigurationChanged(newConfig);
}

// To handle "Back" key press event for WebView to go back to previous screen.
/*@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if ((keyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) {
        web.goBack();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}*/
}

Also I want to add that the "upload page" like the one in this example, wont work on < 4 versions, since it has an image preview feature, if you want to make it work use a simple php upload without preview.

Update:

Please find the solution for lollipop devices here and thanks for gauntface

Update 2:

Found complete solution for all android devices including marshmallow here see its github project for more.


问:
listview to string exception thrown
What I have going on is i am using

```<code>string proj = listView2.SelectedItems[0].ToString();
</code>```

to capture the item of my selected listview item, this works fine the first around, when i click on another listview item it throw the exception of

InvalidArgument=Value of '0' is not valid for 'index'.
  Parameter name: index

Any thoughts?

```<code>    private void listView2_SelectedIndexChanged(object sender, EventArgs e)
    {
       string proj = listView2.SelectedItems[0].ToString();
    }
</code>```

working:

```<code>        string proj ="";
        ListView.SelectedListViewItemCollection lv2si =
        this.listView2.SelectedItems;

        foreach (ListViewItem item in lv2si)
        {
            proj = item.ToString();
        }
</code>```

答:
You should test that the index value is valid before you access it.</p>

```<code>private void listView2_SelectedIndexChanged(object sender, EventArgs e)
{
    string proj;
    if (listView2.SelectedItems.Count > 0)
        proj = listView2.SelectedItems[0].ToString();
    else
        proj = string.Empty;
}
</code>```

Title: listview to string exception thrown

Body:
What I have going on is i am using

string proj = listView2.SelectedItems[0].ToString();

to capture the item of my selected listview item, this works fine the first around, when i click on another listview item it throw the exception of

InvalidArgument=Value of '0' is not valid for 'index'.
  Parameter name: index

Any thoughts?

    private void listView2_SelectedIndexChanged(object sender, EventArgs e)
    {
       string proj = listView2.SelectedItems[0].ToString();
    }

working:

        string proj ="";
        ListView.SelectedListViewItemCollection lv2si =
        this.listView2.SelectedItems;

        foreach (ListViewItem item in lv2si)
        {
            proj = item.ToString();
        }

Body:
You should test that the index value is valid before you access it.

private void listView2_SelectedIndexChanged(object sender, EventArgs e)
{
    string proj;
    if (listView2.SelectedItems.Count > 0)
        proj = listView2.SelectedItems[0].ToString();
    else
        proj = string.Empty;
}


问:
Whats wrong in this SPF syntax?
I am not very familiar with SPF records so I need a bit of help setting up my SPF record correctly.

Below is a record I created using online  tutorials

v=spf1 a mx ip4:192.186.236.104 include:_spf.google.com include:bmsend.com include:postbox.pidatacenters.com ~all

when i check in http://mxtoolbox.com/SuperTool.aspx?action=spf%3apidatacenters.com%3a192.186.236.104&run=toolpage#

it shows everything is right

fraudmarc.com/spf-record-check/

in this website it shows an error like this

enter image description here

Give me the solutions

Thanks in advance.

答:
A few things wrong here. The definitive SPF checker is Scott Kitterman's. It finds this error:

```<code>PermError SPF Permanent Error: Unknown mechanism found: postbox.pidatacenters.com
</code>```

It's not clear why this is presented as this particular error because the syntax itself is valid, but you have a recursive definition - your SPF includes postbox.pidatacenters.com, but the SPF for that domain includes itself, which makes no sense. It also contains the google SPF, so you don't need to include that again.

I suggest you set your SPF records to these. For pidatacenters.com:

```<code>v=spf1 ip4:192.186.236.104 mx include:bmsend.com include:postbox.pidatacenters.com ~all
</code>```

you don't need the a clause in there because it resolves to the same IP as you already listed. It's polite to put ip clauses first as they are fastest to resolve for receivers, as they do not require DNS lookups.

For postbox.pidatacenters.com:

```<code>v=spf1 include:_spf.google.com ~all
</code>```

Title: Whats wrong in this SPF syntax?

Body:
A few things wrong here. The definitive SPF checker is Scott Kitterman's. It finds this error:

PermError SPF Permanent Error: Unknown mechanism found: postbox.pidatacenters.com

It's not clear why this is presented as this particular error because the syntax itself is valid, but you have a recursive definition - your SPF includes postbox.pidatacenters.com, but the SPF for that domain includes itself, which makes no sense. It also contains the google SPF, so you don't need to include that again.

I suggest you set your SPF records to these. For pidatacenters.com:

v=spf1 ip4:192.186.236.104 mx include:bmsend.com include:postbox.pidatacenters.com ~all

you don't need the a clause in there because it resolves to the same IP as you already listed. It's polite to put ip clauses first as they are fastest to resolve for receivers, as they do not require DNS lookups.

For postbox.pidatacenters.com:

v=spf1 include:_spf.google.com ~all


问:
Netbeans debugger not working (GDB has unexpectedly stopped with return 1)
Everytime I try to debug my project with netbeans it doesn't let me do so. It gives the following error:-

"GDB has unexpectedly stopped with return 1"

And when I choose 'ok' it just stops everything. My project runs without any errors when I try to do so in netbeans. I want to step into my code and not being able to do so. Can somebody help me out with this? Thanks.

答:
Gdb Init File was the problem for me.

Run > Set Project Configuration > Customize > Debug

It was pointing to ~/.gdbinit, I cleared that field, and it worked.

Must be something crazy I had in my .gdbinit, even though it works fine with raw gdb.

Netbeans 8.2.


问:
Instance of a Functor
I have a following type newtype Arr2 e1 e2 a = Arr2 { getArr2 :: e1 -> e2 -> a }.
And I got to write Functor instance for it, yet i don't really understand how
I tried

```<code>instance Functor (Arr2 e1 e2) where
  fmap g (Arr2 a) = Arr2 (g a)
</code>```

and

```<code>instance Functor (Arr2 e1 e2) where
  fmap g = g . getArr2
</code>```

which actually results in type

```<code>(a -> b) -> Arr2 e1 e2 a -> b
</code>```

instead of desired

```<code>(a -> b) -> Arr2 e1 e2 a -> Arr2 e1 e2 b
</code>```

So please, help me

答:
The Functor class has as definition:

```<code>class Functor f where:
    fmap :: (a -> b) -> f a -> f b
    (<$) :: a -> f b -> f a
</code>```

The (<$) has a default implementation: (<$) = fmap . const which works fine.

So that means that if we enter a function (g :: a -> b) as first argument, and an Arr2 that produces an a, we have to generate an Arr2 that calls that g on the outcome of the arrow if it is applied.

As a result the definition of fmap for your Arr2 is:

```<code>instance Functor (Arr2 e1 e2) where
  fmap g (Arr2 a) = Arr2 (<b>\x y -> g (a x y)</b>)</code>```

Or more elegantly:

```<code>instance Functor (Arr2 e1 e2) where
  fmap g (Arr2 a) = Arr2 (<b>\x -> g . (a x)</b>)</code>```

Or a more elegant version - commented by @Alec:

```<code>instance Functor (Arr2 e1 e2) where
  fmap g (Arr2 a) = Arr2 (<b>(g .) . a</b>)</code>```

(you can convert expressions to pointfree ones using this tool)

Title: Instance of a Functor

Body:
I have a following type newtype Arr2 e1 e2 a = Arr2 { getArr2 :: e1 -> e2 -> a }.
And I got to write Functor instance for it, yet i don't really understand how
I tried

instance Functor (Arr2 e1 e2) where
  fmap g (Arr2 a) = Arr2 (g a)

and

instance Functor (Arr2 e1 e2) where
  fmap g = g . getArr2

which actually results in type

(a -> b) -> Arr2 e1 e2 a -> b

instead of desired

(a -> b) -> Arr2 e1 e2 a -> Arr2 e1 e2 b

So please, help me

Body:
The Functor class has as definition:

class Functor f where:
    fmap :: (a -> b) -> f a -> f b
    (<$) :: a -> f b -> f a

The (<$) has a default implementation: (<$) = fmap . const which works fine.

So that means that if we enter a function (g :: a -> b) as first argument, and an Arr2 that produces an a, we have to generate an Arr2 that calls that g on the outcome of the arrow if it is applied.

As a result the definition of fmap for your Arr2 is:

instance Functor (Arr2 e1 e2) where
  fmap g (Arr2 a) = Arr2 (\x y -> g (a x y))

Or more elegantly:

instance Functor (Arr2 e1 e2) where
  fmap g (Arr2 a) = Arr2 (\x -> g . (a x))

Or a more elegant version - commented by @Alec:

instance Functor (Arr2 e1 e2) where
  fmap g (Arr2 a) = Arr2 ((g .) . a)

(you can convert expressions to pointfree ones using this tool)


问:
How to find out if a cookie is already there?
So I do simple JS function like

```<code>function writeCookie()
{

var the_cookie = "users_resolution="+ screen.width +"x"+ screen.height;

document.cookie=the_cookie

}
</code>```

how tm make sure that users_resolution is set?

答:
I know you didn't tag this as jQuery, but I made a jQuery plugin to handle cookies, and this is the snippet that reads the cookie value:</p>

```<code>  /**
   * RegExp Breakdown:
   * search from the beginning or last semicolon: (^|;)
   * skip variable number of spaces (escape backslash in string): \\s*
   * find the name of the cookie: name
   * skip spaces around equals sign: \\s*=\\s*
   * select all non-semicolon characters: ([^;]*)
   * select next semicolon or end of string: (;|$)
   */
  var regex = new RegExp( '(^|;)\\s*'+name+'\\s*=\\s*([^;]*)(;|$)' );
  var m = document.cookie.match( regex );
  // if there was a match, match[2] is the value
  // otherwise the cookie is null ?undefined?
  val =  m ? m[2] : null;
</code>```

Body:
So I do simple JS function like

function writeCookie()
{

var the_cookie = "users_resolution="+ screen.width +"x"+ screen.height;

document.cookie=the_cookie

}

how tm make sure that users_resolution is set?

Body:
I know you didn't tag this as jQuery, but I made a jQuery plugin to handle cookies, and this is the snippet that reads the cookie value:

  /**
   * RegExp Breakdown:
   * search from the beginning or last semicolon: (^|;)
   * skip variable number of spaces (escape backslash in string): \\s*
   * find the name of the cookie: name
   * skip spaces around equals sign: \\s*=\\s*
   * select all non-semicolon characters: ([^;]*)
   * select next semicolon or end of string: (;|$)
   */
  var regex = new RegExp( '(^|;)\\s*'+name+'\\s*=\\s*([^;]*)(;|$)' );
  var m = document.cookie.match( regex );
  // if there was a match, match[2] is the value
  // otherwise the cookie is null ?undefined?
  val =  m ? m[2] : null;


问:
Spark GraphX - How to pass and array to to filter graph edges?
I am using Scala on Spark 2.1.0 GraphX. I have an array as shown below:

```<code>scala> TEMP1Vertex.take(5)
res46: Array[org.apache.spark.graphx.VertexId] = Array(-1895512637, -1745667420, -1448961741, -1352361520, -1286348803)
</code>```

If I had to filter the edge table for a single value, let's say for soruce ID -1895512637

```<code>val TEMP1Edge = graph.edges.filter { case Edge(src, dst, prop) => src == -1895512637}

scala> TEMP1Edge.take(5)
res52: Array[org.apache.spark.graphx.Edge[Int]] = Array(Edge(-1895512637,-2105158920,89), Edge(-1895512637,-2020727043,3), Edge(-1895512637,-1963423298,449), Edge(-1895512637,-1855207100,214), Edge(-1895512637,-1852287689,339))

scala> TEMP1Edge.count
17/04/03 10:20:31 WARN Executor: 1 block locks were not released by TID = 1436:[rdd_36_2]
res53: Long = 126
</code>```

But when I pass an array which contains a set of unique source IDs, the code runs successfully but it doesn't return any values as shown below:

```<code>scala> val TEMP1Edge = graph.edges.filter { case Edge(src, dst, prop) => src == TEMP1Vertex}
TEMP1Edge: org.apache.spark.rdd.RDD[org.apache.spark.graphx.Edge[Int]] = MapPartitionsRDD[929] at filter at <console>:56

scala> TEMP1Edge.take(5)
17/04/03 10:29:07 WARN Executor: 1 block locks were not released by TID = 1471:
[rdd_36_5]
res60: Array[org.apache.spark.graphx.Edge[Int]] = Array()

scala> TEMP1Edge.count
17/04/03 10:29:10 WARN Executor: 1 block locks were not released by TID = 1477:
[rdd_36_5]
res61: Long = 0
</code>```

答:
I suppose that TEMP1Vertex is of type Array[VertexId], so I think that your code should be like:

val TEMP1Edge = graph.edges.filter {
  case Edge(src, _, _) => TEMP1Vertex.contains(src)
}
```

Body:
I am using Scala on Spark 2.1.0 GraphX. I have an array as shown below:

scala> TEMP1Vertex.take(5)
res46: Array[org.apache.spark.graphx.VertexId] = Array(-1895512637, -1745667420, -1448961741, -1352361520, -1286348803)

If I had to filter the edge table for a single value, let's say for soruce ID -1895512637

val TEMP1Edge = graph.edges.filter { case Edge(src, dst, prop) => src == -1895512637}

scala> TEMP1Edge.take(5)
res52: Array[org.apache.spark.graphx.Edge[Int]] = Array(Edge(-1895512637,-2105158920,89), Edge(-1895512637,-2020727043,3), Edge(-1895512637,-1963423298,449), Edge(-1895512637,-1855207100,214), Edge(-1895512637,-1852287689,339))

scala> TEMP1Edge.count
17/04/03 10:20:31 WARN Executor: 1 block locks were not released by TID = 1436:[rdd_36_2]
res53: Long = 126

But when I pass an array which contains a set of unique source IDs, the code runs successfully but it doesn't return any values as shown below:

scala> val TEMP1Edge = graph.edges.filter { case Edge(src, dst, prop) => src == TEMP1Vertex}
TEMP1Edge: org.apache.spark.rdd.RDD[org.apache.spark.graphx.Edge[Int]] = MapPartitionsRDD[929] at filter at <console>:56

scala> TEMP1Edge.take(5)
17/04/03 10:29:07 WARN Executor: 1 block locks were not released by TID = 1471:
[rdd_36_5]
res60: Array[org.apache.spark.graphx.Edge[Int]] = Array()

scala> TEMP1Edge.count
17/04/03 10:29:10 WARN Executor: 1 block locks were not released by TID = 1477:
[rdd_36_5]
res61: Long = 0


问:
Browser does not expand content when scrolling sideways?

Update

Also created a minimal test page here: https://superfly-css.github.io/superfly-css-component-button/target/test/html/test.html

Flexbox is mainly used as the layout mechanism for container elements.  I think i may be a bug in the rendering engine.  I see the same behavior in both Chrome and Safari though.  When in portrait mode on my iphone 6 plus the content initially rendered is clipped on the left hand side.  For example the "W" in when is missing.

Start of original post

I created this test page (source code in repository) that shows the subject line behavior.  When I view this page by shrinking it in the chrome developer tooling it looks fine.  However if I open it in chrome on my iphone it looks like this:

In other words it looks like there's a margin on the html element on the right hand side that is pushing everything over, however I can't see that margin set in the developer tooling ... Thoughts?

答:
Try this:</p>

```<code><style>
    html {
        width: 100%;
    }
</style>
</code>```

Body:
Try this:

<style>
    html {
        width: 100%;
    }
</style>


问:
Cannot import cv2 in python in OSX
I have installed OpenCV 3.1 in my Mac, cv2 is also installed through pip install cv2.

```<code>vinllen@ $ pip install cv2
You are using pip version 7.1.0, however version 7.1.2 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
Requirement already satisfied (use --upgrade to upgrade): cv2 in /usr/local/lib/python2.7/site-packages
</code>```

But it looks like cv2 and cv cannot be used:

```<code>Python 2.7.10 (default, Jul 13 2015, 12:05:58)
[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named cv2
>>> import cv
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named cv
</code>```

I have tried almost all the solutions list online, but cannot work.

答:
You can install by </p>

```<code>pip install opencv-python
</code>```

Title: Cannot import cv2 in python in OSX

Body:
I have installed OpenCV 3.1 in my Mac, cv2 is also installed through pip install cv2.

vinllen@ $ pip install cv2
You are using pip version 7.1.0, however version 7.1.2 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
Requirement already satisfied (use --upgrade to upgrade): cv2 in /usr/local/lib/python2.7/site-packages

But it looks like cv2 and cv cannot be used:

Python 2.7.10 (default, Jul 13 2015, 12:05:58)
[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named cv2
>>> import cv
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named cv

I have tried almost all the solutions list online, but cannot work.

Body:
You can install by

pip install opencv-python


问:
Android Mocking a Dagger2 injected dependency for a Espresso test
I have a heavily dependency injected (dagger2) application. I would like to run an espresso test without having the test navigate through the whole application, and log into the application.

I would like to start on my teleActivity, and mock the login manager. However in any @test function, we have already hit the null pointer as we have called onCreate. If I override it before we launch the activity (show below) the activity is null.

To my understanding, the ability to switch our underlining dependencies is a large reason why we use Dagger2, else it would be just a very over engineered singleton. How do I override, mock, or switch the injection to a testing dagger module -- so I can create this simple espresso test.

Note I also wrote all this in the MVP design pattern if that makes a difference.

TeleActivity

```<code>@Inject
TelePresenter mTelePresenter;
@Inject
public LoginStateManager mLoginStateManager;

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ButterKnife.bind(this);
    DaggerInjectorTele.get().inject(this);
    mTelePresenter.setTeleDependencies(this);
    Intent intent = getIntent();

    String searchId = null;

    if (intent != null) {
        searchId = intent.getStringExtra(Constants.SEARCH_ID);
       }

    mTelePresenter.onCreateEvent(searchId,
            Helper.makeAuthorizationHeader(
            // CRASH Null pointer
            mLoginStateManager.getBaseLoginResponse().getAccessToken()));

}
</code>```

Espresso

```<code>@LargeTest
@RunWith(AndroidJUnit4.class)
public class TeleTest {
    @Rule
    public ActivityTestRule<TeleActivity> mActivityTestRule = new ActivityTestRule(
            TeleActivity.class) {
        @Override
        protected void beforeActivityLaunched() {
            super.beforeActivityLaunched();
            TeleActivity teleActivity = (TeleActivity)getActivity();
             //teleActivity NULL!
            teleActivity.mLoginStateManager = mock(LoginStateManager.class);
            LoginResponse loginResponse = mock(LoginResponse.class);
            when(loginResponse.getAccessToken()).thenReturn("1234");
            // Nope here still null

when(teleActivity.mLoginStateManager.getBaseLoginResponse()).thenReturn(loginResponse);

        }
    };
</code>```

Dagger Injector

```<code>  public class DaggerInjectorTele {
    private static TelePresenterComponent telePresenterComponent =
            DaggerTelePresenterComponent.builder().build();

    public static TelePresenterComponent get() {
        return telePresenterComponent;
    }
}
</code>```

TelePresenterComponent

```<code>@Singleton
@Component(modules = {TelePresenterModule.class,
        LoginStateManagerModule.class})
public interface TelePresenterComponent {
    void inject(TeleActivity activity);
}
</code>```

TelePresenterModule

```<code>@Module
public class TelePresenterModule {

    @Provides
    @Singleton
    public TelePresenter getTelePresenter() {
        return new TelePresenter();
    }
}
</code>```

LoginStateManagerModule

```<code>@Module
public class LoginStateManagerModule {

    @Provides
    @Singleton
    public LoginStateManager getLoginStateManager(){
        return new LoginStateManager();
    }
}
</code>```

答:
Seems like architecture problem rather than a minor issue.

First off I wouldn't create a static class for calling dagger2 component my approach would be more android centric, I mean using singleton application with all of its bells and whistles.

anyway...
Best way to run testing without running whole work-flow is to separate your project into two different projects:

1- UI app, your android activities and fragments, etc...

2-Logic Module using an enterprise architecture say MVP/MVC/MVVM (it should be a different project inside your android studio)

Where should you use dagger? inside your UI app for sticking the logic module into your UI.

How can you test different part of app (Logic Module)? since you separated your logic into different part writing tests for them would be much easier even though you are not gonna need Esperesso anymore. simple unit testing wiht JUnit and Mockito can help you without running the whole work-flow.

note that you shouldn't have any kind of logic inside your UI app.

My opinion is Clean Architecture : https://8thlight.com/blog/uncle-bob/2012/08/13/the-clean-architecture.html

I have a simple scaffold for above approach in my github you can read that too, well if you fancy :
https://github.com/vahidhashemi/android_clean_architecture

Body:
I have a heavily dependency injected (dagger2) application. I would like to run an espresso test without having the test navigate through the whole application, and log into the application.

I would like to start on my teleActivity, and mock the login manager. However in any @test function, we have already hit the null pointer as we have called onCreate. If I override it before we launch the activity (show below) the activity is null.

To my understanding, the ability to switch our underlining dependencies is a large reason why we use Dagger2, else it would be just a very over engineered singleton. How do I override, mock, or switch the injection to a testing dagger module -- so I can create this simple espresso test.

Note I also wrote all this in the MVP design pattern if that makes a difference.

TeleActivity

@Inject
TelePresenter mTelePresenter;
@Inject
public LoginStateManager mLoginStateManager;

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ButterKnife.bind(this);
    DaggerInjectorTele.get().inject(this);
    mTelePresenter.setTeleDependencies(this);
    Intent intent = getIntent();

    String searchId = null;

    if (intent != null) {
        searchId = intent.getStringExtra(Constants.SEARCH_ID);
       }

    mTelePresenter.onCreateEvent(searchId,
            Helper.makeAuthorizationHeader(
            // CRASH Null pointer
            mLoginStateManager.getBaseLoginResponse().getAccessToken()));

}

Espresso

@LargeTest
@RunWith(AndroidJUnit4.class)
public class TeleTest {
    @Rule
    public ActivityTestRule<TeleActivity> mActivityTestRule = new ActivityTestRule(
            TeleActivity.class) {
        @Override
        protected void beforeActivityLaunched() {
            super.beforeActivityLaunched();
            TeleActivity teleActivity = (TeleActivity)getActivity();
             //teleActivity NULL!
            teleActivity.mLoginStateManager = mock(LoginStateManager.class);
            LoginResponse loginResponse = mock(LoginResponse.class);
            when(loginResponse.getAccessToken()).thenReturn("1234");
            // Nope here still null

when(teleActivity.mLoginStateManager.getBaseLoginResponse()).thenReturn(loginResponse);

        }
    };

Dagger Injector

  public class DaggerInjectorTele {
    private static TelePresenterComponent telePresenterComponent =
            DaggerTelePresenterComponent.builder().build();

    public static TelePresenterComponent get() {
        return telePresenterComponent;
    }
}

TelePresenterComponent

@Singleton
@Component(modules = {TelePresenterModule.class,
        LoginStateManagerModule.class})
public interface TelePresenterComponent {
    void inject(TeleActivity activity);
}

TelePresenterModule

@Module
public class TelePresenterModule {

    @Provides
    @Singleton
    public TelePresenter getTelePresenter() {
        return new TelePresenter();
    }
}

LoginStateManagerModule

@Module
public class LoginStateManagerModule {

    @Provides
    @Singleton
    public LoginStateManager getLoginStateManager(){
        return new LoginStateManager();
    }
}


问:
Creating Postscript function dictionary type 0
I am trying to create a Postscript function dictionary of type 0. The input is single dimension and the output is 3 dimension.
Input 0 Output [ 0 0 0]
Input 1 Output [ 1 1 1]
I am having trouble writing the DataSource for this function dictionary. The PLRM manual says that DataSource has to be either a string or pure binary data. Can someone help me map these values to the format DataSource expects?

/FunctionType 0
/Domain [ 0 1 ]
/Range [ 0 1 0 1 0 1]
/Order 1
/BitsPerSample 8
/Size [ 2 ]
/DataSource ????

Thanks.

答:
OK, based on your comment, here is how I have done this:

```<code><< % Make gradient pattern dictionary
  /PatternType 2
  /Shading
  <<
    /ShadingType 2
    /ColorSpace /DeviceRGB
    /Coords [ 0 0 72 72 ] % Set coord array (gradient starting point to ending point)
    /Function
    <<
      /FunctionType 2
      /Domain [ 0 1 ]
      /C0 [ 1 1 1 ] % Set color 1 (white in RGB space)
      /C1 [ 0 0 0 ] % Set color 2 (black in RGB space)
      /N 1
    >>
  >>
>>
matrix makepattern
</code>```

This is for an example square at  0,0  0,72  72,72  72,0.

Body:
OK, based on your comment, here is how I have done this:

<< % Make gradient pattern dictionary
  /PatternType 2
  /Shading
  <<
    /ShadingType 2
    /ColorSpace /DeviceRGB
    /Coords [ 0 0 72 72 ] % Set coord array (gradient starting point to ending point)
    /Function
    <<
      /FunctionType 2
      /Domain [ 0 1 ]
      /C0 [ 1 1 1 ] % Set color 1 (white in RGB space)
      /C1 [ 0 0 0 ] % Set color 2 (black in RGB space)
      /N 1
    >>
  >>
>>
matrix makepattern

This is for an example square at  0,0  0,72  72,72  72,0.