问:
angular modal service error
I have on my Single Page App 6 modals which are pretty complex. At the moment I've got them made with controllers, ui-bootstrap style but I don't think it is the best way beacuse controllers got pretty same code over and over again.

I decided to try re-write it as a service but it doesn't work and not showing any error in jsfiddle. Please help me finish of this modal service.

```<code>app.service('modalService', ['$modal',
    function ($modal) {

        var modalDefaults = {
            backdrop: true,
            keyboard: true,
            modalFade: true,
            templateUrl: '/app/partials/modal.html'
        };

        var modalOptions = {
            closeButtonText: 'Close',
            actionButtonText: 'OK',
            headerText: 'Proceed?',
            bodyText: 'Perform this action?'
        };

        this.showModal = function (customModalDefaults, customModalOptions) {
            if (!customModalDefaults) customModalDefaults = {};
            customModalDefaults.backdrop = 'static';
            return this.show(customModalDefaults, customModalOptions);
        };

        this.show = function (customModalDefaults, customModalOptions) {
            //Create temp objects to work with since we're in a singleton service
            var tempModalDefaults = {};
            var tempModalOptions = {};

            //Map angular-ui modal custom defaults to modal defaults defined in service
            angular.extend(tempModalDefaults, modalDefaults, customModalDefaults);

            //Map modal.html $scope custom properties to defaults defined in service
            angular.extend(tempModalOptions, modalOptions, customModalOptions);

            if (!tempModalDefaults.controller) {
                tempModalDefaults.controller = function ($scope, $modalInstance) {
                    $scope.modalOptions = tempModalOptions;
                    $scope.modalOptions.ok = function (result) {
                        $modalInstance.close(result);
                    };
                    $scope.modalOptions.close = function (result) {
                        $modalInstance.dismiss('cancel');
                    };
                }
            }

            return $modal.open(tempModalDefaults).result;
        };

    }]);
</code>```

http://jsfiddle.net/8MVLJ/3095/

答:
Since you use UI Bootstrap, You need to correct below things:

Inject 'ui.bootstrap' as module., like angular.module('app', ['ui.bootstrap']);

Change $modal to '$uibModal'

From HTML you need to call controller $scope function to show modal popup., so create method in controller.

Remove $scope from controller, it can't be injected to service, only passed through the function param.

Here is demo fiddle of your code.

further also Read the Doc. and go through doc plunker as well.

Title: angular modal service error

Body:
I have on my Single Page App 6 modals which are pretty complex. At the moment I've got them made with controllers, ui-bootstrap style but I don't think it is the best way beacuse controllers got pretty same code over and over again.

I decided to try re-write it as a service but it doesn't work and not showing any error in jsfiddle. Please help me finish of this modal service.

app.service('modalService', ['$modal',
    function ($modal) {

        var modalDefaults = {
            backdrop: true,
            keyboard: true,
            modalFade: true,
            templateUrl: '/app/partials/modal.html'
        };

        var modalOptions = {
            closeButtonText: 'Close',
            actionButtonText: 'OK',
            headerText: 'Proceed?',
            bodyText: 'Perform this action?'
        };

        this.showModal = function (customModalDefaults, customModalOptions) {
            if (!customModalDefaults) customModalDefaults = {};
            customModalDefaults.backdrop = 'static';
            return this.show(customModalDefaults, customModalOptions);
        };

        this.show = function (customModalDefaults, customModalOptions) {
            //Create temp objects to work with since we're in a singleton service
            var tempModalDefaults = {};
            var tempModalOptions = {};

            //Map angular-ui modal custom defaults to modal defaults defined in service
            angular.extend(tempModalDefaults, modalDefaults, customModalDefaults);

            //Map modal.html $scope custom properties to defaults defined in service
            angular.extend(tempModalOptions, modalOptions, customModalOptions);

            if (!tempModalDefaults.controller) {
                tempModalDefaults.controller = function ($scope, $modalInstance) {
                    $scope.modalOptions = tempModalOptions;
                    $scope.modalOptions.ok = function (result) {
                        $modalInstance.close(result);
                    };
                    $scope.modalOptions.close = function (result) {
                        $modalInstance.dismiss('cancel');
                    };
                }
            }

            return $modal.open(tempModalDefaults).result;
        };

    }]);

http://jsfiddle.net/8MVLJ/3095/


来源: stackexchange

问:
how to close android app completely
I created an android application with a logout option in onCreateOptionsMenu. The Logout works perfectly but when I press the back button again it takes me to the previous activity, and when it gets a null value it redirects to login screen. Now my login screen appears again and again. I want to close the app completely when I press the back button but don't know how.

Here is my code to handle the back button press in the login screen:

```<code>@Override
public void onBackPressed() {
    new AlertDialog.Builder(this)
        .setTitle("BidNEMO")
        .setMessage("Are you sure you want to exit?")
        .setNegativeButton(android.R.string.no, null)
        .setPositiveButton(android.R.string.yes, new OnClickListener() {
         public void onClick(DialogInterface arg0, int arg1) {
         Main.super.onBackPressed();
         finish();
         }
         }).create().show();
     }
</code>```

please help guyss..

答:
For Xamarin Users:

```<code>int pid = Android.OS.Process.MyPid();
Android.OS.Process.KillProcess(pid);
</code>```

put it in your OnDestroy() function.

Edit:

After investigating it thoroughly, I found out that even the above code I wrote does not "Kill" the app totally (deleting it from task manager - "recent apps"). Eventually, after a lot of code tryouts, I managed to figure something out, Overriding "Finish" functions with this code:

```<code>public override void Finish()
    {
        if (Android.OS.Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
        {
            base.FinishAndRemoveTask();
        }
        else
        {
            base.Finish();
        }
    }
</code>```

this is the sole solution for that question!

ContentLicense: CC BY-SA 3.0

Title: how to close android app completely

Body:
I created an android application with a logout option in onCreateOptionsMenu. The Logout works perfectly but when I press the back button again it takes me to the previous activity, and when it gets a null value it redirects to login screen. Now my login screen appears again and again. I want to close the app completely when I press the back button but don't know how.

Here is my code to handle the back button press in the login screen:

@Override
public void onBackPressed() {
    new AlertDialog.Builder(this)
        .setTitle("BidNEMO")
        .setMessage("Are you sure you want to exit?")
        .setNegativeButton(android.R.string.no, null)
        .setPositiveButton(android.R.string.yes, new OnClickListener() {
         public void onClick(DialogInterface arg0, int arg1) {
         Main.super.onBackPressed();
         finish();
         }
         }).create().show();
     }

please help guyss..

Body:
For Xamarin Users:

int pid = Android.OS.Process.MyPid();
Android.OS.Process.KillProcess(pid);

put it in your OnDestroy() function.

Edit:

After investigating it thoroughly, I found out that even the above code I wrote does not "Kill" the app totally (deleting it from task manager - "recent apps"). Eventually, after a lot of code tryouts, I managed to figure something out, Overriding "Finish" functions with this code:

public override void Finish()
    {
        if (Android.OS.Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
        {
            base.FinishAndRemoveTask();
        }
        else
        {
            base.Finish();
        }
    }

this is the sole solution for that question!


问:
Why my @Async Future<T> blocks?
I have 2 Synchronous methods, the following one does not block.

```<code>@RequestMapping("/send1")
    @Async
    public Future<Boolean> sendMail() throws InterruptedException {
        System.out.println("sending mail 1..-"
                + Thread.currentThread().getName());
        Thread.sleep(1000 * 16);
        System.out.println("sending mail 1 completed");
        return new AsyncResult<Boolean>(true);
    }
</code>```

But the following one blocks.

```<code>@RequestMapping("/send3")
    public void callAsyn3() throws InterruptedException, ExecutionException {
Future<Boolean> go = sendMail3("test");
}

@Async
public Future<Boolean> sendMail3(String msg) throws InterruptedException {
        boolean acceptedYet = false;
        Thread.sleep(1000 * 12);
        if (!msg.equalsIgnoreCase("")) {
            acceptedYet = true;
        }
        return new AsyncResult<>(acceptedYet);
    }
</code>```

They are in the same controller class, Why such different behavior?

答:
In the second case you call internally method. so the @Async is ignored (not proxyed method called).

There are two ways to fix

The first one is to ntroduce a separate bean (e.g. MyService) and move the annotated with @Async method there.

The second way is Autowire the controller to itself

@Controller
public class MyController {

```<code>@Autowired
private MyController myController;

@RequestMapping("/send3")
public void callAsyn3() throws InterruptedException, ExecutionException {
     Future<Boolean> go = myController.sendMail3("test");
}

@Async
public Future<Boolean> sendMail3(String msg) throws InterruptedException {
    boolean acceptedYet = false;
    Thread.sleep(1000 * 12);
    if (!msg.equalsIgnoreCase("")) {
        acceptedYet = true;
    }
    return new AsyncResult<>(acceptedYet);
}
</code>```

Title: Why my @Async Future<T> blocks?

Body:
I have 2 Synchronous methods, the following one does not block.

@RequestMapping("/send1")
    @Async
    public Future<Boolean> sendMail() throws InterruptedException {
        System.out.println("sending mail 1..-"
                + Thread.currentThread().getName());
        Thread.sleep(1000 * 16);
        System.out.println("sending mail 1 completed");
        return new AsyncResult<Boolean>(true);
    }

But the following one blocks.

@RequestMapping("/send3")
    public void callAsyn3() throws InterruptedException, ExecutionException {
Future<Boolean> go = sendMail3("test");
}

@Async
public Future<Boolean> sendMail3(String msg) throws InterruptedException {
        boolean acceptedYet = false;
        Thread.sleep(1000 * 12);
        if (!msg.equalsIgnoreCase("")) {
            acceptedYet = true;
        }
        return new AsyncResult<>(acceptedYet);
    }

They are in the same controller class, Why such different behavior?

Body:
In the second case you call internally method. so the @Async is ignored (not proxyed method called).

There are two ways to fix

The first one is to ntroduce a separate bean (e.g. MyService) and move the annotated with @Async method there.

The second way is Autowire the controller to itself

@Controller
public class MyController {

@Autowired
private MyController myController;

@RequestMapping("/send3")
public void callAsyn3() throws InterruptedException, ExecutionException {
     Future<Boolean> go = myController.sendMail3("test");
}

@Async
public Future<Boolean> sendMail3(String msg) throws InterruptedException {
    boolean acceptedYet = false;
    Thread.sleep(1000 * 12);
    if (!msg.equalsIgnoreCase("")) {
        acceptedYet = true;
    }
    return new AsyncResult<>(acceptedYet);
}


问:
Perl script seg faults in Cmenu
I am getting a core dump when I use the Cmenu module on Solaris 8. The script works fine on Solaris 10.  Could somebody please suggest a possible workaround for this? Using dbx shows the following:

```<code>terminated by signal SEGV (no mapping at the fault address)

Current function is Perl_safesysmalloc
92   Ptr = (Malloc_t)PerlMem_malloc(size?size:1)

 Perl_safesysmalloc(size = 4U), line 92 in "util.c"
</code>```

I built version 5.10 of Perl using gcc on this machine. Please let me know if you have need any other information.

答:
Cmenu is a pure perl module that uses Curses.pm which is based on a C library. So mosts probable place for core dump is Curses.pm. Try upgrading it to latest version. Also try upgrading curses library.

If this does not help, try minimizing your program to get a minimal program that would still result a core dump. Report it to Cmenu bug tracker.

ContentLicense: CC BY-SA 2.5

Title: Perl script seg faults in Cmenu

Body:
I am getting a core dump when I use the Cmenu module on Solaris 8. The script works fine on Solaris 10.  Could somebody please suggest a possible workaround for this? Using dbx shows the following:

terminated by signal SEGV (no mapping at the fault address)

Current function is Perl_safesysmalloc
92   Ptr = (Malloc_t)PerlMem_malloc(size?size:1)

 Perl_safesysmalloc(size = 4U), line 92 in "util.c"

I built version 5.10 of Perl using gcc on this machine. Please let me know if you have need any other information.


问:
Using a refresh token in AAD B2C with Azure App Service and Xamarin.Forms
I'm trying to get a refresh token set up in my Xamarin.Forms app using AAD B2C. I've got everything set up but run into issues when calling LoginAsync on my MobileServiceClient. All of the docs and examples I can find show to update my LoginAsync method to this:

```<code>var user = await App.MobileServiceClient.LoginAsync(MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory,
    new Dictionary<string, string>() { { "response_type", "code id_token" } });
</code>```

Except that the MobileServiceClient does not take a Dictionary<string, string> for the second parameter. It takes a JObject. Here's what my current code looks like:

```<code>var authResult = await App.AuthenticationClient.AcquireTokenAsync(Constants.Scopes, "", UiOptions.SelectAccount, string.Empty, null, Constants.Authority, Constants.Policy);

var payload = new JObject();
payload["access_token"] = authResult.Token;

var user = await App.MobileServiceClient.LoginAsync(MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory, payload);
</code>```

I can not find an example use the JObject anywhere.

It is as simple as adding payload["response_type"] = "code id_token"; to my payload?

答:
AFAIK, Mobile Apps support two authentication flows (client-managed flow and server-managed flow).

Client-managed authentication

Your app can independently contact the identity provider and then provide the returned token during login with your backend. This client flow enables you to provide a single sign-on experience for users or to retrieve additional user data from the identity provider.

After you retrieved the token, then you would login with your azure mobile backend by passing the token into a JObject instance as follows:

```<code>JObject payload = new JObject();
payload["access_token"] = ar.AccessToken;
var user = await client.LoginAsync(MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory, payload);
</code>```

For more details about other identity providers via client-flow authentication, you could refer to Client-managed authentication.

Server-managed authentication

Your app directly contacts your mobile backend, then your azure mobile backend contacts the identity provider and provide you with the logged user.

For Xamarin.Forms UWP app, you could login as follows:

For Xamarin.Forms IOS app, you could login as follows:

For more details about server-managed authentication in Xamarin.Forms, you could refer to Add authentication to your Xamarin Forms app.

UPDATE:

I have checked that if you call MobileServiceClient.LoginAsync in PCL, you could not see any extensions for LoginAsync. As you could see, there are many extension LoginAsync methods in the Microsoft.WindowsAzure.Mobile.Ext.dll for each platform. You need to define the IAuthenticate interface and implement it in each of your app (uwp, android, ios, etc.), for more details you could refer to here.

Body:
I'm trying to get a refresh token set up in my Xamarin.Forms app using AAD B2C. I've got everything set up but run into issues when calling LoginAsync on my MobileServiceClient. All of the docs and examples I can find show to update my LoginAsync method to this:

var user = await App.MobileServiceClient.LoginAsync(MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory,
    new Dictionary<string, string>() { { "response_type", "code id_token" } });

Except that the MobileServiceClient does not take a Dictionary<string, string> for the second parameter. It takes a JObject. Here's what my current code looks like:

var authResult = await App.AuthenticationClient.AcquireTokenAsync(Constants.Scopes, "", UiOptions.SelectAccount, string.Empty, null, Constants.Authority, Constants.Policy);

var payload = new JObject();
payload["access_token"] = authResult.Token;

var user = await App.MobileServiceClient.LoginAsync(MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory, payload);

I can not find an example use the JObject anywhere.

It is as simple as adding payload["response_type"] = "code id_token"; to my payload?

Body:
AFAIK, Mobile Apps support two authentication flows (client-managed flow and server-managed flow).

Client-managed authentication

Your app can independently contact the identity provider and then provide the returned token during login with your backend. This client flow enables you to provide a single sign-on experience for users or to retrieve additional user data from the identity provider.

After you retrieved the token, then you would login with your azure mobile backend by passing the token into a JObject instance as follows:

JObject payload = new JObject();
payload["access_token"] = ar.AccessToken;
var user = await client.LoginAsync(MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory, payload);

For more details about other identity providers via client-flow authentication, you could refer to Client-managed authentication.

Server-managed authentication

Your app directly contacts your mobile backend, then your azure mobile backend contacts the identity provider and provide you with the logged user.

For Xamarin.Forms UWP app, you could login as follows:

For Xamarin.Forms IOS app, you could login as follows:

For more details about server-managed authentication in Xamarin.Forms, you could refer to Add authentication to your Xamarin Forms app.

UPDATE:

I have checked that if you call MobileServiceClient.LoginAsync in PCL, you could not see any extensions for LoginAsync. As you could see, there are many extension LoginAsync methods in the Microsoft.WindowsAzure.Mobile.Ext.dll for each platform. You need to define the IAuthenticate interface and implement it in each of your app (uwp, android, ios, etc.), for more details you could refer to here.


问:
Getting expression text
I want to pass the name of a property of a model to a method. Instead of using the name as string, I am using lambda expression as it is easy to make a typo, and also property names may be changed. Now if the property is a simple property (e.g: model.Name) I can get the name from the expression. But if it is a nested property (e.g: model.AnotherModel.Name) then how can I get full text ("AnotherModel.Name") from the expression. For example, I have the following classes:</p>

```<code>public class BaseModel
{
    public ChildModel Child { get; set; }
    public List<ChildModel> ChildList { get; set; }

    public BaseModel()
    {
        Child = new ChildModel();
        ChildList = new List<ChildModel>();
    }
}

public class ChildModel
{
    public string Name { get;set; }
}

public void GetExpressionText<T>(Expression<Func<T, object>> expression)
{
    string expText;
    //what to do??
    return expText;
}

GetExpressionText<BaseModel>(b => b.Child); //should return "Child"
GetExpressionText<BaseModel>(b => b.Child.Name); //should return "Child.Name"
GetExpressionText<BaseModel>(b => b.ChildList[0].Name); //should return "ChildList[0].Name"
</code>```

答:
Closest i know right now is by simply using expression.Body.ToString() which would result in b.ChildList.get_Item(0).Name as a result.

You would still have to remove the first b. from the string if not wanted, and you could go even further to your intended output with Regex by replacing the get_Item(0) with the typical Index-Accessor.

(Also i had to make the ChildList and the Name-Property of ChildModel public to get it to work)

Title: Getting expression text

Body:
I want to pass the name of a property of a model to a method. Instead of using the name as string, I am using lambda expression as it is easy to make a typo, and also property names may be changed. Now if the property is a simple property (e.g: model.Name) I can get the name from the expression. But if it is a nested property (e.g: model.AnotherModel.Name) then how can I get full text ("AnotherModel.Name") from the expression. For example, I have the following classes:

public class BaseModel
{
    public ChildModel Child { get; set; }
    public List<ChildModel> ChildList { get; set; }

    public BaseModel()
    {
        Child = new ChildModel();
        ChildList = new List<ChildModel>();
    }
}

public class ChildModel
{
    public string Name { get;set; }
}

public void GetExpressionText<T>(Expression<Func<T, object>> expression)
{
    string expText;
    //what to do??
    return expText;
}

GetExpressionText<BaseModel>(b => b.Child); //should return "Child"
GetExpressionText<BaseModel>(b => b.Child.Name); //should return "Child.Name"
GetExpressionText<BaseModel>(b => b.ChildList[0].Name); //should return "ChildList[0].Name"


问:
Can't get value until pattern matches in a required input field
Using AngularJs, I'm trying to store the input field's value to $scope.newPassword but it only works after I have typed at least 6 characters. Is it the default behavior or is there any way to handle it?

Here's some code:

HTML

```<code><input type="password" class="form-control" id="new-password" ng-model="newPassword" name="new-password" required pattern=".{6,}">
</code>```

JS

```<code>app.controller('validationController', function($scope) {
       $scope.noMatch = false;
       $scope.newPassword="";
       $scope.confirmNewPassword="";
       $scope.passMatchTest = function(){
           if($scope.newPassword!=$scope.confirmNewPassword){
               $scope.noMatch = true;
               $("#new-password, #confirm-new-password").css("background-color", "#f0b9b9");
           }else{
               $scope.noMatch = false;
               $("#new-password, #confirm-new-password").css("background-color", "#aff3af");
           }
       };
       $scope.$watch("newPassword", function(){
           console.log($scope.newPassword);
           $scope.passMatchTest();

       });
       $scope.$watch("confirmNewPassword", function(){
           console.log($scope.confirmNewPassword);
           $scope.passMatchTest();
       });
   });
</code>```

console.log shows undefined unless there are more than 6 characters.

答:
Angular will stop reflecting invalid value by default when using pattern or ng-pattern. you can add ng-model-options="{allowInvalid: true}" which will allow invalid value to be populated to ng-model.

```<code><input type="password" class="form-control" id="new-password" ng-model="newPassword" name="new-password" required pattern=".{6,}" ng-model-options="{allowInvalid: true}">
</code>```

Body:
Using AngularJs, I'm trying to store the input field's value to $scope.newPassword but it only works after I have typed at least 6 characters. Is it the default behavior or is there any way to handle it?

Here's some code:

HTML

<input type="password" class="form-control" id="new-password" ng-model="newPassword" name="new-password" required pattern=".{6,}">

JS

app.controller('validationController', function($scope) {
       $scope.noMatch = false;
       $scope.newPassword="";
       $scope.confirmNewPassword="";
       $scope.passMatchTest = function(){
           if($scope.newPassword!=$scope.confirmNewPassword){
               $scope.noMatch = true;
               $("#new-password, #confirm-new-password").css("background-color", "#f0b9b9");
           }else{
               $scope.noMatch = false;
               $("#new-password, #confirm-new-password").css("background-color", "#aff3af");
           }
       };
       $scope.$watch("newPassword", function(){
           console.log($scope.newPassword);
           $scope.passMatchTest();

       });
       $scope.$watch("confirmNewPassword", function(){
           console.log($scope.confirmNewPassword);
           $scope.passMatchTest();
       });
   });

console.log shows undefined unless there are more than 6 characters.

Body:
Angular will stop reflecting invalid value by default when using pattern or ng-pattern. you can add ng-model-options="{allowInvalid: true}" which will allow invalid value to be populated to ng-model.

<input type="password" class="form-control" id="new-password" ng-model="newPassword" name="new-password" required pattern=".{6,}" ng-model-options="{allowInvalid: true}">


问:
gcc or g++ path search order on default directories when linking libraries
I've seen this article and learned that:

Directories specified on the command line with -L option are searched before the default directories.

The directories specified in -L are searched in the order in which they are specified on the command line.

The question is: Is there an search order for the default directories?

For example, if I run this command:

```<code>$ gcc -Xlinker --verbose  2>/dev/null | grep SEARCH | sed 's/SEARCH_DIR("=\?\([^"]\+\)"); */\1\n/g'  | grep -vE '^$'
</code>```

(command copied from this article)

it prints out /usr/local/lib before /usr/lib in my machine (Ubuntu 16.04, 64-bit, gcc 5.4.0). In this case, will /usr/local/lib be searched before /usr/lib?

答:
From the binutils ld manual section 3.4.2 Commands Dealing with Files:

SEARCH_DIR(path)

The SEARCH_DIR command adds path to the list of paths where ld looks for archive libraries. Using SEARCH_DIR(path) is exactly like using `-L path' on the command line (see Command Line Options). If both are used, then the linker will search both paths. Paths specified using the command line option are searched first.

So, yes, as the default directories are given in the default linker script using this SEARCH_DIR() command, they will be searched in the order the SEARCH_DIR() commands appear.

E.g., in my mingw installation, the default linker script starts like this:

```<code>/* Default linker script, for normal executables */
/* Copyright (C) 2014-2017 Free Software Foundation, Inc.
   Copying and distribution of this script, with or without modification,
   are permitted in any medium without royalty provided the copyright
   notice and this notice are preserved.  */
OUTPUT_FORMAT(pei-i386)
SEARCH_DIR("=/mingw32/i686-w64-mingw32/lib");
SEARCH_DIR("=/mingw32/lib");
SEARCH_DIR("=/usr/local/lib");
SEARCH_DIR("=/lib");
SEARCH_DIR("=/usr/lib");
</code>```

--> A library in /usr/local/lib can override libraries in /lib and /usr/lib, but not libraries provided by mingw itself.

Body:
I've seen this article and learned that:

Directories specified on the command line with -L option are searched before the default directories.

The directories specified in -L are searched in the order in which they are specified on the command line.

The question is: Is there an search order for the default directories?

For example, if I run this command:

$ gcc -Xlinker --verbose  2>/dev/null | grep SEARCH | sed 's/SEARCH_DIR("=\?\([^"]\+\)"); */\1\n/g'  | grep -vE '^$'

(command copied from this article)

it prints out /usr/local/lib before /usr/lib in my machine (Ubuntu 16.04, 64-bit, gcc 5.4.0). In this case, will /usr/local/lib be searched before /usr/lib?

Body:
From the binutils ld manual section 3.4.2 Commands Dealing with Files:

SEARCH_DIR(path)

The SEARCH_DIR command adds path to the list of paths where ld looks for archive libraries. Using SEARCH_DIR(path) is exactly like using `-L path' on the command line (see Command Line Options). If both are used, then the linker will search both paths. Paths specified using the command line option are searched first.

So, yes, as the default directories are given in the default linker script using this SEARCH_DIR() command, they will be searched in the order the SEARCH_DIR() commands appear.

E.g., in my mingw installation, the default linker script starts like this:

/* Default linker script, for normal executables */
/* Copyright (C) 2014-2017 Free Software Foundation, Inc.
   Copying and distribution of this script, with or without modification,
   are permitted in any medium without royalty provided the copyright
   notice and this notice are preserved.  */
OUTPUT_FORMAT(pei-i386)
SEARCH_DIR("=/mingw32/i686-w64-mingw32/lib");
SEARCH_DIR("=/mingw32/lib");
SEARCH_DIR("=/usr/local/lib");
SEARCH_DIR("=/lib");
SEARCH_DIR("=/usr/lib");

--> A library in /usr/local/lib can override libraries in /lib and /usr/lib, but not libraries provided by mingw itself.


问:
Unable to bring uploaded images into uploads file using php
After creating a form and typing the php code, i have a form where i am able to input a file, specifically an image, and without reciving any error messages, as well as getting the success message in my url, the image uploaded still can not be found in its destination folder.

Here is the HTML

```<code><form action="" class="navbar-form navbar-right" role="search">
                    <div class="form-group">
                        <input type="text" class="form-control" placeholder="Find Art Here">
                    </div>
                    <button type="submit" class="btn btn-primary">Search</button>
                </form>
</code>```

and here's the php

```<code><?php
if (isset($_POST['submit'])) {
$file = $_FILES['file'];

$fileName = $file['name'];
$fileTmpName = $file['tmp_name'];
$fileSize = $file['size'];
$fileError = $file['error'];
$fileType = $file['type'];

$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));

$allow = array('jpg', 'jpeg', 'png', 'pdf');

if (in_array($fileActualExt, $allow)) {
    if($fileError === 0){
        if($fileSize < 5000000) {
            $fileNameNew = uniqid('', true).".".$fileActualExt;
        $fileDestination = 'uplaods/'.$fileNameNew;
        move_uploaded_file($fileTmpName, $fileDestination);
            header("Location: index.php?uploadsucess");
        } else{
            echo "Your file is too big";
        }
    } else {
        echo "There was an error uplaoding your file!";
    }
} else{
    echo "You cannot upload files of this type!";
}
</code>```

}

Code is based and modified from this video : https://www.youtube.com/watch?v=JaRq73y5MJk

Any help would be much appreciated!

答:
how did you communicate with $_FILES? You need to use
type="file" in your input

Body:
After creating a form and typing the php code, i have a form where i am able to input a file, specifically an image, and without reciving any error messages, as well as getting the success message in my url, the image uploaded still can not be found in its destination folder.

Here is the HTML

<form action="" class="navbar-form navbar-right" role="search">

                        <input type="text" class="form-control" placeholder="Find Art Here">

                    <button type="submit" class="btn btn-primary">Search</button>
                </form>

and here's the php

<?php
if (isset($_POST['submit'])) {
$file = $_FILES['file'];

$fileName = $file['name'];
$fileTmpName = $file['tmp_name'];
$fileSize = $file['size'];
$fileError = $file['error'];
$fileType = $file['type'];

$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));

$allow = array('jpg', 'jpeg', 'png', 'pdf');

if (in_array($fileActualExt, $allow)) {
    if($fileError === 0){
        if($fileSize < 5000000) {
            $fileNameNew = uniqid('', true).".".$fileActualExt;
        $fileDestination = 'uplaods/'.$fileNameNew;
        move_uploaded_file($fileTmpName, $fileDestination);
            header("Location: index.php?uploadsucess");
        } else{
            echo "Your file is too big";
        }
    } else {
        echo "There was an error uplaoding your file!";
    }
} else{
    echo "You cannot upload files of this type!";
}

}

