问:
Push notification not working in foreground
When my app is running I sent notification from firebase, UNUserNotification delegate method called, I got notification and it is displaying on top, But when I sent notification from my API server,

```<code>func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage)
</code>```

firebase delegate is calling and I can fetch the data , but notification is not displaying on the top.

My code is below:

```<code>func registerForPushNotification(_ application: UIApplication)
{

    if #available(iOS 10.0, *) {
        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.current().delegate = self
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {_, _ in })
        // For iOS 10 data message (sent via FCM
        //Messaging.messaging().delegate = self
    } else {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)

        application.registerUserNotificationSettings(settings)
    }
    application.registerForRemoteNotifications()
    application.applicationIconBadgeNumber = 0

}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
    print("device token %@",deviceToken)

    var deviceTokenString = String(format: "%@", deviceToken as CVarArg)
    deviceTokenString = deviceTokenString.trimmingCharacters(in: CharacterSet(charactersIn: "<>"))
    deviceTokenString = deviceTokenString.replacingOccurrences(of: " ", with: "")

    print(deviceTokenString)
    //saveDeviceIdinDefaults(deviceId: deviceTokenString)
    Messaging.messaging().apnsToken = deviceToken

//        InstanceID.instanceID().setAPNSToken(deviceToken, type:InstanceIDAPNSTokenType.sandbox)
//        InstanceID.instanceID().setAPNSToken(deviceToken, type:InstanceIDAPNSTokenType.prod)

}

// The callback to handle data message received via FCM for devices running iOS 10 or above.
func application(received remoteMessage: MessagingRemoteMessage) {
    print(remoteMessage.appData)

}

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    print("Userinfo \(response.notification.request.content.userInfo)")

    if response.actionIdentifier == UNNotificationDismissActionIdentifier {
        print ("Message Closed")
    }
    else if response.actionIdentifier == UNNotificationDefaultActionIdentifier {
        print ("App is Open")
    }

    // Else handle any custom actions. . .
    completionHandler()

    //    print("Userinfo \(response.notification.request.content.userInfo)")
}

func application(_ application: UIApplication,
                 didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("Failed to register: \(error)")
}

@objc func tokenRefreshNotification(_ notification: NSNotification) {
    //  print("refresh token call")
    guard let contents = InstanceID.instanceID().token()
        else {
            return
    }
    // let refreshedToken = FIRInstanceID.instanceID().token()!
    let refreshedToken = contents//InstanceID.instanceID().token()
    print("InstanceID token: \(refreshedToken)")

    Constant.saveFcmToken(fcmToken: refreshedToken, key: "deviceid")
    //        UserDefaults.standard.set(refreshedToken, forKey: "deviceid")

    print("InstanceID token: \(contents)")
    connectToFcm()
}

func connectToFcm() {
    // Won't connect since there is no token
    guard InstanceID.instanceID().token() != nil else {
        print("FCM: Token does not exist.")
        return
    }

    // Disconnect previous FCM connection if it exists.
    Messaging.messaging().disconnect()

    Messaging.messaging().connect { (error) in
        if error != nil {
            print("FCM: Unable to connect with FCM. \(error.debugDescription)")
        } else {
            print("Connected to FCM.")
        }
    }
}
// [START refresh_token]

//MARK: FCM Token Refreshed
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
    // FCM token updated, update it on Backend Server
    print("Firebase registration token: \(fcmToken)")
    saveDeviceIdinDefaults(deviceId: fcmToken)
}

func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
    print("remoteMessage: \(remoteMessage)")
    UNUserNotificationCenter.current().requestAuthorization(
        options: [.alert,.sound,.badge],
        completionHandler: { (granted,error) in
            NotificationCenter.default.post(name: NSNotification.Name("GetPollsUpdateNotification"), object: nil)
            //self.isGrantedNotificationAccess(data: remoteMessage.appData)
    }
    )

    //            let notifiDict = remoteMessage.appData as! [String:String]
    //            print(notifiDict)
    //            let title = notifiDict["title"]
    //            let message = notifiDict["message"]
    //            let image = notifiDict["image"]
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    print(userInfo)
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
    print(userInfo)
    if application.applicationState == .active {

        //write your code here when app is in foreground
    } else {
        //write your code here for other state
    }
}

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
{

    completionHandler([UNNotificationPresentationOptions.alert])

    let userInfo = notification.request.content.userInfo as! NSDictionary
    print("\(String(describing: userInfo))")

    print(notification.description)
}
</code>```

Could any one please help me?

答:
I believe the way to handle this is using the following delegate method:

```<code> @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

            completionHandler([.alert, .sound, .badge])

    }
</code>```

Hope this helps.

Body:
When my app is running I sent notification from firebase, UNUserNotification delegate method called, I got notification and it is displaying on top, But when I sent notification from my API server,

func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage)

firebase delegate is calling and I can fetch the data , but notification is not displaying on the top.

My code is below:

func registerForPushNotification(_ application: UIApplication)
{

    if #available(iOS 10.0, *) {
        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.current().delegate = self
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {_, _ in })
        // For iOS 10 data message (sent via FCM
        //Messaging.messaging().delegate = self
    } else {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)

        application.registerUserNotificationSettings(settings)
    }
    application.registerForRemoteNotifications()
    application.applicationIconBadgeNumber = 0

}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
    print("device token %@",deviceToken)

    var deviceTokenString = String(format: "%@", deviceToken as CVarArg)
    deviceTokenString = deviceTokenString.trimmingCharacters(in: CharacterSet(charactersIn: "<>"))
    deviceTokenString = deviceTokenString.replacingOccurrences(of: " ", with: "")

    print(deviceTokenString)
    //saveDeviceIdinDefaults(deviceId: deviceTokenString)
    Messaging.messaging().apnsToken = deviceToken

//        InstanceID.instanceID().setAPNSToken(deviceToken, type:InstanceIDAPNSTokenType.sandbox)
//        InstanceID.instanceID().setAPNSToken(deviceToken, type:InstanceIDAPNSTokenType.prod)

}

// The callback to handle data message received via FCM for devices running iOS 10 or above.
func application(received remoteMessage: MessagingRemoteMessage) {
    print(remoteMessage.appData)

}

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    print("Userinfo \(response.notification.request.content.userInfo)")

    if response.actionIdentifier == UNNotificationDismissActionIdentifier {
        print ("Message Closed")
    }
    else if response.actionIdentifier == UNNotificationDefaultActionIdentifier {
        print ("App is Open")
    }

    // Else handle any custom actions. . .
    completionHandler()

    //    print("Userinfo \(response.notification.request.content.userInfo)")
}

func application(_ application: UIApplication,
                 didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("Failed to register: \(error)")
}

@objc func tokenRefreshNotification(_ notification: NSNotification) {
    //  print("refresh token call")
    guard let contents = InstanceID.instanceID().token()
        else {
            return
    }
    // let refreshedToken = FIRInstanceID.instanceID().token()!
    let refreshedToken = contents//InstanceID.instanceID().token()
    print("InstanceID token: \(refreshedToken)")

    Constant.saveFcmToken(fcmToken: refreshedToken, key: "deviceid")
    //        UserDefaults.standard.set(refreshedToken, forKey: "deviceid")

    print("InstanceID token: \(contents)")
    connectToFcm()
}

func connectToFcm() {
    // Won't connect since there is no token
    guard InstanceID.instanceID().token() != nil else {
        print("FCM: Token does not exist.")
        return
    }

    // Disconnect previous FCM connection if it exists.
    Messaging.messaging().disconnect()

    Messaging.messaging().connect { (error) in
        if error != nil {
            print("FCM: Unable to connect with FCM. \(error.debugDescription)")
        } else {
            print("Connected to FCM.")
        }
    }
}
// [START refresh_token]

//MARK: FCM Token Refreshed
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
    // FCM token updated, update it on Backend Server
    print("Firebase registration token: \(fcmToken)")
    saveDeviceIdinDefaults(deviceId: fcmToken)
}

func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
    print("remoteMessage: \(remoteMessage)")
    UNUserNotificationCenter.current().requestAuthorization(
        options: [.alert,.sound,.badge],
        completionHandler: { (granted,error) in
            NotificationCenter.default.post(name: NSNotification.Name("GetPollsUpdateNotification"), object: nil)
            //self.isGrantedNotificationAccess(data: remoteMessage.appData)
    }
    )

    //            let notifiDict = remoteMessage.appData as! [String:String]
    //            print(notifiDict)
    //            let title = notifiDict["title"]
    //            let message = notifiDict["message"]
    //            let image = notifiDict["image"]
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    print(userInfo)
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
    print(userInfo)
    if application.applicationState == .active {

        //write your code here when app is in foreground
    } else {
        //write your code here for other state
    }
}

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
{

    completionHandler([UNNotificationPresentationOptions.alert])

    let userInfo = notification.request.content.userInfo as! NSDictionary
    print("\(String(describing: userInfo))")

    print(notification.description)
}

Could any one please help me?

Body:
I believe the way to handle this is using the following delegate method:

 @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

            completionHandler([.alert, .sound, .badge])

    }

Hope this helps.


来源: stackexchange

问:
Add placeholder to select tag in angular2
I have simple component that contains only form:

```<code>import {Component, FORM_DIRECTIVES, NgFor} from 'angular2/angular2';

@Component({
  selector: 'test-component',
  directives: [FORM_DIRECTIVES, NgFor],
  template: `
    <form class="form-inline" (ng-submit)="onSubmit()" #form="form">
      <div class="form-group">
        <select class="form-control"
          [(ng-model)]="model.server"
          ng-control="server"
          #server="form"
          required>
          <option selected hidden>placeholder</option>
          <option *ng-for="#server of servers"
            [value]="server">{{ server | uppercase }}
          </option>
        </select>
      </div>
      <div class="form-group">
        <input class="btn btn-primary" type="submit" value="Load"
          [disabled]="!form.form.valid">
      </div>
    </form>
  `
})
export class TestComponent {
  public model: Model = new Model();
  public servers: string[] = ['a', 'b', 'c'];

  onSubmit(): void {
    // Complicated logic.

    // Reset form.
    this.model.reset();
  }
}

class Model {
  constructor(
    public server: string = ''
  ) { }

  reset(): void {
    this.server = '';
  }
}
</code>```

I want to create "placeholder" for my select, however ng-model overrides selected property which cause no selected option at all. Any sugestions? I am using angular 2.0.0-alpha.48.

答:
Angular 5 Solution and with Reactive forms!

```<code><option value="null" disabled="true" [selected]="true">Placeholder text..</option>
</code>```

:)

ContentLicense: CC BY-SA 3.0

Body:
I have simple component that contains only form:

import {Component, FORM_DIRECTIVES, NgFor} from 'angular2/angular2';

