问:
cannot find module "react/lib/ReactComponentTreeHook" error when updating to React 16.2.0
Changed react and react-dom to 16.2.0 in my package JSON and receiving the following error.

```<code>Uncaught Error: Cannot find module "react/lib/ReactComponentTreeHook"
</code>```

Have tried clearing my node_modules, reinstalling everything, starting with a fresh project and adding dependencies in small chunks to narrow down the issue, and trying just about every option already seen on stack overflow.

my package.json is as follows:

```<code>{
    "name": "",
    "version": "0.0.1",
    "description": "",
    "main": "index.js",
    "repository": {
        "type": "git",
        "url": "..."
    },
    "scripts": {
        "dev": "webpack -d --watch",
        "build": "webpack -p"
    },
    "dependencies": {
        "axios": "^0.17.1",
        "body-parser": "^1.18.2",
        "classnames": "^2.2.5",
        "connect-mongo": "^2.0.0",
        "cookie-parser": "^1.4.3",
        "express": "^4.16.2",
        "express-session": "^1.15.6",
        "moment": "^2.19.3",
        "mongoose": "^4.13.6",
        "multer": "^1.3.0",
        "node-sass": "^4.7.2",
        "passport": "^0.4.0",
        "passport-local": "^1.0.0",
        "qs": "^6.5.1",
        "react": "^16.2.0",
        "react-click-outside": "^3.0.0",
        "react-dom": "16.2.0",
        "react-redux": "5.0.6",
        "redux": "3.7.2",
        "redux-logger": "^3.0.6",
        "redux-promise-middleware": "^5.0.0",
        "redux-thunk": "^2.2.0",
        "underscore": "^1.8.3"
    },
    "devDependencies": {
        "babel-core": "^6.26.0",
        "babel-loader": "^7.1.2",
        "babel-preset-es2015": "^6.24.1",
        "babel-preset-react": "^6.24.1",
        "css-loader": "^0.28.7",
        "extract-text-webpack-plugin": "^3.0.2",
        "file-loader": "^1.1.5",
        "redux-devtools": "^3.4.1",
        "sass-loader": "^6.0.6",
        "serve": "^6.4.1",
        "style-loader": "^0.19.0",
        "svg-sprite-webpack-plugin": "^1.1.0",
        "svg-spritemap-webpack-plugin": "^1.0.3",
        "url-loader": "^0.6.2",
        "vinyl-buffer": "^1.0.0",
        "vinyl-source-stream": "^1.1.0",
        "webpack": "^3.10.0"
    },
    "author": "",
    "license": "ISC",
    "homepage": ""
}
</code>```

After placing a breakpoint at the line erroring out, it seems that the stack trace is coming form the import of react-dom, but if that is at the latest version matching react, i don't understand why i am having this issue.

Out of options that I can think of, would appreciate any help. Thanks.

答:
Have tried clearing my node_modules, reinstalling everything

Remember that since NPM 5-th version it generates package lock file, without purging that reinstalling modules will not work appropriately.

Also check following - if some package has own dependency on old react package version, it will be installed into nested node_modules directory, and then everything is dependent on project/loaders structure. In come circumstance, invalid new or old package version will be loaded. In some npm packages, like graphql, special warning added for that case: "Maybe you have installed different version of package".

So, check other packages' versions, and maybe update them.

Body:
Changed react and react-dom to 16.2.0 in my package JSON and receiving the following error.

Uncaught Error: Cannot find module "react/lib/ReactComponentTreeHook"

Have tried clearing my node_modules, reinstalling everything, starting with a fresh project and adding dependencies in small chunks to narrow down the issue, and trying just about every option already seen on stack overflow.

my package.json is as follows:

{
    "name": "",
    "version": "0.0.1",
    "description": "",
    "main": "index.js",
    "repository": {
        "type": "git",
        "url": "..."
    },
    "scripts": {
        "dev": "webpack -d --watch",
        "build": "webpack -p"
    },
    "dependencies": {
        "axios": "^0.17.1",
        "body-parser": "^1.18.2",
        "classnames": "^2.2.5",
        "connect-mongo": "^2.0.0",
        "cookie-parser": "^1.4.3",
        "express": "^4.16.2",
        "express-session": "^1.15.6",
        "moment": "^2.19.3",
        "mongoose": "^4.13.6",
        "multer": "^1.3.0",
        "node-sass": "^4.7.2",
        "passport": "^0.4.0",
        "passport-local": "^1.0.0",
        "qs": "^6.5.1",
        "react": "^16.2.0",
        "react-click-outside": "^3.0.0",
        "react-dom": "16.2.0",
        "react-redux": "5.0.6",
        "redux": "3.7.2",
        "redux-logger": "^3.0.6",
        "redux-promise-middleware": "^5.0.0",
        "redux-thunk": "^2.2.0",
        "underscore": "^1.8.3"
    },
    "devDependencies": {
        "babel-core": "^6.26.0",
        "babel-loader": "^7.1.2",
        "babel-preset-es2015": "^6.24.1",
        "babel-preset-react": "^6.24.1",
        "css-loader": "^0.28.7",
        "extract-text-webpack-plugin": "^3.0.2",
        "file-loader": "^1.1.5",
        "redux-devtools": "^3.4.1",
        "sass-loader": "^6.0.6",
        "serve": "^6.4.1",
        "style-loader": "^0.19.0",
        "svg-sprite-webpack-plugin": "^1.1.0",
        "svg-spritemap-webpack-plugin": "^1.0.3",
        "url-loader": "^0.6.2",
        "vinyl-buffer": "^1.0.0",
        "vinyl-source-stream": "^1.1.0",
        "webpack": "^3.10.0"
    },
    "author": "",
    "license": "ISC",
    "homepage": ""
}

After placing a breakpoint at the line erroring out, it seems that the stack trace is coming form the import of react-dom, but if that is at the latest version matching react, i don't understand why i am having this issue.

Out of options that I can think of, would appreciate any help. Thanks.


来源: stackexchange

问:
How to send binary data from a Node.js socket.io (v2.0.x) server to a browser client?

Engine.io send function do send binary data as binary, it can be seen
in as binary in DevTools.

Socket.io handles it as json ans sends it
as text.

May be somehow Engine.io send function can be accessed via Socket.io instance?

May be I need to re-implement custom encoder/decoder for this?

答:
This was already answered here. The client code provided is written in java.

EDIT: there is also the javascript client code

ContentLicense: CC BY-SA 3.0


问:
Page Condition becomes false after the ajax call in wordpress
I am trying to avoid some code to get display on particular pages such as tags categories and other pages.

```<code>if( !is_front_page() && !is_search() && !is_page( 'article', 'preview' ) && !is_category() && !is_tax() && !is_tag() ){
//code goes here..
}
</code>```

The condition works fine when a user lands on the page. But these pages uses ajax to retrieve post and when this happens the condition becomes false and unnecessary code displayed on page.

Why is this happening? Do anyone has any idea about this. Any kind of help would be appreciated.

答:
You should add an additional constraint to the if statement to check if the request is an ajax request. This is not used on every server, but if you are using Apache it should work for you.

```<code>if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) && !is_front_page() && !is_search() && !is_page( 'article', 'preview' ) && !is_category() && !is_tax() && !is_tag() ){
 //code here
}
</code>```

The above will only be true if it is NOT an ajax request. In the event that an ajax request is made to this php file strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' should be true and this is how you can check if it is an ajax request and handle it accordingly

Body:
I am trying to avoid some code to get display on particular pages such as tags categories and other pages.

if( !is_front_page() && !is_search() && !is_page( 'article', 'preview' ) && !is_category() && !is_tax() && !is_tag() ){
//code goes here..
}

The condition works fine when a user lands on the page. But these pages uses ajax to retrieve post and when this happens the condition becomes false and unnecessary code displayed on page.

Why is this happening? Do anyone has any idea about this. Any kind of help would be appreciated.

Body:
You should add an additional constraint to the if statement to check if the request is an ajax request. This is not used on every server, but if you are using Apache it should work for you.

if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) && !is_front_page() && !is_search() && !is_page( 'article', 'preview' ) && !is_category() && !is_tax() && !is_tag() ){
 //code here
}

The above will only be true if it is NOT an ajax request. In the event that an ajax request is made to this php file strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' should be true and this is how you can check if it is an ajax request and handle it accordingly


问:
Django Deep Linking render with #tag
I am trying to Deep Link tabs with Dango by adding the #panel1 at the end.

This would be the template needed:

```<code>template = "charts/chart1.html#panel1"
return render ( request, template, context )
</code>```

But obviously Django can not find that template once I add the hashtag.

Is there a way to overcome this issue?

Thank You.

https://foundation.zurb.com/sites/docs/tabs.html

答:
I am not a javascript guy, but I got this to work.  Maybe it can be improved?

I set the tab position inside the View:

```<code>tab = '#panel2v'
</code>```

then call the Foundation JS.

```<code>$('[data-tabs]').eq(0).foundation('selectTab', $('{{tab}}'));
</code>```

I hope this helps?  Cheers.

Title: Django Deep Linking render with #tag

Body:
I am trying to Deep Link tabs with Dango by adding the #panel1 at the end.

This would be the template needed:

template = "charts/chart1.html#panel1"
return render ( request, template, context )

But obviously Django can not find that template once I add the hashtag.

Is there a way to overcome this issue?

Thank You.

https://foundation.zurb.com/sites/docs/tabs.html

Body:
I am not a javascript guy, but I got this to work.  Maybe it can be improved?

I set the tab position inside the View:

tab = '#panel2v'

then call the Foundation JS.

$('[data-tabs]').eq(0).foundation('selectTab', $('{{tab}}'));

I hope this helps?  Cheers.


问:
php youtube api v3 description fetch issue
they say in documentation  in a video resource, the snippet property contains the channelId, title, description, tags, and categoryId properties. my code blew