Code is based and modified from this video : https://www.youtube.com/watch?v=JaRq73y5MJk

Any help would be much appreciated!


问:
Multiple Template Matching
I am trying to do Multiple template matching on teeth.

```<code>import numpy as np
import cv2
import glob

X_data=[]
files = glob.glob ('C:/Users/amuly/Pictures/Saved Pictures/template/*.jpg')

img=cv2.imread('C:/Users/amuly/Pictures/Saved Pictures/teeth.jpeg')
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

for myfile in files:
    temp=cv2.imread(myfile)
    w,h=temp.shape[::-1]
</code>```

I am getting the error    too many values to unpack after this line.
Kindly help.

```<code>    res=cv2.matchTemplate(gray,temp,cv2.TM_CCOEFF_NORMED)
    threshold=0.86
    loc=np.where(res>=threshold)
    for pt in zip(*loc[::-1]):
        cv2.rectangle(img,pt,(pt[0]+w,pt[1]+h),(0,255,255),2)

cv2.imshow('Detected',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

答:
in case your image is in color, the temp.shape will return a tuple with 3 values. You can't unpack that into 2 variables, you need three.

Maybe you also have a double colon by accident in your code.

```<code> w,h=temp.shape[::-1]
</code>```

This would work and remove last element from tuple, so that you can unpack to two variables.

```<code> w,h=temp.shape[:-1]
</code>```

Title: Multiple Template Matching

Body:
I am trying to do Multiple template matching on teeth.

import numpy as np
import cv2
import glob

X_data=[]
files = glob.glob ('C:/Users/amuly/Pictures/Saved Pictures/template/*.jpg')

img=cv2.imread('C:/Users/amuly/Pictures/Saved Pictures/teeth.jpeg')
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

for myfile in files:
    temp=cv2.imread(myfile)
    w,h=temp.shape[::-1]

I am getting the error    too many values to unpack after this line.
Kindly help.

    res=cv2.matchTemplate(gray,temp,cv2.TM_CCOEFF_NORMED)
    threshold=0.86
    loc=np.where(res>=threshold)
    for pt in zip(*loc[::-1]):
        cv2.rectangle(img,pt,(pt[0]+w,pt[1]+h),(0,255,255),2)

cv2.imshow('Detected',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Body:
in case your image is in color, the temp.shape will return a tuple with 3 values. You can't unpack that into 2 variables, you need three.

Maybe you also have a double colon by accident in your code.

 w,h=temp.shape[::-1]

This would work and remove last element from tuple, so that you can unpack to two variables.

 w,h=temp.shape[:-1]


问:
how to insert numeric(10,6) datatype column value in to numeric(8,6) datatype column
I have a table TABLEA with COL1 NUMERIC(8,6) and need to insert a value from second table TABLEB which contains a value 123.000000.I have tried below scenarios.In this case i have to use NVL function and CAST together

```<code>SELECT CAST(899.000000 AS NUMERIC(8,6))-- This gives Numeric overflow.  Value does not fit in a numeric(8,6)
</code>```

Tried below as well

```<code>CAST(NVL(COL1,0) AS NUMERIC(10,6)) -- ERROR:  0 : Numeric value out of range
</code>```

Any insights would be helpful.
Thanks in advance.

答:
You'll need to change the datatype of TABLEA.COL1

Note the following:

```<code>SELECT CAST(899.00000 AS NUMERIC(8,6)) /*Overflow*/
SELECT CAST(899.00000 AS NUMERIC(8,5)) /*Works*/
SELECT CAST(899.00000 AS NUMERIC(9,6)) /*Works*/
SELECT CAST(99.123456 AS NUMERIC(8,6)) /*Works*/
SELECT CAST(100 AS NUMERIC(8,6)) /*Overflow*/
SELECT CAST(99.9999994 AS NUMERIC(8,6)) /*Works (rounds down to 99.999999)*/
SELECT CAST(99.9999995 AS NUMERIC(8,6)) /*Overflow (rounds up to 100)*/
</code>```

Basically, "(8 - 6) == 2", so numeric(8, 6) cannot store any number with more than 2 digits left of the decimal point. I.e. cannot store any number >= 100.

From w3schools.com

```
Data type     | Description
------------- | -----------
DECIMAL(p,s)  | Exact numerical, precision p, scale s.
                Example: decimal(5,2) is a number that has
                3 digits before the decimal and 2 digits after the decimal
