问:
Case insensitive 'Contains(string)'
Is there a way to make the following return true?

```<code>string title = "ASTRINGTOTEST";
title.Contains("string");
</code>```

There doesn't seem to be an overload that allows me to set the case sensitivity. Currently I UPPERCASE them both, but that's just silly (by which I am referring to the i18n issues that come with up- and down casing).

UPDATE

This question is ancient and since then I have realized I asked for a simple answer for a really vast and difficult topic if you care to investigate it fully.

For most cases, in mono-lingual, English code bases this answer will suffice. I'm suspecting because most people coming here fall in this category this is the most popular answer.

This answer however brings up the inherent problem that we can't compare text case insensitive until we know both texts are the same culture and we know  what that culture is. This is maybe a less popular answer, but I think it is more correct and that's why I marked it as such.

答:
if you want to check if your passed string is in string then there is a simple method for that.

```<code>string yourStringForCheck= "abc";
string stringInWhichWeCheck= "Test abc abc";

bool isContained = stringInWhichWeCheck.ToLower().IndexOf(yourStringForCheck.ToLower()) > -1;
</code>```

This boolean value will return if the string is contained or not

OwnerDisplayName: boris callens

Title: Case insensitive 'Contains(string)'

Body:
Is there a way to make the following return true?

string title = "ASTRINGTOTEST";
title.Contains("string");

There doesn't seem to be an overload that allows me to set the case sensitivity. Currently I UPPERCASE them both, but that's just silly (by which I am referring to the i18n issues that come with up- and down casing).

UPDATE

This question is ancient and since then I have realized I asked for a simple answer for a really vast and difficult topic if you care to investigate it fully.

For most cases, in mono-lingual, English code bases this answer will suffice. I'm suspecting because most people coming here fall in this category this is the most popular answer.

This answer however brings up the inherent problem that we can't compare text case insensitive until we know both texts are the same culture and we know  what that culture is. This is maybe a less popular answer, but I think it is more correct and that's why I marked it as such.

LastEditorDisplayName: boris callens

Body:
if you want to check if your passed string is in string then there is a simple method for that.

string yourStringForCheck= "abc";
string stringInWhichWeCheck= "Test abc abc";

bool isContained = stringInWhichWeCheck.ToLower().IndexOf(yourStringForCheck.ToLower()) > -1;

This boolean value will return if the string is contained or not


来源: stackexchange

问:
delphi thread error in subform
I have problem when run a thread in subform.

main form

```<code>type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

uses Unit2;

procedure TForm1.Button1Click(Sender: TObject);
begin
TForm2.create(form1).ShowModal;
end;
</code>```

SUBform

```<code>type
TMthread=class(Tthread)
protected
procedure execute; override;
end;
type
TForm2 = class(TForm)
    Label1: TLabel;
    procedure FormShow(Sender: TObject);
  private
  public
  end;

var
  Form2: TForm2;

implementation

{$R *.dfm}

uses Unit1;

procedure TMthread.Execute;
begin
  synchronize( procedure
               begin
                 sleep(200);
                 freeonterminate:=true;
                 sleep(200);
                 form2.label1.Caption:='beep';
                 form1.button1.Caption:='beep';
               end);
end;

procedure TForm2.FormShow(Sender: TObject);
var Loadcombo2: TMthread;
begin
  Loadcombo2:=TMthread.Create(False);
end;
</code>```

Program

```<code>program Project1;

uses
  Vcl.Forms,
  Unit1 in 'Unit1.pas' {Form1},
  Unit2 in 'Unit2.pas' {Form2};

{$R *.res}

begin
  Application.Initialize;
  Application.MainFormOnTaskbar := True;
  Application.CreateForm(TForm1, Form1);
  Application.Run;
end.
</code>```

I got error in Execute Procedure when trying to access Form2.Label1.caption.

my test:

When I add the subform(Form2) in the Initialize section(last code) the the application runs without error, but doesn't change Label1.caption on the Form2.(Button1.caption on the main form is changed)

When I put exactly the same thread in main form it works without issues.

答:
The variable Form2 is never assigned. Because it is a global variable, its value is nil. Thus you encounter an error when you attempt to reference members of Form2.

You create an instance of Form2 like this:

```<code>TForm2.Create(Form1).ShowModal;
</code>```

I suspect that instead you mean to write something like this:

```<code>Form2 := TForm2.Create(Form1);
Try
  Form2.ShowModal;
Finally
  Form2.Free;
End;
</code>```

ContentLicense: CC BY-SA 3.0

Title: delphi thread error in subform

Body:
I have problem when run a thread in subform.

main form

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

uses Unit2;

procedure TForm1.Button1Click(Sender: TObject);
begin
TForm2.create(form1).ShowModal;
end;

SUBform

type
TMthread=class(Tthread)
protected
procedure execute; override;
end;
type
TForm2 = class(TForm)
    Label1: TLabel;
    procedure FormShow(Sender: TObject);
  private
  public
  end;

var
  Form2: TForm2;

implementation

{$R *.dfm}

uses Unit1;

procedure TMthread.Execute;
begin
  synchronize( procedure
               begin
                 sleep(200);
                 freeonterminate:=true;
                 sleep(200);
                 form2.label1.Caption:='beep';
                 form1.button1.Caption:='beep';
               end);
end;

procedure TForm2.FormShow(Sender: TObject);
var Loadcombo2: TMthread;
begin
  Loadcombo2:=TMthread.Create(False);
end;

Program

program Project1;

uses
  Vcl.Forms,
  Unit1 in 'Unit1.pas' {Form1},
  Unit2 in 'Unit2.pas' {Form2};

{$R *.res}

begin
  Application.Initialize;
  Application.MainFormOnTaskbar := True;
  Application.CreateForm(TForm1, Form1);
  Application.Run;
end.

I got error in Execute Procedure when trying to access Form2.Label1.caption.

my test:

When I add the subform(Form2) in the Initialize section(last code) the the application runs without error, but doesn't change Label1.caption on the Form2.(Button1.caption on the main form is changed)

When I put exactly the same thread in main form it works without issues.

Body:
The variable Form2 is never assigned. Because it is a global variable, its value is nil. Thus you encounter an error when you attempt to reference members of Form2.

You create an instance of Form2 like this:

TForm2.Create(Form1).ShowModal;

I suspect that instead you mean to write something like this:

Form2 := TForm2.Create(Form1);
Try
  Form2.ShowModal;
Finally
  Form2.Free;
End;


问:
Boxing..do I get it right?

Possible Duplicate:

  What is boxing and unboxing and what are the trade offs?

Hi,
From my understanding:
When I assign data of value type to (reference) type object variable, it gets boxed and the result is not actual reference as it points to copy of the value stored on the heap. Is that right?
Thanks

答:
Yes for the first part, assigning a value type to a reference variable will use boxing.
Basically using a value type in any context where a reference type is required will box the value.

And yes, (in the current implementation) the boxing operation will copy the value type to the heap, and return a reference to that location, even if the value is already on the heap (e.g. a value type property of an object), so you won't get a reference to the original value variable, but that is an implementation detail anyway, as value types should be treated as immutable.

ContentLicense: CC BY-SA 2.5

Title: Boxing..do I get it right?


问:
Capitalize first letter of all tables in database
I'm moving databases from windows to Linux and I have the issue of capitalization of table names. While normally, in Linux, the tables have first letter capitalized in windows they all become lower case making it impossible for them to work again in Linux. I can't mess with the servers' sql settings so I'm looking for a query that will solve my problems. After doing some research I combined a few results and ended up with the query below but it doesn't work as the second concat brings out a number. Any solutions?</p>

```<code>use information_schema;
SELECT
  CONCAT('RENAME TABLE ', TABLE_SCHEMA, '.', TABLE_NAME, ' TO ', TABLE_SCHEMA, '.', TABLE_NAME = CONCAT(UCASE(LEFT(TABLE_NAME, 1)),LCASE(SUBSTRING(TABLE_NAME, 2))), ';')
FROM
  information_schema.tables
WHERE `TABLE_SCHEMA` = "test";
</code>```

答:
I've been struggling recently with this and wrote a stored procedure that takes care of the table's first letter capitalization issue. It uses the SELECT statement of the previous answer to populate a temporary table. Then it iterates this temporary table and executes de statements. The procedure is really simple therefor it does not have grammatical intelligence, so that is up to you.
Here it goes:

```<code>CREATE DEFINER=`root`@`localhost` PROCEDURE `aux_uppercase_tablename`()
PROC: BEGIN
/*
Procedimiento que pone en mayúsculas la primera letra del nombre de las tablas,
excluyendo las tablas de auditoría (hay que mejorar el script para que lo haga).
No tiene la inteligencia para separar los nombres de tablas formados por dos o mas palabras,
por ejemplo, lineaventa, lineascomprobante, etc.
*/
DECLARE pIndex int;
DECLARE pInstruction varchar(500);
DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
        SELECT 'Error al procesar.' Mensaje;
        ROLLBACK;
    END;

SET @rowNum = 0;
DROP TEMPORARY TABLE IF EXISTS tmp_instructions;
CREATE TEMPORARY TABLE tmp_instructions ENGINE = MEMORY
    SELECT  (@rowNum := @rowNum + 1) rowNum, CONCAT('RENAME TABLE ', TABLE_NAME,
               ' TO ' ,CONCAT(UCASE(LEFT(TABLE_NAME,1)),SUBSTRING(TABLE_NAME,2)),';') instruction
    FROM    information_schema.TABLES
    WHERE   TABLE_SCHEMA = 'your_schema';

SET pIndex = 1;
WHILE (pIndex <= @rowNum) DO
    SET pInstruction = (SELECT instruction FROM tmp_instructions WHERE rowNum = pIndex);
    SET pIndex = pIndex + 1;

    CALL ssp_eval(pInstruction);

END WHILE;
DROP TEMPORARY TABLE IF EXISTS tmp_instructions;
SELECT 'OK';
END
</code>```

The ssp_eval procedure goes like this:

```<code>CREATE DEFINER=`root`@`localhost` PROCEDURE `ssp_eval`(pCadena mediumtext)
BEGIN
/*
Permite ejecutar una sentencia preparada leída de la base de datos,
como implementación de polimorfismo.
*/
-- SELECT pCadena;
SET @Cadena = pCadena;
PREPARE STMT FROM @Cadena;
EXECUTE STMT;
DEALLOCATE PREPARE STMT;
END
</code>```

