问:
asp.net: How can I remove an item from a dropdownlist?
I have a dropdownlist, and in some cases need to remove an item (in the code-behind).  I need to remove the item based on the value of the item.

How can I do this?

Body: myDropDown.Items.Remove(myDropDown.Items.FindByText("Chicago"));


来源: stackexchange

问:
tracking request flow by ID in node.js
In my node.js application whenever I get request I'd like to "stamp" it with some unique ID and be able to track all the activities (log statements) related to this request by this ID. So when request comes in and I pass its handing to lower application layers (services, database calls etc) I want to be able to collect all logs matching given request ID to rebuild its journey through the app.

So having this picture, I use request-local module now, but it does some heavy magic that has just failed me (logs from multiple requests get the same ID).

The code is mostly based on Promises (not plain old node callbacks) and I use higher order functions to provide dependencies to my actual functions (with application tree being built during the start).

First and quite obvious solution would be to pass this request ID down to every function called, but it's a disaster and I'm not gonna do that.

How do you (reliably) do that kind of request tracking without explicitly passing this id/context as an extra argument to functions all levels down?

答:
I believe that what you're looking for is a logic flow id, which should be unique and generated upon every new request kicking in on your backend. If this assumption is correct, what I normally do is to create a middleware on my express router to generate a new and random flow id (with randomstring). To be sure that this flow id is unique, i add the timestamp to that. In order to pass this flow id to the next middlewares we should store it under res.locals (here the documentation )
Your middleware could look like this:

```<code>//middleware flow.js
var random = require('randomstring');

var generate = function(){
    var dt = new Date();
    return random.generate() + dt.toISOString();
}
module.exports.createID = function(req, res, next){
    //store flowid in res - this hold state over the request life time
    res.locals.flowid = generate();
    next();
}
</code>```

Now we can inject this middleware on the app using:

```<code>var flowcontrol = require('flow.js');
var middleware = require('middleware.js');

app.use(flowcontrol.createID);

//route example
app.get('/api/awesomeresource', middlewares.first, middlewares.second);
</code>```

Using this approach, you will be able to log the same flow id on every middleware like:

```<code>//middleware.js
module.exports.first = function(req, res, next){
   console.log(res.locals.flowid + " - First i did this...");
   //your logic here
   next();
}
module.exports.second = function(req, res, next){
   console.log(res.locals.flowid + " - Second i did this...");
   //your logic here before the response
   res.sendStatus(200);
}
</code>```

The result of
GET /api/awesomeresource HTTP/1.1
will be the following console log:

```<code>> R90A56nEmZWYK73NOEVbWv2RS6DolO4D2017-12-07T10:29:39.291Z - First i did
> this...
> R90A56nEmZWYK73NOEVbWv2RS6DolO4D2017-12-07T10:29:39.291Z -
> Second i did this...
</code>```

Which means that you can then track some sort of log files by this stamp and debug your backend logic if needed.

Cheers

ContentLicense: CC BY-SA 3.0

Title: tracking request flow by ID in node.js

Body:
I believe that what you're looking for is a logic flow id, which should be unique and generated upon every new request kicking in on your backend. If this assumption is correct, what I normally do is to create a middleware on my express router to generate a new and random flow id (with randomstring). To be sure that this flow id is unique, i add the timestamp to that. In order to pass this flow id to the next middlewares we should store it under res.locals (here the documentation )
Your middleware could look like this:

//middleware flow.js
var random = require('randomstring');

var generate = function(){
    var dt = new Date();
    return random.generate() + dt.toISOString();
}
module.exports.createID = function(req, res, next){
    //store flowid in res - this hold state over the request life time
    res.locals.flowid = generate();
    next();
}

Now we can inject this middleware on the app using:

var flowcontrol = require('flow.js');
var middleware = require('middleware.js');

app.use(flowcontrol.createID);

//route example
app.get('/api/awesomeresource', middlewares.first, middlewares.second);

Using this approach, you will be able to log the same flow id on every middleware like:

//middleware.js
module.exports.first = function(req, res, next){
   console.log(res.locals.flowid + " - First i did this...");
   //your logic here
   next();
}
module.exports.second = function(req, res, next){
   console.log(res.locals.flowid + " - Second i did this...");
   //your logic here before the response
   res.sendStatus(200);
}

The result of
GET /api/awesomeresource HTTP/1.1
will be the following console log:

> R90A56nEmZWYK73NOEVbWv2RS6DolO4D2017-12-07T10:29:39.291Z - First i did
> this...
> R90A56nEmZWYK73NOEVbWv2RS6DolO4D2017-12-07T10:29:39.291Z -
> Second i did this...

Which means that you can then track some sort of log files by this stamp and debug your backend logic if needed.

Cheers


问:
How to store field value of the document in firestore
Strong text

i am trying to store the field value of the document in fire store. my Firestore database path like is :
samyata(collection)-> uid's(document)->wallet( sub collection)->again registered users uid's(sub document). In sub document the fields are amount,bank account number, usd. generally the values for the fields are "zero". whenever user add some money to the wallet that added money will be store in the usd field. so i give the database path like is:

```<code>db.collection("samyata")
    .document(mAuth.getuid.toString())
    .collection("wallet")
    .document(mAuth.getuid.toString())
    .setData(dataToSave);
</code>```

But it display this error "java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference". please help how to solve that problem. I want to store the field value in document in firestore. My firestore statement is correct or not? how to reach that path to store the particular field value in the document.

答:
If your database looks like you say then setting the value in that way is correct. The problem in your code is this:

```<code>mAuth.getuid.toString()
</code>```

That error says that you are trying to use toString() method on a null object reference. This means that mAuth.getuid return null. To solve this, you need to verify your authentication process. Be sure that mAuth.getuid returns the correct uid and your problem will be solved.

Body:
Strong text

i am trying to store the field value of the document in fire store. my Firestore database path like is :
samyata(collection)-> uid's(document)->wallet( sub collection)->again registered users uid's(sub document). In sub document the fields are amount,bank account number, usd. generally the values for the fields are "zero". whenever user add some money to the wallet that added money will be store in the usd field. so i give the database path like is:

db.collection("samyata")
    .document(mAuth.getuid.toString())
    .collection("wallet")
    .document(mAuth.getuid.toString())
    .setData(dataToSave);

But it display this error "java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference". please help how to solve that problem. I want to store the field value in document in firestore. My firestore statement is correct or not? how to reach that path to store the particular field value in the document.

Body:
If your database looks like you say then setting the value in that way is correct. The problem in your code is this:

mAuth.getuid.toString()

That error says that you are trying to use toString() method on a null object reference. This means that mAuth.getuid return null. To solve this, you need to verify your authentication process. Be sure that mAuth.getuid returns the correct uid and your problem will be solved.


问:
Fastest way to create Dictionary from pyspark DF
I'm using Snappydata with pyspark to run my sql queries and convert the output DF into a dictionary to bulk insert it into mongo.
I've gone through many similar quertions to test the convertion of a spark DF to Dictionary.

Currently I'm using map(lambda row: row.asDict(), x.collect()) this method to convert my bulk DF to dictionary. And it is taking 2-3sec for 10K records.

I've stated below how I impliment my idea:

```<code>x = snappySession.sql("select * from test")
df = map(lambda row: row.asDict(), x.collect())
db.collection.insert_many(df)
</code>```

Is there any faster way?

答:
I would look into whether you can directly write to Mongo from Spark, as that will be the best method.

Failing that, you can use this method:

```<code>x = snappySession.sql("select * from test")
dictionary_rdd = x.rdd.map(lambda row: row.asDict())

for d in dictionary_rdd.toLocalIterator():
    db.collection.insert_many(d)
</code>```

This will create all the dictionaries in Spark in a distributed manner. The rows will returned to the driver and inserted into Mongo one row at a time so that you don't run out of memory.

Body:
I'm using Snappydata with pyspark to run my sql queries and convert the output DF into a dictionary to bulk insert it into mongo.
I've gone through many similar quertions to test the convertion of a spark DF to Dictionary.

Currently I'm using map(lambda row: row.asDict(), x.collect()) this method to convert my bulk DF to dictionary. And it is taking 2-3sec for 10K records.

I've stated below how I impliment my idea:

x = snappySession.sql("select * from test")
df = map(lambda row: row.asDict(), x.collect())
db.collection.insert_many(df)

Is there any faster way?

Body:
I would look into whether you can directly write to Mongo from Spark, as that will be the best method.

Failing that, you can use this method:

x = snappySession.sql("select * from test")
dictionary_rdd = x.rdd.map(lambda row: row.asDict())

for d in dictionary_rdd.toLocalIterator():
    db.collection.insert_many(d)

This will create all the dictionaries in Spark in a distributed manner. The rows will returned to the driver and inserted into Mongo one row at a time so that you don't run out of memory.


问:
Merge 2 Immutable JS Ordered Map objects
I am using Immutable JS as a redux store for my React Native App. I have 2 Ordered Map which is a Keyed Collection of Lists. When I try to merge these 2 Ordered Maps, if the keys overlap, then the data is being overwritten.

For eg: Consider I have 2 Ordered Maps with dates as their keys. When I merge them, if both of them have keys with the same date, the data of that key will be replaced. How can I concatenate them without losing data?

OrderedMap1: {
  '21-07-2017': List(10),
  '22-07-2017': List(10),
  '23-07-2017': List(10),
  '24-07-2017': List(10)
}

OrderedMap2: {
  '24-07-2017': List(5)
}

When I try to merge them, the data @ key '24-07-2017' gets replaced
OrderedMap1.merge(OrderedMap2) gives
{
  '21-07-2017': List(10),
  '22-07-2017': List(10),
  '23-07-2017': List(10),
  '24-07-2017': List(5)
}

I have tried concat(), merge() and mergeDeep() methods