NUMERIC(p,s)  | Exact numerical, precision p, scale s. (Same as DECIMAL)
```

Body:
I have a table TABLEA with COL1 NUMERIC(8,6) and need to insert a value from second table TABLEB which contains a value 123.000000.I have tried below scenarios.In this case i have to use NVL function and CAST together

SELECT CAST(899.000000 AS NUMERIC(8,6))-- This gives Numeric overflow.  Value does not fit in a numeric(8,6)

Tried below as well

CAST(NVL(COL1,0) AS NUMERIC(10,6)) -- ERROR:  0 : Numeric value out of range

Any insights would be helpful.
Thanks in advance.

Body:
You'll need to change the datatype of TABLEA.COL1

Note the following:

SELECT CAST(899.00000 AS NUMERIC(8,6)) /*Overflow*/
SELECT CAST(899.00000 AS NUMERIC(8,5)) /*Works*/
SELECT CAST(899.00000 AS NUMERIC(9,6)) /*Works*/
SELECT CAST(99.123456 AS NUMERIC(8,6)) /*Works*/
SELECT CAST(100 AS NUMERIC(8,6)) /*Overflow*/
SELECT CAST(99.9999994 AS NUMERIC(8,6)) /*Works (rounds down to 99.999999)*/
SELECT CAST(99.9999995 AS NUMERIC(8,6)) /*Overflow (rounds up to 100)*/

Basically, "(8 - 6) == 2", so numeric(8, 6) cannot store any number with more than 2 digits left of the decimal point. I.e. cannot store any number >= 100.

From w3schools.com

Data type     | Description
------------- | -----------
DECIMAL(p,s)  | Exact numerical, precision p, scale s.
                Example: decimal(5,2) is a number that has
                3 digits before the decimal and 2 digits after the decimal
NUMERIC(p,s)  | Exact numerical, precision p, scale s. (Same as DECIMAL)


问:
Oracle Custom sorting is not working
I have an issue while sorting a column in a custom order in Oracle.

I need a particular row in the column to come first and then the remaining items should come down below in the alphabetic order. The column has a data starting with alphabets, numbers and special characters.. whenever i try to sort the column by ASC it is returning me starting with Special characters first following by number and then alphabets.

Eg result Set

```<code>ACCOUNT_NAME
-------------
First Row
Second Row
Third Row
Fourth Row
Fifth Row
$Specialchar Row
4Number Row
Alpha Row
</code>```

Expected result in the below order

```<code>ACCOUNT_NAME
-------------
First Row
Alpha Row
Fifth Row
Fourth Row
Second Row
Third Row
4Number Row
$Specialchar Row
</code>```

I have tried executing the below query but it doesn't seems to be work

```<code>SELECT ACCOUNT_NAME   FROM ACCOUNT
   ORDER BY decode(ACCOUNT_NAME,'First Row',1),
    regexp_substr(UPPER(ACCOUNT_NAME), '^[a-zA-Z]') ASC;
</code>```

答:
If I understand well, you want to order this way:

an hardcoded values comes as first

strings starting with a letter, in alphabetic order

the strings starting with a digit

then all other strings, based on the ASCII value

If so, you may use a case to build a value to use in the order:

```<code>/* sample data */
with example(ACCOUNT_NAME) as (
    select 'First Row' from dual union all
    select 'Second Row' from dual union all
    select 'Third Row' from dual union all
    select 'Fourth Row' from dual union all
    select 'Fifth Row' from dual union all
    select '$Specialchar Row' from dual union all
    select '4Number Row' from dual union all
    select 'Alpha Row' from dual
)
/* query */
select *
from example
order by case
            when account_name = 'First Row' then 1
            when regexp_like(account_name, '^[A-Za-z]') then 2
            when regexp_like(account_name, '^[0-9]') then 3
            else 4
         end,
         account_name
</code>```

How it works:

```<code>select case
            when account_name = 'First Row' then 1
            when regexp_like(account_name, '^[A-Za-z]') then 2
            when regexp_like(account_name, '^[0-9]') then 3
            else 4
         end as orderByValue,
         account_name
from example
order by case
            when account_name = 'First Row' then 1
            when regexp_like(account_name, '^[A-Za-z]') then 2
            when regexp_like(account_name, '^[0-9]') then 3
            else 4
         end,
         account_name
</code>```

gives:

```<code>ORDERBYVALUE ACCOUNT_NAME
------------ ----------------
           1 First Row
           2 Alpha Row
           2 Fifth Row
           2 Fourth Row
           2 Second Row
           2 Third Row
           3 4Number Row
           4 $Specialchar Row
</code>```

Title: Oracle Custom sorting is not working

Body:
I have an issue while sorting a column in a custom order in Oracle.

I need a particular row in the column to come first and then the remaining items should come down below in the alphabetic order. The column has a data starting with alphabets, numbers and special characters.. whenever i try to sort the column by ASC it is returning me starting with Special characters first following by number and then alphabets.

Eg result Set

ACCOUNT_NAME
-------------
First Row
Second Row
Third Row
Fourth Row
Fifth Row
$Specialchar Row
4Number Row
Alpha Row

Expected result in the below order

ACCOUNT_NAME
-------------
First Row
Alpha Row
Fifth Row
Fourth Row
Second Row
Third Row
4Number Row
$Specialchar Row

I have tried executing the below query but it doesn't seems to be work

SELECT ACCOUNT_NAME   FROM ACCOUNT
   ORDER BY decode(ACCOUNT_NAME,'First Row',1),
    regexp_substr(UPPER(ACCOUNT_NAME), '^[a-zA-Z]') ASC;

Body:
If I understand well, you want to order this way:

an hardcoded values comes as first

strings starting with a letter, in alphabetic order

the strings starting with a digit

then all other strings, based on the ASCII value

If so, you may use a case to build a value to use in the order:

/* sample data */
with example(ACCOUNT_NAME) as (
    select 'First Row' from dual union all
    select 'Second Row' from dual union all
    select 'Third Row' from dual union all
    select 'Fourth Row' from dual union all
    select 'Fifth Row' from dual union all
    select '$Specialchar Row' from dual union all
    select '4Number Row' from dual union all
    select 'Alpha Row' from dual
)
/* query */
select *
from example
order by case
            when account_name = 'First Row' then 1
            when regexp_like(account_name, '^[A-Za-z]') then 2
            when regexp_like(account_name, '^[0-9]') then 3
            else 4
         end,
         account_name

How it works:

select case
            when account_name = 'First Row' then 1
            when regexp_like(account_name, '^[A-Za-z]') then 2
            when regexp_like(account_name, '^[0-9]') then 3
            else 4
         end as orderByValue,
         account_name
from example
order by case
            when account_name = 'First Row' then 1
            when regexp_like(account_name, '^[A-Za-z]') then 2
            when regexp_like(account_name, '^[0-9]') then 3
            else 4
         end,
         account_name

gives:

ORDERBYVALUE ACCOUNT_NAME
------------ ----------------
           1 First Row
           2 Alpha Row
           2 Fifth Row
           2 Fourth Row
           2 Second Row
           2 Third Row
           3 4Number Row
           4 $Specialchar Row


问:
Debugging Custom QuickLook Plugin with Breakpoints
I'm having trouble getting my custom QuickLook Plugin to stop on my breakpoints.

I've tried several approaches with different schemes.

In Post-actions, I've added this in the Run Script:

```<code>rm -Rf "~/Library/QuickLook/$FULL_PRODUCT_NAME"
cp -R "$(BUILD_DIR)/Debug/CustomQuickLookPlug-In.qlgenerator" ~/Library/QuickLook
qlmanage -r
</code>```

I've also tried the approach mentioned in Debugging Quicklook Plugin in Xcode.

I get an error saying com.apple.CFPasteboardClient; this is likely due to sandbox restrictions  Is there any way to bypass this?

答: Apparently you need to copy and paste the qlmanager executable to another location and have your schema run that copy instead to bypass the security just to debug your QuickLook plugin.</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm having trouble getting my custom QuickLook Plugin to stop on my breakpoints.

I've tried several approaches with different schemes.

In Post-actions, I've added this in the Run Script:

rm -Rf "~/Library/QuickLook/$FULL_PRODUCT_NAME"
cp -R "$(BUILD_DIR)/Debug/CustomQuickLookPlug-In.qlgenerator" ~/Library/QuickLook
qlmanage -r

I've also tried the approach mentioned in Debugging Quicklook Plugin in Xcode.

I get an error saying com.apple.CFPasteboardClient; this is likely due to sandbox restrictions  Is there any way to bypass this?


问:
Kubernetes 1.5.4 Kube DNS Getting Deleted
When I run the deployment for Kubedns it launches successfully however, at exactly after 8 minutes of uptime, it is deleted. When it is running it works fine in resolving dns requests.  Has anyone else experienced this?  I'm starting to see this with other random deployments.

Kubernetes version
Client Version: version.Info{Major:"1", Minor:"5", GitVersion:"v1.5.4", GitCommit:"7243c69eb523aa4377bce883e7c0dd76b84709a1", GitTreeState:"clean", BuildDate:"2017-03-07T23:53:09Z", GoVersion:"go1.7.4", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"5", GitVersion:"v1.5.4", GitCommit:"7243c69eb523aa4377bce883e7c0dd76b84709a1", GitTreeState:"clean", BuildDate:"2017-03-07T23:34:32Z", GoVersion:"go1.7.4", Compiler:"gc", Platform:"linux/amd64"}

Environment:
Centos 7

Kernel
Linux at4d-lvk8s01 3.10.0-514.16.1.el7.x86_64 #1 SMP Wed Apr 12 15:04:24 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

Log Messages

After deploying Kubedns:

Apr 20 13:09:33 acme-lvk8s01 kube-controller-manager[912]: I0420 13:09:33.571733     912 event.go:217] Event(api.ObjectReference{Kind:"Deployment", Namespace:"kube-system", Name:"kube-dns", UID:"98ad2b69-25ca-11e7-afbe-90b8d0f6559c", APIVersion:"extensions", ResourceVersion:"262626", FieldPath:""}): type: 'Normal' reason: 'ScalingReplicaSet' Scaled up replica set kube-dns-3777016094 to 1
Apr 20 13:09:33 acme-lvk8s01 kube-controller-manager[912]: I0420 13:09:33.576730     912 replica_set.go:479] Too few "kube-system"/"kube-dns-3777016094" replicas, need 1, creating 1
Apr 20 13:09:33 acme-lvk8s01 kube-controller-manager[912]: I0420 13:09:33.625987     912 deployment_controller.go:298] Error syncing deployment kube-system/kube-dns: Operation cannot be fulfilled on deployments.extensions "kube-dns": the object has been modified; please apply your changes to the latest version and try again
Apr 20 13:09:33 acme-lvk8s01 kube-controller-manager[912]: I0420 13:09:33.656784     912 event.go:217] Event(api.ObjectReference{Kind:"ReplicaSet", Namespace:"kube-system", Name:"kube-dns-3777016094", UID:"98b57f0f-25ca-11e7-afbe-90b8d0f6559c", APIVersion:"extensions", ResourceVersion:"262627", FieldPath:""}): type: 'Normal' reason: 'SuccessfulCreate' Created pod: kube-dns-3777016094-9jt36
Apr 20 13:09:33 acme-lvk8s01 kube-controller-manager[912]: I0420 13:09:33.702938     912 deployment_controller.go:298] Error syncing deployment kube-system/kube-dns: Operation cannot be fulfilled on deployments.extensions "kube-dns": the object has been modified; please apply your changes to the latest version and try again
Apr 20 13:10:03 acme-lvk8s01 kube-controller-manager[912]: W0420 13:10:03.960803     912 reflector.go:319] pkg/controller/garbagecollector/garbagecollector.go:768: watch of  ended with: 401: The event in requested index is outdated and cleared (the requested history has been cleared [261724/260681]) [262723]

Immediately before Kubedns is deleted:

Apr 20 13:17:49 acme-lvk8s01 kube-controller-manager[912]: I0420 13:17:49.528874     912 replica_set.go:512] Too many "kube-system"/"kube-dns-3777016094" replicas, need 0, deleting 1
Apr 20 13:17:49 acme-lvk8s01 kube-controller-manager[912]: I0420 13:17:49.528973     912 controller_utils.go:523] Controller kube-dns-3777016094 deleting pod kube-system/kube-dns-3777016094-9jt36
Apr 20 13:17:49 acme-lvk8s01 kube-controller-manager[912]: I0420 13:17:49.532985     912 event.go:217] Event(api.ObjectReference{Kind:"Deployment", Namespace:"kube-system", Name:"kube-dns", UID:"98ad2b69-25ca-11e7-afbe-90b8d0f6559c", APIVersion:"extensions", ResourceVersion:"263765", FieldPath:""}): type: 'Normal' reason: 'ScalingReplicaSet' Scaled down replica set kube-dns-3777016094 to 0
Apr 20 13:17:49 acme-lvk8s01 kube-controller-manager[912]: I0420 13:17:49.600483     912 deployment_controller.go:298] Error syncing deployment kube-system/kube-dns: Operation cannot be fulfilled on deployments.extensions "kube-dns": the object has been modified; please apply your changes to the latest version and try again
Apr 20 13:17:49 acme-lvk8s01 kube-controller-manager[912]: I0420 13:17:49.623854     912 event.go:217] Event(api.ObjectReference{Kind:"ReplicaSet", Namespace:"kube-system", Name:"kube-dns-3777016094", UID:"98b57f0f-25ca-11e7-afbe-90b8d0f6559c", APIVersion:"extensions", ResourceVersion:"263766", FieldPath:""}): type: 'Normal' reason: 'SuccessfulDelete' Deleted pod: kube-dns-3777016094-9jt36
Apr 20 13:17:52 acme-lvk8s01 kube-controller-manager[912]: I0420 13:17:52.642886     912 garbagecollector.go:761] none of object [v1/Pod, namespace: kube-system, name: kube-dns-3777016094-9jt36, uid: 98d5d128-25ca-11e7-afbe-90b8d0f6559c]'s owners exist any more, will garbage collect it
Apr 20 13:17:52 acme-lvk8s01 kube-controller-manager[912]: I0420 13:17:52.665171     912 deployment_controller.go:322] Deployment has been deleted kube-system/kube-dns
Apr 20 13:18:04 acme-lvk8s01 kube-controller-manager[912]: W0420 13:18:04.972362     912 reflector.go:319] pkg/controller/garbagecollector/garbagecollector.go:768: watch of  ended with: 401: The event in requested index is outdated and cleared (the requested history has been cleared [262818/262725]) [263817]

答:
There is a serivce called kube-addons,I guess you don't start it.
Try this to know the service status：

systemctl status kube-addons.service

if status is stop,just start it and problems will be solved.


问:
Class conforming to protocol as function parameter in Swift Error
I'm currently in Swift 3.1 and the following code does not compile.

```<code>protocol HeaderDisplayable {
    func setTitle(_ string: String)
}

