问:
Passing response from http.post to component.ts in angular2
I am trying to pass the response from http.post call in the typescript service component to the angular2 component so that i can display them in the frontend. Below is my service.ts and component.ts code structure.

```<code>getSearchProfileResponse(body) {
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers: headers});
    return this.http.post(this._url, body, options)
      .map((response:Response) => {
        console.log(JSON.stringify(response));
        JSON.stringify(response);
      })
      .catch((error) => {
        console.log("error is "+ error);
        return Observable.throw(error);
      });
  }

getProfile() {
    this.spinnerService.show();
    this.searchProfileRequest = _.cloneDeep(this.searchKey);
    this.searchProfileService.getSearchProfileResponse(this.searchProfileRequest)
      .subscribe(
        searchProfileResponse => {
          this.searchResult = searchProfileResponse;
          console.log("response in component is "+ searchProfileResponse);  // this is displayed as undefined
          console.log("search result is "+ this.searchResult);
          this.spinnerService.hide();
          this.showProfiles(this.searchResult);
        },
        error => {
          console.log(error);
          this.spinnerService.hide();
          this.showError();
        }
      );
  }
</code>```

My question is I could see the data from the controller being passed in the response in getSearchProfileResponse(body) method. But the response is showing as "undefined" in the getProfile() method's response. Any inputs is appreciated!

答:
You have missed putting return from .map() function.

Try below code:

```<code>getSearchProfileResponse(body) {
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers: headers});
    return this.http.post(this._url, body, options)
      .map((response:Response) => {
        console.log(JSON.stringify(response));
        return JSON.stringify(response);
      })
      .catch((error) => {
        console.log("error is "+ error);
        return Observable.throw(error);
      });
  }
</code>```

Body:
I am trying to pass the response from http.post call in the typescript service component to the angular2 component so that i can display them in the frontend. Below is my service.ts and component.ts code structure.

getSearchProfileResponse(body) {
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers: headers});
    return this.http.post(this._url, body, options)
      .map((response:Response) => {
        console.log(JSON.stringify(response));
        JSON.stringify(response);
      })
      .catch((error) => {
        console.log("error is "+ error);
        return Observable.throw(error);
      });
  }

getProfile() {
    this.spinnerService.show();
    this.searchProfileRequest = _.cloneDeep(this.searchKey);
    this.searchProfileService.getSearchProfileResponse(this.searchProfileRequest)
      .subscribe(
        searchProfileResponse => {
          this.searchResult = searchProfileResponse;
          console.log("response in component is "+ searchProfileResponse);  // this is displayed as undefined
          console.log("search result is "+ this.searchResult);
          this.spinnerService.hide();
          this.showProfiles(this.searchResult);
        },
        error => {
          console.log(error);
          this.spinnerService.hide();
          this.showError();
        }
      );
  }

My question is I could see the data from the controller being passed in the response in getSearchProfileResponse(body) method. But the response is showing as "undefined" in the getProfile() method's response. Any inputs is appreciated!

Body:
You have missed putting return from .map() function.

Try below code:

getSearchProfileResponse(body) {
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers: headers});
    return this.http.post(this._url, body, options)
      .map((response:Response) => {
        console.log(JSON.stringify(response));
        return JSON.stringify(response);
      })
      .catch((error) => {
        console.log("error is "+ error);
        return Observable.throw(error);
      });
  }


来源: stackexchange

问:
How vlookup between range values?
I have this challenge!!

How can I solve the problem below (picture) using any formula?

答:
Please try:

```<code>=INDEX(D$3:D$11,MATCH(A14&B14,A$3:A$11&C$3:C$11,1)+1)
</code>```

in C14 and copied down. It is an array formula to be entered with Ctrl+Shift+Enter.

Note that when at a break point it is the higher % that would be returned.

ContentLicense: CC BY-SA 3.0

Title: How vlookup between range values?

Body:
Please try:

=INDEX(D$3:D$11,MATCH(A14&B14,A$3:A$11&C$3:C$11,1)+1)

in C14 and copied down. It is an array formula to be entered with Ctrl+Shift+Enter.

Note that when at a break point it is the higher % that would be returned.


问:
Counting Sheep (Beatrix Trotter) Javascript
I am trying to solve a question on CodeWars that was part of the Google CodeJam 2016 qualification rounds.
https://www.codewars.com/kata/bleatrix-trotter-the-counting-sheep/train/javascript

I believe my code accounts for all test cases, my only issue is that it cannot be submitted on codewars because it has a runtime greater than 12000 ms.

How Can I make my Code more efficient?? also is there a best practice for testing whether the loop will be infinite.

```<code>function trotter(n) {
  var tracker = [];
  var sum = [];
  var snacker = n;
  for(var i = 0; tracker.length < 10; i++){
    sum = snacker.toString().split('');
    sum.forEach(function(num) {
        if (tracker.indexOf(num) == -1) {
             tracker.push(num);
        }
    });
    snacker += n;
  }
  return tracker.length === 10 ? snacker - n : "INSOMNIA";
}
</code>```

答:
When performance matters and reduced readability is not an issue you should:

Prefer for and while loops rather than built-ins like map, forEach...

In recent (2016) versions of JavaScript, it looks like for loops, specially reverse for loops, are the most performant option.

Also, keep in mind that you don't need to use its 3 expressions. For example, for me...:

```<code>let found = 0;

for (;found < 10;) {
</code>```

and

```<code>let j = chars.length;

for (;j;) {
</code>```

consistently returned better results than the same with the initialisation in the initialisation slot and than while loops, although in this latter case the difference was not so big.

For more one this, see Javascript Performance: While vs For Loops

When using foo.bar in a while's or for's expression, such as for (let i = 0; i < array.length; ++i), prefer to declare the limit condition above so that it is not evaluated each time, as that involves an object lookup:

```<code>const totalElements = array.length;

for (let i = 0; i < totalElements; ++i) { ... }
</code>```

Prefer pre-increment instead of post-increment. The latter will create a temporary variable storing the pre-incrementation value, which will return to you, while the former will first do the increment and then return the incremented value. No temporary variable needed.

For more on this, see post increment vs pre increment - Javascript Optimization

Actually, if the result is going to be the same regardless which one you use, then I would advise you to use pre-increment whenever possible.

Avoid built-in methods that have an equivalent expression. For example, (n + '') is more performant than n.toString().

Avoid type conversions and prefer using integers rather than floats or strings as modern JS engines tag variable types. That means that, on one hand, changing types will have a performance penalty, and, on the other hand, that using them consistently will allow the engine to do some type-specific optimisation.

For more on this, see https://www.html5rocks.com/en/tutorials/speed/v8/

Use bitwise operators when possible. For example, an integer division can be done with Math.floor(a  /b) or with a / b | 0, which is almost twice as fast.

For more on integer division in JavaScript, see this interesting thread: How to perform integer division and get the remainder in JavaScript?

Prefer an object lookup (object.prop or object['prop']) rather than using Array.prototype.indexOf(...).

See Javascript: what lookup is faster: array.indexOf vs object hash?

Avoid using arrays and objects and related methods when there are alternatives with simpler structures or inmutable data structures.

For example, @RobG's solution uses splice. While I'm not aware of the internal implementation, probably it is shifting the elements that come after the deleted ones to compact the array again and updating its length as well.

With my solution, however, the length of the array is always the same and you are just changing its values from false to true, which involves much less overhead, as there's no need to reallocate space.

Use typed arrays when possible, though I tried Uint8Array here, both assigning it true and 1, and none of them improved the times; the former actually almost doubled the time and the first one kept them more or less the same. Maybe it there was a BooleanArray it could work.

Keep in mind this is just a list of some techniques or features I think may help to speed up your example. I highly recommend you to read the external links I added as well in order to better understand how and why they work and where else they can be applied.

Moreover, in general, the lower level you keep your code, that is, you using basic data types and operations, the most performance it will be.

To prove that, below I show you a highly optimised version of this code that uses integer division (n / 10) | 0 and remainder (%).

function trotter(N) {
  if (N === 0) return 'INSOMNIA';

  const digits = [false, false, false, false, false, false, false, false, false, false];

  let n;
  let last = 0;
  let found = 0;

  for (;found < 10;) {
    n = last += N;

    for (;n;) {
      const digit = n % 10;

      n = (n / 10) | 0;

      if (!digits[digit]) {
        digits[digit] = true;

        ++found;
      }
    }
  }

  return last;
}

const numbers = [0, 2, 7, 125, 1625, 1692];
const outputs = ['INSOMNIA', 90, 70, 9000, 9750, 5076];

// CHECK IT WORKS FIRST:

numbers.map((number, index) => {
  if (trotter(number) !== outputs[index]) {
    console.log('EXPECTED = ' + outputs[index]);
    console.log('     GOT = ' + trotter(number));

    throw new Error('Incorrect value.');
  }
});

// PERF. TEST:

const ITERATIONS = 1000000;

const t0 = performance.now();

for (let i = 0; i < ITERATIONS; ++i) {
  numbers.map((number, index) => trotter(number));
}

const t1 = performance.now();

console.log(`AVG. TIME: ${ (t1 - t0) / ITERATIONS } ms. with ${ ITERATIONS } ITERATIONS`);```
</div>
</div>
</p>

```   AVG. TIME: 0.0033206450000000005 ms. with 1000000 ITERATIONS

     BROWSER: Google Chrome Version 59.0.3071.86 (Official Build) (64-bit)
          OS: macOS Sierra

BRAND, MODEL: MacBook Pro (Retina, 15-inch, Mid 2015)
   PROCESSOR: 2,8 GHz Intel Core i7
      MEMORY: 16 GB 1600 MHz DDR3
