问:
AJAX POST-method not allowed Error 405
I'm trying to send an email when I click on a button. For this I make an ajax call to a php file:

Ajax call:

```<code> function postAjax(arr) {
     $.ajax({
         url: "../BackEnd/AjaxHandler.php",
         data: { 'action': 'mail' },
         type: "GET"
     });
 }
</code>```

php file (Ajaxhandler.php)

```<code><?php
   if(isset($_GET['action']) && !empty($_GET['action'])) {
   $action = $_GET['action'];
   switch($action){
      case 'mail':
         mail('N.Suhner@wigasoft.ch', 'Mein Betreff', 'tsest');
         break;
      }
   }
?>
</code>```

call:

```<code>$("#mailto").click(function() {
   postAjax(listOfTasks);
 });
</code>```

In the call I make some more things but these are not relevant (styling).

When I click on the button I got an error that the POST-method is not allowed. Does anyone know what I am doing wrong?

答:
There is a typo, You have entered the wrong keyword... Please check following code

Your code should be like following....

```<code>function postAjax(arr) {
   $.ajax({
      type: "POST",
      url: "../_BackEnd/AjaxHandler.php",
      crossDomain: true,
      data: { id: 12 }
   });
}
</code>```

php file:

```<code><?php
     $message = "This is a text!";
     mail('example@mail.ch', 'subject', $message);
?>
</code>```

EDIT

Html

```<code><form id="foo">
    <label for="bar">A bar</label>
    <input id="bar" name="bar" type="text" value="" />

    <input type="submit" value="Send" />
</form>
</code>```

Jquery

```<code>// Variable to hold request
var request;

// Bind to the submit event of our form
$("#foo").submit(function(event){

    // Prevent default posting of form - put here to work in case of errors
    event.preventDefault();

    // Abort any pending request
    if (request) {
        request.abort();
    }
    // setup some local variables
    var $form = $(this);

    // Let's select and cache all the fields
    var $inputs = $form.find("input, select, button, textarea");

    // Serialize the data in the form
    var serializedData = $form.serialize();

    // Let's disable the inputs for the duration of the Ajax request.
    // Note: we disable elements AFTER the form data has been serialized.
    // Disabled form elements will not be serialized.
    $inputs.prop("disabled", true);

    // Fire off the request to /form.php
    request = $.ajax({
        url: "/form.php",
        type: "post",
        data: serializedData
    });

    // Callback handler that will be called on success
    request.done(function (response, textStatus, jqXHR){
        // Log a message to the console
        console.log("Hooray, it worked!");
    });

    // Callback handler that will be called on failure
    request.fail(function (jqXHR, textStatus, errorThrown){
        // Log the error to the console
        console.error(
            "The following error occurred: "+
            textStatus, errorThrown
        );
    });

    // Callback handler that will be called regardless
    // if the request failed or succeeded
    request.always(function () {
        // Reenable the inputs
        $inputs.prop("disabled", false);
    });

});
</code>```

Title: AJAX POST-method not allowed Error 405

Body:
I'm trying to send an email when I click on a button. For this I make an ajax call to a php file:

Ajax call:

 function postAjax(arr) {
     $.ajax({
         url: "../BackEnd/AjaxHandler.php",
         data: { 'action': 'mail' },
         type: "GET"
     });
 }

php file (Ajaxhandler.php)

<?php
   if(isset($_GET['action']) && !empty($_GET['action'])) {
   $action = $_GET['action'];
   switch($action){
      case 'mail':
         mail('N.Suhner@wigasoft.ch', 'Mein Betreff', 'tsest');
         break;
      }
   }
?>

call:

$("#mailto").click(function() {
   postAjax(listOfTasks);
 });

In the call I make some more things but these are not relevant (styling).

When I click on the button I got an error that the POST-method is not allowed. Does anyone know what I am doing wrong?

Body:
There is a typo, You have entered the wrong keyword... Please check following code

Your code should be like following....

function postAjax(arr) {
   $.ajax({
      type: "POST",
      url: "../_BackEnd/AjaxHandler.php",
      crossDomain: true,
      data: { id: 12 }
   });
}

php file:

<?php
     $message = "This is a text!";
     mail('example@mail.ch', 'subject', $message);
?>

EDIT

Html

<form id="foo">
    <label for="bar">A bar</label>
    <input id="bar" name="bar" type="text" value="" />

    <input type="submit" value="Send" />
</form>

Jquery

// Variable to hold request
var request;

// Bind to the submit event of our form
$("#foo").submit(function(event){

    // Prevent default posting of form - put here to work in case of errors
    event.preventDefault();

    // Abort any pending request
    if (request) {
        request.abort();
    }
    // setup some local variables
    var $form = $(this);

    // Let's select and cache all the fields
    var $inputs = $form.find("input, select, button, textarea");

    // Serialize the data in the form
    var serializedData = $form.serialize();

    // Let's disable the inputs for the duration of the Ajax request.
    // Note: we disable elements AFTER the form data has been serialized.
    // Disabled form elements will not be serialized.
    $inputs.prop("disabled", true);

    // Fire off the request to /form.php
    request = $.ajax({
        url: "/form.php",
        type: "post",
        data: serializedData
    });

    // Callback handler that will be called on success
    request.done(function (response, textStatus, jqXHR){
        // Log a message to the console
        console.log("Hooray, it worked!");
    });

    // Callback handler that will be called on failure
    request.fail(function (jqXHR, textStatus, errorThrown){
        // Log the error to the console
        console.error(
            "The following error occurred: "+
            textStatus, errorThrown
        );
    });

    // Callback handler that will be called regardless
    // if the request failed or succeeded
    request.always(function () {
        // Reenable the inputs
        $inputs.prop("disabled", false);
    });

});


来源: stackexchange

问:
Typescript AngularJS 'this' is undefined
I have a service written with TypeScript. Something like:

```<code>export default class AServiceClass {

    constructor(private $http: ng.IHttpService, ...) {}

    method1(data : any) : void {
        this.$http(...)
    }

    method2(data : any) : void {
        this.$http(...)
    }
}
</code>```

And I have a controller class, that utilize this service:

```<code>export default class AControllerClass {

    constructor(private aService: AServiceClass, ...) {}

    $onInit(){

        let method = true ? this.aService.method1 : this.aService.method2;
        method({ ... data ... });
    }
}
</code>```

Service methods throw an Exception - this is undefind. If I use it like this.aService.method1({ ... data ... }), all is fine. Ofc I can do method.bind(aService)({ ... data ... }) or method.call(aService, { ... data ... }), but why there is a scope difference?

Thx.

答:
Your method1 method is invoked without a context so this inside it will be undefined. You have to call it with the aService object as context or explicitly set the context using call or apply or explicitly bind the context using bind:

```<code>this.aService.method1(); // `this` will be aService inside `method1`

method.call(aService, args);

method.apply(aService, [args]);

// Or bind using `bind`:

let method = true ? this.aService.method1.bind(this.aService) : this.aService.method2.bind(this.aService);

method();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a service written with TypeScript. Something like:

export default class AServiceClass {

    constructor(private $http: ng.IHttpService, ...) {}

    method1(data : any) : void {
        this.$http(...)
    }

    method2(data : any) : void {
        this.$http(...)
    }
}

And I have a controller class, that utilize this service:

export default class AControllerClass {

    constructor(private aService: AServiceClass, ...) {}

    $onInit(){

        let method = true ? this.aService.method1 : this.aService.method2;
        method({ ... data ... });
    }
}

Service methods throw an Exception - this is undefind. If I use it like this.aService.method1({ ... data ... }), all is fine. Ofc I can do method.bind(aService)({ ... data ... }) or method.call(aService, { ... data ... }), but why there is a scope difference?

Thx.

Body:
Your method1 method is invoked without a context so this inside it will be undefined. You have to call it with the aService object as context or explicitly set the context using call or apply or explicitly bind the context using bind:

this.aService.method1(); // `this` will be aService inside `method1`

method.call(aService, args);

method.apply(aService, [args]);

// Or bind using `bind`:

let method = true ? this.aService.method1.bind(this.aService) : this.aService.method2.bind(this.aService);

method();


问:
google static maps API : mobile
i am using static "google  static maps API" on mobile j2me

when i use it on emulator on my PC .... it is retrieve map successfully

but when i use it with mobile it is give me the following exception:
Illegal argument exception

does any body have a solution for this problem

request URL:

```<code>http://maps.google.com/maps/api/staticmap?zoom=6&size=240x229&markers=color:blue|label:L|63.279591,-144.967969&sensor=false
</code>```

Thanks

答:
i found the solution from my TTL

in Nokia mobile http connection does not recognize "|" add URL encoded for
this symbol: "%7C" and it is should work probably

ContentLicense: CC BY-SA 2.5

Title: google static maps API : mobile

Body:
i am using static "google  static maps API" on mobile j2me

when i use it on emulator on my PC .... it is retrieve map successfully

but when i use it with mobile it is give me the following exception:
Illegal argument exception

does any body have a solution for this problem

request URL:

http://maps.google.com/maps/api/staticmap?zoom=6&size=240x229&markers=color:blue|label:L|63.279591,-144.967969&sensor=false

Thanks


问:
The object cannot be deleted because it was not found in the ObjectStateManager
I have this code which normally works:

```<code>db.myTable.DeleteObject(myCurrent);
</code>```

And I got this error:

```<code>The object cannot be deleted because it was not found in the ObjectStateManager.
</code>```

The same ingredients IS in the table in the database.

I tried this:

```<code>db.myTable.Attach(myCurrent);
db.myTable.DeleteObject(myCurrent);
</code>```

And I got another error:

```<code>An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
</code>```

How to fix this?

答:
In my case I was trying to delete an object that is not fetched from the database table "Student".
Wrong way to delete object:

var objStudent= new Student();
 db.Student.Remove(objStudent);

So take care of this. Object to delete should come from the table

Body:
I have this code which normally works:

db.myTable.DeleteObject(myCurrent);

And I got this error:

The object cannot be deleted because it was not found in the ObjectStateManager.

The same ingredients IS in the table in the database.

I tried this:

db.myTable.Attach(myCurrent);
db.myTable.DeleteObject(myCurrent);

And I got another error:

An entity object cannot be referenced by multiple instances of IEntityChangeTracker.

How to fix this?


问:
Creating Jquery Plugin with ajax
this is my first time creating plugin. But my plugin have some little issue. I have created a simple replica of my plugin below

```<code>$.fn.myPlugin = function(url){
    return this.each(function() {
        element = $(this);
        $.getJSON(url, function(response){
            elem.val(response.init_value);
        });
    });
}
</code>```

and Initiated Like this

```<code>$("#test1").myPlugin('/get1.json'); //this should value 1
$("#test2").myPlugin('/get2.json'); //this should value 2
</code>```

but the result is not working as expected

```<code>Element #test1 has done nothing, no value (I think it is broken)
Element #test2 has value of 2
</code>```

My plugin is working fine when i initiate a single instance but when im trying to make a multiple instances, only the last instance is working.

答:
I think this occurs because you've declared element without using var.

This way you've declared element as a global variable, so element = $(this); is basically the same as window.element = $(this);. Because of this, the second function call will overwrite the first instance of element.

That should be a simple fix: var element = $(this);

Title: Creating Jquery Plugin with ajax

Body:
this is my first time creating plugin. But my plugin have some little issue. I have created a simple replica of my plugin below

$.fn.myPlugin = function(url){
    return this.each(function() {
        element = $(this);
        $.getJSON(url, function(response){
            elem.val(response.init_value);
        });
    });
}

and Initiated Like this

$("#test1").myPlugin('/get1.json'); //this should value 1
$("#test2").myPlugin('/get2.json'); //this should value 2

but the result is not working as expected

Element #test1 has done nothing, no value (I think it is broken)
Element #test2 has value of 2

My plugin is working fine when i initiate a single instance but when im trying to make a multiple instances, only the last instance is working.


问:
Spring Cloud Stream partitionKeyExpression wrong calculation
I have a Spring Cloud Stream based microservice using Kafka.

I created a kafka topic with 4 partitions.

I configured the following in my yml:

```<code>spring:
  cloud:
    stream:
      bindings:
        SYNC_TABLE:
          content-type: application/json
          partitionKeyExpression: payload.partitionKey
          partitionCount: 4
          destination: ${envTopicPrefix}.LEGACY_TABLE
