问:
how to delete a substring and get another part from that string
I have some string that have a type like this

```<code>NSString *string1 = @"/Users/mine/Library/Application Support/iPhone Simulator/3.2/Applications/02221798-1B7A-46B4-928F-F5BE37E177B5/Documents/Project/Project 1/Folder 1/2.php";
</code>```

if i just want to get the "02221798-1B7A-46B4-928F-F5BE37E177B5"

i have implement a code like this :

```<code>NSString *subString1;
int count = [string1 length];
NSLog(@"count : %d", count);
subString1 = [string1 substringFromIndex:121];
</code>```

but it left "02221798-1B7A-46B4-928F-F5BE37E177B5/Documents/Project/Project 1/Folder 1/2.php"

how can i do to fix it??

答:
To get the name of your app's parent directory you should try this instead:

```<code>NSString *appUUID = [[[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent] lastPathComponent];
</code>```

This will work both on a device and Simulator.

If you need to get the full path to the Documents folder inside your app sandbox:

```<code>NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
</code>```

If you need to append a path component to a path string:

```<code>NSString *projectPath = [documentsPath stringByAppendingPathComponent: @"Project"];
</code>```

Please, take a look at NSString documentation, section "Tasks", "Working with Paths". It is a must-read.

Body:
I have some string that have a type like this

NSString *string1 = @"/Users/mine/Library/Application Support/iPhone Simulator/3.2/Applications/02221798-1B7A-46B4-928F-F5BE37E177B5/Documents/Project/Project 1/Folder 1/2.php";

if i just want to get the "02221798-1B7A-46B4-928F-F5BE37E177B5"

i have implement a code like this :

NSString *subString1;
int count = [string1 length];
NSLog(@"count : %d", count);
subString1 = [string1 substringFromIndex:121];

but it left "02221798-1B7A-46B4-928F-F5BE37E177B5/Documents/Project/Project 1/Folder 1/2.php"

how can i do to fix it??

Body:
To get the name of your app's parent directory you should try this instead:

NSString *appUUID = [[[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent] lastPathComponent];

This will work both on a device and Simulator.

If you need to get the full path to the Documents folder inside your app sandbox:

NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

If you need to append a path component to a path string:

NSString *projectPath = [documentsPath stringByAppendingPathComponent: @"Project"];

Please, take a look at NSString documentation, section "Tasks", "Working with Paths". It is a must-read.


来源: stackexchange

问:
Syntax for HTTP methods in same def using Swagger
I am new to SwaggerUI. In my python code, I have an API called 'work' which supports POST, PUT and DELETE HTTP methods.

Now I want to create Swagger Documentation for the same. I am using the following code:

```<code>@app.route('/work', methods=['POST', 'PUT', 'DELETE'])
def work():
"""
    Micro Service Based API for work operations
    This API is for work to task matching operations
    ---
    paths:
      /cv:
        put:
          parameters:
            - name: body
              in: body
              required: true
              schema:
                id: data
                properties:
                    _id:
                        type: string
              description: Id
          responses:
                    200:
                        description: Please wait the calculation, you'll receive an email with results
        delete:
          parameters:
            - name: body
              in: body
              required: true
              schema:
                id: data
                properties:
                    _id:
                        type: string
              description: Id
          responses:
                    200:
                        description: Please wait the calculation, you'll receive an email with results
        post:
          responses:
                    200:
                        description: done
"""
</code>```

However, it does not seem to work.

I tried browsing the following Documentation link but not to much help
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#pathsObject

Could you please help me out?

The parameters each of the HTTP methods request is different and I wish to also specify a different description for each method in my HTTP UI.

EDITS

Added this to index.yml file.

```<code>swagger: "2.0"
info:
  description: "This is a sample server Petstore server.  You can find out more about     Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/).      For this sample, you can use the api key `special-key` to test the authorization     filters."
  version: "1.0.0"
  title: "Swagger Petstore"
  schemes:
- "http"
paths:
  /work:
    put:
      tags:
  - "WORK"
  summary: "Update a Work Score"
  description: ""
  consumes:
  - "application/json"
  parameters:
  - in: "body"
    name: "body"
    description: "Work ID whose score needs to be updates"
    required: true
    schema:
      $ref: "#/definitions/Data"
  responses:
    200:
      description: "Invalid input"
  /scoreCompute:
    post:
  tags:
  - "ABCD"
  summary: "Compute ABCD"
  description: ""
  consumes:
  - "application/json"
  parameters:
  - in: "body"
    name: "body"
    description: "Compute ABCD"
    required: true
    schema:
      $ref: "#/definitions/TaskId"
  responses:
    200:
      description: "Invalid input"
definitions:
  Data:
type: object
properties:
  _id:
    type: string
    description: Enter ID
  TaskId:
type: object
properties:
  job_id:
    type: string
    description: Enter ID
</code>```

Made the above changes to python code.

```<code>@app.route('/work', methods=['POST', 'PUT', 'DELETE'])
@swag_from('index.yml')
def work():
</code>```

However http://127.0.0.1:5000/apidocs/#!/default/ shows nothing at all.

答:
If you are using Flasgger (http://github.com/rochacbruno/flasgger)
Sadly it does not support defining different HTTP methods in the same docstring yet,
there is this issue opened.

However, there is a workaround to make it working.

1) Put your YAML in a separate file

2) Load it from Swagger template_file

YAML FILE, saves as test.yaml:

```<code>definitions:
  Data:
    type: object
    properties:
      _id:
        type: string

paths:
  /cv:
    put:
      parameters:
        - name: body
          in: body
          required: true
          schema:
            $ref: '#/definitions/Data'
      responses:
        200:
          description: |
            Please wait the calculation, you'll receive an email with results
    delete:
      parameters:
        - name: body
          in: body
          required: true
          schema:
            $ref: '#/definitions/Data'
      responses:
        200:
          description: |
            Please wait the calculation, you'll receive an email with results
    post:
      responses:
        200:
          description: done
</code>```

and then test.py

```<code>from flask import Flask
from flasgger import Swagger

app = Flask(__name__)
Swagger(app, template_file='test.yaml')

@app.route('/cv', methods=['POST', 'PUT', 'DELETE'])
def cv():
    """
    Micro Service Based API for CV operations
    This API is for job to CVs matching operations
    """

app.run(debug=True)
</code>```

And you get

ContentLicense: CC BY-SA 3.0

Body:
I am new to SwaggerUI. In my python code, I have an API called 'work' which supports POST, PUT and DELETE HTTP methods.

Now I want to create Swagger Documentation for the same. I am using the following code:

@app.route('/work', methods=['POST', 'PUT', 'DELETE'])
def work():
"""
    Micro Service Based API for work operations
    This API is for work to task matching operations
    ---
    paths:
      /cv:
        put:
          parameters:
            - name: body
              in: body
              required: true
              schema:
                id: data
                properties:
                    _id:
                        type: string
              description: Id
          responses:
                    200:
                        description: Please wait the calculation, you'll receive an email with results
        delete:
          parameters:
            - name: body
              in: body
              required: true
              schema:
                id: data
                properties:
                    _id:
                        type: string
              description: Id
          responses:
                    200:
                        description: Please wait the calculation, you'll receive an email with results
        post:
          responses:
                    200:
                        description: done
"""

However, it does not seem to work.

I tried browsing the following Documentation link but not to much help
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#pathsObject

Could you please help me out?

The parameters each of the HTTP methods request is different and I wish to also specify a different description for each method in my HTTP UI.

EDITS

Added this to index.yml file.

swagger: "2.0"
info:
  description: "This is a sample server Petstore server.  You can find out more about     Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/).      For this sample, you can use the api key `special-key` to test the authorization     filters."
  version: "1.0.0"
  title: "Swagger Petstore"
  schemes:
- "http"
paths:
  /work:
    put:
      tags:
  - "WORK"
  summary: "Update a Work Score"
  description: ""
  consumes:
  - "application/json"
  parameters:
  - in: "body"
    name: "body"
    description: "Work ID whose score needs to be updates"
    required: true
    schema:
      $ref: "#/definitions/Data"
  responses:
    200:
      description: "Invalid input"
  /scoreCompute:
    post:
  tags:
  - "ABCD"
  summary: "Compute ABCD"
  description: ""
  consumes:
  - "application/json"
  parameters:
  - in: "body"
    name: "body"
    description: "Compute ABCD"
    required: true
    schema:
      $ref: "#/definitions/TaskId"
  responses:
    200:
      description: "Invalid input"
definitions:
  Data:
type: object
properties:
  _id:
    type: string
    description: Enter ID
  TaskId:
type: object
properties:
  job_id:
    type: string
    description: Enter ID

Made the above changes to python code.

@app.route('/work', methods=['POST', 'PUT', 'DELETE'])
@swag_from('index.yml')
def work():

However http://127.0.0.1:5000/apidocs/#!/default/ shows nothing at all.

Body:
If you are using Flasgger (http://github.com/rochacbruno/flasgger)
Sadly it does not support defining different HTTP methods in the same docstring yet,
there is this issue opened.

However, there is a workaround to make it working.

1) Put your YAML in a separate file

2) Load it from Swagger template_file

YAML FILE, saves as test.yaml:

definitions:
  Data:
    type: object
    properties:
      _id:
        type: string

paths:
  /cv:
    put:
      parameters:
        - name: body
          in: body
          required: true
          schema:
            $ref: '#/definitions/Data'
      responses:
        200:
          description: |
            Please wait the calculation, you'll receive an email with results
    delete:
      parameters:
        - name: body
          in: body
          required: true
          schema:
            $ref: '#/definitions/Data'
      responses:
        200:
          description: |
            Please wait the calculation, you'll receive an email with results
    post:
      responses:
        200:
          description: done

and then test.py

from flask import Flask
from flasgger import Swagger

app = Flask(__name__)
Swagger(app, template_file='test.yaml')

@app.route('/cv', methods=['POST', 'PUT', 'DELETE'])
def cv():
    """
    Micro Service Based API for CV operations
    This API is for job to CVs matching operations
    """

app.run(debug=True)

And you get


问:
Angular2 - Add item with click event
I know it's been asked before but the best answer i found is for 9 month ago : here and doesn't work with new angular

I want to push an
 or any other item to my HTML with simple click in angular2.

How should i do it?

i want to re-create this plunker in new angular

答:
try this  :

import { Component } from '@angular/core';

class ContactInfo {
  constructor(public description: string) {}
}