```

<p>Below you can see my initial answer, which uses some of the other optimisations listed here, but still converts the <code>number</code> variable <code>n</code> to <code>string</code> and uses <code>String.prototype.split()</code> to get its digits.</p>

<p>It is almost 5 times slower then the one above!</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function trotter(N) {
  if (N === 0) return 'INSOMNIA';

  const digits = [false, false, false, false, false, false, false, false, false, false];

  let n = N;
  let i = 0;
  let found = 0;

  for (;found < 10;) {
    // There's no need for this multiplication:

    n = N * ++i;

    // Type conversion + Built-in String.prototype.split(), both can
    // be avoided:

    const chars = (n + '').split('');

    let j = chars.length;

    for (;j;) {
      const digit = chars[--j];

      if (!digits[digit]) {
        digits[digit] = true;

        ++found;
      }
    }
  }

  return n;
}

const numbers = [0, 2, 7, 125, 1625, 1692];
const outputs = ['INSOMNIA', 90, 70, 9000, 9750, 5076];

// CHECK IT WORKS FIRST:

numbers.map((number, index) => {
  if (trotter(number) !== outputs[index]) {
    console.log('EXPECTED = ' + outputs[index]);
    console.log('     GOT = ' + trotter(number));

    throw new Error('Incorrect value.');
  }
});

// PERF. TEST:

const ITERATIONS = 1000000;

const t0 = performance.now();

for (let i = 0; i < ITERATIONS; ++i) {
  numbers.map((number, index) => trotter(number));
}

const t1 = performance.now();

console.log(`AVG. TIME: ${ (t1 - t0) / ITERATIONS } ms. with ${ ITERATIONS } ITERATIONS`);</code>```

```<code>   AVG. TIME: 0.016428575000000004 ms. with 1000000 ITERATIONS

     BROWSER: Google Chrome Version 59.0.3071.86 (Official Build) (64-bit)
          OS: macOS Sierra

BRAND, MODEL: MacBook Pro (Retina, 15-inch, Mid 2015)
   PROCESSOR: 2,8 GHz Intel Core i7
      MEMORY: 16 GB 1600 MHz DDR3
</code>```

Body:
I am trying to solve a question on CodeWars that was part of the Google CodeJam 2016 qualification rounds.
https://www.codewars.com/kata/bleatrix-trotter-the-counting-sheep/train/javascript

I believe my code accounts for all test cases, my only issue is that it cannot be submitted on codewars because it has a runtime greater than 12000 ms.

How Can I make my Code more efficient?? also is there a best practice for testing whether the loop will be infinite.

function trotter(n) {
  var tracker = [];
  var sum = [];
  var snacker = n;
  for(var i = 0; tracker.length < 10; i++){
    sum = snacker.toString().split('');
    sum.forEach(function(num) {
        if (tracker.indexOf(num) == -1) {
             tracker.push(num);
        }
    });
    snacker += n;
  }
  return tracker.length === 10 ? snacker - n : "INSOMNIA";
}

Body:
When performance matters and reduced readability is not an issue you should:

Prefer for and while loops rather than built-ins like map, forEach...

In recent (2016) versions of JavaScript, it looks like for loops, specially reverse for loops, are the most performant option.

Also, keep in mind that you don't need to use its 3 expressions. For example, for me...:

let found = 0;