</code>```

In my code I have my message class that contains (in its superclass) the partitionKey variable:

```<code>@Data
@EqualsAndHashCode(callSuper=true)
@ToString(callSuper=true)
public class TransactionResponse extends GeneralOutputMessage{

}
</code>```

```<code>@Data
@ToString
public class GeneralOutputMessage {

    private String operationType;
    private List<String> affectedFields;
    private Object data;
    private String eventId;
    private String eventName;
    private String partitionKey;
}
</code>```

I am sending the TransactionsResponse object as a message:

```<code>final TransactionResponse transactionResponse = handler.handleEvent(event);
if (transactionResponse != null) {
    outputChannels.tableSync().send(MessageBuilder.withPayload(transactionResponse).build());
    log.info("Message Sent: {}", transactionResponse);
}
</code>```

My expectation is that spring cloud stream would take the key payload.partitionKey, calculate its hashCode() % 4, and send the event to that partition.

However, the logic is completely random. Here are a few examples:

Math.abs("111615631".hashCode()%4) = 1. However, the message is sent to partition number 3.

Math.abs("110019882".hashCode()%4) = 2. However, the message is sent to partition number 0.

Math.abs("943152574".hashCode()%4) = 0. This message does indeed get  sent to partition number 0.

Math.abs("943198862".hashCode()%4) = 0. However, this message is sent to partition number 2.

I'm using the Dalston.SR1 release train.

What am I missing here?

Thanks.

Update:

Just tried to send the same event with the same partitionKey (but slightly different message body). The message goes to two different partitions even though the partition key is the same. Looks like Spring Cloud Stream ignores the partitionKeyExpression completely.

答:
it was my mistake, I forgot to add the producer: section in the yml:</p>

```<code>spring:
  cloud:
    stream:
      bindings:
        SYNC_TABLE:
          content-type: application/json
          producer:
            partitionKeyExpression: payload.partitionKey
            partitionCount: 4
          destination: ${envTopicPrefix}.LEGACY_TABLE
</code>```

Body:
I have a Spring Cloud Stream based microservice using Kafka.

I created a kafka topic with 4 partitions.

I configured the following in my yml:

spring:
  cloud:
    stream:
      bindings:
        SYNC_TABLE:
          content-type: application/json
          partitionKeyExpression: payload.partitionKey
          partitionCount: 4
          destination: ${envTopicPrefix}.LEGACY_TABLE

In my code I have my message class that contains (in its superclass) the partitionKey variable:

@Data
@EqualsAndHashCode(callSuper=true)
@ToString(callSuper=true)
public class TransactionResponse extends GeneralOutputMessage{

}

@Data
@ToString
public class GeneralOutputMessage {

    private String operationType;
    private List<String> affectedFields;
    private Object data;
    private String eventId;
    private String eventName;
    private String partitionKey;
}

I am sending the TransactionsResponse object as a message:

final TransactionResponse transactionResponse = handler.handleEvent(event);
if (transactionResponse != null) {
    outputChannels.tableSync().send(MessageBuilder.withPayload(transactionResponse).build());
    log.info("Message Sent: {}", transactionResponse);
}

My expectation is that spring cloud stream would take the key payload.partitionKey, calculate its hashCode() % 4, and send the event to that partition.

However, the logic is completely random. Here are a few examples:

Math.abs("111615631".hashCode()%4) = 1. However, the message is sent to partition number 3.

Math.abs("110019882".hashCode()%4) = 2. However, the message is sent to partition number 0.

Math.abs("943152574".hashCode()%4) = 0. This message does indeed get  sent to partition number 0.

Math.abs("943198862".hashCode()%4) = 0. However, this message is sent to partition number 2.

I'm using the Dalston.SR1 release train.

What am I missing here?

Thanks.

Update:

Just tried to send the same event with the same partitionKey (but slightly different message body). The message goes to two different partitions even though the partition key is the same. Looks like Spring Cloud Stream ignores the partitionKeyExpression completely.

Body:
it was my mistake, I forgot to add the producer: section in the yml:

spring:
  cloud:
    stream:
      bindings:
        SYNC_TABLE:
          content-type: application/json
          producer:
            partitionKeyExpression: payload.partitionKey
            partitionCount: 4
          destination: ${envTopicPrefix}.LEGACY_TABLE


问:
Fetching all rows of dataframe using Python pandas
I ran a python code and got dataframe output like:

```<code>1    Department of Susta... (2)       Community Services (2)
2    Department of Commu... (2)       Community Services (2)
3    Sustainability Vict... (1)       Community Services (1)
4    Southern Grampians ... (1)       Community Services (1)
5    Productivity Commis... (1)       Community Services (1)
6         Parliament of NSW (1)       Community Services (1)
..                           ...                          ...
30      Noosa Shire Council (2)     Sport and Recreation (2)
31   State Library of Qu... (1)     Sport and Recreation (1)
32   Emergency Services ... (1)     Sport and Recreation (1)
33   Department of Susta... (1)     Sport and Recreation (1)
</code>```

now i don't have rows b/w 7 to 29. How to fetch all rows?

答:
As of 0.20.2, pandas displays only 60 rows from your data by default. You can change this with

```<code>pd.set_option('display.max_rows',n)
</code>```

where n is the number of rows you want it to display.

Body:
I ran a python code and got dataframe output like:

1    Department of Susta... (2)       Community Services (2)
2    Department of Commu... (2)       Community Services (2)
3    Sustainability Vict... (1)       Community Services (1)
4    Southern Grampians ... (1)       Community Services (1)
5    Productivity Commis... (1)       Community Services (1)
6         Parliament of NSW (1)       Community Services (1)
..                           ...                          ...
30      Noosa Shire Council (2)     Sport and Recreation (2)
31   State Library of Qu... (1)     Sport and Recreation (1)
32   Emergency Services ... (1)     Sport and Recreation (1)
33   Department of Susta... (1)     Sport and Recreation (1)

now i don't have rows b/w 7 to 29. How to fetch all rows?

Body:
As of 0.20.2, pandas displays only 60 rows from your data by default. You can change this with

pd.set_option('display.max_rows',n)

where n is the number of rows you want it to display.


问:
How to bind map of custom objects using @RequestBody from JSON
I need to send map of custom objects Map<String, Set<Result>> from frontend to backend.

So I think it should be possible to build JSON, send it to Controller via Ajax and receive it in Controller via @RequestBody annotation which should bind json to object. right?

Controller:

```<code>@RequestMapping(value = "/downloadReport", method = RequestMethod.POST)
public ResponseEntity<byte[]> getReport(@RequestBody Map<String, Set<Result>> resultMap)
{
    Context context = new Context();
    context.setVariable("resultMap", resultMap);
    return createPDF("pdf-report", context);
}
</code>```

JSON:

```<code>{
  "result": [
    {
      "id": 1,
      "item": {
        "id": 3850,
        "name": "iti"
      },
      "severity": "low",
      "code": "A-M-01",
      "row": 1,
      "column": 1,
      "description": "Miscellaneous warning"
    }
  ]
}
</code>```

Model:

```<code>public class Result {
    private Integer id;
    private Item item;
    private String severity;
    private String code;
    private Integer row;
    private Integer column;
    private String description;
    //getter & setters
    //hashCode & equals
}
public class Item {
    private Integer id;
    private String name;
    //getter & setters
}
</code>```

After send such a JSON like above by ajax I am getting error message from browser:

```<code>The request sent by the client was syntactically incorrect
</code>```

If I change JSON to send empty set like below then it works but of course my map has empty set:

```<code>{"result": []}
</code>```

So, Why I am not able to receive filled map with set of objects? Why binding/unmarshalling do not work as expected and what I should do to make it works?

Note:
I am using Jackson library and marshalling for other case for @ResponseBody works fine. Problem is with unmarshalling and binding object via @RequestBody.

答:
you have to deal with map differently,
first create wrapper class

```<code>public MyWrapperClass implements Serializable {
    private static final long serialVersionUID = 1L;
    Map<String, List<String>> fil = new HashMap<String, List<String>>();
    // getters and setters
    }
</code>```

then you should take request in controller,

```<code>@PostMapping
    public Map<String,List<String>> get(@RequestBody Filter filter){
    System.out.println(filter);
    }
</code>```

Json Request should be like

```<code>{
       "fil":{
          "key":[
             "value1",
             "value2"
          ],
          "key":[
             "vakue1"
          ]
       }
    }