@Component({
  selector: 'test-component',
  directives: [FORM_DIRECTIVES, NgFor],
  template: `
    <form class="form-inline" (ng-submit)="onSubmit()" #form="form">

        <select class="form-control"
          [(ng-model)]="model.server"
          ng-control="server"
          #server="form"
          required>
          <option selected hidden>placeholder</option>
          <option *ng-for="#server of servers"
            [value]="server">{{ server | uppercase }}
          </option>
        </select>

        <input class="btn btn-primary" type="submit" value="Load"
          [disabled]="!form.form.valid">

    </form>
  `
})
export class TestComponent {
  public model: Model = new Model();
  public servers: string[] = ['a', 'b', 'c'];

  onSubmit(): void {
    // Complicated logic.

    // Reset form.
    this.model.reset();
  }
}

class Model {
  constructor(
    public server: string = ''
  ) { }

  reset(): void {
    this.server = '';
  }
}

I want to create "placeholder" for my select, however ng-model overrides selected property which cause no selected option at all. Any sugestions? I am using angular 2.0.0-alpha.48.

Body:
Angular 5 Solution and with Reactive forms!

<option value="null" disabled="true" [selected]="true">Placeholder text..</option>

:)


问:
Getting file name out of a string
I need to get the filename 'HomeModel' out of a string app\model\common\HomeModel. This is what I tried

First, replace '\' with '/' using the str_replace.

```<code>$model = 'app\model\common\HomeModel';
$file = str_replace("\\", '/', $model) . ".php";
echo $file;
</code>```

the result

```<code>app/model/common/HomeModel.php
</code>```

then I explode the result like so

```<code>$model = 'app\model\common\HomeModel';
$file = str_replace("\\", '/', $model) . ".php";
echo $file;

$result = explode("/", $file);
echo '<br>';
var_dump($result);
</code>```

and then this is what I have

```<code>array (size=4)
  0 => string 'app' (length=3)
  1 => string 'model' (length=5)
  2 => string 'common' (length=6)
  3 => string 'HomeModel.php' (length=18)
</code>```

Now, how do I get the last value 'HomeModel' out of this array for further use?, I need to assign the value 'HomeModel' to $class.

答:
end() should do the job.

```<code>$class = end($result);
</code>```

Title: Getting file name out of a string

Body:
I need to get the filename 'HomeModel' out of a string app\model\common\HomeModel. This is what I tried

First, replace '\' with '/' using the str_replace.

$model = 'app\model\common\HomeModel';
$file = str_replace("\\", '/', $model) . ".php";
echo $file;

the result

app/model/common/HomeModel.php

then I explode the result like so

$model = 'app\model\common\HomeModel';
$file = str_replace("\\", '/', $model) . ".php";
echo $file;

$result = explode("/", $file);
echo '
';
var_dump($result);

and then this is what I have

array (size=4)
  0 => string 'app' (length=3)
  1 => string 'model' (length=5)
  2 => string 'common' (length=6)
  3 => string 'HomeModel.php' (length=18)

Now, how do I get the last value 'HomeModel' out of this array for further use?, I need to assign the value 'HomeModel' to $class.

Body:
end() should do the job.

$class = end($result);


问:
Custom ASP binding mechanism problem
know ASP since about 6 months, and I've go hard problem. I've created my own DataBinding mechanism and I need some solution to do somthing like this:

I have this example code in my ASPX

```<code><myButton id="someID" runat="server" Text="SomeText" BackColor="{SomeContext}" />
</code>```

and I have in this control my property Context of type Object. I want to bind property which is inside Context to BackColor property. Name of the property from Context is SomeContext (in brackets). All I need is to use some TypeConverter or other technology to identify that there is a name inside {} and remember that name inside instance of myButton control. Any ideas???

I thought that I can use my own class inherited from TypeConverter and catch the moment of converting value {SomeContext} to Color (the BackColor property). I can catch this moment, but I have no info about target control, only empty context of String value. If anyone know how to get target property somehow, will be very!! helpful.

I've been searching web, and nothing...

答: I won't use codebehind in my project. Website will be rendered from compiled customized aspx from database. I have special approach for my system, and my binding is a main part of it. Regular databinding expression won't help because it use ASP binding, which I don't want to use.</p>

ContentLicense: CC BY-SA 2.5

Title: Custom ASP binding mechanism problem

Body:
know ASP since about 6 months, and I've go hard problem. I've created my own DataBinding mechanism and I need some solution to do somthing like this:

I have this example code in my ASPX

<myButton id="someID" runat="server" Text="SomeText" BackColor="{SomeContext}" />

and I have in this control my property Context of type Object. I want to bind property which is inside Context to BackColor property. Name of the property from Context is SomeContext (in brackets). All I need is to use some TypeConverter or other technology to identify that there is a name inside {} and remember that name inside instance of myButton control. Any ideas???

I thought that I can use my own class inherited from TypeConverter and catch the moment of converting value {SomeContext} to Color (the BackColor property). I can catch this moment, but I have no info about target control, only empty context of String value. If anyone know how to get target property somehow, will be very!! helpful.

I've been searching web, and nothing...


问:
Why is the custom font not being applied to my page in ASP.NET MVC?
I am trying to add a custom font to a webpage. I am using Google Chrome.

I am specifying the path in my CSS like so:

```<code>    @font-face {
    font-family: ottosans_regular;
    src: url(../Content/Fonts/ottosans-regular-1v32-webfont.woff);
}
</code>```

And applying it like so:

```<code>    body {
    font-family: ottosans_regular;
    background-color: #F0F0F0;
}
</code>```

答:
The font file may not be loading properly...
Try to add the mime type for .woff in your web.config.

```<code><system.webServer>
  ...
  <staticContent>
    <remove fileExtension=".woff" />
    <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
  </staticContent>
</system.webServer>
</code>```

More info here

Body:
I am trying to add a custom font to a webpage. I am using Google Chrome.

I am specifying the path in my CSS like so:

    @font-face {
    font-family: ottosans_regular;
    src: url(../Content/Fonts/ottosans-regular-1v32-webfont.woff);
}

And applying it like so:

    body {
    font-family: ottosans_regular;
    background-color: #F0F0F0;
}

Body:
The font file may not be loading properly...
Try to add the mime type for .woff in your web.config.

<system.webServer>
  ...
  <staticContent>
    <remove fileExtension=".woff" />
    <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
  </staticContent>
</system.webServer>

More info here


问:
Rxjs Sharing an observable subscription
I have a function with the following code:

```<code>private foo() {
    let obs: Observable<any> = this._http.get<number>('/foo')

    obs.subscribe(x=> {
        console.log("foo : " + x)
    });

     this.blah(obs)
}

private blah(obs: Observable<any>) {
    obs.subscribe(x => {
       console.log("blah : " + x)
    })
}
</code>```

this code is indeed printing both foo and blah, howerver it also does my http call to /foo twice

I would like it to happen only once. I tried replacing the subscribe by do in the blah function but it doesn't work.
What's the issue here ?

答:
That's correct behavior. You're creating two subscriptions and since the http.get creates a "cold" Observable it makes two HTTP calls.

The easiest way to avoid this is to share the source Observable with the share() operator.

```<code>let obs = this._http.get<number>('/foo').share();
</code>```

You could also create a ConnectableObservable with the publish() operator and connect to the shared source manually.

```<code>let obs = this._http.get<number>('/foo').publish();

obs.subscribe(x=> {
    console.log("foo : " + x)
});

this.blah(obs);

obs.connect();
</code>```

Title: Rxjs Sharing an observable subscription

Body:
I have a function with the following code:

private foo() {
    let obs: Observable<any> = this._http.get<number>('/foo')

    obs.subscribe(x=> {
        console.log("foo : " + x)
    });

     this.blah(obs)
}

private blah(obs: Observable<any>) {
    obs.subscribe(x => {
       console.log("blah : " + x)
    })
}

this code is indeed printing both foo and blah, howerver it also does my http call to /foo twice

I would like it to happen only once. I tried replacing the subscribe by do in the blah function but it doesn't work.
What's the issue here ?

Body:
That's correct behavior. You're creating two subscriptions and since the http.get creates a "cold" Observable it makes two HTTP calls.

The easiest way to avoid this is to share the source Observable with the share() operator.

let obs = this._http.get<number>('/foo').share();

You could also create a ConnectableObservable with the publish() operator and connect to the shared source manually.

let obs = this._http.get<number>('/foo').publish();

obs.subscribe(x=> {
    console.log("foo : " + x)
});

this.blah(obs);

obs.connect();


问:
Add Angular 4 to an ASP.NETCore Project
I want to utilize Angular 4 in my ASP.NetCore 1.1 project, within Visual Studio 2017 (read as: *.csproj file)

Previously with ASP.NET Core 1.0 and Visual Studio 2015, you could simply add AngularJS (1.x.x) into the project.json as a dependency and it would wire itself in.

Now, with ASP.NetCore and VS2017, the project.json file has gone away, and the only documentation I can find refers to STARTING an Angular 4 project by using the CLI and using the CLI to generate a NEW angular app.  I don't really want a new project or have to refactor everything I have created to provide a service to a separate UI project. I just want to augment my app with some added client-side UI experience.

Any suggestions?

Update

This questions has been getting a lot of views and the information is of little help so I'm providing this update.

Visual Studio 2017 (*.csproj)

Asp.Net Core 2.0 + Angular (v2.0~v4.0) :: Use the built in template! Best option IMO.

Asp.Net Core 1.X + Angular (v2.0~v4.0)

Create VS Project.

Create Angular Project via Angular CLI

Configuration and setup details : Link

Visual Studio 2015 (project.json)

Tooling: up to version -preview2 - No further updates, all new .NET Core features will be moving to VS 2017

Asp.Net Core 1.X + Angular (v2.0~v4.0)

Asp.Net Core Template Pack

Note: I wouldn't endorse a bad VS Plugin, Mads Kristensen does good work.

Configuration and setup details : Blog post

Asp.Net Core 1.X + AngularJS (~1.5)

Configuration and setup details : Microsoft Tutorial

Asp.Net MVC 5 + AngularJS (~1.5)

Pluralsight Blog Guide

Notes: There are many other ways to get Angular to work with ASP.Net / .NetCore projects such as NPM, Bower, NuGet, etc.  I tried to highlight the ones which are simple and actually work.  Also these are in line with the direction Microsoft is moving in, according to the Pluralsight blog post above.

答:
I have been working on a Angular 4(SPA) and .Net core web api. You can check out the repository and you might get a better understanding.

I had to find solutions to many areas like authentication, authorisation, social login, MongoDB connector e.t.c

Hope this would save time for someone stumbling on this.

https://github.com/Sathya-B/Angular-.NetCore-MongoDB

Title: Add Angular 4 to an ASP.NETCore Project


问:
Split elements of a list and retrieve only the first part from the split
I have a list say

```<code>List<string> someList = new List{"1-30","20-10","21-23","34-80"};
</code>```

I need to split the list so I have with following values

```<code> {"1","20","21","34"};
</code>```

I tried

```<code> someList
   .SelectMany(n => n.Split('-')[0])
   .ToList();
</code>```

But it is not giving me the desired result.