class MyView: UILabel, HeaderDisplayable {
    func setTitle(_ string: String) {
        self.text = string
    }
}

func foo<T: UILabel>(view:T) where T: HeaderDisplayable{
    view.setTitle("HEY")
}

foo(MyView())
</code>```

The error message is saying

Generic parameter 'T' could not be inferred

答:
The error is a bit misleading but you are missing the argument label.  You need to do this:

```<code>foo(view: MyView())
</code>```

or if you want to remove the need for it you could change the method definition to this:

```<code>func foo<T: UILabel>(_ view:T) where T: HeaderDisplayable{
    view.setTitle("HEY")
}
</code>```

Either version will work fine.

Body:
I'm currently in Swift 3.1 and the following code does not compile.

protocol HeaderDisplayable {
    func setTitle(_ string: String)
}

class MyView: UILabel, HeaderDisplayable {
    func setTitle(_ string: String) {
        self.text = string
    }
}

func foo<T: UILabel>(view:T) where T: HeaderDisplayable{
    view.setTitle("HEY")
}

foo(MyView())

The error message is saying

Generic parameter 'T' could not be inferred

Body:
The error is a bit misleading but you are missing the argument label.  You need to do this:

foo(view: MyView())

or if you want to remove the need for it you could change the method definition to this:

func foo<T: UILabel>(_ view:T) where T: HeaderDisplayable{
    view.setTitle("HEY")
}

Either version will work fine.


问:
How to send data from one window to another window?
Could you please tell me how to send data from one window to another window?
I have one button on my parent window. On click of that button I am moving to another page (There is success button present in another page). When I click success button on child or another window I am redirecting to parent window. I want to print "success" text on parent window.

http://plnkr.co/edit/6IRDD0DHxK6A7mExWOUP?p=preview

```<code>$(function() {
  $('#f').on('click', function() {
    // alert('ddd');
    window.open('a.html')
  })

   $('#succ').on('click', function() {
    // alert('succ');
    window.open('index.html')
  })
})
</code>```

答:
You can use the localStorage API to keep track of whether the button was clicked or not.

Whenever the user clicks on the button, add a new key (isClicked, for example) to the localStorage.

When the user lands on the main page, check to see if this flag is set. If set, show the success message.

```<code><!-- index.html -->
<html>
  <body>
    <div id="result"></div>
    <button id="cta">GOTO Sub Page</button>
    <button id="clear">Clear Success</button>
    <script>
      window.onload = function(){
        var isClicked = localStorage.getItem("isClicked");
        if(isClicked){
          document.getElementById("result").innerHTML="Success";
        }
      }
      document.getElementById("cta").onclick=function(){
       window.open("sub-page.html");
      }
      document.getElementById("clear").onclick=function(){
        localStorage.removeItem("isClicked");
        document.getElementById("result").innerHTML="";
      }
    </script>
  </body>
</html>

<!--- sub=page.html -->
<html>
  <body>
    <div id="result"></div>
    <button id="cta">Activate Message</button>
    <script>
      document.getElementById("cta").onclick=function(){
        localStorage.setItem("isClicked","true");
        window.open("index.html");
      }
    </script>
  </body>
</html>
</code>```

Sample Plunkr Implementation

PS: You can use localStorage to store/retrieve other page related values as well. You can even store JS objects by storing their string representations as given by JSON.stringify method

Body:
Could you please tell me how to send data from one window to another window?
I have one button on my parent window. On click of that button I am moving to another page (There is success button present in another page). When I click success button on child or another window I am redirecting to parent window. I want to print "success" text on parent window.

http://plnkr.co/edit/6IRDD0DHxK6A7mExWOUP?p=preview

$(function() {
  $('#f').on('click', function() {
    // alert('ddd');
    window.open('a.html')
  })

   $('#succ').on('click', function() {
    // alert('succ');
    window.open('index.html')
  })
})

Body:
You can use the localStorage API to keep track of whether the button was clicked or not.

Whenever the user clicks on the button, add a new key (isClicked, for example) to the localStorage.

When the user lands on the main page, check to see if this flag is set. If set, show the success message.

<!-- index.html -->
<html>
  <body>
    <div id="result"></div>
    <button id="cta">GOTO Sub Page</button>
    <button id="clear">Clear Success</button>
    <script>
      window.onload = function(){
        var isClicked = localStorage.getItem("isClicked");
        if(isClicked){
          document.getElementById("result").innerHTML="Success";
        }
      }
      document.getElementById("cta").onclick=function(){
       window.open("sub-page.html");
      }
      document.getElementById("clear").onclick=function(){
        localStorage.removeItem("isClicked");
        document.getElementById("result").innerHTML="";
      }
    </script>
  </body>
</html>

<!--- sub=page.html -->
<html>
  <body>
    <div id="result"></div>
    <button id="cta">Activate Message</button>
    <script>
      document.getElementById("cta").onclick=function(){
        localStorage.setItem("isClicked","true");
        window.open("index.html");
      }
    </script>
  </body>
</html>

Sample Plunkr Implementation

PS: You can use localStorage to store/retrieve other page related values as well. You can even store JS objects by storing their string representations as given by JSON.stringify method


问:
curved lines with css on divs and inputs
Is it possible to create something like this only with css?

I think with this is this possible but is it also possible with input fields?

答:
That is not possible with just css, but if you create an svg image with the lateral curved lines than you can do something like:</p>

```<code>input {
  border-top: 1px solid black;
  border-bottom: 1px solid black;
}
input::before {
  background: url("curve-sx.svg")
}
input::after {
  background: url("curve-dx.svg")
}
</code>```

Body:
That is not possible with just css, but if you create an svg image with the lateral curved lines than you can do something like:

input {
  border-top: 1px solid black;
  border-bottom: 1px solid black;
}
input::before {
  background: url("curve-sx.svg")
}
input::after {
  background: url("curve-dx.svg")
}


问:
Prevent download of entire remote resource with HttpClient?
Under UWP, the low-level HttpWebRequest class and its ilk have been been deprecated, and the official recommendation is to use System.Net.Http.HttpClient

However, there seems to be either a glaring oversight or a bug in the the HttpClient implementation: the API does not seem to provide a way to make a request to a remote URI that does not automatically download the entire remote resource (in the case of a GET request) to allow for lazy evaluation of the response stream.

The documentation for the HttpClient.GetAsync() method says:

This operation will not block. The returned task object will complete after the whole response (including content) is read.

Which states upfront that the entire remote resource will be downloaded before the request is considered completed. There is an HttpCompletionOption parameter which would theoretically allow for working around this if HttpCompletionOption.ResponseHeadersRead is specified, as that is documented as follows:

The operation should complete as soon as a response is available and headers are read. The content is not read yet.

However, regardless of which HttpCompletionOption is specified, in all cases, HttpClient.GetAsync() appears to allocate the complete ContentLength bytes of the response (in memory! all at once! without any limit checking!) in the process. Naturally, that is somewhat insane and a real problem.

In my particular case, I just want to read the first few kb of a multi-gigabyte remote resource from a server that does not support http range headers. This is normally a "no sweat" operation: just create web request, read from the response stream until you're satisfied, then close the response and be on your merry way.

That does not seem to be an option with the default HttpClient API. Is there a simple workaround that does not involve crafting my own HTTP requests using raw sockets?

答:
in all cases, HttpClient.GetAsync() appears to allocate the complete ContentLength bytes of the response (in memory! all at once! without any limit checking!)

This is not true for the HttpCompletionOption.ResponseHeadersRead option.

Just like using the old sweet HttpWebRequest class, you can open the response stream and read a few bytes then discard the response. Here is an example.

Here is my experiment: (I use Windows.Web.Http.HttpClient instead, but System.Net.Http.HttpClient provides similar APIs)

```<code>private HttpClient httpClient = new HttpClient();
private CancellationTokenSource cts = new CancellationTokenSource();