```<code>$main=ngegrab('https://www.googleapis.com/youtube/v3/videos?part=snippet&contentDetails&statistics&id=0W55Oed_Uic&key=AIzaSyD7o2nlYk-a57KEXHfW4QNZ1Z6nhE-4x0g');
$sub=json_decode($main);
foreach ($sub->items as $item){
$name = $item->snippet->title;
$des = $item->snippet->description;
$vid = $item->id->videoId;
</code>```

when i try echo to print $name giving video name but $des not giving description and $vid not giving the video id

答: Description is empty for this video https://www.youtube.com/watch?v=0W55Oed_Uic so it will be empty try any other video. </p>

Body:
they say in documentation  in a video resource, the snippet property contains the channelId, title, description, tags, and categoryId properties. my code blew

$main=ngegrab('https://www.googleapis.com/youtube/v3/videos?part=snippet&contentDetails&statistics&id=0W55Oed_Uic&key=AIzaSyD7o2nlYk-a57KEXHfW4QNZ1Z6nhE-4x0g');
$sub=json_decode($main);
foreach ($sub->items as $item){
$name = $item->snippet->title;
$des = $item->snippet->description;
$vid = $item->id->videoId;

when i try echo to print $name giving video name but $des not giving description and $vid not giving the video id


问:
Moodle integration questions
We are checking all the paths to integrate a .Net application with Moodle, we would like to redirect our .net application users to Moodle so they can take some courses there but I have some questions:

Is it required to create a user for each account so they can enroll in a course in Moodle? I mean is it possible to have "anonymous" students taking courses in Moodle?

We would like to authenticate our users from our .Net application and redirect them directly to a course in Moodle, is this possible?

Thanks!

答:
Yes. In Moodle there is the concept of guest access, with which not registered users can access the system and possibly be enrolled into courses. More information here.

Yes. You can use an authentication plugin of Moodle in order to access Moodle from other systems. There are many possibilities here. More details here.

Title: Moodle integration questions


问:
How to join collection in firestore
I have to fetch job list with user detail who posted the job.
How can I achieve this task in firestore. As there is no option to joining collections. </p>

答: There is no way to join collection in firestore. So, I used the associated field to get the data from other collection.</p>

Title: How to join collection in firestore


问:
google map error when add marker
I wan't to add marker in google map, where the latitude and longitude I get from database..

and this code for get data from database and add marker

```<code>public String getJSONUrl(String url) {
        StringBuilder str = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) { // Download OK
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    str.append(line);
                }
            } else {
                Log.e("Log", "Failed to download result..");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return str.toString();
    }

private void WC(final String alamat) {
        class SendPostReqAsyncTask extends AsyncTask<String, Integer, String> {
            @Override
            protected void onPreExecute() {
                myProgressDialog = new ProgressDialog(PetaActivity.this);
                myProgressDialog.setIndeterminate(true);
                myProgressDialog.setMessage("Loading...");
                myProgressDialog.setCancelable(true);
                myProgressDialog.show();
            }

            @Override
            protected String doInBackground(String... params) {
                String text = null;
                String urlwc = alamat;
                try {
                    JSONArray data = new JSONArray(getJSONUrl(urlwc));
                    if (data.length() != 0) {
                        HashMap<String, String> map;

                        for (int i = 0; i < data.length(); i++) {
                            JSONObject c = data.getJSONObject(i);
                            map = new HashMap<String, String>();
                            map.put("id_jalan", c.getString("id_jalan"));
                            map.put("nama_jalan", c.getString("nama_jalan"));
                            map.put("latitude", c.getString("latitude"));
                            map.put("longitude", c.getString("longitude"));
                            map.put("foto", c.getString("foto"));
                            MyArrListMarker.add(map);
                            //end add marker

                            publishProgress((int) (i));
                        }
                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    text = e.getMessage();
                }
                //
                return text;
            }

            @Override
            protected void onProgressUpdate(Integer... progress) {
                maps.addMarker(new MarkerOptions()
                        .title("WC Umum")
                        .snippet("24 Jam")
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.toilet))
                        .position(new LatLng(
                                Double.parseDouble(MyArrListMarker.get(progress[0]).get("latitude")),
                                Double.parseDouble(MyArrListMarker.get(progress[0]).get("longitude"))))
                );
            }

            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);
                myProgressDialog.dismiss();

                if (result != null) {
                    AlertDialog alertDialog = new AlertDialog.Builder(PetaActivity.this).create();
                    alertDialog.setTitle("Koneksi Gagal");
                    alertDialog.setMessage("Silahkan coba lagi");
                    alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "TUTUP", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });

                    alertDialog.show();
                }
            }
        }
        SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
        sendPostReqAsyncTask.execute(alamat);
    }
</code>```

but I get error when add marker, but if the marker I remove it's no error

this the logcat

```<code> 12:36:26.356 31593-31593/lapor.jalan.rusak.com.laporjalanrusak E/dalvikvm: Could not find class 'com.google.android.chimera.Activity', referenced from method lq.b
12-29 12:36:27.276 31593-31593/lapor.jalan.rusak.com.laporjalanrusak E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: lapor.jalan.rusak.com.laporjalanrusak, PID: 31593
                                                                                java.lang.NullPointerException
                                                                                at lapor.jalan.rusak.com.laporjalanrusak.PetaActivity$1SendPostReqAsyncTask.onProgressUpdate(PetaActivity.java:378)
                                                                                at lapor.jalan.rusak.com.laporjalanrusak.PetaActivity$1SendPostReqAsyncTask.onProgressUpdate(PetaActivity.java:334)
                                                                                at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:648)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:146)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5692)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:515)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
                                                                                at dalvik.system.NativeStart.main(Native Method)
12-29 12:36:28.776 31593-31864/lapor.jalan.rusak.com.laporjalanrusak E/DynamiteModule: Failed to load DynamiteLoader: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.dynamite.DynamiteModule$DynamiteLoaderClassLoader" on path: DexPathList[[zip file "/data/app/lapor.jalan.rusak.com.laporjalanrusak-9.apk", zip file "/data/data/lapor.jalan.rusak.com.laporjalanrusak/code_cache/secondary-dexes/lapor.jalan.rusak.com.laporjalanrusak-9.apk.classes2.zip"],nativeLibraryDirectories=[/data/app-lib/lapor.jalan.rusak.com.laporjalanrusak-9, /vendor/lib, /system/lib]]
</code>```

答:
You logcat's last line

E/DynamiteModule: Failed to load DynamiteLoader: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.dynamite.DynamiteModule$DynamiteLoaderClassLoader" on path: DexPathList[[zip file "/data/app/lapor.jalan.rusak.com.laporjalanrusak-9.apk", zip file "/data/data/lapor.jalan.rusak.com.laporjalanrusak/code_cache/secondary-dexes/lapor.jalan.rusak.com.laporjalanrusak-9.apk.classes2.zip"],nativeLibraryDirectories=[/data/app-lib/lapor.jalan.rusak.com.laporjalanrusak-9, /vendor/lib, /system/lib]]

says ClassNotFoundException that means you do not have the class. It is because you may not added the lib dependency or it is being removed at runtime.

Title: google map error when add marker

Body:
I wan't to add marker in google map, where the latitude and longitude I get from database..

and this code for get data from database and add marker

public String getJSONUrl(String url) {
        StringBuilder str = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) { // Download OK
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    str.append(line);
                }
            } else {
                Log.e("Log", "Failed to download result..");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return str.toString();
    }

private void WC(final String alamat) {
        class SendPostReqAsyncTask extends AsyncTask<String, Integer, String> {
            @Override
            protected void onPreExecute() {
                myProgressDialog = new ProgressDialog(PetaActivity.this);
                myProgressDialog.setIndeterminate(true);
                myProgressDialog.setMessage("Loading...");
                myProgressDialog.setCancelable(true);
                myProgressDialog.show();
            }

            @Override
            protected String doInBackground(String... params) {
                String text = null;
                String urlwc = alamat;
                try {
                    JSONArray data = new JSONArray(getJSONUrl(urlwc));
                    if (data.length() != 0) {
                        HashMap<String, String> map;

                        for (int i = 0; i < data.length(); i++) {
                            JSONObject c = data.getJSONObject(i);
                            map = new HashMap<String, String>();
                            map.put("id_jalan", c.getString("id_jalan"));
                            map.put("nama_jalan", c.getString("nama_jalan"));
                            map.put("latitude", c.getString("latitude"));
                            map.put("longitude", c.getString("longitude"));
                            map.put("foto", c.getString("foto"));
                            MyArrListMarker.add(map);
                            //end add marker

                            publishProgress((int) (i));
                        }
                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    text = e.getMessage();
                }
                //
                return text;
            }

            @Override
            protected void onProgressUpdate(Integer... progress) {
                maps.addMarker(new MarkerOptions()
                        .title("WC Umum")
                        .snippet("24 Jam")
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.toilet))
                        .position(new LatLng(
                                Double.parseDouble(MyArrListMarker.get(progress[0]).get("latitude")),
                                Double.parseDouble(MyArrListMarker.get(progress[0]).get("longitude"))))
                );
            }

            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);
                myProgressDialog.dismiss();

                if (result != null) {
                    AlertDialog alertDialog = new AlertDialog.Builder(PetaActivity.this).create();
                    alertDialog.setTitle("Koneksi Gagal");
                    alertDialog.setMessage("Silahkan coba lagi");
                    alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "TUTUP", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });

                    alertDialog.show();
                }
            }
        }
        SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
        sendPostReqAsyncTask.execute(alamat);
    }

but I get error when add marker, but if the marker I remove it's no error

this the logcat

 12:36:26.356 31593-31593/lapor.jalan.rusak.com.laporjalanrusak E/dalvikvm: Could not find class 'com.google.android.chimera.Activity', referenced from method lq.b