UPDATE:
Sorry everyone, Using Select solved my issue. One of those days, when you make silly mistakes

答:
You have to take the 1st part of each item and you can do with a help of Substring (i.e. take item's value up to -):

```<code> List<string> someList = new List{
   "1-30", "20-100", "21-23", "34-80"};

 var result = someList
   .Select(item => item.Substring(0, item.IndexOf('-')))
   .ToList(); // if you want a new list
</code>```

In case you want to change the existing list, just implement a loop:

```<code> for (int i = 0; i < someList.Count; ++i)
   someList[i] = someList[i].Substring(0, someList[i].IndexOf('-'));
</code>```

Edit: what's going on when you put SelectMany instead of Select.

SelectMany wants IEnumerable<T> as an outcome and since String is IEnumerable<char> you have a flatten List<char>s:

```<code>   ['1', '2', '0', '2', '1', '3', '4']
</code>```

Please, notice that each string ("1", "20", "21", "34") is treated as being a collection of chars (['1']; ['2', '0']; ['2', '1']; ['3', '4'])

Body:
I have a list say

List<string> someList = new List{"1-30","20-10","21-23","34-80"};

I need to split the list so I have with following values

 {"1","20","21","34"};

I tried

 someList
   .SelectMany(n => n.Split('-')[0])
   .ToList();

But it is not giving me the desired result.

UPDATE:
Sorry everyone, Using Select solved my issue. One of those days, when you make silly mistakes

Body:
You have to take the 1st part of each item and you can do with a help of Substring (i.e. take item's value up to -):

 List<string> someList = new List{
   "1-30", "20-100", "21-23", "34-80"};

 var result = someList
   .Select(item => item.Substring(0, item.IndexOf('-')))
   .ToList(); // if you want a new list

In case you want to change the existing list, just implement a loop:

 for (int i = 0; i < someList.Count; ++i)
   someList[i] = someList[i].Substring(0, someList[i].IndexOf('-'));

Edit: what's going on when you put SelectMany instead of Select.

SelectMany wants IEnumerable<T> as an outcome and since String is IEnumerable<char> you have a flatten List<char>s:

   ['1', '2', '0', '2', '1', '3', '4']

Please, notice that each string ("1", "20", "21", "34") is treated as being a collection of chars (['1']; ['2', '0']; ['2', '1']; ['3', '4'])


问:
Record instance in F# is null in C#
I'm working on an assignment for school in which we make a small game using monogame, with the added challenge of working in F#. The game logic is fully immutable F#, and the entrypoint is in C# by use of the Game class in monogame. I have however come across a weird problem concerning Record types in F#. In the logic (F#) I have something along the lines of:

```<code>...
module Vectors =
    type Vector = {
        x : double
        y : double
    }

    let Zero : Vector = {x=0.0; y=0.0}
...
</code>```

And in C# I have some code accessing Zero:

```<code>...
player.vector = Vectors.Zero;
...
</code>```

Weirdly enough, when I try to now use player.vector, it comes up as null. When debugging Vector.Zero is also null. I've looked around for a few solutions, and it may be some trivial mistake, but I can't seem to find it.

答:
When you build an F# project as an exe, but use it as a library, occasionally some initialisation code doesn't get called.

This can be fixed by changing the project to build as a library.

Title: Record instance in F# is null in C#

Body:
I'm working on an assignment for school in which we make a small game using monogame, with the added challenge of working in F#. The game logic is fully immutable F#, and the entrypoint is in C# by use of the Game class in monogame. I have however come across a weird problem concerning Record types in F#. In the logic (F#) I have something along the lines of:

...
module Vectors =
    type Vector = {
        x : double
        y : double
    }

    let Zero : Vector = {x=0.0; y=0.0}
...

And in C# I have some code accessing Zero:

...
player.vector = Vectors.Zero;
...

Weirdly enough, when I try to now use player.vector, it comes up as null. When debugging Vector.Zero is also null. I've looked around for a few solutions, and it may be some trivial mistake, but I can't seem to find it.


问:
TFS database project for both Azure SQL database and on premises with multiple filegroups
I am working on a project to replicate an application that currently runs on premises to an Azure SQL Database.  For the foreseeable future, the application will have to run both on site and on Azure.  The project is stored in TFS, and multiple filegroups are specified.  Development is ongoing.  Is there a way I can maintain this as one project in source control, given that Azure SQL databases only have a primary filegroup?  I feel like I can't be the first person in this situation, but I haven't found a decent solution yet.

I'm fine with the Azure database only running on primary, but that is not an option for the local database.  This is not for a single deployment, I would like to continue to deploy changes both locally and to Azure from source control.  I may be asking for too much here, I just really really want to avoid dual maintenance, when there are a number of teams involved.

Thank you!

答:
You have two options:

Add manual SQL Statements to setup Filegroups on your on-premises SQL Server that don't run against SQL Azure

Use a new feature of Azure named SQL Managed Instances. This is fully managed SQL Server instance running in Azure that supports all features of SQL Server such as filegroups. Don't go installing your own SQL Server on IaaS. That's not necessary anymore with this new feature.


问:
SELECT QUERY LIKE containing only specific words in a string
I have one table like below ,table name is js_skills_achievements

```<code>id   skill1  skill2  skill3  skill4
1     java    php    html    android
2     php     java   jquery  html
3     sql     php    html    jquery
</code>```

When admin search key is "java developer in nersupalli"

my query is below

```<code>SELECT *
FROM `js_skills_achievements`
WHERE `skill1`  LIKE '%java developer in nersupalli%'
   OR `skill2`  LIKE '%java developer in nersupalli%'
   OR `skill3`  LIKE '%java developer in nersupalli%'
   OR `skill4`  LIKE '%java developer in nersupalli%'
ORDER BY id DESC
LIMIT 10
</code>```

Its not working for me . My Requirement is i need to display all java records . here total 2 records in java . i.e id1,id2. But am getting empty rows.

Below ways only working

```<code>SELECT *
FROM `js_skills_achievements`
WHERE `skill1`  LIKE '%java%'
   OR `skill2`  LIKE '%java%'
   OR `skill3`  LIKE '%java%'
   OR `skill4`  LIKE '%java%'
ORDER BY id DESC
LIMIT 10
</code>```

I need based on string specified keyword search . can you any one please help on this . Am very appreciate. Thanks

答:
```<code>SELECT *
FROM `js_skills_achievements`
WHERE '%java developer in nersupalli%' LIKE CONCAT('%',skill1,'%')
   OR '%java developer in nersupalli%' LIKE CONCAT('%',skill2,'%')
   OR '%java developer in nersupalli%' LIKE CONCAT('%',skill3,'%')
   OR '%java developer in nersupalli%' LIKE CONCAT('%',skill4,'%')
ORDER BY id DESC
LIMIT 10;
</code>```

Body:
I have one table like below ,table name is js_skills_achievements

id   skill1  skill2  skill3  skill4
1     java    php    html    android
2     php     java   jquery  html
3     sql     php    html    jquery

When admin search key is "java developer in nersupalli"

my query is below

SELECT *
FROM `js_skills_achievements`
WHERE `skill1`  LIKE '%java developer in nersupalli%'
   OR `skill2`  LIKE '%java developer in nersupalli%'
   OR `skill3`  LIKE '%java developer in nersupalli%'
   OR `skill4`  LIKE '%java developer in nersupalli%'
ORDER BY id DESC
LIMIT 10

Its not working for me . My Requirement is i need to display all java records . here total 2 records in java . i.e id1,id2. But am getting empty rows.

Below ways only working

SELECT *
FROM `js_skills_achievements`
WHERE `skill1`  LIKE '%java%'
   OR `skill2`  LIKE '%java%'
   OR `skill3`  LIKE '%java%'
   OR `skill4`  LIKE '%java%'
ORDER BY id DESC
LIMIT 10

I need based on string specified keyword search . can you any one please help on this . Am very appreciate. Thanks


问:
Node.js- How to send a varaible from route's js file to layout.jade
I am working on node.js and express. Using jade as my template engine. I am displaying a navbar which is static.I kept it in layout.jade. I have a login form and need to display user name on the navbar.I am using session to store username and using req.app.locals.env=req.session.username;.

 Now username is global and can use in layout. Its working. But the problem is when I open two users in different browsers, only recently logged in username is displayed for all remaining users in navbars. Can any one help me?

here are the screenshots of my output.

a user logged in chrome(suresh)

another user logged in firefox(user)

Navbar in my output is in layout.jade which i extended in all views.I opened two users in different browsers.
The problem is when I click view,insert, home r any button in navbar,the name "suresh" is changed to "user" in navbar.Since I am displaying name as gobal and storing the session value to dislpay the name in layout.jade. Is there any Other way to display username in Layout?

答:
That's because you are saving username in session and session gets updated after recent login.
Best way to do this is send usersInfo to route on render.</p>

```<code> res.render('/home', { userInfo: userInfo });
</code>```

Body:
That's because you are saving username in session and session gets updated after recent login.
Best way to do this is send usersInfo to route on render.

 res.render('/home', { userInfo: userInfo });


答:
Solved - F# project was building as a console application.
Changing it to be a class library fixed the issue.

Thanks @JohnPalmer

Title: Record instance in F# is null in C#


问:
C: Print Unsigned Int In a Binary Base
I have to make my own printf(for an exercise) and I have to add a %b flag which prints an unsigned number in a binary base. I've created the function but I'm still getting the unsigned number at the output. There you have my code. Thanks in advance!</p>

```<code>int unsignednbr(unsigned int nb)
{
    if (nb < 0)
    {
        putchar('-');
        nb = nb * -1;
    }
    if (nb >= 10)
    {
        putnumber(nb / 10);
        putnumber(nb % 10);
    }
    else
        putchar(nb + '0');
}

int unsigned_to_binary(int nb)
{
    long long binary_nbr = 0;
    int remainder;
    int i = 0;

    unsignednbr(nb);
    while (nb != 0)
    {
        remainder = nb % 2;
        nb /= 2;
        binary_nbr += remainder * i;
        i *= 10;
    }
}

void own_printf(char* format, ...)
{
    int i = 0;
    va_list args;

    va_start(args, format);
    while (format[i])
    {
        if (format[i] == '%')
        {
            switch (format[i + 1])
            {
            case 'b':
                unsigned_to_binary (va_arg( args, int));
                break;
            }
            i++;
        }
    }
    va_end(args);
}

int main()
{
    own_printf("%b", -42);
    return 0;
}
</code>```

答:
You can use following(Using Recursion):

```<code>void printBinaryValue(unsigned int num)
{
    if(!num) return;

    printBinaryValue(num>>1);
    putchar(((num&1 == 1) ? '1' : '0'));
}
</code>```

See it working here

UPDATED

Following code will provide desired output for all inputs including 0(Using while-loop).

```<code> void printBinaryValue2(unsigned int num)
 {
    char result[sizeof(num)*8];
    int count = 0;
    while(num)
    {
        result[count++] = ((num&1 == 1) ? '1' : '0');
        num>>=1;
    }
    if(count)
    {
        count--;
        while(count>=0)
        {
            putchar(result[count--]);
        }
    }
    else
    {
        putchar('0');
    }
 }
</code>```

Title: C: Print Unsigned Int In a Binary Base

Body:
I have to make my own printf(for an exercise) and I have to add a %b flag which prints an unsigned number in a binary base. I've created the function but I'm still getting the unsigned number at the output. There you have my code. Thanks in advance!

int unsignednbr(unsigned int nb)
{
    if (nb < 0)
    {
        putchar('-');
        nb = nb * -1;
    }
    if (nb >= 10)
    {
        putnumber(nb / 10);
        putnumber(nb % 10);
    }
    else
        putchar(nb + '0');
}

int unsigned_to_binary(int nb)
{
    long long binary_nbr = 0;
    int remainder;
    int i = 0;

    unsignednbr(nb);
    while (nb != 0)
    {
        remainder = nb % 2;
        nb /= 2;
        binary_nbr += remainder * i;
        i *= 10;
    }
}

void own_printf(char* format, ...)
{
    int i = 0;
    va_list args;

    va_start(args, format);
    while (format[i])
    {
        if (format[i] == '%')
        {
            switch (format[i + 1])
            {
            case 'b':
                unsigned_to_binary (va_arg( args, int));
                break;
            }
            i++;
        }
    }
    va_end(args);
}

int main()
{
    own_printf("%b", -42);
    return 0;
}

Body:
You can use following(Using Recursion):

void printBinaryValue(unsigned int num)
{
    if(!num) return;

    printBinaryValue(num>>1);
    putchar(((num&1 == 1) ? '1' : '0'));
}

See it working here

UPDATED

Following code will provide desired output for all inputs including 0(Using while-loop).

 void printBinaryValue2(unsigned int num)
 {
    char result[sizeof(num)*8];
    int count = 0;
    while(num)
    {
        result[count++] = ((num&1 == 1) ? '1' : '0');
        num>>=1;
    }
    if(count)
    {
        count--;
        while(count>=0)
        {
            putchar(result[count--]);
        }
    }
    else
    {
        putchar('0');
    }
 }


问:
Resizing inkcanvas to the left and top
I want to resize width and height of inkcanvas to fit the screen. When I resized it, the width expands to the right and height expands to the bottom. But inkcanvas is not fit to screen.

I also want to fix the position of inkcanvas child element. If I can resize inkcanvas to fit the screen, the position of inkcanvas child element will not change.

How do I resize inkcanvas to the left and top to fit the screen?

```<code><Canvas x:Name="Screen" >

                <InkCanvas Name="inkcanvas" ResizeEnabled="True"
                          Width="{Binding ElementName=LayoutRoot, Path=ActualWidth}"
                        Height="{Binding ElementName=LayoutRoot, Path=ActualHeight}"
                           EditingMode="Select" ClipToBounds="False"
                    Background="Bisque"
                    SelectionChanging="OnSelectionChanging"
                    Visibility="Collapsed" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">

                    <!-- InkCanvas' Child Elements -->
                </InkCanvas>
                <Canvas.RenderTransform>
                    <MatrixTransform/>
                </Canvas.RenderTransform>
            </Canvas>
</code>```

Thanks

Update:
I put inkcanvas in a grid. It fit to the screen but the position of child element is changed.

I want to fix the red rectangle position.

The position of red rectangle should not be changed.

```<code><Grid>
        <InkCanvas x:Name="inkcanvas"  Background="Transparent">
            <Rectangle Height="41" HorizontalAlignment="Left"  Name="rectangle1" Stroke="Black" VerticalAlignment="Top" Width="69" Fill="#FFDB1111" />
        </InkCanvas>
        </Grid>
</code>```

My big picure:

My WPF Application contain many pictures. I can zoom in/out the canvas. I can select the pictures by using selection tool.

I have canvas and inkcanvas.

canvas: contain picture and zoom in/out

inkcanvas: has selection tool

If I zoom out, the canvas and inkcanvas become smaller.

If I use selection tool, I copy all pictures from canvas to inkcanvas.

But the inkcanvas is zoom out, I cannot use selection tool if outside the inkcanvas boundary.

It is the reason why I want to resize inkcanvas and fix the children position.

答:
This depends on the container around the InkCanvas. Further you cannot expect the child-elements not to move if you mess with their container. If you need the child elements to behave independently of the InkCanvas you might want to rethink if that is a good idea and if what you want to accomplish can not be done more efficiently using another setup.

You should tell us more about what the big picture is of what you want to achieve, the fact that children are affected by manipulations of their container is expected and generally wanted. Maybe there is a better approach than to try and scale the container and at the same time having to shift all children around to nullify such a manipulation.

Title: Resizing inkcanvas to the left and top

Body:
I want to resize width and height of inkcanvas to fit the screen. When I resized it, the width expands to the right and height expands to the bottom. But inkcanvas is not fit to screen.

I also want to fix the position of inkcanvas child element. If I can resize inkcanvas to fit the screen, the position of inkcanvas child element will not change.

How do I resize inkcanvas to the left and top to fit the screen?

<Canvas x:Name="Screen" >

                <InkCanvas Name="inkcanvas" ResizeEnabled="True"
                          Width="{Binding ElementName=LayoutRoot, Path=ActualWidth}"
                        Height="{Binding ElementName=LayoutRoot, Path=ActualHeight}"
                           EditingMode="Select" ClipToBounds="False"
                    Background="Bisque"
                    SelectionChanging="OnSelectionChanging"
                    Visibility="Collapsed" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">

                </InkCanvas>
                <Canvas.RenderTransform>
                    <MatrixTransform/>
                </Canvas.RenderTransform>
            </Canvas>

Thanks

Update:
I put inkcanvas in a grid. It fit to the screen but the position of child element is changed.

I want to fix the red rectangle position.

The position of red rectangle should not be changed.

<Grid>
        <InkCanvas x:Name="inkcanvas"  Background="Transparent">
            <Rectangle Height="41" HorizontalAlignment="Left"  Name="rectangle1" Stroke="Black" VerticalAlignment="Top" Width="69" Fill="#FFDB1111" />
        </InkCanvas>
        </Grid>

My big picure:

My WPF Application contain many pictures. I can zoom in/out the canvas. I can select the pictures by using selection tool.

I have canvas and inkcanvas.

canvas: contain picture and zoom in/out

inkcanvas: has selection tool

If I zoom out, the canvas and inkcanvas become smaller.

If I use selection tool, I copy all pictures from canvas to inkcanvas.

But the inkcanvas is zoom out, I cannot use selection tool if outside the inkcanvas boundary.

It is the reason why I want to resize inkcanvas and fix the children position.


问:
External API call in Google Spreedsheet is possible?
I have created a Google Spreadsheet with five columns;

Once the user filled the values in the first three columns, It has to call a 3rd party API and fill the value(response) in the forth and fifth columns.

Is it possible to write a code in Google Spreadsheet for API call?
Is it possible to call and get response from external API in Google Spreadsheet?

答:
I've recently come accross the same requirement to read the rows of the sheet and send the data in request and record the response. I thought I would share what I worked out after googling a bit...

```<code>function testing_this() {
    var data = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
    for (row in data) {
        Logger.log(data[row]);

        var row = data[row]
        var options = {
            'method': 'post',
            'payload': { email:row[1]}
        };
        // sending to API. for example:
        UrlFetchApp.fetch('https://your-rest-api-url/v1/customers/', options);
    }
}
</code>```

If you want to get the data in the sheet you should use the function:

```<code>var response = UrlFetchApp.getRequest("http://your-api-url/");
    for(data in response) {
        var respData = response[data];
        // do whatever u want to do with this data...
    }
</code>```

Hope it is useful to you all who are facing similar requirement as above.

I've posted this script in github if you want to fork/pull...

https://github.com/joshiparthin/gsheetScriptExperiments/blob/master/readAndSendToApi.js

Cheers,

Parth

Body:
I've recently come accross the same requirement to read the rows of the sheet and send the data in request and record the response. I thought I would share what I worked out after googling a bit...

function testing_this() {
    var data = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
    for (row in data) {
        Logger.log(data[row]);

        var row = data[row]
        var options = {
            'method': 'post',
            'payload': { email:row[1]}
        };
        // sending to API. for example:
        UrlFetchApp.fetch('https://your-rest-api-url/v1/customers/', options);
    }
}

If you want to get the data in the sheet you should use the function:

var response = UrlFetchApp.getRequest("http://your-api-url/");
    for(data in response) {
        var respData = response[data];
        // do whatever u want to do with this data...
    }

Hope it is useful to you all who are facing similar requirement as above.

I've posted this script in github if you want to fork/pull...

https://github.com/joshiparthin/gsheetScriptExperiments/blob/master/readAndSendToApi.js

Cheers,

Parth


问:
Winforms app: Wrong icon in start menu search
I'm building a simple Winforms application that deploys via msi (Visual Studio setip project). The msi creates a shortcut on the users desktop and the start menu.

Everywhere (desktop, start menu, taskbar when program is running, .exe file) the program icon is displayed correctly.

But not when I type the program name in the start menu search (see screenshot below). There some generic icon is displayed.

I quadruple-checked the icon set in Visual Studio > Winforms Project > Properties > Application and the icon for the shortcut set via the Visual Studio setup project. The .ico file has many different resolutions embedded, up to 512x512px. Since it's working fine everywhere else (except in the search) I can't think of anything als I could try.

答:
Hans' comment was the solution for me. It seems that Windows caches the old/wrong icon. When I tried it on a clean Windows 10, it worked immediately.

Of course, I tried to clear the icon caches according to Application icon is blank when started from Process.Start or the script at http://www.winhelponline.com/blog/how-to-rebuild-the-icon-cache-in-windows but this did not work on my machine (even with a lot of restarts and killing of explorer.exe).


问:
Escape XML entities only once
I have the following XML snippet in a string (note the double encoded &):

```<code>...
<PARA>
S&P
</PARA>
...
</code>```

My desired output would be:

```<code>> ... <PARA> S&P </PARA> ...
</code>```

If I use:

StringEscapeUtils.unescapeXml()

The actual oputput is:

```<code> > ... <PARA> S&P </PARA> ...
</code>```

It seems that StringEscapeUtils.unescapeXml() escapes the input twice, or as long as it contains entities.

Is there a better utility method, or simple solution that can unescape every xml entity (not just a few but all accentuated character) once, so that my encoded & part does not get screwed up?

Thank,
Peter

答:
When you use third-party libraries, you should include the library name and the version.

StringEscapeUtils is part of Apache Commons Text and Apache Commons Lang (deprecated). The latest versions (as of November 2017) are Commons Text 1.1 and Commons Lang 3.3.7. Both versions show correct results.

```<code>import org.apache.commons.text.StringEscapeUtils;
public class EscapeTest {
  public static void main(String[] args) {
    final String s = "<PARA> S&amp;P </PARA>";
    System.out.println(StringEscapeUtils.unescapeXml(s));
  }
}
</code>```

Output: <PARA> S&P </PARA>

Title: Escape XML entities only once

Body:
I have the following XML snippet in a string (note the double encoded &):

...
<PARA>
S&amp;P
</PARA>
...

My desired output would be:

> ... <PARA> S&P </PARA> ...

If I use:

StringEscapeUtils.unescapeXml()

The actual oputput is:

 > ... <PARA> S&P </PARA> ...

It seems that StringEscapeUtils.unescapeXml() escapes the input twice, or as long as it contains entities.

Is there a better utility method, or simple solution that can unescape every xml entity (not just a few but all accentuated character) once, so that my encoded & part does not get screwed up?

Thank,
Peter

Body:
When you use third-party libraries, you should include the library name and the version.

StringEscapeUtils is part of Apache Commons Text and Apache Commons Lang (deprecated). The latest versions (as of November 2017) are Commons Text 1.1 and Commons Lang 3.3.7. Both versions show correct results.

import org.apache.commons.text.StringEscapeUtils;
public class EscapeTest {
  public static void main(String[] args) {
    final String s = "&lt;PARA&gt; S&amp;amp;P &lt;/PARA&gt;";
    System.out.println(StringEscapeUtils.unescapeXml(s));
  }
}

Output: <PARA> S&amp;P </PARA>


问:
android firebase database Invalid token in path
I did the base64 utf-8 encoding of the email.
Because it is a database key.
However, the following problems arise.
I need help.

setValue at /user/aW1hZ2VfNTk1NkBuYXZlci5jb20=
failed: DatabaseError: Invalid token in path

```<code>databaseReference.child("user").child(util.getBase64encode(email)).setValue(userModel)
</code>```

help me...

答:
In my case, the encoded string was having a new line at the end. Using Base64.NO_WRAP as mentioned by @Arvin in this answer worked as a solution. My encoding function now looks like:

```<code>public static String encodeToBase64(String strToEncode) {
    byte[] data = null;
    try {
        data = strToEncode.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return Base64.encodeToString(data, Base64.NO_WRAP);
}
</code>```

If you're aiming to be safe like what @BobSnyder mentioned in the comments above, you could still use URL_SAFE and just trim the String just to make sure.

Body:
I did the base64 utf-8 encoding of the email.
Because it is a database key.
However, the following problems arise.
I need help.

setValue at /user/aW1hZ2VfNTk1NkBuYXZlci5jb20=
failed: DatabaseError: Invalid token in path

databaseReference.child("user").child(util.getBase64encode(email)).setValue(userModel)

help me...

Body:
In my case, the encoded string was having a new line at the end. Using Base64.NO_WRAP as mentioned by @Arvin in this answer worked as a solution. My encoding function now looks like:

public static String encodeToBase64(String strToEncode) {
    byte[] data = null;
    try {
        data = strToEncode.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return Base64.encodeToString(data, Base64.NO_WRAP);
}

If you're aiming to be safe like what @BobSnyder mentioned in the comments above, you could still use URL_SAFE and just trim the String just to make sure.


问:
Delete specific values from column with where condition?
I want to delete specific values/data from one column with the WHERE condition. Putting in another way, I don't want to delete the complete row. Is it possible?</p>

答:
```<code>UPDATE YourTable SET columnName = null WHERE YourCondition
</code>```

ContentLicense: CC BY-SA 4.0


问:
How to remove the white space before a word in a sentance in JS
I have a sentence like below,

```<code>var text  = 'My       name         is           Ran';
</code>```

I wnat this text to print like below,

```<code>'My       name is              Ran';
</code>```

I want to remove the space before 'is'.Can anyone please suggest help.Thanks.

答:
Updated for: Hi Ramesh ,how can I replace only the space before 'is', if my string is My name         is           Ran;

var  data='My name         is           Ran';
var  result = data.split("is");
console.log(result[0].replace(/ +/g, ' ') +"is" + result[1]);```
</div>
</div>
</p>

<h2>For the OP Update 2</h2>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var  data= 'My       name         is           Ran';//
var  result = data.split("is");
var  result1 = data.split("name");
console.log( result1[0]+  "name " + "is" + result[1]);</code>```

Final Solution by the OP question update 5th

   var  data= "My       name     is           Ran";// or My       name  is           Ran

   if(data.indexOf("name   ") == -1)
   {
      var  result = data.split("is");
      var  result1 = data.split("name");
      console.log(result1[0]+  "name " + "is" + result[1]);
   } else   {
      var  result = data.split("is");
      var  result1 = data.split("name");
      console.log(result1[0]+  "name " + "is" + result[1]);
   }```

Body:
I have a sentence like below,

var text  = 'My       name         is           Ran';

I wnat this text to print like below,

'My       name is              Ran';

I want to remove the space before 'is'.Can anyone please suggest help.Thanks.

Body:
Updated for: Hi Ramesh ,how can I replace only the space before 'is', if my string is My name         is           Ran;

var  data='My name         is           Ran';
var  result = data.split("is");
console.log(result[0].replace(/ +/g, ' ') +"is" + result[1]);

For the OP Update 2

var  data= 'My       name         is           Ran';//
var  result = data.split("is");
var  result1 = data.split("name");
console.log( result1[0]+  "name " + "is" + result[1]);

Final Solution by the OP question update 5th

   var  data= "My       name     is           Ran";// or My       name  is           Ran

   if(data.indexOf("name   ") == -1)
   {
      var  result = data.split("is");
      var  result1 = data.split("name");
      console.log(result1[0]+  "name " + "is" + result[1]);
   } else   {
      var  result = data.split("is");
      var  result1 = data.split("name");
      console.log(result1[0]+  "name " + "is" + result[1]);
   }


问:
How do I get emoji autosuggestions on iOS 11 keyboards
Prior to updating to iOS 11, app keyboards used to show emoji suggestions above the keyboard as I typed into a UITextField (for example). This still happens in the iMessages app for example (and the slack app). Is this now a setting I need to set in code? </p>

答: I think — the suggestions reset on the update (or new phone maybe), but as you use emojis in specific apps a bit more, the emoji suggestions come back</p>


问:
How to download all Files of FirebaseStorage folder on Android?
I wants to download all content of a Folder in FirebaseStorage. I can download a only file (image) like this:

```<code>FirebaseStorage storage = FirebaseStorage.getInstance();

    try {
        final File localFile = File.createTempFile("ImagensExercicios","bmp");
        storage.getReference().child("ImagensExercicios").child("abdominal_1.bmp").getFile(localFile).
                addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
                Log.i(TAG,"onSuccess()");
                Bitmap bitmap;
                bitmap = BitmapFactory.decodeFile(localFile.getAbsolutePath());
                imageView.setImageBitmap(bitmap);
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.i(TAG,"onFailure() " + e.getMessage());
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
</code>```

This works, but I wants download all images of the folder. Exists a way to do this?

答:
In the firebase folder rename the items as

abdominal_1.bmp

abdominal_2.bmp

abdominal_3.bmp

And use above try catch inside a forloop.

Body:
I wants to download all content of a Folder in FirebaseStorage. I can download a only file (image) like this:

FirebaseStorage storage = FirebaseStorage.getInstance();

    try {
        final File localFile = File.createTempFile("ImagensExercicios","bmp");
        storage.getReference().child("ImagensExercicios").child("abdominal_1.bmp").getFile(localFile).
                addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
                Log.i(TAG,"onSuccess()");
                Bitmap bitmap;
                bitmap = BitmapFactory.decodeFile(localFile.getAbsolutePath());
                imageView.setImageBitmap(bitmap);
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.i(TAG,"onFailure() " + e.getMessage());
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }

This works, but I wants download all images of the folder. Exists a way to do this?


问:
Why is the positional parameter still present after sourcing the script?
I am sourcing a script and the value of the positional parameter is reflecting even after the script is sourced.</p>

```<code>$ echo $1

$ . $SCRIPTS_DIR/xeye.sh ryadqa
Done
$ echo $1
ryadqa
</code>```

答:
As for bash, this is from the bash man-page, which explains the source command:

source filename [arguments] ... If any arguments are supplied, they become the positional parameters when filename is  executed. Otherwise the positional parameters are unchanged.

(Note that positional parameters refers to that of the sourcing script, because sourcing of a file occurs in the context of the sourcing script).

Body:
I am sourcing a script and the value of the positional parameter is reflecting even after the script is sourced.

$ echo $1

$ . $SCRIPTS_DIR/xeye.sh ryadqa
Done
$ echo $1
ryadqa


问:
elasticsearch alias with rails
I am using rails with elasticsearch, thanks to the elasticsearch-rails gem ( https://github.com/elastic/elasticsearch-rails/tree/master/elasticsearch-persistence )

I am using the repository model as described in the documentation, I can change the index, but is it possible to use the alias feature of ES? If so, how?
Example:

```<code>require 'elasticsearch/persistence'
repository = Elasticsearch::Persistence::Repository.new
repository.index = "myindex"
</code>```

works fine, but no indication on how to create an alias

答:
Update alias without downtime</p>

```<code>client = Elasticsearch::Client.new
# or other es client
client.indices.update_aliases body: {
  actions: [
{ remove: { index: 'your_old_index_name', alias: 'your_alias_name' } },
{ add: { index: 'your_new_index_name', alias: 'your_alias_name' } }
]
}
</code>```

Title: elasticsearch alias with rails

Body:
I am using rails with elasticsearch, thanks to the elasticsearch-rails gem ( https://github.com/elastic/elasticsearch-rails/tree/master/elasticsearch-persistence )

I am using the repository model as described in the documentation, I can change the index, but is it possible to use the alias feature of ES? If so, how?
Example:

require 'elasticsearch/persistence'
repository = Elasticsearch::Persistence::Repository.new
repository.index = "myindex"

works fine, but no indication on how to create an alias

Body:
Update alias without downtime

client = Elasticsearch::Client.new
# or other es client
client.indices.update_aliases body: {
  actions: [
{ remove: { index: 'your_old_index_name', alias: 'your_alias_name' } },
{ add: { index: 'your_new_index_name', alias: 'your_alias_name' } }
]
}


答:
You don't want to delete if you're wanting to leave the row itself intact. You want to update the row, and change the column value.

The general form for this would be an UPDATE statement:

```<code>UPDATE <table name>
SET
    ColumnA = <NULL, or '', or whatever else is suitable for the new value for the column>
WHERE
    ColumnA = <bad value> /* or any other search conditions */
</code>```

Title: Delete specific values from column with where condition?

Body: I want to delete specific values/data from one column with the WHERE condition. Putting in another way, I don't want to delete the complete row. Is it possible?

Body:
You don't want to delete if you're wanting to leave the row itself intact. You want to update the row, and change the column value.

The general form for this would be an UPDATE statement:

UPDATE <table name>
SET
    ColumnA = <NULL, or '', or whatever else is suitable for the new value for the column>
WHERE
    ColumnA = <bad value> /* or any other search conditions */


问:
Create array of objects based off the same property names
I have form inputs that are generated based off an XML file.

We keep a reference of nested elements in the XML file via data-* attributes which can later be used to build an object. For example:

```<code><parent>
 <child>
  <grandchild1>first</grandchild1>
  <grandchild2>second</grandchild2>
 </child>
</parent>
</code>```

Becomes

<input type="text" data-nest="parent.child.grandchild1" value="first"/>
<input type="text" data-nest="parent.child.grandchild2" value="second"/>

When we submit the form, I create an object (with nested objects) based off of their data-nest attribute. The above would become

```<code>parent:{
 child:{
  grandchild1: first,
  grandchild2: second
  }
}
</code>```

The issue that I am running into is where multiple of the same tag are found in the XML file, e.g.

```<code><child>
 <grandchild>first</grandchild>
 <grandchildFriend>firstFriend</grandchildFriend>
</child>
<child>
 <grandchild>second</grandchild>
 <grandchildFriend>secondFriend</grandchildFriend>
</child>
</code>```

When I create my object, I would like it so that if multiple occurrences of the same data-nest value are found, they are nested inside of an array in order to maintain the different values.

With the current setup, the second occurrence of the tag will understandably overwrite the first.

This is the final object structure I desire:

```<code>parent:{
 child:[
  {
   grandchild: first,
   grandchildFriend: firstFriend
  },
  {
   grandchild: second,
   grandchildFriend: secondFriend
  }
  ]
 }
</code>```

TL;DR

I'd like to change an object to an array of nested objects if they have the same data-* attribute

Here's a fiddle of how the current code works to help give a better understanding.

答:
replacing currentObj[lastKey] = value; with this:

```<code>if(typeof currentObj[lastKey] === 'undefined') {
    currentObj[lastKey] = value;
} else  {
    if(typeof currentObj[lastKey] !== 'array')
            currentObj[lastKey] = [currentObj[lastKey]];
    currentObj[lastKey].push(value);
}
</code>```

the code will do the following: if currentObj[lastKey] is not set, you will create an element as always, otherwise, if it is already set and is a string the code will convert it into an array and then push into the arrays the subsequent (as many as you want) elements
and the final result will be something similar to:

```<code>parent:{
...
 grandchild:[
   "first", "second"
  ]
...
 }
</code>```

Edit
in order to have a result in the format that you have requested, you need to do some more edit, like following:

```<code>var json = {};

config = {
  set: function(keyValueString) {

    var pair = keyValueString.split('=');

    // left of the = is the key path
    var keyPath = pair[0];

    // right of the = is the value to set
    var value = pair[1];

    // split keyPath into an array of keys
    var keys = keyPath.split('.');
    var key;

    var currentObj = json;

    // loop through all keys in the key path, except the last one.
    // this creates the object structure implied by the key path.
    // we want to do something different on the last iteration.
    for (var i=0; i < keys.length-1; i++) {

      // Get the current key we are looping
      key = keys[i];
      // if the requested level on the current object doesn't exist,
      // make a blank object.
      if (typeof currentObj[key] === 'undefined') {
        currentObj[key] = i === keys.length-2 ? []: {};
      }

      currentObj = currentObj[key];
    }

    // our loop doesn't handle the last key, because that's when we
    // want to set the actual value.
    var lastKey = keys[keys.length-1]

    // set the property of the deepest object to the value.
    var child = {};
    child[lastKey] = value;
    currentObj.push(child);
  }
};

// iterate through all of our inputs, and nest them based off their data-* attribute
$('input').each(function(){
    // set nest = value setup, e.g. parent.child.grandchild = first
  // we then break this
    var key = $(this).attr('data-nest') + '=' + $(this).val();
  config.set(key);
});

// as a bonus - this is how I went about breaking multiple values within a single input into an array
function traverseObject(object){
  // iterate through the object
  for (var i in object){

    // if the next key exists, run again
    if(object[i] !== null && typeof(object[i])=="object"){
      traverseObject(object[i]);
    } else {
    var value = [object[i]];
     // if the value contains a comma
    if(value.toString().indexOf(',') > -1){
      // set the *nested* key to the
      // value as an array by splitting at the commas
      object[i] =value.toString().split(',').filter(function(el){
        // remove the extra entry after splitting
        return el.length != 0;
      });
    }
    }
  }
}

traverseObject(json);

$('#test').on('click', function(){
    console.log(json)
});
</code>```

Body:
I have form inputs that are generated based off an XML file.

We keep a reference of nested elements in the XML file via data-* attributes which can later be used to build an object. For example:

<parent>
 <child>
  <grandchild1>first</grandchild1>
  <grandchild2>second</grandchild2>
 </child>
</parent>

Becomes

<input type="text" data-nest="parent.child.grandchild1" value="first"/>
<input type="text" data-nest="parent.child.grandchild2" value="second"/>

When we submit the form, I create an object (with nested objects) based off of their data-nest attribute. The above would become

parent:{
 child:{
  grandchild1: first,
  grandchild2: second
  }
}

The issue that I am running into is where multiple of the same tag are found in the XML file, e.g.

<child>
 <grandchild>first</grandchild>
 <grandchildFriend>firstFriend</grandchildFriend>
</child>
<child>
 <grandchild>second</grandchild>
 <grandchildFriend>secondFriend</grandchildFriend>
</child>

When I create my object, I would like it so that if multiple occurrences of the same data-nest value are found, they are nested inside of an array in order to maintain the different values.

With the current setup, the second occurrence of the tag will understandably overwrite the first.

This is the final object structure I desire:

parent:{
 child:[
  {
   grandchild: first,
   grandchildFriend: firstFriend
  },
  {
   grandchild: second,
   grandchildFriend: secondFriend
  }
  ]
 }

TL;DR

I'd like to change an object to an array of nested objects if they have the same data-* attribute

Here's a fiddle of how the current code works to help give a better understanding.

Body:
replacing currentObj[lastKey] = value; with this:

if(typeof currentObj[lastKey] === 'undefined') {
    currentObj[lastKey] = value;
} else  {
    if(typeof currentObj[lastKey] !== 'array')
            currentObj[lastKey] = [currentObj[lastKey]];
    currentObj[lastKey].push(value);
}

the code will do the following: if currentObj[lastKey] is not set, you will create an element as always, otherwise, if it is already set and is a string the code will convert it into an array and then push into the arrays the subsequent (as many as you want) elements
and the final result will be something similar to:

parent:{
...
 grandchild:[
   "first", "second"
  ]
...
 }

Edit
in order to have a result in the format that you have requested, you need to do some more edit, like following:

var json = {};

config = {
  set: function(keyValueString) {

    var pair = keyValueString.split('=');

    // left of the = is the key path
    var keyPath = pair[0];

    // right of the = is the value to set
    var value = pair[1];

    // split keyPath into an array of keys
    var keys = keyPath.split('.');
    var key;

    var currentObj = json;

    // loop through all keys in the key path, except the last one.
    // this creates the object structure implied by the key path.
    // we want to do something different on the last iteration.
    for (var i=0; i < keys.length-1; i++) {

      // Get the current key we are looping
      key = keys[i];
      // if the requested level on the current object doesn't exist,
      // make a blank object.
      if (typeof currentObj[key] === 'undefined') {
        currentObj[key] = i === keys.length-2 ? []: {};
      }

      currentObj = currentObj[key];
    }

    // our loop doesn't handle the last key, because that's when we
    // want to set the actual value.
    var lastKey = keys[keys.length-1]

    // set the property of the deepest object to the value.
    var child = {};
    child[lastKey] = value;
    currentObj.push(child);
  }
};

// iterate through all of our inputs, and nest them based off their data-* attribute
$('input').each(function(){
    // set nest = value setup, e.g. parent.child.grandchild = first
  // we then break this
    var key = $(this).attr('data-nest') + '=' + $(this).val();
  config.set(key);
});

// as a bonus - this is how I went about breaking multiple values within a single input into an array
function traverseObject(object){
  // iterate through the object
  for (var i in object){

    // if the next key exists, run again
    if(object[i] !== null && typeof(object[i])=="object"){
      traverseObject(object[i]);
    } else {
    var value = [object[i]];
     // if the value contains a comma
    if(value.toString().indexOf(',') > -1){
      // set the *nested* key to the
      // value as an array by splitting at the commas
      object[i] =value.toString().split(',').filter(function(el){
        // remove the extra entry after splitting
        return el.length != 0;
      });
    }
    }
  }
}

traverseObject(json);

$('#test').on('click', function(){
    console.log(json)
});


答:
```<code>text = text.replace(/\s+/g,' ').trim();
</code>```

Title: How to remove the white space before a word in a sentance in JS

Body: text = text.replace(/\s+/g,' ').trim();


问:
java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.chrome.driver system property
Here is my code:

```<code>package Basics;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class invokegoogle {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

    System.setProperty("Webdriver.chrome.driver", "C:\\Users\\sravani\\Desktop.exe");
    WebDriver driver=new ChromeDriver();
    driver.get("http://qaclickacademy.com");

    }

}
</code>```

Getting the following errors:

```<code>Exception in thread "main" java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.chrome.driver system property; for more information, see https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver. The latest version can be downloaded from http://chromedriver.storage.googleapis.com/index.html
    at com.google.common.base.Preconditions.checkState(Preconditions.java:754)
    at org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:124)
    at org.openqa.selenium.chrome.ChromeDriverService.access$000(ChromeDriverService.java:32)
    at org.openqa.selenium.chrome.ChromeDriverService$Builder.findDefaultExecutable(ChromeDriverService.java:137)
    at org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:329)
    at org.openqa.selenium.chrome.ChromeDriverService.createDefaultService(ChromeDriverService.java:88)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:124)
    at Basics.invokegoogle.main(invokegoogle.java:12)