</code>```

Body:
I need to send map of custom objects Map<String, Set<Result>> from frontend to backend.

So I think it should be possible to build JSON, send it to Controller via Ajax and receive it in Controller via @RequestBody annotation which should bind json to object. right?

Controller:

@RequestMapping(value = "/downloadReport", method = RequestMethod.POST)
public ResponseEntity<byte[]> getReport(@RequestBody Map<String, Set<Result>> resultMap)
{
    Context context = new Context();
    context.setVariable("resultMap", resultMap);
    return createPDF("pdf-report", context);
}

JSON:

{
  "result": [
    {
      "id": 1,
      "item": {
        "id": 3850,
        "name": "iti"
      },
      "severity": "low",
      "code": "A-M-01",
      "row": 1,
      "column": 1,
      "description": "Miscellaneous warning"
    }
  ]
}

Model:

public class Result {
    private Integer id;
    private Item item;
    private String severity;
    private String code;
    private Integer row;
    private Integer column;
    private String description;
    //getter & setters
    //hashCode & equals
}
public class Item {
    private Integer id;
    private String name;
    //getter & setters
}

After send such a JSON like above by ajax I am getting error message from browser:

The request sent by the client was syntactically incorrect

If I change JSON to send empty set like below then it works but of course my map has empty set:

{"result": []}

So, Why I am not able to receive filled map with set of objects? Why binding/unmarshalling do not work as expected and what I should do to make it works?

Note:
I am using Jackson library and marshalling for other case for @ResponseBody works fine. Problem is with unmarshalling and binding object via @RequestBody.

Body:
you have to deal with map differently,
first create wrapper class

public MyWrapperClass implements Serializable {
    private static final long serialVersionUID = 1L;
    Map<String, List<String>> fil = new HashMap<String, List<String>>();
    // getters and setters
    }

then you should take request in controller,

@PostMapping
    public Map<String,List<String>> get(@RequestBody Filter filter){
    System.out.println(filter);
    }

Json Request should be like

{
       "fil":{
          "key":[
             "value1",
             "value2"
          ],
          "key":[
             "vakue1"
          ]
       }
    }


问:
how to obtain license key for here maps api
I am not able to find the license key from here maps. I have my app ID and app Code already but not the license key.</p>

```<code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    NMAApplicationContext.setAppId(yourAppID, appCode: yourAppCode, licenseKey: yourLicenseKey)
    return true
}
</code>```

答:
For Starter SDKs there is no License key available.

You need to register for Premium SDK

Body:
I am not able to find the license key from here maps. I have my app ID and app Code already but not the license key.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    NMAApplicationContext.setAppId(yourAppID, appCode: yourAppCode, licenseKey: yourLicenseKey)
    return true
}


问:
How to ensure sequential primary key in oracle database using sequence table when doing inserts from multiple threads in a spring batch application
I have a data aggregation and loading application that loads data files to an oracle database. We are using spring integration for file poling and spring batch for loading data to the database. When more than one file is being processed (read and loaded to database ) primary key tends to skip some values.
Oracle sequence created is.

```<code>CREATE SEQUENCE  "SCHEMA"."SEQUENCE_TABLE_NAME"  MINVALUE 1 MAXVALUE
    9999999999999999999999999999 INCREMENT BY 1 START WITH 241488161 CACHE
    20 NOORDER  NOCYCLE ;
</code>```

An inbound-channel-adapter has a poller which has as task executor. the inbound channel adapter sends the file to a transformer which creates a JobLaunchRequest object that is launched by the job-launching-gateway.
The job has a reader and a jdbcwriter that executes the following statement.

```<code><bean id="itemWriter" class="org.springframework.batch.item.database.JdbcBatchItemWriter">
    <property name="dataSource" ref="dataSource"/>
    <property name="sql">
        <value>
            <![CDATA[
            insert  into data_table (id,dataA,dataB)
            values(SEQUENCE_TABLE_NAME.nextval,:dataA,:dataB)
            ]]>
        </value>
    </property>
    <property name="itemSqlParameterSourceProvider">
        <bean
             class="org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider"/>
    </property>
</bean>
</code>```

The key reason for loading to database is that an api is exposed which depends on the primary key being ordered and sequential. but once two many files are present in the folder. due to multiple threads reading and writing to the db. the primary key provided by the sequence table is missing some values in between.

A similar case is explained here (oracle perspective alone).

答:
you should create an own implementation of a sequence that runs in
  transactions...

Try something like this:

```<code>CREATE TABLE schema.sequence_table ( seq BIGINT );

INSERT
  INTO schema.sequence_table
  VALUES (0);

CREATE OR REPLACE
  FUNCTION get_next_seq()
  RETURN BIGINT
  AS
DECLARE
  s BIGINT;
BEGIN
  SELECT COALESCE(seq) + 1
    INTO s
    FROM schema.sequence_table;
  UPDATE schema.sequence_table
    SET seq = s;
  RETURN s;
END;
</code>```

Body:
I have a data aggregation and loading application that loads data files to an oracle database. We are using spring integration for file poling and spring batch for loading data to the database. When more than one file is being processed (read and loaded to database ) primary key tends to skip some values.
Oracle sequence created is.

CREATE SEQUENCE  "SCHEMA"."SEQUENCE_TABLE_NAME"  MINVALUE 1 MAXVALUE
    9999999999999999999999999999 INCREMENT BY 1 START WITH 241488161 CACHE
    20 NOORDER  NOCYCLE ;

An inbound-channel-adapter has a poller which has as task executor. the inbound channel adapter sends the file to a transformer which creates a JobLaunchRequest object that is launched by the job-launching-gateway.
The job has a reader and a jdbcwriter that executes the following statement.

<bean id="itemWriter" class="org.springframework.batch.item.database.JdbcBatchItemWriter">
    <property name="dataSource" ref="dataSource"/>
    <property name="sql">
        <value>
            <![CDATA[
            insert  into data_table (id,dataA,dataB)
            values(SEQUENCE_TABLE_NAME.nextval,:dataA,:dataB)
            ]]>
        </value>
    </property>
    <property name="itemSqlParameterSourceProvider">
        <bean
             class="org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider"/>
    </property>
</bean>

The key reason for loading to database is that an api is exposed which depends on the primary key being ordered and sequential. but once two many files are present in the folder. due to multiple threads reading and writing to the db. the primary key provided by the sequence table is missing some values in between.

A similar case is explained here (oracle perspective alone).

Body:
you should create an own implementation of a sequence that runs in
  transactions...

Try something like this:

CREATE TABLE schema.sequence_table ( seq BIGINT );

INSERT
  INTO schema.sequence_table
  VALUES (0);

CREATE OR REPLACE
  FUNCTION get_next_seq()
  RETURN BIGINT
  AS
DECLARE
  s BIGINT;
BEGIN
  SELECT COALESCE(seq) + 1
    INTO s
    FROM schema.sequence_table;
  UPDATE schema.sequence_table
    SET seq = s;
  RETURN s;
END;


问:
Why can't I switch UIGestureRecognizer's properties in the action function
I have two UITapGestureRecognizer to handle both a single tap and a double tap. My code is like this:

```<code>let doubleTap = UITapGestureRecognizer(
    target: self, action: #selector(viewController.handleDouble)
)
doubleTap.numberOfTapsRequired = 2
myview.addGestureRecognizer(doubleTap)