答:
Maybe http://facebook.github.io/immutable-js/docs/#/Map/mergeWith is what you're looking for. In the merger function you can concat the lists.

According the the provided example for mergeWith it should look like this, I guess:

```<code>OrderedMap1.mergeWith(
    (dates1, dates2) => dates1.concat(dates2),
    OrderedMap2
)
</code>```

Body:
Maybe http://facebook.github.io/immutable-js/docs/#/Map/mergeWith is what you're looking for. In the merger function you can concat the lists.

According the the provided example for mergeWith it should look like this, I guess:

OrderedMap1.mergeWith(
    (dates1, dates2) => dates1.concat(dates2),
    OrderedMap2
)


问:
Need to make a specific column editable upon clicking edit
I have a gridview with "Edit Update Cancel" command field.
When I click Edit, all the columns in the particular row becomes editable.
I just need to have 2 specific columns editable.  How is that made possible ?

(Screen Shot Attached)

[In the screen shot all 3 columns are editable, I just need the second and third to be editable]

Thanks in Advance.

答:
It is very easy. The column you want not editable then place just label and bind properly.

```<code><EditItemTemplate>
 <asp:Label Runat="server" Text='<%# Bind("UnitPrice", "{0:c}") %>' ID="Label1"></asp:Label>
</EditItemTemplate>
</code>```

Here I use label in my EditItemTemplate because when the user clicks on edit button, the textbox will not come up. Rather, the value for that record will show through label, and as a result the user can not update that field.

ContentLicense: CC BY-SA 2.5

Body:
It is very easy. The column you want not editable then place just label and bind properly.

<EditItemTemplate>
 <asp:Label Runat="server" Text='<%# Bind("UnitPrice", "{0:c}") %>' ID="Label1"></asp:Label>
</EditItemTemplate>

Here I use label in my EditItemTemplate because when the user clicks on edit button, the textbox will not come up. Rather, the value for that record will show through label, and as a result the user can not update that field.


问:
How to aggregate an array data in mongodb
I've some problems to make an aggregation query work fine in MongoDB.

I've this json schema:

```<code>{
    "_id" : 11,
    "name": "A green door",
    "price": 12.50,
    "tags": ["home", "green"],
    "pools" : [
        {
            "score" : 2,
            "language" : "en",
            "option" : "Have problems to close!",
            "time" : "2017-06-06"
        },
        {
            "score" : 1,
            "language" : "en",
            "option" : "I can't close this door!",
            "time" : "2017-06-06"
        },
        {
            "score" : 4,
            "language" : "en",
            "option" : "After some time, I'm able to install this door. Works fine!",
            "time" : "2017-06-06"
        },
        {
            "score" : 5,
            "language" : "fr",
            "option" : "Très difficile à installer, mais ça marche quand même.",
            "time" : "2017-06-06"
        },
        {
            "score" : 1,
            "language" : "es",
            "option" : "Perdí mucho tiempo para instalar.",
            "time" : "2017-06-06"
        }
    ]
}
</code>```

I would like to filter only the registries that have language in English ("en") and score equal or greater than 3. So, I try this:

```<code>db.test.aggregate(
    { $match: { "pools.language": "en" }},
    { $match: {"pools.score": { $gte : 3 }}},
    { $unwind: '$pools'})
</code>```

However, I always get results in other languages and incoherent scores.

So, how to write this correctly?

答:
```<code>db.test.aggregate([{
   $addFields:{
  pools:{
    $filter:{
     input:"$pools",
     as:"p",
     cond:{$and:[{$eq:["$$p.language","en"]},{$gte:["$$p.score",3]}]}
    }}
  }

}])
</code>```

for < mongodb 3.4

```<code>db.test.aggregate([{
   $project:{
"_id" : 1,
"name":1,
"price":1,
"tags":1,
  pools:{
    $filter:{
     input:"$pools",
     as:"p",
     cond:{$and:[{$eq:["$$p.language","en"]},{$gte:["$$p.score",3]}]}
    }}
  }

}])
</code>```

Body:
I've some problems to make an aggregation query work fine in MongoDB.

I've this json schema:

{
    "_id" : 11,
    "name": "A green door",
    "price": 12.50,
    "tags": ["home", "green"],
    "pools" : [
        {
            "score" : 2,
            "language" : "en",
            "option" : "Have problems to close!",
            "time" : "2017-06-06"
        },
        {
            "score" : 1,
            "language" : "en",
            "option" : "I can't close this door!",
            "time" : "2017-06-06"
        },
        {
            "score" : 4,
            "language" : "en",
            "option" : "After some time, I'm able to install this door. Works fine!",
            "time" : "2017-06-06"
        },
        {
            "score" : 5,
            "language" : "fr",
            "option" : "Très difficile à installer, mais ça marche quand même.",
            "time" : "2017-06-06"
        },
        {
            "score" : 1,
            "language" : "es",
            "option" : "Perdí mucho tiempo para instalar.",
            "time" : "2017-06-06"
        }
    ]
}

I would like to filter only the registries that have language in English ("en") and score equal or greater than 3. So, I try this:

db.test.aggregate(
    { $match: { "pools.language": "en" }},
    { $match: {"pools.score": { $gte : 3 }}},
    { $unwind: '$pools'})

However, I always get results in other languages and incoherent scores.

So, how to write this correctly?

Body:
db.test.aggregate([{
   $addFields:{
  pools:{
    $filter:{
     input:"$pools",
     as:"p",
     cond:{$and:[{$eq:["$$p.language","en"]},{$gte:["$$p.score",3]}]}
    }}
  }

}])

for < mongodb 3.4

db.test.aggregate([{
   $project:{
"_id" : 1,
"name":1,
"price":1,
"tags":1,
  pools:{
    $filter:{
     input:"$pools",
     as:"p",
     cond:{$and:[{$eq:["$$p.language","en"]},{$gte:["$$p.score",3]}]}
    }}
  }

}])


问:
Convert array to conditional php
I have and array, and I want to convert it into an if conditional.

```<code>$array = ['check 1', 'check 2', 'check 3'];
</code>```

I want the final result to work like this:

```<code>if ($var == 'check 1' || $var == 'check 2' || $var == 'check 3') {
    // Do here.
}
</code>```

I don't have any inspiration, I already searched for convert array to if condition but I couldn't find anything.

How can I convert the array into an if conditional?

答:
```<code><?php

$array = array( "mango", "grapes","apple");
//let you have to find apple

if(in_array('masngo',$array) || in_array('mango',$array)){
    echo "FIND";
    //OR WHATEVER YOU WANT TO DO
}else{
    echo "Not Found";
}
</code>```

Try to run HERE

Title: Convert array to conditional php

Body:
I have and array, and I want to convert it into an if conditional.

$array = ['check 1', 'check 2', 'check 3'];

I want the final result to work like this:

if ($var == 'check 1' || $var == 'check 2' || $var == 'check 3') {
    // Do here.
}

I don't have any inspiration, I already searched for convert array to if condition but I couldn't find anything.

How can I convert the array into an if conditional?

Body:
<?php

$array = array( "mango", "grapes","apple");
//let you have to find apple

if(in_array('masngo',$array) || in_array('mango',$array)){
    echo "FIND";
    //OR WHATEVER YOU WANT TO DO
}else{
    echo "Not Found";
}

Try to run HERE


问:
Java Game - Pick up Item and Look around Function
I have been creating a java text game but I am stuck trying to figure out on how to implement the last 2 methods. I want it to print out the items in the room and the name of the npc thats in the room (A sort of a Look function). I am not sure on how to go on about it. Any help would be appriciated.

```<code>Room[] place = new Room[]{station, UC, Ollies, lounge, palace, AT301};
Sword sword = new Sword();
Thing heal = new HealthPotion();
Thing armour = new Armour();
Thing trap = new Trap();
</code>```

and for the NPC (Mike, Jake, Evil, Carl)

```<code>public abstract class Player{

//abstract attributes
private String name;
private int currentHealth;
private int maxHealth;
private int damage;
private Room currentRoom;
private int stack;
private int effect;

//Constructor for player
public Player(String name, int currentHealth, int maxHealth, int damage, int effect, int stack){
    this.name = name;
    this.currentHealth = currentHealth;
    this.maxHealth = maxHealth;
    this.damage = damage;
    this.effect = effect;
    this.stack = stack;
}

//getters
public String getName(){ return name;}
public int  getCurrentHealth(){ return currentHealth;}
public int getMaxHealth(){ return maxHealth;}
public int getDamage(){ return damage;}
public Room getCurrentRoom(){ return currentRoom;}
public int getEffect(){ return effect;}
public int getStack(){ return stack;}

//setters
public void setCurrentHealth(int currentHealth){this.currentHealth = currentHealth;}
public void setMaxHealth(int maxHealth){this.maxHealth = maxHealth;}
public void setDamage(int damage){ this.damage = damage;}
public void setCurrentRoom(Room room){this.currentRoom = room;}
public void setEffect(int effect){ this.effect = effect;}
public void setStack(int stack){ this.stack = stack;}
public void enter(Room room){ this.currentRoom = room;}

//abstract method because each player has a different attack;

public void takeDamage(int damage){ setCurrentHealth(this.currentHealth-damage);}

public boolean isDead(){
    if(this.currentHealth<=0){ return true;}
    return false;
}
</code>```

}

I was able to make everything functional except the Look function for the player. I can't figure out how to go on about it.

答:
Room is a vector of items right ? If so you can do a function on the player class that when it is called it goes to the vector of the room you're in and simply print out the items that are in the vector, something like this:

```<code>String lookAround(){
    ArrayList temp = (ArrayList)getCurrentRoom(); //returns the array containing the items in the current room
    for(Thing i : temp){
        i.getDescription(); //Method present in all classes that come from Thing that prints out the name of the item and/or its caracheteristics
    }
}
</code>```