@Component({
  selector: 'my-app',
  template: `

      ```{{ info.description }}```

  <input #newInfo (keyup.enter)="addInfo(newInfo.value)" (onclick)="addInfo(newInfo.value); newInfo.value='' ">

  <button (click)="addInfo(newInfo.value)">Add</button>
  `
})
export class AppComponent {
  information = [];

  myInfo = this.information[0];

  addInfo(newInfo: string) {
    if (newInfo) {
      this.information.push(new ContactInfo(newInfo));
    }
  }

}```

Title: Angular2 - Add item with click event

Body:
try this  :

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
import { Component } from '@angular/core';

class ContactInfo {
  constructor(public description: string) {}
}

@Component({
  selector: 'my-app',
  template: `
  <ul>
    <li *ngFor="let info of information">
      <pre>{{ info.description }}</pre>
    </li>
  </ul>

  <input #newInfo (keyup.enter)="addInfo(newInfo.value)" (onclick)="addInfo(newInfo.value); newInfo.value='' ">

  <button (click)="addInfo(newInfo.value)">Add</button>
  `
})
export class AppComponent {
  information = [];

  myInfo = this.information[0];

  addInfo(newInfo: string) {
    if (newInfo) {
      this.information.push(new ContactInfo(newInfo));
    }
  }

}


问:
Closing a task and checking if its not running before starting a new one
I have an application, when a button is clicked, it starts a task which connects to a specific bluetooth device and then have a continuous stream of data coming in and going out. When the user clicks on the button again, I'd like it to check, if the task I created the first time is running, and if it is, terminate the task.
I was thinking of cancelling the task with CancellationToken, but I can't get passed of checking if the task is running or not. Right now, when I click the button the first time, it creates the task and does everything nicely. When I click the button the second time, it still goes past the if statement, thinking the task isn't running and tries to create the task again and connect the bluetooth device again the then gets stuck.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using InTheHand;
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Ports;
using InTheHand.Net.Sockets;
using System.IO;
using System.Threading;

namespace app
{
class Bluetooth
{
    Guid mUUID = new Guid("00001101-0000-1000-8000-00805F9B34FB");
    public BluetoothClient client;
    BluetoothDeviceInfo[] devices;
    private Task connectionTask;

    private void Connect() //This is called from button click
    {
        if (connectionTask == null ||
            connectionTask.IsCompleted == false &&
            connectionTask.Status != TaskStatus.Running &&
            connectionTask.Status != TaskStatus.WaitingToRun &&
            connectionTask.Status != TaskStatus.WaitingForActivation)
           {
            connectionTask = Task.Factory.StartNew(ConnectionTask);
           }

        else
        {
            var form1 = new Form1();
            form1.message("Client already connected", 3);
        }
    }

    private void ConnectionTask()
    {
        //Do Bluetooth connection stuff here which, once connected, will stay in an infinite while loop.

    }
 }
}
</code>```

Ive changed the code to the following, but still only get Client connected messagebox. As I understand, because I have Thread.Sleep(100000) the Task should still count as running?

```<code>class Bluetooth
{

    private Task connectionTask;

    public void bluetooth()
    {
        Connect();
    }

    private void Connect()
    {

        if (connectionTask == null ||
        connectionTask.IsCompleted == false &&
        connectionTask.Status != TaskStatus.Running &&
        connectionTask.Status != TaskStatus.WaitingToRun &&
        connectionTask.Status != TaskStatus.WaitingForActivation)
        {
            connectionTask = Task.Factory.StartNew(ConnectionTask);
        }

        else
        {
            var form1 = new Form1();
            form1.message("Client already connected", 3);
        }
    }

    private void ConnectionTask()
    {

        var form1 = new Form1();
        form1.message("Client connected", 1);
        Thread.Sleep(100000);

    }
}
}
</code>```

答: The problem is, that you create a new Task (and overwrite the instance variable) before checking if the task finished. Just remove the line connectionTask = new Task(ConnectionTask); and additionally check for connectionTask == null  should solve it.

Body:
I have an application, when a button is clicked, it starts a task which connects to a specific bluetooth device and then have a continuous stream of data coming in and going out. When the user clicks on the button again, I'd like it to check, if the task I created the first time is running, and if it is, terminate the task.
I was thinking of cancelling the task with CancellationToken, but I can't get passed of checking if the task is running or not. Right now, when I click the button the first time, it creates the task and does everything nicely. When I click the button the second time, it still goes past the if statement, thinking the task isn't running and tries to create the task again and connect the bluetooth device again the then gets stuck.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using InTheHand;
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Ports;
using InTheHand.Net.Sockets;
using System.IO;
using System.Threading;

namespace app
{
class Bluetooth
{
    Guid mUUID = new Guid("00001101-0000-1000-8000-00805F9B34FB");
    public BluetoothClient client;
    BluetoothDeviceInfo[] devices;
    private Task connectionTask;

    private void Connect() //This is called from button click
    {
        if (connectionTask == null ||
            connectionTask.IsCompleted == false &&
            connectionTask.Status != TaskStatus.Running &&
            connectionTask.Status != TaskStatus.WaitingToRun &&
            connectionTask.Status != TaskStatus.WaitingForActivation)
           {
            connectionTask = Task.Factory.StartNew(ConnectionTask);
           }

        else
        {
            var form1 = new Form1();
            form1.message("Client already connected", 3);
        }
    }

    private void ConnectionTask()
    {
        //Do Bluetooth connection stuff here which, once connected, will stay in an infinite while loop.

    }
 }
}

Ive changed the code to the following, but still only get Client connected messagebox. As I understand, because I have Thread.Sleep(100000) the Task should still count as running?

class Bluetooth
{

    private Task connectionTask;

    public void bluetooth()
    {
        Connect();
    }

    private void Connect()
    {

        if (connectionTask == null ||
        connectionTask.IsCompleted == false &&
        connectionTask.Status != TaskStatus.Running &&
        connectionTask.Status != TaskStatus.WaitingToRun &&
        connectionTask.Status != TaskStatus.WaitingForActivation)
        {
            connectionTask = Task.Factory.StartNew(ConnectionTask);
        }

        else
        {
            var form1 = new Form1();
            form1.message("Client already connected", 3);
        }
    }

    private void ConnectionTask()
    {

        var form1 = new Form1();
        form1.message("Client connected", 1);
        Thread.Sleep(100000);

    }
}
}


问:
Google Awareness Location Fence is not working
I tried using Google Awareness API for Location Fence:
https://medium.com/exploring-android/exploring-the-new-google-awareness-api-bf45f8060bba

But it's not working all times, is there any special trick?

答:
please refer this blog.
its working fine.
https://inthecheesefactory.com/blog/google-awareness-api-in-action/en</p>


问:
Getting the IP Address Of A client For a webservice
I am using JAX-WS and I am having trouble retrieving the client information that is consuming a webservice. I've found out how to do it with JAX-RPC, and Apache Tomcat Axis, but not with JAX-WS. Does anyone have an idea about this?</p>

答:
Or this:</p>

```
@Path("terminal")
public class terminal {
    @Context private javax.servlet.http.HttpServletRequest hsr;
    @GET
    @Path("get_ip")
    @Produces("text/plain")
    public String get_ip()
    {
            return ip = hsr.getRemoteAddr();
    }
}
```

ContentLicense: CC BY-SA 4.0

Body:
Or this:

@Path("terminal")
public class terminal {
    @Context private javax.servlet.http.HttpServletRequest hsr;
    @GET
    @Path("get_ip")
    @Produces("text/plain")
    public String get_ip()
    {
            return ip = hsr.getRemoteAddr();
    }
}


问:
How to return column names by passing table name using Entity Framework in MVC
What i have tried so far,
Passed  "tablename" as a dynamic string in the below coding.</p>

```<code>public List GetColumnNames(string tablename)
{
    using (var Context = new MCPEntities())
    {
        var names = typeof(AdministratorInformation).GetProperties().Select(property => property.Name).ToArray();
        return names.ToList();
    }
}
</code>```

答:
This should work. I haven't tested it though.
Create a method that returns a list of properties of a specific type. If you are using MVC then this can be a controller action.

```<code>public ActionResult ColumnNames(string tableName)
    {
        var columns = Type.GetType("MyNamespace." + tableName).GetProperties().Select(p => p.Name).ToList();
        return Json(columns, JsonRequestBehavior.AllowGet);
    }
</code>```

Bind the result to a dropdown.

Body:
What i have tried so far,
Passed  "tablename" as a dynamic string in the below coding.

public List GetColumnNames(string tablename)
{
    using (var Context = new MCPEntities())
    {
        var names = typeof(AdministratorInformation).GetProperties().Select(property => property.Name).ToArray();
        return names.ToList();
    }
}

Body:
This should work. I haven't tested it though.
Create a method that returns a list of properties of a specific type. If you are using MVC then this can be a controller action.

public ActionResult ColumnNames(string tableName)
    {
        var columns = Type.GetType("MyNamespace." + tableName).GetProperties().Select(p => p.Name).ToList();
        return Json(columns, JsonRequestBehavior.AllowGet);
    }

Bind the result to a dropdown.


问:
How to replace all \ char into ' in javascript
if, a = "Bob\'s house"

how would you replace the backslash with another '?
I want a to equal "Bob''s house"