private async void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    Uri resourceAddress = new Uri("http://somewhere/gigabyte.zip");

    try
    {
        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, resourceAddress);

        // Do not buffer the response.
        HttpResponseMessage response = await httpClient.SendRequestAsync(
            request,
            HttpCompletionOption.ResponseHeadersRead).AsTask(cts.Token);

        using (Stream responseStream = (await response.Content.ReadAsInputStreamAsync()).AsStreamForRead())
        {
            int read = 0;
            byte[] responseBytes = new byte[1000];
            do
            {
                read = await responseStream.ReadAsync(responseBytes, 0, responseBytes.Length);
                break;
            } while (read != 0);
        }
    }
    catch (TaskCanceledException)
    {
    }
    catch (Exception ex)
    {
    }
    finally
    {
    }
}
</code>```

Body:
in all cases, HttpClient.GetAsync() appears to allocate the complete ContentLength bytes of the response (in memory! all at once! without any limit checking!)

This is not true for the HttpCompletionOption.ResponseHeadersRead option.

Just like using the old sweet HttpWebRequest class, you can open the response stream and read a few bytes then discard the response. Here is an example.

Here is my experiment: (I use Windows.Web.Http.HttpClient instead, but System.Net.Http.HttpClient provides similar APIs)

private HttpClient httpClient = new HttpClient();
private CancellationTokenSource cts = new CancellationTokenSource();

private async void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    Uri resourceAddress = new Uri("http://somewhere/gigabyte.zip");

    try
    {
        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, resourceAddress);

        // Do not buffer the response.
        HttpResponseMessage response = await httpClient.SendRequestAsync(
            request,
            HttpCompletionOption.ResponseHeadersRead).AsTask(cts.Token);

        using (Stream responseStream = (await response.Content.ReadAsInputStreamAsync()).AsStreamForRead())
        {
            int read = 0;
            byte[] responseBytes = new byte[1000];
            do
            {
                read = await responseStream.ReadAsync(responseBytes, 0, responseBytes.Length);
                break;
            } while (read != 0);
        }
    }
    catch (TaskCanceledException)
    {
    }
    catch (Exception ex)
    {
    }
    finally
    {
    }
}


问:
Is there a way to trigger the browsers default "scroll to cursor" behaviour when when typing in a textfield?
I want to trigger the browsers default behaviour of jumping to the cursor when someone starts to write and the cursor is of screen.

At the moment, if I resize the cursor is off screen and I want to center the scrollbar on the cursor again after the resize.

When I resize and type the scrollbar automatically jumps to the right position. Is there a way to trigger that "jump to cursor" behaviour with vanilla javascript or jQuery?

答:
You could use document.activeElement to select the focused element and scrollIntoView() :

$(window).resize(function(){
  element = document.activeElement;
  element.scrollIntoView(true);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div{
  height:200vh;
}</code>```

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

Body:
You could use document.activeElement to select the focused element and scrollIntoView() :

$(window).resize(function(){
  element = document.activeElement;
  element.scrollIntoView(true);
});