In the array of the room you should try to include the name of all players in the room including yourself so that you can print out everyone present in the room

Hope this helps

Body:
I have been creating a java text game but I am stuck trying to figure out on how to implement the last 2 methods. I want it to print out the items in the room and the name of the npc thats in the room (A sort of a Look function). I am not sure on how to go on about it. Any help would be appriciated.

Room[] place = new Room[]{station, UC, Ollies, lounge, palace, AT301};
Sword sword = new Sword();
Thing heal = new HealthPotion();
Thing armour = new Armour();
Thing trap = new Trap();

and for the NPC (Mike, Jake, Evil, Carl)

public abstract class Player{

//abstract attributes
private String name;
private int currentHealth;
private int maxHealth;
private int damage;
private Room currentRoom;
private int stack;
private int effect;

//Constructor for player
public Player(String name, int currentHealth, int maxHealth, int damage, int effect, int stack){
    this.name = name;
    this.currentHealth = currentHealth;
    this.maxHealth = maxHealth;
    this.damage = damage;
    this.effect = effect;
    this.stack = stack;
}

//getters
public String getName(){ return name;}
public int  getCurrentHealth(){ return currentHealth;}
public int getMaxHealth(){ return maxHealth;}
public int getDamage(){ return damage;}
public Room getCurrentRoom(){ return currentRoom;}
public int getEffect(){ return effect;}
public int getStack(){ return stack;}

//setters
public void setCurrentHealth(int currentHealth){this.currentHealth = currentHealth;}
public void setMaxHealth(int maxHealth){this.maxHealth = maxHealth;}
public void setDamage(int damage){ this.damage = damage;}
public void setCurrentRoom(Room room){this.currentRoom = room;}
public void setEffect(int effect){ this.effect = effect;}
public void setStack(int stack){ this.stack = stack;}
public void enter(Room room){ this.currentRoom = room;}

//abstract method because each player has a different attack;

public void takeDamage(int damage){ setCurrentHealth(this.currentHealth-damage);}

public boolean isDead(){
    if(this.currentHealth<=0){ return true;}
    return false;
}

}

I was able to make everything functional except the Look function for the player. I can't figure out how to go on about it.

Body:
Room is a vector of items right ? If so you can do a function on the player class that when it is called it goes to the vector of the room you're in and simply print out the items that are in the vector, something like this:

String lookAround(){
    ArrayList temp = (ArrayList)getCurrentRoom(); //returns the array containing the items in the current room
    for(Thing i : temp){
        i.getDescription(); //Method present in all classes that come from Thing that prints out the name of the item and/or its caracheteristics
    }
}

In the array of the room you should try to include the name of all players in the room including yourself so that you can print out everyone present in the room

Hope this helps


问:
How do I give permissions to another user on firebase?
Where can I add an extra user on firebase settings. I cannot find the place to do it. Do I have to set it up using json on the security tab?</p>

答:
Please find the steps to add:

Log in to https://console.firebase.google.com using your Google account. A screen will be displayed with option Add Project.

Click on the Add Project option. You will be asked to enter App name and country. Then proceed by clicking on Create Project button.

Click on Users and Permission option from Settings/cog wheel icon which is adjacent to Project Overview, present on the left menu list.

You will be redirected to new a webpage(https://console.cloud.google.com/iam-admin/iam) and proceed with accepting the terms.

Click on IAM option from the left menu list. Add member by selecting Add on IAM screen.

Provide email id and role, then click on Add for adding the member.


问:
Getting ActionBarOverylayLayout in layout but missing all components
I am newbi so please be patient :)

Why I can't see components on the layout?

I opened an existing project all compiles and looks ok. I opend one of the layouts and I see some components at the component tree, but at the designer I see android...ActionBarOverylayLayout.

how can I see the components ?
my gradle.build :

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