12-29 12:36:27.276 31593-31593/lapor.jalan.rusak.com.laporjalanrusak E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: lapor.jalan.rusak.com.laporjalanrusak, PID: 31593
                                                                                java.lang.NullPointerException
                                                                                at lapor.jalan.rusak.com.laporjalanrusak.PetaActivity$1SendPostReqAsyncTask.onProgressUpdate(PetaActivity.java:378)
                                                                                at lapor.jalan.rusak.com.laporjalanrusak.PetaActivity$1SendPostReqAsyncTask.onProgressUpdate(PetaActivity.java:334)
                                                                                at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:648)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:146)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5692)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:515)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
                                                                                at dalvik.system.NativeStart.main(Native Method)
12-29 12:36:28.776 31593-31864/lapor.jalan.rusak.com.laporjalanrusak E/DynamiteModule: Failed to load DynamiteLoader: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.dynamite.DynamiteModule$DynamiteLoaderClassLoader" on path: DexPathList[[zip file "/data/app/lapor.jalan.rusak.com.laporjalanrusak-9.apk", zip file "/data/data/lapor.jalan.rusak.com.laporjalanrusak/code_cache/secondary-dexes/lapor.jalan.rusak.com.laporjalanrusak-9.apk.classes2.zip"],nativeLibraryDirectories=[/data/app-lib/lapor.jalan.rusak.com.laporjalanrusak-9, /vendor/lib, /system/lib]]


问:
Scanner : Exception in thread "main" java.util.NoSuchElementException
I'm trying to create an Utility Class to take inputs from the Standard Console using java.util.Scanner

```<code>package dbasics;

import java.util.*;

public class Utils {

    public static int getNumericInput() {
        System.out.println("Enter a integer ");
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        scanner.close();
        return n;
    }

    public static int[] getNumericArrayInput(int n) {
        //System.out.println("Enter "+n+"  integers seperated by a whitespace ");
         int[] numbers = new int[n];
         Scanner scanner = new Scanner(System.in);
         for (int i = 0; i < n; i++) {
                 numbers[i] =scanner.nextInt();
             }

         scanner.close();
         return numbers;
    }

}
</code>```

While calling the static methods in another class the method getNumericInput() works fine however the following method getNumericArrayInput(int n) results in an exception.

```<code>package dbasics;

public class Demo {

    public static void main(String[] args) {

        int n = Utils.getNumericInput();
        System.out.println("Number "+n);
        int arr[] = Utils.getNumericArrayInput(n);
        for(int i : arr) {
            System.out.println(i);
        }
    }

}
</code>```

Running this results in following exception

```<code>Enter a integer
5
Number 5
Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at dbasics.Utils.getNumericArrayInput(Utils.java:21)
    at dbasics.Demo.main(Demo.java:9)
</code>```

The intresting thing I have noticed is if I comment out the first input procedure the array input works fine

答: In the first method, don't close the scanner

Body:
I'm trying to create an Utility Class to take inputs from the Standard Console using java.util.Scanner

package dbasics;

import java.util.*;

public class Utils {

    public static int getNumericInput() {
        System.out.println("Enter a integer ");
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        scanner.close();
        return n;
    }

    public static int[] getNumericArrayInput(int n) {
        //System.out.println("Enter "+n+"  integers seperated by a whitespace ");
         int[] numbers = new int[n];
         Scanner scanner = new Scanner(System.in);
         for (int i = 0; i < n; i++) {
                 numbers[i] =scanner.nextInt();
             }

         scanner.close();
         return numbers;
    }

}

While calling the static methods in another class the method getNumericInput() works fine however the following method getNumericArrayInput(int n) results in an exception.

package dbasics;

public class Demo {

    public static void main(String[] args) {

        int n = Utils.getNumericInput();
        System.out.println("Number "+n);
        int arr[] = Utils.getNumericArrayInput(n);
        for(int i : arr) {
            System.out.println(i);
        }
    }

}

Running this results in following exception

Enter a integer
5
Number 5
Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at dbasics.Utils.getNumericArrayInput(Utils.java:21)
    at dbasics.Demo.main(Demo.java:9)

The intresting thing I have noticed is if I comment out the first input procedure the array input works fine


问:
Bootstrap - Prevent Alert From Closing Through JavaScript Alert Event
Kindly look at my code:

```<code>$('#myPanel').on('closed.bs.alert', function () {
    //  insert code here
});
</code>```

I tried return false inside, and even passed event as parameter in function(){} and performed event.preventDefault(), but it still won't stop the alert from being closed. I need to prevent the alert from being closed in case some conditions that I will put will not be satisfied.

答:
The reason the code wasn't working is that you were adding an event handler to the event that fires after the alert has already been closed and not the one before it closes. This is what you wanted:

```<code>$('#myPanel').on('close.bs.alert', function (e) {
    e.preventPropagation();
});
</code>```

Using return false; would also work but I try to use the event methods whenever I can since not all browsers interpret returning false from an event handler in the same way.

Body:
Kindly look at my code:

$('#myPanel').on('closed.bs.alert', function () {
    //  insert code here
});

I tried return false inside, and even passed event as parameter in function(){} and performed event.preventDefault(), but it still won't stop the alert from being closed. I need to prevent the alert from being closed in case some conditions that I will put will not be satisfied.

Body:
The reason the code wasn't working is that you were adding an event handler to the event that fires after the alert has already been closed and not the one before it closes. This is what you wanted:

$('#myPanel').on('close.bs.alert', function (e) {
    e.preventPropagation();
});

Using return false; would also work but I try to use the event methods whenever I can since not all browsers interpret returning false from an event handler in the same way.


问:
splitting string in SQL Server
Could you please help me with this task. I have a table with two columns (ID, String). String in that column is separated by '#'. And I need to produce column "Cut"

答:
Here is another way:

```<code>CREATE TABLE MyStrings (
    ID INT,
    String VARCHAR (25)
    );
INSERT INTO MyStrings VALUES
(1, 'A#B#C'),
(1, 'A#B#C'),
(1, 'A#B#C'),
(2, 'K#L#X#W#I'),
(2, 'K#L#X#W#I'),
(2, 'K#L#X#W#I'),
(2, 'K#L#X#W#I'),
(2, 'K#L#X#W#I'),
(3, 'G');

WITH CTE AS(
SELECT *,
        ROW_NUMBER () OVER (PARTITION BY ID ORDER BY ID) AS RN
FROM MyStrings
    )
    SELECT ID, String,
            SUBSTRING(String, IIF(RN = 1 , RN, RN + (RN-1))
                      , 1) AS Cut
    FROM CTE;
</code>```

OR

```<code>WITH CTE AS(
SELECT *,
        REPLACE (String, '#', '') AS STR,
        ROW_NUMBER () OVER (PARTITION BY ID ORDER BY ID) AS RN
FROM MyStrings
    )
    SELECT ID, String, SUBSTRING(STR, RN, 1) AS Cut
    FROM CTE;
</code>```

Results:

```<code>+----+-----------+-----+
| ID |  String   | Cut |
+----+-----------+-----+
|  1 | A#B#C     | A   |
|  1 | A#B#C     | B   |
|  1 | A#B#C     | C   |
|  2 | K#L#X#W#I | K   |
|  2 | K#L#X#W#I | L   |
|  2 | K#L#X#W#I | X   |
|  2 | K#L#X#W#I | W   |
|  2 | K#L#X#W#I | I   |
|  3 | G         | G   |
+----+-----------+-----+
</code>```

Title: splitting string in SQL Server

Body:
Here is another way:

CREATE TABLE MyStrings (
    ID INT,
    String VARCHAR (25)
    );
INSERT INTO MyStrings VALUES
(1, 'A#B#C'),
(1, 'A#B#C'),
(1, 'A#B#C'),
(2, 'K#L#X#W#I'),
(2, 'K#L#X#W#I'),
(2, 'K#L#X#W#I'),
(2, 'K#L#X#W#I'),
(2, 'K#L#X#W#I'),
(3, 'G');

WITH CTE AS(
SELECT *,
        ROW_NUMBER () OVER (PARTITION BY ID ORDER BY ID) AS RN
FROM MyStrings
    )
    SELECT ID, String,
            SUBSTRING(String, IIF(RN = 1 , RN, RN + (RN-1))
                      , 1) AS Cut
    FROM CTE;

OR

WITH CTE AS(
SELECT *,
        REPLACE (String, '#', '') AS STR,
        ROW_NUMBER () OVER (PARTITION BY ID ORDER BY ID) AS RN
FROM MyStrings
    )
    SELECT ID, String, SUBSTRING(STR, RN, 1) AS Cut
    FROM CTE;

Results:

+----+-----------+-----+
| ID |  String   | Cut |
+----+-----------+-----+
|  1 | A#B#C     | A   |
|  1 | A#B#C     | B   |
|  1 | A#B#C     | C   |
|  2 | K#L#X#W#I | K   |
|  2 | K#L#X#W#I | L   |
|  2 | K#L#X#W#I | X   |
|  2 | K#L#X#W#I | W   |
|  2 | K#L#X#W#I | I   |
|  3 | G         | G   |
+----+-----------+-----+


问:
Office 365 API for Word
We are exploring Office 365 API & are in initial stage. We are figuring out if we can move our Word Docs in Office 365.

Does Office 365 provide an API for Word Processing like writing Macros.

答: As mentioned above, I don't believe Microsoft offers such an API for Word processing (and pretty much every other format processing). So you will need to use third-party API or third-party components in your API. As example, Aspose offers both and has free plan (Dislaimer: I am affiliated with the company). Check out Aspose Words Cloud</p>

Title: Office 365 API for Word


问:
Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)
I am getting this kind of error, how to fix it.</p>

```<code>Error:Unable to load class 'org.gradle.tooling.internal.protocol.test.InternalTestExecutionConnection'.
Possible causes for this unexpected error Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)
Re-download dependencies and sync project (requires network)The state of a Gradle build process (daemon) may be corrupt. Stopping all Gradle daemons may solve this problem.
Stop Gradle build processes (requires restart)Your project may be using a third-party plugin which is not compatible with the other plugins in the project or the version of Gradle requested by the project.In the case of corrupt Gradle processes, you can also try closing the IDE and then killing all Java processes.
</code>```

答:
You can try this

first Open your Android Studio  > open any project you're doing