for (;found < 10;) {

and

let j = chars.length;

for (;j;) {

consistently returned better results than the same with the initialisation in the initialisation slot and than while loops, although in this latter case the difference was not so big.

For more one this, see Javascript Performance: While vs For Loops

When using foo.bar in a while's or for's expression, such as for (let i = 0; i < array.length; ++i), prefer to declare the limit condition above so that it is not evaluated each time, as that involves an object lookup:

const totalElements = array.length;

for (let i = 0; i < totalElements; ++i) { ... }

Prefer pre-increment instead of post-increment. The latter will create a temporary variable storing the pre-incrementation value, which will return to you, while the former will first do the increment and then return the incremented value. No temporary variable needed.

For more on this, see post increment vs pre increment - Javascript Optimization

Actually, if the result is going to be the same regardless which one you use, then I would advise you to use pre-increment whenever possible.

Avoid built-in methods that have an equivalent expression. For example, (n + '') is more performant than n.toString().

Avoid type conversions and prefer using integers rather than floats or strings as modern JS engines tag variable types. That means that, on one hand, changing types will have a performance penalty, and, on the other hand, that using them consistently will allow the engine to do some type-specific optimisation.

For more on this, see https://www.html5rocks.com/en/tutorials/speed/v8/

Use bitwise operators when possible. For example, an integer division can be done with Math.floor(a  /b) or with a / b | 0, which is almost twice as fast.

For more on integer division in JavaScript, see this interesting thread: How to perform integer division and get the remainder in JavaScript?

Prefer an object lookup (object.prop or object['prop']) rather than using Array.prototype.indexOf(...).

See Javascript: what lookup is faster: array.indexOf vs object hash?

Avoid using arrays and objects and related methods when there are alternatives with simpler structures or inmutable data structures.

For example, @RobG's solution uses splice. While I'm not aware of the internal implementation, probably it is shifting the elements that come after the deleted ones to compact the array again and updating its length as well.

With my solution, however, the length of the array is always the same and you are just changing its values from false to true, which involves much less overhead, as there's no need to reallocate space.

Use typed arrays when possible, though I tried Uint8Array here, both assigning it true and 1, and none of them improved the times; the former actually almost doubled the time and the first one kept them more or less the same. Maybe it there was a BooleanArray it could work.

Keep in mind this is just a list of some techniques or features I think may help to speed up your example. I highly recommend you to read the external links I added as well in order to better understand how and why they work and where else they can be applied.

Moreover, in general, the lower level you keep your code, that is, you using basic data types and operations, the most performance it will be.

To prove that, below I show you a highly optimised version of this code that uses integer division (n / 10) | 0 and remainder (%).

function trotter(N) {
  if (N === 0) return 'INSOMNIA';

  const digits = [false, false, false, false, false, false, false, false, false, false];

  let n;
  let last = 0;
  let found = 0;

  for (;found < 10;) {
    n = last += N;

    for (;n;) {
      const digit = n % 10;

      n = (n / 10) | 0;

      if (!digits[digit]) {
        digits[digit] = true;

        ++found;
      }
    }
  }

  return last;
}

const numbers = [0, 2, 7, 125, 1625, 1692];
const outputs = ['INSOMNIA', 90, 70, 9000, 9750, 5076];

// CHECK IT WORKS FIRST:

numbers.map((number, index) => {
  if (trotter(number) !== outputs[index]) {
    console.log('EXPECTED = ' + outputs[index]);
    console.log('     GOT = ' + trotter(number));

    throw new Error('Incorrect value.');
  }
});

// PERF. TEST:

const ITERATIONS = 1000000;

const t0 = performance.now();

for (let i = 0; i < ITERATIONS; ++i) {
  numbers.map((number, index) => trotter(number));
}

const t1 = performance.now();

console.log(`AVG. TIME: ${ (t1 - t0) / ITERATIONS } ms. with ${ ITERATIONS } ITERATIONS`);

   AVG. TIME: 0.0033206450000000005 ms. with 1000000 ITERATIONS

     BROWSER: Google Chrome Version 59.0.3071.86 (Official Build) (64-bit)
          OS: macOS Sierra

BRAND, MODEL: MacBook Pro (Retina, 15-inch, Mid 2015)
   PROCESSOR: 2,8 GHz Intel Core i7
      MEMORY: 16 GB 1600 MHz DDR3

Below you can see my initial answer, which uses some of the other optimisations listed here, but still converts the number variable n to string and uses String.prototype.split() to get its digits.

It is almost 5 times slower then the one above!

function trotter(N) {
  if (N === 0) return 'INSOMNIA';

  const digits = [false, false, false, false, false, false, false, false, false, false];

  let n = N;
  let i = 0;
  let found = 0;

  for (;found < 10;) {
    // There's no need for this multiplication:

    n = N * ++i;

    // Type conversion + Built-in String.prototype.split(), both can
    // be avoided:

    const chars = (n + '').split('');

    let j = chars.length;

    for (;j;) {
      const digit = chars[--j];

      if (!digits[digit]) {
        digits[digit] = true;

        ++found;
      }
    }
  }

  return n;
}

const numbers = [0, 2, 7, 125, 1625, 1692];
const outputs = ['INSOMNIA', 90, 70, 9000, 9750, 5076];

// CHECK IT WORKS FIRST:

numbers.map((number, index) => {
  if (trotter(number) !== outputs[index]) {
    console.log('EXPECTED = ' + outputs[index]);
    console.log('     GOT = ' + trotter(number));

    throw new Error('Incorrect value.');
  }
});

// PERF. TEST:

const ITERATIONS = 1000000;

const t0 = performance.now();

for (let i = 0; i < ITERATIONS; ++i) {
  numbers.map((number, index) => trotter(number));
}

const t1 = performance.now();

console.log(`AVG. TIME: ${ (t1 - t0) / ITERATIONS } ms. with ${ ITERATIONS } ITERATIONS`);

   AVG. TIME: 0.016428575000000004 ms. with 1000000 ITERATIONS

     BROWSER: Google Chrome Version 59.0.3071.86 (Official Build) (64-bit)
          OS: macOS Sierra

BRAND, MODEL: MacBook Pro (Retina, 15-inch, Mid 2015)
   PROCESSOR: 2,8 GHz Intel Core i7
      MEMORY: 16 GB 1600 MHz DDR3


问:
SQL Query in Oracle where clause
I have table Groups with 3 rows, ID, GROUP_NAME and PARENT_GROUP_ID, the table itself presents a basic group-subgroup functionality. Example is: if my Group name is - "First Group" with ID = 1, and it has a subgroup named "Sub Group" with ID = 2, and PARENT_GROUP_ID = 1; this means that Sub Group is the subgroup of the group with ID = 1. My problem is that I have a procedure, which loads the data according to parameters(pn_parent_group_id is a number)

```<code>CURSOR c1 IS
SELECT * FROM GROUPS WHERE PARENT_GROUP_ID = pn_parent_group_id;
</code>```

This query works fine when I send any pn_parent_group_id into the procedure, and it finds all the necessary subgroups, however when I send NULL to the pn_parent_group_id it works wrong, because it should return those without parent_group_id(meaning only parent groups). I know my explanation is lacking, but I hope you got the idea, any help would be appreciated!

答:
Null is never equal to null. So you need to add an explicit test for null to your cursor.</p>

```<code>CURSOR c1 IS
    SELECT * FROM GROUPS
     WHERE PARENT_GROUP_ID = pn_parent_group_id
     or (pn_parent_group_id is null and parent_group_id is null);
</code>```

Title: SQL Query in Oracle where clause

Body:
I have table Groups with 3 rows, ID, GROUP_NAME and PARENT_GROUP_ID, the table itself presents a basic group-subgroup functionality. Example is: if my Group name is - "First Group" with ID = 1, and it has a subgroup named "Sub Group" with ID = 2, and PARENT_GROUP_ID = 1; this means that Sub Group is the subgroup of the group with ID = 1. My problem is that I have a procedure, which loads the data according to parameters(pn_parent_group_id is a number)

CURSOR c1 IS
SELECT * FROM GROUPS WHERE PARENT_GROUP_ID = pn_parent_group_id;

This query works fine when I send any pn_parent_group_id into the procedure, and it finds all the necessary subgroups, however when I send NULL to the pn_parent_group_id it works wrong, because it should return those without parent_group_id(meaning only parent groups). I know my explanation is lacking, but I hope you got the idea, any help would be appreciated!

Body:
Null is never equal to null. So you need to add an explicit test for null to your cursor.

CURSOR c1 IS
    SELECT * FROM GROUPS
     WHERE PARENT_GROUP_ID = pn_parent_group_id
     or (pn_parent_group_id is null and parent_group_id is null);


问:
Load dynamic functions in iOS app
I need to create this app with dynamic functions and screens.
    Lets say I got 2 types of users for the app - typeA and typeB.
    If typeA user logs in, he will only be presented and allowed to use functionA  and screenA
    If typeB user logs in, he will be presented with functionA  and screenA  PLUS functionB  and screenB.

When it goes to prod and the app gets installed on the device, it is rarely to happen that 2 types of users will login. It is just typeA or typeB.

Requirement is if its a typeA user that logs in, my app size and memory footprint should only be for functionA  and screenA. So by theory the app should be lighter than that of typeB.

Im not sure on the term here. But its like the original app will only have functionA  and screenA. But it typeB logs in, it will load the other functions and screens dynamically - that is not in the original app.

Is this possible?

答:
What you want isn't really possible. The binaries are precompiled before they're uploaded so the app size couldn't vary depending on the kind of user unless you cut two different binaries.

Swizzling methods based on user type is possible, though. Let's say you have a User (user) with an isPremium property. You could do something like this:

```<code>@IBAction func userTappedButton(_ sender: UIButton) {
   user.IsPremium ? performMethodOne() : performMethodTwo()
}
</code>```

That way if the user is premium method one is called, and if they're not method two is called. Presumably you would need a bunch of these checks all over your app.

Title: Load dynamic functions in iOS app

Body:
What you want isn't really possible. The binaries are precompiled before they're uploaded so the app size couldn't vary depending on the kind of user unless you cut two different binaries.

Swizzling methods based on user type is possible, though. Let's say you have a User (user) with an isPremium property. You could do something like this:

@IBAction func userTappedButton(_ sender: UIButton) {
   user.IsPremium ? performMethodOne() : performMethodTwo()
}

That way if the user is premium method one is called, and if they're not method two is called. Presumably you would need a bunch of these checks all over your app.


问:
No column in a table even after creation
I am making an app in Android Studio using java. I had created an internal database with two columns(name and productID) and everything was working just fine. when i added two more columns(Customer Name and Delivery date), it keeps crashing. The code for that activity is below as well as the logcat.

```<code>package com.kristar.busibooks;

import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import android.widget.Toast;

public class OrderActivity extends AppCompatActivity implements View.OnClickListener {

private EditText editCusTextName;
private EditText editTextName;
private EditText editTextAdd;
private EditText editDDTextName;
private Button btnAdd;
private Button btnView;
private Button btnCurrency;

private SQLiteDatabase db;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.content_order);

    createDatabase();

    editCusTextName = (EditText) findViewById(R.id.editCusTextName);
    editTextName = (EditText) findViewById(R.id.editTextName);
    editTextAdd = (EditText) findViewById(R.id.editTextpID);
    editDDTextName = (EditText) findViewById(R.id.editDDTextName);

    btnAdd = (Button) findViewById(R.id.btnAdd);
    btnView = (Button) findViewById(R.id.btnView);
    btnCurrency = (Button) findViewById(R.id.btnCurrency);

    btnAdd.setOnClickListener(this);
    btnView.setOnClickListener(this);
    btnCurrency.setOnClickListener(this);

    btnView.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent intentProduct = new Intent(getApplicationContext(), Products.class);
            startActivity(intentProduct);
        }
    });

    btnCurrency.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){
            Intent intentCurrencyConverter = new Intent(getApplicationContext(), CurrencyConverter.class);
            startActivity(intentCurrencyConverter);
        }
    });

}

protected void createDatabase(){
    db=openOrCreateDatabase("ProductDB", Context.MODE_PRIVATE, null);
    db.execSQL("CREATE TABLE IF NOT EXISTS product(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, Custo_name VARCHAR, name VARCHAR,productID INT, Deli_Date DATE);");
}

protected void insertIntoDB(){
    String cus_name = editCusTextName.getText().toString().trim();
    String name = editTextName.getText().toString().trim();
    String add = editTextAdd.getText().toString().trim();
    String d_date = editDDTextName.getText().toString().trim();
    if(cus_name.equals("") || name.equals("") || add.equals("") || d_date.equals("")){
        Toast.makeText(getApplicationContext(),"Please fill all fields", Toast.LENGTH_LONG).show();
        return;
    }

    String query = "INSERT INTO product (Custo_name,name,productID,Deli_Date) VALUES('"+cus_name+"', '"+name+"', '"+add+"', '"+d_date+"');";
    db.execSQL(query);
    Toast.makeText(getApplicationContext(),"Saved Successfully", Toast.LENGTH_LONG).show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onClick(View v) {
    if(v == btnAdd){
        insertIntoDB();
    }
}
</code>```

}

```<code>06-06 05:32:15.095 2362-2362/com.kristar.busibooks I/art: Not

late-enabling -Xcheck:jni (already on)
06-06 05:32:15.096 2362-2362/com.kristar.busibooks I/art: Late-enabling JIT
06-06 05:32:15.175 2362-2362/com.kristar.busibooks I/art: JIT created with code_cache_capacity=2MB compile_threshold=1000
06-06 05:32:15.592 2362-2362/com.kristar.busibooks W/System: ClassLoader referenced unknown path: /data/app/com.kristar.busibooks-2/lib/x86
06-06 05:32:16.065 2362-2373/com.kristar.busibooks I/art: WaitForGcToComplete blocked for 46.015ms for cause Background
06-06 05:32:17.134 2362-2376/com.kristar.busibooks D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
06-06 05:32:17.163 2362-2373/com.kristar.busibooks I/art: Background sticky concurrent mark sweep GC freed 9565(411KB) AllocSpace objects, 0(0B) LOS objects, 31% free, 2MB/3MB, paused 120.897ms total 1.085s
06-06 05:32:17.212 2362-2362/com.kristar.busibooks D/: HostConnection::get() New Host Connection established 0xab74d8e0, tid 2362
06-06 05:32:17.448 2362-2376/com.kristar.busibooks D/: HostConnection::get() New Host Connection established 0xab74dcb0, tid 2376
06-06 05:32:17.466 2362-2376/com.kristar.busibooks I/OpenGLRenderer: Initialized EGL, version 1.4
06-06 05:32:17.645 2362-2376/com.kristar.busibooks W/EGL_emulation: eglSurfaceAttrib not implemented
06-06 05:32:17.645 2362-2376/com.kristar.busibooks W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xabe7f900, error=EGL_SUCCESS
06-06 05:32:18.820 2362-2362/com.kristar.busibooks I/Choreographer: Skipped 64 frames!  The application may be doing too much work on its main thread.
06-06 05:32:24.125 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 7.568ms
06-06 05:32:24.333 2362-2376/com.kristar.busibooks W/EGL_emulation: eglSurfaceAttrib not implemented
06-06 05:32:24.333 2362-2376/com.kristar.busibooks W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xad6d1620, error=EGL_SUCCESS
06-06 05:32:24.682 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 35.944ms
06-06 05:32:26.172 2362-2362/com.kristar.busibooks I/Choreographer: Skipped 95 frames!  The application may be doing too much work on its main thread.
06-06 05:32:26.568 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 12.282ms
06-06 05:32:27.091 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 16.750ms
06-06 05:32:29.126 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 13.683ms
06-06 05:32:34.472 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 25.061ms
06-06 05:32:34.943 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 6.799ms
06-06 05:32:37.274 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 5.115ms
06-06 05:32:38.558 2362-2376/com.kristar.busibooks E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab755640
06-06 05:32:39.187 2362-2362/com.kristar.busibooks I/Choreographer: Skipped 201 frames!  The application may be doing too much work on its main thread.
06-06 05:32:41.686 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 27.114ms
06-06 05:32:45.302 2362-2376/com.kristar.busibooks W/EGL_emulation: eglSurfaceAttrib not implemented
06-06 05:32:45.302 2362-2376/com.kristar.busibooks W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xad6f0720, error=EGL_SUCCESS
06-06 05:32:45.485 2362-2376/com.kristar.busibooks E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab755640
06-06 05:32:46.455 2362-2376/com.kristar.busibooks W/EGL_emulation: eglSurfaceAttrib not implemented
06-06 05:32:46.455 2362-2376/com.kristar.busibooks W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xad6f0720, error=EGL_SUCCESS
06-06 05:32:46.551 2362-2376/com.kristar.busibooks E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab754920
06-06 05:32:46.703 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 77.331ms
06-06 05:32:46.739 2362-2362/com.kristar.busibooks I/Choreographer: Skipped 37 frames!  The application may be doing too much work on its main thread.
06-06 05:32:46.830 2362-2373/com.kristar.busibooks I/art: Background partial concurrent mark sweep GC freed 4946(325KB) AllocSpace objects, 0(0B) LOS objects, 39% free, 3MB/5MB, paused 26.008ms total 568.072ms
06-06 05:32:47.154 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 37.891ms
06-06 05:32:47.737 2362-2362/com.kristar.busibooks I/Choreographer: Skipped 58 frames!  The application may be doing too much work on its main thread.
06-06 05:32:53.132 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 33.821ms
06-06 05:32:54.141 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 32.107ms
06-06 05:32:57.998 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 29.788ms
06-06 05:32:58.477 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 5.348ms
06-06 05:33:06.832 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 57.211ms
06-06 05:33:06.841 2362-2362/com.kristar.busibooks E/SQLiteLog: (1) table product has no column named Custo_name
06-06 05:33:06.842 2362-2362/com.kristar.busibooks D/AndroidRuntime: Shutting down VM
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime: FATAL EXCEPTION: main
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime: Process: com.kristar.busibooks, PID: 2362
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime: android.database.sqlite.SQLiteException: table product has no column named Custo_name (code 1): , while compiling: INSERT INTO product (Custo_name,name,productID,Deli_Date) VALUES('fg', 'gh', '56', '2017-11-12');
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1674)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at com.kristar.busibooks.OrderActivity.insertIntoDB(OrderActivity.java:91)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at com.kristar.busibooks.OrderActivity.onClick(OrderActivity.java:122)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at android.view.View.performClick(View.java:5198)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at android.view.View$PerformClick.run(View.java:21147)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at android.os.Handler.handleCallback(Handler.java:739)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:95)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:148)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5417)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Native Method)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
06-06 05:33:09.908 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 7.133ms
06-06 05:33:12.921 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 43.865ms
06-06 05:33:14.574 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 7.056ms
06-06 05:33:15.794 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 14.265ms
06-06 05:33:22.451 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 13.150ms
</code>```

答:
In your code,

```<code>openOrCreateDatabase()
</code>```

creates new database only if the one does not exist.

and

```<code>CREATE TABLE IF NOT EXISTS
</code>```

does not alter old table, it only creates a new table if it does not even exist

The app's Database or it's TABLES are not removed until your code specifies or you uninstall the app.

If you want to keep old entries

use
    ALTER TABLE
instead,

Or you can just uninstall the app and run from Android studio then.

Body:
I am making an app in Android Studio using java. I had created an internal database with two columns(name and productID) and everything was working just fine. when i added two more columns(Customer Name and Delivery date), it keeps crashing. The code for that activity is below as well as the logcat.

package com.kristar.busibooks;

import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import android.widget.Toast;

public class OrderActivity extends AppCompatActivity implements View.OnClickListener {

private EditText editCusTextName;
private EditText editTextName;
private EditText editTextAdd;
private EditText editDDTextName;
private Button btnAdd;
private Button btnView;
private Button btnCurrency;

private SQLiteDatabase db;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.content_order);

    createDatabase();

    editCusTextName = (EditText) findViewById(R.id.editCusTextName);
    editTextName = (EditText) findViewById(R.id.editTextName);
    editTextAdd = (EditText) findViewById(R.id.editTextpID);
    editDDTextName = (EditText) findViewById(R.id.editDDTextName);

    btnAdd = (Button) findViewById(R.id.btnAdd);
    btnView = (Button) findViewById(R.id.btnView);
    btnCurrency = (Button) findViewById(R.id.btnCurrency);

    btnAdd.setOnClickListener(this);
    btnView.setOnClickListener(this);
    btnCurrency.setOnClickListener(this);

    btnView.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent intentProduct = new Intent(getApplicationContext(), Products.class);
            startActivity(intentProduct);
        }
    });

    btnCurrency.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){
            Intent intentCurrencyConverter = new Intent(getApplicationContext(), CurrencyConverter.class);
            startActivity(intentCurrencyConverter);
        }
    });

}