let singleTap = UITapGestureRecognizer(
    target: self, action: #selector(viewController.handleSingle)
)
singleTap.numberOfTapsRequired = 1
singleTap.require(toFail: doubleTap)
myview.addGestureRecognizer(singleTap)
</code>```

And handelDouble and handleSingle are the functions handle double and single taps. This works perfectly well.

Now I would like to just create one UITapGestureRecognizer to handle both case, something like:

```<code>let tap = UITapGestureRecognizer(
    target: self, action: #selector(viewController.handleTap(recognizer:))
)
myview.addGestureRecognizer(Tap)
</code>```

And in the handelTap function I wrote like this:

```<code>func handleTap(recognizer: UITapGestureRecognizer) {
    switch recognizer.state {
    case .ended:
        if (recognizer.numberOfTapsRequired = 2) {
             // to do something with double tapping
        } else {
             // to do something with single tapping
        }
    default: break
    }
}
</code>```

However, this does not work. More weird is that when double tapping, things for single tapping happens.

This also happens to UISwipeGestureRecognizer as I cannot using one function to select which direction it is.

So is it that we can only create multiple UIGestureRecognizer instances for such work?

答:
In your code you numberOfTapsRequired for singleTap is equal 2. I think correct value would be 1

```<code>let singleTap = UITapGestureRecognizer(
    target: self, action: #selector(viewController.handleSingle)
)
singleTap.numberOfTapsRequired = 2
singleTap.require(toFail: doubleTap)
myview.addGestureRecognizer(singleTap)
</code>```

Body:
I have two UITapGestureRecognizer to handle both a single tap and a double tap. My code is like this:

let doubleTap = UITapGestureRecognizer(
    target: self, action: #selector(viewController.handleDouble)
)
doubleTap.numberOfTapsRequired = 2
myview.addGestureRecognizer(doubleTap)

let singleTap = UITapGestureRecognizer(
    target: self, action: #selector(viewController.handleSingle)
)
singleTap.numberOfTapsRequired = 1
singleTap.require(toFail: doubleTap)
myview.addGestureRecognizer(singleTap)

And handelDouble and handleSingle are the functions handle double and single taps. This works perfectly well.

Now I would like to just create one UITapGestureRecognizer to handle both case, something like:

let tap = UITapGestureRecognizer(
    target: self, action: #selector(viewController.handleTap(recognizer:))
)
myview.addGestureRecognizer(Tap)

And in the handelTap function I wrote like this:

func handleTap(recognizer: UITapGestureRecognizer) {
    switch recognizer.state {
    case .ended:
        if (recognizer.numberOfTapsRequired = 2) {
             // to do something with double tapping
        } else {
             // to do something with single tapping
        }
    default: break
    }
}

However, this does not work. More weird is that when double tapping, things for single tapping happens.

This also happens to UISwipeGestureRecognizer as I cannot using one function to select which direction it is.

So is it that we can only create multiple UIGestureRecognizer instances for such work?

Body:
In your code you numberOfTapsRequired for singleTap is equal 2. I think correct value would be 1

let singleTap = UITapGestureRecognizer(
    target: self, action: #selector(viewController.handleSingle)
)
singleTap.numberOfTapsRequired = 2
singleTap.require(toFail: doubleTap)
myview.addGestureRecognizer(singleTap)


问:
How to use a variable from one method to other in a same class in Ruby?
I am new to Ruby. I have the below code in my controller.
Desired Behaviour:-
I want to display the validation error string on my views on edit page. So I am putting those errors in a variable. When validation fails then I want to use that variable in my edit method, so that I can display that on my edit page view.

Observed behavior:-
There is a variable @vpinerr in create method. I want to use that variable in edit method. I have tried to use the class variable (@@vpinerr) and initialized it with an empty string (@@vpinerr = "") then the value of this variable becomes empty in edit method.

```<code>require 'rho/rhocontroller'
    require 'helpers/browser_helper'

    class LeadController < Rho::RhoController
      include BrowserHelper

      # GET /Lead
      def index
        @leads = Lead.find(:all)
        render :back => '/app'
      end

    # GET /Lead/new
      def new
        @lead = Lead.new
        render :action => :new, :back => url_for(:action => :index)
      end

      def create
        # Update
        if Lead.find(@params['id'])
            @lead = Lead.find(@params['id'])
            # array of objects
            @leadadd = LeadAddress.find(:all,
                                        :conditions => {:parentKey => @lead.object}
                                    )
            @leadcon = LeadContact.find(:all,
                                        :conditions => {:parentKey => @lead.object}
                                        )

            #hash of hashes
            leadaddressArray = @params['leadaddress']

            arr1 = @leadadd.count - 1

            for i in 0..arr1
              j=i.to_s
              @leadaddHash = @leadadd[i]
              leadaddressHash = leadaddressArray[j]

              if leadaddressHash['removed'] == "1"
                singleadd = LeadAddress.find(:first,
                                        :conditions => {:object => leadaddressHash['object']}
                                    )
                singleadd.destroy if singleadd
              else
                #validation
                vpin = leadaddressHash['pincode']
                #validation check
                if vpin =~ /^[[:digit:]]+$/
                  @leadaddHash.update_attributes(leadaddressHash) if @leadaddHash
                else
                  err = 1
                  @vpinerr = "Pincode is invalid"
                end
              end
            end

            leadconArray = @params['leadcontact']
            arr2 = @leadcon.count - 1
            for k in 0..arr2
              z=k.to_s
              @leadconHash = @leadcon[k]
              leadContact = leadconArray[z]
              if leadContact['removed'] == "1"
                singlecon = LeadContact.find(:first,
                                        :conditions => {:object => leadContact['object']}
                                    )
                singlecon.destroy if singlecon
              else
                @leadconHash.update_attributes(leadContact) if @leadconHash
              end

            end

            @lead.update_attributes(@params['lead']) if @lead
            if err == 0
              redirect :action => :index
            else
              redirect :action => :edit, :id => @lead.object, :vpin =>@vpinerr
            end

        else
        # Create
            err = 0

            # validation
            vlead = @params['lead']
            vfirstname = vlead['firstname']
            vlastname = vlead['lastname']
            vage = vlead['age']

            #validation check
            if (vfirstname =~ /^[[:alpha:][:blank:]]+$/) and (vlastname =~ /^[[:alpha:][:blank:]]+$/) and (vage =~ /^[[:digit:]]+$/)
              @lead = Lead.create(@params['lead'])
              @key = @lead.object
            else
              err = 1
              @basicerr = "Basic Details are invalid"
            end

            if @params['leadaddress']
              leadaddressArray = @params['leadaddress']
              arrcount = leadaddressArray.count
              for i in 1..arrcount
                j=(i-1).to_s
                leadaddressHash = leadaddressArray[j]
                #validation
                vpin = leadaddressHash['pincode']
                #validation check
                if vpin =~ /^[[:digit:]]+$/
                  @leadAdd = LeadAddress.create(leadaddressHash)
                  @leadAdd.parentKey = @key
                  @leadAdd.save()
                else
                  err = 1
                  @vpinerr = "Pincode is invalid"
                end
              end
            end

            if @params['leadcontact']
              leadconArray = @params['leadcontact']
              arrcount2 = leadconArray.count
              for k in 1..arrcount2
                h=(k-1).to_s
                leadconHash = leadconArray[h]
                #validation
                vhome = leadconHash['home']
                vmobile = leadconHash['mobile']
                vemail = leadconHash['email']
                #validation check
                if (vhome =~ /^[[:digit:]]+$/) and (vmobile =~ /^[[:digit:]]+$/) and (vemail =~ /\A([\w+\-]\.?)+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i)
                  @leadcontact = LeadContact.create(leadconHash)
                  @leadcontact.parentKey = @key
                  @leadcontact.save()
                else
                  err = 1
                  @contacterr = "Contact Details are invalid"
                end
              end
            end

            if err == 0
              redirect :action => :index
            else
              redirect :action => :edit, :id => @lead.object
            end
        end
      end

    # GET /Lead/{1}
      def show
        @lead = Lead.find(@params['id'])
        @leadadd = LeadAddress.find(:all,
                                        :conditions => {:parentKey => @lead.object}
                                    )
        @leadcontact = LeadContact.find(:all,
                                        :conditions => {:parentKey => @lead.object}
                                        )

        if @lead
          render :action => :show, :back => url_for(:action => :index)
        else
          redirect :action => :index
        end
      end

      # GET /Lead/{1}/edit
      def edit
        @lead = Lead.find(@params['id'])
        @leadaddress = LeadAddress.find(:all,
                                        :conditions => {:parentKey => @lead.object}
                                    )
        @leadcontact = LeadContact.find(:all,
                                        :conditions => {:parentKey => @lead.object}
                                       )
        @vpinerr2 = @vpinerr

        if @lead
          render :action => :new, :back => url_for(:action => :index)
        else
          redirect :action => :index
        end
      end

    end
</code>```

答:
Variables with a prepending @ are considered as instance variables and are available in a class's instance. Your controller is a class and with every request, Rails instantiates a new controller instance. In that sense, when you make a request to the create action, a new instance is created and @vpinerr is set in the instance. When you redirect the user to the edit action, its a new request and a new controller instance is instantiated. Since the instances from create action and edit actions are different, you won't have the value of @vpinerr in the edit action.

You have alternatives.

Class-level variables.

Class-level variables are set on the class and are available in all instances. Any variable prepended with @@ are class variables. Change to @@vpinerr everywhere instead of @vpinerr.

This would be wrong to use in your case because, you could want it to be different for each user but using class variable will keep the value for other users too until its changed. Read about class variables:  http://www.railstips.org/blog/archives/2006/11/18/class-and-instance-variables-in-ruby

Session variables.

Session variables are used to save variables within a session. They can be shared between controllers too. To set a session variable session[:vpinerr] = "Some error" and to use it, you can simple call session[:vpinerr].

ContentLicense: CC BY-SA 4.0

Body:
I am new to Ruby. I have the below code in my controller.
Desired Behaviour:-
I want to display the validation error string on my views on edit page. So I am putting those errors in a variable. When validation fails then I want to use that variable in my edit method, so that I can display that on my edit page view.

Observed behavior:-
There is a variable @vpinerr in create method. I want to use that variable in edit method. I have tried to use the class variable (@@vpinerr) and initialized it with an empty string (@@vpinerr = "") then the value of this variable becomes empty in edit method.

require 'rho/rhocontroller'
    require 'helpers/browser_helper'

    class LeadController < Rho::RhoController
      include BrowserHelper

      # GET /Lead
      def index
        @leads = Lead.find(:all)
        render :back => '/app'
      end

    # GET /Lead/new
      def new
        @lead = Lead.new
        render :action => :new, :back => url_for(:action => :index)
      end

      def create
        # Update
        if Lead.find(@params['id'])
            @lead = Lead.find(@params['id'])
            # array of objects
            @leadadd = LeadAddress.find(:all,
                                        :conditions => {:parentKey => @lead.object}
                                    )
            @leadcon = LeadContact.find(:all,
                                        :conditions => {:parentKey => @lead.object}
                                        )

            #hash of hashes
            leadaddressArray = @params['leadaddress']

            arr1 = @leadadd.count - 1

            for i in 0..arr1
              j=i.to_s
              @leadaddHash = @leadadd[i]
              leadaddressHash = leadaddressArray[j]

              if leadaddressHash['removed'] == "1"
                singleadd = LeadAddress.find(:first,
                                        :conditions => {:object => leadaddressHash['object']}
                                    )
                singleadd.destroy if singleadd
              else
                #validation
                vpin = leadaddressHash['pincode']
                #validation check
                if vpin =~ /^[[:digit:]]+$/
                  @leadaddHash.update_attributes(leadaddressHash) if @leadaddHash
                else
                  err = 1
                  @vpinerr = "Pincode is invalid"
                end
              end
            end

            leadconArray = @params['leadcontact']
            arr2 = @leadcon.count - 1
            for k in 0..arr2
              z=k.to_s
              @leadconHash = @leadcon[k]
              leadContact = leadconArray[z]
              if leadContact['removed'] == "1"
                singlecon = LeadContact.find(:first,
                                        :conditions => {:object => leadContact['object']}
                                    )
                singlecon.destroy if singlecon
              else
                @leadconHash.update_attributes(leadContact) if @leadconHash
              end

            end

            @lead.update_attributes(@params['lead']) if @lead
            if err == 0
              redirect :action => :index
            else
              redirect :action => :edit, :id => @lead.object, :vpin =>@vpinerr
            end

        else
        # Create
            err = 0

            # validation
            vlead = @params['lead']
            vfirstname = vlead['firstname']
            vlastname = vlead['lastname']
            vage = vlead['age']

            #validation check
            if (vfirstname =~ /^[[:alpha:][:blank:]]+$/) and (vlastname =~ /^[[:alpha:][:blank:]]+$/) and (vage =~ /^[[:digit:]]+$/)
              @lead = Lead.create(@params['lead'])
              @key = @lead.object
            else
              err = 1
              @basicerr = "Basic Details are invalid"
            end

            if @params['leadaddress']
              leadaddressArray = @params['leadaddress']
              arrcount = leadaddressArray.count
              for i in 1..arrcount
                j=(i-1).to_s
                leadaddressHash = leadaddressArray[j]
                #validation
                vpin = leadaddressHash['pincode']
                #validation check
                if vpin =~ /^[[:digit:]]+$/
                  @leadAdd = LeadAddress.create(leadaddressHash)
                  @leadAdd.parentKey = @key
                  @leadAdd.save()
                else
                  err = 1
                  @vpinerr = "Pincode is invalid"
                end
              end
            end

            if @params['leadcontact']
              leadconArray = @params['leadcontact']
              arrcount2 = leadconArray.count
              for k in 1..arrcount2
                h=(k-1).to_s
                leadconHash = leadconArray[h]
                #validation
                vhome = leadconHash['home']
                vmobile = leadconHash['mobile']
                vemail = leadconHash['email']
                #validation check
                if (vhome =~ /^[[:digit:]]+$/) and (vmobile =~ /^[[:digit:]]+$/) and (vemail =~ /\A([\w+\-]\.?)+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i)
                  @leadcontact = LeadContact.create(leadconHash)
                  @leadcontact.parentKey = @key
                  @leadcontact.save()
                else
                  err = 1
                  @contacterr = "Contact Details are invalid"
                end
              end
            end

            if err == 0
              redirect :action => :index
            else
              redirect :action => :edit, :id => @lead.object
            end
        end
      end

    # GET /Lead/{1}
      def show
        @lead = Lead.find(@params['id'])
        @leadadd = LeadAddress.find(:all,
                                        :conditions => {:parentKey => @lead.object}
                                    )
        @leadcontact = LeadContact.find(:all,
                                        :conditions => {:parentKey => @lead.object}
                                        )

        if @lead
          render :action => :show, :back => url_for(:action => :index)
        else
          redirect :action => :index
        end
      end

      # GET /Lead/{1}/edit
      def edit
        @lead = Lead.find(@params['id'])
        @leadaddress = LeadAddress.find(:all,
                                        :conditions => {:parentKey => @lead.object}
                                    )
        @leadcontact = LeadContact.find(:all,
                                        :conditions => {:parentKey => @lead.object}
                                       )
        @vpinerr2 = @vpinerr

        if @lead
          render :action => :new, :back => url_for(:action => :index)
        else
          redirect :action => :index
        end
      end

    end


问:
Make a whole div clickable in order to launch a _blank document
How can I write the _blank statement in this location.href call?

```<code>  <div onclick="location.href='http://www.test.com';" style="display:block; height:40px; width:100px; cursor:pointer;"></div>
</code>```

Please note: I need to keep the div and treat it as a href container.

When someone clicks it should open a new browser window, not a popup box.

答:
or using jquery:

```<code>$(this).click(function(){

$(this).open(
{
 width: 400,
 height: 250,
 scrollbars: false
});
</code>```

});

Body:
How can I write the _blank statement in this location.href call?

Please note: I need to keep the div and treat it as a href container.

When someone clicks it should open a new browser window, not a popup box.

Body:
or using jquery:

$(this).click(function(){

$(this).open(
{
 width: 400,
 height: 250,
 scrollbars: false
});

});


问:
Given When Then Testing - Do I NEED a "When"?
I am implementing some smoke tests to our website.

I'm using a Given/When/Then format for existing automated acceptance tests/User stories. But now I want to do an initial smoke test of:

Given I'm on the homepage

Then I should see "Welcome To The Site"

Am I missing something? Is it "ok" to not have a When?

Tools Used: MVC3, SpecFlow, Nunit, Watin

答:
I tend to see Given as the equivalent of traditional pre-conditions.  When as the equivalent of the test action. And Then as the equivalent of the expected result.

Therefore, if there are no pre-conditions, I would leave out Given and simply focus on When and Then:

```<code>When I'm on the homepage
Then I should see "Welcome To The Site"
</code>```

Specflow will allow you to use Given or When, but Visual Studio will also allow you to write a single class that is 1000's of lines long.  Just because both are possible, does not mean either is 'right'.

Body:
I tend to see Given as the equivalent of traditional pre-conditions.  When as the equivalent of the test action. And Then as the equivalent of the expected result.

Therefore, if there are no pre-conditions, I would leave out Given and simply focus on When and Then:

When I'm on the homepage
Then I should see "Welcome To The Site"

Specflow will allow you to use Given or When, but Visual Studio will also allow you to write a single class that is 1000's of lines long.  Just because both are possible, does not mean either is 'right'.


问:
Error after importing project to Android Studio
I have received an old code, coded in 2014 and I was requested to update some functionalities.

I am having problems running the code, for it was built on Eclipse and now I imported it to Android Studio.

First of all, the code calls 3 libraries that are included in the project, one of them is in cpp. This is why I think it was needed to add the bundle-ndk.

I added: android.useDeprecatedNdk=true to gradle-wrapper.properties

These are the gradle files I currently have:

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}
</code>```

First Library Gradle

```<code>apply plugin: 'com.android.library'

android {
    compileSdkVersion 16
    buildToolsVersion "23.0.3"

    defaultConfig {
        minSdkVersion 5
        targetSdkVersion 16
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}
</code>```

Second Library

```<code>apply plugin: 'com.android.library'

android {
    compileSdkVersion 16
    buildToolsVersion "23.0.3"

    defaultConfig {
        minSdkVersion 5
        targetSdkVersion 5
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}

dependencies {
    compile project(':FirstLibrary')
    compile 'com.android.support:support-v4:18.0.0'
    compile files('libs/libGoogleAnalyticsV2.jar')
}
</code>```

Third Library

```<code>apply plugin: 'com.android.library'

android {
    compileSdkVersion 16
    buildToolsVersion "23.0.3"

    defaultConfig {
        minSdkVersion 5
        targetSdkVersion 7
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}

dependencies {
    compile 'com.android.support:support-v4:18.0.0'
}
</code>```

Module Gradle of Project

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 8
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.application.id"
        minSdkVersion 8
        targetSdkVersion 17
    }

    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-project.txt'
        }
    }
}