android {
    compileSdkVersion 24

    defaultConfig {
        applicationId "com.adafruit.bluefruit.le.connect"
        minSdkVersion 19
        targetSdkVersion 24
        versionCode 17
        versionName "2.2.1"
    }

    useLibrary 'org.apache.http.legacy'     // TODO: remove Apache library and use HttpURLConnection (Apache is deprecated since Android 6.0)

    aaptOptions {
        noCompress "zip"
    }

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

repositories {
    maven {
        url "https://repo.eclipse.org/content/repositories/paho-releases/"
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'no.nordicsemi.android:dfu:1.0.4'
    compile(group: 'org.eclipse.paho', name: 'org.eclipse.paho.android.service', version: '1.0.2') {
        exclude module: 'support-v4'
    }
    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.larswerkman:HoloColorPicker:1.4'
    compile 'com.android.support:design:24.2.1'

    compile 'com.google.android.gms:play-services-analytics:9.6.1'
    compile 'com.google.android.gms:play-services-location:9.6.1'
    compile 'com.google.android.gms:play-services-vision:9.6.1'
}
</code>```

the layout xml :

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rootLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/default_background"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.adafruit.bluefruit.le.connect.app.UartActivity">

    <LinearLayout
        android:id="@+id/sendLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#cccccc"
            android:orientation="horizontal">

            <EditText
                android:id="@+id/sendEditText"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:inputType="textNoSuggestions|textVisiblePassword"
                android:scrollbarAlwaysDrawVerticalTrack="true"
                android:scrollbars="vertical"
                android:singleLine="false" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="onClickSend"
                android:text="@string/uart_send" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="end"
            android:layout_marginTop="4dp"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/sentBytesTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/uart_sentbytes_format"
                android:textColor="@drawable/default_infotextcolor" />

            <TextView
                android:id="@+id/receivedBytesTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="20dp"
                android:text="@string/uart_receivedbytes_format"
                android:textColor="@drawable/default_infotextcolor" />

        </LinearLayout>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/sendLayout"
        android:layout_alignParentTop="true"
        android:orientation="vertical">
        <!--
          android:layout_below="@id/headerLayout"
          android:layout_marginTop="10dp"
          !-->
        <ListView
            android:id="@+id/bufferListView"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:background="#cccccc" />

        <EditText
            android:id="@+id/bufferTextView"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:background="#cccccc"
            android:cursorVisible="false"
            android:gravity="top"
            android:scrollbarFadeDuration="0"
            android:textColorHighlight="#ffffff" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <Button
                style="?android:attr/borderlessButtonStyle"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:onClick="onClickCopy"
                android:text="@string/uart_copy"
                android:textColor="@drawable/default_textcolor" />

            <Button
                style="?android:attr/borderlessButtonStyle"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:onClick="onClickShare"
                android:text="@string/uart_share"
                android:textColor="@drawable/default_textcolor" />

            <Button
                style="?android:attr/borderlessButtonStyle"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:onClick="onClickClear"
                android:text="@string/uart_clear"
                android:textColor="@drawable/default_textcolor" />

        </LinearLayout>
    </LinearLayout>

</RelativeLayout>
</code>```

答:
you are missing '+' in id resource

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rootLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/default_background"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.adafruit.bluefruit.le.connect.app.UartActivity">

<LinearLayout
    android:id="@+id/sendLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#cccccc"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/sendEditText"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:inputType="textNoSuggestions|textVisiblePassword"
            android:scrollbarAlwaysDrawVerticalTrack="true"
            android:scrollbars="vertical"
            android:singleLine="false" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="onClickSend"
            android:text="@string/uart_send" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end"
        android:layout_marginTop="4dp"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/sentBytesTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/uart_sentbytes_format"
            android:textColor="@drawable/default_infotextcolor" />

        <TextView
            android:id="@+id/receivedBytesTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="20dp"
            android:text="@string/uart_receivedbytes_format"
            android:textColor="@drawable/default_infotextcolor" />

    </LinearLayout>

</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/sendLayout" //here change
    android:layout_alignParentTop="true"
    android:orientation="vertical">
    <!--
      android:layout_below="@id/headerLayout"
      android:layout_marginTop="10dp"
      !-->
    <ListView
        android:id="@+id/bufferListView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="#cccccc" />

    <EditText
        android:id="@+id/bufferTextView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="#cccccc"
        android:cursorVisible="false"
        android:gravity="top"
        android:scrollbarFadeDuration="0"
        android:textColorHighlight="#ffffff" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            style="?android:attr/borderlessButtonStyle"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="onClickCopy"
            android:text="@string/uart_copy"
            android:textColor="@drawable/default_textcolor" />

        <Button
            style="?android:attr/borderlessButtonStyle"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="onClickShare"
            android:text="@string/uart_share"
            android:textColor="@drawable/default_textcolor" />

        <Button
            style="?android:attr/borderlessButtonStyle"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="onClickClear"
            android:text="@string/uart_clear"
            android:textColor="@drawable/default_textcolor" />

    </LinearLayout>
</LinearLayout>
</code>```

also update SDK tool and try In menu File -> Invalidate caches/restart

Body:
I am newbi so please be patient :)

Why I can't see components on the layout?

I opened an existing project all compiles and looks ok. I opend one of the layouts and I see some components at the component tree, but at the designer I see android...ActionBarOverylayLayout.

how can I see the components ?
my gradle.build :

apply plugin: 'com.android.application'

android {
    compileSdkVersion 24

    defaultConfig {
        applicationId "com.adafruit.bluefruit.le.connect"
        minSdkVersion 19
        targetSdkVersion 24
        versionCode 17
        versionName "2.2.1"
    }

    useLibrary 'org.apache.http.legacy'     // TODO: remove Apache library and use HttpURLConnection (Apache is deprecated since Android 6.0)

    aaptOptions {
        noCompress "zip"
    }

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

repositories {
    maven {
        url "https://repo.eclipse.org/content/repositories/paho-releases/"
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'no.nordicsemi.android:dfu:1.0.4'
    compile(group: 'org.eclipse.paho', name: 'org.eclipse.paho.android.service', version: '1.0.2') {
        exclude module: 'support-v4'
    }
    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.larswerkman:HoloColorPicker:1.4'
    compile 'com.android.support:design:24.2.1'

    compile 'com.google.android.gms:play-services-analytics:9.6.1'
    compile 'com.google.android.gms:play-services-location:9.6.1'
    compile 'com.google.android.gms:play-services-vision:9.6.1'
}

the layout xml :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rootLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/default_background"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.adafruit.bluefruit.le.connect.app.UartActivity">

    <LinearLayout
        android:id="@+id/sendLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#cccccc"
            android:orientation="horizontal">

            <EditText
                android:id="@+id/sendEditText"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:inputType="textNoSuggestions|textVisiblePassword"
                android:scrollbarAlwaysDrawVerticalTrack="true"
                android:scrollbars="vertical"
                android:singleLine="false" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="onClickSend"
                android:text="@string/uart_send" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="end"
            android:layout_marginTop="4dp"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/sentBytesTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/uart_sentbytes_format"
                android:textColor="@drawable/default_infotextcolor" />

            <TextView
                android:id="@+id/receivedBytesTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="20dp"
                android:text="@string/uart_receivedbytes_format"
                android:textColor="@drawable/default_infotextcolor" />

        </LinearLayout>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/sendLayout"
        android:layout_alignParentTop="true"
        android:orientation="vertical">

        <ListView
            android:id="@+id/bufferListView"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:background="#cccccc" />

        <EditText
            android:id="@+id/bufferTextView"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:background="#cccccc"
            android:cursorVisible="false"
            android:gravity="top"
            android:scrollbarFadeDuration="0"
            android:textColorHighlight="#ffffff" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <Button
                style="?android:attr/borderlessButtonStyle"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:onClick="onClickCopy"
                android:text="@string/uart_copy"
                android:textColor="@drawable/default_textcolor" />

            <Button
                style="?android:attr/borderlessButtonStyle"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:onClick="onClickShare"
                android:text="@string/uart_share"
                android:textColor="@drawable/default_textcolor" />

            <Button
                style="?android:attr/borderlessButtonStyle"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:onClick="onClickClear"
                android:text="@string/uart_clear"
                android:textColor="@drawable/default_textcolor" />

        </LinearLayout>
    </LinearLayout>

</RelativeLayout>

Body:
you are missing '+' in id resource

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rootLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/default_background"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.adafruit.bluefruit.le.connect.app.UartActivity">

<LinearLayout
    android:id="@+id/sendLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#cccccc"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/sendEditText"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:inputType="textNoSuggestions|textVisiblePassword"
            android:scrollbarAlwaysDrawVerticalTrack="true"
            android:scrollbars="vertical"
            android:singleLine="false" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="onClickSend"
            android:text="@string/uart_send" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end"
        android:layout_marginTop="4dp"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/sentBytesTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/uart_sentbytes_format"
            android:textColor="@drawable/default_infotextcolor" />

        <TextView
            android:id="@+id/receivedBytesTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="20dp"
            android:text="@string/uart_receivedbytes_format"
            android:textColor="@drawable/default_infotextcolor" />

    </LinearLayout>

</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/sendLayout" //here change
    android:layout_alignParentTop="true"
    android:orientation="vertical">
    <!--
      android:layout_below="@id/headerLayout"
      android:layout_marginTop="10dp"
      !-->
    <ListView
        android:id="@+id/bufferListView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="#cccccc" />

    <EditText
        android:id="@+id/bufferTextView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="#cccccc"
        android:cursorVisible="false"
        android:gravity="top"
        android:scrollbarFadeDuration="0"
        android:textColorHighlight="#ffffff" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            style="?android:attr/borderlessButtonStyle"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="onClickCopy"
            android:text="@string/uart_copy"
            android:textColor="@drawable/default_textcolor" />

        <Button
            style="?android:attr/borderlessButtonStyle"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="onClickShare"
            android:text="@string/uart_share"
            android:textColor="@drawable/default_textcolor" />

        <Button
            style="?android:attr/borderlessButtonStyle"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="onClickClear"
            android:text="@string/uart_clear"
            android:textColor="@drawable/default_textcolor" />

    </LinearLayout>
</LinearLayout>

also update SDK tool and try In menu File -> Invalidate caches/restart


问:
Change datatables ScrollY clicking on button
I have a dataTable like this one:

```<code><table id="example" class="display" cellspacing="0" width="100%">
    <thead>
       <tr>
         <th></th>
         <th></th>
         <th></th>
         <th></th>
       </tr>
     </thead>
     <tbody>
        <?php
        $query = "SELECT something";
        $get_result = sqlsrv_query($conection,$query);
        while($row = sqlsrv_fetch_array($get_result)){
          $dest = $row['dest'];
          $num1 = $row['num1'];
          $num2 = $row['num2'];
          $num3 = $row['num3'];
          echo "<tr>
                  <td class='hidden'>{$dest}</td>
                  <td>{$num1}</td>
                  <td>{$num2}</td>
                  <td>{$num3}</td>
               </tr>";
         }
         sqlsrv_close($conection);
         ?>
    </tbody>
 </table>
 <div class="the_button">
    <a href="#" id="view_all_link" class="button">View All</a>
 </div>
</code>```

And my js for the dataTable :

```<code>$(document).ready(function() {
$('#example').DataTable( {
    "scrollY":        "100px", // Here
    "scrollCollapse": true,
    "paging":         false,
    "ordering": false,
    "info": false,
    initComplete: function () {
        this.api().columns([0]).every( function () {
            var column = this;
            var select = $('<select><option value="">Select Option</option></select>')
                .appendTo( $(column.header()).empty() )
                .on( 'change', function () {
                    var val = $.fn.dataTable.util.escapeRegex(
                        $(this).val()
                    );
                    column
                        .search( val ? '^'+val+'$' : '', true, false )
                        .draw();
                } );

            column.data().unique().sort().each( function ( d, j ) {
                select.append( '<option value="'+d+'">'+d+'</option>' )
            } );
        } );
    }
} );
</code>```

} );

```<code><script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
</code>```

So lets go in my problem.

I want when the button view all is clicked to change the ScrollY from 100px to auto value or 500px e.g.

I tried many examples found on community but not chance.

I tried by changing the css with js but not luck.

```<code>$('.dataTables_scrollBody').css('height', 400); Not working for me this one
</code>```

Also I tried to leave the ScrollY blank and add the height with CSS and javascript but still no luck.

Any ideas?

Thanks

答:
I have experienced a similar problem, but this was my solution:

```<code>   $("#myTable").DataTable({scrollY: 100});
   // ...
   $("#myTable").DataTable({retrieve: true}).destroy();
   // ...
   $("#myTable").DataTable({scrollY: 200});
</code>```

I did this because dataTables are intended to run with a single initialisation. The retrieve option on the second executable line above only returns the instance without re-initialisation the dataTable, then I call destroy on it - which reverts all the changes the plugin has made to the DOM. a Simple re-initialisation was the dirty fix that changed the height as per required.

Body:
I have a dataTable like this one:

        <?php
        $query = "SELECT something";
        $get_result = sqlsrv_query($conection,$query);
        while($row = sqlsrv_fetch_array($get_result)){
          $dest = $row['dest'];
          $num1 = $row['num1'];
          $num2 = $row['num2'];
          $num3 = $row['num3'];
          echo "

                  {$dest}
                  {$num1}
                  {$num2}
                  {$num3}

";
         }
         sqlsrv_close($conection);
         ?>

    View All

And my js for the dataTable :

$(document).ready(function() {
$('#example').DataTable( {
    "scrollY":        "100px", // Here
    "scrollCollapse": true,
    "paging":         false,
    "ordering": false,
    "info": false,
    initComplete: function () {
        this.api().columns([0]).every( function () {
            var column = this;
            var select = $('<select><option value="">Select Option</option></select>')
                .appendTo( $(column.header()).empty() )
                .on( 'change', function () {
                    var val = $.fn.dataTable.util.escapeRegex(
                        $(this).val()
                    );
                    column
                        .search( val ? '^'+val+'$' : '', true, false )
                        .draw();
                } );

            column.data().unique().sort().each( function ( d, j ) {
                select.append( '<option value="'+d+'">'+d+'</option>' )
            } );
        } );
    }
} );

} );

So lets go in my problem.

I want when the button view all is clicked to change the ScrollY from 100px to auto value or 500px e.g.

I tried many examples found on community but not chance.

I tried by changing the css with js but not luck.

$('.dataTables_scrollBody').css('height', 400); Not working for me this one

Also I tried to leave the ScrollY blank and add the height with CSS and javascript but still no luck.

Any ideas?

Thanks

Body:
I have experienced a similar problem, but this was my solution:

   $("#myTable").DataTable({scrollY: 100});
   // ...
   $("#myTable").DataTable({retrieve: true}).destroy();
   // ...
   $("#myTable").DataTable({scrollY: 200});

I did this because dataTables are intended to run with a single initialisation. The retrieve option on the second executable line above only returns the instance without re-initialisation the dataTable, then I call destroy on it - which reverts all the changes the plugin has made to the DOM. a Simple re-initialisation was the dirty fix that changed the height as per required.


问:
Program will print largest number and smallest number
I have some trouble when I try to code a program.

```<code>double max = 0, min = 0;
int i;
double array[] = new double[10];
Scanner input = new Scanner(System.in);
for (i = 0; i < 10; i++) {
    System.out.println("Give the " + (i + 1) + " number");
    array[i] = input.nextDouble();
}
for (i = 0; i < 10; i++) {
    if (array[i] > max) {
        max = array[i];
    }
    for (i = 0; i < 10; i++) {
        if (array[i] < min) {
            min = array[i];
        }
    }
}
System.out.println("The Max is :" + max);
System.out.println("The Min is :" + min);
</code>```

When I type 10 numbers that include one largest number and one smallest number,
the result is
The Max is : largest number
The Min is : 0.0

Always the Smallest I get the 0.0 whatever I type. No 2 I will type, No 4 I will type as a smallest number (always on separate launch), every time I get 0.0.

答:
Your curly braces are not proper. You are ending the max loop before the SYSOUT.

```<code>    double max = 0, min = 0;
    int i;

    double array[] = new double[10] ;
    Scanner input = new Scanner (System.in) ;
    for (i = 0; i < 10; i++)
    {
        System.out.println("Give the " + (i+1) + " number") ;
        array[i] = input.nextDouble();
    }
        max = array[0];
        min = array[0];
        for (i = 0; i < 10; i++) {
            if (array[i] > max) {
                max = array[i];
            }

            }

            for (i = 0; i < 10; i++) {
                if (array[i] < min) {
                    min = array[i];
                }
            }

        System.out.println("The Max is :" + max);
        System.out.println("The Min is :" + min);
</code>```

Run this. It will give the proper result.

Body:
I have some trouble when I try to code a program.

double max = 0, min = 0;
int i;
double array[] = new double[10];
Scanner input = new Scanner(System.in);
for (i = 0; i < 10; i++) {
    System.out.println("Give the " + (i + 1) + " number");
    array[i] = input.nextDouble();
}
for (i = 0; i < 10; i++) {
    if (array[i] > max) {
        max = array[i];
    }
    for (i = 0; i < 10; i++) {
        if (array[i] < min) {
            min = array[i];
        }
    }
}
System.out.println("The Max is :" + max);
System.out.println("The Min is :" + min);

When I type 10 numbers that include one largest number and one smallest number,
the result is
The Max is : largest number
The Min is : 0.0

Always the Smallest I get the 0.0 whatever I type. No 2 I will type, No 4 I will type as a smallest number (always on separate launch), every time I get 0.0.

Body:
Your curly braces are not proper. You are ending the max loop before the SYSOUT.

    double max = 0, min = 0;
    int i;

    double array[] = new double[10] ;
    Scanner input = new Scanner (System.in) ;
    for (i = 0; i < 10; i++)
    {
        System.out.println("Give the " + (i+1) + " number") ;
        array[i] = input.nextDouble();
    }
        max = array[0];
        min = array[0];
        for (i = 0; i < 10; i++) {
            if (array[i] > max) {
                max = array[i];
            }

            }

            for (i = 0; i < 10; i++) {
                if (array[i] < min) {
                    min = array[i];
                }
            }

        System.out.println("The Max is :" + max);
        System.out.println("The Min is :" + min);

Run this. It will give the proper result.


问:
How to get data after post json
here is my PHP code

```<code>$response = array();

$user1 = array();
$user1['name'] = 'Tom';
$user1['age'] = '13';

$user2 = array();
$user2['name'] = 'Jack';
$user2['age'] = '20';

$response[] = $user1;
$response[] = $user2;

echo json_encode($response);
</code>```

and here is my .html file that use jquery to get data from PHP file like

```<code>$.post('file.php', {userid : '1234'}, function(data){
   alert(data) //problem here
}, 'json');
</code>```

the problem is how to get user1's name after I use $.post in that code.

Thank you :)

答:
Because your user arrays are associative, they are being translated into json objects, not arrays.

access them with data[0].name

Title: How to get data after post json

Body:
here is my PHP code

$response = array();

$user1 = array();
$user1['name'] = 'Tom';
$user1['age'] = '13';

$user2 = array();
$user2['name'] = 'Jack';
$user2['age'] = '20';

$response[] = $user1;
$response[] = $user2;

echo json_encode($response);

and here is my .html file that use jquery to get data from PHP file like

$.post('file.php', {userid : '1234'}, function(data){
   alert(data) //problem here
}, 'json');

the problem is how to get user1's name after I use $.post in that code.

Thank you :)


问:
Currency convert in category page
I want show in category multiple curency price

i have a code tike this

```<code>$this->currency->convert($price, 'RUB', 'CNY'),
</code>```

Where to put this in caregory controller for working?

答:
I resolve my problem like this

```<code>if ($this->customer->isLogged() || !$this->config->get('config_customer_price')) {
                $price = $this->currency->format($this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']);
                $price_2 = $this->currency->format($this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax')), 'CNY');
            } else {
                $price = false;
                $price_2 = false;
            }
</code>```

Maybe someone have better way to make.

Title: Currency convert in category page

Body:
I want show in category multiple curency price

i have a code tike this

$this->currency->convert($price, 'RUB', 'CNY'),

Where to put this in caregory controller for working?

Body:
I resolve my problem like this

if ($this->customer->isLogged() || !$this->config->get('config_customer_price')) {
                $price = $this->currency->format($this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']);
                $price_2 = $this->currency->format($this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax')), 'CNY');
            } else {
                $price = false;
                $price_2 = false;
            }

Maybe someone have better way to make.


问:
Exclude from iCloud backup: NSURLIsExcludedFromBackupKey
My app had been rejected the 2nd times and I lost 3 weeks  :(

The first submit, I excluded ONLY DIRECTORIES from being backed-up in iCloud. Apple rejected...

The second submit, I excluded DIRECTORIES & PICTURES downloaded from being backed-up in iCloud. Apple again rejected...  Apple also complaint that I have no "Restore" feature for my In-App purchase, while in fact, I do have a "Restore" button and it worked when I tested it.

I've done as Apple had suggested by excluding the file from being backedup using NSURLIsExcludedFromBackupKey. There was an interesting comment made by Macmade's on stackoverflow here:

sometimes Apple reviewers think your data can be re-generated, when
  it's not. Then you'll have to explain why the data has to be backed-up

How often do the reviewer misunderstood and we have to explain to them that the content is required offline & not re-generateable?

Here is the code I used to exclude my files & directories from iCloud. Do you spot any problems?

```<code>- (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL
{
    // There's a chance the download failed, but don't assert here
    //assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);

    NSError *error = nil;
    BOOL success = [URL setResourceValue:[NSNumber numberWithBool:YES]
                                  forKey:NSURLIsExcludedFromBackupKey
                                   error: &error];
    if(!success){
        NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
    }
    return success;
}

//Download picture from Google and exclude it from being backed-up in iCloud
- (void)downloadFetcher:(GTMHTTPFetcher *)fetcher
       finishedWithData:(NSData *)data
                  error:(NSError *)error
{

    if (error == nil) {

        // successfully retrieved this photo's data; save it to disk
        GDataEntryPhoto *photoEntry = [fetcher propertyForKey:@"photo entry"];

        // Create album directory if it doesn't already exist
        NSString *path = [self findOrCreateApplicationSupportSubPath:[photoEntry albumTitle]];
        path = [path stringByAppendingPathComponent:[[photoEntry title] stringValue]];

        if (path != nil) {

            // Write to disk
            BOOL didSave = [data writeToFile:path
                                     options:NSDataWritingAtomic
                                       error:&error];
            if (didSave) {

                // Exclude file from being backed up in iCloud
                NSURL *url = [NSURL fileURLWithPath:path];
                BOOL excludeBackupResult = [self addSkipBackupAttributeToItemAtURL:url];

                if (excludeBackupResult == NO) {
                    NSLog(@"Error excluding FILE from iCloud: %@", path);
                }

                // Update the download progress bar
                _downloadedFileCounter = _downloadedFileCounter + 1;
                float progress = _downloadedFileCounter / kMaleWireframeImagesTotal;
                [self updateProgress:progress];

                // The download completed. -2 just incase a package is lost, but let the user move on...
                if (_downloadedFileCounter >= _downloadableFilesTotal -2) {
                    [_panel6 downloadCompleted];
                }

            } else {
                // error saving file.  Perhaps out of space?  Write permissions error?
                NSLog(@"Save anatomy picture failed: %@", error.localizedDescription);
            }

        } else {
            NSLog(@"downloadFetcher: Cannot create directory");
        }
    } else {
        NSLog(@"downloadFetcher failed: %@", error);
    }
}

//Create directory and exclude it from being backed-up in iCloud
-(NSString*)findOrCreateApplicationSupportSubPath:(NSString*)subPath
{

    NSString *resolvedPath;
    NSArray *appSupportDir = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);

    if ([appSupportDir count] != 0) {

        resolvedPath = [appSupportDir objectAtIndex:0];

        // Append the name of this application
        NSString *executableName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleExecutable"];
        resolvedPath = [resolvedPath stringByAppendingPathComponent:executableName];
        resolvedPath = [resolvedPath stringByAppendingPathComponent:subPath];

        NSFileManager *manager = [NSFileManager defaultManager];
        if (![manager fileExistsAtPath:resolvedPath]) {

            // Path doesn't exist, creates it
            NSError *error;
            BOOL successful = [manager createDirectoryAtPath:resolvedPath withIntermediateDirectories:YES attributes:nil error:&error];

            if(!successful) {
                NSLog(@"ERROR creating APP Support Sub-Directory: %@", error.localizedDescription);
                return nil;
            } else {

                // Exclude path from backing-up in iCloud
                NSURL *url = [NSURL fileURLWithPath:resolvedPath];
                BOOL excludeBackupResult = [self addSkipBackupAttributeToItemAtURL:url];

                if(!excludeBackupResult){
                    NSLog(@"Error excluding DIRECTORY from iCloud backup. This is a violation to their guideline.");
                    return  nil;
                }
            }
        }

    } else {
        NSLog(@"No Application Support Path available");
        return  nil;
    }

    return resolvedPath;
}
</code>```

答:
Little UPDATE from previous answers.

You have to check the existence of the file. Otherwise, you will get this error,

```<code>Error excluding [FileName] from backup:
Error Domain=NSCocoaErrorDomain Code=4 "The file “[FileName]” doesn’t exist."
 ...
</code>```

I am not sure if we should check for the value is already updated or not.
e.g. if the API reset already set value or not. If it tries to update the file system again for a set value that is more time consuming, I guess.

Updated method...

```<code>+ (BOOL)addSkipBackupAttributeToURLAtPath:(NSURL *)url
{
    if (!url) return NO;
    if (![[NSFileManager defaultManager] fileExistsAtPath:url.path]) return NO;

    NSError *error = nil;
    NSNumber *value = nil;
    BOOL success = [url getResourceValue:&value forKey:NSURLIsExcludedFromBackupKey error:&error];
    if (value.boolValue == YES) return YES;

    success = [url setResourceValue:[NSNumber numberWithBool:YES]
                                  forKey:NSURLIsExcludedFromBackupKey error:&error];
    if(!success){
        NSLog(@"Error excluding %@ from backup: %@", [url lastPathComponent], error);
    }
    return success;
}

+ (BOOL)addSkipBackupAttributeToFileAtPath:(NSString *)path
{
    if (!path) return NO;
    return [self addSkipBackupAttributeToURLAtPath:[NSURL fileURLWithPath:path]];
}
</code>```

Body:
My app had been rejected the 2nd times and I lost 3 weeks  :(

The first submit, I excluded ONLY DIRECTORIES from being backed-up in iCloud. Apple rejected...

The second submit, I excluded DIRECTORIES & PICTURES downloaded from being backed-up in iCloud. Apple again rejected...  Apple also complaint that I have no "Restore" feature for my In-App purchase, while in fact, I do have a "Restore" button and it worked when I tested it.

I've done as Apple had suggested by excluding the file from being backedup using NSURLIsExcludedFromBackupKey. There was an interesting comment made by Macmade's on stackoverflow here:

sometimes Apple reviewers think your data can be re-generated, when
  it's not. Then you'll have to explain why the data has to be backed-up

How often do the reviewer misunderstood and we have to explain to them that the content is required offline & not re-generateable?

Here is the code I used to exclude my files & directories from iCloud. Do you spot any problems?

- (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL
{
    // There's a chance the download failed, but don't assert here
    //assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);

    NSError *error = nil;
    BOOL success = [URL setResourceValue:[NSNumber numberWithBool:YES]
                                  forKey:NSURLIsExcludedFromBackupKey
                                   error: &error];
    if(!success){
        NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
    }
    return success;
}

//Download picture from Google and exclude it from being backed-up in iCloud
- (void)downloadFetcher:(GTMHTTPFetcher *)fetcher
       finishedWithData:(NSData *)data
                  error:(NSError *)error
{

    if (error == nil) {

        // successfully retrieved this photo's data; save it to disk
        GDataEntryPhoto *photoEntry = [fetcher propertyForKey:@"photo entry"];

        // Create album directory if it doesn't already exist
        NSString *path = [self findOrCreateApplicationSupportSubPath:[photoEntry albumTitle]];
        path = [path stringByAppendingPathComponent:[[photoEntry title] stringValue]];

        if (path != nil) {

            // Write to disk
            BOOL didSave = [data writeToFile:path
                                     options:NSDataWritingAtomic
                                       error:&error];
            if (didSave) {

                // Exclude file from being backed up in iCloud
                NSURL *url = [NSURL fileURLWithPath:path];
                BOOL excludeBackupResult = [self addSkipBackupAttributeToItemAtURL:url];

                if (excludeBackupResult == NO) {
                    NSLog(@"Error excluding FILE from iCloud: %@", path);
                }

                // Update the download progress bar
                _downloadedFileCounter = _downloadedFileCounter + 1;
                float progress = _downloadedFileCounter / kMaleWireframeImagesTotal;
                [self updateProgress:progress];

                // The download completed. -2 just incase a package is lost, but let the user move on...
                if (_downloadedFileCounter >= _downloadableFilesTotal -2) {
                    [_panel6 downloadCompleted];
                }

            } else {
                // error saving file.  Perhaps out of space?  Write permissions error?
                NSLog(@"Save anatomy picture failed: %@", error.localizedDescription);
            }

        } else {
            NSLog(@"downloadFetcher: Cannot create directory");
        }
    } else {
        NSLog(@"downloadFetcher failed: %@", error);
    }
}

//Create directory and exclude it from being backed-up in iCloud
-(NSString*)findOrCreateApplicationSupportSubPath:(NSString*)subPath
{

    NSString *resolvedPath;
    NSArray *appSupportDir = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);

    if ([appSupportDir count] != 0) {

        resolvedPath = [appSupportDir objectAtIndex:0];

        // Append the name of this application
        NSString *executableName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleExecutable"];
        resolvedPath = [resolvedPath stringByAppendingPathComponent:executableName];
        resolvedPath = [resolvedPath stringByAppendingPathComponent:subPath];

        NSFileManager *manager = [NSFileManager defaultManager];
        if (![manager fileExistsAtPath:resolvedPath]) {

            // Path doesn't exist, creates it
            NSError *error;
            BOOL successful = [manager createDirectoryAtPath:resolvedPath withIntermediateDirectories:YES attributes:nil error:&error];

            if(!successful) {
                NSLog(@"ERROR creating APP Support Sub-Directory: %@", error.localizedDescription);
                return nil;
            } else {

                // Exclude path from backing-up in iCloud
                NSURL *url = [NSURL fileURLWithPath:resolvedPath];
                BOOL excludeBackupResult = [self addSkipBackupAttributeToItemAtURL:url];

                if(!excludeBackupResult){
                    NSLog(@"Error excluding DIRECTORY from iCloud backup. This is a violation to their guideline.");
                    return  nil;
                }
            }
        }

    } else {
        NSLog(@"No Application Support Path available");
        return  nil;
    }

    return resolvedPath;
}

Body:
Little UPDATE from previous answers.

You have to check the existence of the file. Otherwise, you will get this error,

Error excluding [FileName] from backup:
Error Domain=NSCocoaErrorDomain Code=4 "The file “[FileName]” doesn’t exist."
 ...

I am not sure if we should check for the value is already updated or not.
e.g. if the API reset already set value or not. If it tries to update the file system again for a set value that is more time consuming, I guess.

Updated method...

+ (BOOL)addSkipBackupAttributeToURLAtPath:(NSURL *)url
{
    if (!url) return NO;
    if (![[NSFileManager defaultManager] fileExistsAtPath:url.path]) return NO;

    NSError *error = nil;
    NSNumber *value = nil;
    BOOL success = [url getResourceValue:&value forKey:NSURLIsExcludedFromBackupKey error:&error];
    if (value.boolValue == YES) return YES;

    success = [url setResourceValue:[NSNumber numberWithBool:YES]
                                  forKey:NSURLIsExcludedFromBackupKey error:&error];
    if(!success){
        NSLog(@"Error excluding %@ from backup: %@", [url lastPathComponent], error);
    }
    return success;
}

+ (BOOL)addSkipBackupAttributeToFileAtPath:(NSString *)path
{
    if (!path) return NO;
    return [self addSkipBackupAttributeToURLAtPath:[NSURL fileURLWithPath:path]];
}


问:
Read remote file beginning with "smb://" using R
To read a file in R, I'd normally do something like the following:

```<code>read.csv('/Users/myusername/myfilename.csv')
</code>```

But, I'm trying to read a file located on a remote server (Windows SMB/CIFS share) which I access on my Mac via the Finder → Go → Connect to Server menu item.

When I view that file's properties, the file path is different than what I'm used to. Instead of beginning with: /Users/myusername/..., it is smb://server.msu.edu/.../myfilename.csv.

Trying to read the file, I tried the following:

```<code>read.csv('smb://server.msu.edu/.../myfilename.csv')
</code>```

But, this didn't work.

Instead of the usual "No such file or directory" error, this returned:

smb://server.msu.edu/.../myfilename.csv does not exist in current working directory

I imagine the file path needs a different format, but I can't figure what.

How can you read this type of file in R?

答:
In my opinion, there is two way to achieve your goal.

The first one is to use fstab to add definitely the remote folder as local disk.

The second one is to temporary mount the remote folder as a folder when it is required

Bellow, I will explain how the second method can be implemented

Create a local directory :

mkdir <mountdirectory>

Mount your remote directory to the local with this command line :

sshfs <remoteserverip>:<remotedirpath> <mountdirectory> for SSH

OR (first install cifs util: sudo apt-get install cifs-utils)

mount -t cifs -o username=<USERNAME>,password=<PASSWD> //<remoteserverip>/<remotedirpath> <mountdirectory> for SMB

Do the job with local file !

At the end, use this command to unmount :

fusermount -u <mountdirectory>

Body:
To read a file in R, I'd normally do something like the following:

read.csv('/Users/myusername/myfilename.csv')

But, I'm trying to read a file located on a remote server (Windows SMB/CIFS share) which I access on my Mac via the Finder → Go → Connect to Server menu item.

When I view that file's properties, the file path is different than what I'm used to. Instead of beginning with: /Users/myusername/..., it is smb://server.msu.edu/.../myfilename.csv.

Trying to read the file, I tried the following:

read.csv('smb://server.msu.edu/.../myfilename.csv')

But, this didn't work.

Instead of the usual "No such file or directory" error, this returned:

smb://server.msu.edu/.../myfilename.csv does not exist in current working directory

I imagine the file path needs a different format, but I can't figure what.

How can you read this type of file in R?


问:
Hide softkeyboard in single activity - Android
I have been searching the 'net for a bit here, I can't seem to stop the SoftKeyboard from appearing when an EditText gets focus, I've tried at least 3 different methods, setting the Input Type to None (think I saw that in the Android Dev Docs), and two different ways inside the onCreate method, they are:

```<code>getWindow().requestFeature(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
</code>```

And

```<code>getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
</code>```

I know I can disable it for the entire app in the manifest file, but I only need it disabled in this activity.

答:
for this one whenever u want key board at that only u write soft keyboard appear,likebelow code

```<code>EditText EditTextName=findViewById(R.id.EditText01);
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(EditTextName), 0);
</code>```

In above code i am enable the keyboard when edittext has focus.In the same way u disable the keyboard using

```<code>((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInput(EditTextName), 0);
</code>```

Body:
I have been searching the 'net for a bit here, I can't seem to stop the SoftKeyboard from appearing when an EditText gets focus, I've tried at least 3 different methods, setting the Input Type to None (think I saw that in the Android Dev Docs), and two different ways inside the onCreate method, they are:

getWindow().requestFeature(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

And

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

I know I can disable it for the entire app in the manifest file, but I only need it disabled in this activity.

Body:
for this one whenever u want key board at that only u write soft keyboard appear,likebelow code

EditText EditTextName=findViewById(R.id.EditText01);
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(EditTextName), 0);

In above code i am enable the keyboard when edittext has focus.In the same way u disable the keyboard using

((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInput(EditTextName), 0);


问:
$batch request resulting in error "Default changeset implementation allows only one operation"
I am making a worklist application using SAPUI5. The problem is that when I create an entry and then create another one right after that, I get the following error:

Default changeset implementation allows only one operation.

I checked the $batch header and I see that there is a MERGE and a POST, with the MERGE updating the previous entry for some reason. Can anyone shed some light? Could it be a backend error and not a UI5 error?

Creating the new entry:

_onMetadataLoaded: function() {
  var oModel = this.getView().getModel();
  var that = this;
  // ...
  oModel.read("/USERS_SET", {
    success: function(oData) {
      var oProperties = {
        Qmnum: "0",
        Otherstuff: "cool"
      };
      that._oContext = that._oView.getModel().createEntry("/ENTITYSET", {
        properties: oProperties
      });
      that.getView().setBindingContext(that._oContext);
      // ...
    }
  });
},

handleSavePress: function(oEvent) {
  // ...
  this.getView().getModel().submitChanges({
    success: function(oData) {
      // ...
    },
    error: function(oError) {
      // ...
    }
  });
},
```

答:
tl-dr: Apparently you must be using the SAP Gateway. If you do not need to process those requests in one transaction then send them in different changesets. If you do not need batch calls at all consider turning it off by supplying your model with "useBatch": false upon instantiation. However if you need to process the requests together in one transaction then you have to read the details below.

In order to understand the problem you have to understand how the gateway and the batch and changeset requests work.

Batch requests consist of multiple requests bundled together. The purpose is to open only one connection and group together relevant requests so that the overhead is minimalized. Changesets form smaller blocks inside batch requests, where modification requests can be bundled and processed together in order to ensure an all-or-nothing characteristic.

So on the gateway side: there are two relevant classes for your OData service, assuming that you have used the SAP Gateway Service Builder (SEGW transaction). There is one with the ending ...DPC and one with ...DPC_EXT. Don't touch the former, it will be always regenerated when you update your service in the service builder. The latter is the one that we will need in this example. You will have to redefine at least two methods:

/IWBEP/IF_MGW_APPL_SRV_RUNTIME~CHANGESET_BEGIN

/IWBEP/IF_MGW_APPL_SRV_RUNTIME~CHANGESET_PROCESS

By default the changeset_begin method will only allow changeset processing for changesets where the number of requests equals to one. This can be handled automatically that's why a limitation exists. If there were more requests one could not ensure their processing automatically as they could have a business dependency on each other.

So make sure to allow a bundled (deferred mode) processing of changesets under the desired conditions:

/IWBEP/IF_MGW_APPL_SRV_RUNTIME~CHANGESET_BEGIN: first call the super->/iwbep/if_mgw_appl_srv_runtime~changeset_begin method in a try catch block, then loop at it_operation_info to decide and narrow down processing only in selected cases and then allow cv_defer_mode only for the selected cases, otherwise throw a /iwbep/cx_mgw_tech_exception=>changeset_not_supported exception.

/IWBEP/IF_MGW_APPL_SRV_RUNTIME~CHANGESET_PROCESS: all requests will be available in the it_changeset_request. Make sure to fill the ct_changeset_response table with the responses.

```<code>  METHOD /iwbep/if_mgw_appl_srv_runtime~changeset_process.
    DATA:
        lv_operation_counter TYPE i VALUE 0,
        lr_context           TYPE REF TO /iwbep/cl_mgw_request,
        lr_entry_provider    TYPE REF TO /iwbep/if_mgw_entry_provider,
        lr_message_container TYPE REF TO /iwbep/if_message_container,
        lr_entity_data       TYPE REF TO data,
        ls_context_details   TYPE /iwbep/if_mgw_core_srv_runtime=>ty_s_mgw_request_context,
        ls_changeset_response LIKE LINE OF ct_changeset_response.

    FIELD-SYMBOLS:
        <fs_ls_changeset_request>  LIKE LINE OF it_changeset_request.

    LOOP AT it_changeset_request ASSIGNING <fs_ls_changeset_request>.
        lr_context          ?= <fs_ls_changeset_request>-request_context.
        lr_entry_provider    = <fs_ls_changeset_request>-entry_provider.
        lr_message_container = <fs_ls_changeset_request>-msg_container.
        ls_context_details   = lr_context->get_request_details( ).
        CASE ls_context_details-target_entity.
          WHEN 'SomeEntity'.
            "Do the processing here
          WHEN OTHERS.
        ENDCASE.
    ENDLOOP.
  ENDMETHOD.
</code>```

ContentLicense: CC BY-SA 4.0

Body:
tl-dr: Apparently you must be using the SAP Gateway. If you do not need to process those requests in one transaction then send them in different changesets. If you do not need batch calls at all consider turning it off by supplying your model with "useBatch": false upon instantiation. However if you need to process the requests together in one transaction then you have to read the details below.

In order to understand the problem you have to understand how the gateway and the batch and changeset requests work.

Batch requests consist of multiple requests bundled together. The purpose is to open only one connection and group together relevant requests so that the overhead is minimalized. Changesets form smaller blocks inside batch requests, where modification requests can be bundled and processed together in order to ensure an all-or-nothing characteristic.

So on the gateway side: there are two relevant classes for your OData service, assuming that you have used the SAP Gateway Service Builder (SEGW transaction). There is one with the ending ...DPC and one with ...DPC_EXT. Don't touch the former, it will be always regenerated when you update your service in the service builder. The latter is the one that we will need in this example. You will have to redefine at least two methods:

/IWBEP/IF_MGW_APPL_SRV_RUNTIME~CHANGESET_BEGIN

/IWBEP/IF_MGW_APPL_SRV_RUNTIME~CHANGESET_PROCESS

By default the changeset_begin method will only allow changeset processing for changesets where the number of requests equals to one. This can be handled automatically that's why a limitation exists. If there were more requests one could not ensure their processing automatically as they could have a business dependency on each other.

So make sure to allow a bundled (deferred mode) processing of changesets under the desired conditions:

/IWBEP/IF_MGW_APPL_SRV_RUNTIME~CHANGESET_BEGIN: first call the super->/iwbep/if_mgw_appl_srv_runtime~changeset_begin method in a try catch block, then loop at it_operation_info to decide and narrow down processing only in selected cases and then allow cv_defer_mode only for the selected cases, otherwise throw a /iwbep/cx_mgw_tech_exception=>changeset_not_supported exception.

/IWBEP/IF_MGW_APPL_SRV_RUNTIME~CHANGESET_PROCESS: all requests will be available in the it_changeset_request. Make sure to fill the ct_changeset_response table with the responses.

  METHOD /iwbep/if_mgw_appl_srv_runtime~changeset_process.
    DATA:
        lv_operation_counter TYPE i VALUE 0,
        lr_context           TYPE REF TO /iwbep/cl_mgw_request,
        lr_entry_provider    TYPE REF TO /iwbep/if_mgw_entry_provider,
        lr_message_container TYPE REF TO /iwbep/if_message_container,
        lr_entity_data       TYPE REF TO data,
        ls_context_details   TYPE /iwbep/if_mgw_core_srv_runtime=>ty_s_mgw_request_context,
        ls_changeset_response LIKE LINE OF ct_changeset_response.

    FIELD-SYMBOLS:
        <fs_ls_changeset_request>  LIKE LINE OF it_changeset_request.

    LOOP AT it_changeset_request ASSIGNING <fs_ls_changeset_request>.
        lr_context          ?= <fs_ls_changeset_request>-request_context.
        lr_entry_provider    = <fs_ls_changeset_request>-entry_provider.
        lr_message_container = <fs_ls_changeset_request>-msg_container.
        ls_context_details   = lr_context->get_request_details( ).
        CASE ls_context_details-target_entity.
          WHEN 'SomeEntity'.
            "Do the processing here
          WHEN OTHERS.
        ENDCASE.
    ENDLOOP.
  ENDMETHOD.


问:
how to print a receipt in java label
enter image description herei want to print all the Double variables in    a java label. but when i execute the program only Qty1 print in the label.so that i used escape sequences but the also dont work. Could anyone tell me how to fix this.What i really expect to do is something like in the attachment.

Code

```<code>JButton receipt = new JButton("Receipt");
        receipt.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Double Qty1= Double.parseDouble(textField.getText());
                Double Qty2=Double.parseDouble(textField_2.getText());
                Double Qty3=Double.parseDouble(textField_3.getText());
                lblRecipt.setText("\t\nHotel \n\nManagement System"+Qty1);
            //  lblRecipt.setText("Hotel Management System"+Qty1);
</code>```

答:
You can use swing's html formatting feature as explained in https://docs.oracle.com/javase/tutorial/uiswing/components/html.html.

To specify that a component's text has HTML formatting, just put the  tag at the beginning of the text, then use any valid HTML in the remainder.

This is what swing example offers:

Your code might look like:

```<code>lblRecipt.setText("<html>\t<br>Hotel<br><br>Management System"+Qty1+"</html>");
</code>```

Title: how to print a receipt in java label

Body:
enter image description herei want to print all the Double variables in    a java label. but when i execute the program only Qty1 print in the label.so that i used escape sequences but the also dont work. Could anyone tell me how to fix this.What i really expect to do is something like in the attachment.

Code

JButton receipt = new JButton("Receipt");
        receipt.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Double Qty1= Double.parseDouble(textField.getText());
                Double Qty2=Double.parseDouble(textField_2.getText());
                Double Qty3=Double.parseDouble(textField_3.getText());
                lblRecipt.setText("\t\nHotel \n\nManagement System"+Qty1);
            //  lblRecipt.setText("Hotel Management System"+Qty1);

Body:
You can use swing's html formatting feature as explained in https://docs.oracle.com/javase/tutorial/uiswing/components/html.html.

To specify that a component's text has HTML formatting, just put the  tag at the beginning of the text, then use any valid HTML in the remainder.

This is what swing example offers:

Your code might look like:

lblRecipt.setText("<html>\t<br>Hotel<br><br>Management System"+Qty1+"</html>");


问:
Validating UK phone number (Regex C#)
```<code>public static bool ValidatePhoneNumber(string number)
{
    return Regex.Match(number, "^(\+44\s?7\d{3}|\(?07\d{3}\)?)\s?\d{3}\s?\d{3}$", RegexOptions.IgnoreCase).Success;
}
</code>```

This is what I have but I get errors saying Unrecognized escape sequence. Can anbody help? needs to be able to have +44.

答:
This works well and allows 3 and 4 digit extensions. It also ensures that only mobile numbers are entered. UK mobile numbers start with 07 regardless of the provider</p>

```<code>^(\+44\s?7\d{3}|\(?07\d{3}\)?)\s?\d{3}\s?\d{3}(\s?\#(\d{4}|\d{3}))?$
</code>```

Title: Validating UK phone number (Regex C#)

Body:
public static bool ValidatePhoneNumber(string number)
{
    return Regex.Match(number, "^(\+44\s?7\d{3}|\(?07\d{3}\)?)\s?\d{3}\s?\d{3}$", RegexOptions.IgnoreCase).Success;
}

This is what I have but I get errors saying Unrecognized escape sequence. Can anbody help? needs to be able to have +44.

Body:
This works well and allows 3 and 4 digit extensions. It also ensures that only mobile numbers are entered. UK mobile numbers start with 07 regardless of the provider

^(\+44\s?7\d{3}|\(?07\d{3}\)?)\s?\d{3}\s?\d{3}(\s?\#(\d{4}|\d{3}))?$


问:
what is wrong with my jQuery POST request?
I am trying to authenticate with a remote service through jQuery.  First, I verify that I can do this outside of the browser:

```<code> curl -X POST -H "Content-Type: application/json" -H "Accept: appliction/json" -d '{"username":"...","password":"..."}' http://example.com/auth
</code>```

This successfully returns a token.

Now I try it with jQuery:

```<code>$.ajax({
    url: "http://example.com/auth",
    type: "POST",
    dataType: "json",
    contentType: "json",
    data: {username:"...",password:"..."},
    error: function(data){alert(JSON.stringify(data))},
    success: function(data){alert(JSON.stringify(data))}
});
</code>```

I get a server error (500).  Clearly I am doing something wrong.  This is my first time trying to do a POST in jQuery, so I don't know how to identify what the problem is.  What am I doing wrong here?

P.S. I can successfully do a GET request through jQuery, if I already have a token:

```<code>$.ajax({
    url: "http://example.com/stuff?token=f42652adcbfe3ed9d59fae62b5267b8d",
    type: "GET",
    dataType: "json",
    error: function(data){alert(JSON.stringify(data))},
    success: function(data){alert(JSON.stringify(data))}
});
</code>```

答:
1) Open Network in Tools (f12)

2) Select "Network"

3) Select error row

4) Open "Body" on rights side

5) In title you can see error description eq.

<title>The parameters dictionary contains a null entry for parameter 'Id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Delete(Int32)' in 'BosCatalog.Controllers.ProductsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters</title>

Body:
I am trying to authenticate with a remote service through jQuery.  First, I verify that I can do this outside of the browser:

 curl -X POST -H "Content-Type: application/json" -H "Accept: appliction/json" -d '{"username":"...","password":"..."}' http://example.com/auth

This successfully returns a token.

Now I try it with jQuery:

$.ajax({
    url: "http://example.com/auth",
    type: "POST",
    dataType: "json",
    contentType: "json",
    data: {username:"...",password:"..."},
    error: function(data){alert(JSON.stringify(data))},
    success: function(data){alert(JSON.stringify(data))}
});

I get a server error (500).  Clearly I am doing something wrong.  This is my first time trying to do a POST in jQuery, so I don't know how to identify what the problem is.  What am I doing wrong here?

P.S. I can successfully do a GET request through jQuery, if I already have a token:

$.ajax({
    url: "http://example.com/stuff?token=f42652adcbfe3ed9d59fae62b5267b8d",
    type: "GET",
    dataType: "json",
    error: function(data){alert(JSON.stringify(data))},
    success: function(data){alert(JSON.stringify(data))}
});

Body:
1) Open Network in Tools (f12)

2) Select "Network"

3) Select error row

4) Open "Body" on rights side

5) In title you can see error description eq.