div{
  height:200vh;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<input type="text" />


问:
Why my @Async Future<T> blocks?
I have 2 Synchronous methods, the following one does not block.

```<code>@RequestMapping("/send1")
    @Async
    public Future<Boolean> sendMail() throws InterruptedException {
        System.out.println("sending mail 1..-"
                + Thread.currentThread().getName());
        Thread.sleep(1000 * 16);
        System.out.println("sending mail 1 completed");
        return new AsyncResult<Boolean>(true);
    }
</code>```

But the following one blocks.

```<code>@RequestMapping("/send3")
    public void callAsyn3() throws InterruptedException, ExecutionException {
Future<Boolean> go = sendMail3("test");
}

@Async
public Future<Boolean> sendMail3(String msg) throws InterruptedException {
        boolean acceptedYet = false;
        Thread.sleep(1000 * 12);
        if (!msg.equalsIgnoreCase("")) {
            acceptedYet = true;
        }
        return new AsyncResult<>(acceptedYet);
    }
</code>```

They are in the same controller class, Why such different behavior?

答:
Calling method in the same class do not pass through the proxy. So you can not use a method with @Async in the same class and make calls asynchronous.

We can create another service and write the @Async method there. Something like this

```<code>@Service
public class MyService {
    @Async
    public Future<Boolean> sendMail3(String msg) throws InterruptedException {
        boolean acceptedYet = false;
        Thread.sleep(1000 * 12);
        if (!msg.equalsIgnoreCase("")) {
            acceptedYet = true;
        }
        return new AsyncResult<>(acceptedYet);
    }
}
</code>```

This will run asynchronously ( non-blocking ).

If you want to do this in the same controller, you can submit it manually to some thread pool.

Title: Why my @Async Future<T> blocks?

Body:
I have 2 Synchronous methods, the following one does not block.

@RequestMapping("/send1")
    @Async
    public Future<Boolean> sendMail() throws InterruptedException {
        System.out.println("sending mail 1..-"
                + Thread.currentThread().getName());
        Thread.sleep(1000 * 16);
        System.out.println("sending mail 1 completed");
        return new AsyncResult<Boolean>(true);
    }

But the following one blocks.

@RequestMapping("/send3")
    public void callAsyn3() throws InterruptedException, ExecutionException {
Future<Boolean> go = sendMail3("test");
}

@Async
public Future<Boolean> sendMail3(String msg) throws InterruptedException {
        boolean acceptedYet = false;
        Thread.sleep(1000 * 12);
        if (!msg.equalsIgnoreCase("")) {
            acceptedYet = true;
        }
        return new AsyncResult<>(acceptedYet);
    }

They are in the same controller class, Why such different behavior?

Body:
Calling method in the same class do not pass through the proxy. So you can not use a method with @Async in the same class and make calls asynchronous.

We can create another service and write the @Async method there. Something like this

@Service
public class MyService {
    @Async
    public Future<Boolean> sendMail3(String msg) throws InterruptedException {
        boolean acceptedYet = false;
        Thread.sleep(1000 * 12);
        if (!msg.equalsIgnoreCase("")) {
            acceptedYet = true;
        }
        return new AsyncResult<>(acceptedYet);
    }
}

This will run asynchronously ( non-blocking ).

If you want to do this in the same controller, you can submit it manually to some thread pool.


问:
Tableau - Dotted Line Instead of a Continuous one (Pareto chart)
I have followed the directions (video) to create a Pareto chart at http://www.tableau.com/learn/tutorials/on-demand/pareto-charts

From the start, their lines are continuous and their bar charts are filled in areas under the curve, rather than separate bars.  I am following along with my own data set, and I have dotted lines, and separate bars.

I am following the directions in the video step-by-step, so apparently there is some underlying setting that is different.  I am working from a fresh install of Tableau 10.0.2.

As for the line, the column is CNTD(Product) - continuous and count distinct. The row is SUM(Sales) - continuous and measure(sum).  This is what the video shows, and they have a continuous line.  I have a dotted line.  If I change the count distinct setting, I then get a continuous line, but it changed the bottom horizontal axis from "% of Total Running Sum of Distinct count of Proeduct" to the product names (which are letters).  The video shows the CNTD(), the "% of Total..." and has a continuous line.  How to I get my result to match theirs?

(Windows 8.0; Tableau 10.0.2)

答: you must select Line chart if you complete before Edit table calculation.


问:
Using reflection to capture error details
I have a quick question that hopefully someone has worked through before. In the system that I am currently working on, we have rolled our own custom provider for handling web exceptions. One of the things that I like about this provider is that it allows us to add in parameter values of the method that throws the exception. The code looks something like this.

```<code>Public Sub Dosomething(ByVal Parameter1 As String, ByVal Parameter2 As String)
    Try
        'Do some process that causes and error.
    Catch ex As Exception
        Dim ErrorDetails = New List(Of String)

        ErrorDetails.Add("Parameter Values:")
        ErrorDetails.Add(String.Format("Parameter 1: {0}", Parameter1))
        ErrorDetails.Add(String.Format("Parameter 2: {0}", Parameter2))

        RaiseNewCustomException(ex, ErrorDetails)
    End Try
End Sub
</code>```

In the case of this method, the capture of the parameters and their values is very manual and prone to error as more and more people touch the code base and forget to update the thrown error. Is there a way to approach this problem in a more automated / less error prone way?

I have played around with reflection, but I don't think you can ascertain the parameter values via reflection. I would like something like:

```<code>Public Sub Dosomething(ByVal Parameter1 As String, ByVal Parameter2 As String)
    Try
        'Do some process that causes and error.
    Catch ex As Exception
        RaiseNewCustomExceptionAndAutomaticallyGenerateParameterErrorString(ex, System.Reflection.MethodInfo.GetCurrentMethod())
    End Try
End Sub
</code>```

答:
It is not possible to use Reflection to retrieve method argument values.  Only a debugger can have a shot at it, but even a debugger is powerless when the code is optimized.  Argument passing is heavily optimized by the JIT compiler.  Suppressing this optimization isn't worth the considerable cost, nor can an app debug itself.

As long as you want to keep this style of exception reporting, you'll have to explicitly pass the argument values to some kind of formatter.  A helper function that takes a Params array and returns an exception object that you can throw jumps to mind.

Body:
I have a quick question that hopefully someone has worked through before. In the system that I am currently working on, we have rolled our own custom provider for handling web exceptions. One of the things that I like about this provider is that it allows us to add in parameter values of the method that throws the exception. The code looks something like this.

Public Sub Dosomething(ByVal Parameter1 As String, ByVal Parameter2 As String)
    Try
        'Do some process that causes and error.
    Catch ex As Exception
        Dim ErrorDetails = New List(Of String)

        ErrorDetails.Add("Parameter Values:")
        ErrorDetails.Add(String.Format("Parameter 1: {0}", Parameter1))
        ErrorDetails.Add(String.Format("Parameter 2: {0}", Parameter2))

        RaiseNewCustomException(ex, ErrorDetails)
    End Try
End Sub

In the case of this method, the capture of the parameters and their values is very manual and prone to error as more and more people touch the code base and forget to update the thrown error. Is there a way to approach this problem in a more automated / less error prone way?

I have played around with reflection, but I don't think you can ascertain the parameter values via reflection. I would like something like:

Public Sub Dosomething(ByVal Parameter1 As String, ByVal Parameter2 As String)
    Try
        'Do some process that causes and error.
    Catch ex As Exception
        RaiseNewCustomExceptionAndAutomaticallyGenerateParameterErrorString(ex, System.Reflection.MethodInfo.GetCurrentMethod())
    End Try
End Sub


答:
you have self-invocation , call method sendMail3 from method callAsyn3 directly. it doesn't work because it bypasses the proxy and calls the underlying method directly.
simple fix - you should get contoller from context and call callAsyn3 from this instance.
normal fix - create new service - asyncSendMailComponent/Service, move sendMail3 into asyncSendMailComponent , inject asyncSendMailComponent into you controller and call sendMail3

in controller :

```<code>@Autowired
private AsyncSendMailComponent asyncSendMailComponent;
@RequestMapping("/send3")
    public void callAsyn3() throws InterruptedException, ExecutionException {
Future<Boolean> go = asyncSendMailComponent.sendMail3(msg)
}
</code>```

Async service

```<code> @Service
    pubclic class AsyncSendMailComponent {
    @Async
    public Future<Boolean> sendMail3(String msg) throws InterruptedException {
            boolean acceptedYet = false;
            Thread.sleep(1000 * 12);
            if (!msg.equalsIgnoreCase("")) {
                acceptedYet = true;
            }
            return new AsyncResult<>(acceptedYet);
        }
    }
</code>```

Title: Why my @Async Future<T> blocks?

Body:
you have self-invocation , call method sendMail3 from method callAsyn3 directly. it doesn't work because it bypasses the proxy and calls the underlying method directly.
simple fix - you should get contoller from context and call callAsyn3 from this instance.
normal fix - create new service - asyncSendMailComponent/Service, move sendMail3 into asyncSendMailComponent , inject asyncSendMailComponent into you controller and call sendMail3

in controller :

@Autowired
private AsyncSendMailComponent asyncSendMailComponent;
@RequestMapping("/send3")
    public void callAsyn3() throws InterruptedException, ExecutionException {
Future<Boolean> go = asyncSendMailComponent.sendMail3(msg)
}

Async service

 @Service
    pubclic class AsyncSendMailComponent {
    @Async
    public Future<Boolean> sendMail3(String msg) throws InterruptedException {
            boolean acceptedYet = false;
            Thread.sleep(1000 * 12);
            if (!msg.equalsIgnoreCase("")) {
                acceptedYet = true;
            }
            return new AsyncResult<>(acceptedYet);
        }
    }


问:
Javascript Regular Expression For a Valid Input
I want JavaScript regular expression which validates below number format (only number and min length should be 11 and maximum 16).<br>
e.g   </p>

```<code>12345678901 // valid
+1234567890 // valid
+1234567890+ // invalid
+123456789trtr // invalid
+trtr // invalid
</code>```

答:
Fairly simple RegExp for what you want to get will be:

```<code>/^\+?\d{11,16}$/
</code>```

It returns you a string with a possible + sign at the beginning followed by 11 - 16 digits.

As user Jins Peter suggested, you probably want a RegExp that validates phone number.

If it is really a phone number there often will be spaces in it. Also area code would be optional. So in the end I suggest using:

```<code>/^(\+?\d{2})? ?\d{3} ?\d{3} ?\d{3}$/
</code>```

It makes the examples below pass the RegExp:

```<code>+48 666 555 444 //valid
48 666 555 444 //valid
+48666555444 //valid
48666555444 //valid
666555444 //valid
666 555 444 //valid
</code>```

Keep in mind that some weird phone numbers will also pass the validation. For example:

```<code>48 666 555444 //valid
+48666555 444 //valid
</code>```

etc.

Body:
I want JavaScript regular expression which validates below number format (only number and min length should be 11 and maximum 16).

e.g

12345678901 // valid
+1234567890 // valid
+1234567890+ // invalid
+123456789trtr // invalid
+trtr // invalid

Body:
Fairly simple RegExp for what you want to get will be:

/^\+?\d{11,16}$/

It returns you a string with a possible + sign at the beginning followed by 11 - 16 digits.

As user Jins Peter suggested, you probably want a RegExp that validates phone number.

If it is really a phone number there often will be spaces in it. Also area code would be optional. So in the end I suggest using:

/^(\+?\d{2})? ?\d{3} ?\d{3} ?\d{3}$/

It makes the examples below pass the RegExp:

+48 666 555 444 //valid
48 666 555 444 //valid
+48666555444 //valid
48666555444 //valid
666555444 //valid
666 555 444 //valid

Keep in mind that some weird phone numbers will also pass the validation. For example:

48 666 555444 //valid
+48666555 444 //valid

etc.


问:
How can I insert the result of store procedure in available table in my sql server?
I need to save the result of my store procedure in the defined table in my sql server. I test different code for that ,but, non of them was useful.
Could you please hep me?
This is my code:

```<code>AS BEGIN EXEC sp_execute_external_script    @language =N'R',       @script=N'   library(e1071);   naivemodel <-naiveBayes(datafile[,3:12], datafile[,13]);   trained_model <- data.frame(payload = as.raw(serialize(naivemodel, connection=NULL)));
      ',
      @input_data_1 =N'SELECT * from R_CT',    @input_data_1_name = N'datafile',   @output_data_1_name = N'trained_model'   with result sets ((model varbinary(max)));       end; insert into my_models (model) exec sp_RDA_Prd_naiveBayes; update my_models set model_name = 'e1071 - Naive Bayes' where model_name = 'default model'; select * from my_models;
</code>```

but,I confronted with this error:

Column name or number of supplied values does not match table definition.

This is the defined table:

```<code>create table my_models (
    model_name varchar(30) not null default('default model') primary key,
    model varbinary(max) not null
);
</code>```

答:
I would suggest

```<code>INSERT INTO my_models (model) VALUES (model)
</code>```

the first 'model' is you column name,the second 'model' is your actual value

Body:
I need to save the result of my store procedure in the defined table in my sql server. I test different code for that ,but, non of them was useful.
Could you please hep me?
This is my code:

AS BEGIN EXEC sp_execute_external_script    @language =N'R',       @script=N'   library(e1071);   naivemodel <-naiveBayes(datafile[,3:12], datafile[,13]);   trained_model <- data.frame(payload = as.raw(serialize(naivemodel, connection=NULL)));
      ',
      @input_data_1 =N'SELECT * from R_CT',    @input_data_1_name = N'datafile',   @output_data_1_name = N'trained_model'   with result sets ((model varbinary(max)));       end; insert into my_models (model) exec sp_RDA_Prd_naiveBayes; update my_models set model_name = 'e1071 - Naive Bayes' where model_name = 'default model'; select * from my_models;

but,I confronted with this error:

Column name or number of supplied values does not match table definition.

This is the defined table:

create table my_models (
    model_name varchar(30) not null default('default model') primary key,
    model varbinary(max) not null
);

Body:
I would suggest

INSERT INTO my_models (model) VALUES (model)

the first 'model' is you column name,the second 'model' is your actual value


问:
i am trying to split a full name to first middle and last name in pandas but i am stuck at replace
i am trying to break the name into two parts and keeping first name last name and finally replacing the common part in all of them such that first name is must then last name then if middle name remain it is added to column

```<code>df['owner1_first_name'] = df['owner1_name'].str.split().str[0].astype(str,
errors='ignore')
df['owner1_last_name'] =
df['owner1_name'].str.split().str[-1].str.replace(df['owner1_first_name'],
"").astype(str, errors='ignore')
['owner1_middle_name'] =
df['owner1_name'].str.replace(df['owner1_first_name'],
"").str.replace(df['owner1_last_name'], "").astype(str, errors='ignore')
</code>```

the problem is i am not able to use
    .str.replace(df['owner1_name'], "")

as  i am getting an error
    "TypeError: 'Series' objects are mutable, thus they cannot be hashed"

is there any replacement sytax in pandas for what i am tryin to achieve

my desired output is

full name = THOMAS MARY D which is in column owner1_name

I want

```<code>owner1_first_name = THOMAS
owner1_middle_name = MARY
owner1_last_name = D
</code>```

答:
I think you need mask which replace if same values in both columns to empty strings:

```<code>df = pd.DataFrame({'owner1_name':['THOMAS MARY D', 'JOE Long', 'MARY Small']})

splitted = df['owner1_name'].str.split()
df['owner1_first_name'] = splitted.str[0]
df['owner1_last_name'] = splitted.str[-1]
df['owner1_middle_name'] = splitted.str[1]
df['owner1_middle_name'] = df['owner1_middle_name']
                             .mask(df['owner1_middle_name'] == df['owner1_last_name'], '')
print (df)
     owner1_name owner1_first_name owner1_last_name owner1_middle_name
0  THOMAS MARY D            THOMAS                D               MARY
1       JOE Long               JOE             Long
2     MARY Small              MARY            Small
</code>```

What is same as:

```<code>splitted = df['owner1_name'].str.split()
df['owner1_first_name'] = splitted.str[0]
df['owner1_last_name'] = splitted.str[-1]
middle = splitted.str[1]
df['owner1_middle_name'] = middle.mask(middle == df['owner1_last_name'], '')
print (df)
     owner1_name owner1_first_name owner1_last_name owner1_middle_name
0  THOMAS MARY D            THOMAS                D               MARY
1       JOE Long               JOE             Long
2     MARY Small              MARY            Small
</code>```

EDIT:

For replace by rows is possible use apply with axis=1:

```<code>df = pd.DataFrame({'owner1_name':['THOMAS MARY-THOMAS', 'JOE LongJOE', 'MARY Small']})

splitted = df['owner1_name'].str.split()
df['a'] = splitted.str[0]
df['b'] = splitted.str[-1]

df['c'] = df.apply(lambda x: x['b'].replace(x['a'], ''), axis=1)
print (df)
          owner1_name       a            b      c
0  THOMAS MARY-THOMAS  THOMAS  MARY-THOMAS  MARY-
1         JOE LongJOE     JOE      LongJOE   Long
2          MARY Small    MARY        Small  Small
</code>```

the exact code to in three line to achieve what i wanted in my question is

```<code>df['owner1_first_name'] = df['owner1_name'].str.split().str[0]
df['owner1_last_name'] = df.apply(lambda x: x['owner1_name'].split()
[-1].replace(x['owner1_first_name'], ''), axis=1)
df['owner1_middle_name'] = df.apply(lambda x:
x['owner1_name'].replace(x['owner1_first_name'],
'').replace(x['owner1_last_name'], ''), axis=1)
</code>```

Body:
i am trying to break the name into two parts and keeping first name last name and finally replacing the common part in all of them such that first name is must then last name then if middle name remain it is added to column

df['owner1_first_name'] = df['owner1_name'].str.split().str[0].astype(str,
errors='ignore')
df['owner1_last_name'] =
df['owner1_name'].str.split().str[-1].str.replace(df['owner1_first_name'],
"").astype(str, errors='ignore')
['owner1_middle_name'] =
df['owner1_name'].str.replace(df['owner1_first_name'],
"").str.replace(df['owner1_last_name'], "").astype(str, errors='ignore')

the problem is i am not able to use
    .str.replace(df['owner1_name'], "")

as  i am getting an error
    "TypeError: 'Series' objects are mutable, thus they cannot be hashed"

is there any replacement sytax in pandas for what i am tryin to achieve

my desired output is

full name = THOMAS MARY D which is in column owner1_name

I want

owner1_first_name = THOMAS
owner1_middle_name = MARY
owner1_last_name = D

Body:
I think you need mask which replace if same values in both columns to empty strings:

df = pd.DataFrame({'owner1_name':['THOMAS MARY D', 'JOE Long', 'MARY Small']})

splitted = df['owner1_name'].str.split()
df['owner1_first_name'] = splitted.str[0]
df['owner1_last_name'] = splitted.str[-1]
df['owner1_middle_name'] = splitted.str[1]
df['owner1_middle_name'] = df['owner1_middle_name']
                             .mask(df['owner1_middle_name'] == df['owner1_last_name'], '')
print (df)
     owner1_name owner1_first_name owner1_last_name owner1_middle_name
0  THOMAS MARY D            THOMAS                D               MARY
1       JOE Long               JOE             Long
2     MARY Small              MARY            Small

What is same as:

splitted = df['owner1_name'].str.split()
df['owner1_first_name'] = splitted.str[0]
df['owner1_last_name'] = splitted.str[-1]
middle = splitted.str[1]
df['owner1_middle_name'] = middle.mask(middle == df['owner1_last_name'], '')
print (df)
     owner1_name owner1_first_name owner1_last_name owner1_middle_name
0  THOMAS MARY D            THOMAS                D               MARY
1       JOE Long               JOE             Long
2     MARY Small              MARY            Small

EDIT:

For replace by rows is possible use apply with axis=1:

df = pd.DataFrame({'owner1_name':['THOMAS MARY-THOMAS', 'JOE LongJOE', 'MARY Small']})

splitted = df['owner1_name'].str.split()
df['a'] = splitted.str[0]
df['b'] = splitted.str[-1]

df['c'] = df.apply(lambda x: x['b'].replace(x['a'], ''), axis=1)
print (df)
          owner1_name       a            b      c
0  THOMAS MARY-THOMAS  THOMAS  MARY-THOMAS  MARY-
1         JOE LongJOE     JOE      LongJOE   Long
2          MARY Small    MARY        Small  Small

the exact code to in three line to achieve what i wanted in my question is

df['owner1_first_name'] = df['owner1_name'].str.split().str[0]
df['owner1_last_name'] = df.apply(lambda x: x['owner1_name'].split()
[-1].replace(x['owner1_first_name'], ''), axis=1)
df['owner1_middle_name'] = df.apply(lambda x:
x['owner1_name'].replace(x['owner1_first_name'],
'').replace(x['owner1_last_name'], ''), axis=1)


问:
Dropdown Scroll Bar Position
So far I have achieved this:

What I want is the scroll bar position on the right side with padding. Something like this:

My HTML:

```<code><div class="dropdown">
        <div id="dropdown-label" class="dropdown-active" data-toggle="dropdown"  title="{{selected.label}}">
          <i class="g2icon-user-dropdown dropdown-entity-icon"></i> {{ selected.label }}
          <span class="right-icon glyph-2 fa fa-chevron-down"></span>
        </div>
        <ul class="dropdown-menu" aria-labelledby="dropdown-label" lr-infinite-scroll="loadMore">
          <!-- My Organizations-->
          <li class="col-md-12 full-s calendar-list-break">
            <span>My Organization</span>
          </li>
          <li class="col-md-12 full-s calendar-item" ng-repeat="item in items | filter: 'organization'" title="{{item.label}}">
            <span ng-click="selectOption(item.id)"><i class="dropdown-entity-icon"></i> {{item.label}}</span>
          </li>

          <!-- My Groups -->
          <li class="col-md-12 full-s calendar-list-break">
            <span>My Groups</span>
          </li>
          <li class="col-md-12 full-s calendar-item" ng-repeat="item in items | filter: 'group'" title="{{item.label}}">
            <span ng-click="selectOption(item.id)"><i class=" dropdown-entity-icon"></i> {{item.label}}</span>
          </li>
        </ul>
      </div>
</code>```

My CSS:

```<code>.dropdown {
@include modal-scrollbar; //etc etc
}
</code>```

My SASS mixin looks like this:

```<code>@mixin custom-scrollbar() {
  ::-webkit-scrollbar {
    width: 12px;
  }

  ::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
    border-radius: 10px;
  }

  ::-webkit-scrollbar-thumb {
    background-color: darkgrey;
    border-radius: 10px;
    -webkit-box-shadow: inset 0 0 6px darkgrey;
  }
}
</code>```

How can I achieve this?
Thank you.
NOTE: I didn't find something useful googling around.

答:
Refer this: Link
It has added a position and set the right property of the parent div element(In this case your dropdown class) hence the overall effect will look like the same as you want.</p>

Title: Dropdown Scroll Bar Position

Body:
So far I have achieved this:

What I want is the scroll bar position on the right side with padding. Something like this:

My HTML:

           {{ selected.label }}

            My Organization

             {{item.label}}

            My Groups

             {{item.label}}

My CSS:

.dropdown {
@include modal-scrollbar; //etc etc
}

My SASS mixin looks like this:

@mixin custom-scrollbar() {
  ::-webkit-scrollbar {
    width: 12px;
  }

  ::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
    border-radius: 10px;
  }

  ::-webkit-scrollbar-thumb {
    background-color: darkgrey;
    border-radius: 10px;
    -webkit-box-shadow: inset 0 0 6px darkgrey;
  }
}