protected void createDatabase(){
    db=openOrCreateDatabase("ProductDB", Context.MODE_PRIVATE, null);
    db.execSQL("CREATE TABLE IF NOT EXISTS product(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, Custo_name VARCHAR, name VARCHAR,productID INT, Deli_Date DATE);");
}

protected void insertIntoDB(){
    String cus_name = editCusTextName.getText().toString().trim();
    String name = editTextName.getText().toString().trim();
    String add = editTextAdd.getText().toString().trim();
    String d_date = editDDTextName.getText().toString().trim();
    if(cus_name.equals("") || name.equals("") || add.equals("") || d_date.equals("")){
        Toast.makeText(getApplicationContext(),"Please fill all fields", Toast.LENGTH_LONG).show();
        return;
    }

    String query = "INSERT INTO product (Custo_name,name,productID,Deli_Date) VALUES('"+cus_name+"', '"+name+"', '"+add+"', '"+d_date+"');";
    db.execSQL(query);
    Toast.makeText(getApplicationContext(),"Saved Successfully", Toast.LENGTH_LONG).show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onClick(View v) {
    if(v == btnAdd){
        insertIntoDB();
    }
}

}

06-06 05:32:15.095 2362-2362/com.kristar.busibooks I/art: Not

late-enabling -Xcheck:jni (already on)
06-06 05:32:15.096 2362-2362/com.kristar.busibooks I/art: Late-enabling JIT
06-06 05:32:15.175 2362-2362/com.kristar.busibooks I/art: JIT created with code_cache_capacity=2MB compile_threshold=1000
06-06 05:32:15.592 2362-2362/com.kristar.busibooks W/System: ClassLoader referenced unknown path: /data/app/com.kristar.busibooks-2/lib/x86
06-06 05:32:16.065 2362-2373/com.kristar.busibooks I/art: WaitForGcToComplete blocked for 46.015ms for cause Background
06-06 05:32:17.134 2362-2376/com.kristar.busibooks D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
06-06 05:32:17.163 2362-2373/com.kristar.busibooks I/art: Background sticky concurrent mark sweep GC freed 9565(411KB) AllocSpace objects, 0(0B) LOS objects, 31% free, 2MB/3MB, paused 120.897ms total 1.085s
06-06 05:32:17.212 2362-2362/com.kristar.busibooks D/: HostConnection::get() New Host Connection established 0xab74d8e0, tid 2362
06-06 05:32:17.448 2362-2376/com.kristar.busibooks D/: HostConnection::get() New Host Connection established 0xab74dcb0, tid 2376
06-06 05:32:17.466 2362-2376/com.kristar.busibooks I/OpenGLRenderer: Initialized EGL, version 1.4
06-06 05:32:17.645 2362-2376/com.kristar.busibooks W/EGL_emulation: eglSurfaceAttrib not implemented
06-06 05:32:17.645 2362-2376/com.kristar.busibooks W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xabe7f900, error=EGL_SUCCESS
06-06 05:32:18.820 2362-2362/com.kristar.busibooks I/Choreographer: Skipped 64 frames!  The application may be doing too much work on its main thread.
06-06 05:32:24.125 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 7.568ms
06-06 05:32:24.333 2362-2376/com.kristar.busibooks W/EGL_emulation: eglSurfaceAttrib not implemented
06-06 05:32:24.333 2362-2376/com.kristar.busibooks W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xad6d1620, error=EGL_SUCCESS
06-06 05:32:24.682 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 35.944ms
06-06 05:32:26.172 2362-2362/com.kristar.busibooks I/Choreographer: Skipped 95 frames!  The application may be doing too much work on its main thread.
06-06 05:32:26.568 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 12.282ms
06-06 05:32:27.091 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 16.750ms
06-06 05:32:29.126 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 13.683ms
06-06 05:32:34.472 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 25.061ms
06-06 05:32:34.943 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 6.799ms
06-06 05:32:37.274 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 5.115ms
06-06 05:32:38.558 2362-2376/com.kristar.busibooks E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab755640
06-06 05:32:39.187 2362-2362/com.kristar.busibooks I/Choreographer: Skipped 201 frames!  The application may be doing too much work on its main thread.
06-06 05:32:41.686 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 27.114ms
06-06 05:32:45.302 2362-2376/com.kristar.busibooks W/EGL_emulation: eglSurfaceAttrib not implemented
06-06 05:32:45.302 2362-2376/com.kristar.busibooks W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xad6f0720, error=EGL_SUCCESS
06-06 05:32:45.485 2362-2376/com.kristar.busibooks E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab755640
06-06 05:32:46.455 2362-2376/com.kristar.busibooks W/EGL_emulation: eglSurfaceAttrib not implemented
06-06 05:32:46.455 2362-2376/com.kristar.busibooks W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xad6f0720, error=EGL_SUCCESS
06-06 05:32:46.551 2362-2376/com.kristar.busibooks E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab754920
06-06 05:32:46.703 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 77.331ms
06-06 05:32:46.739 2362-2362/com.kristar.busibooks I/Choreographer: Skipped 37 frames!  The application may be doing too much work on its main thread.
06-06 05:32:46.830 2362-2373/com.kristar.busibooks I/art: Background partial concurrent mark sweep GC freed 4946(325KB) AllocSpace objects, 0(0B) LOS objects, 39% free, 3MB/5MB, paused 26.008ms total 568.072ms
06-06 05:32:47.154 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 37.891ms
06-06 05:32:47.737 2362-2362/com.kristar.busibooks I/Choreographer: Skipped 58 frames!  The application may be doing too much work on its main thread.
06-06 05:32:53.132 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 33.821ms
06-06 05:32:54.141 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 32.107ms
06-06 05:32:57.998 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 29.788ms
06-06 05:32:58.477 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 5.348ms
06-06 05:33:06.832 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 57.211ms
06-06 05:33:06.841 2362-2362/com.kristar.busibooks E/SQLiteLog: (1) table product has no column named Custo_name
06-06 05:33:06.842 2362-2362/com.kristar.busibooks D/AndroidRuntime: Shutting down VM
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime: FATAL EXCEPTION: main
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime: Process: com.kristar.busibooks, PID: 2362
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime: android.database.sqlite.SQLiteException: table product has no column named Custo_name (code 1): , while compiling: INSERT INTO product (Custo_name,name,productID,Deli_Date) VALUES('fg', 'gh', '56', '2017-11-12');
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1674)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at com.kristar.busibooks.OrderActivity.insertIntoDB(OrderActivity.java:91)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at com.kristar.busibooks.OrderActivity.onClick(OrderActivity.java:122)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at android.view.View.performClick(View.java:5198)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at android.view.View$PerformClick.run(View.java:21147)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at android.os.Handler.handleCallback(Handler.java:739)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:95)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:148)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5417)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Native Method)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
06-06 05:33:06.843 2362-2362/com.kristar.busibooks E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
06-06 05:33:09.908 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 7.133ms
06-06 05:33:12.921 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 43.865ms
06-06 05:33:14.574 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 7.056ms
06-06 05:33:15.794 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 14.265ms
06-06 05:33:22.451 2362-2369/com.kristar.busibooks W/art: Suspending all threads took: 13.150ms