</code>```

Any help is highly appreciated. Thanks in advance

答:
Once you download chrome driver into your system, after extracting it (unzipping it) into the folder, it looks like you have directly copied the folder path "Downloads/chromedriver_win32.exe", instead using full path as below mentioned

Open the folder (chromedriver_win32.exe), then you will see "chromedriver.exe" as .exe file, and use this path instead and it looks like this

```<code>System.setProperty("webdriver.chrome.driver", C:\Downloads\chromedriver_win32\chromedriver.exe");
</code>```

This will work

Body:
Here is my code:

package Basics;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class invokegoogle {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

    System.setProperty("Webdriver.chrome.driver", "C:\\Users\\sravani\\Desktop.exe");
    WebDriver driver=new ChromeDriver();
    driver.get("http://qaclickacademy.com");

    }

}

Getting the following errors:

Exception in thread "main" java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.chrome.driver system property; for more information, see https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver. The latest version can be downloaded from http://chromedriver.storage.googleapis.com/index.html
    at com.google.common.base.Preconditions.checkState(Preconditions.java:754)
    at org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:124)
    at org.openqa.selenium.chrome.ChromeDriverService.access$000(ChromeDriverService.java:32)
    at org.openqa.selenium.chrome.ChromeDriverService$Builder.findDefaultExecutable(ChromeDriverService.java:137)
    at org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:329)
    at org.openqa.selenium.chrome.ChromeDriverService.createDefaultService(ChromeDriverService.java:88)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:124)
    at Basics.invokegoogle.main(invokegoogle.java:12)

Any help is highly appreciated. Thanks in advance

Body:
Once you download chrome driver into your system, after extracting it (unzipping it) into the folder, it looks like you have directly copied the folder path "Downloads/chromedriver_win32.exe", instead using full path as below mentioned

Open the folder (chromedriver_win32.exe), then you will see "chromedriver.exe" as .exe file, and use this path instead and it looks like this

System.setProperty("webdriver.chrome.driver", C:\Downloads\chromedriver_win32\chromedriver.exe");

This will work


问:
Get output column for each Key
I have a database with roughly this fields:

```<code>SELECT [UserId]
  ,[MissionId]
  ,[LevelId]
  ,[Key]
  ,[BooleanAnswer]
  ,[CreationDateTimeUtc]
  ,[QuestionId]
  FROM [Bakman].[dbo].[LevelEntries]
  WHERE LevelId = 2 AND QuestionId = 1 OR QuestionId = 2 OR QuestionId = 3 OR QuestionId = 4 OR QuestionId = 5 OR QuestionId = 6
</code>```

Now I get this kind of output:

```<code>UserId  MissionId   LevelId Key BooleanAnswer   CreationDateTimeUtc QuestionId
0      1            2       1   1               2017-10-07 11:39:26.350 1
0      1            2       2   1               2017-10-07 11:39:26.350 1
0      1            2       3   0               2017-10-07 11:39:26.350 1
0      1            2       4   1               2017-10-07 11:39:26.350 1
0      1            2       5   0               2017-10-07 11:39:26.350 1
0      1            2       6   1               2017-10-07 11:39:26.350 1
</code>```

But now I want to get a column for each QuestionId (which are equal to the [key]).

Like this :

```<code>       UserId   MissionId   LevelId Key1  Key2  Key3   Key4   Key5   Key6       CreationDateTimeUtc     QuestionId
      1         2       1     0     1     1     0      1      1      1          2017-10-07 11:39:26.350 1
</code>```

Where Key[key] has the boolean awnser and the key belonging to that element.
Good to know is that the Userid + MissionId + LevelId + Key are the Composite key for this table.

EDIT:

Trying both given answers I now get something like this

```<code>    UserId  MissionId   LevelId Key1    Key2    Key3    Key4    Key5    Key6
   1    1   2   1   NULL    NULL    NULL    NULL    NULL
    1   1   2   NULL    1   NULL    NULL    NULL    NULL
    1   1   2   NULL    NULL    0   NULL    NULL    NULL
    1   1   2   NULL    NULL    NULL    1   NULL    NULL
    1   1   2   NULL    NULL    NULL    NULL    1   NULL
    1   1   2   NULL    NULL    NULL    NULL    NULL    1
</code>```

Now I want to combine those so I get the level result of the user.

答:
You can use PIVOT for that purpose.

```<code>    with Entries as
    (
        select UserId,
            MissionId,
            LevelId,
            'Key' + cast([Key] as varchar) as [Key],
            BooleanAnswer,
            CreationDateTimeUtc,
            QuestionId
        from [Bakman].[dbo].[LevelEntries]
        where LevelId = 2 and QuestionId in (1, 2, 3, 4, 5, 6)
    )

    select UserId,
        MissionId,
        LevelId,
        Key1,
        Key2,
        Key3,
        Key4,
        Key5,
        Key6,
        CreationDateTimeUtc,
        QuestionId
    from Entries t
    pivot
    (
        max(BooleanAnswer)
        for [Key] in (Key1, Key2, Key3, Key4, Key5, Key6)
    ) p;
</code>```

Title: Get output column for each Key

Body:
I have a database with roughly this fields:

SELECT [UserId]
  ,[MissionId]
  ,[LevelId]
  ,[Key]
  ,[BooleanAnswer]
  ,[CreationDateTimeUtc]
  ,[QuestionId]
  FROM [Bakman].[dbo].[LevelEntries]
  WHERE LevelId = 2 AND QuestionId = 1 OR QuestionId = 2 OR QuestionId = 3 OR QuestionId = 4 OR QuestionId = 5 OR QuestionId = 6

Now I get this kind of output:

UserId  MissionId   LevelId Key BooleanAnswer   CreationDateTimeUtc QuestionId
0      1            2       1   1               2017-10-07 11:39:26.350 1
0      1            2       2   1               2017-10-07 11:39:26.350 1
0      1            2       3   0               2017-10-07 11:39:26.350 1
0      1            2       4   1               2017-10-07 11:39:26.350 1
0      1            2       5   0               2017-10-07 11:39:26.350 1
0      1            2       6   1               2017-10-07 11:39:26.350 1

But now I want to get a column for each QuestionId (which are equal to the [key]).

Like this :

       UserId   MissionId   LevelId Key1  Key2  Key3   Key4   Key5   Key6       CreationDateTimeUtc     QuestionId
      1         2       1     0     1     1     0      1      1      1          2017-10-07 11:39:26.350 1

Where Key[key] has the boolean awnser and the key belonging to that element.
Good to know is that the Userid + MissionId + LevelId + Key are the Composite key for this table.

EDIT:

Trying both given answers I now get something like this

    UserId  MissionId   LevelId Key1    Key2    Key3    Key4    Key5    Key6
   1    1   2   1   NULL    NULL    NULL    NULL    NULL
    1   1   2   NULL    1   NULL    NULL    NULL    NULL
    1   1   2   NULL    NULL    0   NULL    NULL    NULL
    1   1   2   NULL    NULL    NULL    1   NULL    NULL
    1   1   2   NULL    NULL    NULL    NULL    1   NULL
    1   1   2   NULL    NULL    NULL    NULL    NULL    1

Now I want to combine those so I get the level result of the user.

Body:
You can use PIVOT for that purpose.

    with Entries as
    (
        select UserId,
            MissionId,
            LevelId,
            'Key' + cast([Key] as varchar) as [Key],
            BooleanAnswer,
            CreationDateTimeUtc,
            QuestionId
        from [Bakman].[dbo].[LevelEntries]
        where LevelId = 2 and QuestionId in (1, 2, 3, 4, 5, 6)
    )

    select UserId,
        MissionId,
        LevelId,
        Key1,
        Key2,
        Key3,
        Key4,
        Key5,
        Key6,
        CreationDateTimeUtc,
        QuestionId
    from Entries t
    pivot
    (
        max(BooleanAnswer)
        for [Key] in (Key1, Key2, Key3, Key4, Key5, Key6)
    ) p;


问:
Typescript generic type T toString
I don't think is possible but it's worth asking.
In a generic method or class, I would like to log the name of the generic T type that has been used, I need it as string.

Imagine a method like this:

```<code>static getTypeName<T>(): string {
    return typeof T; // This is wrong
}
</code>```

I would expect to be able to use it this way:

```<code>let m = getTypeName<Message>(); // Expected string "Message"
let p = getTypeName<Person>();  // Expected string "Person"
</code>```

The above getTypeName is wrong, it won't even build.
typeof would be transpiled in JS and wouldn't produce the desired effect.
I tried various things but with no success.

Is there any way to actually do it?

EDIT: Why this is not a duplicate of: this question

The question and the example code shows how to get back an object and not the name of the type specified.
Also the method is not generic because if you try to pass in a Type that has constructor parameters it will show the error:
"[ts] Argument of type 'typeof MyType' is not assignable to parameter of type 'new () => MyType'."
Moreover, if you use the function within a generic method you cannot use T as parameter, this means that everywhere I would need to get the name from the generic Type, I would need to add the ctor to the parameters.

答:
Using the answer here, I adapted it to better cover my needs, but still, this is not my full answer, because even dough it works, compiles and the tests passes, the following code shows an error in VS and VS Code.

The helper class:

```<code>export class TypeHelper {

    static typeName(ctor: { name:string }) : string {
        return ctor.name;
    }
}
</code>```

The test class (Jasmine spec):

```<code>import { TypeHelper } from './../util/TypeHelper';

class MyClass {
    public MyGenericMethod<T>(): string {
        let iNeedTheTypeNameHere = TypeHelper.typeName(T);
        return `Use the string here somehow: ${iNeedTheTypeNameHere}`;
    }
}
describe("TypeHelper", () => {
    describe("TypeHelper", () => {
        it("typeName, returns the string type name of the Class passed as parameter", () => {
            let t = TypeHelper.typeName(TypeHelper);
            expect(t).toBe("TypeHelper");
            let m = TypeHelper.typeName(MyClass);
            expect(m).toBe("MyClass");
        });

        it("typeName, returns the string type name of a generic type T passed as parameter", () => {
            let myClass = new MyClass();
            let t = myClass.MyGenericMethod<TypeHelper>();
            expect(t).toBe("TypeHelper");
            let m = myClass.MyGenericMethod<MyClass>();
            expect(m).toBe("MyClass");
        });
    });
});
</code>```

The error:
[ts] 'T' only refers to a type, but is being used as a value here.

I'm not a TS expert but I will keep looking into this to try to understand how to solve this issue.

EDIT: Added playground example

Title: Typescript generic type T toString

Body:
I don't think is possible but it's worth asking.
In a generic method or class, I would like to log the name of the generic T type that has been used, I need it as string.

Imagine a method like this:

static getTypeName<T>(): string {
    return typeof T; // This is wrong
}

I would expect to be able to use it this way:

let m = getTypeName<Message>(); // Expected string "Message"
let p = getTypeName<Person>();  // Expected string "Person"

The above getTypeName is wrong, it won't even build.
typeof would be transpiled in JS and wouldn't produce the desired effect.
I tried various things but with no success.

Is there any way to actually do it?

EDIT: Why this is not a duplicate of: this question

The question and the example code shows how to get back an object and not the name of the type specified.
Also the method is not generic because if you try to pass in a Type that has constructor parameters it will show the error:
"[ts] Argument of type 'typeof MyType' is not assignable to parameter of type 'new () => MyType'."
Moreover, if you use the function within a generic method you cannot use T as parameter, this means that everywhere I would need to get the name from the generic Type, I would need to add the ctor to the parameters.

Body:
Using the answer here, I adapted it to better cover my needs, but still, this is not my full answer, because even dough it works, compiles and the tests passes, the following code shows an error in VS and VS Code.

The helper class:

export class TypeHelper {

    static typeName(ctor: { name:string }) : string {
        return ctor.name;
    }
}

The test class (Jasmine spec):

import { TypeHelper } from './../util/TypeHelper';

class MyClass {
    public MyGenericMethod<T>(): string {
        let iNeedTheTypeNameHere = TypeHelper.typeName(T);
        return `Use the string here somehow: ${iNeedTheTypeNameHere}`;
    }
}
describe("TypeHelper", () => {
    describe("TypeHelper", () => {
        it("typeName, returns the string type name of the Class passed as parameter", () => {
            let t = TypeHelper.typeName(TypeHelper);
            expect(t).toBe("TypeHelper");
            let m = TypeHelper.typeName(MyClass);
            expect(m).toBe("MyClass");
        });

        it("typeName, returns the string type name of a generic type T passed as parameter", () => {
            let myClass = new MyClass();
            let t = myClass.MyGenericMethod<TypeHelper>();
            expect(t).toBe("TypeHelper");
            let m = myClass.MyGenericMethod<MyClass>();
            expect(m).toBe("MyClass");
        });
    });
});

The error:
[ts] 'T' only refers to a type, but is being used as a value here.

I'm not a TS expert but I will keep looking into this to try to understand how to solve this issue.

EDIT: Added <a href="http://www.typescriptlang.org/play/index.html#src=class%20MyClassA%20%7B%20%7D%3B%0D%0Aclass%20MyClassB%20%7B%20%7D%3B%0D%0Aclass%20MyClassC%20%7B%20%0D%0A%20%20%20%20public%20static%20aGenericMethod%3CT%3E()%3A%20string%20%7B%0D%0A%20%20%20%20%20%20%20%20let%20typeNameFromClass%20%3D%20typeName(MyClassA)%3B%0D%0A%20%20%20%20%20%20%20%20let%20typeNameFromGenericT%20%3D%20typeName(T)%3B%0D%0A%20%20%20%20%20%20%20%20return%20typeNameFromGenericT%3B%0D%0A%20%20%20%20%7D%0D%0A%7D%3B%0D%0A%20%0D%0Alet%20typeName%20%3D%20(ctor%3A%20%7B%20name%3Astring%20%7D)%20%3A%20string%20%3D%3E%20%7B%0D%0A%20%20%20%20return%20ctor.name%3B%0D%0A%7D%0D%0A%0D%0Alet%20a%20%3D%20typeName(MyClassA)%3B%20%0D%0Aalert(%22MyClassA%20type%20name%20is%3A%20%22%20%2B%20a)%3B%0D%0A%0D%0Alet%20b%20%3D%20typeName(MyClassB)%3B%20%0D%0Aalert(%22MyClassB%20type%20name%20is%3A%20%22%20%2B%20b)%3B%0D%0A%0D%0A%2F%2F%20Error%20visible%20from%20dev%20tool%20(f12)%20%22T%20is%20not%20defined%22%22%0D%0Alet%20c%20%3D%20MyClassC.aGenericMethod%3CMyClassA%3E()%3B%0D%0Aalert(%22From%20Generic%20method%20MyClass1%20type%20name%20is%3A%20%22%20%2B%20c)%3B" rel="nofollow noreferrer">playground example


问:
How to trace and profile all low level calls (c libraries) being used by a mod_perl or a mod_php application?
I've seen once on a site, a call graph digging into the most low level libraries of a web request initiated by a PHP appplication with call timings and summary. Seems to me that this is a great way to spot the reason of bottlenecks that aren't obvious while profiling PHP-only code.

Something like strace does but with far more detail.

答: Tools like VTune helps here. You can point this tool at a process or a system to profile and it will help find performance hotspots. VTune also has a call graph mode.</p>

OwnerDisplayName: UnbiasedEntropy

OwnerDisplayName: Stephen Doyle


问:
Getting file name out of a string
I need to get the filename 'HomeModel' out of a string app\model\common\HomeModel. This is what I tried

First, replace '\' with '/' using the str_replace.

```<code>$model = 'app\model\common\HomeModel';
$file = str_replace("\\", '/', $model) . ".php";
echo $file;
</code>```

the result

```<code>app/model/common/HomeModel.php
</code>```

then I explode the result like so

```<code>$model = 'app\model\common\HomeModel';
$file = str_replace("\\", '/', $model) . ".php";
echo $file;

$result = explode("/", $file);
echo '<br>';
var_dump($result);
</code>```

and then this is what I have

```<code>array (size=4)
  0 => string 'app' (length=3)
  1 => string 'model' (length=5)
  2 => string 'common' (length=6)
  3 => string 'HomeModel.php' (length=18)
</code>```

Now, how do I get the last value 'HomeModel' out of this array for further use?, I need to assign the value 'HomeModel' to $class.

答:
You can use pathinfo function </p>

```<code>$file = str_replace("\\", '/', $model) . ".php";
echo pathinfo($file)['filename']; // HomeModel
</code>```

Title: Getting file name out of a string

Body:
I need to get the filename 'HomeModel' out of a string app\model\common\HomeModel. This is what I tried

First, replace '\' with '/' using the str_replace.

$model = 'app\model\common\HomeModel';
$file = str_replace("\\", '/', $model) . ".php";
echo $file;

the result

app/model/common/HomeModel.php

then I explode the result like so

$model = 'app\model\common\HomeModel';
$file = str_replace("\\", '/', $model) . ".php";
echo $file;

$result = explode("/", $file);
echo '
';
var_dump($result);

and then this is what I have

array (size=4)
  0 => string 'app' (length=3)
  1 => string 'model' (length=5)
  2 => string 'common' (length=6)
  3 => string 'HomeModel.php' (length=18)

Now, how do I get the last value 'HomeModel' out of this array for further use?, I need to assign the value 'HomeModel' to $class.

Body:
You can use pathinfo function

$file = str_replace("\\", '/', $model) . ".php";
echo pathinfo($file)['filename']; // HomeModel


问:
Mass Delete All Files starting with “DirsToDelete” using python
I have a directory called Somedir.
I then add 5 files called DirsToDelete 1, DirsToDelete 1 – Copy, DirsToDelete (2)..etc,,,
They are all identically named except for digits at end or - Copy

I want to delete files with "DirsToDelete"

I have tried the following-

```<code>D1 ='DirsToDelete'
for filename in glob.glob("C:/Somedir"):
    os.remove(D1)

PermissionError: [WinError 5] Access is denied: 'C:/Somedir'
</code>```

I have also tried running Cmd commands from python including –

```<code>FOR /D /R %%X IN (C:\Somedir\DirsToDelete) DO RD /S /Q "%%X"
</code>```

This works overkill deleting crucial files.

```<code>FOR /D /R %%X IN (C:\Somedir\DirsToDelete) DO RD /S /Q "%%X"
</code>```

The works but deletes crucial files.

Maybe

```<code>del /s C:\*’DirsToDelete’
</code>```

答:
This is how it should be done:

```<code>import glob
path = "/home/mydir/Somedir*"
for filename in glob.glob(path):
    os.remove(filename)
</code>```

Though as per the permission issues. Run the script as the administrator if you dont have rights to delete. However make sure what you really want to delete since C drive has critical files.

Body:
I have a directory called Somedir.
I then add 5 files called DirsToDelete 1, DirsToDelete 1 – Copy, DirsToDelete (2)..etc,,,
They are all identically named except for digits at end or - Copy

I want to delete files with "DirsToDelete"

I have tried the following-

D1 ='DirsToDelete'
for filename in glob.glob("C:/Somedir"):
    os.remove(D1)

PermissionError: [WinError 5] Access is denied: 'C:/Somedir'

I have also tried running Cmd commands from python including –

FOR /D /R %%X IN (C:\Somedir\DirsToDelete) DO RD /S /Q "%%X"

This works overkill deleting crucial files.

FOR /D /R %%X IN (C:\Somedir\DirsToDelete) DO RD /S /Q "%%X"

The works but deletes crucial files.

Maybe

del /s C:\*’DirsToDelete’

Body:
This is how it should be done:

import glob
path = "/home/mydir/Somedir*"
for filename in glob.glob(path):
    os.remove(filename)

Though as per the permission issues. Run the script as the administrator if you dont have rights to delete. However make sure what you really want to delete since C drive has critical files.


问:
Getting weights of features using scikit-learn Logistic Regression
I am a little new to this.
I am using a simple Logistic Regression Classifier in python scikit-learn. I have 4 features.
My code is

```<code>X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 0.2, random_state = 42)
classifier = LogisticRegression(random_state = 0, C=100)
classifier.fit(X_train, y_train)
coef = classifier.coef_[0]
print (coef)