Hope it work's for everyone with this issue! Greetings.

Body:
I'm moving databases from windows to Linux and I have the issue of capitalization of table names. While normally, in Linux, the tables have first letter capitalized in windows they all become lower case making it impossible for them to work again in Linux. I can't mess with the servers' sql settings so I'm looking for a query that will solve my problems. After doing some research I combined a few results and ended up with the query below but it doesn't work as the second concat brings out a number. Any solutions?

use information_schema;
SELECT
  CONCAT('RENAME TABLE ', TABLE_SCHEMA, '.', TABLE_NAME, ' TO ', TABLE_SCHEMA, '.', TABLE_NAME = CONCAT(UCASE(LEFT(TABLE_NAME, 1)),LCASE(SUBSTRING(TABLE_NAME, 2))), ';')
FROM
  information_schema.tables
WHERE `TABLE_SCHEMA` = "test";

Body:
I've been struggling recently with this and wrote a stored procedure that takes care of the table's first letter capitalization issue. It uses the SELECT statement of the previous answer to populate a temporary table. Then it iterates this temporary table and executes de statements. The procedure is really simple therefor it does not have grammatical intelligence, so that is up to you.
Here it goes:

CREATE DEFINER=`root`@`localhost` PROCEDURE `aux_uppercase_tablename`()
PROC: BEGIN
/*
Procedimiento que pone en mayúsculas la primera letra del nombre de las tablas,
excluyendo las tablas de auditoría (hay que mejorar el script para que lo haga).
No tiene la inteligencia para separar los nombres de tablas formados por dos o mas palabras,
por ejemplo, lineaventa, lineascomprobante, etc.
*/
DECLARE pIndex int;
DECLARE pInstruction varchar(500);
DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
        SELECT 'Error al procesar.' Mensaje;
        ROLLBACK;
    END;

SET @rowNum = 0;
DROP TEMPORARY TABLE IF EXISTS tmp_instructions;
CREATE TEMPORARY TABLE tmp_instructions ENGINE = MEMORY
    SELECT  (@rowNum := @rowNum + 1) rowNum, CONCAT('RENAME TABLE ', TABLE_NAME,
               ' TO ' ,CONCAT(UCASE(LEFT(TABLE_NAME,1)),SUBSTRING(TABLE_NAME,2)),';') instruction
    FROM    information_schema.TABLES
    WHERE   TABLE_SCHEMA = 'your_schema';

SET pIndex = 1;
WHILE (pIndex <= @rowNum) DO
    SET pInstruction = (SELECT instruction FROM tmp_instructions WHERE rowNum = pIndex);
    SET pIndex = pIndex + 1;

    CALL ssp_eval(pInstruction);

END WHILE;
DROP TEMPORARY TABLE IF EXISTS tmp_instructions;
SELECT 'OK';
END

The ssp_eval procedure goes like this:

CREATE DEFINER=`root`@`localhost` PROCEDURE `ssp_eval`(pCadena mediumtext)
BEGIN
/*
Permite ejecutar una sentencia preparada leída de la base de datos,
como implementación de polimorfismo.
*/
-- SELECT pCadena;
SET @Cadena = pCadena;
PREPARE STMT FROM @Cadena;
EXECUTE STMT;
DEALLOCATE PREPARE STMT;
END

Hope it work's for everyone with this issue! Greetings.


问:
Android services and Intent filters
When we declare something like this in the manifest, is it guaranteed that the service will be executed (if it is not already running) on receiving an intent of that type? Does this work the same way on Android Oreo 8.0?</p>

```<code>    <service
        android:name=".MyFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>
</code>```

答:
It depends Upon what type of Service you are using .

1.
Foreground-: A foreground service performs some operation that is noticeable to the user

2: Background:- Background service performs an operation that isn't directly noticed by the user. For example, if an app used a service to compact its storage, that would usually be a background service.

```<code>Note: If your app targets API level 26 or higher, the system imposes restrictions on running background services when the app itself is not in the foreground. In most cases like this, your app should use a scheduled job instead.
</code>```

3. Bound
    A service is bound when an application component binds to it by calling bindService().

So as you see on note for android Oreo or higher there are certain limitations on Background service. For More info on topic you can read Here.

Title: Android services and Intent filters

Body:
When we declare something like this in the manifest, is it guaranteed that the service will be executed (if it is not already running) on receiving an intent of that type? Does this work the same way on Android Oreo 8.0?

    <service
        android:name=".MyFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>

Body:
It depends Upon what type of Service you are using .

1.
Foreground-: A foreground service performs some operation that is noticeable to the user

2: Background:- Background service performs an operation that isn't directly noticed by the user. For example, if an app used a service to compact its storage, that would usually be a background service.

Note: If your app targets API level 26 or higher, the system imposes restrictions on running background services when the app itself is not in the foreground. In most cases like this, your app should use a scheduled job instead.

3. Bound
    A service is bound when an application component binds to it by calling bindService().

So as you see on note for android Oreo or higher there are certain limitations on Background service. For More info on topic you can read Here.


问:
Fetch only specific objects from JSON via javascript or jQuery
I would like to fetch only specific objects from the below JSON such as only those JSON objects which have a classDefinition = "com.sap.bpm.wfs.UserTask". Please suggest on how to do this:</p>

```<code>var metadata = {
    "contents": {
        "83eaead8-cfae-459b-9bdd-8b12e32d6715": {
            "classDefinition": "com.sap.bpm.wfs.StartEvent",
            "id": "startevent1",
            "name": "StartEvent1"
        },
        "13583ac9-596d-4375-b9e1-e5f6f21e829f": {
            "classDefinition": "com.sap.bpm.wfs.EndEvent",
            "id": "endevent1",
            "name": "EndEvent1"
        },
        "6c2b0935-444b-4299-ac8e-92973ce93558": {
            "classDefinition": "com.sap.bpm.wfs.UserTask",
            "subject": "Upload document",
            "description": "{context.description}",
            "priority": "MEDIUM",
            "isHiddenInLogForParticipant": false,
            "userInterface": "sapui5://html5apps/saptest/com.sap.test",
            "recipientUsers": "I311520, I310811",
            "id": "usertask1",
            "name": "UserTask1"
        },
        "6728bf81-3d4e-4ae3-a428-1700a2096d34": {
            "classDefinition": "com.sap.bpm.wfs.SequenceFlow",
            "id": "sequenceflow1",
            "name": "SequenceFlow1",
            "sourceRef": "83eaead8-cfae-459b-9bdd-8b12e32d6715",
            "targetRef": "6c2b0935-444b-4299-ac8e-92973ce93558"
        },
        "aa99931e-2523-44c3-86b3-d522acdbde10": {
            "classDefinition": "com.sap.bpm.wfs.ui.Diagram",
            "symbols": {
                "760f0725-3400-4d48-b082-5c69ad79d697": {},
                "aa9a0d10-63be-4af8-9ac2-4d2b648a18fc": {},
                "7fbd11bb-cf82-4a27-97d7-e80dda2014ee": {},
                "20c66c48-6058-465e-b500-d69d6e54c028": {},
                "2e8f324c-5361-4512-a09a-fc7693f206ba": {}
            }
        }
    }
};
</code>```

答:
Or you can do one by one