dependencies {
    compile project(':secondLbrary')
    compile project(':thirdLibrary')
}
</code>```

Latest Error Received:

Error:Execution failed for task ':library:compileDebugNdk'.

Error: Your project contains C++ files but it is not using a supported native build system.
Consider using CMake or ndk-build integration with the stable Android Gradle plugin:
https://developer.android.com/studio/projects/add-native-code.html
or use the experimental plugin:
http://tools.android.com/tech-docs/new-build-system/gradle-experimental.

What can I do to investigate this?

答:
This is usually related to gradle version - you should update to recent version and try again. Look here Plugin is too old.

Also - why do you need "com.android.tools.build:gradle-experimental:0.7.0-alpha4"?

Body:
I have received an old code, coded in 2014 and I was requested to update some functionalities.

I am having problems running the code, for it was built on Eclipse and now I imported it to Android Studio.

First of all, the code calls 3 libraries that are included in the project, one of them is in cpp. This is why I think it was needed to add the bundle-ndk.

I added: android.useDeprecatedNdk=true to gradle-wrapper.properties

These are the gradle files I currently have:

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

First Library Gradle

apply plugin: 'com.android.library'

android {
    compileSdkVersion 16
    buildToolsVersion "23.0.3"

    defaultConfig {
        minSdkVersion 5
        targetSdkVersion 16
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}

Second Library

apply plugin: 'com.android.library'

android {
    compileSdkVersion 16
    buildToolsVersion "23.0.3"

    defaultConfig {
        minSdkVersion 5
        targetSdkVersion 5
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}

dependencies {
    compile project(':FirstLibrary')
    compile 'com.android.support:support-v4:18.0.0'
    compile files('libs/libGoogleAnalyticsV2.jar')
}

Third Library

apply plugin: 'com.android.library'

android {
    compileSdkVersion 16
    buildToolsVersion "23.0.3"

    defaultConfig {
        minSdkVersion 5
        targetSdkVersion 7
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}

dependencies {
    compile 'com.android.support:support-v4:18.0.0'
}

Module Gradle of Project

apply plugin: 'com.android.application'

android {
    compileSdkVersion 8
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.application.id"
        minSdkVersion 8
        targetSdkVersion 17
    }

    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-project.txt'
        }
    }
}

dependencies {
    compile project(':secondLbrary')
    compile project(':thirdLibrary')
}

Latest Error Received:

Error:Execution failed for task ':library:compileDebugNdk'.

Error: Your project contains C++ files but it is not using a supported native build system.
Consider using CMake or ndk-build integration with the stable Android Gradle plugin:
https://developer.android.com/studio/projects/add-native-code.html
or use the experimental plugin:
http://tools.android.com/tech-docs/new-build-system/gradle-experimental.

What can I do to investigate this?


问:
Angular service is not returning error response
I am calling service saveRouteInfo(), but only success callback is getting invoked for both error and success in the controller.

Service

```<code>gisApp.factory('rpServc', function($http) {
      return {
          saveRouteInfo:function(routeInfo){
              return $http.post("/GISWebApp/gis/api/v1/route",routeInfo).then(
                  function(response)
                  {
                      return response.data;
                  }, function(response) {
                      return response.data;
                  });
            },
      };
});
</code>```

controller

```<code>rpServc.saveRouteInfo(routeInfo).then(function(data) {
    alert(JSON.stringify(data));

}, function(error) {
    alert(JSON.stringify(error));
});
</code>```

答:
Use $q</p>

```<code> gisApp.factory('rpServc', function($http, $q) {
        var deferred = $q.defer();
        return {
            saveRouteInfo:function(routeInfo){
                return $http.post("/GISWebApp/gis/api/v1/route", routeInfo).
                then(function(response) {
                  return response;
                }, function(reason) {
                  return $q.reject(reason);
                });
            },
        };
    });
</code>```

Body:
I am calling service saveRouteInfo(), but only success callback is getting invoked for both error and success in the controller.

Service

gisApp.factory('rpServc', function($http) {
      return {
          saveRouteInfo:function(routeInfo){
              return $http.post("/GISWebApp/gis/api/v1/route",routeInfo).then(
                  function(response)
                  {
                      return response.data;
                  }, function(response) {
                      return response.data;
                  });
            },
      };
});

controller

rpServc.saveRouteInfo(routeInfo).then(function(data) {
    alert(JSON.stringify(data));

}, function(error) {
    alert(JSON.stringify(error));
});

Body:
Use $q

 gisApp.factory('rpServc', function($http, $q) {
        var deferred = $q.defer();
        return {
            saveRouteInfo:function(routeInfo){
                return $http.post("/GISWebApp/gis/api/v1/route", routeInfo).
                then(function(response) {
                  return response;
                }, function(reason) {
                  return $q.reject(reason);
                });
            },
        };
    });


问:
Applescript command to move files in current folder with *.extension to the folder with Name inside this folder
I'm newbie in Scripting. Can you please help with this:

I need to move files with *.extension in current (selected) folder to the folder with Name inside this current (selected) folder.

for example: Move all .zip files in Folder 1, to the folder ZIP inside Folder 1. But I need to use it as a service (something like: select Folder 1, control+click "Move all zip to ZIP")

Thanks guys!

答:
Updated Answer - More automated and with a context menu/item

You can add a context item to Finder's menu (Finder > Services), which will only appear when you have a folder selected (the one you want to move the files from.)

This is what you'll see when you have a folder selected:

Follow these steps

1. Open the "Automator" application. (command + spacebar & type ""Automator" to find)

2. Press "New Document" (bottom left corner), if this doesn't show just do command + n

3. Select "Service" (One with the gear icon) and press enter.

4. Select these options in the top bar, so it looks like this:

In the search field, type in "Run AppleScript"

Drag it into the blank space on the right:

7. Delete all the script in there and paste in my script instead:

```<code>on run {input, parameters}
    set fromFolder to item 1 of input
    -- Choose the file extension to be moved
    set fileExtension to text returned of (display dialog "Please enter the file extension you want to move." default answer "zip")
    -- This will put the files in a folder inside your selected folder with the name of the file extension
    -- e.g. move txt files in Kamil:Desktop:TextStuff will move it into Kamil:Desktop:TextStuff:txt
    -- Change it to what suits your needs
    set toFolder to fromFolder & fileExtension as string

    -- Finder will handle the moving of files
    tell application "Finder"

        set filesMoved to (every file of folder fromFolder whose name ends with fileExtension)
        move filesMoved to folder toFolder

        display notification "Into \"" & toFolder & "\"" with title "Moved " & (count of filesMoved) & " " & fileExtension & " files"

    end tell