Body:
In your code,

openOrCreateDatabase()

creates new database only if the one does not exist.

and

CREATE TABLE IF NOT EXISTS

does not alter old table, it only creates a new table if it does not even exist

The app's Database or it's TABLES are not removed until your code specifies or you uninstall the app.

If you want to keep old entries

use
    ALTER TABLE
instead,

Or you can just uninstall the app and run from Android studio then.


问:
Simple PHP Login URL not connecting with code
I have been trying to make working php code which will return "1".

As well the database information is all removed, but is accurate since I get no "3" error.

Example being: www.mysite.com/login.php/?test=itemindatabase

and if "itemindatabase" is found in the database, then it will return "1"

A few notes:

login is the name of the table.

test is the name of the only column (other than id)

```<code><?php
 $host = "localhost";
 $username = "";
 $password = "";
 $database = "";

      $connect = new PDO("mysql:host=$host; dbname=$database", $username, $password);
      $connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
           if(empty($_POST["test"]))
           {
                die("3");
           }
           else
           {
                $query = "SELECT * FROM login WHERE test = :test";
                $statement = $connect->prepare($query);
                $statement->execute(
                     array(
                          'test'     =>     $_POST["test"]
                     )
                );
                $count = $statement->rowCount();
                if($count > 0)
                {
                     die("1"); //success!
                }
                else
                {
                     die("0"); //fail not found
                }
        }

?>
</code>```

I have only been getting "0" every try which means failure.

答:
Things:-

1.Your all db credentials are empty? if you removed them because of security issue then Ok. Otherwise please provide valid and correct values there.Otherwise connection itself will not create.

2.$_POST["test"] need to be  $_GET["test"]

3.array('test'=>$_POST["test"]) need to be array(':test'=>$_POST["test"])

Check this code and try:-

```<code><?php

 //comment these two lines when code started working fine
 error_reporting(E_ALL);
 ini_set('display_errors',1);

 $host = "localhost";
 $username = "";  //check and provide valid value
 $password = "";  //check and provide valid value
 $database = "";  //this can't be empty in any case

    try {
        $connect = new PDO("mysql:host=$host;dbname=$database", $username, $password);
        $connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

           if(!empty($_GET['test'])){
                $statement = $connect->prepare("SELECT * FROM login WHERE test = :test");
                $statement->execute(array(':test'=>$_GET["test"]));
                $count = $statement->rowCount();
                if($count > 0)
                {
                     echo "record found successfully";
                }
                else
                {
                     echo "no record found";
                }

           }else{
             echo "Please provide input value";
           }
    }
    catch(PDOException $e){
        echo "Error: " . $e->getMessage();
    }
    $conn = null;
?>
</code>```

Note:- How to fetch records

Body:
I have been trying to make working php code which will return "1".

As well the database information is all removed, but is accurate since I get no "3" error.

Example being: www.mysite.com/login.php/?test=itemindatabase

and if "itemindatabase" is found in the database, then it will return "1"

A few notes:

login is the name of the table.

test is the name of the only column (other than id)

<?php
 $host = "localhost";
 $username = "";
 $password = "";
 $database = "";

      $connect = new PDO("mysql:host=$host; dbname=$database", $username, $password);
      $connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
           if(empty($_POST["test"]))
           {
                die("3");
           }
           else
           {
                $query = "SELECT * FROM login WHERE test = :test";
                $statement = $connect->prepare($query);
                $statement->execute(
                     array(
                          'test'     =>     $_POST["test"]
                     )
                );
                $count = $statement->rowCount();
                if($count > 0)
                {
                     die("1"); //success!
                }
                else
                {
                     die("0"); //fail not found
                }
        }

?>

I have only been getting "0" every try which means failure.

Body:
Things:-

1.Your all db credentials are empty? if you removed them because of security issue then Ok. Otherwise please provide valid and correct values there.Otherwise connection itself will not create.

2.$_POST["test"] need to be  $_GET["test"]

3.array('test'=>$_POST["test"]) need to be array(':test'=>$_POST["test"])

Check this code and try:-

<?php

 //comment these two lines when code started working fine
 error_reporting(E_ALL);
 ini_set('display_errors',1);

 $host = "localhost";
 $username = "";  //check and provide valid value
 $password = "";  //check and provide valid value
 $database = "";  //this can't be empty in any case

    try {
        $connect = new PDO("mysql:host=$host;dbname=$database", $username, $password);
        $connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

           if(!empty($_GET['test'])){
                $statement = $connect->prepare("SELECT * FROM login WHERE test = :test");
                $statement->execute(array(':test'=>$_GET["test"]));
                $count = $statement->rowCount();
                if($count > 0)
                {
                     echo "record found successfully";
                }
                else
                {
                     echo "no record found";
                }

           }else{
             echo "Please provide input value";
           }
    }
    catch(PDOException $e){
        echo "Error: " . $e->getMessage();
    }
    $conn = null;
?>

Note:- How to fetch records


问:
angular-schema-form default, hidden values
I want to build a (section of a) form which produces the following output:

```<code>{
  ...
  offers: {
     context: "http://schema.org",
     minPrice: 3
  }
  ...
}
</code>```

The catch is, context should always be present - the only field the user gets to manipulate is minPrice. Immediately, a hidden field with a value comes to mind. So here's the schema definition:

```<code>$scope.schema = {
  ...
  offers: {
    type: 'object',
    properties: {
      minPrice: {
        type: 'number'
      }
    }
  }
  ...
};
</code>```

And here the form definition:

```<code>$scope.form = [
  ...
  {
    key: 'offers',
    type: 'fieldset',
    items: [
      {
        key: 'offers.minPrice',
        type: 'number'
      },
      {
        key: 'offers.context',
        type: 'hidden',
        default: 'http://schema.org'
      }
    ]
  }
  ...
];
</code>```

However, observing the generated model it's obvious the entry context is not present. I have successfully used a combination of type: 'hidden' and default with a tabarray, but I just can't get it right with an object. I am using version 0.8.13 of angular-schema-forms - the latest at the time of this writing.

I'd appreciate any insights, thanks.

答:
You must include context and it's default value within the schema in that version.

I expect that your issue relates to a bug which should have been fixed in the alphas for v1.0.0

It should work with:

Schema

{
  "type": "object",
  "properties": {
    "offers": {
      "type": "object",
      "properties": {
        "minPrice": {
          "type": "number"
        },
        "context": {
          "type": "string",
          "default": "http://schema.org"
        }
      }
    }
  }
}
```

<p><strong>Form</strong></p>

<pre class="lang-json prettyprint-override"><code>[
  {
    "type": "fieldset",
    "items": [
      {
        "key": "offers.minPrice",
        "type":"number"
      },
      {
        "key": "offers.context",
        "type": "hidden",
        "notitle": true
      }
    ]
  }
]
</code>```

Body:
I want to build a (section of a) form which produces the following output:

{
  ...
  offers: {
     context: "http://schema.org",
     minPrice: 3
  }
  ...
}

The catch is, context should always be present - the only field the user gets to manipulate is minPrice. Immediately, a hidden field with a value comes to mind. So here's the schema definition:

$scope.schema = {
  ...
  offers: {
    type: 'object',
    properties: {
      minPrice: {
        type: 'number'
      }
    }
  }
  ...
};

And here the form definition:

$scope.form = [
  ...
  {
    key: 'offers',
    type: 'fieldset',
    items: [
      {
        key: 'offers.minPrice',
        type: 'number'
      },
      {
        key: 'offers.context',
        type: 'hidden',
        default: 'http://schema.org'
      }
    ]
  }
  ...
];

However, observing the generated model it's obvious the entry context is not present. I have successfully used a combination of type: 'hidden' and default with a tabarray, but I just can't get it right with an object. I am using version 0.8.13 of angular-schema-forms - the latest at the time of this writing.

I'd appreciate any insights, thanks.

Body:
You must include context and it's default value within the schema in that version.

I expect that your issue relates to a bug which should have been fixed in the alphas for v1.0.0

It should work with:

Schema

{
  "type": "object",
  "properties": {
    "offers": {
      "type": "object",
      "properties": {
        "minPrice": {
          "type": "number"
        },
        "context": {
          "type": "string",
          "default": "http://schema.org"
        }
      }
    }
  }
}

Form

[
  {
    "type": "fieldset",
    "items": [
      {
        "key": "offers.minPrice",
        "type":"number"
      },
      {
        "key": "offers.context",
        "type": "hidden",
        "notitle": true
      }
    ]
  }
]


问:
JavaScript deletes the text in my textbox
I have multiple buttons with the rel attribute. I called them rel1, rel2 etc.

The rels contains data, that I retrieve with Javascript.

When I click on the button the button needs to send run a second JavaScript. The second JavaScript sends the rel to a textbox.

So far the script is working. But when I click on the button for the second rel the first textbox, that is filled with the data of rel1 gets empty.

Does someone know what the problem is and how I can solve it?

Here is the script for button1:

```<code><script type="text/javascript">
  $( document ).ready(function() {
    $('#grid1').DataTable({
      "bprocessing": true,
      "serverSide": true,
      "ajax": {
        "url": "response1.php",
        "type": "POST",
        "error": function(){
          $("#employee_grid_processing").css("display","none");
        }
      },
      "columnDefs": [ {
        "targets": 6,
        "render": function ( data, type, full, meta ) {
          return  '<button type="button" id="product_select1" rel1="'+data+'" onclick="getProduct1()">Button</button>';
        }
      } ]
    });
  });
</script>
</code>```

This scripts sends the data to the textbox:

```<code><script type="text/javascript">
  $('body').on('click', '.selectClass', function () {
    var product_txt1         = $(this).attr('rel1');

    $("#product_txt1").val(product_txt1);
    modal1.style.display = "none";

  });
</script>
</code>```

Maybe its neccesary. Here is my second script:

```<code><script type="text/javascript">
  $( document ).ready(function() {
    $('#grid2').DataTable({
      "bprocessing": true,
      "serverSide": true,
      "ajax": {
        "url": "response2.php",
        "type": "POST",
        "error": function(){
          $("#employee_grid_processing").css("display","none");
        }
      },
      "columnDefs": [ {
        "targets": 6,
        "render": function ( data, type, full, meta ) {
          return  '<button type="button" id="product_select1" rel2="'+data+'" onclick="getProduct2()">Button</button>';
        }
      } ]
    });
  });
</script>

<script type="text/javascript">
  $('body').on('click', '.selectClass', function () {
    var product_txt2         = $(this).attr('rel2');

    $("#product_txt2").val(product_txt2);
    modal2.style.display = "none";

  });
</script>
</code>```

答:
The problem is when you click one button, it triggle all click function. Because you handle click function by class. You need to specify your buttons by unique ID and handle click function by that ID. Either you can merge your click function like that:</p>

```<code>$('body').on('click', '.selectClass', function () {
    var product_txt1         = $(this).attr('rel1');
    var product_txt2         = $(this).attr('rel2');
    if(product_txt1 != null && product_txt1 != undefined){
        $("#product_txt1").val(product_txt1);
        modal1.style.display = "none";
    }
    if(product_txt2 != null && product_txt2 != undefined){
        $("#product_txt2").val(product_txt2);
        modal2.style.display = "none";
    }

  });
</code>```

Body:
I have multiple buttons with the rel attribute. I called them rel1, rel2 etc.

The rels contains data, that I retrieve with Javascript.

When I click on the button the button needs to send run a second JavaScript. The second JavaScript sends the rel to a textbox.

So far the script is working. But when I click on the button for the second rel the first textbox, that is filled with the data of rel1 gets empty.

Does someone know what the problem is and how I can solve it?

Here is the script for button1:

This scripts sends the data to the textbox:

Maybe its neccesary. Here is my second script:

Body:
The problem is when you click one button, it triggle all click function. Because you handle click function by class. You need to specify your buttons by unique ID and handle click function by that ID. Either you can merge your click function like that:

$('body').on('click', '.selectClass', function () {
    var product_txt1         = $(this).attr('rel1');
    var product_txt2         = $(this).attr('rel2');
    if(product_txt1 != null && product_txt1 != undefined){
        $("#product_txt1").val(product_txt1);
        modal1.style.display = "none";
    }
    if(product_txt2 != null && product_txt2 != undefined){
        $("#product_txt2").val(product_txt2);
        modal2.style.display = "none";
    }

  });


问:
How to make assert_select in a integration test select a css class?
I'm building my integrations tests, and i need to assure that a HTML tag has an specific integer as value, but i get this error:

```<code>ReportsTest
  test_report_shows_the_right_data_for_last_30_days              ERROR (0.94s)
NoMethodError:         NoMethodError: undefined method `content_type' for nil:NilClass
            test/integration/reports_test.rb:15:in `block in <class:ReportsTest>'
            test/test_helper.rb:45:in `instance_eval'
            test/test_helper.rb:45:in `block in test'
</code>```

This is my view:

```<code><div class="panel panel-default report-summary">
  <div class="panel-heading">
    <h3 class="panel-title">Resumen</h3>
  </div>
  <div class="panel-body">
    <div class="row">
      <div class="col-sm-4 summary-item">
        <div class="summary-value resources-count"><%= @resources_count %></div>
        <div class="summary-label">Recursos Publicados</div>
      </div>
      <div class="col-sm-4 summary-item">
        <div class="summary-value"><%= @likes_count %></div>
        <div class="summary-label">Likes</div>
      </div>
      <div class="col-sm-4 summary-item">
        <div class="summary-value"><%= @searches_count %></div>
        <div class="summary-label">Búsquedas</div>
      </div>
    </div>
    <div class="row">
      <div class="col-sm-4 summary-item">
        <div class="summary-value"><%= @comments_count %></div>
        <div class="summary-label">Comentarios</div>
      </div>
      <div class="col-sm-4 summary-item">
        <div class="summary-value"><%= @views_count %></div>
        <div class="summary-label">Vistas</div>
      </div>
      <div class="col-sm-4 summary-item">
        <div class="summary-value"><%= @users.count %></div>
        <div class="summary-label">Colaboradores</div>
      </div>
    </div>
  </div>
</div>
</code>```

This is my test:

```<code>require 'test_helper'

class ReportsTest < ActionDispatch::IntegrationTest
  test 'show report without time range', subdomain: :mainco do
    sign_in users(:juan)
    visit reports_path
    assert_equal 2, page.all(".report-resources table tbody tr").count
  end

  test 'report shows the right data for last 30 days', subdomain: :mainco do
    sign_in users(:juan)
    visit reports_path
    knowledge_bases(:sales).resources.create!(user: users(:juan),
        title: "JavaScript", type: "Discussion", created_at: 31.days.ago)

    assert_select ".resources-count" do |elements|
      elements.each do |element|
        assert_equal element, 1
      end
    end
  end

end
</code>```

It seems like my assert_select is not correctly finding the HTML tag with the css class resources-count.

Thanks for reading.

答:
Just use

```<code>assert_select '.resources-count', "1"
</code>```

See http://guides.rubyonrails.org/testing.html#testing-views

Body:
I'm building my integrations tests, and i need to assure that a HTML tag has an specific integer as value, but i get this error:

ReportsTest
  test_report_shows_the_right_data_for_last_30_days              ERROR (0.94s)
NoMethodError:         NoMethodError: undefined method `content_type' for nil:NilClass
            test/integration/reports_test.rb:15:in `block in <class:ReportsTest>'
            test/test_helper.rb:45:in `instance_eval'
            test/test_helper.rb:45:in `block in test'

This is my view:

Resumen

<%= @resources_count %>

Recursos Publicados

<%= @likes_count %>

Likes

<%= @searches_count %>

Búsquedas

<%= @comments_count %>

Comentarios

<%= @views_count %>

Vistas

<%= @users.count %>

Colaboradores

This is my test:

require 'test_helper'

class ReportsTest < ActionDispatch::IntegrationTest
  test 'show report without time range', subdomain: :mainco do
    sign_in users(:juan)
    visit reports_path
    assert_equal 2, page.all(".report-resources table tbody tr").count
  end

  test 'report shows the right data for last 30 days', subdomain: :mainco do
    sign_in users(:juan)
    visit reports_path
    knowledge_bases(:sales).resources.create!(user: users(:juan),
        title: "JavaScript", type: "Discussion", created_at: 31.days.ago)

    assert_select ".resources-count" do |elements|
      elements.each do |element|
        assert_equal element, 1
      end
    end
  end

end

It seems like my assert_select is not correctly finding the HTML tag with the css class resources-count.

Thanks for reading.

Body:
Just use

assert_select '.resources-count', "1"

See http://guides.rubyonrails.org/testing.html#testing-views


问:
Multiple submit buttons with values passed from buttons
The way I have structured the form is that there are multiple "Test Connection" submit buttons plus a "Save" submit button to save all the credentials and urls for each test connection. I have seen some suggested solutions but I don't feel like doing an ajax or javascript. So I'm wondering if this is possible. And by the way, I would like to pass values to the controller via the submit buttons as enum values and receive that enum in my controller.

I could easily make multiple ActionResults but it just feels so convoluted for me and if I have to change something in the test connection, I would have to change all. So I would like to have only one ActionResult method for TestConnection plus one Save ActionResult all within the same form.

When I click the Save button, all the credentials are sent to the controller as the ApplicationSettings model.

When I click the Test Connection button, I still receive the ApplicationSettings model plus the DatabaseSystems enum and depending on the enum received form the button, I would do the necessary connection.

Below are the code snippets but I just can't make them work.

Approaches tried:
1.  Blank form action, submit buttons has name as "Save" and "TestConnection" accordingly. - Save works. TestConnection does not work saying The resource cannot be found.
2.  Form action pointed to "TestConnection", TestConnection button names set as
"database" while value set as @DatabaseSystems.xxx, Save button set as "action:Save", ActionResult method for Save added [MultipleButton(Name = "action", Argument = "Save")] - TestConnection works, Save does not work saying ambiguous request.

I can't seem to figure out the config to make them both work. :(

View

```<code>@using Models.Enums
@model MyApp.Data.ApplicationSettings

@Html.AntiForgeryToken()
@using (Html.BeginForm())
{
<div class="row">
    <div class="col-md-2">
        @Html.EditorFor(model => model.con1_un, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con1_un) } })
    </div>
    <div class="col-md-2">
        @Html.EditorFor(model => model.con1_pw, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con1_pw) } })
    </div>
    <div class="col-md-7">
        @Html.EditorFor(model => model.con1_url, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con1_url), @rows = "1", @style = "max-width:520px !important" } })
    </div>
    <div class="col-md-1 pull-right">
        <button type="submit" class="btn btn-warning pull-right" name="database" value="@DatabaseSystems.System1" data-toggle="collapse" data-target="#loading"><span class="glyphicon glyphicon-link"></span>  Test Connection</button>
    </div>
</div>
<div class="row">
    <div class="col-md-2">
        @Html.EditorFor(model => model.con2_un, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con2_un) } })
    </div>
    <div class="col-md-2">
        @Html.EditorFor(model => model.con2_pw, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con2_pw) } })
    </div>
    <div class="col-md-7">
        @Html.EditorFor(model => model.con2_url, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con2_url), @rows = "1", @style = "max-width:520px !important" } })
    </div>
    <div class="col-md-1 pull-right">
        <button type="submit" class="btn btn-warning pull-right" name="database" value="@DatabaseSystems.System2" data-toggle="collapse" data-target="#loading"><span class="glyphicon glyphicon-link"></span>  Test Connection</button>
    </div>
</div>

<div class="row">
    <div class="col-md-2">
        @Html.EditorFor(model => model.con3_un, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con3_un) } })
    </div>
    <div class="col-md-2">
        @Html.EditorFor(model => model.con3_pw, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con3_pw) } })
    </div>
    <div class="col-md-7">
        @Html.EditorFor(model => model.con3_url, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con3_url), @rows = "1", @style = "max-width:520px !important" } })
    </div>
    <div class="col-md-1 pull-right">
        <button type="submit" class="btn btn-warning pull-right" name="database" value="@DatabaseSystems.System3" data-toggle="collapse" data-target="#loading"><span class="glyphicon glyphicon-link"></span>  Test Connection</button>
    </div>
</div>

... and many more test connections for different systems

<button type="submit" class="btn btn-success pull-right" name="Save" data-toggle="collapse" data-target="#loading"><span class="glyphicon glyphicon-floppy-disk"></span> Save</button>
}
</code>```