How can I achieve this?
Thank you.
NOTE: I didn't find something useful googling around.


问:
Push notification to all the users subscribed to the topic except login user using FCM Firebase
Now i have a group which have more than ten thousand members and for a group i have created a topic(Notification topic) where all the users in the group subscribed to that topic. Now inside the group any user can add post like image or file or video. When user add the post i need to send notification to all the users subscribed to that topic but except one, that is person who add the post. How can i achieve this??

Now notification is going to all the users including the person who add the post.

答:
There is currently no parameter of any sort to exclude a specific user from receiving a message from a topic they are subscribed to. However, as a workaround, you could simply have a custom implementation on building the payload and handling the message to receive it.

Depending on how you build your payload, you could just add a custom key-value pair that includes the user id of the one who posted the data (something like posterId or simply userId).

Then on your client side, when handling the push notification, just check if the id is the user's or not. If it is the same user, don't show the notification, else show it. e.g.:

```<code>if (userId == currentUserId) {
    // if user is the one that sent the message, don't show the notification
    return;
}
</code>```

Body:
There is currently no parameter of any sort to exclude a specific user from receiving a message from a topic they are subscribed to. However, as a workaround, you could simply have a custom implementation on building the payload and handling the message to receive it.

Depending on how you build your payload, you could just add a custom key-value pair that includes the user id of the one who posted the data (something like posterId or simply userId).

Then on your client side, when handling the push notification, just check if the id is the user's or not. If it is the same user, don't show the notification, else show it. e.g.:

if (userId == currentUserId) {
    // if user is the one that sent the message, don't show the notification
    return;
}


问:
Powershell, How to match files names with partial names stored in text file
Sorry for the dump question as I am a beginner in PowerShell. We have a lot of coming files into a directory, and they are always increasing and decreasing in that directory because it is moved to another directory after we are done from using them.

We have a priority file list in a txt file which has only partial name of the file name.

For example, for the file name:

2017-06-5---666-12-05-01.txt

In the priority list, I have the partial name as ---666---.

How can I check if the files in the folder are already in the priority list by using Powershell?

I wrote the below script since I need only the files which are older than a given time. But it is not working.

```<code>Get-ChildItem -path $Struct.Path  -filter $Struct.filter |
Where-Object {$_.CreationTime -lt $time} |
Where-Object {$_.Name -contains "*$PriorityList*"} |
ForEach-Object { $counterP++}
</code>```

答:
I have updated your code and now it is working perfectly</p>

```<code>Get-ChildItem -path $Struct.Path  -filter $Struct.filter |
Where-Object {$_.CreationTime -lt $time} | ForEach-Object { If($_.name -
Match $Priorfilter) { $counterP++  }
</code>```

Body:
Sorry for the dump question as I am a beginner in PowerShell. We have a lot of coming files into a directory, and they are always increasing and decreasing in that directory because it is moved to another directory after we are done from using them.

We have a priority file list in a txt file which has only partial name of the file name.

For example, for the file name:

2017-06-5---666-12-05-01.txt

In the priority list, I have the partial name as ---666---.

How can I check if the files in the folder are already in the priority list by using Powershell?

I wrote the below script since I need only the files which are older than a given time. But it is not working.

Get-ChildItem -path $Struct.Path  -filter $Struct.filter |
Where-Object {$_.CreationTime -lt $time} |
Where-Object {$_.Name -contains "*$PriorityList*"} |
ForEach-Object { $counterP++}

Body:
I have updated your code and now it is working perfectly

Get-ChildItem -path $Struct.Path  -filter $Struct.filter |
Where-Object {$_.CreationTime -lt $time} | ForEach-Object { If($_.name -
Match $Priorfilter) { $counterP++  }


问:
Decimal number to 32 bit binary
```<code>int main()
{
    unsigned n;
    cin>>n;
    for(int i=(1<<31);i>0;i/=2)
        (i&n)?(cout<<1):(cout<<0);
}
</code>```

I ran the following code with n=1 but it prints nothing on the console. Changing the type of variable i to unsigned did the trick and printed 00000000000000000000000000000001. Any idea why?

答: Given that your platform is a 32-bit one, int i with a value of (i<<31) is a negative number. So, the execution never enters for-loop because you want i>0.</p>

Title: Decimal number to 32 bit binary

Body:
int main()
{
    unsigned n;
    cin>>n;
    for(int i=(1<<31);i>0;i/=2)
        (i&n)?(cout<<1):(cout<<0);
}

I ran the following code with n=1 but it prints nothing on the console. Changing the type of variable i to unsigned did the trick and printed 00000000000000000000000000000001. Any idea why?