<title>The parameters dictionary contains a null entry for parameter 'Id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Delete(Int32)' in 'BosCatalog.Controllers.ProductsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.<br>Parameter name: parameters</title>


问:
Set robot dimensions
I'm using MRPT, in particular the CHolonomicVFF class, for a university project. I made a ROS node which implements a simple obstacle avoidance functionality, it seems to work but I need a way to specify the robot dimensions. I checked the CHolonomicVFF class wiki, but i didn't find anything helpful.

Thanks a lot.

答:
mrpt::nav::CHolonomicVFF (and all other "holonomic" solvers in mrpt-nav) works on the assumption of a "point robot", without radius.

In other words, you should enlarge all your obstacles with the robot radius before feeding them to this class. Similar to the way cost_map does in ROS.

The reason for this design is that "holonomic" navigators in MRPT play a role in the navigation pipeline after what is called PTG-based transformations, which abstract away the actual robot shape so it can be dealt as a "point".

Title: Set robot dimensions


问:
Compilation error when passing Integer into generic method with Function<T, ? extends Number>>
I have some code with 3 overriding methods that perform the same operation ( code is identically for each method) on the Inputs, the only difference between them is the input parameter type

```<code>private List<String> extractDoubleValues(Function<MyClass, List<Double>> extractions)
private List<String> extractLongValues(Function<MyClass List<Long>> extractions)
private List<String> extractIntegerValues(Function<MyClass, List<Integer>> extractions)
</code>```

