问:
Splash Screen image background in LinearLayout not fit
I used an image as a background of LinearLayout in splash screen activity but it show not fit for the screen. I don't know how to use attribute for it to stretching it.</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_splash"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.myproject.SplashActivity"
    android:orientation="horizontal"
    android:background="@drawable/my_image_background">

</LinearLayout>
</code>```

答:
Use this:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_splash"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.myproject.SplashActivity"
android:fitSystemWindows="true"
android:orientation="horizontal"
android:scaleType="fitXY"
android:background="@drawable/my_image_background">
</code>```

This code definitely fit your Screen.

Body:
I used an image as a background of LinearLayout in splash screen activity but it show not fit for the screen. I don't know how to use attribute for it to stretching it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_splash"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.myproject.SplashActivity"
    android:orientation="horizontal"
    android:background="@drawable/my_image_background">

</LinearLayout>

Body:
Use this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_splash"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.myproject.SplashActivity"
android:fitSystemWindows="true"
android:orientation="horizontal"
android:scaleType="fitXY"
android:background="@drawable/my_image_background">

This code definitely fit your Screen.


来源: stackexchange

问:
Android - Display a video thumbnail from a URL
I need to display a video thumbnail based to a URL into an ImageView view child of my ListView items, i have found this post but not worked.

Result

Code

```<code>        thumb_image.setImageBitmap(new LoadVideoThumbnail().execute(URLs.videos +"/"+videos.get(position).getId()+".mp4").get());
</code>```

AsyncTask

```<code>public class LoadVideoThumbnail extends AsyncTask<String, Object, Bitmap>{

        @Override
        protected Bitmap doInBackground(String... objectURL) {
            //return ThumbnailUtils.createVideoThumbnail(objectURL[0], Thumbnails.MINI_KIND);
            return ThumbnailUtils.extractThumbnail(ThumbnailUtils.createVideoThumbnail(objectURL[0], Thumbnails.MINI_KIND), 100, 100);
        }

        @Override
        protected void onPostExecute(Bitmap result){
             //img.setImageBitmap(result);
        }

    }
</code>```

答:
Hello try this snippet working in my case

```<code>        Uri videoUri = data.getData();
        String selectedPathVideo="";
        selectedPathVideo = ImageFilePath.getPath(getApplicationContext(), videoUri);
        Log.i("Image File Path", ""+selectedPathVideo);

        try {
            Bitmap thumb = ThumbnailUtils.createVideoThumbnail(selectedPathVideo, MediaStore.Video.Thumbnails.MICRO_KIND);

            imgFarmerVideo.setImageBitmap(thumb);

        } catch (Exception e) {
            e.printStackTrace();
        }
</code>```

The support class