click on File > Settings > Build,Execution,Deployment > Gradle

At Project-Level settings , there are 2 option to sync the gradle either usin the default or local.

now change from default to a local gradle distribution > gradle Home

select the path on your computer.

C:\Program Files\Android\Android Studio\gradle\gradle-4.1

click on OK

Now build starts again  it should be solved.

Body:
I am getting this kind of error, how to fix it.

Error:Unable to load class 'org.gradle.tooling.internal.protocol.test.InternalTestExecutionConnection'.
Possible causes for this unexpected error Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)
Re-download dependencies and sync project (requires network)The state of a Gradle build process (daemon) may be corrupt. Stopping all Gradle daemons may solve this problem.
Stop Gradle build processes (requires restart)Your project may be using a third-party plugin which is not compatible with the other plugins in the project or the version of Gradle requested by the project.In the case of corrupt Gradle processes, you can also try closing the IDE and then killing all Java processes.


问:
SUBMIT parameters values when not defined?
When you comment a parameter in a SUBMIT of a report, what would be its value? The initial value of that type or the value that should have in a standard run of the equivalent transaction?

I mean, if you want to run a transaction setting in a defined way several dynprofields by submitting the transaction report, would you have to state every field that does have initial value or set just those that differ from the usual value they have when executing the transaction?

答: The initial value, so you don't need to pass those values in the SUBMIT (you can comment those out).</p>


问:
How can I locate a resource file for a Kitura server?
I would like to load a file from disk in my Kitura server, but there doesn't seem to be a straightforward way to locate a file. Can anyone suggest how you would locate a file included with the server?

Note I am not talking about serving a static resource here, like a HTML page. I want to load the file into the server from disk, so I can work with the data.

答: You may find this IBM-Swift recently released package useful: https://github.com/IBM-Swift/FileKit</p>


问:
Missing operand after '=' operator
I have this line of code which uses a dataview view_1 and I'm trying to filter the datagridview by product_name and its size using the RowFilter.
Here is the code:

```<code>view_1.RowFilter = "product_name = '" + cboProduct.Text + "' AND size = " + cboSize.Text + "";
</code>```

And when I try to run the application it says Missing operand after '=' operator.
So what is that missing operand?

答:
If the variable product_name is having a value that contains a space then the value needs to be wrapped in square brackets in the filter expression:
So,just wrap the variable product_name by pair of square brackets like this
[product_name]

```<code>view_1.RowFilter = "[product_name] = '" + cboProduct.Text + "' AND size = " +
cboSize.Text + "";
</code>```

Title: Missing operand after '=' operator

Body:
I have this line of code which uses a dataview view_1 and I'm trying to filter the datagridview by product_name and its size using the RowFilter.
Here is the code:

view_1.RowFilter = "product_name = '" + cboProduct.Text + "' AND size = " + cboSize.Text + "";

And when I try to run the application it says Missing operand after '=' operator.
So what is that missing operand?

Body:
If the variable product_name is having a value that contains a space then the value needs to be wrapped in square brackets in the filter expression:
So,just wrap the variable product_name by pair of square brackets like this
[product_name]

view_1.RowFilter = "[product_name] = '" + cboProduct.Text + "' AND size = " +
cboSize.Text + "";


问:
VaultQueryException when query returns > 200 states from the vault
When I query the vault and the query returns over 200 results, I see the following error:

```<code>Exception in thread "main" net.corda.core.node.services.VaultQueryException:
Please specify a `PageSpecification` as there are more results [201] than the default page size [200]
</code>```

How do I specify a PageSpecification?

答:
Here's an example of a query that extracts every unconsumed ContractState from the vault in pages of size 200, starting from the default page number (page one):

```<code>val vaultSnapshot = proxy.vaultQueryBy<ContractState>(
    QueryCriteria.VaultQueryCriteria(Vault.StateStatus.UNCONSUMED),
    PageSpecification(DEFAULT_PAGE_NUM, 200)
)
</code>```

You can find more information about page specifications here: https://docs.corda.net/api-vault-query.html#pagination.

Body:
When I query the vault and the query returns over 200 results, I see the following error:

Exception in thread "main" net.corda.core.node.services.VaultQueryException:
Please specify a `PageSpecification` as there are more results [201] than the default page size [200]

How do I specify a PageSpecification?

Body:
Here's an example of a query that extracts every unconsumed ContractState from the vault in pages of size 200, starting from the default page number (page one):

val vaultSnapshot = proxy.vaultQueryBy<ContractState>(
    QueryCriteria.VaultQueryCriteria(Vault.StateStatus.UNCONSUMED),
    PageSpecification(DEFAULT_PAGE_NUM, 200)
)

You can find more information about page specifications here: https://docs.corda.net/api-vault-query.html#pagination.


问:
How to use std::foreach with parameters/modification
I've found myself writing

```<code>for(int i=0;i<myvec.size();i++)
   myvec[i]->DoWhatever(param);
</code>```

a lot, and I'd like to compress this into a foreach statement, but I'm not sure how to get param in there without going super-verbose. I've also got things like

```<code>for(int i=0;i<myvec.size();i++)
   if(myvec[i]->IsOK())
      myvec[i]->DoWhatever(param);
</code>```

and I'd like to rewrite that guy too. Any thoughts?

Oh, also, for various reasons, I don't want to use boost.

答:
Oh, also, for various reasons, I don't want to use boost.

Valid decision, but most likely the wrong one. Consider Boost as an extension to the STL. C++ is a library-driven language. If you don't take this into account, your code will be qualitatively inferior.

While std::for_each can be used here, the absence of lambda expressions in C++ until C++0x makes this tedious. I advocate using Boost.ForEach! It makes this much easier:

```<code>foreach (yourtype x, yourvec)
    if (x.IsOK())
        x.Whatever();
</code>```

OwnerDisplayName: Jesse Beder

ContentLicense: CC BY-SA 2.5

Body:
I've found myself writing

for(int i=0;i<myvec.size();i++)
   myvec[i]->DoWhatever(param);

a lot, and I'd like to compress this into a foreach statement, but I'm not sure how to get param in there without going super-verbose. I've also got things like

for(int i=0;i<myvec.size();i++)
   if(myvec[i]->IsOK())
      myvec[i]->DoWhatever(param);

and I'd like to rewrite that guy too. Any thoughts?

Oh, also, for various reasons, I don't want to use boost.

Body:
Oh, also, for various reasons, I don't want to use boost.

Valid decision, but most likely the wrong one. Consider Boost as an extension to the STL. C++ is a library-driven language. If you don't take this into account, your code will be qualitatively inferior.

While std::for_each can be used here, the absence of lambda expressions in C++ until C++0x makes this tedious. I advocate using Boost.ForEach! It makes this much easier:

foreach (yourtype x, yourvec)
    if (x.IsOK())
        x.Whatever();

OwnerDisplayName: Konrad Rudolph


问:
Whats the difference between /deep/ ::ng-deep?
Could you please tell me, the differences between the below two scss styles?
I didn't get the clear idea about this.

:host {
  display: inline-block;

  /deep/ {
    span {
      color: red;
    }
  }
}

:host {
  display: inline-block;

  ::ng-deep {
    span {
      color: red;
    }
  }
}
```

答:
The main difference is, that ::ng-deep is supported by SASS, while support for /deep/ was removed. This is the reason why ::ng-deep was added to Angular in addition to /deep/

Besides that, both are deprecated in Angular, because when native shadow DOM support in all browsers becomes usable, they will probably remove ViewEncapsulation.Emulated


问:
Auto-expand inner div when a sibling div is removed
I have a problem with CSS which I don't know how to solve for a few days now. Searched for an answer everywhere ...

this is a fiddle I created for this purpose:

https://jsfiddle.net/tdckcxhh/8/

```<code><body style="margin:0; background: lightgray;">
<div style="width: 400px; height: 400px; position:absolute; top: 30px; left: 30px;">
    <div style="height:100%; border: 1px solid red;">
        <div style="background:#d0d0ff" class="disclaimer">
            This is a removable message which is always different (up to 100 words)
        </div>
        <div style="background:#d0d00f; height: 25px" class="desc">
            This is content description
        </div>
        <div style="background:#d0ffd0; height: 100%">
            <div id='newdiv'>
                <div class="overflow: auto;">
                    <table class="table2">
                            <tr>
                                <td width="40%">Name</td>
                                <td width="20%">zip</td>
                                <td>Address</td>
                            </tr>
                            <tr>
                                <td>A very long name</td>
                                <td>12345</td>
                                <td>followed by an even longer name</td>
                            </tr>
                            <tr>
                                <td>A very long name 2</td>
                                <td>23456</td>
                                <td>followed by another name</td>
                            </tr>
                            <tr>
                                <td>A very long name</td>
                                <td>12345</td>
                                <td>followed by an even longer name</td>
                            </tr>
                            <tr>
                                <td>A very long name 2</td>
                                <td>23456</td>
                                <td>followed by another name</td>
                            </tr>
                            <tr>
                                <td>A very long name</td>
                                <td>12345</td>
                                <td>followed by an even longer name</td>
                            </tr>
                            <tr>
                                <td>A very long name 2</td>
                                <td>23456</td>
                                <td>followed by another name</td>
                            </tr>
                            <tr>
                                <td>A very long name</td>
                                <td>12345</td>
                                <td>followed by an even longer name</td>
                            </tr>
                            <tr>
                                <td>A very long name 2</td>
                                <td>23456</td>
                                <td>followed by another name</td>
                            </tr>
                            <tr>
                                <td>A very long name</td>
                                <td>12345</td>
                                <td>followed by an even longer name</td>
                            </tr>
                            <tr>
                                <td>A very long name 2</td>
                                <td>23456</td>
                                <td>followed by another name</td>
                            </tr>
                            <tr>
                                <td>A very long name 2</td>
                                <td>23456</td>
                                <td>followed by another name</td>
                            </tr>
                            <tr>
                                <td>A very long name 2</td>
                                <td>23456</td>
                                <td>followed by another name</td>
                            </tr>
                            <tr>
                                <td>A very long name 2</td>
                                <td>23456</td>
                                <td>followed by another name</td>
                            </tr>
                            <tr>
                                <td>A very long name 2</td>
                                <td>23456</td>
                                <td>followed by another name</td>
                            </tr>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