I would assume that I can do a.replace("\", "'") but this doesn't work

答: as  user2182349 said, a.repalce("\\", "'") did the trick


问:
Read Hibernate entity identity value
Does Hibernate have an API for reading the value of an entity's identity field? In my case, this would be the Serializable value returned by the field annotated with @Id. For example, suppose I had a Person entity:

```<code>class Person {
    @Id private long id;
    // ... other fields, getters/setters, etc ...
}

Person p = new Person();
p.setId(42L);

Hibernate.unknownFunction(p); // returns 42L
</code>```

Sure I could read the annotations to find the @Id field myself, but this seems like something that might be built in.

答:
session.getIdentifier(object)

Return the identifier value of the given entity as associated with this session. An exception is thrown if the given entity instance is transient or detached in relation to this session.

The object needs to have an ID, and to be associated with the current session, otherwise an exception is thrown. But that is logical, I think.

ContentLicense: CC BY-SA 2.5

Title: Read Hibernate entity identity value

Body:
Does Hibernate have an API for reading the value of an entity's identity field? In my case, this would be the Serializable value returned by the field annotated with @Id. For example, suppose I had a Person entity:

class Person {
    @Id private long id;
    // ... other fields, getters/setters, etc ...
}

Person p = new Person();
p.setId(42L);

Hibernate.unknownFunction(p); // returns 42L

Sure I could read the annotations to find the @Id field myself, but this seems like something that might be built in.


问:
Automatically close PuTTY when connection is lost
I have a script in bash, running multiple PuTTY sessions.
For example, I open the connection to run a couple of commands, when it finishes it saves the values, closes the session, opens a new session and runs a couple more.

This script is supposed to run for 60 hours, more or less, so i need to have everything automated.

My issue is, when the PuTTY session is open, and connected to the device i need, if at some point the device reboots (don't know why it reboots, it just does), a window in putty appears saying the connection was terminated (obviously). The problem is that the window stays open until I press the "ok" button. So my script just stops there until some manual interaction with the PuTTY session.

Is there a way to automatically terminate the PuTTY session if a disconnection happens?

Thank you for your help, if you need some more information just let me know!
regards

答:
PuTTY is not intended for automation.

Use PLink (PuTTY command-line tool). It's a console application, with the same command line arguments as PuTTY, so the transition should be easy.

Though setting "Close window on exit" to "Always" does work (even if you claim it does not).


问:
Handling Request at serverside with C# web api
I want to handle the requests made from the swift app at C#. Before using C# I was using php on laravel framework. Laravel has type of Request

to demonstrate a short example my methods were like

```<code>function MyFindById(Request &request){
   $name = $request->input('name');
}
</code>```

is there any C# equivalent of this? where I could fetch the keyvalue pair I sent with swift ? and also how do I get the request data? like when it is sent, or device info,header and so on..

I apologize for my poor english by the way

答:
You will want to create a new C# WebAPI project using the Visual Studio template that is included with the web development installation or the .net CLI.

Once you have your project created there will be multiple ways you can access the request data.

Here are a couple ways to fetch the key value pair.

```<code>using System;
using Microsoft.AspNetCore.Mvc;

namespace WebApplication4.Controllers
{
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        [HttpPost]
        public void Post()
        {
            var name = HttpContext.Request.Form["name"].ToString();
        }

        [HttpPost("post-my-request")]
        public void Post([FromBody]MyRequest myRequest)
        {
            var name = myRequest.name;
        }
    }

    public class MyRequest
    {
        public string name { get; set; }
    }
}
</code>```

The first will access the form encoded field "name" at /api/values.

The second approach leverages the WebAPI model binder to serialize the request into an object.  I prefer this approach.  This will access the data at /api/values/post-my-request

Body:
I want to handle the requests made from the swift app at C#. Before using C# I was using php on laravel framework. Laravel has type of Request

to demonstrate a short example my methods were like

function MyFindById(Request &request){
   $name = $request->input('name');
}

is there any C# equivalent of this? where I could fetch the keyvalue pair I sent with swift ? and also how do I get the request data? like when it is sent, or device info,header and so on..

I apologize for my poor english by the way

Body:
You will want to create a new C# WebAPI project using the Visual Studio template that is included with the web development installation or the .net CLI.

Once you have your project created there will be multiple ways you can access the request data.

Here are a couple ways to fetch the key value pair.

using System;
using Microsoft.AspNetCore.Mvc;

namespace WebApplication4.Controllers
{
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        [HttpPost]
        public void Post()
        {
            var name = HttpContext.Request.Form["name"].ToString();
        }

        [HttpPost("post-my-request")]
        public void Post([FromBody]MyRequest myRequest)
        {
            var name = myRequest.name;
        }
    }

    public class MyRequest
    {
        public string name { get; set; }
    }
}

The first will access the form encoded field "name" at /api/values.

The second approach leverages the WebAPI model binder to serialize the request into an object.  I prefer this approach.  This will access the data at /api/values/post-my-request


问:
update Migration Command Fails for ConfigurationDbContext and PersistentGrantDbContext
I have  been trying to get IdentityServer4 version 1.5.2 to work for a few days now without success. I am using VS2017
My Entity classes,DataContexts, repositories and migrations are resident in a .Net Standard Library (1.6). So far so good except when I run update-migration command for "PersistenGrantDbContext" and "ConfigurationDbCOntext". I get the error message

```<code>Could not load file or assembly 'System.Data.SqlClient, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified.
</code>```

The datacontext classes that i created myself dont seem to have this problem after implementing "IDbContextFactory" interface
Here I have the implementation for the two culprits

```<code>public class TemporaryDbContextFactoryScopes : IDbContextFactory<PersistedGrantDbContext>
{
    public PersistedGrantDbContext Create(DbContextFactoryOptions options)
    {
        var builder = new DbContextOptionsBuilder<PersistedGrantDbContext>();
        builder.UseSqlServer("Server=-------;Database=-----------;Trusted_Connection=True;MultipleActiveResultSets=true",
            optionsBuilder => optionsBuilder.MigrationsAssembly(typeof(UserDbContext).GetTypeInfo().Assembly.GetName().Name));
        return new PersistedGrantDbContext(builder.Options, new OperationalStoreOptions());
    }
}

public class TemporaryDbContextFactoryOperational : IDbContextFactory<ConfigurationDbContext>
{
    public ConfigurationDbContext Create(DbContextFactoryOptions options)
    {
        var builder = new DbContextOptionsBuilder<ConfigurationDbContext>();
        builder.UseSqlServer("Server=---------;Database=--------;Trusted_Connection=True;MultipleActiveResultSets=true",
            optionsBuilder => optionsBuilder.MigrationsAssembly(typeof(UserDbContext).GetTypeInfo().Assembly.GetName().Name));

        return new ConfigurationDbContext(builder.Options, new ConfigurationStoreOptions());
    }
}
</code>```

I have installed the latest version of System.Data.SqlClient still not working

答:
I was also in a similar situation few weeks ago and here's how I solved it.

Very similar to yours, I have two projects called Company.Identity (.NETCoreApp) as my Identity Project and Company.Identity.Data (.NETStandard 1.6) for migrations. I Use Company.Identity Project  as the startup project for migration purposes as it is in the same solution as my data project and I didn't want to clutter the solution with yet another project just as a startup project for migrations.

I followed the tutorial in here.

The cli tool reference <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.1" /> is in my Company.Identity.csproj file.

I followed all the steps in the above tutorial except for the following difference

In ConfigureServices method in the Company.Identity Startup class, I have set the migrationsAssembly to Company.Identity.Data

```<code>var migrationsAssembly = "Company.Identity.Data";
</code>```

Note that Company.Identity project has already got IdentityServer4.EntityFramework nuget package installed. This enabled me to add the migration for PersistedGrantDbContext. But when I tried to run migration for ConfigurationDbContext it gave me a build error. This was because the migrations generated for PersistedGrantDbContext requried IdentityServer4.EntityFramework nuget package. So I had to install that in the Company.Identity.Data project

I was able to add migrations using the following commands after above changes through command prompt in my Company.Identity project.

```<code>dotnet ef migrations add InitialIdentityServerPersistedGrantDbMigration -c PersistedGrantDbContext -o Migrations/IdentityServer/PersistedGrantDb -p ../Company.Identity.Data

dotnet ef migrations add InitialIdentityServerConfigurationDbMigration -c ConfigurationDbContext -o Migrations/IdentityServer/ConfigurationDb -p ../Company.Identity.Data
</code>```

Hope that helps

Body:
I have  been trying to get IdentityServer4 version 1.5.2 to work for a few days now without success. I am using VS2017
My Entity classes,DataContexts, repositories and migrations are resident in a .Net Standard Library (1.6). So far so good except when I run update-migration command for "PersistenGrantDbContext" and "ConfigurationDbCOntext". I get the error message

Could not load file or assembly 'System.Data.SqlClient, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified.

The datacontext classes that i created myself dont seem to have this problem after implementing "IDbContextFactory" interface
Here I have the implementation for the two culprits

public class TemporaryDbContextFactoryScopes : IDbContextFactory<PersistedGrantDbContext>
{
    public PersistedGrantDbContext Create(DbContextFactoryOptions options)
    {
        var builder = new DbContextOptionsBuilder<PersistedGrantDbContext>();
        builder.UseSqlServer("Server=-------;Database=-----------;Trusted_Connection=True;MultipleActiveResultSets=true",
            optionsBuilder => optionsBuilder.MigrationsAssembly(typeof(UserDbContext).GetTypeInfo().Assembly.GetName().Name));
        return new PersistedGrantDbContext(builder.Options, new OperationalStoreOptions());
    }
}

public class TemporaryDbContextFactoryOperational : IDbContextFactory<ConfigurationDbContext>
{
    public ConfigurationDbContext Create(DbContextFactoryOptions options)
    {
        var builder = new DbContextOptionsBuilder<ConfigurationDbContext>();
        builder.UseSqlServer("Server=---------;Database=--------;Trusted_Connection=True;MultipleActiveResultSets=true",
            optionsBuilder => optionsBuilder.MigrationsAssembly(typeof(UserDbContext).GetTypeInfo().Assembly.GetName().Name));

        return new ConfigurationDbContext(builder.Options, new ConfigurationStoreOptions());
    }
}

I have installed the latest version of System.Data.SqlClient still not working

Body:
I was also in a similar situation few weeks ago and here's how I solved it.

Very similar to yours, I have two projects called Company.Identity (.NETCoreApp) as my Identity Project and Company.Identity.Data (.NETStandard 1.6) for migrations. I Use Company.Identity Project  as the startup project for migration purposes as it is in the same solution as my data project and I didn't want to clutter the solution with yet another project just as a startup project for migrations.

I followed the tutorial in here.

The cli tool reference <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.1" /> is in my Company.Identity.csproj file.

I followed all the steps in the above tutorial except for the following difference

In ConfigureServices method in the Company.Identity Startup class, I have set the migrationsAssembly to Company.Identity.Data

var migrationsAssembly = "Company.Identity.Data";

Note that Company.Identity project has already got IdentityServer4.EntityFramework nuget package installed. This enabled me to add the migration for PersistedGrantDbContext. But when I tried to run migration for ConfigurationDbContext it gave me a build error. This was because the migrations generated for PersistedGrantDbContext requried IdentityServer4.EntityFramework nuget package. So I had to install that in the Company.Identity.Data project

I was able to add migrations using the following commands after above changes through command prompt in my Company.Identity project.

dotnet ef migrations add InitialIdentityServerPersistedGrantDbMigration -c PersistedGrantDbContext -o Migrations/IdentityServer/PersistedGrantDb -p ../Company.Identity.Data

dotnet ef migrations add InitialIdentityServerConfigurationDbMigration -c ConfigurationDbContext -o Migrations/IdentityServer/ConfigurationDb -p ../Company.Identity.Data

Hope that helps


问:
Errors in OpenCL kernel code at runtime
I am new to Visual Studio and I am using it to write a simple parallel sorting program using OpenCL.
When I run it, I get a line before my output (i.e. from before I receive and print the result buffer) saying "5 Errors Generated.".
I assume this is telling me that I have errors in my kernel file, and if I deliberately write errors in my kernel file that number increases.

I would really like to know what those errors are so I can correct my program. Being unfamiliar with VS I simply cannot find them listed anywhere.
Does anyone know where I can find what errors are being generated.
Thanks

答:
You need to call clGetProgramBuidlInfo asking for the CL_PROGRAM_BUILD_LOG in order to get the runtime errors of the compiler.</p>

```<code>char result[4096];
size_t size;
clGetProgramBuildInfo( program, device, CL_PROGRAM_BUILD_LOG, sizeof(result), result, &size);
printf("%s\n", result);
</code>```

Title: Errors in OpenCL kernel code at runtime

Body:
You need to call clGetProgramBuidlInfo asking for the CL_PROGRAM_BUILD_LOG in order to get the runtime errors of the compiler.

char result[4096];
size_t size;
clGetProgramBuildInfo( program, device, CL_PROGRAM_BUILD_LOG, sizeof(result), result, &size);
printf("%s\n", result);


问:
Functions with returns 'table' has no begin...end?
If I ever add 'Begin' after 'As' It says incorrect syntax. It works just fine If I'm trying to return one value though.

Instead I should add 'return' after 'as' and open brackets ()

Why is that?

With one value as returns, I can do it fine:

```<code> CREATE FUNCTION MATHEE(@A int,@B int)
 returns int
 as
 begin
    DECLARE @C int

    SET @C = @A + @B

 return @C
 end
</code>```

With table as returns, I cant:

```<code>   CREATE FUNCTION TOP_USERSs(@number int,@bob varchar(20))
RETURNS TABLE
AS
BEGIN

RETURN SELECT agent from Agents where agent = @bob and prime > @number
END
</code>```

It says :

Incorrect syntax near 'BEGIN'.

It works fine using brackets and without begin..end though:

```<code>CREATE FUNCTION TOP_USERSs(@number int,@bob varchar(20))
RETURNS TABLE
AS
RETURN
(
 SELECT agent from Agents where agent = @bob and prime > @number
)
</code>```

答:
Per the documentation, there are two kinds of table-valued function, with different syntaxes:

```<code>-- Transact-SQL Inline Table-Valued Function Syntax
CREATE [ OR ALTER ] FUNCTION [ schema_name. ] function_name
( [ { @parameter_name [ AS ] [ type_schema_name. ] parameter_data_type
    [ = default ] [ READONLY ] }
    [ ,...n ]
  ]
)
RETURNS TABLE
    [ WITH <function_option> [ ,...n ] ]
    [ AS ]
    RETURN [ ( ] select_stmt [ ) ]
[ ; ]
</code>```

This is an inline TVF. As the syntax shows, it can include solely a RETURN followed by a SELECT. Nothing more, nothing less.

```<code>-- Transact-SQL Multi-Statement Table-Valued Function Syntax
CREATE [ OR ALTER ] FUNCTION [ schema_name. ] function_name
( [ { @parameter_name [ AS ] [ type_schema_name. ] parameter_data_type
    [ = default ] [READONLY] }
    [ ,...n ]
  ]
)
RETURNS @return_variable TABLE <table_type_definition>
    [ WITH <function_option> [ ,...n ] ]
    [ AS ]
    BEGIN
        function_body
        RETURN
    END
[ ; ]
</code>```

This is a multi-statement TVF. As the name suggests, you can include multiple statements in the definition. But note that you must specify the schema of the returned table as part of the function definitions.

Body:
If I ever add 'Begin' after 'As' It says incorrect syntax. It works just fine If I'm trying to return one value though.

Instead I should add 'return' after 'as' and open brackets ()

Why is that?

With one value as returns, I can do it fine:

 CREATE FUNCTION MATHEE(@A int,@B int)
 returns int
 as
 begin
    DECLARE @C int

    SET @C = @A + @B

 return @C
 end

With table as returns, I cant:

   CREATE FUNCTION TOP_USERSs(@number int,@bob varchar(20))
RETURNS TABLE
AS
BEGIN

RETURN SELECT agent from Agents where agent = @bob and prime > @number
END

It says :

Incorrect syntax near 'BEGIN'.

It works fine using brackets and without begin..end though:

CREATE FUNCTION TOP_USERSs(@number int,@bob varchar(20))
RETURNS TABLE
AS
RETURN
(
 SELECT agent from Agents where agent = @bob and prime > @number
)

Body:
Per the documentation, there are two kinds of table-valued function, with different syntaxes:

-- Transact-SQL Inline Table-Valued Function Syntax
CREATE [ OR ALTER ] FUNCTION [ schema_name. ] function_name
( [ { @parameter_name [ AS ] [ type_schema_name. ] parameter_data_type
    [ = default ] [ READONLY ] }
    [ ,...n ]
  ]
)
RETURNS TABLE
    [ WITH <function_option> [ ,...n ] ]
    [ AS ]
    RETURN [ ( ] select_stmt [ ) ]
[ ; ]

This is an inline TVF. As the syntax shows, it can include solely a RETURN followed by a SELECT. Nothing more, nothing less.

-- Transact-SQL Multi-Statement Table-Valued Function Syntax
CREATE [ OR ALTER ] FUNCTION [ schema_name. ] function_name
( [ { @parameter_name [ AS ] [ type_schema_name. ] parameter_data_type
    [ = default ] [READONLY] }
    [ ,...n ]
  ]
)
RETURNS @return_variable TABLE <table_type_definition>
    [ WITH <function_option> [ ,...n ] ]
    [ AS ]
    BEGIN
        function_body
        RETURN
    END
[ ; ]

This is a multi-statement TVF. As the name suggests, you can include multiple statements in the definition. But note that you must specify the schema of the returned table as part of the function definitions.


问:
Add month/year to each returned row postgres sql
I have a query like this:

```<code>select location,  subItem1, item2, SUM(sub.intervalEnd - sub.intervalStart +1) as days

from (select
    location, item1,item2,
    case when effective_start_date> '2017-05-01' then effective_start_date else '2017-05-01' end as intervalStart,
    case when effective_end_date< '2017-05-31' then effective_end_date else '2017-05-31' end as intervalEnd,
    case when item1 =  'APPLE' then item1 else 'ORANGE' end as subItem1
from myTable

where (effective_start_date<='2017-05-01' and effective_end_date>='2017-05-01')
   OR (effective_start_date<='2017-05-31' and effective_end_date>='2017-05-31')
group by item1, item2, location, effective_start_date, effective_end_date
   )sub
  group by location, subItem1, item2
</code>```

which returns a table like this:

```<code>Location | subItem1 | subItem2 | days
"LOC1","APPLE","thisItem2","31"
"LOC2","APPLE","thisItem2","31"
"LOC3","ORANGE","thisItem2","31"
"LOC4","APPLE","thisItem2","62"
"LOC5","APPLE","thisItem2","31"
"LOC6","APPLE","thisItem2","62"
</code>```

But what I need is to add the Month/Year to each row like this:

```<code>"05/2017","LOC1","APPLE","thisItem2","31"
"05/2017","LOC2","APPLE","thisItem2","31"
"05/2017","LOC3","ORANGE","thisItem2","31"
"05/2017","LOC4","APPLE","thisItem2","62"
"05/2017","LOC5","APPLE","thisItem2","31"
"05/2017","LOC6","APPLE","thisItem2","62"
</code>```

Any ideas?  I looked at the extract function but it only gives me either month or year.  But i need both.

答:
Probably was a very noob question.  But I am only learning sql and managed to figure it out.   Answer was kind of easy really, just wrap it in another select statement.  Dunno if this is the best way to go about it - but it works:</p>

```<code>select location,  subItem1, item2, days, theMonth

from (
select location,  subItem1, item2, SUM(sub.intervalEnd - sub.intervalStart +1) as days

from (select
    location, item1,item2,
    case when effective_start_date> '2017-05-01' then effective_start_date else '2017-05-01' end as intervalStart,
    case when effective_end_date< '2017-05-31' then effective_end_date else '2017-05-31' end as intervalEnd,
    case when item1 =  'APPLE' then item1 else 'ORANGE' end as subItem1
from myTable

where (effective_start_date<='2017-05-01' and effective_end_date>='2017-05-01')
   OR (effective_start_date<='2017-05-31' and effective_end_date>='2017-05-31')
group by item1, item2, location, effective_start_date, effective_end_date
   )sub
  group by location, subItem1, item2

)t

group by location, month, item1, item2
order by location
</code>```

Body:
I have a query like this:

select location,  subItem1, item2, SUM(sub.intervalEnd - sub.intervalStart +1) as days

from (select
    location, item1,item2,
    case when effective_start_date> '2017-05-01' then effective_start_date else '2017-05-01' end as intervalStart,
    case when effective_end_date< '2017-05-31' then effective_end_date else '2017-05-31' end as intervalEnd,
    case when item1 =  'APPLE' then item1 else 'ORANGE' end as subItem1
from myTable

where (effective_start_date<='2017-05-01' and effective_end_date>='2017-05-01')
   OR (effective_start_date<='2017-05-31' and effective_end_date>='2017-05-31')
group by item1, item2, location, effective_start_date, effective_end_date
   )sub
  group by location, subItem1, item2

which returns a table like this:

Location | subItem1 | subItem2 | days
"LOC1","APPLE","thisItem2","31"
"LOC2","APPLE","thisItem2","31"
"LOC3","ORANGE","thisItem2","31"
"LOC4","APPLE","thisItem2","62"
"LOC5","APPLE","thisItem2","31"
"LOC6","APPLE","thisItem2","62"

But what I need is to add the Month/Year to each row like this:

"05/2017","LOC1","APPLE","thisItem2","31"
"05/2017","LOC2","APPLE","thisItem2","31"
"05/2017","LOC3","ORANGE","thisItem2","31"
"05/2017","LOC4","APPLE","thisItem2","62"
"05/2017","LOC5","APPLE","thisItem2","31"
"05/2017","LOC6","APPLE","thisItem2","62"

Any ideas?  I looked at the extract function but it only gives me either month or year.  But i need both.

Body:
Probably was a very noob question.  But I am only learning sql and managed to figure it out.   Answer was kind of easy really, just wrap it in another select statement.  Dunno if this is the best way to go about it - but it works:

select location,  subItem1, item2, days, theMonth

from (
select location,  subItem1, item2, SUM(sub.intervalEnd - sub.intervalStart +1) as days

from (select
    location, item1,item2,
    case when effective_start_date> '2017-05-01' then effective_start_date else '2017-05-01' end as intervalStart,
    case when effective_end_date< '2017-05-31' then effective_end_date else '2017-05-31' end as intervalEnd,
    case when item1 =  'APPLE' then item1 else 'ORANGE' end as subItem1
from myTable

where (effective_start_date<='2017-05-01' and effective_end_date>='2017-05-01')
   OR (effective_start_date<='2017-05-31' and effective_end_date>='2017-05-31')
group by item1, item2, location, effective_start_date, effective_end_date
   )sub
  group by location, subItem1, item2

)t

group by location, month, item1, item2
order by location


问:
Laravel Accessing Foreign Key Using Eloquent Where Clause
I have two models called Item and Sale where

```<code>class Item extends Model
{
    public function sale()
    {
        return $this->hasMany('App\Sale', 'sale_id');
    }
}
</code>```

and

```<code>class Sale extends Model
{
    public function item()
    {
        return $this->belongsTo('App\Sale', 'item_id');
    }
}
</code>```

This is my migration files for Items

```<code>public function up()
    {
        Schema::create('items', function (Blueprint $table) {
            $table->increments('id');
            $table->string('code');
            $table->string('name');
            $table->string('location');
            $table->double('buy_price');
            $table->double('sell_price');
            $table->integer('quantity');
            $table->timestamps();
        });
    }
</code>```

And Sales

```<code>public function up()
    {
        Schema::create('sales', function (Blueprint $table) {
            $table->increments('id');
            $table->date('date');
            $table->integer('quantity');
            $table->double('sell_price');
            $table->double('subtotal');
            $table->integer('item_id')->unsigned();
            $table->timestamps();
        });

        Schema::table('sales', function (Blueprint $table) {
            $table->foreign('item_id')->references('id')->on('items')
                  ->onDelete('cascade')->onUpdate('cascade');
        });
    }
</code>```

I recorded the daily sales data to see what are the items sold that day. Therefore I wanted to view the sales daily. And this is what I have done in my controller.

```<code>class SaleController extends Controller
{
    public function show($date)
    {
        $sales = Sale::where('date', $date)->get();
        return view('sale.detail', compact('sales'));
    }
}
</code>```

And finally in my blade, I did this to call the information of the items

```<code>@foreach($sales as $sale)
    <tr>
        <td>{{ $sale->item->code }}</td>
        <td>{{ $sale->item->name }}</td>
        <td>{{ $sale->sell_price }}</td>
        <td>{{ $sale->quantity }}</td>
    </tr>
@endforeach
</code>```

In the end I got Trying to get property of non-object
Can someone enlighten me what is wrong with my code?
I am relatively new in Laravel but I'm keen on trying different things to see what this framework can do.

Thanks a lot

答:
Since you need to access the item object multiple times, the better way to do it is to eager load it as:

```<code>public function show($date)
{
    $sales = Sale::with('item')->where('date', $date)->get();
    return view('sale.detail', compact('sales'));
}
</code>```

Then you can leave your blade file as it is.

Body:
I have two models called Item and Sale where

class Item extends Model
{
    public function sale()
    {
        return $this->hasMany('App\Sale', 'sale_id');
    }
}

and

class Sale extends Model
{
    public function item()
    {
        return $this->belongsTo('App\Sale', 'item_id');
    }
}

This is my migration files for Items

public function up()
    {
        Schema::create('items', function (Blueprint $table) {
            $table->increments('id');
            $table->string('code');
            $table->string('name');
            $table->string('location');
            $table->double('buy_price');
            $table->double('sell_price');
            $table->integer('quantity');
            $table->timestamps();
        });
    }

And Sales

public function up()
    {
        Schema::create('sales', function (Blueprint $table) {
            $table->increments('id');
            $table->date('date');
            $table->integer('quantity');
            $table->double('sell_price');
            $table->double('subtotal');
            $table->integer('item_id')->unsigned();
            $table->timestamps();
        });

        Schema::table('sales', function (Blueprint $table) {
            $table->foreign('item_id')->references('id')->on('items')
                  ->onDelete('cascade')->onUpdate('cascade');
        });
    }

I recorded the daily sales data to see what are the items sold that day. Therefore I wanted to view the sales daily. And this is what I have done in my controller.

class SaleController extends Controller
{
    public function show($date)
    {
        $sales = Sale::where('date', $date)->get();
        return view('sale.detail', compact('sales'));
    }
}

And finally in my blade, I did this to call the information of the items

@foreach($sales as $sale)

        {{ $sale->item->code }}
        {{ $sale->item->name }}
        {{ $sale->sell_price }}
        {{ $sale->quantity }}

@endforeach

In the end I got Trying to get property of non-object
Can someone enlighten me what is wrong with my code?
I am relatively new in Laravel but I'm keen on trying different things to see what this framework can do.

Thanks a lot

Body:
Since you need to access the item object multiple times, the better way to do it is to eager load it as:

public function show($date)
{
    $sales = Sale::with('item')->where('date', $date)->get();
    return view('sale.detail', compact('sales'));
}

Then you can leave your blade file as it is.


问:
HostListener to analyse combination key press
I am trying to trace when a user presses a Shift+Tab combination key using keyboard, but I am not able to fire that event  </p>

```<code>@HostListener('keyup', ['$event'])
@HostListener('keydown', ['$event'])

onkeyup(event) {
  if (event.keyCode == 16 && event.keyCode == 9) {
    this.isShift = true;
    console.log("On Keyup " + event.keyCode);
  }
}

onkeydown(event) {
  console.log("On KeyDown" + event.keyCode);
}
</code>```

答:
It works when I do this:

```<code>@Directive({
  selector: '[test-directive]'
})
export class TestDirective {
  @HostListener('keydown', ['$event']) onKeyDown(e) {
    if (e.shiftKey && e.keyCode == 9) {
      console.log('shift and tab');
    }
  }
}

<input type="text" test-directive />
</code>```

Note that keyup can be tricky because tab may unfocus the element. So by the time keyup fires, you may be on the next element, so keyup may actually fire on that element. So it depends on what you need. But keydown works for the current element.

Body:
I am trying to trace when a user presses a Shift+Tab combination key using keyboard, but I am not able to fire that event

@HostListener('keyup', ['$event'])
@HostListener('keydown', ['$event'])

onkeyup(event) {
  if (event.keyCode == 16 && event.keyCode == 9) {
    this.isShift = true;
    console.log("On Keyup " + event.keyCode);
  }
}

onkeydown(event) {
  console.log("On KeyDown" + event.keyCode);
}

Body:
It works when I do this:

@Directive({
  selector: '[test-directive]'
})
export class TestDirective {
  @HostListener('keydown', ['$event']) onKeyDown(e) {
    if (e.shiftKey && e.keyCode == 9) {
      console.log('shift and tab');
    }
  }
}

<input type="text" test-directive />

Note that keyup can be tricky because tab may unfocus the element. So by the time keyup fires, you may be on the next element, so keyup may actually fire on that element. So it depends on what you need. But keydown works for the current element.


问:
Define Java POJO so Gson does not write value double quoted
Note is this example javascript

```<code><html>
<head>
<script type="text/javascript">
window.onload = function () {
    var chart = new CanvasJS.Chart("chartContainer",
    {
        title: {
            text: "Using labelFormatter function of axisY"
        },
        axisY:{
            labelFormatter: function(e){
                return  "Y: " + e.value;
            }
        },
        data: [
        {
            type: "spline",
            dataPoints: [
                { y: 5  },
                { y: 9  },
                { y: 17 },
                { y: 32 },
                { y: 22 },
                { y: 14 },
                { y: 25 },
                { y: 18 },
                { y: 20 }
            ]
        }
        ]
    });
    chart.render();
}
</script>
<script type="text/javascript" src="/assets/script/canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>
</code>```

from http://canvasjs.com/docs/charts/chart-options/axisy/label-formatter/ that the value of labelFormatter field is not double quoted, and if I modify it to be double quoted then the code does not work.

I dont understand the Javascript rules for when it shoud/not be double quoted but it seems functions must not be.

I am trying to generate such code from Java using Gson, how do I create my POJO so that its value is not double quoted when output to json. Currently it is just defined as type String and therefore gets double quoted.

e.g

```<code>public class AxisY
{
    private boolean reversed;
    private int     labelMaxWidth;
    private boolean labelWrap;
    private String  title;
    private int     viewportMinimum = 0;
    private int     viewportMaximum;
    private int     interval;
    private String  labelFormatter;

    public boolean isReversed()
    {
        return reversed;
    }

    public void setReversed(boolean reversed)
    {
        this.reversed = reversed;
    }

    public int getLabelMaxWidth()
    {
        return labelMaxWidth;
    }

    public void setLabelMaxWidth(int labelMaxWidth)
    {
        this.labelMaxWidth = labelMaxWidth;
    }

    public boolean isLabelWrap()
    {
        return labelWrap;
    }

    public void setLabelWrap(boolean labelWrap)
    {
        this.labelWrap = labelWrap;
    }

    public String getTitle()
    {
        return title;
    }

    public void setTitle(String title)
    {
        this.title = title;
    }

    public int getViewportMinimum()
    {
        return viewportMinimum;
    }

    public void setViewportMinimum(int viewportMinimum)
    {
        this.viewportMinimum = viewportMinimum;
    }

    public int getViewportMaximum()
    {
        return viewportMaximum;
    }

    public void setViewportMaximum(int viewportMaximum)
    {
        this.viewportMaximum = viewportMaximum;
    }

    public int getInterval()
    {
        return interval;
    }

    public void setInterval(int interval)
    {
        this.interval = interval;
    }

    public String getLabelFormatter()
    {
        return labelFormatter;
    }

    public void setLabelFormatter(String labelFormatter)
    {
        this.labelFormatter = labelFormatter;
    }
}

  <!DOCTYPE HTML>
    <html>
    <head>
    <script type="text/javascript">
    window.onload = function () {
        var chart = new CanvasJS.Chart("chartContainer",
        {
            title: {
                text: "Using labelFormatter function of axisY"
            },
            axisY:{
                labelFormatter: function(e){
                    return  "Y: " + e.value;
                }
            },
            data: [
            {
                type: "spline",
                dataPoints: [
                    { y: 5  },
                    { y: 9  },
                    { y: 17 },
                    { y: 32 },
                    { y: 22 },
                    { y: 14 },
                    { y: 25 },
                    { y: 18 },
                    { y: 20 }
                ]
            }
            ]
        });
        chart.render();
    }
    </script>
    <script type="text/javascript" src="/assets/script/canvasjs.min.js"></script>
    </head>
    <body>
    <div id="chartContainer" style="height: 300px; width: 100%;"></div>
    </body>
    </html>
</code>```

答: Gson is serializing your Java POJO to JSON. JSON does not support function values. Value types supported by JSON are object, array, string, boolean, and number.</p>

Body:
Note is this example javascript

from http://canvasjs.com/docs/charts/chart-options/axisy/label-formatter/ that the value of labelFormatter field is not double quoted, and if I modify it to be double quoted then the code does not work.

I dont understand the Javascript rules for when it shoud/not be double quoted but it seems functions must not be.

I am trying to generate such code from Java using Gson, how do I create my POJO so that its value is not double quoted when output to json. Currently it is just defined as type String and therefore gets double quoted.

e.g

public class AxisY
{
    private boolean reversed;
    private int     labelMaxWidth;
    private boolean labelWrap;
    private String  title;
    private int     viewportMinimum = 0;
    private int     viewportMaximum;
    private int     interval;
    private String  labelFormatter;

    public boolean isReversed()
    {
        return reversed;
    }

    public void setReversed(boolean reversed)
    {
        this.reversed = reversed;
    }

    public int getLabelMaxWidth()
    {
        return labelMaxWidth;
    }

    public void setLabelMaxWidth(int labelMaxWidth)
    {
        this.labelMaxWidth = labelMaxWidth;
    }

    public boolean isLabelWrap()
    {
        return labelWrap;
    }

    public void setLabelWrap(boolean labelWrap)
    {
        this.labelWrap = labelWrap;
    }

    public String getTitle()
    {
        return title;
    }

    public void setTitle(String title)
    {
        this.title = title;
    }

    public int getViewportMinimum()
    {
        return viewportMinimum;
    }

    public void setViewportMinimum(int viewportMinimum)
    {
        this.viewportMinimum = viewportMinimum;
    }

    public int getViewportMaximum()
    {
        return viewportMaximum;
    }

    public void setViewportMaximum(int viewportMaximum)
    {
        this.viewportMaximum = viewportMaximum;
    }

    public int getInterval()
    {
        return interval;
    }

    public void setInterval(int interval)
    {
        this.interval = interval;
    }

    public String getLabelFormatter()
    {
        return labelFormatter;
    }

    public void setLabelFormatter(String labelFormatter)
    {
        this.labelFormatter = labelFormatter;
    }
}

  <!DOCTYPE HTML>


问:
How to put divs on opposite sides of parent div, with parent width relative to them on scaling?
I have a container div (that cannot be floated) with two children elements. I want child elements to be on opposite sides - first on left, second on right. On 100% browser width children summary width is less than container, but on greater scales it is not, so container should be greater too. How to set container to grow when it's gloat child grow?

UPD: something like this
 I need all elements to stay one line in any scale.

```<code> <div id="page">
     <div id="container">
         <div id="left">
           <div>first</div>
           <div>second</div>
           <div>third</div>
         </div>
         <div id="right">
            right
         </div>
      </div>
    </div>
    <style>
    #page {
      background-color: grey;
      width: 100%;
      height: 300px;
    }
    #container {
      /*this styles are needed to other parts*/
      position: relative;
      clear: both;
      /*=====================================*/
      background-color:red;
      height: 50px;
      width: 90%;
      margin: 0 5%;
    }
    #left {
        float: left;
        background-color: blue;
    }
    #left div {
      width: 50px;
      display: inline-block;
    }
    #right{
     float: right;
     background-color: green;
     display: block;
     max-width: 200px;
    }
    </style>
</code>```

答:
```<code>.container {
  display: flex;
  justify-content: space-between;
}
</code>```

It should do that.
Google up FlexBox Introduction for good explaination.

Body:
I have a container div (that cannot be floated) with two children elements. I want child elements to be on opposite sides - first on left, second on right. On 100% browser width children summary width is less than container, but on greater scales it is not, so container should be greater too. How to set container to grow when it's gloat child grow?

UPD: something like this
 I need all elements to stay one line in any scale.

first

second

third

            right

Body:
.container {
  display: flex;
  justify-content: space-between;
}

It should do that.
Google up FlexBox Introduction for good explaination.


问:
Head First C string.h related questions
```<code>#include <stdio.h>
#include <string.h>

void print_reverse(char *s)
{
    size_t len = strlen(s);
    char *t = s + len - 1;
    while (t >= s)
    {
        printf("%c", *t);
        t = t - 1;
    }
    puts("");
}
</code>```

Above is a function that will display a string backward on the screen. But I don't understand the 7th line (char *t = s+ len-1;). Could anybody explain this is spoken English please?

答:
For starters this function

```<code>void print_reverse(char *s)
{
    size_t len = strlen(s);
    char *t = s + len - 1;
    while (t >= s)
    {
        printf("%c", *t);
        t = t - 1;
    }
    puts("");
}
</code>```

is wrong and has undefined behavior.:)