var metadata = {
    "contents": {
        "83eaead8-cfae-459b-9bdd-8b12e32d6715": {
            "classDefinition": "com.sap.bpm.wfs.StartEvent",
            "id": "startevent1",
            "name": "StartEvent1"
        },
        "13583ac9-596d-4375-b9e1-e5f6f21e829f": {
            "classDefinition": "com.sap.bpm.wfs.EndEvent",
            "id": "endevent1",
            "name": "EndEvent1"
        },
        "6c2b0935-444b-4299-ac8e-92973ce93558": {
            "classDefinition": "com.sap.bpm.wfs.UserTask",
            "subject": "Upload document",
            "description": "{context.description}",
            "priority": "MEDIUM",
            "isHiddenInLogForParticipant": false,
            "userInterface": "sapui5://html5apps/saptest/com.sap.test",
            "recipientUsers": "I311520, I310811",
            "id": "usertask1",
            "name": "UserTask1"
        },
        "6728bf81-3d4e-4ae3-a428-1700a2096d34": {
            "classDefinition": "com.sap.bpm.wfs.SequenceFlow",
            "id": "sequenceflow1",
            "name": "SequenceFlow1",
            "sourceRef": "83eaead8-cfae-459b-9bdd-8b12e32d6715",
            "targetRef": "6c2b0935-444b-4299-ac8e-92973ce93558"
        },
        "aa99931e-2523-44c3-86b3-d522acdbde10": {
            "classDefinition": "com.sap.bpm.wfs.ui.Diagram",
            "symbols": {
                "760f0725-3400-4d48-b082-5c69ad79d697": {},
                "aa9a0d10-63be-4af8-9ac2-4d2b648a18fc": {},
                "7fbd11bb-cf82-4a27-97d7-e80dda2014ee": {},
                "20c66c48-6058-465e-b500-d69d6e54c028": {},
                "2e8f324c-5361-4512-a09a-fc7693f206ba": {}
            }
        }
    }
}
var content = metadata["contents"];
var subContent = content["6c2b0935-444b-4299-ac8e-92973ce93558"];
var classDef = subContent["classDefinition"];
alert(classDef);```

Body:
I would like to fetch only specific objects from the below JSON such as only those JSON objects which have a classDefinition = "com.sap.bpm.wfs.UserTask". Please suggest on how to do this:

var metadata = {
    "contents": {
        "83eaead8-cfae-459b-9bdd-8b12e32d6715": {
            "classDefinition": "com.sap.bpm.wfs.StartEvent",
            "id": "startevent1",
            "name": "StartEvent1"
        },
        "13583ac9-596d-4375-b9e1-e5f6f21e829f": {
            "classDefinition": "com.sap.bpm.wfs.EndEvent",
            "id": "endevent1",
            "name": "EndEvent1"
        },
        "6c2b0935-444b-4299-ac8e-92973ce93558": {
            "classDefinition": "com.sap.bpm.wfs.UserTask",
            "subject": "Upload document",
            "description": "{context.description}",
            "priority": "MEDIUM",
            "isHiddenInLogForParticipant": false,
            "userInterface": "sapui5://html5apps/saptest/com.sap.test",
            "recipientUsers": "I311520, I310811",
            "id": "usertask1",
            "name": "UserTask1"
        },
        "6728bf81-3d4e-4ae3-a428-1700a2096d34": {
            "classDefinition": "com.sap.bpm.wfs.SequenceFlow",
            "id": "sequenceflow1",
            "name": "SequenceFlow1",
            "sourceRef": "83eaead8-cfae-459b-9bdd-8b12e32d6715",
            "targetRef": "6c2b0935-444b-4299-ac8e-92973ce93558"
        },
        "aa99931e-2523-44c3-86b3-d522acdbde10": {
            "classDefinition": "com.sap.bpm.wfs.ui.Diagram",
            "symbols": {
                "760f0725-3400-4d48-b082-5c69ad79d697": {},
                "aa9a0d10-63be-4af8-9ac2-4d2b648a18fc": {},
                "7fbd11bb-cf82-4a27-97d7-e80dda2014ee": {},
                "20c66c48-6058-465e-b500-d69d6e54c028": {},
                "2e8f324c-5361-4512-a09a-fc7693f206ba": {}
            }
        }
    }
};


问:
Android: SQLite part or full word search not working using SELECT query
I have 10 movie names in SQLite database. I am searching in the database using SearchView and storing result data into ArrayList and then displaying in custom ListView.
The problem is, it works sometimes only. For example, when I search for "the god" or "god" it returns "The Godfather" but when I search for "the shaw" or "shaw" it doesn't return "The Shawshank Redemption". Also, when searching "the" it returns all the movie names starting with "the" like The Godfather, The good, bad and the ugly, the Shawshank redemption etc. I have the below code. Also "Not found" toast is never getting triggered.

SearchActivity.java

```<code>            searchView = findViewById(R.id.searchBar);
            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {

                    myDB = new DatabaseHelper(SearchActivity.this);

                    data = myDB.searchRecord(query);//Sends search term to database helper which returns all data found according to the search term

                    if (data==null){
                        Toasty.error(SearchActivity.this, "Not found", Toast.LENGTH_SHORT, true);
                    }else {
                        searchResultMethod();//Calling method which stores curser data in arraylist
                    }
            return false;
            }

        private void searchResultMethod() {
            if(data == null)
            {
                Toast toastem = Toasty.warning(SearchActivity.this, "Database is empty", Toast.LENGTH_SHORT, true);
                toastem.show();
             }else{
                while(data.moveToNext())
                {
                    arrayListTitle.add(data.getString(1));
                    arrayListYear.add(data.getString(2));
                    arrayListRating.add(data.getString(3));
                    arrayListThumb.add(data.getString(4));
                    arrayListUrl.add(data.getString(5));
                 }
        }
         CustomSearchListAdapter customSearchListAdapter = new CustomSearchListAdapter(SearchActivity.this,arrayListTitle, arrayListYear, arrayListRating, arrayListThumb, arrayListUrl);

    searchListView.setAdapter(customSearchListAdapter);
    searchListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Intent webActivityIntent = new Intent(SearchActivity.this, WebViewActivity.class);
                                            webActivityIntent.putExtra("url_list",arrayListUrl);//Sending imdb url to web view activity
                                            webActivityIntent.putExtra("position",i);
                                            startActivity(webActivityIntent);

   }
 });

}
</code>```

searchRecord() method in DatabaseHelper.java

```<code>public Cursor searchRecord(String searchTerm)
{
    db = this.getReadableDatabase();
    String query ="SELECT  *  FROM " + TABLE_NAME + " WHERE title LIKE '%" + searchTerm + "%' OR '" + searchTerm + "%' OR '%" + searchTerm + "'";

    Cursor c = db.rawQuery(query, null);

    if (c == null) {
        return null;
    } else if (!c.moveToFirst()) {
        c.close();
        return null;
    }

    return c;
}
</code>```

I can not figure out what I am doing wrong. Any help is appreciated.

答:
It looks like you first execute c.moveToFirst(), then data.moveToNext() and then process data. You miss the first row. Change

```<code>            while(data.moveToNext())
            {
                arrayListTitle.add(data.getString(1));
                arrayListYear.add(data.getString(2));
                arrayListRating.add(data.getString(3));
                arrayListThumb.add(data.getString(4));
                arrayListUrl.add(data.getString(5));
             }
</code>```

to

```<code>            do
            {
                arrayListTitle.add(data.getString(1));
                arrayListYear.add(data.getString(2));
                arrayListRating.add(data.getString(3));
                arrayListThumb.add(data.getString(4));
                arrayListUrl.add(data.getString(5));
             }
            while(data.moveToNext())
</code>```

Body:
I have 10 movie names in SQLite database. I am searching in the database using SearchView and storing result data into ArrayList and then displaying in custom ListView.
The problem is, it works sometimes only. For example, when I search for "the god" or "god" it returns "The Godfather" but when I search for "the shaw" or "shaw" it doesn't return "The Shawshank Redemption". Also, when searching "the" it returns all the movie names starting with "the" like The Godfather, The good, bad and the ugly, the Shawshank redemption etc. I have the below code. Also "Not found" toast is never getting triggered.

SearchActivity.java

            searchView = findViewById(R.id.searchBar);
            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {

                    myDB = new DatabaseHelper(SearchActivity.this);

                    data = myDB.searchRecord(query);//Sends search term to database helper which returns all data found according to the search term

                    if (data==null){
                        Toasty.error(SearchActivity.this, "Not found", Toast.LENGTH_SHORT, true);
                    }else {
                        searchResultMethod();//Calling method which stores curser data in arraylist
                    }
            return false;
            }

        private void searchResultMethod() {
            if(data == null)
            {
                Toast toastem = Toasty.warning(SearchActivity.this, "Database is empty", Toast.LENGTH_SHORT, true);
                toastem.show();
             }else{
                while(data.moveToNext())
                {
                    arrayListTitle.add(data.getString(1));
                    arrayListYear.add(data.getString(2));
                    arrayListRating.add(data.getString(3));
                    arrayListThumb.add(data.getString(4));
                    arrayListUrl.add(data.getString(5));
                 }
        }
         CustomSearchListAdapter customSearchListAdapter = new CustomSearchListAdapter(SearchActivity.this,arrayListTitle, arrayListYear, arrayListRating, arrayListThumb, arrayListUrl);

    searchListView.setAdapter(customSearchListAdapter);
    searchListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Intent webActivityIntent = new Intent(SearchActivity.this, WebViewActivity.class);
                                            webActivityIntent.putExtra("url_list",arrayListUrl);//Sending imdb url to web view activity
                                            webActivityIntent.putExtra("position",i);
                                            startActivity(webActivityIntent);

   }
 });

}

searchRecord() method in DatabaseHelper.java

public Cursor searchRecord(String searchTerm)
{
    db = this.getReadableDatabase();
    String query ="SELECT  *  FROM " + TABLE_NAME + " WHERE title LIKE '%" + searchTerm + "%' OR '" + searchTerm + "%' OR '%" + searchTerm + "'";

    Cursor c = db.rawQuery(query, null);

    if (c == null) {
        return null;
    } else if (!c.moveToFirst()) {
        c.close();
        return null;
    }

    return c;
}

I can not figure out what I am doing wrong. Any help is appreciated.

Body:
It looks like you first execute c.moveToFirst(), then data.moveToNext() and then process data. You miss the first row. Change

            while(data.moveToNext())
            {
                arrayListTitle.add(data.getString(1));
                arrayListYear.add(data.getString(2));
                arrayListRating.add(data.getString(3));
                arrayListThumb.add(data.getString(4));
                arrayListUrl.add(data.getString(5));
             }

to

            do
            {
                arrayListTitle.add(data.getString(1));
                arrayListYear.add(data.getString(2));
                arrayListRating.add(data.getString(3));
                arrayListThumb.add(data.getString(4));
                arrayListUrl.add(data.getString(5));
             }
            while(data.moveToNext())


问:
Context Variable support for Amazon lex chatbot
I am trying to build a chatbot version of AWS management console and wanted to see if I can use  things like region as environment variable instead of prompting it every time . Is there something like that ? </p>

答:
You can define environment variables in AWS Lambda "Environment variables" section and use it in your code.
If you want to use custom environment variable in your code, you need to define it, and then use it in code like below:

```<code>import os
#assuming your environment variable is named as "name"
name = os.environ['name']
</code>```

If you want to use pre-defined environment variables, you can use them as well. Example: AWS_REGION environment variable will give the name of region where lambda function is being executed. Like mine is giving me us-east-1 as output.

```<code>import os
os.environ['AWS_REGION']
</code>```

Body:
You can define environment variables in AWS Lambda "Environment variables" section and use it in your code.
If you want to use custom environment variable in your code, you need to define it, and then use it in code like below:

import os
#assuming your environment variable is named as "name"
name = os.environ['name']

If you want to use pre-defined environment variables, you can use them as well. Example: AWS_REGION environment variable will give the name of region where lambda function is being executed. Like mine is giving me us-east-1 as output.

import os
os.environ['AWS_REGION']


问:
Are the page-size going to be doubled in Server-side Rendering (SSR) + React + Redux?
Server-side Rendering (SSR) + React + Redux assumes that server puts both the fully rendered page and the inital state of the Redux store into the sent HTML. For a text-heavy page with most of the text also part of the state, doesn't it mean the same information is going to be sent twice (just in different form)? Doesn't that mean we are unnecessarily doubling the page size?

答:
Well, yes, but only if you are not compressing your http responses. In this case if all your initial state data is duplicated as the content of the first page rendered by server, you will basically receive twice as much data on page loading phase compared to what you'd get in client-only rendering scenario.

Strictly speaking, you'll waste even more than that. Server-rendered page contains all the html-markup which have to be transmitted over the wire, and which is not there in case of client-only rendering.

But is it really worth worrying about? How many kilobytes of data do you want to save, compared to all the other stuff to be loaded (i.e. images, style-sheets, etc.)?

Also, as I noted above, you can (and probably should) add gzip compression of your response body. Text compression ratio is very high, so duplication can be greatly reduced.


问:
PHPMyAdmin: Many-to-Many relations in MyISAM (without foreign key support)
I've discovered that my host may only support MyISAM and not InnoDB.  Thus, I lack built-in foreign key support.  How would I then implement a many-to-many relationship with three tables in PHPMyAdmin?  The only solution is to enter in the relations manually through MySQL queries, correct?</p>

答: I would implement it in the same way as you would using Innodb but ensure data integrity in the application layer.   If you have a good data abstraction layer then this should be fairly simple to implement.</p>


问:
Javascript constructor from string variable in angular
I've got a little angular (v1.5.11) app where I'm trying to instantiate an object from a string variable. This code used to work in my old setup but after changing from bower/gulp to webpack (3.8.1), I'm now getting the error below. I'm not sure whether this is caused by my new import statement or something.

A similar question (Javascript "Not a Constructor" Exception while creating objects) dicussed the problem but I wasn't able to get get any of the solutions to work in my example which is why I'm thinking it might be down to the import or the pojo structure itself?

Error:

```<code>TypeError: $window[iteratorType] is not a constructor
</code>```

Code:

MyService.js

```<code>import ListIterator from './util/listiterator.pojo.js';