I was trying to attempt to replace these 3 methods with a single method that makes us of generic wildcards as follows

```<code>private List<String> extractNumberValues(Function<MyClass, List<? extends Number>> extractions)
</code>```

When I attempt to use the above generic method in place of one of the 3 type specific methods

```<code>Function<MyClass, List<Integer>> intExtractions;
List<String> extractedValues = extractNumberValues(intExtractions);
</code>```

I get a the following compilation error on the second line of code above

```<code>Error:(59, 80) java: incompatible types: java.util.function.Function<MyClass,java.util.List<java.lang.Double>> cannot be converted to java.util.function.Function<MyClass,java.util.List<? extends java.lang.Number>>
</code>```

I've successfully replaced duplicate methods with the wildcard before, as bellow

```<code>List<String> convertNumberListToStringList(List<Integer> numberList)
List<String> convertNumberListToStringList(List<Double> numberList)
</code>```

with

```<code>List<String> convertNumberListToStringList(List<? extends Number> numberList)
</code>```

I'm new to the idea of generics so I was curious as why the above would fail to compile? I do not quite understand why it would fail to compile

答: When you declare the instance of Function<MyClass, List<Number>> as Function<MyClass, List<Integer>> you restrict other types of number to be added to the List, i.e. Long and Double can't be added to the List<Integer>. Hence the incompatible type error.