There are two problems.

The first one is that the passed string as the argument can have a zero-length. In this case this declaration

```<code>char *t = s + len - 1;
</code>```

will look like

```<code>char *t = s - 1;
</code>```

and the pointer t can be wrong.

The second problem is that this expression statement

```<code>t = t - 1;
</code>```

has undefined behavior in case when the pointer t is equal to s.

From the C Standard (6.5.6 Additive operators)

...If both the pointer operand and the result point to elements of the same
  array object, or one past the last element of the array
  object, the evaluation shall not produce an overflow; otherwise, the
  behavior is undefined.

A correct function implementation can look the following way

```<code>void print_reverse( const char *s)
                    ^^^^^
{
    size_t len = strlen(s);
    const char *t = s + len;
                    ^^^^^^^
    while (t != s)
           ^^^^^^
    {
        printf("%c", *--t);
                     ^^^^
    }
    puts("");
}
</code>```

As for your question then in this declaration

```<code>char *t = s + len - 1;
</code>```

the pointer t is tried to be initialized by the address of the last character of the string before the terminating zero.

Title: Head First C string.h related questions

Body:
#include <stdio.h>
#include <string.h>

void print_reverse(char *s)
{
    size_t len = strlen(s);
    char *t = s + len - 1;
    while (t >= s)
    {
        printf("%c", *t);
        t = t - 1;
    }
    puts("");
}