MyService.$inject = ['$log', '$window'];

function MyService($log, $window) {
  ...
  // this variable is obviously dynamic but for now I made it a static string
  var iteratorType = 'ListIterator';
  var iterator = new $window[iteratorType](); //<-- breaks as $window[iteratorType] is undefined
  //var iterator = new ListIterator();  <-- this works just fine
  ...
</code>```

listiterator.pojo.js

```<code>var ListIterator = function() {
    this.executedIterations = 0;
    this.iter = null;
};
...
export default ListIterator;
</code>```

答:
This is angular way:</p>

```<code>app.factory('F1', function() {...})
app.factory('F2', function() {...})
app.factory('F3', function() {...})

app.factory('MyService', function($injector) {
  var name = 'F1';
  var someFactory = $injector.get(name);
})
</code>```

Body:
I've got a little angular (v1.5.11) app where I'm trying to instantiate an object from a string variable. This code used to work in my old setup but after changing from bower/gulp to webpack (3.8.1), I'm now getting the error below. I'm not sure whether this is caused by my new import statement or something.

A similar question (Javascript "Not a Constructor" Exception while creating objects) dicussed the problem but I wasn't able to get get any of the solutions to work in my example which is why I'm thinking it might be down to the import or the pojo structure itself?

Error:

TypeError: $window[iteratorType] is not a constructor

Code:

MyService.js

import ListIterator from './util/listiterator.pojo.js';

MyService.$inject = ['$log', '$window'];

function MyService($log, $window) {
  ...
  // this variable is obviously dynamic but for now I made it a static string
  var iteratorType = 'ListIterator';
  var iterator = new $window[iteratorType](); //<-- breaks as $window[iteratorType] is undefined
  //var iterator = new ListIterator();  <-- this works just fine
  ...

listiterator.pojo.js

var ListIterator = function() {
    this.executedIterations = 0;
    this.iter = null;
};
...
export default ListIterator;

Body:
This is angular way:

app.factory('F1', function() {...})
app.factory('F2', function() {...})
app.factory('F3', function() {...})

app.factory('MyService', function($injector) {
  var name = 'F1';
  var someFactory = $injector.get(name);
})


问:
Access is denied when running mkdir command from Jenkins
I am trying to create a new directory and copy files to it. So I'm using a job of "Execute batch command".

First I tried to run: robocopy source destination /e.

Then I tried: mkdir destination. In both cases I got an "Access is denied" mssage.

If I try it myself manualy I am able to create a directory and copy files to it.

The destination is a remote computer's shared folder: \computerName\sharedFolder\

Anyone knows how to get access rights with Jenkins?

答:
To find out the user under which your jobs run, create a "scratch" job in Jenkins.  Give it a single "Execute Windows Batch command" build step and enter "set" as the text of your batch command.  If your affected job is running on a Windows slave, make sure this job runs on the same slave.  Run the job.  Your console will show a list of the environment variables known to that job, the same as if you typed "set" in a Command Prompt window on your desktop.  The difference will be that near the bottom, the username shown for "USERDOMAIN" and "USERNAME" in your command window will be you (the user you are logged in as); in the console output, it will be the user account that your Jenkins job runs under.

That user may not actually have login rights.  And, if Jenkins is running as a service, you can't just set up a share in your command window: Jenkins jobs run under a different Windows "session" and that session will not see the share you created in your login session.

A not-very-secure way to get you over the hump would be to add parameters to your job for the username (string parameter) and password (password parameter).  Before you need access to the drive, either in the same build step or in a 'Execute Windows Batch Command' step that runs prior to that build step, run "@net use : \computername\sharename %% /USER:%% /persistent:no".  (for example: "@net use p: \COMPUTER\SHARE %PASSWORD% %USER% /persistent:no").  The "@" will keep the password from showing in the log.  (However, the password will be associated with the job and will be encoded in Jenkins if "Allow rebuild" is enabled.)  Make sure when you are done you clean up ("net use  /delete") and you may need to test and clean up the drive letter before you try to connect, in case a previous job failed without releasing the drive letter.

In this scenario you would have to enter a username and password for someone who can access the share when you run the job.  You could encode hidden parameters with these values pre-filled in, but that means that user's username and password are encoded into the job definition, and the default for the hidden password parameter would not be encrypted in the Jenkins config files.

There are definitely more secure ways to get the drive share enabled in the Jenkins service session, but depending on your environment this may be 'good enough' to get you past the block you are faced with right now.  I have used tricks like these in an environment where I was not a Jenkins administrator and I had very limited access rights (and no admin rights) on the Jenkins slaves.


问:
Output filename and count of a directory in a text file - windows
I have a batch to output filename and count of filenames with the same prefix and date in a text file.

E.g.

Q1231111.zip

Q1241111.zip

where:

Q123 - is a prefix

1111 - is a date.

I want an output such as:

123 : 1

124 : 1

125 : 0

But the batch file unable to output the last one. I wanna see the file is present so i need the 0 output.

Here's my code:

```<code>@echo off
setlocal EnableExtensions
for %%I in ("Z:\StoreDataJDA\Q1231111.zip") do call :CountFile "%%~nI"
for %%I in ("Z:\StoreDataJDA\Q1241111.zip") do call :CountFile "%%~nI"
for %%I in ("Z:\StoreDataJDA\Q1251111.zip") do call :CountFile "%%~nI"

for /F "tokens=2,3 delims=#=" %%I in ('set Group# 2^>nul') do echo %%I: %%J >>count.txt
endlocal
goto :EOF

:CountFile
set "FileName=%~1"
set "FileGroup=%FileName:~1,4%"
if "Group#%FileGroup%" == "" (
    set "Group#%FileGroup%=1"
) else (
    set /A Group#%FileGroup%+=1
)
goto :EOF
pause
</code>```

Thanks in advance!

答:
From your description, it's hard to tell exactly what you are looking for. But by looking at your very similar question from a year ago, and from Gerhard's comment, I think what you're looking for is:

Count the number of files with a given prefix, each file having a different date suffix.

I think this should do it:

```<code>@echo off
setlocal EnableExtensions
set "Group#123=0" & for %%I in ("Z:\StoreDataJDA\Q123????.zip") do call :CountFile "%%~nI"
set "Group#124=0" & for %%I in ("Z:\StoreDataJDA\Q124????.zip") do call :CountFile "%%~nI"
set "Group#125=0" & for %%I in ("Z:\StoreDataJDA\Q125????.zip") do call :CountFile "%%~nI"

(for /F "tokens=2,3 delims=#=" %%I in ('set Group# 2^>nul') do echo %%I: %%J)>count.txt
endlocal
goto :EOF

:CountFile
set "FileName=%~1"
set "FileGroup=%FileName:~1,3%"
set /A Group#%FileGroup%+=1
goto :EOF
</code>```

Body:
I have a batch to output filename and count of filenames with the same prefix and date in a text file.

E.g.

Q1231111.zip

Q1241111.zip

where:

Q123 - is a prefix

1111 - is a date.

I want an output such as:

123 : 1

124 : 1

125 : 0

But the batch file unable to output the last one. I wanna see the file is present so i need the 0 output.

Here's my code:

@echo off
setlocal EnableExtensions
for %%I in ("Z:\StoreDataJDA\Q1231111.zip") do call :CountFile "%%~nI"
for %%I in ("Z:\StoreDataJDA\Q1241111.zip") do call :CountFile "%%~nI"
for %%I in ("Z:\StoreDataJDA\Q1251111.zip") do call :CountFile "%%~nI"

for /F "tokens=2,3 delims=#=" %%I in ('set Group# 2^>nul') do echo %%I: %%J >>count.txt
endlocal
goto :EOF

:CountFile
set "FileName=%~1"
set "FileGroup=%FileName:~1,4%"
if "Group#%FileGroup%" == "" (
    set "Group#%FileGroup%=1"
) else (
    set /A Group#%FileGroup%+=1
)
goto :EOF
pause

Thanks in advance!

Body:
From your description, it's hard to tell exactly what you are looking for. But by looking at your very similar question from a year ago, and from Gerhard's comment, I think what you're looking for is:

Count the number of files with a given prefix, each file having a different date suffix.

I think this should do it:

@echo off
setlocal EnableExtensions
set "Group#123=0" & for %%I in ("Z:\StoreDataJDA\Q123????.zip") do call :CountFile "%%~nI"
set "Group#124=0" & for %%I in ("Z:\StoreDataJDA\Q124????.zip") do call :CountFile "%%~nI"
set "Group#125=0" & for %%I in ("Z:\StoreDataJDA\Q125????.zip") do call :CountFile "%%~nI"

(for /F "tokens=2,3 delims=#=" %%I in ('set Group# 2^>nul') do echo %%I: %%J)>count.txt
endlocal
goto :EOF

:CountFile
set "FileName=%~1"
set "FileGroup=%FileName:~1,3%"
set /A Group#%FileGroup%+=1
goto :EOF


问:
Xamarin : Reverse the bool value in xamarin listview viewcell
I am new with xamarin, I am facing an issue in my xamarin forms project.
I have two images inside listview-viewcell, one is for showing like and other for unlike.
If the value of isUserLiked is true show the second image and otherwise show the first one. I try with !, but not working.
Here is my code:

```<code>   <StackLayout HeightRequest="500">
        <ListView x:Name="ListView1" RowHeight="500" HorizontalOptions="CenterAndExpand">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                    <StackLayout
                            Orientation="Vertical">
                                <Image
                                    Source="unlike.png"
                                    IsVisible="{Binding !isUserLiked}">
                                </Image>
                                <Image
                                    Source="like.png"
                                    IsVisible="{Binding isUserLiked}">
                                </Image>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
          </ListView>
    </StackLayout>
</code>```

How to reverse the binding value inside listview-viewcell.
Anybody please suggest a solution with working code.
Thanks in advance.

答:
You could either work around it by creating another property in your ViewModel which gives you the inverse value.

A better way would be to use a ValueConverter, I have written a blog about it here. In the converter you could inverse the boolean value.

However there are also libraries that do that for you, they basically implement this converter for you.

Body:
I am new with xamarin, I am facing an issue in my xamarin forms project.
I have two images inside listview-viewcell, one is for showing like and other for unlike.
If the value of isUserLiked is true show the second image and otherwise show the first one. I try with !, but not working.
Here is my code:

   <StackLayout HeightRequest="500">
        <ListView x:Name="ListView1" RowHeight="500" HorizontalOptions="CenterAndExpand">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                    <StackLayout
                            Orientation="Vertical">
                                <Image
                                    Source="unlike.png"
                                    IsVisible="{Binding !isUserLiked}">
                                </Image>
                                <Image
                                    Source="like.png"
                                    IsVisible="{Binding isUserLiked}">
                                </Image>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
          </ListView>
    </StackLayout>

How to reverse the binding value inside listview-viewcell.
Anybody please suggest a solution with working code.
Thanks in advance.


问:
R ggplot2 : continuous x + colors
I'm trying to create a boxplot using ggplot2 with :

X as a continuous variable

Colors for different groups

Here is an example :

```<code>    x <- sample(c(1,2,5),300,replace = TRUE)
    y <- sapply(x,function(mu) rnorm(1,mean = mu))
    color <- sample(c("color 1","color 2"),300,replace = TRUE)
    data <- data.frame(x, y, color)
</code>```

I can either have colors and x as a factor :

```<code>   ggplot(data = data) + geom_boxplot(aes(x = factor(x),y = y,col = color))
</code>```

or x as a continuous variable and no colors :

```<code>  ggplot(data = data) + geom_boxplot(aes(x = x,y = y,group = x))
</code>```

But not both.
Does somebody know how to do this ?
Thanks

答:
You could misuse the fill aesthetic:

```<code>ggplot(data = data) +
  geom_boxplot(aes(x = x, y = y, col = color, fill = factor(x))) +
  scale_fill_manual(values = rep(NA, 3), guide = "none")
</code>```

Title: R ggplot2 : continuous x + colors

Body:
I'm trying to create a boxplot using ggplot2 with :

X as a continuous variable

Colors for different groups

Here is an example :

    x <- sample(c(1,2,5),300,replace = TRUE)
    y <- sapply(x,function(mu) rnorm(1,mean = mu))
    color <- sample(c("color 1","color 2"),300,replace = TRUE)
    data <- data.frame(x, y, color)

I can either have colors and x as a factor :

   ggplot(data = data) + geom_boxplot(aes(x = factor(x),y = y,col = color))

or x as a continuous variable and no colors :

  ggplot(data = data) + geom_boxplot(aes(x = x,y = y,group = x))

But not both.
Does somebody know how to do this ?
Thanks

Body:
You could misuse the fill aesthetic:

ggplot(data = data) +
  geom_boxplot(aes(x = x, y = y, col = color, fill = factor(x))) +
  scale_fill_manual(values = rep(NA, 3), guide = "none")


问:
JS: add onclick function to table cell
I've created a minimal example: https://jsfiddle.net/n2r5t91v/

var myvalue = 20 // abbreviating how I calculate myvalue
var cell = document.getElementById("mytd");
cell.setAttribute('onclick', 'addToCell(' + myvalue + ');');

function addToCell(value) {
  var td_cell = document.getElementById("mytd");
  td_cell.value = td_cell.value + ' ' + value;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <td id="mytd">
      test
    </td>
  </tr>
</table></code>```

I expect the value of that  cell to change from "test" to "test 20" upon clicking. Why doesn't it work like this?

答:
Try With This</p>

```<code>var myvalue = 20 // abbreviating how I calculate myvalue
var cell = document.getElementById("mytd");
//cell.setAttribute('onclick', 'addToCell(' + myvalue + ');');
cell.addEventListener('click', function() {
    addToCell(myvalue);
    });
function addToCell(value){
var td_cell = document.getElementById("mytd");
td_cell.innerHTML = td_cell.innerHTML + ' ' + value;
}
</code>```

Title: JS: add onclick function to table cell

Body:
I've created a minimal example: https://jsfiddle.net/n2r5t91v/

var myvalue = 20 // abbreviating how I calculate myvalue
var cell = document.getElementById("mytd");
cell.setAttribute('onclick', 'addToCell(' + myvalue + ');');

function addToCell(value) {
  var td_cell = document.getElementById("mytd");
  td_cell.value = td_cell.value + ' ' + value;
}

      test

I expect the value of that  cell to change from "test" to "test 20" upon clicking. Why doesn't it work like this?

Body:
Try With This

var myvalue = 20 // abbreviating how I calculate myvalue
var cell = document.getElementById("mytd");
//cell.setAttribute('onclick', 'addToCell(' + myvalue + ');');
cell.addEventListener('click', function() {
    addToCell(myvalue);
    });
function addToCell(value){
var td_cell = document.getElementById("mytd");
td_cell.innerHTML = td_cell.innerHTML + ' ' + value;
}


问:
Moving from a one-to-one relationship into a many-to-many relationship in rails
Like the title says, I want to move from a one-to-one relationship into a many-to-many relationship in my rails 3 app.

I'm fairly good with rails now but I lack a good understanding of databases and migrations.

Currently, I have a Project and User model. A Project belongs_to a User and a User has_many Projects.
I want to move into a situation where a project can have many users collaborating on it at once.

I'm pretty sure I need to set up a has_many :through type of relationship, but I am also curious as to how I can migrate all of my existing projects and users into this type of system.

Thanks!

答:
Right, I have the relationship set up now. How do I migrate all of my existing projects and users into this new format table ?

Well, it depends on how you have set the tables up now; how the two existing relations are implemented; where the ProjectUser data is sitting in the old table.  Post your DDL. You should be able to simply INSERT ProjectUser SELECT FROM ....  We need to complete that FROM.

Also the number of rows is relevant; if it is large, you may have to break it into batches.


问:
Check if a string contain digits and dash
I'm trying to find the right regex to grepl weather a string contains digits[0-9] and the special character "-" only.

ex,

```<code>str1="00-25" #TRUE
str2="0a-2" #FALSE
</code>```

I have tried

```<code>grepl("[^[:digit:]|-]",str2)
#[1] TRUE
</code>```

thoughts?

答:
You want to check if the string has only digit and -.

To create the ensemble, you need to use "[]" so :

```<code>[0-9-]
</code>```

Now you want to check that every character of the string is in the ensemble you have created, in other term you want to start(^) and finish($) by this ensemble :

```<code>^[0-9-]$
</code>```

Finally in the variable there is 1 or more character, so I use the "+" :

```<code>grepl("^[0-9-]+$",str)
</code>```

Body:
I'm trying to find the right regex to grepl weather a string contains digits[0-9] and the special character "-" only.

ex,

str1="00-25" #TRUE
str2="0a-2" #FALSE

I have tried

grepl("[^[:digit:]|-]",str2)
#[1] TRUE

thoughts?

Body:
You want to check if the string has only digit and -.

To create the ensemble, you need to use "[]" so :

[0-9-]

Now you want to check that every character of the string is in the ensemble you have created, in other term you want to start(^) and finish($) by this ensemble :

^[0-9-]$

Finally in the variable there is 1 or more character, so I use the "+" :

grepl("^[0-9-]+$",str)


问:
git not changing crlf to lf when changing encoding of a file
I have a utf-16 file checked in. Git treats it as binary file.

Steps :
In windows :

I change the encoding of file to utf-8 in windows.

I commit the change.

In linux :

I pull the branch.

In git status, i see the file as modified even though i have not touched it here in this repo.

Reason : git didn't change crlf to lf in step 2 above.

If i do the same exercise in linux and then pull in windows, it is no issue.

As during diff or commit, it says :  warning: CRLF will be replaced by LF in Foo.xml

What is the reason that git didn't automatically change crlf to lf when destination file formatting is recognized by it as text ?

Note : i have a lot of other files and with them crlf-lf conversion works good. It is only during changing encoding of format recognized by git as binary (here utf-16) to utf-8 (text format for git), it does not do conversion.

Is it because base-line in commit is of binary file ?
Also, it behaves correctly in linux atleast.

Are my observations right ?

答:
After changing the encoding, git rm --cached file_name && git add file_name works good.

This way git takes newer encoding of file.


问:
Rownumberer doesn't appear in sequence after deleting/adding row ExtJS 4.1
I have a grid using rownumberer. But if I delete any row (except for the last row), the number doesn't appear in sequence. I've already use grid.getView().refresh() but it didn't solve my problem.
Please help

```<code>var productHardwareGrid = Ext.create('Ext.grid.Panel', {
    id: 'productHardwareGrid',
    store: prodHardGridStore,
    selModel: prodHardCheckBoxSelection,
    frame: false,
    loadMask: true,
    stripeRows: true,
    autoScroll: true,
    preventRender: true,
    tbar: [{
            xtype: 'button',
            text: 'Add Product',
            id: 'addProductHW',
            iconCls: "icon-grid-add",
            handler: function () {
                prodWinAdd('productHardwareGrid', 'HW');
            }
        },
            {
                xtype: 'button',
                text: 'Delete Product',
                iconCls: "icon-grid-delete",
                handler: function () {
                    prodDelete('HW');
                    productHardwareGrid.getView().refresh();
                },
                id: 'prodHardDelBtn',
                disabled: true
            }
        ],
            columns: [
            {
                xtype: 'rownumberer',
                header: 'No',
                defaults: {
                    align: 'center',
                    flex: 0,
                    width: 40,
                    sortable: false,
                    menuDisabled: true
                }
            },
</code>```

答:
renderer is again here to save the day.

```<code>var data = [];

for(var i=0;i<10; i++) {
    data.push({name: i, age: 1});
}

Ext.application({
    name: 'Fiddle',

    launch: function () {

    var store = new Ext.data.Store({
        fields: ['name', 'age'],
        data: data,
        autoLoad: true,
        pageSize: 10
    });
    Ext.create('Ext.panel.Panel', {
        renderTo: Ext.getBody(),
        items: [{
            xtype: 'grid',
            id: "grid1",
            columns: [{
                xtype: 'rownumberer',
                renderer: function (value, metaData, record, rowIdx, colIdx, store) {
                    var rowspan = this.rowspan;
                    if (rowspan) {
                        metaData.tdAttr = 'rowspan="' + rowspan + '"';
                    }
                    metaData.tdCls = Ext.baseCSSPrefix + 'grid-cell-special';
                    return store.indexOf(record) + 1;
                }
            }, {
                text: 'name',
                dataIndex: 'name',
                flex: 1
            }, {
                text: 'age',
                dataIndex: 'age',
                flex: 1
            }],
            store: store
        }],
        dockedItems: [{
            xtype: 'toolbar',
            items: [{
                xtype: 'button',
                text: 'Delete 1st',
                handler: function () {
                    store.removeAt(0);
                    var grid = Ext.getCmp('grid1');
                    grid.view.refresh();
                }
            }]
        }]
    });
}
});
</code>```

Fiddle: https://fiddle.sencha.com/#view/editor&fiddle/29og

Body:
I have a grid using rownumberer. But if I delete any row (except for the last row), the number doesn't appear in sequence. I've already use grid.getView().refresh() but it didn't solve my problem.
Please help

var productHardwareGrid = Ext.create('Ext.grid.Panel', {
    id: 'productHardwareGrid',
    store: prodHardGridStore,
    selModel: prodHardCheckBoxSelection,
    frame: false,
    loadMask: true,
    stripeRows: true,
    autoScroll: true,
    preventRender: true,
    tbar: [{
            xtype: 'button',
            text: 'Add Product',
            id: 'addProductHW',
            iconCls: "icon-grid-add",
            handler: function () {
                prodWinAdd('productHardwareGrid', 'HW');
            }
        },
            {
                xtype: 'button',
                text: 'Delete Product',
                iconCls: "icon-grid-delete",
                handler: function () {
                    prodDelete('HW');
                    productHardwareGrid.getView().refresh();
                },
                id: 'prodHardDelBtn',
                disabled: true
            }
        ],
            columns: [
            {
                xtype: 'rownumberer',
                header: 'No',
                defaults: {
                    align: 'center',
                    flex: 0,
                    width: 40,
                    sortable: false,
                    menuDisabled: true
                }
            },

Body:
renderer is again here to save the day.

var data = [];

for(var i=0;i<10; i++) {
    data.push({name: i, age: 1});
}

Ext.application({
    name: 'Fiddle',

    launch: function () {

    var store = new Ext.data.Store({
        fields: ['name', 'age'],
        data: data,
        autoLoad: true,
        pageSize: 10
    });
    Ext.create('Ext.panel.Panel', {
        renderTo: Ext.getBody(),
        items: [{
            xtype: 'grid',
            id: "grid1",
            columns: [{
                xtype: 'rownumberer',
                renderer: function (value, metaData, record, rowIdx, colIdx, store) {
                    var rowspan = this.rowspan;
                    if (rowspan) {
                        metaData.tdAttr = 'rowspan="' + rowspan + '"';
                    }
                    metaData.tdCls = Ext.baseCSSPrefix + 'grid-cell-special';
                    return store.indexOf(record) + 1;
                }
            }, {
                text: 'name',
                dataIndex: 'name',
                flex: 1
            }, {
                text: 'age',
                dataIndex: 'age',
                flex: 1
            }],
            store: store
        }],
        dockedItems: [{
            xtype: 'toolbar',
            items: [{
                xtype: 'button',
                text: 'Delete 1st',
                handler: function () {
                    store.removeAt(0);
                    var grid = Ext.getCmp('grid1');
                    grid.view.refresh();
                }
            }]
        }]
    });
}
});

Fiddle: https://fiddle.sencha.com/#view/editor&fiddle/29og


问:
Remove class on outside click
I would like so that when i click outside and the default text loads the previous clicked class should be removed. So for example if i press " Fair Trade " and it becomes color: red; that should fade away when i press outside and load the default text just as it fades away when i click on another title.

var $imgs = $(".section-link");

var data = [{
    title: "Fair Trade",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Toxicfree",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Quality",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Organic",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Vegan",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
];

// Get reference to the output area
var $outputDiv = $(".section-display");
var defaulttext = $outputDiv.find(".text1").html()
var defaultTitle = $outputDiv.find(".title1").html();

$imgs.on("click", function() {

  $This = $(this) ;

  $imgs.removeClass("clicked") ;
  $This.addClass("clicked");

  $(".title1", $outputDiv).animate({
    opacity: 0
  }, function() {
    $(".title1", $outputDiv).html(data[$This.index() - 1].title)
      .animate({
        opacity: 1
      });
  });
  $(".text1", $outputDiv).animate({
    opacity: 0
  }, function() {
    $(".text1", $outputDiv).html(data[$This.index() - 1].text)
      .animate({
        opacity: 1
      });
  })
});

$(document).on("click", function(e) {
  if ($(e.target).closest('.section-display').length != 1 && $(e.target).closest(".section-link").length != 1) {
    $(".title1", $outputDiv).animate({
      opacity: 0
    }, function() {
      $(".title1", $outputDiv).html(defaultTitle)
        .animate({
          opacity: 1
        });
    });
    $(".text1", $outputDiv).animate({
      opacity: 0
    }, function() {
      $(".text1", $outputDiv).html(defaulttext)
        .animate({
          opacity: 1
        });
    })
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.section-link {
  width: 100px;

  -webkit-transition: all .5s ease-in-out;
  -moz-transition: all .5s ease-in-out;
  -ms-transition: all .5s ease-in-out;
  -o-transition: all .5s ease-in-out;
  transition: all .5s ease-in-out;
}
.section-link.clicked{
  color: red;
}</code>```

    <nobr>FAIR-TRADE</nobr>

TOXICFREE

QUALITY

ORGANIC

VEGAN

Lorem ipsum

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

 Tap on the symbols if you want to know more.

```

答:
The no-break tag for fair-trade broke my logic; so I removed it;

besides that, this will meet your requirement.

var $imgs = $(".section-link");

var data = [{
    title: "Fair Trade",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Toxicfree",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Quality",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Organic",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Vegan",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
];

// Get reference to the output area
var $outputDiv = $(".section-display");
var defaulttext = $outputDiv.find(".text1").html()
var defaultTitle = $outputDiv.find(".title1").html();

$(window).click(function(e) {
if(!e.target.parentNode.classList.contains('clicked')) $(".section-link.clicked").removeClass("clicked")
});

$imgs.on("click", function() {

  $This = $(this) ;

  $imgs.removeClass("clicked") ;
  $This.addClass("clicked");

  $(".title1", $outputDiv).animate({
    opacity: 0
  }, function() {
    $(".title1", $outputDiv).html(data[$This.index() - 1].title)
      .animate({
        opacity: 1
      });
  });
  $(".text1", $outputDiv).animate({
    opacity: 0
  }, function() {
    $(".text1", $outputDiv).html(data[$This.index() - 1].text)
      .animate({
        opacity: 1
      });
  })
});

$(document).on("click", function(e) {
  if ($(e.target).closest('.section-display').length != 1 && $(e.target).closest(".section-link").length != 1) {
    $(".title1", $outputDiv).animate({
      opacity: 0
    }, function() {
      $(".title1", $outputDiv).html(defaultTitle)
        .animate({
          opacity: 1
        });
    });
    $(".text1", $outputDiv).animate({
      opacity: 0
    }, function() {
      $(".text1", $outputDiv).html(defaulttext)
        .animate({
          opacity: 1
        });
    })
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.section-link {
  width: 100px;

  -webkit-transition: all .5s ease-in-out;
  -moz-transition: all .5s ease-in-out;
  -ms-transition: all .5s ease-in-out;
  -o-transition: all .5s ease-in-out;
  transition: all .5s ease-in-out;
}
.section-link.clicked{
  color: red;
}</code>```

    FAIR-TRADE

TOXICFREE

QUALITY

ORGANIC

VEGAN

Lorem ipsum

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

 Tap on the symbols if you want to know more.

```

Title: Remove class on outside click

Body:
I would like so that when i click outside and the default text loads the previous clicked class should be removed. So for example if i press " Fair Trade " and it becomes color: red; that should fade away when i press outside and load the default text just as it fades away when i click on another title.

var $imgs = $(".section-link");

var data = [{
    title: "Fair Trade",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Toxicfree",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Quality",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Organic",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Vegan",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
];

// Get reference to the output area
var $outputDiv = $(".section-display");
var defaulttext = $outputDiv.find(".text1").html()
var defaultTitle = $outputDiv.find(".title1").html();

$imgs.on("click", function() {

  $This = $(this) ;

  $imgs.removeClass("clicked") ;
  $This.addClass("clicked");

  $(".title1", $outputDiv).animate({
    opacity: 0
  }, function() {
    $(".title1", $outputDiv).html(data[$This.index() - 1].title)
      .animate({
        opacity: 1
      });
  });
  $(".text1", $outputDiv).animate({
    opacity: 0
  }, function() {
    $(".text1", $outputDiv).html(data[$This.index() - 1].text)
      .animate({
        opacity: 1
      });
  })
});

$(document).on("click", function(e) {
  if ($(e.target).closest('.section-display').length != 1 && $(e.target).closest(".section-link").length != 1) {
    $(".title1", $outputDiv).animate({
      opacity: 0
    }, function() {
      $(".title1", $outputDiv).html(defaultTitle)
        .animate({
          opacity: 1
        });
    });
    $(".text1", $outputDiv).animate({
      opacity: 0
    }, function() {
      $(".text1", $outputDiv).html(defaulttext)
        .animate({
          opacity: 1
        });
    })
  }
})

.section-link {
  width: 100px;

  -webkit-transition: all .5s ease-in-out;
  -moz-transition: all .5s ease-in-out;
  -ms-transition: all .5s ease-in-out;
  -o-transition: all .5s ease-in-out;
  transition: all .5s ease-in-out;
}
.section-link.clicked{
  color: red;
}

    <nobr>FAIR-TRADE</nobr>

TOXICFREE

QUALITY

ORGANIC

VEGAN

Lorem ipsum

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

 Tap on the symbols if you want to know more.

Body:
The no-break tag for fair-trade broke my logic; so I removed it;

besides that, this will meet your requirement.

var $imgs = $(".section-link");

var data = [{
    title: "Fair Trade",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Toxicfree",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Quality",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Organic",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Vegan",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
];

// Get reference to the output area
var $outputDiv = $(".section-display");
var defaulttext = $outputDiv.find(".text1").html()
var defaultTitle = $outputDiv.find(".title1").html();

$(window).click(function(e) {
if(!e.target.parentNode.classList.contains('clicked')) $(".section-link.clicked").removeClass("clicked")
});

$imgs.on("click", function() {

  $This = $(this) ;

  $imgs.removeClass("clicked") ;
  $This.addClass("clicked");

  $(".title1", $outputDiv).animate({
    opacity: 0
  }, function() {
    $(".title1", $outputDiv).html(data[$This.index() - 1].title)
      .animate({
        opacity: 1
      });
  });
  $(".text1", $outputDiv).animate({
    opacity: 0
  }, function() {
    $(".text1", $outputDiv).html(data[$This.index() - 1].text)
      .animate({
        opacity: 1
      });
  })
});

$(document).on("click", function(e) {
  if ($(e.target).closest('.section-display').length != 1 && $(e.target).closest(".section-link").length != 1) {
    $(".title1", $outputDiv).animate({
      opacity: 0
    }, function() {
      $(".title1", $outputDiv).html(defaultTitle)
        .animate({
          opacity: 1
        });
    });
    $(".text1", $outputDiv).animate({
      opacity: 0
    }, function() {
      $(".text1", $outputDiv).html(defaulttext)
        .animate({
          opacity: 1
        });
    })
  }
})

.section-link {
  width: 100px;

  -webkit-transition: all .5s ease-in-out;
  -moz-transition: all .5s ease-in-out;
  -ms-transition: all .5s ease-in-out;
  -o-transition: all .5s ease-in-out;
  transition: all .5s ease-in-out;
}
.section-link.clicked{
  color: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="section-link small-solid-circle-p4 fair-d">
  <h2>
    FAIR-TRADE
  </h2>
</div>
<div class="section-link small-solid-circle-p4 toxic-d">
  <h2>TOXICFREE</h2>
</div>
<div class="section-link small-solid-circle-p4 quality-d">
  <h2>QUALITY</h2>
</div>
<div class="section-link small-solid-circle-p4 organic-d">
  <h2>ORGANIC</h2>
</div>
<div class="section-link small-solid-circle-p4 vegan-d">
  <h2>VEGAN</h2>
</div>
<div class="section-display active info-p4">
  <h2 class="title1">Lorem ipsum</h2>
  <h2 class="text1">"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.<br>
  <br> Tap on the symbols if you want to know more.</h2>
</div>


问:
How does one parse XML files?
Is there a simple method of parsing XML files in C#? If so, what?</p>

答: You can use XmlDocument and for manipulating or retrieve data from attributes you can Linq to XML classes.</p>

OwnerDisplayName: domoaringatoo

Title: How does one parse XML files?


问:
Using a select box to trigger JS event to make another select box become passive/active? HTML/JS
I want select box B to become visible when option 2 is selected in select box A, otherwise it should remain hidden.  It's not working.  Here's my code: [EDIT: I actually want it to be passive instead of hidden.]

The JavaScript first:

```<code>function toggle2(value){
if(value=='confirm')
 document.getElementById('test').style.visibility='visible';
else
 document.getElementById('test').style.visibility='hidden';
}

 <select class="select3" name="CaseType" onchange="toggle2()">
  <option value="select" selected="selected">- Select Case Type -</option>
  <option value="suspect">Suspected</option>
  <option value="confirm">Confirmed</option>
  </select>

  <select id="test" class="select4" name="test" style="visibility: hidden;">
  <option selected="selected">- Select test -</option>
  </select>
</code>```

Thanks!

答:
You can create an empty
 with an id, and onchange, set the innerHTML to whatever you want.

Nur

Body:
I want select box B to become visible when option 2 is selected in select box A, otherwise it should remain hidden.  It's not working.  Here's my code: [EDIT: I actually want it to be passive instead of hidden.]

The JavaScript first:

function toggle2(value){
if(value=='confirm')
 document.getElementById('test').style.visibility='visible';
else
 document.getElementById('test').style.visibility='hidden';
}

 <select class="select3" name="CaseType" onchange="toggle2()">
  <option value="select" selected="selected">- Select Case Type -</option>
  <option value="suspect">Suspected</option>
  <option value="confirm">Confirmed</option>
  </select>

  <select id="test" class="select4" name="test" style="visibility: hidden;">
  <option selected="selected">- Select test -</option>
  </select>

Thanks!

Body:
You can create an empty <div> with an id, and onchange, set the innerHTML to whatever you want.

Nur


问:
How to store XML format data in MongoDB?
I have several files in XML format. Each file contains XML header and approx 15-20 items. I want to store these files in MongoDB which I think stores data in JSON format. Here is the sample of data I want to store in MongoDB.

```<code><?xml version="1.0" encoding="utf-8"?>
<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
    xmlns:slash="http://purl.org/rss/1.0/modules/slash/" version="2.0">
    <channel>
        <title>Channel Title</title>
        <link>Channel link</link>
        <description>Channel desc</description>
        <!-- Item 1 -->
        <item>
          <title>Your Title</title>
                    <link>Your link</link>
          <pubDate>Published date</pubDate>
          <description>Your description</description>
        </item>
        <!-- Item 2 -->
        <item>
          <title>Your Title</title>
                    <link>Your link</link>
          <pubDate>Published date</pubDate>
          <description>Your description</description>
        </item>

    </channel>
</rss>
</code>```

How to proceed? Can anyone help using some example and sample code how to store these data in MongoDB? Note: I will be using Node/Javascript for CRUD operations.

Edit:
The process of storing data would be like there is a form and you choose a category(Channel name, like channel title) and you just add a <item> to that channel. But whole data would be stored in MongoDB.

答:
There is no xml type in mongodb. Every thing is BSON in mongodb internally.

You can save as string form.

```<code>    var str = '<?xml version="1.0" encoding="utf-8"?>\
    <rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"\
        xmlns:slash="http://purl.org/rss/1.0/modules/slash/" version="2.0">\
        <channel>\
            <title>Channel Title</title>\
            <link>Channel link</link>\
            <description>Channel desc</description>\
            <!-- Item 1 -->\
            <item>\
              <title>Your Title</title>\
                        <link>Your link</link>\
              <pubDate>Published date</pubDate>\
              <description>Your description</description>\
            </item>\
            <!-- Item 2 -->\
            <item>\
              <title>Your Title</title>\
                        <link>Your link</link>\
              <pubDate>Published date</pubDate>\
              <description>Your description</description>\
            </item>\
    \
        </channel>\
    </rss>'
  console.log(str);
</code>```

This is string. Now you can save it in mongodb.

If data is coming from outside is in some string or any other type, the only approach is convert to string and then fetch it when you wanted. You will get the same xml string back you wanted.

Body:
I have several files in XML format. Each file contains XML header and approx 15-20 items. I want to store these files in MongoDB which I think stores data in JSON format. Here is the sample of data I want to store in MongoDB.

<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
    xmlns:slash="http://purl.org/rss/1.0/modules/slash/" version="2.0">
    <channel>
        <title>Channel Title</title>
        <link>Channel link</link>
        <description>Channel desc</description>

        <item>
          <title>Your Title</title>
                    <link>Your link</link>
          <pubDate>Published date</pubDate>
          <description>Your description</description>
        </item>

        <item>
          <title>Your Title</title>
                    <link>Your link</link>
          <pubDate>Published date</pubDate>
          <description>Your description</description>
        </item>

    </channel>
</rss>

How to proceed? Can anyone help using some example and sample code how to store these data in MongoDB? Note: I will be using Node/Javascript for CRUD operations.

Edit:
The process of storing data would be like there is a form and you choose a category(Channel name, like channel title) and you just add a <item> to that channel. But whole data would be stored in MongoDB.

Body:
There is no xml type in mongodb. Every thing is BSON in mongodb internally.

You can save as string form.

    var str = '<?xml version="1.0" encoding="utf-8"?>\
    <rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"\
        xmlns:slash="http://purl.org/rss/1.0/modules/slash/" version="2.0">\
        <channel>\
            <title>Channel Title</title>\
            <link>Channel link</link>\
            <description>Channel desc</description>\
            <!-- Item 1 -->\
            <item>\
              <title>Your Title</title>\
                        <link>Your link</link>\
              <pubDate>Published date</pubDate>\
              <description>Your description</description>\
            </item>\
            <!-- Item 2 -->\
            <item>\
              <title>Your Title</title>\
                        <link>Your link</link>\
              <pubDate>Published date</pubDate>\
              <description>Your description</description>\
            </item>\
    \
        </channel>\
    </rss>'
  console.log(str);

This is string. Now you can save it in mongodb.

If data is coming from outside is in some string or any other type, the only approach is convert to string and then fetch it when you wanted. You will get the same xml string back you wanted.


问:
How to get div values that are dynamically generated by a php script?
I want to alert the name of the item whose place bid button I will click but my code seems to alert only laptop. Can anyone tell me how to get div values that are dynamically generated through a php script. Below is the code for the page.I want to alert name of that item whose place bid I click on. Since the page is dynamically generated which gets item details from a database containing item details.

<?php
 $con = mysqli_connect("localhost","root","*****","bidding") or
 die(mysqli_error($con));
 $select_query = "select * from items";
 $select_query_result = mysqli_query($con, $select_query) or
 die("Query Mistake");
?>
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Bid</title>
        <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
        <link rel="stylesheet" href="materialize/css/materialize.css"/>
        <link rel="stylesheet" type="text/css" href="seperate2.css">

Bid

   <?php while($row = mysqli_fetch_array($select_query_result)) { ?>

<?php echo"$row[item_name]"?>

<?php echo"$row[starting_price]"?

<?php echo"$row[description]"?>

    <button class="btn waves-effect waves-teal"
                 onclick="post_data()">Place Bid</button>

      <?php } ?>

```

答:
Your code requires a counter by which the dynamically created DIVs may be accessed. Your
 block would be:

```<code>    <div class="row">
        <?php
        $divCounter = 0;
        while($row = mysqli_fetch_array($select_query_result)) {
        $divCounter += 1;
        ?>
        <div class="col s3" >
            <div id="item_name<?php echo $divCounter; ?>"><?php echo"$row[item_name]"?></div>
            <div id="starting_price"><?php echo"$row[starting_price]"?</div>
            <div><?php echo"$row[description]"?></div>
            <button class="btn waves-effect waves-teal"
             onclick="post_data('<?php echo 'item_name'.$divCounter; ?>')">Place Bid</button>
        </div>
        <?php } ?>
    </div>
</code>```

Notice that the call to the Javascript function post_data() now provides the DIV id that contains its counter. To complete the job, adjust post_data() to include the parameter:

```<code>    <script type="text/javascript">
    function post_data(divId){
        var item_name = document.getElementById(divId).innerHTML;
        alert(item_name);
    }
    </script>
</code>```

If you prefer, instead of using a counter and concatenating with the static "item_name", you may use the $row[item_name] property instead. Whether or not you can do this will depend on whether this property can serve as a valid HTML id attribute value.

Body:
Your code requires a counter by which the dynamically created DIVs may be accessed. Your <div class="row"> block would be:

    <div class="row">
        <?php
        $divCounter = 0;
        while($row = mysqli_fetch_array($select_query_result)) {
        $divCounter += 1;
        ?>
        <div class="col s3" >
            <div id="item_name<?php echo $divCounter; ?>"><?php echo"$row[item_name]"?></div>
            <div id="starting_price"><?php echo"$row[starting_price]"?</div>
            <div><?php echo"$row[description]"?></div>
            <button class="btn waves-effect waves-teal"
             onclick="post_data('<?php echo 'item_name'.$divCounter; ?>')">Place Bid</button>
        </div>
        <?php } ?>
    </div>

Notice that the call to the Javascript function post_data() now provides the DIV id that contains its counter. To complete the job, adjust post_data() to include the parameter:

    <script type="text/javascript">
    function post_data(divId){
        var item_name = document.getElementById(divId).innerHTML;
        alert(item_name);
    }
    </script>

If you prefer, instead of using a counter and concatenating with the static "item_name", you may use the $row[item_name] property instead. Whether or not you can do this will depend on whether this property can serve as a valid HTML id attribute value.


问:
'pvk2pfx.exe' is not recognized as an internal or external command in command promt
for creating certificate run this command

pvk2pfx.exe -pvk C:\myCerts\ELServer.pvk -spc C:\myCerts\ELServer.cer -pfx C:\myCerts\ELServer.pfx

following error occurred in command prompt

'pvk2pfx.exe' is not recognized as an internal or external command,
operable program or batch file.

答:
I got exactly this error. The first thing I did was try to search for the .exe using Powershell:

```<code>Get-ChildItem -Path C:\ -Filter pvk2pfx.exe -Recurse -ErrorAction SilentlyContinue -Force
</code>```

I could not find it but I could find makecert.exe with this command.

Turned out I did not have the package Desktop development with C++ installed for Visual Studio 2017. After I added this everything worked. Remember to run the command through Developer Command Prompt for VS 2017.

If you do not use Visual Studio 2017 you can download Windows Driver Kit (WDK) from here instead:

https://developer.microsoft.com/en-us/windows/hardware/windows-driver-kit

Body:
I got exactly this error. The first thing I did was try to search for the .exe using Powershell:

Get-ChildItem -Path C:\ -Filter pvk2pfx.exe -Recurse -ErrorAction SilentlyContinue -Force

I could not find it but I could find makecert.exe with this command.

Turned out I did not have the package Desktop development with C++ installed for Visual Studio 2017. After I added this everything worked. Remember to run the command through Developer Command Prompt for VS 2017.

If you do not use Visual Studio 2017 you can download Windows Driver Kit (WDK) from here instead:

https://developer.microsoft.com/en-us/windows/hardware/windows-driver-kit


问:
How to show ajax response data into php variable inside a foreach loop
I have a view where some data is shown in a table with filtering option. When I choose an option of dropdown from the filtering part I want only table part will be refreshed and shown the updated data.
I have successfully filtered data from database using ajax. But can't show the filtered data (ajax response) in the table.

Filtering and table part of view.php

```<code><div class="col-lg-8">
    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3 class="panel-title"> Search </h3>
        </div>
        <div class="panel-body">
            <div class=" col-md-5">
                <select class="form-control selectpicker searchField" id="selectTitleId_search">

                    <option value="">Select Title</option>

                    @foreach($titleData as $value)
                        <option value="{{$value->id}}">{{$value->name}}</option>
                    @endforeach

                </select>
            </div>
            <div class="col-md-5">
                <input type="text" id="datepicker" class="form-control searchField" placeholder="Select date">
                <span class="add-on"><i class="icon-th"></i></span>
            </div>
            <div class="col-md-2">
                <button type="button" class="btn btn-info" id="searchButton">
                    Search
                </button>
            </div>
        </div>
    </div>
</div>

<br/>

<div class="col-lg-9">
    <div class="panel panel-info" >
        <div class="panel-heading" style="padding:5px" >
            <div class="panel-title">
                <h3> Daily Income Report</h3>
            </div>
        </div>
        <div class="panel-body" id="report">

            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>Title Name</th>
                        <th>Amount</th>
                        <th>Date & Time</th>
                    </tr>
                </thead>
                <tbody style="font-size: 1.3em;">
                    <!-- Button trigger modal -->
                    <button type="button" class="btn btn-info pull-right addItem" data-toggle="modal" data-target="#exampleModal">
                      Add
                    </button>

                @foreach($data as $value)
                    <tr class="itemList" data-toggle="modal" data-target="#exampleModal">
                        <input type="hidden" id="id" value="{{ $value->id }}">
                        <input type="hidden" id="titleId" value="{{ $value->title_id }}">
                        <td id="title_name" >

                            {{ $value->name }}

                        </td>
                        <td id="transaction_amount" >

                            {{ $value->amount }}

                        </td>
                        <td id="transaction_date">

                            {{ $value->created_at }}

                        </td>

                    </tr>
                @endforeach

              </tbody>
            </table>

            {{ $data->links() }}

        </div>
    </div>
</div>
</code>```

ajax part of view.php

```<code>$(".searchField").change(function()
{
    var title_id = $("#selectTitleId_search").val();
    var date = $('#datepicker').val();
    var token = $('input[name=_token]').val();
    var report_type_id = 1;
    // console.log(date);
    $.ajax({
        url:"/filter",
        type: 'POST',
        data: {_token :token, title_id : title_id, date : date, report_type_id : report_type_id},
        success:function(msg)
        {
            console.log(msg);
            $(".itemList").append(msg);
        }
    });
});
</code>```

Now how can I send the ajax response data to foreach() loop of the table to show the filtered data

答:
Use foreach loop in ajax success function and append data to list</p>

```<code>$.ajax({
    url:"/filter",
    type: 'POST',
    data: {_token :token, title_id : title_id, date : date, report_type_id : report_type_id},
    success:function(msg){
        console.log(msg);
        msg.forEach(function(item) {
            // do something with `item`
            $(".itemList").append(item);
        });
    }
});
</code>```

Body:
I have a view where some data is shown in a table with filtering option. When I choose an option of dropdown from the filtering part I want only table part will be refreshed and shown the updated data.
I have successfully filtered data from database using ajax. But can't show the filtered data (ajax response) in the table.

Filtering and table part of view.php

 Search

                <select class="form-control selectpicker searchField" id="selectTitleId_search">

                    <option value="">Select Title</option>

                    @foreach($titleData as $value)
                        <option value="{{$value->id}}">{{$value->name}}</option>
                    @endforeach

                </select>

                <input type="text" id="datepicker" class="form-control searchField" placeholder="Select date">

                <button type="button" class="btn btn-info" id="searchButton">
                    Search
                </button>

 Daily Income Report

                        Title Name
                        Amount
                        Date & Time

                    <button type="button" class="btn btn-info pull-right addItem" data-toggle="modal" data-target="#exampleModal">
                      Add
                    </button>

                @foreach($data as $value)

                        <input type="hidden" id="id" value="{{ $value->id }}">
                        <input type="hidden" id="titleId" value="{{ $value->title_id }}">

                            {{ $value->name }}

                            {{ $value->amount }}

                            {{ $value->created_at }}

                @endforeach

            {{ $data->links() }}

ajax part of view.php

$(".searchField").change(function()
{
    var title_id = $("#selectTitleId_search").val();
    var date = $('#datepicker').val();
    var token = $('input[name=_token]').val();
    var report_type_id = 1;
    // console.log(date);
    $.ajax({
        url:"/filter",
        type: 'POST',
        data: {_token :token, title_id : title_id, date : date, report_type_id : report_type_id},
        success:function(msg)
        {
            console.log(msg);
            $(".itemList").append(msg);
        }
    });
});

Now how can I send the ajax response data to foreach() loop of the table to show the filtered data

Body:
Use foreach loop in ajax success function and append data to list

$.ajax({
    url:"/filter",
    type: 'POST',
    data: {_token :token, title_id : title_id, date : date, report_type_id : report_type_id},
    success:function(msg){
        console.log(msg);
        msg.forEach(function(item) {
            // do something with `item`
            $(".itemList").append(item);
        });
    }
});