end run
</code>```

7. Press command + s and give it the name you want and press save.

8. Now quit Automator

Now open a Finder window and select a folder with a folder created inside it named the file extension you will be sorting; go to Finder > Services > [What you named it],
type in the file extension and press enter.

You should see a notification when it's done moving the files, which tells you how many were moved and to which folder.

I hope this better answers your request, and if does, don't forget to mark it as the answer, otherwise, comment on it and l'll see what I can do.

Body:
Updated Answer - More automated and with a context menu/item

You can add a context item to Finder's menu (Finder > Services), which will only appear when you have a folder selected (the one you want to move the files from.)

This is what you'll see when you have a folder selected:

Follow these steps

1. Open the "Automator" application. (command + spacebar & type ""Automator" to find)

2. Press "New Document" (bottom left corner), if this doesn't show just do command + n

3. Select "Service" (One with the gear icon) and press enter.

4. Select these options in the top bar, so it looks like this:

In the search field, type in "Run AppleScript"

Drag it into the blank space on the right:

7. Delete all the script in there and paste in my script instead:

on run {input, parameters}
    set fromFolder to item 1 of input
    -- Choose the file extension to be moved
    set fileExtension to text returned of (display dialog "Please enter the file extension you want to move." default answer "zip")
    -- This will put the files in a folder inside your selected folder with the name of the file extension
    -- e.g. move txt files in Kamil:Desktop:TextStuff will move it into Kamil:Desktop:TextStuff:txt
    -- Change it to what suits your needs
    set toFolder to fromFolder & fileExtension as string

    -- Finder will handle the moving of files
    tell application "Finder"

        set filesMoved to (every file of folder fromFolder whose name ends with fileExtension)
        move filesMoved to folder toFolder

        display notification "Into \"" & toFolder & "\"" with title "Moved " & (count of filesMoved) & " " & fileExtension & " files"

    end tell

end run

7. Press command + s and give it the name you want and press save.

8. Now quit Automator

Now open a Finder window and select a folder with a folder created inside it named the file extension you will be sorting; go to Finder > Services > [What you named it],
type in the file extension and press enter.

You should see a notification when it's done moving the files, which tells you how many were moved and to which folder.

I hope this better answers your request, and if does, don't forget to mark it as the answer, otherwise, comment on it and l'll see what I can do.


问:
What are practical guidelines for evaluating a language's "Turing Completeness"?
I've read "what-is-turing-complete" and the wikipedia page, but I'm less interested in a formal proof than in the practical implications of requirements for being Turing Complete.

What I'm actually trying to decide is if the toy language I've just designed could be used as a general-purpose language.  I know I can prove it is if I can write a Turing machine with it.  But I don't want to go through that exercise until I'm fairly certain of success.

Is there a minimum set of features without which Turing Completeness is impossible?
Is there a set of features which virtually guarantees completeness?

(My guess is that conditional branching and a readable/writeable memory store will get me most of the way there)

EDIT:

I think I've gone off on a tangent by saying "Turing Complete".   I'm trying to guess with reasonable confidence that a newly invented language with a certain feature set (or alternately, a VM with a certain instruction set) would be able to compute anything worth computing.  I know that proving you can build a Turing machine with it is one way, but not the only way.

What I was hoping for was a set of guidelines like: "if a language can do X,Y,and Z, it can probably do anything".

答: I cannot remember seeing anything like minimum features for Turing Completeness. However, if your language supports loops and conditional branches, the chances that it is Turing complete is good. However, the only way to prove it is still to similate a Turing Machine or another Turing Complete language.

OwnerDisplayName: AShelly

LastEditorDisplayName: AShelly

OwnerDisplayName: PolyThinker


问:
Swift compiler segmentation fault using `ReferenceWritableKeyPath `
Using a ReferenceWritaleKeyPath to read a property is causing a compiler segmentation fault.

I am setting up a helper to simplify binding two variables. With help from OOPer I got the basic binding to work, but if modify the code as shown below to check the values are different before doing the binding it has a segmentation fault.

```<code>protocol Bindable: class {
    var observers: [NSKeyValueObservation] {get set}
}

extension Bindable {
    func bind<Value>(to targetKeyPath: ReferenceWritableKeyPath<Self, Value>, from sourceKeyPath: KeyPath<Self, Value>)
        where Self: NSObject {
        self.observers.append( self.observe(sourceKeyPath, options: [.initial, .new]) {object, change in

            // FAILS: compiler failed due to signal: Segmentation fault: 11
            if( self[keyPath:targetKeyPath] != change.newValue ) {
                self[keyPath: targetKeyPath] = change.newValue!
            }
        })
    }
}
</code>```

答:
The problem is that you attempt to use != with the generic type Value, which does not necessarily have == and != implementations. Replacing <Value> by <Value: Equatable> solves it.

Having said that, the compiler crashing with a segmentation fault is always a bug, regardless of whether your code is correct or not. You should consider filing a bug report at https://bugs.swift.org if you have time.

Body:
Using a ReferenceWritaleKeyPath to read a property is causing a compiler segmentation fault.

I am setting up a helper to simplify binding two variables. With help from OOPer I got the basic binding to work, but if modify the code as shown below to check the values are different before doing the binding it has a segmentation fault.

protocol Bindable: class {
    var observers: [NSKeyValueObservation] {get set}
}

extension Bindable {
    func bind<Value>(to targetKeyPath: ReferenceWritableKeyPath<Self, Value>, from sourceKeyPath: KeyPath<Self, Value>)
        where Self: NSObject {
        self.observers.append( self.observe(sourceKeyPath, options: [.initial, .new]) {object, change in

            // FAILS: compiler failed due to signal: Segmentation fault: 11
            if( self[keyPath:targetKeyPath] != change.newValue ) {
                self[keyPath: targetKeyPath] = change.newValue!
            }
        })
    }
}


问:
proper way of doing auto complete dropdown in angular 2
hello friends I am new in angular 2 I find the way to auto complete dropdown I tried the ng2-select but it did not work for me. is there is another npm that work with angular 2. as the functionality is we also set the selected value for the dropdown as well? if you know any npm that provide autocomplete as well as set the initial value as well then suggest me thank u.</p>

答: You can check out Material 2: https://material.angular.io/components/autocomplete/overview</p>


问:
Why is akima::interp interpolating outside the bounds of the original data? - R
If I am using the quakes dataset and the tidyverse to plot an interpolation using the akima package, I am attempting to do it like this:

```<code>library(tidyverse)
library(akima)
</code>```

A function to interpolate:

```<code>## Interpolation and convert to a dataframe
dpinterp <- function(x,y,z) {
  interp_df <- interp(x = x, y = y, z = z, duplicate = "strip", extrap = FALSE, nx = 100, ny = 100)
  interp2xyz(interp_df, data.frame=TRUE)
}
</code>```

Find the max depth for each stations variable. Choosing the stations subset less than 34 for ease of analysis:

```<code>quakes_sub <- quakes %>%
  filter(stations <= 34) %>%
  group_by(stations) %>%
  summarise(depth = max(depth)) %>%
  mutate(mag = 4)
</code>```

A pipe to complete the interpolation then some data cleaning/wrangling:

```<code>quakes_interp <- quakes %>%
  filter(stations <= 34) %>%
  do(dpinterp(x = .$stations, y = .$depth, z = .$mag)) %>%
  filter(!is.na(z)) %>%
  rename(stations = x, depth = y, mag = z)
</code>```

A plot to visualization and illustrate how the interpolation extends beyond the raw data points. Points in blue:

```<code>quakes_interp %>%
  ggplot(aes(x = stations, y = depth, z = mag, fill = mag)) +
  geom_tile() +
  scale_y_reverse(expand = c(0,0)) +
  scale_x_continuous(expand = c(0, 0)) +
  #geom_vline(data = quakes_sub, aes(xintercept = stations, colour= depth)) +
  geom_point(data = quakes_sub, aes(x = stations, y = depth, colour = mag)) +
  #stat_contour(aes(fill=..level..), geom="polygon", binwidth=0.005) +
  #geom_contour(color = "white", alpha = 0.5) +
  #geom_text(data = meta_data, aes(label = Station)) +
  scale_fill_distiller(palette="RdYlGn",
                       na.value="white") +
  theme_minimal()
</code>```

Question: Is there a way to constrain an interpolation such that it does not extend beyond the original raw data?

Session Info

```<code>R version 3.4.0 (2017-04-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

Matrix products: default

locale:
[1] LC_COLLATE=English_Canada.1252  LC_CTYPE=English_Canada.1252    LC_MONETARY=English_Canada.1252
[4] LC_NUMERIC=C                    LC_TIME=English_Canada.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] bindrcpp_0.2       padr_0.3.0         lubridate_1.6.0    akima_0.6-2        readxl_1.0.0       dplyr_0.7.1
 [7] purrr_0.2.2.2      readr_1.1.1        tidyr_0.6.3        tibble_1.3.3       ggplot2_2.2.1.9000 tidyverse_1.1.1

loaded via a namespace (and not attached):
 [1] reshape2_1.4.2     haven_1.0.0        lattice_0.20-35    colorspace_1.3-2   htmltools_0.3.6    yaml_2.1.14
 [7] rlang_0.1.1        foreign_0.8-67     glue_1.1.1         RColorBrewer_1.1-2 sp_1.2-4           modelr_0.1.0
[13] fortunes_1.5-4     bindr_0.1          plyr_1.8.4         stringr_1.2.0      munsell_0.4.3      gtable_0.2.0
[19] cellranger_1.1.0   rvest_0.3.2        psych_1.7.5        evaluate_0.10      labeling_0.3       knitr_1.16
[25] forcats_0.2.0      parallel_3.4.0     broom_0.4.2        Rcpp_0.12.11       scales_0.4.1       backports_1.1.0
[31] jsonlite_1.5       mnormt_1.5-5       hms_0.3            digest_0.6.12      stringi_1.1.5      grid_3.4.0
[37] rprojroot_1.2      tools_3.4.0        magrittr_1.5       lazyeval_0.2.0     pkgconfig_2.0.1    swtext_0.0.1
[43] xml2_1.1.1         assertthat_0.2.0   rmarkdown_1.6      httr_1.2.1         R6_2.2.1           nlme_3.1-131
[49] compiler_3.4.0
</code>```

答:
The data you are interpolating from comes from quakes with stations less than or equal to 34:

```<code>quakes_interp <- quakes %>%
  filter(stations <= 34) %>%
  do(dpinterp(x = .$stations, y = .$depth, z = .$mag))