Controller

```<code>[HttpPost]
ActionResult TestConnection(ApplicationSettings model, DatabaseSystems database)
{
    // depending on the DatabaseSystems enum passed, then I'll do the necessary connection check.
{
[HttpPost]
ActionResult Save(ApplicationSettings model)
{
    // Save credentials entered in all the input fields above for con1, con2 & con3.
}
</code>```

Model

```<code>[Serializable]
public class ApplicationSettings
{
    public string con1_un { get; set; }
    public string con1_pw { get; set; }
    public string con1_url { get; set; }

    public string con2_un { get; set; }
    public string con2_pw { get; set; }
    public string con2_url { get; set; }

    public string con3_un { get; set; }
    public string con3_pw { get; set; }
    public string con3_url { get; set; }

    ... and many more systems
}
</code>```

Enum

```<code>public enum DatabaseSystems
{
    System1,
    System2,
    System3,
    ... and many more systems
}
</code>```

答:
Use single action name with different parameters for multiple submit button.and give name is same in both button but value is different

for check connectin

```<code><button type="submit" class="btn btn-warning pull-right" name="save" value="@DatabaseSystems.System3" data-toggle="collapse" data-target="#loading"><span class="glyphicon glyphicon-link"></span>  Test Connection</button>
</code>```

for save

```<code><button type="submit" class="btn btn-warning pull-right" name="Save" value="save" data-toggle="collapse" data-target="#loading"><span class="glyphicon glyphicon-link"></span>  Save</button>

    [HttpPost]
    ActionResult Save(ApplicationSettings model,string Save)
                {
    if(Save=="Testconnection")
    {
     //do your code on save
    }
    if(save="Save")
    {
     //do your code on save
     }
      }
</code>```

Body:
The way I have structured the form is that there are multiple "Test Connection" submit buttons plus a "Save" submit button to save all the credentials and urls for each test connection. I have seen some suggested solutions but I don't feel like doing an ajax or javascript. So I'm wondering if this is possible. And by the way, I would like to pass values to the controller via the submit buttons as enum values and receive that enum in my controller.

I could easily make multiple ActionResults but it just feels so convoluted for me and if I have to change something in the test connection, I would have to change all. So I would like to have only one ActionResult method for TestConnection plus one Save ActionResult all within the same form.

When I click the Save button, all the credentials are sent to the controller as the ApplicationSettings model.

When I click the Test Connection button, I still receive the ApplicationSettings model plus the DatabaseSystems enum and depending on the enum received form the button, I would do the necessary connection.

Below are the code snippets but I just can't make them work.

Approaches tried:
1.  Blank form action, submit buttons has name as "Save" and "TestConnection" accordingly. - Save works. TestConnection does not work saying The resource cannot be found.
2.  Form action pointed to "TestConnection", TestConnection button names set as
"database" while value set as @DatabaseSystems.xxx, Save button set as "action:Save", ActionResult method for Save added [MultipleButton(Name = "action", Argument = "Save")] - TestConnection works, Save does not work saying ambiguous request.

I can't seem to figure out the config to make them both work. :(

View

@using Models.Enums
@model MyApp.Data.ApplicationSettings

@Html.AntiForgeryToken()
@using (Html.BeginForm())
{

        @Html.EditorFor(model => model.con1_un, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con1_un) } })

        @Html.EditorFor(model => model.con1_pw, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con1_pw) } })

        @Html.EditorFor(model => model.con1_url, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con1_url), @rows = "1", @style = "max-width:520px !important" } })

        <button type="submit" class="btn btn-warning pull-right" name="database" value="@DatabaseSystems.System1" data-toggle="collapse" data-target="#loading">  Test Connection</button>

        @Html.EditorFor(model => model.con2_un, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con2_un) } })

        @Html.EditorFor(model => model.con2_pw, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con2_pw) } })

        @Html.EditorFor(model => model.con2_url, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con2_url), @rows = "1", @style = "max-width:520px !important" } })

        <button type="submit" class="btn btn-warning pull-right" name="database" value="@DatabaseSystems.System2" data-toggle="collapse" data-target="#loading">  Test Connection</button>

        @Html.EditorFor(model => model.con3_un, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con3_un) } })

        @Html.EditorFor(model => model.con3_pw, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con3_pw) } })

        @Html.EditorFor(model => model.con3_url, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con3_url), @rows = "1", @style = "max-width:520px !important" } })

        <button type="submit" class="btn btn-warning pull-right" name="database" value="@DatabaseSystems.System3" data-toggle="collapse" data-target="#loading">  Test Connection</button>

... and many more test connections for different systems

<button type="submit" class="btn btn-success pull-right" name="Save" data-toggle="collapse" data-target="#loading"> Save</button>
}

Controller