Above is a function that will display a string backward on the screen. But I don't understand the 7th line (char *t = s+ len-1;). Could anybody explain this is spoken English please?

Body:
For starters this function

void print_reverse(char *s)
{
    size_t len = strlen(s);
    char *t = s + len - 1;
    while (t >= s)
    {
        printf("%c", *t);
        t = t - 1;
    }
    puts("");
}

is wrong and has undefined behavior.:)

There are two problems.

The first one is that the passed string as the argument can have a zero-length. In this case this declaration

char *t = s + len - 1;

will look like

char *t = s - 1;

and the pointer t can be wrong.

The second problem is that this expression statement

t = t - 1;

has undefined behavior in case when the pointer t is equal to s.

From the C Standard (6.5.6 Additive operators)

...If both the pointer operand and the result point to elements of the same
  array object, or one past the last element of the array
  object, the evaluation shall not produce an overflow; otherwise, the
  behavior is undefined.

A correct function implementation can look the following way

void print_reverse( const char *s)
                    ^^^^^
{
    size_t len = strlen(s);
    const char *t = s + len;
                    ^^^^^^^
    while (t != s)
           ^^^^^^
    {
        printf("%c", *--t);
                     ^^^^
    }
    puts("");
}

As for your question then in this declaration

char *t = s + len - 1;