</code>```

Let's just extract those:

```<code>> qdata = quakes %>% filter(stations <=34)
</code>```

And now lets plot the locations that interp has interpolated at:

```<code>> plot(quakes_interp$stations, quakes_interp$depth)
</code>```

And now add the data points on top:

```<code>> points(qdata$stations,qdata$depth,col="red",pch=19)
</code>```

And for good measure add the convex hull of the original data points:

```<code>> lines(
    qdata[
        chull(qdata$stations, qdata$depth),
        c("stations","depth")],lwd=2)
</code>```

(upside-down compared to yours)

Your question was "Is there a way to constrain an interpolation such that it does not extend beyond the original raw data?" and I seem to have demonstrated that it doesn't, where the definition of "beyond" is the convex hull.

If you did a separate interp for each station then interp wouldn't go beyond the min and max value for depth, because you would have a one-dimensional case (mag~depth) and the convex hull in one dimension is defined by the min and max of the dimension.

interp is designed for interpolating on continuous coordinates. Your thinking that it shouldn't go beyond the max(depth) for each station is not applicable. Station is, to interps eyes, a continuous coordinate like coordinates in space. In most cases with continuous coordinates the max(x) for any y is going to be the one value of x that goes with that y, because y, being continuous, has only unique values.

The convex hull is one answer to the question of "what is the region of interest for this set of coordinate points?". Other answers may be "the rectangular bounding box [min(x),max(x),min(y),max(y)]" or "The concave hull alpha shape defined by alpha=0.2", or "the coastline of France". If you want to restrict your region of interest that only extends as far as the max(depth) for each station then you need to clip the output of interp manually.

But interp may be totally inappropriate here - if stations is discrete on integers then the value of an interpolation at stations==3.75 may be meaningless.

Actually, interp is probably even wronger. It interpolates based on equality of the coordinates, such that a difference of 1 station is the same as a difference of 1 depth unit. This explains the appearance of horizontal stripes in your plot. If you do the plot with an aspect ratio of 1 by adding coord_equal() to your ggplot you'll see the actual 2d surface that interp is working with.

Body:
If I am using the quakes dataset and the tidyverse to plot an interpolation using the akima package, I am attempting to do it like this:

library(tidyverse)
library(akima)

A function to interpolate:

## Interpolation and convert to a dataframe
dpinterp <- function(x,y,z) {
  interp_df <- interp(x = x, y = y, z = z, duplicate = "strip", extrap = FALSE, nx = 100, ny = 100)
  interp2xyz(interp_df, data.frame=TRUE)
}

Find the max depth for each stations variable. Choosing the stations subset less than 34 for ease of analysis:

quakes_sub <- quakes %>%
  filter(stations <= 34) %>%
  group_by(stations) %>%
  summarise(depth = max(depth)) %>%
  mutate(mag = 4)

A pipe to complete the interpolation then some data cleaning/wrangling:

quakes_interp <- quakes %>%
  filter(stations <= 34) %>%
  do(dpinterp(x = .$stations, y = .$depth, z = .$mag)) %>%
  filter(!is.na(z)) %>%
  rename(stations = x, depth = y, mag = z)

A plot to visualization and illustrate how the interpolation extends beyond the raw data points. Points in blue:

quakes_interp %>%
  ggplot(aes(x = stations, y = depth, z = mag, fill = mag)) +
  geom_tile() +
  scale_y_reverse(expand = c(0,0)) +
  scale_x_continuous(expand = c(0, 0)) +
  #geom_vline(data = quakes_sub, aes(xintercept = stations, colour= depth)) +
  geom_point(data = quakes_sub, aes(x = stations, y = depth, colour = mag)) +
  #stat_contour(aes(fill=..level..), geom="polygon", binwidth=0.005) +
  #geom_contour(color = "white", alpha = 0.5) +
  #geom_text(data = meta_data, aes(label = Station)) +
  scale_fill_distiller(palette="RdYlGn",
                       na.value="white") +
  theme_minimal()

Question: Is there a way to constrain an interpolation such that it does not extend beyond the original raw data?

Session Info

R version 3.4.0 (2017-04-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

Matrix products: default

locale:
[1] LC_COLLATE=English_Canada.1252  LC_CTYPE=English_Canada.1252    LC_MONETARY=English_Canada.1252
[4] LC_NUMERIC=C                    LC_TIME=English_Canada.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] bindrcpp_0.2       padr_0.3.0         lubridate_1.6.0    akima_0.6-2        readxl_1.0.0       dplyr_0.7.1
 [7] purrr_0.2.2.2      readr_1.1.1        tidyr_0.6.3        tibble_1.3.3       ggplot2_2.2.1.9000 tidyverse_1.1.1

loaded via a namespace (and not attached):
 [1] reshape2_1.4.2     haven_1.0.0        lattice_0.20-35    colorspace_1.3-2   htmltools_0.3.6    yaml_2.1.14
 [7] rlang_0.1.1        foreign_0.8-67     glue_1.1.1         RColorBrewer_1.1-2 sp_1.2-4           modelr_0.1.0
[13] fortunes_1.5-4     bindr_0.1          plyr_1.8.4         stringr_1.2.0      munsell_0.4.3      gtable_0.2.0
[19] cellranger_1.1.0   rvest_0.3.2        psych_1.7.5        evaluate_0.10      labeling_0.3       knitr_1.16
[25] forcats_0.2.0      parallel_3.4.0     broom_0.4.2        Rcpp_0.12.11       scales_0.4.1       backports_1.1.0
[31] jsonlite_1.5       mnormt_1.5-5       hms_0.3            digest_0.6.12      stringi_1.1.5      grid_3.4.0
[37] rprojroot_1.2      tools_3.4.0        magrittr_1.5       lazyeval_0.2.0     pkgconfig_2.0.1    swtext_0.0.1
[43] xml2_1.1.1         assertthat_0.2.0   rmarkdown_1.6      httr_1.2.1         R6_2.2.1           nlme_3.1-131
[49] compiler_3.4.0

Body:
The data you are interpolating from comes from quakes with stations less than or equal to 34:

quakes_interp <- quakes %>%
  filter(stations <= 34) %>%
  do(dpinterp(x = .$stations, y = .$depth, z = .$mag))

Let's just extract those:

> qdata = quakes %>% filter(stations <=34)

And now lets plot the locations that interp has interpolated at:

> plot(quakes_interp$stations, quakes_interp$depth)

And now add the data points on top:

> points(qdata$stations,qdata$depth,col="red",pch=19)

And for good measure add the convex hull of the original data points:

> lines(
    qdata[
        chull(qdata$stations, qdata$depth),
        c("stations","depth")],lwd=2)

(upside-down compared to yours)

Your question was "Is there a way to constrain an interpolation such that it does not extend beyond the original raw data?" and I seem to have demonstrated that it doesn't, where the definition of "beyond" is the convex hull.

If you did a separate interp for each station then interp wouldn't go beyond the min and max value for depth, because you would have a one-dimensional case (mag~depth) and the convex hull in one dimension is defined by the min and max of the dimension.

interp is designed for interpolating on continuous coordinates. Your thinking that it shouldn't go beyond the max(depth) for each station is not applicable. Station is, to interps eyes, a continuous coordinate like coordinates in space. In most cases with continuous coordinates the max(x) for any y is going to be the one value of x that goes with that y, because y, being continuous, has only unique values.

The convex hull is one answer to the question of "what is the region of interest for this set of coordinate points?". Other answers may be "the rectangular bounding box [min(x),max(x),min(y),max(y)]" or "The concave hull alpha shape defined by alpha=0.2", or "the coastline of France". If you want to restrict your region of interest that only extends as far as the max(depth) for each station then you need to clip the output of interp manually.

But interp may be totally inappropriate here - if stations is discrete on integers then the value of an interpolation at stations==3.75 may be meaningless.

Actually, interp is probably even wronger. It interpolates based on equality of the coordinates, such that a difference of 1 station is the same as a difference of 1 depth unit. This explains the appearance of horizontal stripes in your plot. If you do the plot with an aspect ratio of 1 by adding coord_equal() to your ggplot you'll see the actual 2d surface that interp is working with.


问:
Query for xml values in sql server
I have xml field in the below table in Data column

ID | website | Data

Following is the xml field

```<code><Product>
 <field name="IsCustomer" type="System.Boolean, mscorlib">
    <boolean>false</boolean>
  </field>
</product>
</code>```

I need to retrieve all the IsCustomer values in my table.

Following is the code part that I tried so far.

```<code>SELECT EMP.ED.value() as EmployeeID
FROM   [dbo].[Products]
CROSS APPLY Data.nodes('/Product/Field[@Name="IsCustomer"]/Boolean') as EMP(ED)
</code>```

Can anyone please help me?

答:
I already wrote a post about XQuerying which might be helpful to you.

Note: XQuerying is case sensitive and you need to position yourself properly. Take a look at the post i linked, and if it does not help i will update this comment with a solution regarding your query

Update

To answer your question

First and foremost you need to have properly formatted XML, which means tags need to match their case sensitivity, and same rule applies when you are referencing a tag in a XQuery.

So one of the solutions would be :

```<code>DECLARE @XML as XML
SET @XML = '<Product>
 <field name="IsCustomer" type="System.Boolean, mscorlib">
    <boolean>false</boolean>
  </field>
</Product>'