Body:
I have some code with 3 overriding methods that perform the same operation ( code is identically for each method) on the Inputs, the only difference between them is the input parameter type

private List<String> extractDoubleValues(Function<MyClass, List<Double>> extractions)
private List<String> extractLongValues(Function<MyClass List<Long>> extractions)
private List<String> extractIntegerValues(Function<MyClass, List<Integer>> extractions)

I was trying to attempt to replace these 3 methods with a single method that makes us of generic wildcards as follows

private List<String> extractNumberValues(Function<MyClass, List<? extends Number>> extractions)

When I attempt to use the above generic method in place of one of the 3 type specific methods

Function<MyClass, List<Integer>> intExtractions;
List<String> extractedValues = extractNumberValues(intExtractions);

I get a the following compilation error on the second line of code above

Error:(59, 80) java: incompatible types: java.util.function.Function<MyClass,java.util.List<java.lang.Double>> cannot be converted to java.util.function.Function<MyClass,java.util.List<? extends java.lang.Number>>

I've successfully replaced duplicate methods with the wildcard before, as bellow

List<String> convertNumberListToStringList(List<Integer> numberList)
List<String> convertNumberListToStringList(List<Double> numberList)

with

List<String> convertNumberListToStringList(List<? extends Number> numberList)

I'm new to the idea of generics so I was curious as why the above would fail to compile? I do not quite understand why it would fail to compile