[HttpPost]
ActionResult TestConnection(ApplicationSettings model, DatabaseSystems database)
{
    // depending on the DatabaseSystems enum passed, then I'll do the necessary connection check.
{
[HttpPost]
ActionResult Save(ApplicationSettings model)
{
    // Save credentials entered in all the input fields above for con1, con2 & con3.
}

Model

[Serializable]
public class ApplicationSettings
{
    public string con1_un { get; set; }
    public string con1_pw { get; set; }
    public string con1_url { get; set; }

    public string con2_un { get; set; }
    public string con2_pw { get; set; }
    public string con2_url { get; set; }

    public string con3_un { get; set; }
    public string con3_pw { get; set; }
    public string con3_url { get; set; }

    ... and many more systems
}

Enum

public enum DatabaseSystems
{
    System1,
    System2,
    System3,
    ... and many more systems
}

Body:
Use single action name with different parameters for multiple submit button.and give name is same in both button but value is different

for check connectin

<button type="submit" class="btn btn-warning pull-right" name="save" value="@DatabaseSystems.System3" data-toggle="collapse" data-target="#loading"><span class="glyphicon glyphicon-link"></span>  Test Connection</button>

for save

<button type="submit" class="btn btn-warning pull-right" name="Save" value="save" data-toggle="collapse" data-target="#loading"><span class="glyphicon glyphicon-link"></span>  Save</button>

    [HttpPost]
    ActionResult Save(ApplicationSettings model,string Save)
                {
    if(Save=="Testconnection")
    {
     //do your code on save
    }
    if(save="Save")
    {
     //do your code on save
     }
      }


问:
Sql phone number constraint
Constraint for Phone Number. if it is starting with 03 then it must be 11 digits long, but if the digits are 10 then the second digit must not be 3. my code is not working correctly help please.</p>

```<code>c_Phone varchar(11) unique c_Phone check(c_Phone not like '%[^0-9]%'and
((c_Phone like '03%' and len(c_Phone)=11) or
(c_Phone like '0^3%' and len(c_Phone)=10))))
</code>```

答:
```<code>alter table dbo.Test
add constraint UQ_Phone unique (c_Phone)

alter table dbo.Test
add constraint CC_Phone  check
(
    c_Phone not like '%[^0-9]%'and
    ((c_Phone like '03%' and len(c_Phone) = 11) or
    (c_Phone not like '_3%' and len(c_Phone) = 10))
)
</code>```

Title: Sql phone number constraint

Body:
Constraint for Phone Number. if it is starting with 03 then it must be 11 digits long, but if the digits are 10 then the second digit must not be 3. my code is not working correctly help please.

c_Phone varchar(11) unique c_Phone check(c_Phone not like '%[^0-9]%'and
((c_Phone like '03%' and len(c_Phone)=11) or
(c_Phone like '0^3%' and len(c_Phone)=10))))


问:
Javascript while loop terminating without executing the statement
I want my program should work like: it should ask user for the answer over and over until correct answer and at the end alert with well done message.

Any help why it isn't woking that way????

```<code>var answer = prompt('What is the capital of Pakistan?');
while(answer != 'islamabad'){
  if(answer === 'islamabad'){
    alert('Your answer is correct!');
  }else if(answer != 'islamabad'){
    answer = prompt('Try again.');
  }else{
    alert('Well Done');
  }
}
</code>```

答:
This condition if(answer === 'islamabad') will never be true: you are checking if == islamabad after a condition which checks if != islamabad

```<code>while(answer != 'islamabad'){
    if(answer === 'islamabad'){   ◄ this will never be true
</code>```

Try using the following:

```<code>var answer = prompt('What is the capital of Pakistan?');
while(answer != 'islamabad'){
    answer = prompt('Try again.');
}
alert('Well Done');
</code>```

Body:
I want my program should work like: it should ask user for the answer over and over until correct answer and at the end alert with well done message.

Any help why it isn't woking that way????

var answer = prompt('What is the capital of Pakistan?');
while(answer != 'islamabad'){
  if(answer === 'islamabad'){
    alert('Your answer is correct!');
  }else if(answer != 'islamabad'){
    answer = prompt('Try again.');
  }else{
    alert('Well Done');
  }
}

Body:
This condition if(answer === 'islamabad') will never be true: you are checking if == islamabad after a condition which checks if != islamabad

while(answer != 'islamabad'){
    if(answer === 'islamabad'){   ◄ this will never be true

Try using the following:

var answer = prompt('What is the capital of Pakistan?');
while(answer != 'islamabad'){
    answer = prompt('Try again.');
}
alert('Well Done');


问:
What are some very useful JQuery plugins for social networking sites?
Any suggestions would be nice.</p>

答: You can find some suggestions here : 23 Facebook Style Plugins</p>

ContentLicense: CC BY-SA 2.5

Body: Any suggestions would be nice.


问:
I am trying to use Sikuli in my Selenium Webdriver test but due to image resolution the test is not clicking the image
When performing my test I captured the image of the File Name input field from File Upload windows pop up. The image resolution on my local machine is a bit different from the image resolution on the Windows Server 2012 VM machine so test keeps on failing as it tries to match the File Name input field image that I have in the Selenium WebDriver project and the image that is displayed in the VM. How to handle the resolution issue.

Local Machine image

Windows Server 2012 VM Machine image

答:
There is not much you can do about it. Your only solution is to create your patterns based on the resolution of the target machine or alternatively change the resolution of the target machine to match the one you are using for pattern creation.

The other thing I find peculiar is how did you configure SikuliX to run on a VM? There is a known limitation that it cannot run in headless mode. Unless you have configured some kind of VNC. Just make sure that the error you're getting is caused by the reason you mentioned and not due to this limitation.


问:
Windows Programming, window not opening, no build errors
I don't have much experience with windows programming, but can't specifically see what's wrong with this code, yet the window doesn't open. Although sometimes, not always, it will be open in task manager, so my guess is that it is registering the class and creating the window, but the problem is with the ShowWindow() function. But, I'm not positive.

To my understanding the flow of the program is:
Window is created with the registered class.
The window is shown.
Continuously looks for messages that are processed in the window Proc.

I feel like I've done all these things, so is my understanding wrong, or is my code missing something?

Thanks.

Source Code:

```<code>#include <Windows.h>

LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    if (uMsg == WM_DESTROY)
    {
        PostQuitMessage(0);
        return 0;
    }
    DefWindowProc(hwnd, uMsg, wParam, lParam);
}

int WINAPI wWinMain(HINSTANCE hinstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow)
{
    //Variable for message loop.
    MSG msg;

    //Setting up the window class.
    WNDCLASSEX windowClass;
    windowClass.cbSize = sizeof(windowClass);
    windowClass.style = CS_HREDRAW | CS_VREDRAW | CS_PARENTDC;
    windowClass.lpfnWndProc = WindowProc;
    windowClass.hInstance = hinstance;
    windowClass.hbrBackground = (HBRUSH)COLOR_WINDOW;
    windowClass.lpszClassName = "WindowClass";

    RegisterClassEx(&windowClass);

    HWND windowHandle = CreateWindowEx(WS_EX_OVERLAPPEDWINDOW, "WindowClass", "My Program", WS_OVERLAPPEDWINDOW, 500, 200, 800, 500, NULL, NULL, hinstance, 0);

    if (!windowHandle)
        return FALSE;

    ShowWindow(windowHandle, nCmdShow);

    // Start the message loop.
    while (GetMessage(&msg, NULL, 0, 0) != 0)
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    // Return the exit code to the system.
    return msg.wParam;
}
</code>```

答:
Your window procedure is invoking DefWindowProc but not actually returning the result, and you have undefined behavior because of that.  The return value is important, and it can control how the OS handles successive messages to your window.  For example, it's important to return the correct value in response to the WM_CREATE message.

Change your window procedure to:

```<code>LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    if (uMsg == WM_DESTROY)
    {
        PostQuitMessage(0);
        return 0;
    }
    return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
</code>```

Also, as Mark Ransom identified in the comments section, you should zero-initialize your WNDCLASSEX structure to ensure that you don't get garbage on any members that you didn't explicitly initialize.

Body:
I don't have much experience with windows programming, but can't specifically see what's wrong with this code, yet the window doesn't open. Although sometimes, not always, it will be open in task manager, so my guess is that it is registering the class and creating the window, but the problem is with the ShowWindow() function. But, I'm not positive.

To my understanding the flow of the program is:
Window is created with the registered class.
The window is shown.
Continuously looks for messages that are processed in the window Proc.

I feel like I've done all these things, so is my understanding wrong, or is my code missing something?

Thanks.

Source Code:

#include <Windows.h>

LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    if (uMsg == WM_DESTROY)
    {
        PostQuitMessage(0);
        return 0;
    }
    DefWindowProc(hwnd, uMsg, wParam, lParam);
}

int WINAPI wWinMain(HINSTANCE hinstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow)
{
    //Variable for message loop.
    MSG msg;

    //Setting up the window class.
    WNDCLASSEX windowClass;
    windowClass.cbSize = sizeof(windowClass);
    windowClass.style = CS_HREDRAW | CS_VREDRAW | CS_PARENTDC;
    windowClass.lpfnWndProc = WindowProc;
    windowClass.hInstance = hinstance;
    windowClass.hbrBackground = (HBRUSH)COLOR_WINDOW;
    windowClass.lpszClassName = "WindowClass";

    RegisterClassEx(&windowClass);

    HWND windowHandle = CreateWindowEx(WS_EX_OVERLAPPEDWINDOW, "WindowClass", "My Program", WS_OVERLAPPEDWINDOW, 500, 200, 800, 500, NULL, NULL, hinstance, 0);

    if (!windowHandle)
        return FALSE;

    ShowWindow(windowHandle, nCmdShow);

    // Start the message loop.
    while (GetMessage(&msg, NULL, 0, 0) != 0)
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    // Return the exit code to the system.
    return msg.wParam;
}

Body:
Your window procedure is invoking DefWindowProc but not actually returning the result, and you have undefined behavior because of that.  The return value is important, and it can control how the OS handles successive messages to your window.  For example, it's important to return the correct value in response to the WM_CREATE message.

Change your window procedure to:

LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    if (uMsg == WM_DESTROY)
    {
        PostQuitMessage(0);
        return 0;
    }
    return DefWindowProc(hwnd, uMsg, wParam, lParam);
}

Also, as Mark Ransom identified in the comments section, you should zero-initialize your WNDCLASSEX structure to ensure that you don't get garbage on any members that you didn't explicitly initialize.


问:
Complete a String containing comma and dot separated integers
Question:

Given an input String like "1,2,3..6..8,9..11", we have to convert it into "1,2,3,4,5,6,7,8,9,10,11". So basically we have to populate the ranges mentioned by dots. Below is my solution. Is there any better way to solve this ? Can we optimize this further ?

```<code>    public class FlattenAString {

    public static String flattenAString(String input) {
        StringBuilder sbr = new StringBuilder("");
        StringBuilder current = new StringBuilder("");
        StringBuilder next = new StringBuilder("");
        int i = 0;
        while (i < input.length()) {
            if (input.charAt(i) == '.') {
                i = i + 2;
                while (i != input.length() && input.charAt(i) != '.' && input.charAt(i) != ',') {
                    next.append(input.charAt(i));
                    i++;
                }
                int currentInt = Integer.parseInt(current.toString());
                int nextInt = Integer.parseInt(next.toString());
                appendFromCurrentTillPrevToNextInt(currentInt, nextInt, sbr);
                current = next;
                next = new StringBuilder("");
            } else if (input.charAt(i) == ',') {
                sbr.append(current);
                sbr.append(',');
                current = new StringBuilder("");
                i++;
            } else {
                current.append(input.charAt(i));
                i++;
            }
        }
        sbr.append(current);
        return sbr.toString();
    }

    private static void appendFromCurrentTillPrevToNextInt(int current, int val, StringBuilder sbr) {
        for (int i = current; i < val; i++) {
            sbr.append(i);
            sbr.append(',');
        }
    }
}
</code>```

答:
Try this.</p>

```<code>static final Pattern RANGE = Pattern.compile("(\\d+)(\\.\\.(\\d+))+");

static String flattenString(String input) {
    StringBuffer sb = new StringBuffer();
    StringBuilder temp = new StringBuilder();
    Matcher m = RANGE.matcher(input);
    while (m.find()) {
        int begin = Integer.parseInt(m.group(1));
        int end = Integer.parseInt(m.group(3));
        temp.setLength(0);
        for (int i = begin; i <= end; ++i)
            temp.append(",").append(i);
        m.appendReplacement(sb, temp.substring(1));
    }
    m.appendTail(sb);
    return sb.toString();
}
</code>```

Body:
Question:

Given an input String like "1,2,3..6..8,9..11", we have to convert it into "1,2,3,4,5,6,7,8,9,10,11". So basically we have to populate the ranges mentioned by dots. Below is my solution. Is there any better way to solve this ? Can we optimize this further ?

    public class FlattenAString {

    public static String flattenAString(String input) {
        StringBuilder sbr = new StringBuilder("");
        StringBuilder current = new StringBuilder("");
        StringBuilder next = new StringBuilder("");
        int i = 0;
        while (i < input.length()) {
            if (input.charAt(i) == '.') {
                i = i + 2;
                while (i != input.length() && input.charAt(i) != '.' && input.charAt(i) != ',') {
                    next.append(input.charAt(i));
                    i++;
                }
                int currentInt = Integer.parseInt(current.toString());
                int nextInt = Integer.parseInt(next.toString());
                appendFromCurrentTillPrevToNextInt(currentInt, nextInt, sbr);
                current = next;
                next = new StringBuilder("");
            } else if (input.charAt(i) == ',') {
                sbr.append(current);
                sbr.append(',');
                current = new StringBuilder("");
                i++;
            } else {
                current.append(input.charAt(i));
                i++;
            }
        }
        sbr.append(current);
        return sbr.toString();
    }

    private static void appendFromCurrentTillPrevToNextInt(int current, int val, StringBuilder sbr) {
        for (int i = current; i < val; i++) {
            sbr.append(i);
            sbr.append(',');
        }
    }
}

Body:
Try this.

static final Pattern RANGE = Pattern.compile("(\\d+)(\\.\\.(\\d+))+");

static String flattenString(String input) {
    StringBuffer sb = new StringBuffer();
    StringBuilder temp = new StringBuilder();
    Matcher m = RANGE.matcher(input);
    while (m.find()) {
        int begin = Integer.parseInt(m.group(1));
        int end = Integer.parseInt(m.group(3));
        temp.setLength(0);
        for (int i = begin; i <= end; ++i)
            temp.append(",").append(i);
        m.appendReplacement(sb, temp.substring(1));
    }
    m.appendTail(sb);
    return sb.toString();
}