SELECT EMP.t.value('boolean[1]','varchar(20)') as EmployeeID
FROM   @XML.nodes('/Product/field') as EMP(t)
</code>```

Title: Query for xml values in sql server

Body:
I have xml field in the below table in Data column

ID | website | Data

Following is the xml field

<Product>
 <field name="IsCustomer" type="System.Boolean, mscorlib">
    <boolean>false</boolean>
  </field>
</product>

I need to retrieve all the IsCustomer values in my table.

Following is the code part that I tried so far.

SELECT EMP.ED.value() as EmployeeID
FROM   [dbo].[Products]
CROSS APPLY Data.nodes('/Product/Field[@Name="IsCustomer"]/Boolean') as EMP(ED)

Can anyone please help me?

Body:
I already wrote a post about XQuerying which might be helpful to you.

Note: XQuerying is case sensitive and you need to position yourself properly. Take a look at the post i linked, and if it does not help i will update this comment with a solution regarding your query

Update

To answer your question

First and foremost you need to have properly formatted XML, which means tags need to match their case sensitivity, and same rule applies when you are referencing a tag in a XQuery.

So one of the solutions would be :

DECLARE @XML as XML
SET @XML = '<Product>
 <field name="IsCustomer" type="System.Boolean, mscorlib">
    <boolean>false</boolean>
  </field>
</Product>'

SELECT EMP.t.value('boolean[1]','varchar(20)') as EmployeeID
FROM   @XML.nodes('/Product/field') as EMP(t)


问:
do-while with Java8-Optional
I'm frequently using the do-while-checkNextForNull-getNext looping pattern (don't know if there is an official name for it) in some of my projects. But in Java8, the use of Optional is considered as cleaner code than checking for null references in client-code. But when using Optional in this looping pattern, the code gets a bit verbose and ugly, but because Optional has some handy methodS, I would expect that there must exist a cleaner way than the one I came up with below.

Example:

Given the following class.

```<code>class Item {
    int nr;

    Item(nr) {
        this.nr = nr;
        // an expensive operation
    }

    Item next() {
        return ...someCondition....
            ? new Item(nr + 1)
            : null;
    }
}
</code>```

In which the first item always has nr==1 and each item determines the next item, and you don't want to create unnecessary new items.

I can use the following looping do-while-checkNextForNull-getNext pattern in client-code:

```<code>Item item = new Item(1);
do {
    // do something with the item ....
} while ((item = item.next()) != null);
</code>```

With Java8-Optional, the given class becomes:

```<code>class Item {
    ....

    Optional<Item> next() {
        return ...someCondition....
            ? Optional.of(new Item(nr + 1))
            : Optional.empty();
    }
}
</code>```

And then the do-while-checkNextForNull-getNext looping pattern becomes a bit ugly and verbose:

```<code>Item item = new Item(1);
do {
    // do something with the item ....
} while ((item = item.next().orElse(null)) != null);
</code>```

The orElse(null)) != null part feels uncomfortable.

I have looked for other kind of loops, but haven't found a better one. Is there a cleaner solution?

Update:

It is possible to use a for-each loop while at the same time avoiding null-references (the use of null-references is considered as a bad practice). This solution has been proposed by Xavier Delamotte, and doesn't need Java8-Optional.

Implementation with a generic iterator:

```<code>public class Item implements Iterable<Item>, Iterator<Item> {
    int nr;

    Item(int nr) {
        this.nr = nr;
        // an expensive operation
    }

    public Item next() {
        return new Item(nr + 1);
    }

    public boolean hasNext() {
        return ....someCondition.....;
    }

    @Override
    public Iterator<Item> iterator() {
        return new CustomIterator(this);
    }
}
</code>```

and

```<code>class CustomIterator<T extends Iterator<T>> implements Iterator<T> {
    T currentItem;
    boolean nextCalled;

    public CustomIterator(T firstItem) {
        this.currentItem = firstItem;
    }

    @Override
    public boolean hasNext() {
        return currentItem.hasNext();
    }

    @Override
    public T next() {
        if (! nextCalled) {
            nextCalled = true;
            return currentItem;
        } else {
            currentItem = currentItem.next();
            return currentItem;
        }
    }
}
</code>```

Then client code becomes very simple/clean:

```<code>for (Item item : new Item(1)) {
    // do something with the item ....
}
</code>```

Although this may be seen as a violation of the Iterator contract because the new Item(1) object is included in the loop, whereas normally, the for loop would immediately call next() and thus skipping the first object. In other words: for the first object, next() is violated because it returnS the first object itself.

答:
Since this is related to some kind of design i come up with below design.

Create interface which support to provide optional next.

```<code>public interface NextProvidble<T> {

    Optional<T> next();
}
</code>```

Item implement NextProvidble interface.

```<code>public class Item implements NextProvidble<Item> {
    int nr;

    Item(int nr) {
        this.nr = nr;
        // an expensive operation
    }

    @Override
    public Optional<Item> next() {
        return /*...someCondition....*/ nr < 10 ? Optional.of(new Item(nr + 1)) : Optional.empty();
    }

    @Override
    public String toString() {
        return "NR : " + nr;
    }
}
</code>```

Here i use /...someCondition..../ as  nr < 10

And new class for Custom Do While as below.

```<code>public abstract class CustomDoWhile<T extends NextProvidble<T>> {

    public void operate(T t) {
        doOperation(t);
        Optional<T> next = t.next();
        next.ifPresent( nextT -> operate(nextT));
    }

    protected abstract void doOperation(T t);
}
</code>```

Now what you have to done in your client code.

```<code> new CustomDoWhile<Item>() {
            @Override
            protected void doOperation(Item item) {
                System.out.println(item.toString());
            }
        }.operate(new Item(1));
</code>```

It may very clear.
Please add your thoughts.

Title: do-while with Java8-Optional

Body:
I'm frequently using the do-while-checkNextForNull-getNext looping pattern (don't know if there is an official name for it) in some of my projects. But in Java8, the use of Optional is considered as cleaner code than checking for null references in client-code. But when using Optional in this looping pattern, the code gets a bit verbose and ugly, but because Optional has some handy methodS, I would expect that there must exist a cleaner way than the one I came up with below.

Example:

Given the following class.

class Item {
    int nr;

    Item(nr) {
        this.nr = nr;
        // an expensive operation
    }

    Item next() {
        return ...someCondition....
            ? new Item(nr + 1)
            : null;
    }
}

In which the first item always has nr==1 and each item determines the next item, and you don't want to create unnecessary new items.

I can use the following looping do-while-checkNextForNull-getNext pattern in client-code:

Item item = new Item(1);
do {
    // do something with the item ....
} while ((item = item.next()) != null);

With Java8-Optional, the given class becomes:

class Item {
    ....

    Optional<Item> next() {
        return ...someCondition....
            ? Optional.of(new Item(nr + 1))
            : Optional.empty();
    }
}

And then the do-while-checkNextForNull-getNext looping pattern becomes a bit ugly and verbose:

Item item = new Item(1);
do {
    // do something with the item ....
} while ((item = item.next().orElse(null)) != null);

The orElse(null)) != null part feels uncomfortable.

I have looked for other kind of loops, but haven't found a better one. Is there a cleaner solution?

Update:

It is possible to use a for-each loop while at the same time avoiding null-references (the use of null-references is considered as a bad practice). This solution has been proposed by Xavier Delamotte, and doesn't need Java8-Optional.

Implementation with a generic iterator:

public class Item implements Iterable<Item>, Iterator<Item> {
    int nr;

    Item(int nr) {
        this.nr = nr;
        // an expensive operation
    }

    public Item next() {
        return new Item(nr + 1);
    }

    public boolean hasNext() {
        return ....someCondition.....;
    }

    @Override
    public Iterator<Item> iterator() {
        return new CustomIterator(this);
    }
}

and

class CustomIterator<T extends Iterator<T>> implements Iterator<T> {
    T currentItem;
    boolean nextCalled;

    public CustomIterator(T firstItem) {
        this.currentItem = firstItem;
    }

    @Override
    public boolean hasNext() {
        return currentItem.hasNext();
    }

    @Override
    public T next() {
        if (! nextCalled) {
            nextCalled = true;
            return currentItem;
        } else {
            currentItem = currentItem.next();
            return currentItem;
        }
    }
}

Then client code becomes very simple/clean:

for (Item item : new Item(1)) {
    // do something with the item ....
}

Although this may be seen as a violation of the Iterator contract because the new Item(1) object is included in the loop, whereas normally, the for loop would immediately call next() and thus skipping the first object. In other words: for the first object, next() is violated because it returnS the first object itself.

Body:
Since this is related to some kind of design i come up with below design.

Create interface which support to provide optional next.

public interface NextProvidble<T> {

    Optional<T> next();
}

Item implement NextProvidble interface.

public class Item implements NextProvidble<Item> {
    int nr;

    Item(int nr) {
        this.nr = nr;
        // an expensive operation
    }

    @Override
    public Optional<Item> next() {
        return /*...someCondition....*/ nr < 10 ? Optional.of(new Item(nr + 1)) : Optional.empty();
    }

    @Override
    public String toString() {
        return "NR : " + nr;
    }
}

Here i use /...someCondition..../ as  nr < 10

And new class for Custom Do While as below.

public abstract class CustomDoWhile<T extends NextProvidble<T>> {

    public void operate(T t) {
        doOperation(t);
        Optional<T> next = t.next();
        next.ifPresent( nextT -> operate(nextT));
    }

    protected abstract void doOperation(T t);
}

Now what you have to done in your client code.

 new CustomDoWhile<Item>() {
            @Override
            protected void doOperation(Item item) {
                System.out.println(item.toString());
            }
        }.operate(new Item(1));

It may very clear.
Please add your thoughts.


问:
How can I print a list of characters in a string using a for loop?
I want to print the all the characters from A to Z to display using for loop. This is what I have got so far:

```<code>string alpha = "A";

for(int i=0; i <= 25 ; i++)
{
   Console.WriteLine(Convert.ToChar(alpha[i] + 1));
}
</code>```

I know this code is not correct. Can anyone help me out?

答:
If you want to print every character in a string:

```<code>string alpha = "This is a string";
for(int i = 0, l = alpha.Length; i < l; i++) {
    Console.WriteLine(alpha[i]);
}

/** This will print:
* T
* h
* i
* s
* <space>
* i
* s
* <space>
* a
* <space>
* s
* t
* r
* i
* n
* g
*/
</code>```

But if you want to print from A to Z starting from a given character alpha:

```<code>char alpha = 'B'; //you should use char instead of string.
for (var c = alpha; c <= 'Z'; c++) {
    Console.WriteLine(c);
}
// this will of course print from B to Z
</code>```

Or if you really want to use the number 25:

```<code>char alpha = 'A';
for(int i=0; i <= 25 ; i++)
{
    Console.WriteLine(Convert.ToChar(alpha + i));
}
//this will print from A - Z, but if alpha = 'B', this will print from 'B' - '['
</code>```

Body:
I want to print the all the characters from A to Z to display using for loop. This is what I have got so far:

string alpha = "A";

for(int i=0; i <= 25 ; i++)
{
   Console.WriteLine(Convert.ToChar(alpha[i] + 1));
}

I know this code is not correct. Can anyone help me out?

Body:
If you want to print every character in a string:

string alpha = "This is a string";
for(int i = 0, l = alpha.Length; i < l; i++) {
    Console.WriteLine(alpha[i]);
}

/** This will print:
* T
* h
* i
* s
* <space>
* i
* s
* <space>
* a
* <space>
* s
* t
* r
* i
* n
* g
*/

But if you want to print from A to Z starting from a given character alpha:

char alpha = 'B'; //you should use char instead of string.
for (var c = alpha; c <= 'Z'; c++) {
    Console.WriteLine(c);
}
// this will of course print from B to Z

Or if you really want to use the number 25:

char alpha = 'A';
for(int i=0; i <= 25 ; i++)
{
    Console.WriteLine(Convert.ToChar(alpha + i));
}
//this will print from A - Z, but if alpha = 'B', this will print from 'B' - '['