<script>
$(document).ready(function(){

$(".disclaimer").click(function(){
    $(this).remove();
});

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

Code description:

Table length is always different. Sometimes, it is just one row, but it can go up to 500 rows. Table header is always the same.

Depending on table size, there is appropriate disclaimer - a removable message which is also always different. User removes it by clicking on it

Problem:

I need a table to be inside a div which will have an automatic height equal to what is left after disclaimer and description are placed. That div will have a scrollbar if the table is bigger than the div. When disclaimer is removed, the table div will auto expand and keep the scroll bar if needed

This has to be pure CSS solution which may have as many wrapping HTML elements as needed - it is ok as long as it looks like original and has the required functionality without using jQuery (or similar libraries)

P.S Solution with bootstrap will be perfect

EDIT: I found a solution here:

Fill remaining vertical space with CSS using display:flex

http://jsfiddle.net/7yLFL/5/

答:
Answer is here

Fill remaining vertical space with CSS using display:flex

http://jsfiddle.net/7yLFL/5/

CSS:

```<code>section {
  display: flex;
  flex-flow: column;
  height: 300px;
}
header {
  background: tomato;
}
div {
  flex: 2 ;
  background: gold;
  overflow: auto;
}
footer {
  background: lightgreen;
  min-height: 60px;
}
</code>```

Body:
I have a problem with CSS which I don't know how to solve for a few days now. Searched for an answer everywhere ...

this is a fiddle I created for this purpose:

https://jsfiddle.net/tdckcxhh/8/

            This is a removable message which is always different (up to 100 words)

            This is content description

                                Name
                                zip
                                Address

                                A very long name
                                12345
                                followed by an even longer name

                                A very long name 2
                                23456
                                followed by another name

                                A very long name
                                12345
                                followed by an even longer name

                                A very long name 2
                                23456
                                followed by another name

                                A very long name
                                12345
                                followed by an even longer name

                                A very long name 2
                                23456
                                followed by another name

                                A very long name
                                12345
                                followed by an even longer name

                                A very long name 2
                                23456
                                followed by another name

                                A very long name
                                12345
                                followed by an even longer name

                                A very long name 2
                                23456
                                followed by another name

                                A very long name 2
                                23456
                                followed by another name

                                A very long name 2
                                23456
                                followed by another name

                                A very long name 2
                                23456
                                followed by another name

                                A very long name 2
                                23456
                                followed by another name

Code description:

Table length is always different. Sometimes, it is just one row, but it can go up to 500 rows. Table header is always the same.

Depending on table size, there is appropriate disclaimer - a removable message which is also always different. User removes it by clicking on it

Problem:

I need a table to be inside a div which will have an automatic height equal to what is left after disclaimer and description are placed. That div will have a scrollbar if the table is bigger than the div. When disclaimer is removed, the table div will auto expand and keep the scroll bar if needed

This has to be pure CSS solution which may have as many wrapping HTML elements as needed - it is ok as long as it looks like original and has the required functionality without using jQuery (or similar libraries)

P.S Solution with bootstrap will be perfect

EDIT: I found a solution here:

Fill remaining vertical space with CSS using display:flex

http://jsfiddle.net/7yLFL/5/

Body:
Answer is here

Fill remaining vertical space with CSS using display:flex

http://jsfiddle.net/7yLFL/5/

CSS:

section {
  display: flex;
  flex-flow: column;
  height: 300px;
}
header {
  background: tomato;
}
div {
  flex: 2 ;
  background: gold;
  overflow: auto;
}
footer {
  background: lightgreen;
  min-height: 60px;
}


问:
How to get 5day weather forecast from openweathermap to my uwp app
I'm not an experienced developer. I'm just a noob to programming.

I've managed to get current weather info to my app via this url http://samples.openweathermap.org/data/2.5/weather?lat=7.0744&lon=79.8919&appid=a7cae8ecfab2535dec05a83525f5ac7a

but I don't know how to get 5day weather forecast data from this openweathermap url  http://samples.openweathermap.org/data/2.5/forecast?lat=7.0744&lon=79.8919&appid=a7cae8ecfab2535dec05a83525f5ac7a

this is the Weatherforecast class i created

```<code> class WeatherForecast
{
    public async static Task<RootObject> GetWeatherForecast(double lat,double lon)
    {
        var httpn = new HttpClient();
        var uri = String.Format("http://samples.openweathermap.org/data/2.5/forecast?lat={0}&lon={1}&appid=a7cae8ecfab2535dec05a83525f5ac7a", lat, lon);
        var response = await httpn.GetAsync(uri);
        var result = await response.Content.ReadAsStringAsync();
        var data = JsonConvert.DeserializeObject<RootObject>(result);

        return data;

    }

}
public class Main
{
    public double temp { get; set; }
    public double temp_min { get; set; }
    public double temp_max { get; set; }
    public double pressure { get; set; }
    public double sea_level { get; set; }
    public double grnd_level { get; set; }
    public int humidity { get; set; }
    public int temp_kf { get; set; }
}

public class Weather
{
    public int id { get; set; }
    public string main { get; set; }
    public string description { get; set; }
    public string icon { get; set; }
}

public class Clouds
{
    public int all { get; set; }
}

public class Wind
{
    public double speed { get; set; }
    public double deg { get; set; }
}

public class Rain
{
}

public class Sys
{
    public string pod { get; set; }
}

public class List
{
    public int dt { get; set; }
    public Main main { get; set; }
    public List<Weather> weather { get; set; }
    public Clouds clouds { get; set; }
    public Wind wind { get; set; }
    public Rain rain { get; set; }
    public Sys sys { get; set; }
    public string dt_txt { get; set; }
}

public class Coord
{
    public double lat { get; set; }
    public double lon { get; set; }
}

public class City
{
    public int id { get; set; }
    public string name { get; set; }
    public Coord coord { get; set; }
    public string country { get; set; }
}

public class RootObject
{
    public string cod { get; set; }
    public double message { get; set; }
    public int cnt { get; set; }
    public List<List> list { get; set; }
    public City city { get; set; }
}
</code>```

`

This is the the click event of getweatherforcast button (I added a button to get forcast)

```<code>    private async void ForecastButton_Click(object sender, RoutedEventArgs e)
    {
        var position1 = await LocationManager.GetPosition();
        var latitude1 = position1.Coordinate.Latitude;
        var longitude1 = position1.Coordinate.Longitude;
        UWPWeatherforMobileForeCast.RootObject forecast = await WeatherForecast.GetWeatherForecast(latitude1, longitude1);

    }
</code>```

This is the Gridview I want to bind data

```<code>   <GridView x:Name="ForecastGridView" >
            <GridView.ItemTemplate>
                <DataTemplate >
                    <StackPanel>
                        <TextBlock Name="forecastdatetextblock"/>
                        <TextBlock Name="forecasttemptextblock" />
                        <TextBlock Name="forecastdescriptiontextblock"/>
                     </StackPanel>
                </DataTemplate>
            </GridView.ItemTemplate>
        </GridView>
</code>```

How to bind 5day forecast date,temp and description to this gridview. what kind of itemsource and data type should I use?

This is a screenshot of my app
it's a  very simple app for my education purposes. I want to bind date,temp,description on to a gridview in that area I drawn.

p.s. this is my first stackoverflow question so forgive me if there any mistakes

答:
How to bind 5day forecast date,temp and description to this gridview. what kind of itemsource and data type should I use?

After you get the RootObject object in the button click event, you should operate the data to get five days weather and make them display on the UI. Here is a simple example code to bind 5 days weather to the UI, you can have a reference. (Click the button to get the 5 day whether data and display them)

This is the xaml

```<code><StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Button Content="get whether" Click="Button_Click"/>
    <GridView ItemsSource="{Binding collection}" x:Name="ForecastGridView">
        <GridView.ItemTemplate>
            <DataTemplate >
                <StackPanel>
                    <TextBlock Name="forecastdatetextblock" Text="{Binding dt}"/>
                    <TextBlock Name="forecasttemptextblock" Text="{Binding main.temp}" />
                    <TextBlock Name="forecastdescriptiontextblock"  Text="{Binding weather[0].description}"/>
                </StackPanel>
            </DataTemplate>
        </GridView.ItemTemplate>
    </GridView>
</StackPanel>
</code>```

This is the code behind

```<code>public MainPage()
{
    this.InitializeComponent();
    collection = new ObservableCollection<List>();
    this.DataContext = this;
}

public ObservableCollection<List> collection { get; set; }
private async void Button_Click(object sender, RoutedEventArgs e)
{
    var position1 = await LocationManager.GetPosition();
    var latitude1 = position1.Coordinate.Latitude;
    var longitude1 = position1.Coordinate.Longitude;
    RootObject forecast = await WeatherForecast.GetWeatherForecast(latitude1, longitude1);

    for (int i = 0; i < 5; i++)
    {

        collection.Add(forecast.list[i]);
    }

    ForecastGridView.ItemsSource = collection;

}
</code>```

Body:
I'm not an experienced developer. I'm just a noob to programming.

I've managed to get current weather info to my app via this url http://samples.openweathermap.org/data/2.5/weather?lat=7.0744&lon=79.8919&appid=a7cae8ecfab2535dec05a83525f5ac7a

but I don't know how to get 5day weather forecast data from this openweathermap url  http://samples.openweathermap.org/data/2.5/forecast?lat=7.0744&lon=79.8919&appid=a7cae8ecfab2535dec05a83525f5ac7a

this is the Weatherforecast class i created

 class WeatherForecast
{
    public async static Task<RootObject> GetWeatherForecast(double lat,double lon)
    {
        var httpn = new HttpClient();
        var uri = String.Format("http://samples.openweathermap.org/data/2.5/forecast?lat={0}&lon={1}&appid=a7cae8ecfab2535dec05a83525f5ac7a", lat, lon);
        var response = await httpn.GetAsync(uri);
        var result = await response.Content.ReadAsStringAsync();
        var data = JsonConvert.DeserializeObject<RootObject>(result);

        return data;

    }

}
public class Main
{
    public double temp { get; set; }
    public double temp_min { get; set; }
    public double temp_max { get; set; }
    public double pressure { get; set; }
    public double sea_level { get; set; }
    public double grnd_level { get; set; }
    public int humidity { get; set; }
    public int temp_kf { get; set; }
}

public class Weather
{
    public int id { get; set; }
    public string main { get; set; }
    public string description { get; set; }
    public string icon { get; set; }
}

public class Clouds
{
    public int all { get; set; }
}

public class Wind
{
    public double speed { get; set; }
    public double deg { get; set; }
}

public class Rain
{
}

public class Sys
{
    public string pod { get; set; }
}

public class List
{
    public int dt { get; set; }
    public Main main { get; set; }
    public List<Weather> weather { get; set; }
    public Clouds clouds { get; set; }
    public Wind wind { get; set; }
    public Rain rain { get; set; }
    public Sys sys { get; set; }
    public string dt_txt { get; set; }
}

public class Coord
{
    public double lat { get; set; }
    public double lon { get; set; }
}

public class City
{
    public int id { get; set; }
    public string name { get; set; }
    public Coord coord { get; set; }
    public string country { get; set; }
}

public class RootObject
{
    public string cod { get; set; }
    public double message { get; set; }
    public int cnt { get; set; }
    public List<List> list { get; set; }
    public City city { get; set; }
}

`

This is the the click event of getweatherforcast button (I added a button to get forcast)

    private async void ForecastButton_Click(object sender, RoutedEventArgs e)
    {
        var position1 = await LocationManager.GetPosition();
        var latitude1 = position1.Coordinate.Latitude;
        var longitude1 = position1.Coordinate.Longitude;
        UWPWeatherforMobileForeCast.RootObject forecast = await WeatherForecast.GetWeatherForecast(latitude1, longitude1);

    }

This is the Gridview I want to bind data

   <GridView x:Name="ForecastGridView" >
            <GridView.ItemTemplate>
                <DataTemplate >
                    <StackPanel>
                        <TextBlock Name="forecastdatetextblock"/>
                        <TextBlock Name="forecasttemptextblock" />
                        <TextBlock Name="forecastdescriptiontextblock"/>
                     </StackPanel>
                </DataTemplate>
            </GridView.ItemTemplate>
        </GridView>

How to bind 5day forecast date,temp and description to this gridview. what kind of itemsource and data type should I use?

This is a screenshot of my app
it's a  very simple app for my education purposes. I want to bind date,temp,description on to a gridview in that area I drawn.

p.s. this is my first stackoverflow question so forgive me if there any mistakes

Body:
How to bind 5day forecast date,temp and description to this gridview. what kind of itemsource and data type should I use?

After you get the RootObject object in the button click event, you should operate the data to get five days weather and make them display on the UI. Here is a simple example code to bind 5 days weather to the UI, you can have a reference. (Click the button to get the 5 day whether data and display them)

This is the xaml

<StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Button Content="get whether" Click="Button_Click"/>
    <GridView ItemsSource="{Binding collection}" x:Name="ForecastGridView">
        <GridView.ItemTemplate>
            <DataTemplate >
                <StackPanel>
                    <TextBlock Name="forecastdatetextblock" Text="{Binding dt}"/>
                    <TextBlock Name="forecasttemptextblock" Text="{Binding main.temp}" />
                    <TextBlock Name="forecastdescriptiontextblock"  Text="{Binding weather[0].description}"/>
                </StackPanel>
            </DataTemplate>
        </GridView.ItemTemplate>
    </GridView>
</StackPanel>

This is the code behind

public MainPage()
{
    this.InitializeComponent();
    collection = new ObservableCollection<List>();
    this.DataContext = this;
}

public ObservableCollection<List> collection { get; set; }
private async void Button_Click(object sender, RoutedEventArgs e)
{
    var position1 = await LocationManager.GetPosition();
    var latitude1 = position1.Coordinate.Latitude;
    var longitude1 = position1.Coordinate.Longitude;
    RootObject forecast = await WeatherForecast.GetWeatherForecast(latitude1, longitude1);

    for (int i = 0; i < 5; i++)
    {

        collection.Add(forecast.list[i]);
    }

    ForecastGridView.ItemsSource = collection;

}


问:
Hide Div until hover on icon
I have hit a brick wall on this one, I am working on a website where I need to hide a DIV of extra content until the user hovers over an icon but I cannot figure out how to do this. I have tried various different ways (>, + and ~) but I just cant get it to work.

HTML

.fa-canapes-icon:hover .canapes-popup{
    display:block;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="canapes">
<p>Canapes <i class="fa fa-info-circle fa-canapes-icon"></i></p>
<div class="canapes-popup">
<h1>Example Canape Menu</h1>
<p>This is a popular selection. We do of course have other options we are happy to discuss with you.<br>
Mini Yorkshires with Medium Roast Beef and Horseradish<br>
Satay Chicken Skewers with a Peanut Sauce<br>
Spicy Prawn with Mango<br>
Smoked Salmon & Mascarpone crostini with Dill & Lemon<br>
Mozzerella Pearls with Sun-blush tomatoes & Fresh Basil (V)<br>
Honey and Sesame Coated Cocktail Sausages</p>
</div>
</div></code>```

The page can be viewed here and it is the 'wedding package 3' with the canapes i icon that I am trying to add it onto.

Any help would be greatly appreciated.

答:
As .fa-canapes-icon is a child of its parent
 (and .canapes-popup is a sibling of that
) we have no way of targeting .canapes-popup in relation to .fa-canapes-icon.

A much simpler solution would be to display the .canapes-popup on hover of its parent. This also has the affect of keeping the popup open when you move the mouse inside it.

E.G:

.canapes-popup {
  display: none;
}

.canapes:hover .canapes-popup {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="canapes">
  <p>Canapes <i class="fa fa-info-circle fa-canapes-icon"></i></p>
  <div class="canapes-popup">
    <h1>Example Canape Menu</h1>
    <p>This is a popular selection. We do of course have other options we are happy to discuss with you.<br> Mini Yorkshires with Medium Roast Beef and Horseradish<br> Satay Chicken Skewers with a Peanut Sauce<br> Spicy Prawn with Mango<br> Smoked Salmon
      & Mascarpone crostini with Dill & Lemon<br> Mozzerella Pearls with Sun-blush tomatoes & Fresh Basil (V)<br> Honey and Sesame Coated Cocktail Sausages</p>
  </div>
</div></code>```

Title: Hide Div until hover on icon

Body:
I have hit a brick wall on this one, I am working on a website where I need to hide a DIV of extra content until the user hovers over an icon but I cannot figure out how to do this. I have tried various different ways (>, + and ~) but I just cant get it to work.

HTML

.fa-canapes-icon:hover .canapes-popup{
    display:block;

}

Canapes

Example Canape Menu

This is a popular selection. We do of course have other options we are happy to discuss with you.

Mini Yorkshires with Medium Roast Beef and Horseradish

Satay Chicken Skewers with a Peanut Sauce

Spicy Prawn with Mango

Smoked Salmon & Mascarpone crostini with Dill & Lemon

Mozzerella Pearls with Sun-blush tomatoes & Fresh Basil (V)

Honey and Sesame Coated Cocktail Sausages

The page can be viewed here and it is the 'wedding package 3' with the canapes i icon that I am trying to add it onto.

Any help would be greatly appreciated.

Body:
As .fa-canapes-icon is a child of its parent <p> (and .canapes-popup is a sibling of that <p>) we have no way of targeting .canapes-popup in relation to .fa-canapes-icon.

A much simpler solution would be to display the .canapes-popup on hover of its parent. This also has the affect of keeping the popup open when you move the mouse inside it.

E.G:

.canapes-popup {
  display: none;
}

.canapes:hover .canapes-popup {
  display: block;
}

<div class="canapes">
  <p>Canapes <i class="fa fa-info-circle fa-canapes-icon"></i></p>
  <div class="canapes-popup">
    <h1>Example Canape Menu</h1>
    <p>This is a popular selection. We do of course have other options we are happy to discuss with you.<br> Mini Yorkshires with Medium Roast Beef and Horseradish<br> Satay Chicken Skewers with a Peanut Sauce<br> Spicy Prawn with Mango<br> Smoked Salmon
      &amp; Mascarpone crostini with Dill &amp; Lemon<br> Mozzerella Pearls with Sun-blush tomatoes &amp; Fresh Basil (V)<br> Honey and Sesame Coated Cocktail Sausages</p>
  </div>
</div>


问:
Why doesn't Grails notify me of error at domain object saving?
I'm just starting with Grails, and here is the first issue.

I spent several hours to find out that domain object cannot be inserted in DB, until all its properties are populated.

```<code>class Item {
  String title
  String link
}

class ItemController {
  def fetch = {
    def item = new Item()
    item.title = "blabla"
    // no value for "link"
    item.save()
  }
}
</code>```

Looks logical, but why is it skipped so silently? Can I configure something to get exceptions in such cases?

Thanks

答:
To make your save() call throw a RuntimeException, you can use item.save(failOnError:true) . But you can also check the return value of save() method. If it's false, that means something wrong happened.

```<code>if (item.save()) {
   //succeeded
}
else  {
   //not succeeded
}
</code>```

Body:
I'm just starting with Grails, and here is the first issue.

I spent several hours to find out that domain object cannot be inserted in DB, until all its properties are populated.

class Item {
  String title
  String link
}

class ItemController {
  def fetch = {
    def item = new Item()
    item.title = "blabla"
    // no value for "link"
    item.save()
  }
}

Looks logical, but why is it skipped so silently? Can I configure something to get exceptions in such cases?

Thanks

Body:
To make your save() call throw a RuntimeException, you can use item.save(failOnError:true) . But you can also check the return value of save() method. If it's false, that means something wrong happened.

if (item.save()) {
   //succeeded
}
else  {
   //not succeeded
}


问:
Why RecyclerView smoothScrollToPosition scrolled to 0 happens slowly?
I have RecyclerView and use it instead ViewPager with BottomNavigationView from support library. RecyclerView for nicely and comfort scroll have PagerSnapHelper.

And i faced with terrible and strange problem:
when my listener for BottomNavigationView catches in method onNavigationItemSelected new position i make this:

```<code>    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        var newPos = -1
        //little code for checked only a NEW position, the same values ignored
        recycler.smoothScrollToPosition(currentPos) //values 0, 1 and 2

        return true
    }
</code>```

when i smoothScrollToPosition with currentPos = 0 recycler scroll to First position (0) very slow (compared to other
). Time between call method smoothScrollToPosition and onScrollStateChanged (for recycler view scroll listener with parameter newState = RecyclerView.SCROLL_STATE_IDLE) with values 1 and 2 very small, and with value = 0 about a second (!)

Why is this happening and how can I fix it?

答:
Use recyclerView.scrollToPosition(position); instead of  recycler.smoothScrollToPosition(currentPos)

recyclerView.scrollToPosition(position); will not show the animation of scrolling down, the effect will be immediate.

You can also try this if you set linearLayoutManager for your recyclerView

linearLayoutManager.scrollToPositionWithOffset(position, 0);

Body:
I have RecyclerView and use it instead ViewPager with BottomNavigationView from support library. RecyclerView for nicely and comfort scroll have PagerSnapHelper.

And i faced with terrible and strange problem:
when my listener for BottomNavigationView catches in method onNavigationItemSelected new position i make this:

    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        var newPos = -1
        //little code for checked only a NEW position, the same values ignored
        recycler.smoothScrollToPosition(currentPos) //values 0, 1 and 2

        return true
    }

when i smoothScrollToPosition with currentPos = 0 recycler scroll to First position (0) very slow (compared to other
). Time between call method smoothScrollToPosition and onScrollStateChanged (for recycler view scroll listener with parameter newState = RecyclerView.SCROLL_STATE_IDLE) with values 1 and 2 very small, and with value = 0 about a second (!)

Why is this happening and how can I fix it?


问:
What would cause PayPal's AdaptivePayments API to return a " internal server error. please check the server logs for details"?
I am working on integrating PayPal's AdaptivePayment API but everytime I make a call I am getting the error "Internal server error. Please check the server logs for details" returned from the CURL call. I believe I have all the required headers. Has anyone else had this issue? My code is below:

```<code>            $appID = "APP-80W284485P519543T";
            $username = "***********";
            $password = "***********";
            $signature = "**********";

            $endpoint = "https://svcs.sandbox.paypal.com/AdaptivePayments/";

            $headers = array(
                "X-PAYPAL-SECURITY-USERID: " . $username,
                "X-PAYPAL-SECURITY-PASSWORD: ". $password,
                "X-PAYPAL-SECURITY-SIGNATURE: ". $signature,
                "X-PAYPAL-REQUEST-DATA-FORMAT: JSON",
                "X-PAYPAL-RESPONSE-DATA-FORMAT: JSON",
                "X-PAYPAL-APPLICATION-ID: ". $appID
            );

            $packet = array(
                "actionType" => "PAY",
                "currencyCode" => "USD",
                "cancelUrl" => "cancel.html",
                "returnUrl" => "success.html",
                "receiverList" => array(
                    "receiver" => array(
                        array(
                            "amount" => "1.00",
                            "email" => "example@gmail.com",
                            "primary" => true
                        ),
                        array(
                            "amount" => "0.50",
                            "email" => "example2@gmail.com",
                            "primary" => false
                        )
                    )
                ),
                "requestEnvelope" => array(
                    "errorLanguage" => "en_US"
                )
            );

            $ch = curl_init();

            curl_setopt($ch, CURLOPT_URL, $endpoint."PAY");
            curl_setopt($ch, CURLOPT_VERBOSE, 1);

            //turning off the server and peer verification(TrustManager Concept).
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

            curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($packet));

            $response = curl_exec($ch);

            if (curl_errno($ch))
            {
                // moving to display page to display curl errors
                echo curl_errno($ch);
                echo curl_error($ch);

                  //Execute the Error handling module to display errors.
            }
            else
            {
                echo "RESPONSE";
                header('Content-Type: application/json');
                echo $response;
                curl_close($ch);
            }
</code>```

答:
Your endpoint URL is wrong, it should be:</p>

```<code>$endpoint = "https://svcs.sandbox.paypal.com/AdaptivePayments/Pay";
</code>```

Body:
I am working on integrating PayPal's AdaptivePayment API but everytime I make a call I am getting the error "Internal server error. Please check the server logs for details" returned from the CURL call. I believe I have all the required headers. Has anyone else had this issue? My code is below:

            $appID = "APP-80W284485P519543T";
            $username = "***********";
            $password = "***********";
            $signature = "**********";

            $endpoint = "https://svcs.sandbox.paypal.com/AdaptivePayments/";

            $headers = array(
                "X-PAYPAL-SECURITY-USERID: " . $username,
                "X-PAYPAL-SECURITY-PASSWORD: ". $password,
                "X-PAYPAL-SECURITY-SIGNATURE: ". $signature,
                "X-PAYPAL-REQUEST-DATA-FORMAT: JSON",
                "X-PAYPAL-RESPONSE-DATA-FORMAT: JSON",
                "X-PAYPAL-APPLICATION-ID: ". $appID
            );

            $packet = array(
                "actionType" => "PAY",
                "currencyCode" => "USD",
                "cancelUrl" => "cancel.html",
                "returnUrl" => "success.html",
                "receiverList" => array(
                    "receiver" => array(
                        array(
                            "amount" => "1.00",
                            "email" => "example@gmail.com",
                            "primary" => true
                        ),
                        array(
                            "amount" => "0.50",
                            "email" => "example2@gmail.com",
                            "primary" => false
                        )
                    )
                ),
                "requestEnvelope" => array(
                    "errorLanguage" => "en_US"
                )
            );

            $ch = curl_init();

            curl_setopt($ch, CURLOPT_URL, $endpoint."PAY");
            curl_setopt($ch, CURLOPT_VERBOSE, 1);

            //turning off the server and peer verification(TrustManager Concept).
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

            curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($packet));

            $response = curl_exec($ch);

            if (curl_errno($ch))
            {
                // moving to display page to display curl errors
                echo curl_errno($ch);
                echo curl_error($ch);

                  //Execute the Error handling module to display errors.
            }
            else
            {
                echo "RESPONSE";
                header('Content-Type: application/json');
                echo $response;
                curl_close($ch);
            }

Body:
Your endpoint URL is wrong, it should be:

$endpoint = "https://svcs.sandbox.paypal.com/AdaptivePayments/Pay";


问:
Using findbugs-slf4j plugin with maven
I am trying findbugs-slf4j plugin with maven. As mentioned in their documentation I have added the below in my `pom.xml

```<code><plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>findbugs-maven-plugin</artifactId>
        <version>3.0.1</version>
        <configuration>
          <plugins>
            <plugin>
              <groupId>jp.skypencil.findbugs.slf4j</groupId>
              <artifactId>bug-pattern</artifactId>
              <version>1.2.4</version>
            </plugin>
          </plugins>
        </configuration>
      </plugin>
</code>```

To test this I added a log like below in my code

```<code>logger.error("Could not send inventory data to collector. Exception: {}", e); // where e is an instance of Exception
</code>```

But on compiling the project and then executing mvn findbugs:findbugs and then mvn findbugs:gui I am not seeing any bugs related to SLF4J_PLACE_HOLDER_MISMATCH.

EDIT
As suggested in one of the answer I changes my plugin dependency to

```<code><reporting>
        <plugins>
            <plugin>
                <groupId>com.github.spotbugs</groupId>
                <artifactId>spotbugs-maven-plugin</artifactId>
                <version>3.1.0-RC7</version>
                <configuration>
                    <plugins>
                        <plugin>
                            <groupId>jp.skypencil.findbugs.slf4j</groupId>
                            <artifactId>bug-pattern</artifactId>
                            <version>1.2.4</version>
                        </plugin>
                    </plugins>
                </configuration>
            </plugin>
        </plugins>
    </reporting>
</code>```

But on running mvn spotbugs:spotbugs it is throwing me the below error

```<code>No plugin found for prefix 'spotbugs' in the current project and in the plugin groups [org.apache.maven.plugins, org.codehaus.mojo] available from the repositories [local (/Users/dmanna/.m2/repository), central (http://artifactory.srk.local:8080/plugins-release), snapshots (http://artifactory.srk.local:8080/plugins-snapshot)]
</code>```

Can someone let me know what I am doing wrong?

答:
Move your <plugin>...</plugin> from <reporting><plugins> to <build><plugins>. The plugin inside of <reporting> will triggered only when you kick site goal.

https://maven.apache.org/pom.html#Reporting

Title: Using findbugs-slf4j plugin with maven

Body:
I am trying findbugs-slf4j plugin with maven. As mentioned in their documentation I have added the below in my `pom.xml

<plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>findbugs-maven-plugin</artifactId>
        <version>3.0.1</version>
        <configuration>
          <plugins>
            <plugin>
              <groupId>jp.skypencil.findbugs.slf4j</groupId>
              <artifactId>bug-pattern</artifactId>
              <version>1.2.4</version>
            </plugin>
          </plugins>
        </configuration>
      </plugin>

To test this I added a log like below in my code

logger.error("Could not send inventory data to collector. Exception: {}", e); // where e is an instance of Exception

But on compiling the project and then executing mvn findbugs:findbugs and then mvn findbugs:gui I am not seeing any bugs related to SLF4J_PLACE_HOLDER_MISMATCH.

EDIT
As suggested in one of the answer I changes my plugin dependency to

<reporting>
        <plugins>
            <plugin>
                <groupId>com.github.spotbugs</groupId>
                <artifactId>spotbugs-maven-plugin</artifactId>
                <version>3.1.0-RC7</version>
                <configuration>
                    <plugins>
                        <plugin>
                            <groupId>jp.skypencil.findbugs.slf4j</groupId>
                            <artifactId>bug-pattern</artifactId>
                            <version>1.2.4</version>
                        </plugin>
                    </plugins>
                </configuration>
            </plugin>
        </plugins>
    </reporting>

But on running mvn spotbugs:spotbugs it is throwing me the below error

No plugin found for prefix 'spotbugs' in the current project and in the plugin groups [org.apache.maven.plugins, org.codehaus.mojo] available from the repositories [local (/Users/dmanna/.m2/repository), central (http://artifactory.srk.local:8080/plugins-release), snapshots (http://artifactory.srk.local:8080/plugins-snapshot)]

Can someone let me know what I am doing wrong?


问:
asp.net calendar control: is it good?
I'm looking to determine if I'm going to use the calendar control that's out-of-the-box in ASP.NET 4 or if I should look elsewhere, may be a jQuery calendar that just receives json or another .net server option.

Has anyone worked with the native calendar control?

Thanks.

答: I personally like Rick Strahl's implementation of the [link text][jQuery Date Picker]  for ASP.Net.   I used the one at http://www.eworldui.net/ prior to discovering the West Wind date picker, and will never go back.</p>

Title: asp.net calendar control: is it good?


问:
IONIC 2 native Network.onDisconnect() running code twice
i am working with ionic 2 RC1 and using sublime as text editor. i need to check if the network connection is connected or not. so for this purpose i am using ionic native Network for this purpose. but i am facing problem with the Network.onDisconnect() Observable. I have edited initializeApp() method in which i check for network connection and show alert if connection got disconnected. the I have the following code written in app.component.ts

```<code>  showAlert(title, msg) {
    let alert = this.alertCtrl.create({
      title: title,
      subTitle: msg,
      buttons: ['OK']
    });
    alert.present();
  }

  initializeApp() {
    this.platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      let disconnectSubscription = Network.onDisconnect().subscribe(() => {
        this.showAlert("Error", "No internet connection");
      });
      StatusBar.styleDefault();
    });
  }
</code>```

The problem i am facing is that alert is shown twice if application get disconnected from internet. I have found similar issue in this post but it got unanswered. Any help on this regard will be much appreciated.
Thanks in advance !

答:
I have solved this issue. The real problem that people are having is that in a lot of cases multiple instances of Ionic pages are created. So if you register an event receiver on a page and then start navigating back and forth through the App, the event receiver will be registered multiple times.
The solution is to add the event receiver in app.component.ts 's  intializeApp method, like so:

```<code>// top of page
import { Observable } from 'rxjs/Observable';

initializeApp() {
    this.platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      this.statusBar.styleDefault();
      this.splashScreen.hide();

      var offline = Observable.fromEvent(window, "offline");
      var online = Observable.fromEvent(window, "online");

      offline.subscribe(() => {
          console.log('Offline event was detected.');
      });

      online.subscribe(() => {
          console.log('Online event was detected.');
      })
    });
  }
</code>```

Both log messages will only be triggered once when you go online/offline respectively no matter how much you navigate within the App.

Body:
i am working with ionic 2 RC1 and using sublime as text editor. i need to check if the network connection is connected or not. so for this purpose i am using ionic native Network for this purpose. but i am facing problem with the Network.onDisconnect() Observable. I have edited initializeApp() method in which i check for network connection and show alert if connection got disconnected. the I have the following code written in app.component.ts

  showAlert(title, msg) {
    let alert = this.alertCtrl.create({
      title: title,
      subTitle: msg,
      buttons: ['OK']
    });
    alert.present();
  }

  initializeApp() {
    this.platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      let disconnectSubscription = Network.onDisconnect().subscribe(() => {
        this.showAlert("Error", "No internet connection");
      });
      StatusBar.styleDefault();
    });
  }

The problem i am facing is that alert is shown twice if application get disconnected from internet. I have found similar issue in this post but it got unanswered. Any help on this regard will be much appreciated.
Thanks in advance !

Body:
I have solved this issue. The real problem that people are having is that in a lot of cases multiple instances of Ionic pages are created. So if you register an event receiver on a page and then start navigating back and forth through the App, the event receiver will be registered multiple times.
The solution is to add the event receiver in app.component.ts 's  intializeApp method, like so:

// top of page
import { Observable } from 'rxjs/Observable';

initializeApp() {
    this.platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      this.statusBar.styleDefault();
      this.splashScreen.hide();

      var offline = Observable.fromEvent(window, "offline");
      var online = Observable.fromEvent(window, "online");

      offline.subscribe(() => {
          console.log('Offline event was detected.');
      });

      online.subscribe(() => {
          console.log('Online event was detected.');
      })
    });
  }

Both log messages will only be triggered once when you go online/offline respectively no matter how much you navigate within the App.


问:
How to remove Wordpress Plugin free version text

Is there any way to remove "WordPress carousel free version" this text.
Wonder Plugin version 12.3

You can see carousel example here http://rashedulalam.info

答:
Go to plugin

wonderplugin-carousel-> engine folder-> wonderplugincarousel.js

Edit wonderplugincarousel.js file and search wtextcssdefault then change opacity:0.9 to opacity: 0
and save.


问:
UNNotificationAttachment failing to attach image
So the following code is being used to attach an image from local storage url of an image. I check in Terminal to see if the image is stored and it does store the image without any issues. So ruling out any issues with the url itself.

```<code>do {
let attachment = try UNNotificationAttachment(identifier: imageTag, url: url, options: nil)
content.attachments = [attachment]
} catch {
print("The attachment was not loaded.")
}
</code>```

Other code that goes with the creation of UserNotification works fine as it triggers at the correct specified time.

The code always goes to the catch block. Can anybody please point me to the mistake if there is any in the implementation. Please help. Thank you.

Edit: with print(error.localizedDescription) error message is Invalid attachment file URL.

Edit2 : with print(error) error message is Error Domain=UNErrorDomain Code=100 "Invalid attachment file URL" UserInfo={NSLocalizedDescription=Invalid attachment file URL}

答:
I have found the real issue behind it. In apple documentation it is written that the url should be a file url and because of which you might be facing issue.

To solve this I have added image to temporary directory and then added to UNNotificationAttachment .

Please find the code below. (For my use case I was getting an imageURL)

```<code>extension UNNotificationAttachment {
    /// Save the image to disk
    static func create(imageFileIdentifier: String, data: NSData, options: [NSObject : AnyObject]?) -> UNNotificationAttachment? {
        let fileManager = FileManager.default
        let tmpSubFolderName = ProcessInfo.processInfo.globallyUniqueString
        let tmpSubFolderURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(tmpSubFolderName, isDirectory: true)

        do {
            try fileManager.createDirectory(at: tmpSubFolderURL!, withIntermediateDirectories: true, attributes: nil)
            let fileURL = tmpSubFolderURL?.appendingPathComponent(imageFileIdentifier)
            try data.write(to: fileURL!, options: [])
            let imageAttachment = try UNNotificationAttachment.init(identifier: imageFileIdentifier, url: fileURL!, options: options)
            return imageAttachment
        } catch let error {
            print("error \(error)")
        }
        return nil
    }
}
</code>```

data in the argument of this function is Data of image . Below is how did I call this method.

```<code>let imageData = NSData(contentsOf: url)
guard let attachment = UNNotificationAttachment.create(imageFileIdentifier: "img.jpeg", data: imageData!, options: nil) else { return  }
            bestAttemptContent?.attachments = [attachment]
</code>```

Body:
So the following code is being used to attach an image from local storage url of an image. I check in Terminal to see if the image is stored and it does store the image without any issues. So ruling out any issues with the url itself.

do {
let attachment = try UNNotificationAttachment(identifier: imageTag, url: url, options: nil)
content.attachments = [attachment]
} catch {
print("The attachment was not loaded.")
}

Other code that goes with the creation of UserNotification works fine as it triggers at the correct specified time.

The code always goes to the catch block. Can anybody please point me to the mistake if there is any in the implementation. Please help. Thank you.

Edit: with print(error.localizedDescription) error message is Invalid attachment file URL.

Edit2 : with print(error) error message is Error Domain=UNErrorDomain Code=100 "Invalid attachment file URL" UserInfo={NSLocalizedDescription=Invalid attachment file URL}

Body:
I have found the real issue behind it. In apple documentation it is written that the url should be a file url and because of which you might be facing issue.

To solve this I have added image to temporary directory and then added to UNNotificationAttachment .

Please find the code below. (For my use case I was getting an imageURL)

extension UNNotificationAttachment {
    /// Save the image to disk
    static func create(imageFileIdentifier: String, data: NSData, options: [NSObject : AnyObject]?) -> UNNotificationAttachment? {
        let fileManager = FileManager.default
        let tmpSubFolderName = ProcessInfo.processInfo.globallyUniqueString
        let tmpSubFolderURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(tmpSubFolderName, isDirectory: true)

        do {
            try fileManager.createDirectory(at: tmpSubFolderURL!, withIntermediateDirectories: true, attributes: nil)
            let fileURL = tmpSubFolderURL?.appendingPathComponent(imageFileIdentifier)
            try data.write(to: fileURL!, options: [])
            let imageAttachment = try UNNotificationAttachment.init(identifier: imageFileIdentifier, url: fileURL!, options: options)
            return imageAttachment
        } catch let error {
            print("error \(error)")
        }
        return nil
    }
}

data in the argument of this function is Data of image . Below is how did I call this method.

let imageData = NSData(contentsOf: url)
guard let attachment = UNNotificationAttachment.create(imageFileIdentifier: "img.jpeg", data: imageData!, options: nil) else { return  }
            bestAttemptContent?.attachments = [attachment]

ContentLicense: CC BY-SA 4.0