the pointer t is tried to be initialized by the address of the last character of the string before the terminating zero.


问:
How to replace any text between html tags
i have text between html tags. For example:

```<code><td>vip</td>
</code>```

I will have any text between tags
How can i cut any text from these tags and put any text between these tags.
I need to do it via bash/shell.
How can i do this ?
First of all, i tried to get this text, but without success
sed -n "//,/<\/td>/p" test.txt. But in a result i have
vip	. but according to documentation, i should get only vip

答:
If you Input_file is same as shown example then following may help you too.

```<code>echo "<td>vip</td>" | awk -F"[><]" '{print $3}'
</code>```

Simply printing the  tag with echo then using awk to create a field separator >< then printing the 3rd field then which is your request.

Body:
i have text between html tags. For example:

vip

I will have any text between tags
How can i cut any text from these tags and put any text between these tags.
I need to do it via bash/shell.
How can i do this ?
First of all, i tried to get this text, but without success
sed -n "//,/<\/td>/p" test.txt. But in a result i have
vip	. but according to documentation, i should get only vip

Body:
If you Input_file is same as shown example then following may help you too.

echo "<td>vip</td>" | awk -F"[><]" '{print $3}'

Simply printing the  tag with echo then using awk to create a field separator >< then printing the 3rd field then which is your request.


问:
Redirect HTTP to HTTPS with Ninja framework on Heroku
How to configure a Ninja web application running on Heroku to force the use of SSL, that is, redirect all requests to HTTPS?</p>

答:
Here is the class to add in the conf package:</p>

```<code>public class Filters implements ApplicationFilters {
  @Override
  public void addFilters (List<Class<? extends Filter>> list) {
    list.add (HttpsFilter.class);
  }
  public static class HttpsFilter implements Filter {
    @Override
    public Result filter (FilterChain filterChain, Context context) {
      if ("http".equals (context.getHeader ("X-Forwarded-Proto"))) {
        return Results.redirect ("https://" + context.getHostname ()
          + context.getRequestPath ());
      }
      return filterChain.next (context);
    }
  }
}
</code>```

Body:
Here is the class to add in the conf package:

public class Filters implements ApplicationFilters {
  @Override
  public void addFilters (List<Class<? extends Filter>> list) {
    list.add (HttpsFilter.class);
  }
  public static class HttpsFilter implements Filter {
    @Override
    public Result filter (FilterChain filterChain, Context context) {
      if ("http".equals (context.getHeader ("X-Forwarded-Proto"))) {
        return Results.redirect ("https://" + context.getHostname ()
          + context.getRequestPath ());
      }
      return filterChain.next (context);
    }
  }
}


问:
Can not match mobile nos using PHP
I am facing one issue .I am trying to match two mobile no using PHP but it is not giving the output as per expected. I am explaining my code below.

```<code><?php
$mobile="09029704634";
$mobj="+919029704634";
if(strpos($mobj,$mobile)){
    $flag=1;
}else{
    $flag=0;
}
echo $flag;
?>
</code>```