```<code>public class ImageFilePath {
    /**
     * Method for return file path of Gallery image
     *
     * @param context
     * @param uri
     * @return path of the selected image file from gallery
     */
    public static String getPath(final Context context, final Uri uri)
    {

        //check here to KITKAT or new version
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {

            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[] {
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {

            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context The context.
     * @param uri The Uri to query.
     * @param selection (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to display a video thumbnail based to a URL into an ImageView view child of my ListView items, i have found this post but not worked.

Result

Code

        thumb_image.setImageBitmap(new LoadVideoThumbnail().execute(URLs.videos +"/"+videos.get(position).getId()+".mp4").get());

AsyncTask

public class LoadVideoThumbnail extends AsyncTask<String, Object, Bitmap>{

        @Override
        protected Bitmap doInBackground(String... objectURL) {
            //return ThumbnailUtils.createVideoThumbnail(objectURL[0], Thumbnails.MINI_KIND);
            return ThumbnailUtils.extractThumbnail(ThumbnailUtils.createVideoThumbnail(objectURL[0], Thumbnails.MINI_KIND), 100, 100);
        }

        @Override
        protected void onPostExecute(Bitmap result){
             //img.setImageBitmap(result);
        }

    }

Body:
Hello try this snippet working in my case

        Uri videoUri = data.getData();
        String selectedPathVideo="";
        selectedPathVideo = ImageFilePath.getPath(getApplicationContext(), videoUri);
        Log.i("Image File Path", ""+selectedPathVideo);

        try {
            Bitmap thumb = ThumbnailUtils.createVideoThumbnail(selectedPathVideo, MediaStore.Video.Thumbnails.MICRO_KIND);

            imgFarmerVideo.setImageBitmap(thumb);

        } catch (Exception e) {
            e.printStackTrace();
        }

The support class

public class ImageFilePath {
    /**
     * Method for return file path of Gallery image
     *
     * @param context
     * @param uri
     * @return path of the selected image file from gallery
     */
    public static String getPath(final Context context, final Uri uri)
    {

        //check here to KITKAT or new version
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {

            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[] {
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {

            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context The context.
     * @param uri The Uri to query.
     * @param selection (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }
}


问:
Change Class to Hover Class
I have a couple of nested divs and have set a CSS class for one of the interior divs. How would I go about setting off the hover version of the class (class.hover) when the user hovers of the outer div, but not necessarily over the interior div's area.

I'm assuming this has to be done via JavaScript. I need some inputs with this.

Thanks

答:
Use the CSS :hover pseudo class.  like so:

```<code>div.outer-div:hover > div.child-div { /* styles! */}
</code>```

Here's a reference to the spec.

ContentLicense: CC BY-SA 2.5

Title: Change Class to Hover Class

Body:
Use the CSS :hover pseudo class.  like so:

div.outer-div:hover > div.child-div { /* styles! */}

Here's a reference to the spec.


问:
Converting a string to JSON object
How do you make JS think that a string is JSON ?

I have a function which only works if JSON object is passed to it. If I pass a string to it, with same format as JSON, it doesn't work. So I want to make that function think that the string passed to it is a JSON. The string is indeed in the JSON format.

I also tried the following. I inputted the string through Ajax , with "handle as" parameter as "JSON", and then when  I passed the result to the function it works.

So I deduced the problem is not with the string. How do I convert this string to JSON? If i get same string through ajax request and then passing it to function works, whereas directly passing it doesn't work.

The string is as follows:

```<code>  {
     "data": [
   {
  "id": "id1",
      "fields": [
        {
          "id": "name1",
          "label": "joker",
          "unit": "year"
        },
         {"id": "name2", "label": "Quantity"},
    ],
      "rows": [    data here....

and closing braces..
</code>```

答:
```<code>var Data=[{"id": "name2", "label": "Quantity"}]
</code>```

Pass the string variable into Json parse :

```<code>Objdata= Json.parse(Data);
</code>```

Title: Converting a string to JSON object

Body:
How do you make JS think that a string is JSON ?

I have a function which only works if JSON object is passed to it. If I pass a string to it, with same format as JSON, it doesn't work. So I want to make that function think that the string passed to it is a JSON. The string is indeed in the JSON format.

I also tried the following. I inputted the string through Ajax , with "handle as" parameter as "JSON", and then when  I passed the result to the function it works.

So I deduced the problem is not with the string. How do I convert this string to JSON? If i get same string through ajax request and then passing it to function works, whereas directly passing it doesn't work.

The string is as follows:

  {
     "data": [
   {
  "id": "id1",
      "fields": [
        {
          "id": "name1",
          "label": "joker",
          "unit": "year"
        },
         {"id": "name2", "label": "Quantity"},
    ],
      "rows": [    data here....

and closing braces..

Body:
var Data=[{"id": "name2", "label": "Quantity"}]

Pass the string variable into Json parse :

Objdata= Json.parse(Data);


问:
How can I optimize this jquery script? Different classes and same function
I have this jquery function but it is too long for me. Is there any way to make as one jquery change function. I need your help.

```<code> $(document).ready(function () {
                $('.sub-cat select').change(function () {
                    if ($('.sub-cat select option:selected').text() == "Other") {
                        $('.sub-cat .other-category').show();
                    }
                    else {
                        $('.sub-cat .other-category').hide();
                    }
                });
                $('.prod-type select').change(function () {
                    if ($('.prod-type select option:selected').text() == "Other") {
                        $('.prod-type .other-category').show();
                    }
                    else {
                        $('.prod-type .other-category').hide();
                    }
                });
                $('.prod-finnish select').change(function () {
                    if ($('.prod-finnish select option:selected').text() == "Other") {
                        $('.prod-finnish .other-category').show();
                    }
                    else {
                        $('.prod-finnish .other-category').hide();
                    }
                });
                $('.prod-color select').change(function () {
                    if ($('.prod-color select option:selected').text() == "Other") {
                        $('.prod-color .other-category').show();
                    }
                    else {
                        $('.prod-color .other-category').hide();
                    }
                });
                $('.prod-included select').change(function () {
                    if ($('.prod-included select option:selected').text() == "Other") {
                        $('.prod-included .other-category').show();
                    }
                    else {
                        $('.prod-included .other-category').hide();
                    }
                });
                $('.prod-series select').change(function () {
                    if ($('.prod-series select option:selected').text() == "Other") {
                        $('.prod-series .other-category').show();
                    }
                    else {
                        $('.prod-series .other-category').hide();
                    }
                });
            });
</code>```

答:
Assign a common class i.e. 'commonClass' to all the parent element i.e. 'sub-cat, prod-included,...', then use various DOM traversal methods to target 'other-category' element.

Learn to use this, element which initiated the event

```<code>$('.commonClass select').change(function () {
    $(this).closest('.commonClass').find('.other-category').toggle($('option:selected', this).text() == "Other");
});
</code>```

References

.closest()

.find()

.toggle()

Body:
I have this jquery function but it is too long for me. Is there any way to make as one jquery change function. I need your help.

 $(document).ready(function () {
                $('.sub-cat select').change(function () {
                    if ($('.sub-cat select option:selected').text() == "Other") {
                        $('.sub-cat .other-category').show();
                    }
                    else {
                        $('.sub-cat .other-category').hide();
                    }
                });
                $('.prod-type select').change(function () {
                    if ($('.prod-type select option:selected').text() == "Other") {
                        $('.prod-type .other-category').show();
                    }
                    else {
                        $('.prod-type .other-category').hide();
                    }
                });
                $('.prod-finnish select').change(function () {
                    if ($('.prod-finnish select option:selected').text() == "Other") {
                        $('.prod-finnish .other-category').show();
                    }
                    else {
                        $('.prod-finnish .other-category').hide();
                    }
                });
                $('.prod-color select').change(function () {
                    if ($('.prod-color select option:selected').text() == "Other") {
                        $('.prod-color .other-category').show();
                    }
                    else {
                        $('.prod-color .other-category').hide();
                    }
                });
                $('.prod-included select').change(function () {
                    if ($('.prod-included select option:selected').text() == "Other") {
                        $('.prod-included .other-category').show();
                    }
                    else {
                        $('.prod-included .other-category').hide();
                    }
                });
                $('.prod-series select').change(function () {
                    if ($('.prod-series select option:selected').text() == "Other") {
                        $('.prod-series .other-category').show();
                    }
                    else {
                        $('.prod-series .other-category').hide();
                    }
                });
            });

Body:
Assign a common class i.e. 'commonClass' to all the parent element i.e. 'sub-cat, prod-included,...', then use various DOM traversal methods to target 'other-category' element.

Learn to use this, element which initiated the event

$('.commonClass select').change(function () {
    $(this).closest('.commonClass').find('.other-category').toggle($('option:selected', this).text() == "Other");
});

References

.closest()

.find()

.toggle()


问:
Cannot resolve symbol 'Theme.AppCompat.Light.DarkActionBar' in styles.xml
Theme.AppCompat.Light.DarkActionBar is not compiling in styles.xml. I have added compile 'com.android.support:appcompat-v7:25.1.0' in app module's
build.gradle.

I have searched for solution in google. A lot of them are about changing the classpath in Project's build.gradle.Still its showing the same error.

```<code>build.gradle

dependencies {
    compile 'com.android.support:appcompat-v7:25.1.0'
    compile 'com.android.support:design:25.1.0'
    compile 'com.android.support:support-annotations:25.1.0'
    compile 'com.android.support:cardview-v7:25.1.0'
    compile 'com.android.support:recyclerview-v7:25.1.0'
    //    compile 'ch.acra:acra:4.5.0'

    testCompile 'junit:junit:4.12'
}

android {
    compileSdkVersion 25
    buildToolsVersion '25.0.2'

    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 25
        versionCode = 146
        versionName = "0.6.65"
    }
</code>```

答:
Check your build.gradle file , set compileSdkVersion  to 25 .
Following gradle is working for me with appcompat-v7:25.1.0'</p>

```<code>android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    defaultConfig {
        applicationId "xxx.xx.xxxxx"
        minSdkVersion 16
        targetSdkVersion 21
        versionCode 26
        versionName "3.16"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    //compile 'com.google.firebase:firebase-messaging:9.0.1'
    compile 'com.android.support:appcompat-v7:25.1.0'
}
</code>```

Body:
Theme.AppCompat.Light.DarkActionBar is not compiling in styles.xml. I have added compile 'com.android.support:appcompat-v7:25.1.0' in app module's
build.gradle.

I have searched for solution in google. A lot of them are about changing the classpath in Project's build.gradle.Still its showing the same error.

build.gradle

dependencies {
    compile 'com.android.support:appcompat-v7:25.1.0'
    compile 'com.android.support:design:25.1.0'
    compile 'com.android.support:support-annotations:25.1.0'
    compile 'com.android.support:cardview-v7:25.1.0'
    compile 'com.android.support:recyclerview-v7:25.1.0'
    //    compile 'ch.acra:acra:4.5.0'

    testCompile 'junit:junit:4.12'
}

android {
    compileSdkVersion 25
    buildToolsVersion '25.0.2'

    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 25
        versionCode = 146
        versionName = "0.6.65"
    }

Body:
Check your build.gradle file , set compileSdkVersion  to 25 .
Following gradle is working for me with appcompat-v7:25.1.0'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    defaultConfig {
        applicationId "xxx.xx.xxxxx"
        minSdkVersion 16
        targetSdkVersion 21
        versionCode 26
        versionName "3.16"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    //compile 'com.google.firebase:firebase-messaging:9.0.1'
    compile 'com.android.support:appcompat-v7:25.1.0'
}


问:
How to get the selected dropdown value on submit in Laravel?
In Laravel, I am trying to get the value of selected drop-down value and send it to another controller. And by using that drop-down value below values need to be changed by fetching the data from the database.

Below is the code I have tried.

```<code><form action="{{{ url("/getDetailsBynumber/$_POST['number']") }}}" method="post">
<select name="number" id="number">
    <option selected="selected">Select number id</option>
    <?php
    $numberArray = json_decode($number_id, true);

    for ($i = 0 ; $i<=$number_count ; $i++) {
    ?>
    <option value="<?php echo $numberArray[$i]["number_value"] ?>"><?php echo $numberArray[$i]["number_value"]; ?></option>
    <?php
    }
    ?>
</select>
<input type="submit" value="Submit">
</code>```

答:
This is my code to get state name after submit if validation fail incase then it works
on load of page you can get the country id like this

```<code>var countryid = $('#opt_country').val();
</code>```

after that base on that you have to find state_id

like this

```<code>if (countryid != '')
{

    $.ajax({
        url: base_path + 'getstate',
        type: "POST",
        data: {in_country_id: countryid},
        async: true,
        cache: false,
        success: function (statedata) {
            var obj = jQuery.parseJSON(statedata);
            console.log(obj);
            if (obj.SUCC_FLAG == 1)
            {
                for (var i in obj)
                {
                    console.log(obj);
                    var id = obj[i].in_state_id;
                    var name = obj[i].st_state_name;
                    if (id == stateid)
                    {
                        $("#opt_state").append("<option value='" + id + "' selected >" + name.toString() + "</option>");
                    } else {
                        $("#opt_state").append("<option value='" + id + "'>" + name.toString() + "</option>");
                    }
                }
            }
            else
            {
                confirm('We are unable to load State');
            }
        },
        error: function () {
            alert("server error");
        }

    });
}
</code>```

and after that you can get the state so here is my example to get state after submit the page

Body:
In Laravel, I am trying to get the value of selected drop-down value and send it to another controller. And by using that drop-down value below values need to be changed by fetching the data from the database.

Below is the code I have tried.

<form action="{{{ url("/getDetailsBynumber/$_POST['number']") }}}" method="post">
<select name="number" id="number">
    <option selected="selected">Select number id</option>
    <?php
    $numberArray = json_decode($number_id, true);

    for ($i = 0 ; $i<=$number_count ; $i++) {
    ?>
    <option value="<?php echo $numberArray[$i]["number_value"] ?>"><?php echo $numberArray[$i]["number_value"]; ?></option>
    <?php
    }
    ?>
</select>
<input type="submit" value="Submit">

Body:
This is my code to get state name after submit if validation fail incase then it works
on load of page you can get the country id like this

var countryid = $('#opt_country').val();

after that base on that you have to find state_id

like this

if (countryid != '')
{

    $.ajax({
        url: base_path + 'getstate',
        type: "POST",
        data: {in_country_id: countryid},
        async: true,
        cache: false,
        success: function (statedata) {
            var obj = jQuery.parseJSON(statedata);
            console.log(obj);
            if (obj.SUCC_FLAG == 1)
            {
                for (var i in obj)
                {
                    console.log(obj);
                    var id = obj[i].in_state_id;
                    var name = obj[i].st_state_name;
                    if (id == stateid)
                    {
                        $("#opt_state").append("<option value='" + id + "' selected >" + name.toString() + "</option>");
                    } else {
                        $("#opt_state").append("<option value='" + id + "'>" + name.toString() + "</option>");
                    }
                }
            }
            else
            {
                confirm('We are unable to load State');
            }
        },
        error: function () {
            alert("server error");
        }

    });
}

and after that you can get the state so here is my example to get state after submit the page


问:
LDAP Query to List All Groups User is a Member of?
Given a username, how would I go about writing an LDAP query that will return all groups that the user is a member of? </p>

答:
Here is a another way to get the group information:

Make sure you add a reference for System.DirectoryServices.

```<code>DirectoryEntry root = new DirectoryEntry("LDAP://OU=YourOrganizationOU,DC=foo,DC=bar");

DirectoryEntry user = GetObjectBySAM("SomeUserName", root);

if (user != null)
{
  foreach (string g in GetMemberOf(user))
  {
    Console.WriteLine(g);
  }
}
</code>```

The following methods get the user entry and return a list of strings which is the groups the user is a member of.

```<code>public List<string> GetMemberOf(DirectoryEntry de)
{
  List<string> memberof = new List<string>();

  foreach (object oMember in de.Properties["memberOf"])
  {
    memberof.Add(oMember.ToString());
  }

  return memberof;
}

public DirectoryEntry GetObjectBySAM(string sam, DirectoryEntry root)
{
  using (DirectorySearcher searcher = new DirectorySearcher(root, string.Format("(sAMAccountName={0})", sam)))
  {
    SearchResult sr = searcher.FindOne();

    if (!(sr == null)) return sr.GetDirectoryEntry();
    else
      return null;
  }
}
</code>```

Body:
Here is a another way to get the group information:

Make sure you add a reference for System.DirectoryServices.

DirectoryEntry root = new DirectoryEntry("LDAP://OU=YourOrganizationOU,DC=foo,DC=bar");

DirectoryEntry user = GetObjectBySAM("SomeUserName", root);

if (user != null)
{
  foreach (string g in GetMemberOf(user))
  {
    Console.WriteLine(g);
  }
}

The following methods get the user entry and return a list of strings which is the groups the user is a member of.

public List<string> GetMemberOf(DirectoryEntry de)
{
  List<string> memberof = new List<string>();

  foreach (object oMember in de.Properties["memberOf"])
  {
    memberof.Add(oMember.ToString());
  }

  return memberof;
}

public DirectoryEntry GetObjectBySAM(string sam, DirectoryEntry root)
{
  using (DirectorySearcher searcher = new DirectorySearcher(root, string.Format("(sAMAccountName={0})", sam)))
  {
    SearchResult sr = searcher.FindOne();

    if (!(sr == null)) return sr.GetDirectoryEntry();
    else
      return null;
  }
}


问:
Add a Security Header into SOAP Webservice in Xamarin.Forms
I'am trying to get data from a SOAP Webservice. I was able to get data from a test service. Simply like this:

```<code>var service = new CurrencyConvertor();
var f = service.ConversionRate(Currency.EUR, Currency.USD);
</code>```

I added the service as 'Web Reference' into the Droid-Project - used it with proxy classes.

Now I am stuck with a new web service. The problem is: I need to provide a Security-Header and I really can't get it working with Xamarin. Already tried to use in the PCL, but there I cant add the Header too.

Webservice-Header:

```<code><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
      <s:Header>
        <Security s:mustUnderstand="1" xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
          <wsse:UsernameToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
            <wsse:Username>UserName</wsse:Username>
            <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">Password</wsse:Password>
          </wsse:UsernameToken>
        </Security>
      </s:Header>
    ...
</code>```

The request works in SoapUI.

答: Solved it by creating a second wcf-service, that consumes the one above. In the new one I use in-code authentification and then call the one with the security-header. Only solution that worked for me.</p>

Body:
I'am trying to get data from a SOAP Webservice. I was able to get data from a test service. Simply like this:

var service = new CurrencyConvertor();
var f = service.ConversionRate(Currency.EUR, Currency.USD);

I added the service as 'Web Reference' into the Droid-Project - used it with proxy classes.

Now I am stuck with a new web service. The problem is: I need to provide a Security-Header and I really can't get it working with Xamarin. Already tried to use in the PCL, but there I cant add the Header too.

Webservice-Header:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
      <s:Header>
        <Security s:mustUnderstand="1" xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
          <wsse:UsernameToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
            <wsse:Username>UserName</wsse:Username>
            <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">Password</wsse:Password>
          </wsse:UsernameToken>
        </Security>
      </s:Header>
    ...

The request works in SoapUI.


问:
Remove header and footer from window.print()
I am using window.print() for printing page, but I got header and footer contains page title, file path, page number and date. How to remove them?

I tried print stylesheet also.

```<code>#header, #nav, .noprint
{
display: none;
}
</code>```

Please help. Thanks.

答:
<pre class="lang-css prettyprint-override"><code>@media print {
    .footer,
    #non-printable {
        display: none !important;
    }
    #printable {
        display: block;
    }
}
</code>```

Body:
I am using window.print() for printing page, but I got header and footer contains page title, file path, page number and date. How to remove them?

I tried print stylesheet also.

#header, #nav, .noprint
{
display: none;
}

Please help. Thanks.

ContentLicense: CC BY-SA 4.0


问:
Angular 2 how to keep event from triggering digest loop/detection cycle?
We are implementing drag and drop functionality with Angular 2.

I'm using the dragover event just to run the preventDefault() function. So that the drop event works as explained in this question.

The dragover method is being handled by the onDragOver function in the component.

```<code><div draggable="true"
    (dragover)="onDragOver($event)">
...
</code>```

In the component, this function prevents default behavior allowing for the dragged item to be dropped at this target.

```<code>onDragOver(event) {
    event.preventDefault();
}
</code>```

This works as expected. The dragover event gets fired every few hundred milliseconds.

But, every time the onDragOver function is called, Angular 2 runs its digest cycle. This slows down the application. I'd like to run this function without triggering the digest cycle.

A workaround we use for this is subscribing to element event and running it outside of the Angular 2's context as follows:

```<code>constructor( ele: ElementRef, private ngZone: NgZone ) {
    this.ngZone.runOutsideAngular( () => {
        Observable.fromEvent(ele.nativeElement, "dragover")
            .subscribe( (event: Event) => {
                event.preventDefault();
            }
        );
    });
}
</code>```

This works fine. But is there a way to achieve this without having to access the nativeElement directly?

答:
You can detach the change detector to prevent change detection to be invoked for a component</p>

```<code>constructor(private cdRef:ChangeDetectorRef) {}
foo() {
  this.cdRef.detach();
  ...
  this.cdRef.attach();
}
</code>```

Body:
We are implementing drag and drop functionality with Angular 2.

I'm using the dragover event just to run the preventDefault() function. So that the drop event works as explained in this question.

The dragover method is being handled by the onDragOver function in the component.

...

In the component, this function prevents default behavior allowing for the dragged item to be dropped at this target.

onDragOver(event) {
    event.preventDefault();
}

This works as expected. The dragover event gets fired every few hundred milliseconds.

But, every time the onDragOver function is called, Angular 2 runs its digest cycle. This slows down the application. I'd like to run this function without triggering the digest cycle.

A workaround we use for this is subscribing to element event and running it outside of the Angular 2's context as follows:

constructor( ele: ElementRef, private ngZone: NgZone ) {
    this.ngZone.runOutsideAngular( () => {
        Observable.fromEvent(ele.nativeElement, "dragover")
            .subscribe( (event: Event) => {
                event.preventDefault();
            }
        );
    });
}

This works fine. But is there a way to achieve this without having to access the nativeElement directly?

Body:
You can detach the change detector to prevent change detection to be invoked for a component

constructor(private cdRef:ChangeDetectorRef) {}
foo() {
  this.cdRef.detach();
  ...
  this.cdRef.attach();
}


问:
How to check if locationManager has updated current location?
I would like to show user's current location on startup, and then keep tracking their location but stop centring on the current location. My idea is to centre on the current location in viewDidLoad(), but I don't know how to wait for locationManager to update the current location before centring. Here are the relevant parts of my code:</p>

```<code>var currentLocation : CLLocation?
@IBOutlet weak var mapView: MKMapView!

override func viewDidLoad() {
    super.viewDidLoad()

    if CLLocationManager.locationServicesEnabled() {
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()

        // wait for currentLocation to be updated
        animateMap(currentLocation!)

    }

    mapView.showsUserLocation = true
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    currentLocation = locations.last!
}

func animateMap(_ location: CLLocation) {
    let region = MKCoordinateRegionMakeWithDistance(location.coordinate, 1000, 1000)
    mapView.setRegion(region, animated: true)
}
</code>```

答:
// MARK:- Location lattitude longtitude method Delegate Methods</p>

```<code>func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
    if locationManager.location != nil
    {
        let locValue = (locationManager.location?.coordinate)!
        lat = locValue.latitude
        long = locValue.longitude
    }
}
</code>```

Body:
I would like to show user's current location on startup, and then keep tracking their location but stop centring on the current location. My idea is to centre on the current location in viewDidLoad(), but I don't know how to wait for locationManager to update the current location before centring. Here are the relevant parts of my code:

var currentLocation : CLLocation?
@IBOutlet weak var mapView: MKMapView!

override func viewDidLoad() {
    super.viewDidLoad()

    if CLLocationManager.locationServicesEnabled() {
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()

        // wait for currentLocation to be updated
        animateMap(currentLocation!)

    }

    mapView.showsUserLocation = true
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    currentLocation = locations.last!
}

func animateMap(_ location: CLLocation) {
    let region = MKCoordinateRegionMakeWithDistance(location.coordinate, 1000, 1000)
    mapView.setRegion(region, animated: true)
}

Body:
// MARK:- Location lattitude longtitude method Delegate Methods

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
    if locationManager.location != nil
    {
        let locValue = (locationManager.location?.coordinate)!
        lat = locValue.latitude
        long = locValue.longitude
    }
}


问:
Error with file reader
I'm getting an error with

```<code>PersonsInfoData[i] = PersonsInfoin.setPersonsInfo(temp[0],temp[1],temp[2],temp[3],temp[4]);
</code>```

"Incompatible types: void cannot be coverted to PersonsInfo"

```<code>public void readFile(String fileName)
{
    // Try to read in the data and if an exception occurs go to the Catch section
    try
    {
        FileInputStream fstream = new FileInputStream(fileName);
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));

        int i = 0;    // i is used as the line counter
        String line;  // line is used to temporarily store the line read in from the data file

        // Read a line from the data file into the buffer and then check whether
        //      it is null.  The while loop continues until a line read in is null.
        while ((line = br.readLine()) != null)
        {
            // Split the line of data (from the text file) and put each entry into the
    //                                             temporary array - temp[]
            String[] temp = line.split(",");
            // Save each entry into its respective PCDataRecord object.
            PersonsInfoData[i] = PersonsInfoin.setPersonsInfo(temp[0],temp[1],temp[2],temp[3],temp[4]);
            i++;  // Increment i so we can keep a count of how many entries have been read in.
        }
        numberOfEntries = i;   // Set numberOfEntries equal to i, to remember how many entries are now in the array
        br.close();            // Close the BufferedReader
        in.close();            // Close the DataInputStream
        fstream.close();       // Close the FileInputStream
    }
    catch (Exception e)
    {
        System.err.println("Error Reading File: " + e.getMessage());
    }
}
</code>```

答:
I guess you are trying to write the values to PersonsInfoData[i]. If yes, then replace the line with -

PersonsInfoData[i].setPersonsInfo(temp[0],temp[1],temp[2],temp[3],temp[4]);

Title: Error with file reader

Body:
I'm getting an error with

PersonsInfoData[i] = PersonsInfoin.setPersonsInfo(temp[0],temp[1],temp[2],temp[3],temp[4]);

"Incompatible types: void cannot be coverted to PersonsInfo"

public void readFile(String fileName)
{
    // Try to read in the data and if an exception occurs go to the Catch section
    try
    {
        FileInputStream fstream = new FileInputStream(fileName);
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));

        int i = 0;    // i is used as the line counter
        String line;  // line is used to temporarily store the line read in from the data file

        // Read a line from the data file into the buffer and then check whether
        //      it is null.  The while loop continues until a line read in is null.
        while ((line = br.readLine()) != null)
        {
            // Split the line of data (from the text file) and put each entry into the
    //                                             temporary array - temp[]
            String[] temp = line.split(",");
            // Save each entry into its respective PCDataRecord object.
            PersonsInfoData[i] = PersonsInfoin.setPersonsInfo(temp[0],temp[1],temp[2],temp[3],temp[4]);
            i++;  // Increment i so we can keep a count of how many entries have been read in.
        }
        numberOfEntries = i;   // Set numberOfEntries equal to i, to remember how many entries are now in the array
        br.close();            // Close the BufferedReader
        in.close();            // Close the DataInputStream
        fstream.close();       // Close the FileInputStream
    }
    catch (Exception e)
    {
        System.err.println("Error Reading File: " + e.getMessage());
    }
}


问:
How do you transfer the data from a CRM 4.0 database into another CRM 4.0 database?
Our client wants to transfer all the data in the Production CRM 4.0 database and use it in UAT.  What is the best way to transfer the data over.</p>

答:
Open SQL Server Management Studio

Right click on your source database and select Tasks/Back Up

Update the Destination to your desired location and click OK

Right click on the empty target database and choose Tasks/Restore Database

Select from Device and choose the file name for your backup, then click OK


问:
JSONException: End of input at character 0
I'm facing the error as given in the logs below. The error says that the return code which is passed is 0. I can successfully receive the OPT via my email and when I enter it and press confirm registration there's the toast error message I get Unable to generate valid response for registration. Try again. I don't understand exactly why this is happening.

Error:

答:
Check your backend API because a token isn't received from API.

token not null but the response is empty.


问:
How Remove Required Validation at Conditional Checkout Field at Woocommerce
I use     conditional checkout fields as given at Conditionally unset checkout field in woocommerce .
But, It doesn't  remove required validation fields?
How can I pass conditional statement within "if (true)" to remove required validation ?
 At the other words, how can I check which option is selected?
Regards</p>

```<code> if( true ){ // pass conditional statement here
     unset($fields['billing']['add_house_name']);  //  remove field
     $fields['billing']['add_building_name']['required']   = false; //            remove required validation
        }
        return $fields;
</code>```

答:
You can override checkout fields using this code:

```<code>// Hook in
add_filter( 'woocommerce_default_address_fields' , 'custom_override_default_address_fields' );

// Our hooked in function - $address_fields is passed via the filter!
function custom_override_default_address_fields( $address_fields ) {
     $address_fields['address_1']['required'] = false;

     return $address_fields;
}
</code>```

You can add this hook to a condition where you check inputs based on which you want to trigger validation.

Body:
I use     conditional checkout fields as given at Conditionally unset checkout field in woocommerce .
But, It doesn't  remove required validation fields?
How can I pass conditional statement within "if (true)" to remove required validation ?
 At the other words, how can I check which option is selected?
Regards

 if( true ){ // pass conditional statement here
     unset($fields['billing']['add_house_name']);  //  remove field
     $fields['billing']['add_building_name']['required']   = false; //            remove required validation
        }
        return $fields;

Body:
You can override checkout fields using this code:

// Hook in
add_filter( 'woocommerce_default_address_fields' , 'custom_override_default_address_fields' );

// Our hooked in function - $address_fields is passed via the filter!
function custom_override_default_address_fields( $address_fields ) {
     $address_fields['address_1']['required'] = false;

     return $address_fields;
}

You can add this hook to a condition where you check inputs based on which you want to trigger validation.


问:
angularjs push function not working
Hi I am trying to make a single page angular js application but while adding to the list "schedulelist" only the latest record are getting pushed into the list and all the previous records are getting replaced by the latest record

This is my Html:

```<code> <table class="table1" cellspacing=2 cellpadding=5 border=0>
  <div ng-repeat="scheduleDTO in schedules">
<tr>
<td>
       <SELECT id="days" name="days" class="form-right" style="width:90%" ng-model="scheduleDTO.day_of_the_week" required>

                    <OPTION selected value="Monday">Monday</OPTION>
                    <OPTION value="Tuesday">Tuesday</OPTION>
                    <OPTION value="Wednesday">Wednesday</OPTION>
                    <OPTION value="Thursday">Thursday</OPTION>
                    <OPTION value="Friday">Friday</OPTION>
                    <OPTION value="Saturday">Saturday</OPTION>
                    <OPTION value="Sunday">Sunday</OPTION>
        </SELECT>

</td>
<td>
       <SELECT id="start_time" name="Start" class="form-right" style="width:90%" ng-model="scheduleDTO.start_time" required>
                    <OPTION value="1:00">01:00</OPTION>
                    <OPTION value="2:00">02:00</OPTION>
                    <OPTION value="3:00">03:00</OPTION>
                    <OPTION value="4:00">04:00</OPTION>
                    <OPTION value="5:00">05:00</OPTION>
                    <OPTION value="6:00">06:00</OPTION>
                    <OPTION value="7:00">07:00</OPTION>
                    <OPTION value="8:00">08:00</OPTION>
                    <OPTION selected value="9:00">09:00</OPTION>
                    <OPTION value="10:00">10:00</OPTION>
                    <OPTION value="11:00">11:00</OPTION>
                    <OPTION value="12:00">12:00</OPTION>
        </SELECT>

</td>
<td>
<SELECT id="start" name="am" class="form-right" style="width:90%" ng-model="scheduleDTO.start_time_meridiem"required>
                    <OPTION selected value="AM">AM</OPTION>
                    <OPTION value="PM">PM</OPTION>
</SELECT>

<td><SELECT  id="end_time"class="form-right" name="end" style="width:90%" ng-model="scheduleDTO.end_time" required>
                    <OPTION value="1:00">01:00</OPTION>
                    <OPTION value="2:00">02:00</OPTION>
                    <OPTION value="3:00">03:00</OPTION>
                    <OPTION value="4:00">04:00</OPTION>
                    <OPTION selected value="5:00">05:00</OPTION>
                    <OPTION value="6:00">06:00</OPTION>
                    <OPTION value="7:00">07:00</OPTION>
                    <OPTION value="8:00">08:00</OPTION>
                    <OPTION value="9:00">09:00</OPTION>
                    <OPTION value="10:00">10:00</OPTION>
                    <OPTION value="11:00">11:00</OPTION>
                    <OPTION value="12:00">12:00</OPTION>
        </SELECT>

        </td>
<td>

<SELECT id="end" name="pm" class="form-right" style="width:90%" ng-model="scheduleDTO.end_time_meridiem" required>
                    <OPTION value="AM">AM</OPTION>
                    <OPTION selected value="PM">PM</OPTION>
</SELECT>

</td>
<td><input type="button" class="addSch" ng-click="add(scheduleDTO)" value="Add Schedule" style="width:90%"> <!-- add_schedule(); -->

</td>
</tr>
</div>
</table>
<table align='center' class="table1" cellspacing=2 cellpadding=5 id="table" border=0>

<tr ng-repeat="ScheduleDTO in schedulelist">

<td>{{scheduleDTO.day_of_the_week}}</td>
<td>{{scheduleDTO.start_time}}</td>
<td>{{scheduleDTO.start_time_meridiem}}</td><td>To</td>
<td>{{scheduleDTO.end_time}}</td>
<td>{{scheduleDTO.end_time_meridiem}}</td>
<td><input type='button' value='Delete' class='delete' ng-click="remove(scheduleDTO)"></td>

</table>
</code>```

This is rthe controller:

```<code>$scope.schedulelist = [

    ];

    $scope.add = function (schedule)
            {                   schedule.volunteer_id="";
                                schedule.sid="";
                   $scope.schedulelist.push({"ScheduleDTO":schedule});
                    alert(angular.toJson($scope.schedulelist));
            };
    $scope.remove = function(schedule) {
                var index = $scope.schedulelist.indexOf(schedule);
                $scope.schedulelist.splice(index, 1);
                    alert(angular.toJson($scope.schedulelist));
            };
</code>```

答:
Use angular copy and and also change variable name from select box and list. Please check this fiddle</p>

```<code> (function($){

try{
var demoApp = angular.module('demoApp',[]);
demoApp.controller('demoController',['$scope',function($scope){
    $scope.schedulelist = [

    ];

    $scope.add = function (scheduleObject) {

                            var schedule = angular.copy(scheduleObject)
                  schedule['volunteer_id']="";
                  schedule['sid']="";

                  $scope.schedulelist.push(
                    {"ScheduleDTO":schedule}
                  );
            };
    $scope.remove = function(schedule) {
                var index = $scope.schedulelist.indexOf(schedule);
                $scope.schedulelist.splice(index, 1);
                    alert(angular.toJson($scope.schedulelist));
            };

            }])
}catch(e){
console.log(e)
}

})(jQuery)
</code>```

Title: angularjs push function not working

Body:
Hi I am trying to make a single page angular js application but while adding to the list "schedulelist" only the latest record are getting pushed into the list and all the previous records are getting replaced by the latest record

This is my Html:

       <SELECT id="days" name="days" class="form-right" style="width:90%" ng-model="scheduleDTO.day_of_the_week" required>

                    <OPTION selected value="Monday">Monday</OPTION>
                    <OPTION value="Tuesday">Tuesday</OPTION>
                    <OPTION value="Wednesday">Wednesday</OPTION>
                    <OPTION value="Thursday">Thursday</OPTION>
                    <OPTION value="Friday">Friday</OPTION>
                    <OPTION value="Saturday">Saturday</OPTION>
                    <OPTION value="Sunday">Sunday</OPTION>
        </SELECT>

       <SELECT id="start_time" name="Start" class="form-right" style="width:90%" ng-model="scheduleDTO.start_time" required>
                    <OPTION value="1:00">01:00</OPTION>
                    <OPTION value="2:00">02:00</OPTION>
                    <OPTION value="3:00">03:00</OPTION>
                    <OPTION value="4:00">04:00</OPTION>
                    <OPTION value="5:00">05:00</OPTION>
                    <OPTION value="6:00">06:00</OPTION>
                    <OPTION value="7:00">07:00</OPTION>
                    <OPTION value="8:00">08:00</OPTION>
                    <OPTION selected value="9:00">09:00</OPTION>
                    <OPTION value="10:00">10:00</OPTION>
                    <OPTION value="11:00">11:00</OPTION>
                    <OPTION value="12:00">12:00</OPTION>
        </SELECT>

<SELECT id="start" name="am" class="form-right" style="width:90%" ng-model="scheduleDTO.start_time_meridiem"required>
                    <OPTION selected value="AM">AM</OPTION>
                    <OPTION value="PM">PM</OPTION>
</SELECT>

<SELECT  id="end_time"class="form-right" name="end" style="width:90%" ng-model="scheduleDTO.end_time" required>
                    <OPTION value="1:00">01:00</OPTION>
                    <OPTION value="2:00">02:00</OPTION>
                    <OPTION value="3:00">03:00</OPTION>
                    <OPTION value="4:00">04:00</OPTION>
                    <OPTION selected value="5:00">05:00</OPTION>
                    <OPTION value="6:00">06:00</OPTION>
                    <OPTION value="7:00">07:00</OPTION>
                    <OPTION value="8:00">08:00</OPTION>
                    <OPTION value="9:00">09:00</OPTION>
                    <OPTION value="10:00">10:00</OPTION>
                    <OPTION value="11:00">11:00</OPTION>
                    <OPTION value="12:00">12:00</OPTION>
        </SELECT>

<SELECT id="end" name="pm" class="form-right" style="width:90%" ng-model="scheduleDTO.end_time_meridiem" required>
                    <OPTION value="AM">AM</OPTION>
                    <OPTION selected value="PM">PM</OPTION>
</SELECT>

<input type="button" class="addSch" ng-click="add(scheduleDTO)" value="Add Schedule" style="width:90%">

{{scheduleDTO.day_of_the_week}}
{{scheduleDTO.start_time}}
{{scheduleDTO.start_time_meridiem}}	To
{{scheduleDTO.end_time}}
{{scheduleDTO.end_time_meridiem}}
<input type='button' value='Delete' class='delete' ng-click="remove(scheduleDTO)">

This is rthe controller:

$scope.schedulelist = [

    ];

    $scope.add = function (schedule)
            {                   schedule.volunteer_id="";
                                schedule.sid="";
                   $scope.schedulelist.push({"ScheduleDTO":schedule});
                    alert(angular.toJson($scope.schedulelist));
            };
    $scope.remove = function(schedule) {
                var index = $scope.schedulelist.indexOf(schedule);
                $scope.schedulelist.splice(index, 1);
                    alert(angular.toJson($scope.schedulelist));
            };

Body:
Use angular copy and and also change variable name from select box and list. Please check this fiddle

 (function($){

try{
var demoApp = angular.module('demoApp',[]);
demoApp.controller('demoController',['$scope',function($scope){
    $scope.schedulelist = [

    ];

    $scope.add = function (scheduleObject) {

                            var schedule = angular.copy(scheduleObject)
                  schedule['volunteer_id']="";
                  schedule['sid']="";

                  $scope.schedulelist.push(
                    {"ScheduleDTO":schedule}
                  );
            };
    $scope.remove = function(schedule) {
                var index = $scope.schedulelist.indexOf(schedule);
                $scope.schedulelist.splice(index, 1);
                    alert(angular.toJson($scope.schedulelist));
            };

            }])
}catch(e){
console.log(e)
}

})(jQuery)


问:
See the type of a var in Visual Studio
Is there a way to see the type of a var within the Visual Studio 2013 code editor?

When I have a crazy linq query it would be nice to see what the resulting type will be.  I don't want to replace the var keyword with the actual type, I just want to see what it is.

答: Add a variable watch. Check the type in the watch window.</p>

Title: See the type of a var in Visual Studio


问:
How to access route after certain controller call
I have two routes

```<code>Route::post('checkout','CartController@billingSave');
Route::get('success','CartController@billingSave');
</code>```

So after completing the billingSave method it will redirect to success page..
But if put /success also in url it shows the success page also..though he didn't complete the payment..is there anyway i could let access only the success url after completing the billingSave functionality?

means he can't access success url instead of completing the billingSave method ..or like don't give him access the success url?

答: You could block the success route using laravel's Middleware https://laravel.com/docs/5.4/middleware You can write your own middleware to check whether billingSave was done.</p>

Body:
I have two routes

Route::post('checkout','CartController@billingSave');
Route::get('success','CartController@billingSave');

So after completing the billingSave method it will redirect to success page..
But if put /success also in url it shows the success page also..though he didn't complete the payment..is there anyway i could let access only the success url after completing the billingSave functionality?

means he can't access success url instead of completing the billingSave method ..or like don't give him access the success url?


问:
Python: List of lists - presence of an element
I am trying to check the presence of an element in a list of lists and, if so, do something at this particular list (within the list of list):

```<code>transac1 = ['John','6', '20/10/2016']
transac2 = ['Emma','6', '20/10/2016']
transactions = [['Marie',2],['Emma',9]]
</code>```

I would like to do the following:

```<code>## non-Python code
if ['John',x] exists in transactions:
     ## I need to have the index where [John,x] is at that point
     then transactions[index][1] += transac1[1]
else:
     transactions.append(['John',6])
</code>```

So executing this loop with transac1 would make:

```<code>transactions = [['Marie',2],['Emma',9],['John',6]]
</code>```

And executing this loop with transac2 would make:

```<code>transactions = [['Marie',2],['Emma',15],['John',6]]
</code>```

The problem I face with a "classic double loop" is that, each time it does not find ['John',x] it will append to the list, where I need to know that for the entire list before doing something (plus, I have the assurance that if 'John' is in the list, it is only once).

My constraint is I cannot use Dictionaries. Thanks a lot.

答:
Is using numpy an option? If so, you can do the following:

```<code>import numpy as np

transac1 = ['John','6', '20/10/2016']
transac2 = ['Emma','6', '20/10/2016']
transactions = [['Marie',2],['Emma',9]]

t1 = np.array(transac1)
t2 = np.array(transac2)
tt = np.array(transactions)

names = tt[:, 0]
amounts = tt[:, 1]

if t1[0] in names:
    tt[names.index(t1[0]), 1] += t[1]
else:
    tt.append([t1[0], t1[1])
</code>```

If not, I would just check the name every iteration.

```<code>transac1 = ['John','6', '20/10/2016']
transac2 = ['Emma','6', '20/10/2016']
transactions = [['Marie',2],['Emma',9]]

# Run with transac1
def func():
    for i, t in enumerate(transactions):
        if t[0] == transac1[0]:
            transactions[i][1] += transac1[1]
            return transactions
    transactions.append([transac1[0], transac1[1])
    return transactions

func()
</code>```

Body:
I am trying to check the presence of an element in a list of lists and, if so, do something at this particular list (within the list of list):

transac1 = ['John','6', '20/10/2016']
transac2 = ['Emma','6', '20/10/2016']
transactions = [['Marie',2],['Emma',9]]

I would like to do the following:

## non-Python code
if ['John',x] exists in transactions:
     ## I need to have the index where [John,x] is at that point
     then transactions[index][1] += transac1[1]
else:
     transactions.append(['John',6])

So executing this loop with transac1 would make:

transactions = [['Marie',2],['Emma',9],['John',6]]

And executing this loop with transac2 would make:

transactions = [['Marie',2],['Emma',15],['John',6]]

The problem I face with a "classic double loop" is that, each time it does not find ['John',x] it will append to the list, where I need to know that for the entire list before doing something (plus, I have the assurance that if 'John' is in the list, it is only once).

My constraint is I cannot use Dictionaries. Thanks a lot.

Body:
Is using numpy an option? If so, you can do the following:

import numpy as np

transac1 = ['John','6', '20/10/2016']
transac2 = ['Emma','6', '20/10/2016']
transactions = [['Marie',2],['Emma',9]]

t1 = np.array(transac1)
t2 = np.array(transac2)
tt = np.array(transactions)

names = tt[:, 0]
amounts = tt[:, 1]

if t1[0] in names:
    tt[names.index(t1[0]), 1] += t[1]
else:
    tt.append([t1[0], t1[1])

If not, I would just check the name every iteration.

transac1 = ['John','6', '20/10/2016']
transac2 = ['Emma','6', '20/10/2016']
transactions = [['Marie',2],['Emma',9]]

# Run with transac1
def func():
    for i, t in enumerate(transactions):
        if t[0] == transac1[0]:
            transactions[i][1] += transac1[1]
            return transactions
    transactions.append([transac1[0], transac1[1])
    return transactions

func()


问:
How to save object property with ODATA?
I have these classes, when I save Invoice

```<code>string serviceUri = "http://myserviceurl.azurewebsites.net/odata/";
var container = new Default.Container(new Uri(serviceUri));

var myInvoice = container.Invoice.Expand("CreatedBy").Where(x => x.Id == new Guid("B7E5EEAD-EA77-4174-8305-50440AD057C7")).Skip(0).First();
myInvoice.CreatedBy = container.User.First();
container.UpdateObject(myInvoice);
</code>```

It saves the Invoice (fields: GUID, string), but the CreatedBy User field does not get saved (it is not sent to the server, on server side I checked it and comes null)

How can I fix it, or is it a limitation in ODATA 4?

Should I use ODATA only to Read;
and create another WebApi to Save the Entire Invoice Entity (including CreatedBy) ? Comments, solutions will be appreciated.

```<code>[PropertyChanged.ImplementPropertyChanged]
public class User
{
    [Index]
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }
    public string Name { get; set; }
}

[PropertyChanged.ImplementPropertyChanged]
public class Invoice
{
    [Index]
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }

    public User CreatedBy { get; set; }    // how to save this?

    [InverseProperty("Invoice")]
    public ICollection<InvoiceItem> Items { get; set; }    // how to save this?
 }

[PropertyChanged.ImplementPropertyChanged]
public class InvoiceItem
{
    [Index]
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }
    public Invoice Invoice { get; set; }

    public decimal Qty { get; set; }
    public decimal Price { get; set; }
    public decimal Total { get; set; }
}
</code>```

On these scenarios, is ODATA suitable only to READ? to WRITE, I should write my own WebApi?
Some thing like this: (or maybe a generic version of this)

```<code>public void Post([FromBody] Invoice p)
{
    SyncContext db = new SyncContext();

    db.Entry(p).State = System.Data.Entity.EntityState.Modified; // Exists?

    foreach (var item in p.Items)
    {
        var f = db.InvoiceItem.Where(i => i.Id == item.Id).FirstOrDefault();
        db.Entry(item).State = f == null ?
                            System.Data.Entity.EntityState.Added :
                            System.Data.Entity.EntityState.Modified;
    }

    db.SaveChanges();
}
</code>```

Client side:

```<code>using (var client = new WebClient())
{
    var dataString = JsonConvert.SerializeObject(myInvoice);
    client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
    client.UploadString(new Uri("http://localhost:56948/odata/Invoice"), "POST", dataString);
}
</code>```

答:
You need to add the user as a foreign key to the invoice. Because your user ID is created by the database you will need to create the user first. </p>

<p>[Example] (https://learn.microsoft.com/en-us/aspnet/web-api/overview/odata-support-in-aspnet-web-api/odata-v4/entity-relations-in-odata-v4)</p>

```<code>public class Invoice
{
    ...
    // New code:
    [ForeignKey("User")]
    public Guid userId { get; set; }
    public virtual User User { get; set; }
}
</code>```

Title: How to save object property with ODATA?

Body:
I have these classes, when I save Invoice

string serviceUri = "http://myserviceurl.azurewebsites.net/odata/";
var container = new Default.Container(new Uri(serviceUri));

var myInvoice = container.Invoice.Expand("CreatedBy").Where(x => x.Id == new Guid("B7E5EEAD-EA77-4174-8305-50440AD057C7")).Skip(0).First();
myInvoice.CreatedBy = container.User.First();
container.UpdateObject(myInvoice);

It saves the Invoice (fields: GUID, string), but the CreatedBy User field does not get saved (it is not sent to the server, on server side I checked it and comes null)

How can I fix it, or is it a limitation in ODATA 4?

Should I use ODATA only to Read;
and create another WebApi to Save the Entire Invoice Entity (including CreatedBy) ? Comments, solutions will be appreciated.

[PropertyChanged.ImplementPropertyChanged]
public class User
{
    [Index]
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }
    public string Name { get; set; }
}

[PropertyChanged.ImplementPropertyChanged]
public class Invoice
{
    [Index]
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }

    public User CreatedBy { get; set; }    // how to save this?

    [InverseProperty("Invoice")]
    public ICollection<InvoiceItem> Items { get; set; }    // how to save this?
 }

[PropertyChanged.ImplementPropertyChanged]
public class InvoiceItem
{
    [Index]
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }
    public Invoice Invoice { get; set; }

    public decimal Qty { get; set; }
    public decimal Price { get; set; }
    public decimal Total { get; set; }
}

On these scenarios, is ODATA suitable only to READ? to WRITE, I should write my own WebApi?
Some thing like this: (or maybe a generic version of this)

public void Post([FromBody] Invoice p)
{
    SyncContext db = new SyncContext();

    db.Entry(p).State = System.Data.Entity.EntityState.Modified; // Exists?

    foreach (var item in p.Items)
    {
        var f = db.InvoiceItem.Where(i => i.Id == item.Id).FirstOrDefault();
        db.Entry(item).State = f == null ?
                            System.Data.Entity.EntityState.Added :
                            System.Data.Entity.EntityState.Modified;
    }

    db.SaveChanges();
}

Client side:

using (var client = new WebClient())
{
    var dataString = JsonConvert.SerializeObject(myInvoice);
    client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
    client.UploadString(new Uri("http://localhost:56948/odata/Invoice"), "POST", dataString);
}

Body:
You need to add the user as a foreign key to the invoice. Because your user ID is created by the database you will need to create the user first.

[Example] (https://learn.microsoft.com/en-us/aspnet/web-api/overview/odata-support-in-aspnet-web-api/odata-v4/entity-relations-in-odata-v4)

public class Invoice
{
    ...
    // New code:
    [ForeignKey("User")]
    public Guid userId { get; set; }
    public virtual User User { get; set; }
}


问:
How can I transload data between two delphi applications over internet?
Hi
let me make my question clear. Two people using my app are connected to the internet. Both have each other's IP and they want to chat (like Y!messanger) with each other.
I think I need to use Indy components; right? Which component should I use?
Thanks in advance</p>

答: Have you looked at any of the demos on Indy's website yet?</p>


答:
You need to simply call that animateMap(currentLocation!) function in delegate method didUpdateLocations where you are initializing the currentLocation.

```<code>func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    currentLocation = locations.last!
    animateMap(currentLocation!)
    //Either Call `stopUpdatingLocation()`
    locationManager.stopUpdatingLocation()
    //Or you can create one boolean property with default value false and compare it inside this method
    if !animatedFlag {
        animateMap(currentLocation!)
        animatedFlag = true
    }
}

var animatedFlag = false
</code>```

Title: How to check if locationManager has updated current location?

Body:
You need to simply call that animateMap(currentLocation!) function in delegate method didUpdateLocations where you are initializing the currentLocation.

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    currentLocation = locations.last!
    animateMap(currentLocation!)
    //Either Call `stopUpdatingLocation()`
    locationManager.stopUpdatingLocation()
    //Or you can create one boolean property with default value false and compare it inside this method
    if !animatedFlag {
        animateMap(currentLocation!)
        animatedFlag = true
    }
}

var animatedFlag = false


问:
Validation Of UserEmail Is not working in php
I am going to validate the POST variable userEmail. But the problem is even though I used filter_var to validate, it is not working even when inputting a wrong email and instead gets inserted. Can you help me in getting the solution.

insert_dummy.php

```<code><html>
<head><title>Insertion</title>

</head>
<body>
<style>

#colour {
text-decoration:none;
}
</style>
<div id="display">
<?php
include('header/page_header.php');
include('db.php');

if(isset($_POST['add']))
{
$userName=mysql_real_escape_string($_POST['userName']);

$userEmail=mysql_real_escape_string($_POST['userEmail']);
if(!filter_var($userEmail, FILTER_VALIDATE_EMAIL))
{
echo "Please Enter The Valid Email Address";
}

$userPassword=mysql_real_escape_string($_POST['userPassword']);
$expiry_date1=mysql_real_escape_string($_POST['expiry_date']);
$expiry_date=date("Y-m-d" ,strtotime($expiry_date1));
$end_date1=mysql_real_escape_string($_POST['end_date']);
$end_date=date("Y-m-d",strtotime($end_date1));

 $regDate = date("Y-m-d");

function generateCode($characters)
{
    $possible = '23456789abcdefghjkmnpqrstuvwxyz!@#$%^&*';
    $code = '';
    $i = 0;
    while ($i < $characters) {
        $code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
        $i++;
    }
    return $code;
}

$registration_key=generateCode(10);

$str="insert into coeds_user(userName,userEmail,userPassword,regDate,expiry_date,registration_key) values('$userName','$userEmail','$userPassword','$regDate','$expiry_date','$registration_key')";

$query=mysql_query($str);
$userid=mysql_insert_id();
if($query)
{
$display="Success";
}

else
{
$display= "Failed";
}

$string="select * from coeds_user where userId=$userid";
$query2=mysql_query($string);
$display.="<table border='1' align='center'>";
$display.="<tr><th>UserName</th><th>UserEmail</th><th>UserPassword</th><th>RegDate</th><th>ExpiryDate</th><th>RegistrationKey</th><th colspan='3'>Action</th></tr>";
while($result=mysql_fetch_array($query2))
{
$display.="<tr>";

$display.="<td>".$result['userName']."</td>";
$display.="<td>".$result['userEmail']."</td>";
$display.="<td>".$result['userPassword']."</td>";
$display.="<td>".$result['regDate']."</td>";
$display.="<td>".$result['expiry_date']."</td>";
$display.="<td>".$result['registration_key']."</td>";
$display.="<td><a id='colour' class='tooltip' title='Edit' href='user_update.php?user_Id=".$result['userId']."'><img id='image' src='./images/small.gif'/></a></td>";
$display.="<td><a id='colour' class='tooltip' data-toggle='tooltip' title='Delete' href='user_delete.php?user_Id=".$result['userId']." '><img id='image' src='./images/trash.png'/></a></td>";

$display.="<td><a id='colour' class='tooltip' data-toggle='tooltip' title='insert' href='chapter_subscription_search.php?user_Id=".$result['userId']." '>i</a></td>";
$display.="</tr>";

$display.="</table>";

 $end_date1 = date('Y-m-d', strtotime("+3 months"));
 $end_date2 = date('Y-m-d', strtotime("+6 months"));
 $end_date3 = date('Y-m-d', strtotime("+9 months"));
 $page="";

 ?>

<table align='center' border='1'>

    <tr>

           <td> <label for="userId">UserId</label></td>
            <td ><input id="userId" name="userId"  type="text" value="<?php echo $userid;?>"/></td>

        </tr>
        <tr>
        <td> <label for="userName">UserName</label></td>
        <td ><input id="userName" name="userName" type="text" value="<?php echo $result['userName'];?>"/></td>
        </tr>
        <tr>
        <td> <label for="userEmail">UserEmail</label></td>
        <td ><input id="userEmail" name="userEmail" type="text" value="<?php echo $result['userEmail'];?>"/></td>
        </tr>
        <tr>
        <td> <label for="userPassword">UserPassword</label></td>
        <td ><input id="userPassword" name="userPassword" type="password" value="<?php echo $result['userPassword'];?>"/></td>
        </tr>
        <tr>
        <td> <label for="expiry_date">ExpiryDate</label></td>
        <td ><input id="expiry_date" name="expiry_date" type="text" value="<?php echo $result['expiry_date'];?>"/></td>
        </tr>
        <tr>
        <td> <label for="end_date">EndDate</label></td>
        <td >  <select name="end_date" id="end_date">
             <option value=<?php echo $end_date1; ?>><?php echo $end_date1; ?></option>
             <option value=<?php echo $end_date2; ?>><?php echo $end_date2; ?> </option>
             <option value=<?php echo $end_date3;?>><?php echo $end_date3;?> </option>

        </select>
</td>
        </tr>

        </table>

<?php
}
$str="select chapter_no from chapter_details ";

$query7=mysql_query($str);

$count=mysql_num_rows($query7);
for($i=0;$i<$count;$i++)
{
$chap_lic=generateCode(50);
$chapter_no=mysql_result($query7,$i,'chapter_no');
$start_date=date('Y-m-d');
$expiry_date=mysql_real_escape_string($_POST['end_date']);
$end_date1=mysql_real_escape_string($_POST['end_date']);
$end_date=date("Y-m-d",strtotime($end_date1));
$s="insert into chapter_subscriptions (userId,chapter_no,start_date,end_date) values($userid,$chapter_no,'$start_date','$end_date')";

$query8=mysql_query($s);
}
$strings="select * from chapter_subscriptions where userId=$userid";
$query9=mysql_query($strings);
$display.="<table border='1' align='center'>";
$display.="<tr><th>ChapterNumber</th><th>StartDate</th><th>EndDate</th><th colspan='2'>Action</th></tr>";
while($result=mysql_fetch_array($query9))
{
$display.="<tr>";
$display.="<td>".$result['chapter_no']."</td>";
$display.="<td>".$result['start_date']."</td>";

$display.="<td>".$result['end_date']."</td>";

$display.="<td><a id='colour' class='tooltip' title='Edit' href='chapter_subscription_update.php?user_Id=".$result['userId']."'><img id='image' src='./images/small.gif'/></a></td>";
$display.="<td><a id='colour' class='tooltip' data-toggle='tooltip' title='Delete' href='chapter_subscription_delete.php?user_Id=".$result['userId']." '><img id='image' src='./images/trash.png'/></a></td>";

$display.="</tr>";
}
$display.="</table>";

echo $display;
}

?>
</div>
 <script type="text/javascript">
    $(document).ready(function() {
    $( "#expiry_date" ).datepicker();
    $("#menuwrapper").hide();
    $("#unicode").click(function() {
        $("#menuwrapper").slideToggle(500);
    });
    });

</script>

</body>
</html>
</code>```

答:
You could consider using a flag variable $valid.

```<code>$valid = true;

if (!filter_var($userEmail, FILTER_VALIDATE_EMAIL)) {
    echo "Please Enter The Valid Email Address";
    $valid = false; // Change to false when an error encounters
}

$userPassword=mysql_real_escape_string($_POST['userPassword']);
/* ------ Other code ---------- */
$registration_key=generateCode(10);

/* Execute INSERT query ONLY IF INPUTS ARE VALID i.e if $valid = true */

if ($valid) {

    $str="insert into coeds_user(userName,userEmail,userPassword,regDate,expiry_date,registration_key) values('$userName','$userEmail','$userPassword','$regDate','$expiry_date','$registration_key')";

    $query=mysql_query($str);
    $userid=mysql_insert_id();
    if($query) {
        $display="Success";
    } else {
        $display= "Failed";
    }
}
</code>```

Body:
I am going to validate the POST variable userEmail. But the problem is even though I used filter_var to validate, it is not working even when inputting a wrong email and instead gets inserted. Can you help me in getting the solution.

insert_dummy.php

<title>Insertion</title>

<?php
include('header/page_header.php');
include('db.php');

if(isset($_POST['add']))
{
$userName=mysql_real_escape_string($_POST['userName']);

$userEmail=mysql_real_escape_string($_POST['userEmail']);
if(!filter_var($userEmail, FILTER_VALIDATE_EMAIL))
{
echo "Please Enter The Valid Email Address";
}

$userPassword=mysql_real_escape_string($_POST['userPassword']);
$expiry_date1=mysql_real_escape_string($_POST['expiry_date']);
$expiry_date=date("Y-m-d" ,strtotime($expiry_date1));
$end_date1=mysql_real_escape_string($_POST['end_date']);
$end_date=date("Y-m-d",strtotime($end_date1));

 $regDate = date("Y-m-d");

function generateCode($characters)
{
    $possible = '23456789abcdefghjkmnpqrstuvwxyz!@#$%^&*';
    $code = '';
    $i = 0;
    while ($i < $characters) {
        $code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
        $i++;
    }
    return $code;
}

$registration_key=generateCode(10);

$str="insert into coeds_user(userName,userEmail,userPassword,regDate,expiry_date,registration_key) values('$userName','$userEmail','$userPassword','$regDate','$expiry_date','$registration_key')";

$query=mysql_query($str);
$userid=mysql_insert_id();
if($query)
{
$display="Success";
}

else
{
$display= "Failed";
}

$string="select * from coeds_user where userId=$userid";
$query2=mysql_query($string);
$display.="
";
$display.="
UserName	UserEmail	UserPassword	RegDate	ExpiryDate	RegistrationKey	Action
";
while($result=mysql_fetch_array($query2))
{
$display.="
";

$display.="".$result['userName']."	";
$display.="".$result['userEmail']."	";
$display.="".$result['userPassword']."	";
$display.="".$result['regDate']."	";
$display.="".$result['expiry_date']."	";
$display.="".$result['registration_key']."	";
$display.="	";
$display.="	";

$display.="i	";
$display.="
";

$display.="
";

 $end_date1 = date('Y-m-d', strtotime("+3 months"));
 $end_date2 = date('Y-m-d', strtotime("+6 months"));
 $end_date3 = date('Y-m-d', strtotime("+9 months"));
 $page="";

 ?>

            UserId
            <input id="userId" name="userId"  type="text" value="<?php echo $userid;?>"/>

         UserName
        <input id="userName" name="userName" type="text" value="<?php echo $result['userName'];?>"/>

         UserEmail
        <input id="userEmail" name="userEmail" type="text" value="<?php echo $result['userEmail'];?>"/>

         UserPassword
        <input id="userPassword" name="userPassword" type="password" value="<?php echo $result['userPassword'];?>"/>

         ExpiryDate
        <input id="expiry_date" name="expiry_date" type="text" value="<?php echo $result['expiry_date'];?>"/>

         EndDate
          <select name="end_date" id="end_date">
             <option value=<?php echo $end_date1; ?>><?php echo $end_date1; ?></option>
             <option value=<?php echo $end_date2; ?>><?php echo $end_date2; ?> </option>
             <option value=<?php echo $end_date3;?>><?php echo $end_date3;?> </option>

        </select>

<?php
}
$str="select chapter_no from chapter_details ";

$query7=mysql_query($str);

$count=mysql_num_rows($query7);
for($i=0;$i<$count;$i++)
{
$chap_lic=generateCode(50);
$chapter_no=mysql_result($query7,$i,'chapter_no');
$start_date=date('Y-m-d');
$expiry_date=mysql_real_escape_string($_POST['end_date']);
$end_date1=mysql_real_escape_string($_POST['end_date']);
$end_date=date("Y-m-d",strtotime($end_date1));
$s="insert into chapter_subscriptions (userId,chapter_no,start_date,end_date) values($userid,$chapter_no,'$start_date','$end_date')";

$query8=mysql_query($s);
}
$strings="select * from chapter_subscriptions where userId=$userid";
$query9=mysql_query($strings);
$display.="
";
$display.="
ChapterNumber	StartDate	EndDate	Action
";
while($result=mysql_fetch_array($query9))
{
$display.="
";
$display.="".$result['chapter_no']."	";
$display.="".$result['start_date']."	";

$display.="".$result['end_date']."	";

$display.="	";
$display.="	";

$display.="
";
}
$display.="
";

echo $display;
}

?>

Body:
You could consider using a flag variable $valid.

$valid = true;

if (!filter_var($userEmail, FILTER_VALIDATE_EMAIL)) {
    echo "Please Enter The Valid Email Address";
    $valid = false; // Change to false when an error encounters
}

$userPassword=mysql_real_escape_string($_POST['userPassword']);
/* ------ Other code ---------- */
$registration_key=generateCode(10);

/* Execute INSERT query ONLY IF INPUTS ARE VALID i.e if $valid = true */

if ($valid) {

    $str="insert into coeds_user(userName,userEmail,userPassword,regDate,expiry_date,registration_key) values('$userName','$userEmail','$userPassword','$regDate','$expiry_date','$registration_key')";

    $query=mysql_query($str);
    $userid=mysql_insert_id();
    if($query) {
        $display="Success";
    } else {
        $display= "Failed";
    }
}


问:
Powershell to executable .bat
I'm trying to get the script below, which is in Powershell, converted to an executable .bat file. The basic idea is that I have a bunch of files of which the file name exists out of 3 parts:

Part 1: TKSYSTEMID

Part 2: Variable name

Part 3: YYYY MM DD HHMM

So a simple example would look like: TKSYSTEMID NOTES YYYY MM DD HHMM

I'm looking for a .bat file that can replace the TKSYSTEM ID and the YYYY MM DD HHMM with something the user gets prompted to input.

The powershell script I have so far is:

```<code>$NEWSYSTEMID = Read-Host -Prompt 'Please input SEJ SYSTEM ID'
Write-Host "Changing TKSYSTEMID to '$NEWSYSTEMID'"
dir | Rename-Item -NewName {$_.name -replace 'TKSYSTEMID',$NEWSYSTEMID}

$NEWDATETIME = Read-Host -Prompt 'Please input the upload date and time'
Write-Host "Changing YYYY MM DD HHMM to '$NEWDATETIME'"
dir | Rename-Item -NewName {$_.name -replace 'YYYY MM DD HHMM',$NEWDATETIME}
</code>```

Could someone be so kind as to show me how to convert this or to provide a .bat script for this? It would mean the world.

答:
Windows doesn't, per default, allow running Powershell scripts by double-clicking a .PS1 file. This actually is a security feature aimed at protecting the less-computer savvy users. Back in the days, VBScript files were a popular attack vector for all kind of malware. This was as VBScript files were runnable by default wit a double-click. It was all too easy to fool inexperienced users to get infected with, say, Love Letter worm.

As a work-around, create a shortcut that launches Powershell's shell and passes parameter to the script. In case of link rot, :

```<code>powershell.exe -command "& 'C:\A path with spaces\MyScript.ps1' -MyArguments blah"
</code>```

Title: Powershell to executable .bat

Body:
I'm trying to get the script below, which is in Powershell, converted to an executable .bat file. The basic idea is that I have a bunch of files of which the file name exists out of 3 parts:

Part 1: TKSYSTEMID

Part 2: Variable name

Part 3: YYYY MM DD HHMM

So a simple example would look like: TKSYSTEMID NOTES YYYY MM DD HHMM

I'm looking for a .bat file that can replace the TKSYSTEM ID and the YYYY MM DD HHMM with something the user gets prompted to input.

The powershell script I have so far is:

$NEWSYSTEMID = Read-Host -Prompt 'Please input SEJ SYSTEM ID'
Write-Host "Changing TKSYSTEMID to '$NEWSYSTEMID'"
dir | Rename-Item -NewName {$_.name -replace 'TKSYSTEMID',$NEWSYSTEMID}

$NEWDATETIME = Read-Host -Prompt 'Please input the upload date and time'
Write-Host "Changing YYYY MM DD HHMM to '$NEWDATETIME'"
dir | Rename-Item -NewName {$_.name -replace 'YYYY MM DD HHMM',$NEWDATETIME}

Could someone be so kind as to show me how to convert this or to provide a .bat script for this? It would mean the world.

Body:
Windows doesn't, per default, allow running Powershell scripts by double-clicking a .PS1 file. This actually is a security feature aimed at protecting the less-computer savvy users. Back in the days, VBScript files were a popular attack vector for all kind of malware. This was as VBScript files were runnable by default wit a double-click. It was all too easy to fool inexperienced users to get infected with, say, Love Letter worm.

As a work-around, create a shortcut that launches Powershell's shell and passes parameter to the script. In case of link rot, :

powershell.exe -command "& 'C:\A path with spaces\MyScript.ps1' -MyArguments blah"


问:
Creating a Zoom Effect on an image on hover using CSS?
I'm currently trying to create a zoom effect on hover over one of my four images. The problem is most examples usually use tables or mask divs to apply some sort of effect.

Here's one example that implements what I would like this.

This is my code so far.

HTML

```<code><div id="menu">
<img class ="blog" src="http://s18.postimg.org/il7hbk7i1/image.png" alt="">
<img class ="music" src="http://s18.postimg.org/4st2fxgqh/image.png" alt="">
<img class ="projects" src="http://s18.postimg.org/sxtrxn115/image.png" alt="">
<img class ="bio" src="http://s18.postimg.org/5xn4lb37d/image.png" alt="">
</div>
</code>```

CSS

```<code>#menu {
    max-width: 1200px;
    text-align: center;
    margin: auto;
}

#menu img {
    width: 250px;
    height: 375px;
    padding: 0px 5px 0px 5px;
    overflow: hidden;
}

.blog {
    height: 375px;
    -webkit-transition: all 1s ease;
    -moz-transition: all 1s ease;
    -o-transition: all 1s ease;
    -ms-transition: all 1s ease;
    transition: all 1s ease;
}

.blog:hover {
    cursor: pointer;
    height:475px;
    width: 350px;
}

.music {
    height: 375px;
}

.projects {
    height: 375px;
}

.bio {
    height: 375px;
}
</code>```

答:
```<code>  <div class="item">
  <img src="yamahdi1.jpg" alt="pepsi" width="50" height="58">
  <img src="yamahdi.jpg" alt="pepsi" width="50" height="58">
  <div class="item-overlay top"></div>
</code>```

css:

```<code>.item img {

  -moz-transition: all 0.3s;
  -webkit-transition: all 0.3s;
  transition: all 0.3s;
}
.item img:hover {
  -moz-transform: scale(1.1);
  -webkit-transform: scale(1.1);
  transform: scale(1.1);
}
</code>```

Body:
I'm currently trying to create a zoom effect on hover over one of my four images. The problem is most examples usually use tables or mask divs to apply some sort of effect.

Here's one example that implements what I would like this.

This is my code so far.

HTML

CSS

#menu {
    max-width: 1200px;
    text-align: center;
    margin: auto;
}

#menu img {
    width: 250px;
    height: 375px;
    padding: 0px 5px 0px 5px;
    overflow: hidden;
}

.blog {
    height: 375px;
    -webkit-transition: all 1s ease;
    -moz-transition: all 1s ease;
    -o-transition: all 1s ease;
    -ms-transition: all 1s ease;
    transition: all 1s ease;
}

.blog:hover {
    cursor: pointer;
    height:475px;
    width: 350px;
}

.music {
    height: 375px;
}

.projects {
    height: 375px;
}

.bio {
    height: 375px;
}

Body:
  <div class="item">
  <img src="yamahdi1.jpg" alt="pepsi" width="50" height="58">
  <img src="yamahdi.jpg" alt="pepsi" width="50" height="58">
  <div class="item-overlay top"></div>

css:

.item img {

  -moz-transition: all 0.3s;
  -webkit-transition: all 0.3s;
  transition: all 0.3s;
}
.item img:hover {
  -moz-transform: scale(1.1);
  -webkit-transform: scale(1.1);
  transform: scale(1.1);
}