[-1.07091645 -0.07848958  0.66913624  0.43500273]
</code>```

I want to know what does the coef array signifies?

can we use these coef * features to rank?

Does this mean that the last two features are most important in classifying results?

答:
I have answered your questions below but based on your questions and the comments, it looks like you're still learning about logistic regressions. I can recommend Advanced Data Analysis (http://www.stat.cmu.edu/~cshalizi/ADAfaEPoV/) which has a great chapter on logistic regressions as well as the Elements of Statistical Learning or Introduction to Statistical Learning textbooks to dive into the topic.

I want to know what does the coef array signifies?

The coefficient array is the list of coefficient values. The values are ordered by the order of columns in your X_train dataset. i.e. -1.07091645 is the coefficient value for the first column in X_train, -0.07848958 is the coefficient value for the second column and so on.

So, the equation from your comment will become:

-1.07091645*f1 + -0.07848958*f2 + 0.66913624*f3 + 0.43500273*f4

can we use these coef * features to rank?

I'm guessing you're trying to rank the importance of features, correct me if I misunderstood your question and I'll edit the post accordingly.

First, it is important to make sure that the variables you are using are comparable. For example, let's suppose that the first two variables in your dataset are age (in years) and income (in dollars).

This means that a one year increase in age will decrease the outcome variable by -1.07091645 and a one dollar increase in income will reduce the outcome by -0.07848958. Now the effect of a one year increase is considerably higher than a one dollar increase, but the unit increase for age (one year) cannot readily be compared to a unit increase for income (one dollar).

So in this case, is age more important than income? It's hard to say.

One common way to get around this is to scale each variable to the same range. This way at least you're comparing similar step-changes. However, this can make interpretation of the coefficient values more difficult since you're not sure what a one-unit change in a scaled variable corresponds to.

Does this mean that the last two features are most important in classifying results?

No. As @Vivek Kumar points in his comment, you should look at the absolute value. So in this case, if you feel the variables are comparable, then in order of importance it's 1, 3, 4, 2.

The logic is that even though the first variable has a negative coefficient, the effect of changing that variable is greater while keeping all other variables constant is greater than the effect of changing one of variables 2, 3 or 4.

Body:
I am a little new to this.
I am using a simple Logistic Regression Classifier in python scikit-learn. I have 4 features.
My code is

X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 0.2, random_state = 42)
classifier = LogisticRegression(random_state = 0, C=100)
classifier.fit(X_train, y_train)
coef = classifier.coef_[0]
print (coef)

[-1.07091645 -0.07848958  0.66913624  0.43500273]

I want to know what does the coef array signifies?

can we use these coef * features to rank?

Does this mean that the last two features are most important in classifying results?