See here both mobile are logically same. One has 0 in beginning and another has country code +91 in the beginning. Here I need if both no are logically same it should return 1 otherwise 0.Here any country code can come not only +91 .Please help me.

答:
If the length of mobile number varies across the globe, this might be a good option that can be tried out. Strip all 0s at the beginning.

Usually a 0 is added for national calls, and 00 for international calls. So ltrim any + or 0 at the beginning of the number, and do a strpos()

```<code><?php

$mobile="09029704634";
$mobile= ltrim($mobile,'+');
$mobile = ltrim($mobile, '0');
$mobj="+919029704634";
if(strpos($mobj,$mobile)){
    $flag=1;
}else{
    $flag=0;
}
echo $flag;
?>
</code>```

Looking for feedbacks, if this is inefficient.

ADD: If the both comparing operands interchange in their formats, or isnt predictable, then the only way you have is to get hold of all country codes from a database, compare the operands by stripping country codes or appending them, doing multiple checks to finally deduce if they are same logically or not.

Title: Can not match mobile nos using PHP

Body:
I am facing one issue .I am trying to match two mobile no using PHP but it is not giving the output as per expected. I am explaining my code below.

<?php
$mobile="09029704634";
$mobj="+919029704634";
if(strpos($mobj,$mobile)){
    $flag=1;
}else{
    $flag=0;
}
echo $flag;
?>

See here both mobile are logically same. One has 0 in beginning and another has country code +91 in the beginning. Here I need if both no are logically same it should return 1 otherwise 0.Here any country code can come not only +91 .Please help me.

Body:
If the length of mobile number varies across the globe, this might be a good option that can be tried out. Strip all 0s at the beginning.

Usually a 0 is added for national calls, and 00 for international calls. So ltrim any + or 0 at the beginning of the number, and do a strpos()

<?php

$mobile="09029704634";
$mobile= ltrim($mobile,'+');
$mobile = ltrim($mobile, '0');
$mobj="+919029704634";
if(strpos($mobj,$mobile)){
    $flag=1;
}else{
    $flag=0;
}
echo $flag;
?>

Looking for feedbacks, if this is inefficient.

ADD: If the both comparing operands interchange in their formats, or isnt predictable, then the only way you have is to get hold of all country codes from a database, compare the operands by stripping country codes or appending them, doing multiple checks to finally deduce if they are same logically or not.


问:
Maven not executing the test cases configured under runner class in cucumber
Trying to Achieve:

Run cucumber test cases configured in runner class using Maven.

Issue:

Configured test cases are not being executed using maven.

Configured pom.xml file:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>simplify360Cucumber</groupId>
    <artifactId>s360UIAutomation</artifactId>
    <version>0.0.1</version>
    <packaging>jar</packaging>
    <name>Cucumber-JVM template</name>

    <dependencies>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>1.2.5</version>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-testng</artifactId>
            <version>1.2.5</version>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>1.2.5</version>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-jvm</artifactId>
            <version>1.2.5</version>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.4.0</version>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-firefox-driver</artifactId>
            <version>3.4.0</version>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>htmlunit-driver</artifactId>
            <version>2.24</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>net.masterthought</groupId>
            <artifactId>cucumber-reporting</artifactId>
            <version>3.7.0</version>
        </dependency>
        <dependency>
            <groupId>com.aventstack</groupId>
            <artifactId>extentreports</artifactId>
            <version>3.0.6</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.16</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.16</version>
        </dependency>
        <dependency>
            <groupId>xml-apis</groupId>
            <artifactId>xml-apis</artifactId>
            <version>2.0.2</version>
        </dependency>
        <dependency>
            <groupId>xerces</groupId>
            <artifactId>xercesImpl</artifactId>
            <version>2.8.0</version>
        </dependency>
        <!-- <dependency> <groupId>org.apache.maven.surefire</groupId> <artifactId>surefire-junit</artifactId>
            <version>2.6</version> </dependency> -->
    </dependencies>
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.3</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.20</version>
                    <configuration>
                        <includes>
                            <include>**/helpers.RunCukesTest.java</include>
                        </includes>
                        <!-- <excludes> <exclude>**/*RunCukesTest.java</exclude> </excludes> -->
                    </configuration>
                    <!-- <dependencies> <dependency> <groupId>org.apache.maven.surefire</groupId>
                        <artifactId>surefire-junit</artifactId> <version>2.6</version> </dependency>
                        </dependencies> -->
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>
</code>```

And the runner class is like this

```<code>import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(
        features = {"classpath:features"},
        plugin = {"pretty", "html:target/cucumber-html-report","json:target/cucumber.json"},
        tags = {"@tag1"},
        glue={"helpers","stepDefinitions"},
//      dryRun = true,
        monochrome = true
        )
public class RunCukesTest{

}
</code>```

When maven test or maven install are executed from eclipse, test cases are not getting executed but the build is successfull.

答:
```<code>import org.apache.log4j.Logger;
import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(plugin = { "pretty", "json:target/Cucumber-report/cucumber.json" },
    features = { "src/test/resources/com/testcases/testsuite" })

public final class CucumberCommandLineTest {

private CucumberCommandLineTest() {
}

static final Logger LOGGER = Logger.getLogger(CucumberCommandLineTest.class.getName());

}
</code>```

This seems to work for me for running at the CLI :

```<code>C:\Tools\jdk1.7.0_79\bin\java" -cp lib\*;target\62110_Automation_KW_Smoke_Test-1.0.0.0-jar-with-dependencies.jar cucumber.api.cli.Main --glue com.gm.testcases .\src\test\resources\com\testcases\testsuite --tags @TC_185826,@TC_185824 --plugin pretty
</code>```

in src/main/java and when doing maven clean:install through Eclipse m2e plugin.

Body:
Trying to Achieve:

Run cucumber test cases configured in runner class using Maven.

Issue:

Configured test cases are not being executed using maven.

Configured pom.xml file:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>simplify360Cucumber</groupId>
    <artifactId>s360UIAutomation</artifactId>
    <version>0.0.1</version>
    <packaging>jar</packaging>
    <name>Cucumber-JVM template</name>

    <dependencies>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>1.2.5</version>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-testng</artifactId>
            <version>1.2.5</version>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>1.2.5</version>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-jvm</artifactId>
            <version>1.2.5</version>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.4.0</version>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-firefox-driver</artifactId>
            <version>3.4.0</version>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>htmlunit-driver</artifactId>
            <version>2.24</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>net.masterthought</groupId>
            <artifactId>cucumber-reporting</artifactId>
            <version>3.7.0</version>
        </dependency>
        <dependency>
            <groupId>com.aventstack</groupId>
            <artifactId>extentreports</artifactId>
            <version>3.0.6</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.16</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.16</version>
        </dependency>
        <dependency>
            <groupId>xml-apis</groupId>
            <artifactId>xml-apis</artifactId>
            <version>2.0.2</version>
        </dependency>
        <dependency>
            <groupId>xerces</groupId>
            <artifactId>xercesImpl</artifactId>
            <version>2.8.0</version>
        </dependency>

    </dependencies>
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.3</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.20</version>
                    <configuration>
                        <includes>
                            <include>**/helpers.RunCukesTest.java</include>
                        </includes>

                    </configuration>

                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

And the runner class is like this

import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(
        features = {"classpath:features"},
        plugin = {"pretty", "html:target/cucumber-html-report","json:target/cucumber.json"},
        tags = {"@tag1"},
        glue={"helpers","stepDefinitions"},
//      dryRun = true,
        monochrome = true
        )
public class RunCukesTest{

}

When maven test or maven install are executed from eclipse, test cases are not getting executed but the build is successfull.

Body:
import org.apache.log4j.Logger;
import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(plugin = { "pretty", "json:target/Cucumber-report/cucumber.json" },
    features = { "src/test/resources/com/testcases/testsuite" })

public final class CucumberCommandLineTest {

private CucumberCommandLineTest() {
}

static final Logger LOGGER = Logger.getLogger(CucumberCommandLineTest.class.getName());

}

This seems to work for me for running at the CLI :

C:\Tools\jdk1.7.0_79\bin\java" -cp lib\*;target\62110_Automation_KW_Smoke_Test-1.0.0.0-jar-with-dependencies.jar cucumber.api.cli.Main --glue com.gm.testcases .\src\test\resources\com\testcases\testsuite --tags @TC_185826,@TC_185824 --plugin pretty

in src/main/java and when doing maven clean:install through Eclipse m2e plugin.


问:
How do I make my controls inside a winforms UserControl private?
I would like to make the controls inside my user control private, so that only the methods/properties I choose to expose are accessible.

I found this similar question: How do I make my controls inside a UserControl private?

However, I would like to know how/if this can be done in windows forms (not wpf.)

It seems like something that should be really simple... what am I missing?

Thanks.

EDIT: In response to some of the comments/answers, I just want to make it clear that I am using VB.net for which the default modifier for a control is "friend", not "Private".

答: I would recommend changing the Modifiers, as per https://msdn.microsoft.com/en-us/library/ms233630(v=vs.110).aspx .</p>


问:
replacing text in xml using xslt
I have an XML file which has some values in child Element aswell in attributes.
If i want to replace some text when specific value is matched how can i achieve it?
I tried using xlst:translate() function. But i cant use this function for each element or attribute in xml.
So is there anyway to replace/translate value at one shot?

```<code><?xml version="1.0" encoding="UTF-8"?>
<Employee>
 <Name>Emp1</Name>
 <Age>40</Age>
 <sex>M</sex>
 <Address>Canada</Address>
 <PersonalInformation>
   <Country>Canada</country>
   <Street1>KO 92</Street1>
 </PersonalInformation>
</Employee>
</code>```

Output :

```<code><?xml version="1.0" encoding="UTF-8"?>
<Employee>
 <Name>Emp1</Name>
 <Age>40</Age>
 <sex>M</sex>
 <Address>UnitedStates</Address>
 <PersonalInformation>
   <Country>UnitedStates</country>
   <Street1>KO 92</Street1>
 </PersonalInformation>
</Employee>
</code>```

in the output, replaced text from Canada to UnitedStates.
so, without using xslt:transform() functions on any element , i should be able to replace text Canada to UnitedStates irrespective of level nodes.
Where ever i find 'Canada' i should be able to replace to 'UnitedStates' in entire xml.
So how can i achieve this.?

答:
I. XSLT 1.0 solution:

This transformation:

```<code><xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:my="my:my" >
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>
 <my:Reps>
  <rep>
    <old>replace this</old>
    <new>replaced</new>
  </rep>
  <rep>
    <old>cat</old>
    <new>tiger</new>
  </rep>
 </my:Reps>

 <xsl:variable name="vReps" select=
  "document('')/*/my:Reps/*"/>

 <xsl:template match="node()|@*" name="identity">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="@*">
  <xsl:attribute name="{name()}">
   <xsl:call-template name="replace">
    <xsl:with-param name="pText" select="."/>
   </xsl:call-template>
  </xsl:attribute>
 </xsl:template>

 <xsl:template match="text()" name="replace">
  <xsl:param name="pText" select="."/>
   <xsl:if test="string-length($pText)">
     <xsl:choose>
       <xsl:when test=
        "not($vReps/old[contains($pText, .)])">
         <xsl:copy-of select="$pText"/>
       </xsl:when>
       <xsl:otherwise>
         <xsl:variable name="vthisRep" select=
         "$vReps/old[contains($pText, .)][1]
         "/>

         <xsl:variable name="vNewText">
           <xsl:value-of
            select="substring-before($pText, $vthisRep)"/>
           <xsl:value-of select="$vthisRep/../new"/>
           <xsl:value-of select=
            "substring-after($pText, $vthisRep)"/>
         </xsl:variable>

         <xsl:call-template name="replace">
           <xsl:with-param name="pText"
            select="$vNewText"/>
         </xsl:call-template>
       </xsl:otherwise>
     </xsl:choose>
   </xsl:if>
 </xsl:template>
</xsl:stylesheet>
</code>```

when applied on this XML document:

```<code><t>
 <a attr1="X replace this Y">
   <b>cat mouse replace this cat dog</b>
 </a>
 <c/>
</t>
</code>```

produces the wanted, correct result:

```<code><t>
   <a attr1="X replaced Y">
      <b>tiger mouse replaced tiger dog</b>
   </a>
   <c/>
</t>
</code>```

Explanation:

The identity rule is used to copy "as-is" some nodes.

We perform multiple replacements, parameterized in my:Reps

If a text node or an attribute doesn't contain any rep-target, it is copied as-is.

If a text node or an attribute contains text to be replaced (rep target), then the replacements are done in the order specified in my:Reps

If the string contains more than one string target, then all targets are replaced: first all occurences of the first rep target, then all occurences of the second rep target, ..., last all occurences of the last rep target.

II. XSLT 2.0 solution:

In XSLT 2.0 one can simply use the standard XPath 2.0 function replace(). However, for multiple replacements the solution would be still very similar to the XSLT 1.0 solution specified above.

Title: replacing text in xml using xslt

Body:
I have an XML file which has some values in child Element aswell in attributes.
If i want to replace some text when specific value is matched how can i achieve it?
I tried using xlst:translate() function. But i cant use this function for each element or attribute in xml.
So is there anyway to replace/translate value at one shot?

<?xml version="1.0" encoding="UTF-8"?>
<Employee>
 <Name>Emp1</Name>
 <Age>40</Age>
 <sex>M</sex>
 <Address>Canada</Address>
 <PersonalInformation>
   <Country>Canada</country>
   <Street1>KO 92</Street1>
 </PersonalInformation>
</Employee>

Output :

<?xml version="1.0" encoding="UTF-8"?>
<Employee>
 <Name>Emp1</Name>
 <Age>40</Age>
 <sex>M</sex>
 <Address>UnitedStates</Address>
 <PersonalInformation>
   <Country>UnitedStates</country>
   <Street1>KO 92</Street1>
 </PersonalInformation>
</Employee>

in the output, replaced text from Canada to UnitedStates.
so, without using xslt:transform() functions on any element , i should be able to replace text Canada to UnitedStates irrespective of level nodes.
Where ever i find 'Canada' i should be able to replace to 'UnitedStates' in entire xml.
So how can i achieve this.?

Body:
I. XSLT 1.0 solution:

This transformation:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:my="my:my" >
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>
 <my:Reps>
  <rep>
    <old>replace this</old>
    <new>replaced</new>
  </rep>
  <rep>
    <old>cat</old>
    <new>tiger</new>
  </rep>
 </my:Reps>

 <xsl:variable name="vReps" select=
  "document('')/*/my:Reps/*"/>

 <xsl:template match="node()|@*" name="identity">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="@*">
  <xsl:attribute name="{name()}">
   <xsl:call-template name="replace">
    <xsl:with-param name="pText" select="."/>
   </xsl:call-template>
  </xsl:attribute>
 </xsl:template>

 <xsl:template match="text()" name="replace">
  <xsl:param name="pText" select="."/>
   <xsl:if test="string-length($pText)">
     <xsl:choose>
       <xsl:when test=
        "not($vReps/old[contains($pText, .)])">
         <xsl:copy-of select="$pText"/>
       </xsl:when>
       <xsl:otherwise>
         <xsl:variable name="vthisRep" select=
         "$vReps/old[contains($pText, .)][1]
         "/>

         <xsl:variable name="vNewText">
           <xsl:value-of
            select="substring-before($pText, $vthisRep)"/>
           <xsl:value-of select="$vthisRep/../new"/>
           <xsl:value-of select=
            "substring-after($pText, $vthisRep)"/>
         </xsl:variable>

         <xsl:call-template name="replace">
           <xsl:with-param name="pText"
            select="$vNewText"/>
         </xsl:call-template>
       </xsl:otherwise>
     </xsl:choose>
   </xsl:if>
 </xsl:template>
</xsl:stylesheet>

when applied on this XML document:

<t>
 <a attr1="X replace this Y">
   <b>cat mouse replace this cat dog</b>
 </a>
 <c/>
</t>

produces the wanted, correct result:

<t>
   <a attr1="X replaced Y">
      <b>tiger mouse replaced tiger dog</b>
   </a>
   <c/>
</t>

Explanation:

The identity rule is used to copy "as-is" some nodes.

We perform multiple replacements, parameterized in my:Reps

If a text node or an attribute doesn't contain any rep-target, it is copied as-is.

If a text node or an attribute contains text to be replaced (rep target), then the replacements are done in the order specified in my:Reps

If the string contains more than one string target, then all targets are replaced: first all occurences of the first rep target, then all occurences of the second rep target, ..., last all occurences of the last rep target.

II. XSLT 2.0 solution:

In XSLT 2.0 one can simply use the standard XPath 2.0 function replace(). However, for multiple replacements the solution would be still very similar to the XSLT 1.0 solution specified above.


问:
Move the mouse pointer every 30 minutes
I want my mouse pointer to move automatically every 30 minutes.

I am writing the code in Excel VBA.

I tried https://support.microsoft.com/en-us/help/152969/visual-basic-procedure-to-get-set-cursor-position but it doesn't work.

答:
Create new module with following code:

```<code>Private dtmNext As Date
Private Type POINTAPI
    x As Long
    y As Long
End Type

Private Declare Function GetCursorPos Lib "user32" (Point As POINTAPI) As Long
Private Declare Function SetCursorPos Lib "user32" (ByVal x As Integer, ByVal y As Integer) As Long

Sub Move_Cursor()
    Dim Hold As POINTAPI
    GetCursorPos Hold
    SetCursorPos Hold.x + 30, Hold.y
    dtmNext = DateAdd("n", 30, Now)
    Application.OnTime dtmNext, "Move_Cursor"
End Sub

Sub Stop_Cursor()
    Application.OnTime dtmNext, "Move_Cursor", , False
End Sub
</code>```

Call Move_Cursor() to start moving the cursor every 30 minuts. To stop the automatic motion, use

```<code>Application.OnTime dtmNext, "Move_Cursor", , False
</code>```

Title: Move the mouse pointer every 30 minutes

Body:
Create new module with following code:

Private dtmNext As Date
Private Type POINTAPI
    x As Long
    y As Long
End Type

Private Declare Function GetCursorPos Lib "user32" (Point As POINTAPI) As Long
Private Declare Function SetCursorPos Lib "user32" (ByVal x As Integer, ByVal y As Integer) As Long

Sub Move_Cursor()
    Dim Hold As POINTAPI
    GetCursorPos Hold
    SetCursorPos Hold.x + 30, Hold.y
    dtmNext = DateAdd("n", 30, Now)
    Application.OnTime dtmNext, "Move_Cursor"
End Sub

Sub Stop_Cursor()
    Application.OnTime dtmNext, "Move_Cursor", , False
End Sub

Call Move_Cursor() to start moving the cursor every 30 minuts. To stop the automatic motion, use

Application.OnTime dtmNext, "Move_Cursor", , False


答: Change the modifier of the control to private  notice that this is private by default in winforms c# but in vb win forms this will be set to friend by default.

Title: How do I make my controls inside a winforms UserControl private?

Body:
I would like to make the controls inside my user control private, so that only the methods/properties I choose to expose are accessible.

I found this similar question: How do I make my controls inside a UserControl private?

However, I would like to know how/if this can be done in windows forms (not wpf.)

It seems like something that should be really simple... what am I missing?

Thanks.

EDIT: In response to some of the comments/answers, I just want to make it clear that I am using VB.net for which the default modifier for a control is "friend", not "Private".


问:
JQuery .text() Multi-Line
Is there a way I can turn this obnoxiously long line of text into a paragraph?

Before:

```<code>$('.ContText-1').text('For a business to thrive, it needs a team of people who are dedicated to its success. Paul Lister, Bryan Jeter, and Bryan Lloyd are committed to being a part of that team for each of their clients.');
</code>```

After:

```<code>$('.ContText-1').text('
             For a business to thrive, it needs a team of people who are dedicated to its
        success. Paul Lister, Bryan Jeter, and Bryan Lloyd are committed to being a part of
        that team for each of their clients.
');
</code>```

If I run the paragraph one I get this error: Uncaught SyntaxError: Invalid or unexpected token

Its referencing to the single quotation mark after the (.

答:
Instead of enclosing the String with ' , try to use ` .

At least in newer iteration of JS this should work fine.

UPDATE:

Actually, this had been covered before: Creating multiline strings in JavaScript

Title: JQuery .text() Multi-Line

Body:
Is there a way I can turn this obnoxiously long line of text into a paragraph?

Before:

$('.ContText-1').text('For a business to thrive, it needs a team of people who are dedicated to its success. Paul Lister, Bryan Jeter, and Bryan Lloyd are committed to being a part of that team for each of their clients.');

After:

$('.ContText-1').text('
             For a business to thrive, it needs a team of people who are dedicated to its
        success. Paul Lister, Bryan Jeter, and Bryan Lloyd are committed to being a part of
        that team for each of their clients.
');

If I run the paragraph one I get this error: Uncaught SyntaxError: Invalid or unexpected token

Its referencing to the single quotation mark after the (.