问:
Workflow for creating packages in Go
I understand that programs in Go are run from the main function as their starting point. But I was wondering what the workflow is for creating functions for a new package.

In python for example I use __main__ in module's when the module is called directly. When the module is imported from another file __main__ would be ignored. Which is useful when you're developing a new module.

```<code>if __name__ == "__main__":
    # Run module code here if module called directly
</code>```

For Go I'm using a test.go file with a package main along with my main.go file to test functions in packages I'm creating.

```<code>// test.go
package main

import (
    "newpackage"
)

func main() {
    newpackage.MyNewFunc()
}
</code>```

Is there a better way to do this or is this the standard workflow? Thanks.

答:
You don't test in Go using main. Go has its own test framework.

First, read "How to Write Go Code" which will explain Go's package layout and testing tools. It's best to go with them because so much of the Go tools expect that layout.

When creating a package, put it somewhere in ~/go/src. I'd recommend following the convention using the repository you like to use, even for things you aren't necessarily going to upload. It makes for better organization; go get will put other external packages in ~/go/src/ as well.

For example, I'd use ~/go/src/github.com/schwern/newpackage/ even though I don't intend to upload this to Github. github.com/schwern acts as my "organization" within the Go source tree.

Put the functions into newpackage.go under package newpackage.

```<code>$ cat ~/go/src/github.com/schwern/newpackage/newpackage.go
package newpackage

func MyNewFunc() string {
    return "Hello!"
}
</code>```

Then tests go in newpackage_test.go right next to newpackage.go. These should be familiar from Python, write a bunch of Test* functions. Unlike Python it doesn't use asserts.

```<code>$ cat ~/go/src/github.com/schwern/newpackage/newpackage_test.go
package newpackage_test

import(
    "testing"
    "github.com/schwern/newpackage"
)

func TestMyNewFunc( t *testing.T ) {
    want := "Hello!"
    have := newpackage.MyNewFunc()

    if have != want {
        t.Errorf("MyNewFunc(): have: '%v', want: '%v'", have, want )
    }
}
</code>```

If you run go test inside the package directory it will compile the current package and its dependencies, find and compile all *_test.go files in the package directory, and execute their Test* functions.

```<code>$ pwd
/Users/schwern/go/src/github.com/schwern/newpackage
$ go test -v
=== RUN   TestMyNewFunc
--- PASS: TestMyNewFunc (0.00s)
PASS
ok      github.com/schwern/newpackage   0.013s
</code>```

Note that the test is in a different package than what its testing. That makes it a blackbox test, it can only see the exported (ie. UpperCase) functions. You can make a glassbox test by putting the tests in the same package, it's best to do that in a separate file like newpackage_internal_test.go.

Unfortunately Go doesn't come with assert functions, the above if and call to t.Errorf is the equivalent. Rather than constantly hand-roll them, there's libraries out there which provide assert functions like stvp/assert. After running go get github.com/stvp/assert you could write...

```<code>package newpackage_test

import(
    "testing"
    "github.com/schwern/newpackage"
    "github.com/stvp/assert"
)

func TestMyNewFunc( t *testing.T ) {
    assert.Equal( t, newpackage.MyNewFunc(), "Hello!" )
}
</code>```

If you want an executable that uses newpackage, it should probably go in its own package. Unless it's an integral part of newpackage.

```<code>$ cat ~/go/src/github.com/schwern/newexec/main.go
package main

import (
    "fmt"
    "github.com/schwern/newpackage"
)

func main() {
    fmt.Println(newpackage.MyNewFunc())
}
</code>```

If you want to test main, the testing package provides a special TestMain function... though I admit I do not fully understand it. Like any other language, it's best to put as much functionality as possible into library calls and have main be a thin wrapper.

Title: Workflow for creating packages in Go

Body:
I understand that programs in Go are run from the main function as their starting point. But I was wondering what the workflow is for creating functions for a new package.

In python for example I use __main__ in module's when the module is called directly. When the module is imported from another file __main__ would be ignored. Which is useful when you're developing a new module.

if __name__ == "__main__":
    # Run module code here if module called directly

For Go I'm using a test.go file with a package main along with my main.go file to test functions in packages I'm creating.

// test.go
package main

import (
    "newpackage"
)

func main() {
    newpackage.MyNewFunc()
}

Is there a better way to do this or is this the standard workflow? Thanks.

Body:
You don't test in Go using main. Go has its own test framework.

First, read "How to Write Go Code" which will explain Go's package layout and testing tools. It's best to go with them because so much of the Go tools expect that layout.

When creating a package, put it somewhere in ~/go/src. I'd recommend following the convention using the repository you like to use, even for things you aren't necessarily going to upload. It makes for better organization; go get will put other external packages in ~/go/src/ as well.

For example, I'd use ~/go/src/github.com/schwern/newpackage/ even though I don't intend to upload this to Github. github.com/schwern acts as my "organization" within the Go source tree.

Put the functions into newpackage.go under package newpackage.

$ cat ~/go/src/github.com/schwern/newpackage/newpackage.go
package newpackage

func MyNewFunc() string {
    return "Hello!"
}

Then tests go in newpackage_test.go right next to newpackage.go. These should be familiar from Python, write a bunch of Test* functions. Unlike Python it doesn't use asserts.

$ cat ~/go/src/github.com/schwern/newpackage/newpackage_test.go
package newpackage_test

import(
    "testing"
    "github.com/schwern/newpackage"
)

func TestMyNewFunc( t *testing.T ) {
    want := "Hello!"
    have := newpackage.MyNewFunc()

    if have != want {
        t.Errorf("MyNewFunc(): have: '%v', want: '%v'", have, want )
    }
}

If you run go test inside the package directory it will compile the current package and its dependencies, find and compile all *_test.go files in the package directory, and execute their Test* functions.

$ pwd
/Users/schwern/go/src/github.com/schwern/newpackage
$ go test -v
=== RUN   TestMyNewFunc
--- PASS: TestMyNewFunc (0.00s)
PASS
ok      github.com/schwern/newpackage   0.013s

Note that the test is in a different package than what its testing. That makes it a blackbox test, it can only see the exported (ie. UpperCase) functions. You can make a glassbox test by putting the tests in the same package, it's best to do that in a separate file like newpackage_internal_test.go.

Unfortunately Go doesn't come with assert functions, the above if and call to t.Errorf is the equivalent. Rather than constantly hand-roll them, there's libraries out there which provide assert functions like stvp/assert. After running go get github.com/stvp/assert you could write...

package newpackage_test

import(
    "testing"
    "github.com/schwern/newpackage"
    "github.com/stvp/assert"
)

func TestMyNewFunc( t *testing.T ) {
    assert.Equal( t, newpackage.MyNewFunc(), "Hello!" )
}

If you want an executable that uses newpackage, it should probably go in its own package. Unless it's an integral part of newpackage.

$ cat ~/go/src/github.com/schwern/newexec/main.go
package main

import (
    "fmt"
    "github.com/schwern/newpackage"
)

func main() {
    fmt.Println(newpackage.MyNewFunc())
}

If you want to test main, the testing package provides a special TestMain function... though I admit I do not fully understand it. Like any other language, it's best to put as much functionality as possible into library calls and have main be a thin wrapper.


来源: stackexchange

问:
Recursion error while creating Asset which is having self-join relationship
I have defined Asset as :

```<code> asset PurchaseOrderAsset identified by orderId {

    o String orderId

    --> SupplierChainParticipant createdBy

    --> SupplierChainParticipant assignedTo

    o String description

    o String status

    o Integer quantity

    o String assetId

    o PurchaseOrderAsset[] subPurchaseOrders
}
</code>```

Now, When I am trying to create Asset, I am getting error as "InternalError: too much recursion".  i am facing this error in composer playground.

Can we have self-join relationship or not?

答:
This is a bug, please create an issue for it, attaching your example BNA.

To workaround it I recommend that you create a concept for the line items of a purchase order. Conceptually those "sub" purchase orders are not assets, because they are not addressable through a registry.

Please also see: Different between 'o' and arrow symbol used in .cto file?

ContentLicense: CC BY-SA 3.0

Body:
I have defined Asset as :

 asset PurchaseOrderAsset identified by orderId {

    o String orderId

    --> SupplierChainParticipant createdBy

    --> SupplierChainParticipant assignedTo

    o String description

    o String status

    o Integer quantity

    o String assetId

    o PurchaseOrderAsset[] subPurchaseOrders
}

Now, When I am trying to create Asset, I am getting error as "InternalError: too much recursion".  i am facing this error in composer playground.

Can we have self-join relationship or not?


问:
Need to filter out all columns which have null,0 or empty values in sql server from a group of tables
I have a bunch of tables about 50 of them and from all of those tables I am trying to figure out a way to filter all the columns which have 0 null or empty values in them. Not sure if sys.tables or Information_schema.tables would have any such function to suffice this.Like here the last column have null values for all rows so for each table I  supply in my query I need all such column with table name</p>

答:
The following command will use NULLIF two times to deal with 0 and with '' and with NULL all the same. COUNT() will not count rows with NULL. If the count returns 0, then there is no other content in this column:

```<code>SELECT COUNT(NULLIF(NULLIF(CAST(tbl.SomeField AS NVARCHAR(MAX)),''),'0'))
FROM SomeTable AS tbl;
</code>```

The nice part is: You do not have to type this for all columns... The following code will generate this command for all columns of a given table and use EXEC() for its execution:

```<code>DECLARE @cmd NVARCHAR(MAX);
DECLARE @tableName NVARCHAR(MAX)='SomeTable'
SELECT @cmd='SELECT '
      + STUFF(
        (
        SELECT ',COUNT(NULLIF(NULLIF(CAST(' +  QUOTENAME(COLUMN_NAME) + ' AS NVARCHAR(MAX)),''''),''0''))'
             + ' AS ' + QUOTENAME('CountOf_' + COLUMN_NAME)
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_NAME=@tableName
        FOR XML PATH(''),TYPE).value(N'.',N'nvarchar(max)'),1,1,'')
      + ' FROM ' + QUOTENAME(@tableName) + ';'

PRINT @cmd; --check the output in a query window
EXEC(@cmd);
</code>```

You might want to use a WHERE clause to reduce this to columns with specific types...

It should be rather easy to take this further to deal with all your tables in a (CURSOR) loop dynamically.

Body:
The following command will use NULLIF two times to deal with 0 and with '' and with NULL all the same. COUNT() will not count rows with NULL. If the count returns 0, then there is no other content in this column:

SELECT COUNT(NULLIF(NULLIF(CAST(tbl.SomeField AS NVARCHAR(MAX)),''),'0'))
FROM SomeTable AS tbl;

The nice part is: You do not have to type this for all columns... The following code will generate this command for all columns of a given table and use EXEC() for its execution:

DECLARE @cmd NVARCHAR(MAX);
DECLARE @tableName NVARCHAR(MAX)='SomeTable'
SELECT @cmd='SELECT '
      + STUFF(
        (
        SELECT ',COUNT(NULLIF(NULLIF(CAST(' +  QUOTENAME(COLUMN_NAME) + ' AS NVARCHAR(MAX)),''''),''0''))'
             + ' AS ' + QUOTENAME('CountOf_' + COLUMN_NAME)
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_NAME=@tableName
        FOR XML PATH(''),TYPE).value(N'.',N'nvarchar(max)'),1,1,'')
      + ' FROM ' + QUOTENAME(@tableName) + ';'

PRINT @cmd; --check the output in a query window
EXEC(@cmd);

You might want to use a WHERE clause to reduce this to columns with specific types...

It should be rather easy to take this further to deal with all your tables in a (CURSOR) loop dynamically.


问:
How can I detect manually modified Nuget content in my solution?
In my project I use a number of Nuget packages (javascript, typescript, other stuff). I'm afraid that while working on it I modified some content which was initially created by the package manager. So there are some questions:

how can I detect files received from Nuget that have been modified by me, e.g. those that don't match with the initial version of file rendered by Nuget?

how can I restore modified Nuget files to their initial versions?

how can I prevent this in the future, e.g. get some notification like "this content originates from Nuget, don't modify it!"

Thanks in advance.

答:
how can I detect files received from Nuget that have been modified by me, e.g. those that don't match with the initial version of file rendered by Nuget?

AFAIK, there is not a intuitive way to detect files received from Nuget that have been modified, but I would like provide you a workaround to detect those modified files. You can use the below command line in the Package Manager Console:

```<code>Update-Package –reinstall packagename
</code>```

If you have made some modification on that package before using this command, you will get a prompt: Skipping filename' because it was modified. in the Package Manager Console window.

how can I restore modified Nuget files to their initial versions?

You can also use the method which I mentioned before, you can notice that there is an another prompting: "File is already exist in the project, Do you want to overwrite it". If you enter Y or A, all the modified files will restore to their initial versions, or you can uninstall the package and reinstall it(need to delete those modification file manually)

how can I prevent this in the future, e.g. get some notification like "this content originates from Nuget, don't modify it!"

If you want to prevent the file from being modified, you can consider marking the files as read-only or something - any files that are pulled down i.e. source file or content should be considered read-only IMO.

Body:
how can I detect files received from Nuget that have been modified by me, e.g. those that don't match with the initial version of file rendered by Nuget?

AFAIK, there is not a intuitive way to detect files received from Nuget that have been modified, but I would like provide you a workaround to detect those modified files. You can use the below command line in the Package Manager Console:

Update-Package –reinstall packagename

If you have made some modification on that package before using this command, you will get a prompt: Skipping filename' because it was modified. in the Package Manager Console window.

how can I restore modified Nuget files to their initial versions?

You can also use the method which I mentioned before, you can notice that there is an another prompting: "File is already exist in the project, Do you want to overwrite it". If you enter Y or A, all the modified files will restore to their initial versions, or you can uninstall the package and reinstall it(need to delete those modification file manually)

how can I prevent this in the future, e.g. get some notification like "this content originates from Nuget, don't modify it!"

If you want to prevent the file from being modified, you can consider marking the files as read-only or something - any files that are pulled down i.e. source file or content should be considered read-only IMO.


问:
Why is my program skipping over the indices of repeated words
I am having problems with my program. Basically it finds the word count of a text file, the most and least repeated word, and have the user find a word. My problem is that when I find a words, it skips the indices of the repeated words. For example, if a text file has the words:

one two one one three five

and the user searches for "three", it will output that the index is 2. It skips over the repeated words. Why is that?

Here is my code:

```<code>int main() {
    int counts[ARRAY_SIZE] = { 0 };
    string words[ARRAY_SIZE];
    ifstream inFile;
    string filename, searchWord, lowerCase;
    int wordCount = 0, totalWords = 0, index = 0;
    int result, mostIndex, leastIndex;
    cout << "Enter a text file: ";
    cin >> filename;
    inFile.open(filename);
    while (!inFile.is_open()) {

        if (filename == "q") {
            inFile.close();
            return 0;
        }
        else if (inFile.is_open()) {
            cout << filename << " is open";
        }
        else {
            cout << "Enter a valid file or type \"q\".";
        }
        cout << "The file you enetered is not valid, please enter a valid file or type \"q\" to quit.";
        cin >> filename;
        inFile.open(filename);
    }
    while (!inFile.eof()) {
        while (inFile >> lowerCase) {
            wordCount++;
            lowerCase = convertCase(lowerCase);
            result = search(words, lowerCase, totalWords);
            if (result == NOT_FOUND) {
                words[totalWords] = lowerCase; // lowerCase is a new word, so add it to the array,
                counts[totalWords] = 1;      //  and set it's count to 1.
                totalWords++;
            }
            else {
                counts[result]++; // The word was found, so increment the times we've seen it.
            }
        }

        cout << endl << "Total words: " << wordCount << endl;
        cout << "Search a word: ";
        cin >> searchWord;
        index = search(words, searchWord, totalWords);
        if (index == NOT_FOUND) {
            cout << "\"" << searchWord << "\"" << " was not found." << endl;
        }
        else {
            cout << endl << "the word " << "\"" << searchWord << "\"" << " is found on at index " << index << endl;
        }
        mostIndex = findIndexOfMost(counts, totalWords);
        leastIndex = findIndexOfLeast(counts, totalWords);
        cout << "The most repeated word is \"" << words[mostIndex] << "\" and was found " << counts[mostIndex] << " time(s)." << endl;
        cout << "The least repeated word is \"" << words[leastIndex] << "\" and was found " << counts[leastIndex] << " time(s)." << endl;
    }
    system("pause");
    return 0;
}

string convertCase(string word){
    for (int i = 0; i < word.length(); i++) {
        word[i] = tolower(word[i]);
    }
    return word;
}

int search(string words[], string searchWord, int totalWords){

    int index = NOT_FOUND;
    for (int i = 0; i < totalWords; i++){
        if (words[i] == searchWord){
            index = i;
            break;
        }
    }
    return index;
}

int findIndexOfMost(int counts[], int totalWords){
    int most; // assume most is first count.
    int index = 0, i;
    most = counts[index];

    for (i = 0; i < totalWords; i++)
    {
        if (counts[i] > most){
            most = counts[i];
            index = i;
        }
    }

    return index;
}

int findIndexOfLeast(int counts[], int totalWords) {
    int least, index = 0, i;
    least = counts[index];

    for (i = 0; i < totalWords; i++)
    {
        if (counts[i] < least) {
            least = counts[i];
            index = i;
        }
    }

    return index;
}
</code>```

答:
I agree with the comments on your post, but I did find your error rather quickly. I highly suggest you try the debugger in the future to follow the variables you care about and see what is happening and how they are updating, when they're not updating as you think they would. Even simply printing your array words would show you the problem.

You're only adding words to the words array when they haven't been found yet, so when you search through words, you're searching through the unique words.

```<code>    if (result == NOT_FOUND) {
        words[totalWords] = lowerCase; // lowerCase is a new word, so add it to the array,
        counts[totalWords] = 1;      //  and set it's count to 1.
        totalWords++;
    }
    else {
        counts[result]++; // The word was found, so increment the times we've seen it.
    }
</code>```

For the file

```<code>one two one one three five
</code>```

your variable words would hold

```<code>one two three five
</code>```

so if you searched for 'three' in words you would get the index 2, even though it's the fifth word in your file, so you want the index 4.

Body:
I am having problems with my program. Basically it finds the word count of a text file, the most and least repeated word, and have the user find a word. My problem is that when I find a words, it skips the indices of the repeated words. For example, if a text file has the words:

one two one one three five

and the user searches for "three", it will output that the index is 2. It skips over the repeated words. Why is that?

Here is my code:

int main() {
    int counts[ARRAY_SIZE] = { 0 };
    string words[ARRAY_SIZE];
    ifstream inFile;
    string filename, searchWord, lowerCase;
    int wordCount = 0, totalWords = 0, index = 0;
    int result, mostIndex, leastIndex;
    cout << "Enter a text file: ";
    cin >> filename;
    inFile.open(filename);
    while (!inFile.is_open()) {

        if (filename == "q") {
            inFile.close();
            return 0;
        }
        else if (inFile.is_open()) {
            cout << filename << " is open";
        }
        else {
            cout << "Enter a valid file or type \"q\".";
        }
        cout << "The file you enetered is not valid, please enter a valid file or type \"q\" to quit.";
        cin >> filename;
        inFile.open(filename);
    }
    while (!inFile.eof()) {
        while (inFile >> lowerCase) {
            wordCount++;
            lowerCase = convertCase(lowerCase);
            result = search(words, lowerCase, totalWords);
            if (result == NOT_FOUND) {
                words[totalWords] = lowerCase; // lowerCase is a new word, so add it to the array,
                counts[totalWords] = 1;      //  and set it's count to 1.
                totalWords++;
            }
            else {
                counts[result]++; // The word was found, so increment the times we've seen it.
            }
        }

        cout << endl << "Total words: " << wordCount << endl;
        cout << "Search a word: ";
        cin >> searchWord;
        index = search(words, searchWord, totalWords);
        if (index == NOT_FOUND) {
            cout << "\"" << searchWord << "\"" << " was not found." << endl;
        }
        else {
            cout << endl << "the word " << "\"" << searchWord << "\"" << " is found on at index " << index << endl;
        }
        mostIndex = findIndexOfMost(counts, totalWords);
        leastIndex = findIndexOfLeast(counts, totalWords);
        cout << "The most repeated word is \"" << words[mostIndex] << "\" and was found " << counts[mostIndex] << " time(s)." << endl;
        cout << "The least repeated word is \"" << words[leastIndex] << "\" and was found " << counts[leastIndex] << " time(s)." << endl;
    }
    system("pause");
    return 0;
}

string convertCase(string word){
    for (int i = 0; i < word.length(); i++) {
        word[i] = tolower(word[i]);
    }
    return word;
}

int search(string words[], string searchWord, int totalWords){

    int index = NOT_FOUND;
    for (int i = 0; i < totalWords; i++){
        if (words[i] == searchWord){
            index = i;
            break;
        }
    }
    return index;
}

int findIndexOfMost(int counts[], int totalWords){
    int most; // assume most is first count.
    int index = 0, i;
    most = counts[index];

    for (i = 0; i < totalWords; i++)
    {
        if (counts[i] > most){
            most = counts[i];
            index = i;
        }
    }

    return index;
}

int findIndexOfLeast(int counts[], int totalWords) {
    int least, index = 0, i;
    least = counts[index];

    for (i = 0; i < totalWords; i++)
    {
        if (counts[i] < least) {
            least = counts[i];
            index = i;
        }
    }

    return index;
}

Body:
I agree with the comments on your post, but I did find your error rather quickly. I highly suggest you try the debugger in the future to follow the variables you care about and see what is happening and how they are updating, when they're not updating as you think they would. Even simply printing your array words would show you the problem.

You're only adding words to the words array when they haven't been found yet, so when you search through words, you're searching through the unique words.

    if (result == NOT_FOUND) {
        words[totalWords] = lowerCase; // lowerCase is a new word, so add it to the array,
        counts[totalWords] = 1;      //  and set it's count to 1.
        totalWords++;
    }
    else {
        counts[result]++; // The word was found, so increment the times we've seen it.
    }

For the file

one two one one three five

your variable words would hold

one two three five

so if you searched for 'three' in words you would get the index 2, even though it's the fifth word in your file, so you want the index 4.


问:
Reading CSV files from RAM
Situation: I have a CVD (ClamAV Virus Database) file loaded into RAM using mmap. The format of every line in the CVD file is same as the one of CSV files (':' delimited). Below is a snippet of the code:

```<code>def mapping():
    with open("main.cvd", 'rt') as f:
        global mapper
        mapper = mmap.mmap(f.fileno(), 0, prot=mmap.PROT_READ)
        csv.register_dialect('delimit', delimiter=':', quoting=csv.QUOTE_NONE)

def compare(hashed):
    for row in csv.reader(mapper, dialect='delimit'):
        if row[1] == hashed:
            print('Found!')
</code>```

Problem: When run, it returns the error _csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)

Question: How do I read CSV files as text that have been loaded to memory?

Additional information 1: I have tried using StringIO, it throws the error TypeError: initial_value must be str or None, not mmap.mmap

Additional information 2: I need the file to be in the RAM for faster access to the file and I cannot sacrifice time reading it line by line using functions such as readline()

答:
The csvfile argument to the csv.reader constructor "can be any object which supports the iterator protocol and returns a string each time its next() method is called".

This means the "object" can be a generator function or a generator expression. In the code below I've implement a generator function called mmap_file_reader() which will convert the bytes in the memory map into character strings and yield each line of output it detects.

I made the mmap.mmap constructor call conditional so it would work on Windows, too. This shouldn't be necessary if you used the access= keyword instead of prot= keyword—but I couldn't test that and so did it as shown.

```<code>import csv
import mmap
import sys

def mapping():
    with open("main.cvd", 'rt') as f:
        global mapper
        if sys.platform.startswith('win32'):
            mmf = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)  # windows
        else:
            mmf = mmap.mmap(f.fileno(), 0, prot=mmap.PROT_READ)  # unix
        mapper = mmap_file_reader(mmf)
        csv.register_dialect('delimit', delimiter=':', quoting=csv.QUOTE_NONE)

def mmap_file_reader(mmf):
    '''Yield successive lines of the given memory-mapped file as strings.

    Generator function which reads and converts the bytes of the given mmapped file
    to strings and yields them one line at a time.
    '''
    while True:
        line = mmf.readline()
        if not line:  # EOF?
            return
        yield str(line, encoding='utf-8')  # convert bytes of lineread into a string

def compare(hashed):
    for row in csv.reader(mapper, dialect='delimit'):
        if row[1] == hashed:
            print('Found!')
</code>```

Title: Reading CSV files from RAM

Body:
Situation: I have a CVD (ClamAV Virus Database) file loaded into RAM using mmap. The format of every line in the CVD file is same as the one of CSV files (':' delimited). Below is a snippet of the code:

def mapping():
    with open("main.cvd", 'rt') as f:
        global mapper
        mapper = mmap.mmap(f.fileno(), 0, prot=mmap.PROT_READ)
        csv.register_dialect('delimit', delimiter=':', quoting=csv.QUOTE_NONE)

def compare(hashed):
    for row in csv.reader(mapper, dialect='delimit'):
        if row[1] == hashed:
            print('Found!')

Problem: When run, it returns the error _csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)

Question: How do I read CSV files as text that have been loaded to memory?

Additional information 1: I have tried using StringIO, it throws the error TypeError: initial_value must be str or None, not mmap.mmap

Additional information 2: I need the file to be in the RAM for faster access to the file and I cannot sacrifice time reading it line by line using functions such as readline()

Body:
The csvfile argument to the csv.reader constructor "can be any object which supports the iterator protocol and returns a string each time its next() method is called".

This means the "object" can be a generator function or a generator expression. In the code below I've implement a generator function called mmap_file_reader() which will convert the bytes in the memory map into character strings and yield each line of output it detects.

I made the mmap.mmap constructor call conditional so it would work on Windows, too. This shouldn't be necessary if you used the access= keyword instead of prot= keyword—but I couldn't test that and so did it as shown.

import csv
import mmap
import sys

def mapping():
    with open("main.cvd", 'rt') as f:
        global mapper
        if sys.platform.startswith('win32'):
            mmf = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)  # windows
        else:
            mmf = mmap.mmap(f.fileno(), 0, prot=mmap.PROT_READ)  # unix
        mapper = mmap_file_reader(mmf)
        csv.register_dialect('delimit', delimiter=':', quoting=csv.QUOTE_NONE)

def mmap_file_reader(mmf):
    '''Yield successive lines of the given memory-mapped file as strings.

    Generator function which reads and converts the bytes of the given mmapped file
    to strings and yields them one line at a time.
    '''
    while True:
        line = mmf.readline()
        if not line:  # EOF?
            return
        yield str(line, encoding='utf-8')  # convert bytes of lineread into a string

def compare(hashed):
    for row in csv.reader(mapper, dialect='delimit'):
        if row[1] == hashed:
            print('Found!')


问:
select a button using selenium
how to select login button using selenium web driver

```<code><li id="buttons" class="greetings_fmt">
    <a href="#">
       <div class="user_btn log_in_icon">LOG IN</div>
    </a>
    <a href="#">
       <div class="user_btn sign_up_icon">SIGN UP</div>
    </a>
</li>
</code>```

tried with this code but not working

```<code>WebElement ele = driver.findElement(By.id("buttons"));
      List<WebElement> ele1 = ele.findElements(By.tagName("a"));
      for(WebElement e : ele1){
         e.click()

      }
</code>```

答: It looks what you are trying to automate is incomplete.Login is not a button. It is a link. Clicking on this link will take you nowhere as href="#".

Title: select a button using selenium

Body:
how to select login button using selenium web driver

LOG IN

SIGN UP

tried with this code but not working

WebElement ele = driver.findElement(By.id("buttons"));
      List<WebElement> ele1 = ele.findElements(By.tagName("a"));
      for(WebElement e : ele1){
         e.click()

      }


问:
Creation of buttons for SpriteKit
I am creating the main menu for a sprite kit application I am building. Throughout my entire project, I have used SKScenes to hold my levels and the actual gameplay. However, now I need a main menu, which holds buttons like "Play," "Levels," "Shop," etc... However, I don't feel really comfortable the way I am adding buttons now, which is like this:

```<code>let currentButton = SKSpriteNode(imageNamed: button)  // Create the SKSpriteNode that holds the button

self.addChild(currentButton) // Add that SKSpriteNode to the SKScene
</code>```

And I check for the touch of the button like this:

```<code>override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first
    let touchLocation = touch!.location(in: self)

    for node in self.nodes(at: touchLocation) {
        guard let nodeName = node.name else {
            continue
        }
        if nodeName == ButtonLabel.Play.rawValue {
            DispatchQueue.main.asyncAfter(deadline: .now()) {
                let transition = SKTransition.reveal(with: .left, duration: 1)
                self.view?.presentScene(self.initialLevel, transition: transition)
                self.initialLevel.loadStartingLevel()
            }
            return
        }
        if nodeName == ButtonLabel.Levels.rawValue {
            slideOut()
        }

    }
}
</code>```

However, I don't know if this is considered efficient. I was thinking of using UIButtons instead, but for that would I have to use an UIView?

Or can I add UIButtons to an SKView (I don't really get the difference between an SKView, SKScene, and UIView) What is recommended for menus?

答:
For simple scenes what you are doing is fine, and actually preferred because you can use the .SKS file.

However, if you have a complex scene what I like to do is subclass a Sprite and then override that node's touchesBegan.

Here is a node that I use in all of my projects... It is a simple "on off" button. I use a "pointer" to a Boolean via the custom Reference class I made, so that way this node doesn't need to be concerned with your other scenes, nodes, etc--it simply changes the value of the Bool for the other bits of code to do with what they want:

```<code>public final class Reference<T> { var value: T; init(_ value: T) { self.value = value } }

// MARK: - Toggler:
public final class Toggler: SKLabelNode {

  private var refBool: Reference<Bool>
  var value: Bool { return refBool.value }

  var labelName: String
  /*
   var offText = ""
   var onText = ""
   */

  func toggleOn() {
    refBool.value = true
    text = labelName + ": on"
  }

  func toggleOff() {
    refBool.value = false
    text = labelName + ": off"
  }

  /*init(offText: String, onText: String, refBool: Reference<Bool>) {
   ref = refBool
   super.init(fontNamed: "Chalkduster")
   if refBool.value { toggleOn() } else { toggleOff() }
   isUserInteractionEnabled = true
   }
   */

  init(labelName: String, refBool: Reference<Bool>) {
    self.refBool = refBool
    self.labelName = labelName
    super.init(fontNamed: "Chalkduster")
    isUserInteractionEnabled = true

    self.refBool = refBool
    self.labelName = labelName
    if refBool.value { toggleOn() } else { toggleOff() }
  }

  public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if refBool.value { toggleOff() } else { toggleOn() }
  }

  public required init?(coder aDecoder: NSCoder) { fatalError("") }
  override init() {
    self.refBool = Reference<Bool>(false)
    self.labelName = "ERROR"
    super.init()
  }
};
</code>```

This is a more elaborate button than say something that just runs a bit of code when you click it.

The important thing here is that if you go this route, then you need to make sure to set the node's .isUserInteractionEnabled to true or it will not receive touch input.

Another suggestion along the lines of what you are doing, is to separate the logic from the action:

```<code>// Outside of touches func:
func touchPlay() {
  // Play code
}

func touchExit() {
  // Exit code
}

// In touches began:
guard let name = node.name else { return }

switch name {
  case "play": touchPlay()
  case "exit": touchExit()
  default:()
}
</code>```

PS:

Here is a very basic example of how to use Toggler:

```<code>class Scene: SKScene {

  let spinnyNode = SKSpriteNode(color: .blue, size: CGSize(width: 50, height: 50))

  // This is the reference type instance that will be stored inside of our Toggler instance:
  var shouldSpin = Reference<Bool>(true)

  override func didMove(to view: SKView) {
    addChild(spinnyNode)
    spinnyNode.run(.repeatForever(.rotate(byAngle: 3, duration: 1)))

    let toggleSpin = Toggler(labelName: "Toggle Spin", refBool: shouldSpin)
    addChild(toggleSpin)
    toggleSpin.position.y += 100
  }

  override func update(_ currentTime: TimeInterval) {
    if shouldSpin.value == true {
      spinnyNode.isPaused = false
    } else if shouldSpin.value == false {
      spinnyNode.isPaused = true
    }
  }
}
</code>```

Title: Creation of buttons for SpriteKit

Body:
I am creating the main menu for a sprite kit application I am building. Throughout my entire project, I have used SKScenes to hold my levels and the actual gameplay. However, now I need a main menu, which holds buttons like "Play," "Levels," "Shop," etc... However, I don't feel really comfortable the way I am adding buttons now, which is like this:

let currentButton = SKSpriteNode(imageNamed: button)  // Create the SKSpriteNode that holds the button

self.addChild(currentButton) // Add that SKSpriteNode to the SKScene

And I check for the touch of the button like this:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first
    let touchLocation = touch!.location(in: self)

    for node in self.nodes(at: touchLocation) {
        guard let nodeName = node.name else {
            continue
        }
        if nodeName == ButtonLabel.Play.rawValue {
            DispatchQueue.main.asyncAfter(deadline: .now()) {
                let transition = SKTransition.reveal(with: .left, duration: 1)
                self.view?.presentScene(self.initialLevel, transition: transition)
                self.initialLevel.loadStartingLevel()
            }
            return
        }
        if nodeName == ButtonLabel.Levels.rawValue {
            slideOut()
        }

    }
}

However, I don't know if this is considered efficient. I was thinking of using UIButtons instead, but for that would I have to use an UIView?

Or can I add UIButtons to an SKView (I don't really get the difference between an SKView, SKScene, and UIView) What is recommended for menus?

Body:
For simple scenes what you are doing is fine, and actually preferred because you can use the .SKS file.

However, if you have a complex scene what I like to do is subclass a Sprite and then override that node's touchesBegan.

Here is a node that I use in all of my projects... It is a simple "on off" button. I use a "pointer" to a Boolean via the custom Reference class I made, so that way this node doesn't need to be concerned with your other scenes, nodes, etc--it simply changes the value of the Bool for the other bits of code to do with what they want:

public final class Reference<T> { var value: T; init(_ value: T) { self.value = value } }

// MARK: - Toggler:
public final class Toggler: SKLabelNode {

  private var refBool: Reference<Bool>
  var value: Bool { return refBool.value }

  var labelName: String
  /*
   var offText = ""
   var onText = ""
   */

  func toggleOn() {
    refBool.value = true
    text = labelName + ": on"
  }

  func toggleOff() {
    refBool.value = false
    text = labelName + ": off"
  }

  /*init(offText: String, onText: String, refBool: Reference<Bool>) {
   ref = refBool
   super.init(fontNamed: "Chalkduster")
   if refBool.value { toggleOn() } else { toggleOff() }
   isUserInteractionEnabled = true
   }
   */

  init(labelName: String, refBool: Reference<Bool>) {
    self.refBool = refBool
    self.labelName = labelName
    super.init(fontNamed: "Chalkduster")
    isUserInteractionEnabled = true

    self.refBool = refBool
    self.labelName = labelName
    if refBool.value { toggleOn() } else { toggleOff() }
  }

  public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if refBool.value { toggleOff() } else { toggleOn() }
  }

  public required init?(coder aDecoder: NSCoder) { fatalError("") }
  override init() {
    self.refBool = Reference<Bool>(false)
    self.labelName = "ERROR"
    super.init()
  }
};

This is a more elaborate button than say something that just runs a bit of code when you click it.

The important thing here is that if you go this route, then you need to make sure to set the node's .isUserInteractionEnabled to true or it will not receive touch input.

Another suggestion along the lines of what you are doing, is to separate the logic from the action:

// Outside of touches func:
func touchPlay() {
  // Play code
}

func touchExit() {
  // Exit code
}

// In touches began:
guard let name = node.name else { return }

switch name {
  case "play": touchPlay()
  case "exit": touchExit()
  default:()
}

PS:

Here is a very basic example of how to use Toggler:

class Scene: SKScene {

  let spinnyNode = SKSpriteNode(color: .blue, size: CGSize(width: 50, height: 50))

  // This is the reference type instance that will be stored inside of our Toggler instance:
  var shouldSpin = Reference<Bool>(true)

  override func didMove(to view: SKView) {
    addChild(spinnyNode)
    spinnyNode.run(.repeatForever(.rotate(byAngle: 3, duration: 1)))

    let toggleSpin = Toggler(labelName: "Toggle Spin", refBool: shouldSpin)
    addChild(toggleSpin)
    toggleSpin.position.y += 100
  }

  override func update(_ currentTime: TimeInterval) {
    if shouldSpin.value == true {
      spinnyNode.isPaused = false
    } else if shouldSpin.value == false {
      spinnyNode.isPaused = true
    }
  }
}


问:
Validate mobile number into 10 digit numbers in php jquery
I am trying to validate phone number jquery when alphabets are pressed it as to display error message. Below code takes enters digits but doesnt validate to 10 digits. How to validate to 10 digit number. </p>

```<code><script type="text/javascript" >
 $(function() {
   $("#phno").bind("keypress", function (event) {
                if (event.charCode != 0) {
                       var regex = new RegExp("^[0-9]{10}$");
                    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
                    if (!regex.test(key)) {
                      alert("Please enter valid Student Phone No");
                        event.preventDefault();
                        return false;
                    }
                }
            });
 });
</code>```

答:
Here is a working code for you which EXACTLY checks for 10 digits, only accepts numbers and nothing else:

$(function() {
  $("#phno").bind("keydown", function(event) {
    var a = $(this).val();
    if (a.match(/^\d{9}$/)) {
      console.log("Perfect!");
    } else {
      console.log("Invalid. Ensure, there are 10 digits.");
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='phno' /></code>```

Body:
Here is a working code for you which EXACTLY checks for 10 digits, only accepts numbers and nothing else:

$(function() {
  $("#phno").bind("keydown", function(event) {
    var a = $(this).val();
    if (a.match(/^\d{9}$/)) {
      console.log("Perfect!");
    } else {
      console.log("Invalid. Ensure, there are 10 digits.");
    }
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='phno' />


问:
VBA Excel Export Rows to Columns in .txt
Does anyone have an idea how to write VBA in Excel to export multiple rows to just one column. Additionally, I would like to add "enter" at the end of each "row". Ideally, this would be exported in .txt, but it would be already great even if it is converted inside the same document.

Thank you!

Edit: For example: I have rows which contain some text/value A1:A5, B1:B5, ... I would need all of These rows to get "moved" in a single column D for instance. So, A1 would go to D1,A2-D2, A3-D3 ... B1 to D7 and so on. After each end (A5, B5, C5,...) I would need an empty cell (when I convert this to .txt it means enter). I hope it is a bit clearer now.

答:
you need add reference Microsoft ActiveX Data Objects 2.8 Library</p>

```<code>Set ff = CreateObject("ADODB.Stream")
ff.Type = 2
ff.Charset = "utf-8"
ff.Open

For Each Cell In Range("A1:D5").Cells
ff.WriteText Cell.Value & vbNewLine
Next

path_to_save = ActiveWorkbook.Path

ff.SaveToFile path_to_save & "\test.txt", 2
</code>```

Body:
you need add reference Microsoft ActiveX Data Objects 2.8 Library

Set ff = CreateObject("ADODB.Stream")
ff.Type = 2
ff.Charset = "utf-8"
ff.Open

For Each Cell In Range("A1:D5").Cells
ff.WriteText Cell.Value & vbNewLine
Next

path_to_save = ActiveWorkbook.Path

ff.SaveToFile path_to_save & "\test.txt", 2


答:
you can use this

$(function() {
   $("#phno").bind("keydown", function (e) {
        if ((e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 96 && e.keyCode <= 105)) {
             // 0-9
            var val = $(this).val();
            if (!val.match(/^\d{9}$/))
            {
               console.log("it is a number but nut match 10 digit")
            }
            else
            {
               console.log("success");
               return false; // to restrict user to not enter more than 10 digit
            }
        }
        else
        {
           if(e.keyCode == 8)
              return true; // backspace
           alert("Please enter valid Student Phone No");
                event.preventDefault();
                return false;
        }
   });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='phno' /></code>```

Title: Validate mobile number into 10 digit numbers in php jquery

Body: I am trying to validate phone number jquery when alphabets are pressed it as to display error message. Below code takes enters digits but doesnt validate to 10 digits. How to validate to 10 digit number.

Body:
you can use this

$(function() {
   $("#phno").bind("keydown", function (e) {
        if ((e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 96 && e.keyCode <= 105)) {
             // 0-9
            var val = $(this).val();
            if (!val.match(/^\d{9}$/))
            {
               console.log("it is a number but nut match 10 digit")
            }
            else
            {
               console.log("success");
               return false; // to restrict user to not enter more than 10 digit
            }
        }
        else
        {
           if(e.keyCode == 8)
              return true; // backspace
           alert("Please enter valid Student Phone No");
                event.preventDefault();
                return false;
        }
   });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='phno' />


问:
UnsupportedOperationException: Can't convert to dimension: type=0x1
In Android I got following Error in the emulator and some mobile device but not in Tablet:

I can't understand what is the error actually?

I have searched many tutorials but can't find any solution.

Please help me to solve this.

Note: In this application, I have used ActionbarSherlock and theme, may i got because of that library or any other problem?

My Error Log is:

```<code>09-11 17:52:57.342: E/AndroidRuntime(9935): FATAL EXCEPTION: main
09-11 17:52:57.342: E/AndroidRuntime(9935): android.view.InflateException: Binary XML file line #2: Error inflating class <unknown>
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.LayoutInflater.createView(LayoutInflater.java:613)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.LayoutInflater.onCreateView(LayoutInflater.java:660)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:685)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.LayoutInflater.inflate(LayoutInflater.java:466)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:371)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.widget.ArrayAdapter.getView(ArrayAdapter.java:362)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.widget.AbsSpinner.onMeasure(AbsSpinner.java:193)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.widget.Spinner.onMeasure(Spinner.java:439)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.View.measure(View.java:15518)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:681)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.View.measure(View.java:15518)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.widget.ScrollView.measureChildWithMargins(ScrollView.java:1217)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.widget.ScrollView.onMeasure(ScrollView.java:321)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.View.measure(View.java:15518)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.View.measure(View.java:15518)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.widget.LinearLayout.measureVertical(LinearLayout.java:847)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.View.measure(View.java:15518)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2176)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.View.measure(View.java:15518)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1874)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1089)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1265)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.Choreographer.doCallbacks(Choreographer.java:562)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.Choreographer.doFrame(Choreographer.java:532)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.os.Handler.handleCallback(Handler.java:725)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.os.Handler.dispatchMessage(Handler.java:92)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.os.Looper.loop(Looper.java:137)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.app.ActivityThread.main(ActivityThread.java:5041)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at java.lang.reflect.Method.invokeNative(Native Method)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at java.lang.reflect.Method.invoke(Method.java:511)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at dalvik.system.NativeStart.main(Native Method)
09-11 17:52:57.342: E/AndroidRuntime(9935): Caused by: java.lang.reflect.InvocationTargetException
09-11 17:52:57.342: E/AndroidRuntime(9935):     at java.lang.reflect.Constructor.constructNative(Native Method)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.LayoutInflater.createView(LayoutInflater.java:587)
09-11 17:52:57.342: E/AndroidRuntime(9935):     ... 45 more
09-11 17:52:57.342: E/AndroidRuntime(9935): Caused by: java.lang.UnsupportedOperationException: Can't convert to dimension: type=0x1
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.content.res.TypedArray.getDimensionPixelSize(TypedArray.java:463)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.widget.TextView.<init>(TextView.java:916)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.widget.TextView.<init>(TextView.java:578)
09-11 17:52:57.342: E/AndroidRuntime(9935):     ... 48 more
</code>```

My XML Layout file is:

```<code><?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:panel="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/activity_vertical_margin"
        android:layout_marginLeft="@dimen/other_activity_horizontal_margin"
        android:layout_marginRight="@dimen/other_activity_horizontal_margin"
        android:layout_marginTop="@dimen/activity_vertical_margin"
        android:orientation="vertical" >

        <EditText
            android:id="@+id/custDetailsNameEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:hint="@string/name_cust_all_add"
            android:inputType="textPersonName"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/custDetailsEmailEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/custDetailsNameEditText"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="15dp"
            android:hint="@string/email_cust_all_add"
            android:inputType="textEmailAddress"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <Spinner
            android:id="@+id/custDetailsDistributorSpinner"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/custDetailsEmailEditText"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="15dp"
            android:entries="@array/slide_menu_items"
            android:prompt="@string/select_distributor_prompt_add"
            android:spinnerMode="dialog" >
        </Spinner>

        <EditText
            android:id="@+id/custDetailsAddress1TitleEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/custDetailsDistributorSpinner"
            android:layout_marginTop="15dp"
            android:hint="@string/address_1_cust_all_add"
            android:inputType="textPostalAddress"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/custDetailsAddress2TitleEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/custDetailsAddress1TitleEditText"
            android:layout_marginTop="15dp"
            android:hint="@string/address_2_cust_all_add"
            android:inputType="textPostalAddress"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/custDetailsAddress3TitleEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/custDetailsAddress2TitleEditText"
            android:layout_marginTop="15dp"
            android:hint="@string/address_3_cust_all_add"
            android:inputType="textPostalAddress"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <Spinner
            android:id="@+id/custDetailsCompanyAreaSpinner"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/custDetailsAddress3TitleEditText"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="15dp"
            android:entries="@array/slide_menu_items"
            android:prompt="@string/select_company_area_prompt_add"
            android:spinnerMode="dialog"
            android:fastScrollEnabled="true"
            >
        </Spinner>

        <EditText
            android:id="@+id/custDetailsPincodeEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/custDetailsCompanyAreaSpinner"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="15dp"
            android:hint="@string/pincode_cust_all_add"
            android:inputType="number"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/custDetailsPhone1EditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/custDetailsPincodeEditText"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="15dp"
            android:hint="@string/phone_1_cust_all_add"
            android:inputType="phone"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/custDetailsPhone2EditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/custDetailsPhone1EditText"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="15dp"
            android:hint="@string/phone_2_cust_all_add"
            android:inputType="phone"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/custDetailsMobileNo1EditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/custDetailsPhone2EditText"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="15dp"
            android:hint="@string/mobile_no_1_cust_all_add"
            android:inputType="phone"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/custDetailsMobileNo2EditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/custDetailsMobileNo1EditText"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="15dp"
            android:hint="@string/mobile_no_2_cust_all_add"
            android:inputType="phone"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/custDetailsContactPerson1EditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/custDetailsMobileNo2EditText"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="15dp"
            android:hint="@string/contact_person_1_cust_all_add"
            android:inputType="text"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/custDetailsContactPerson2EditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/custDetailsContactPerson1EditText"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="15dp"
            android:hint="@string/contact_person_2_cust_all_add"
            android:inputType="text"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/custDetailsTinNoEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/custDetailsContactPerson2EditText"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="15dp"
            android:hint="@string/tin_no_cust_all_add"
            android:inputType="text"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/custDetailsCstNoEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/custDetailsTinNoEditText"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="15dp"
            android:hint="@string/cst_no_cust_all_add"
            android:inputType="text"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <RadioGroup
            android:id="@+id/custDetailsVTVRRadioGroup"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/custDetailsCstNoEditText"
            android:layout_marginTop="15dp"
            android:orientation="horizontal" >

            <TextView
                android:id="@+id/custDetailsVTVRLableTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/vt_vr_cust_all_add"
                android:textAppearance="?android:attr/textAppearanceMedium" />

            <RadioButton
                android:id="@+id/custDetailsVTRadioButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:checked="true"
                android:text="@string/vt_cust_all_add" />

            <RadioButton
                android:id="@+id/custDetailsVRRadioButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/vr_cust_all_add" />
        </RadioGroup>

        <RadioGroup
            android:id="@+id/custDetailsCFormRadioGroup"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/custDetailsVTVRRadioGroup"
            android:layout_marginTop="15dp"
            android:orientation="horizontal" >

            <TextView
                android:id="@+id/custDetailsCFormLableTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/c_form_cust_add_all"
                android:textAppearance="?android:attr/textAppearanceMedium" />

            <RadioButton
                android:id="@+id/custDetailsCFormYesRadioButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:checked="true"
                android:text="@string/yes_cust_add_all" />

            <RadioButton
                android:id="@+id/custDetailsCFormNoRadioButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/no_cust_add_all" />
        </RadioGroup>
    </RelativeLayout>

</ScrollView>
</code>```

styles.xml in values folder:

```<code><resources xmlns:android="http://schemas.android.com/apk/res/android">

    <!--
        Base application theme, dependent on API level. This theme is replaced
        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
    -->
    <style name="AppBaseTheme" parent="android:Theme.Light">
        <!--
            Theme customizations available in newer API levels can go in
            res/values-vXX/styles.xml, while customizations related to
            backward-compatibility can go here.
        -->
    </style>

    <style name="SlideBarTheme" parent="@style/Theme.Sherlock.NoActionBar">
        <item name="android:background">@drawable/slide_bg</item>
        <item name="android:cacheColorHint">@android:color/transparent</item>
        <item name="android:choiceMode">singleChoice</item>
    </style>

    <style name="ActivityTheme" parent="@style/Theme.Sherlock.Light">
        <item name="android:textColor">@color/activity_text</item>
        <item name="android:background">@color/activity_background</item>
    </style>

    <!-- For Widget -->

    <style name="MyAndroidTheme" parent="@style/Theme.Sherlock.Light.DarkActionBar">
        <item name="android:editTextStyle">@style/EditTextAppTheme</item>
        <item name="android:autoCompleteTextViewStyle">@style/AutoCompleteTextViewAppTheme</item>
        <item name="android:checkboxStyle">@style/CheckBoxAppTheme</item>
        <item name="android:spinnerStyle">@style/SpinnerAppTheme</item>
        <item name="android:dropDownSpinnerStyle">@style/SpinnerAppTheme.DropDown</item>
        <item name="android:spinnerDropDownItemStyle">@style/SpinnerDropDownItemAppTheme</item>
        <item name="android:listViewStyle">@style/ListViewAppTheme</item>
        <item name="android:listViewWhiteStyle">@style/ListViewAppTheme.White</item>
        <item name="android:spinnerItemStyle">@style/SpinnerItemAppTheme</item>
    </style>

</resources>
</code>```

styles.xml in values-11 folder:

```<code>    <resources>

    <!--
        Base application theme for API 11+. This theme completely replaces
        AppBaseTheme from res/values/styles.xml on API 11+ devices.
    -->

    <!-- API 11 theme customizations can go here. -->
    <style name="MyAndroidTheme" parent="android:Theme.Holo.Light.DarkActionBar">
        <item name="android:editTextBackground">@drawable/edit_text_holo_light</item>
        <item name="android:autoCompleteTextViewStyle">@style/AutoCompleteTextViewAppTheme</item>
        <item name="android:listChoiceIndicatorMultiple">@drawable/btn_check_holo_light</item>
        <item name="android:dropDownSpinnerStyle">@style/SpinnerAppTheme</item>
        <item name="android:listChoiceBackgroundIndicator">@drawable/list_selector_holo_light</item>
        <item name="android:activatedBackgroundIndicator">@drawable/activated_background_holo_light</item>
    </style>

</resources>
</code>```

styles.xml in values-14 folder:

```<code><resources>

    <!--
        Base application theme for API 14+. This theme completely replaces
        AppBaseTheme from BOTH res/values/styles.xml and
        res/values-v11/styles.xml on API 14+ devices.
    -->
    <style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">
        <!-- API 14 theme customizations can go here. -->
    </style>

</resources>
</code>```

And also I have a custom theme file:

In values folder named styles_apptheme.xml and styles_myactionbar.xml,
In values-v11 folder named styles_apptheme.xml,
In values-v14 folder named styles_myactionbar.xml

What should I change?

答:
just add in root    tools:ignore="ContentDescription"</p>

```<code> <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:ignore="ContentDescription" >
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In Android I got following Error in the emulator and some mobile device but not in Tablet:

I can't understand what is the error actually?

I have searched many tutorials but can't find any solution.

Please help me to solve this.

Note: In this application, I have used ActionbarSherlock and theme, may i got because of that library or any other problem?

My Error Log is:

09-11 17:52:57.342: E/AndroidRuntime(9935): FATAL EXCEPTION: main
09-11 17:52:57.342: E/AndroidRuntime(9935): android.view.InflateException: Binary XML file line #2: Error inflating class <unknown>
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.LayoutInflater.createView(LayoutInflater.java:613)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.LayoutInflater.onCreateView(LayoutInflater.java:660)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:685)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.LayoutInflater.inflate(LayoutInflater.java:466)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:371)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.widget.ArrayAdapter.getView(ArrayAdapter.java:362)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.widget.AbsSpinner.onMeasure(AbsSpinner.java:193)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.widget.Spinner.onMeasure(Spinner.java:439)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.View.measure(View.java:15518)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:681)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.View.measure(View.java:15518)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.widget.ScrollView.measureChildWithMargins(ScrollView.java:1217)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.widget.ScrollView.onMeasure(ScrollView.java:321)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.View.measure(View.java:15518)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.View.measure(View.java:15518)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.widget.LinearLayout.measureVertical(LinearLayout.java:847)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.View.measure(View.java:15518)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2176)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.View.measure(View.java:15518)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1874)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1089)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1265)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.Choreographer.doCallbacks(Choreographer.java:562)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.Choreographer.doFrame(Choreographer.java:532)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.os.Handler.handleCallback(Handler.java:725)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.os.Handler.dispatchMessage(Handler.java:92)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.os.Looper.loop(Looper.java:137)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.app.ActivityThread.main(ActivityThread.java:5041)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at java.lang.reflect.Method.invokeNative(Native Method)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at java.lang.reflect.Method.invoke(Method.java:511)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at dalvik.system.NativeStart.main(Native Method)
09-11 17:52:57.342: E/AndroidRuntime(9935): Caused by: java.lang.reflect.InvocationTargetException
09-11 17:52:57.342: E/AndroidRuntime(9935):     at java.lang.reflect.Constructor.constructNative(Native Method)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.view.LayoutInflater.createView(LayoutInflater.java:587)
09-11 17:52:57.342: E/AndroidRuntime(9935):     ... 45 more
09-11 17:52:57.342: E/AndroidRuntime(9935): Caused by: java.lang.UnsupportedOperationException: Can't convert to dimension: type=0x1
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.content.res.TypedArray.getDimensionPixelSize(TypedArray.java:463)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.widget.TextView.<init>(TextView.java:916)
09-11 17:52:57.342: E/AndroidRuntime(9935):     at android.widget.TextView.<init>(TextView.java:578)
09-11 17:52:57.342: E/AndroidRuntime(9935):     ... 48 more

My XML Layout file is:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:panel="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/activity_vertical_margin"
        android:layout_marginLeft="@dimen/other_activity_horizontal_margin"
        android:layout_marginRight="@dimen/other_activity_horizontal_margin"
        android:layout_marginTop="@dimen/activity_vertical_margin"
        android:orientation="vertical" >

        <EditText
            android:id="@+id/custDetailsNameEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:hint="@string/name_cust_all_add"
            android:inputType="textPersonName"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/custDetailsEmailEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/custDetailsNameEditText"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="15dp"
            android:hint="@string/email_cust_all_add"
            android:inputType="textEmailAddress"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <Spinner
            android:id="@+id/custDetailsDistributorSpinner"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/custDetailsEmailEditText"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="15dp"
            android:entries="@array/slide_menu_items"
            android:prompt="@string/select_distributor_prompt_add"
            android:spinnerMode="dialog" >
        </Spinner>

        <EditText
            android:id="@+id/custDetailsAddress1TitleEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/custDetailsDistributorSpinner"
            android:layout_marginTop="15dp"
            android:hint="@string/address_1_cust_all_add"
            android:inputType="textPostalAddress"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/custDetailsAddress2TitleEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/custDetailsAddress1TitleEditText"
            android:layout_marginTop="15dp"
            android:hint="@string/address_2_cust_all_add"
            android:inputType="textPostalAddress"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/custDetailsAddress3TitleEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/custDetailsAddress2TitleEditText"
            android:layout_marginTop="15dp"
            android:hint="@string/address_3_cust_all_add"
            android:inputType="textPostalAddress"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <Spinner
            android:id="@+id/custDetailsCompanyAreaSpinner"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/custDetailsAddress3TitleEditText"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="15dp"
            android:entries="@array/slide_menu_items"
            android:prompt="@string/select_company_area_prompt_add"
            android:spinnerMode="dialog"
            android:fastScrollEnabled="true"
            >
        </Spinner>

        <EditText
            android:id="@+id/custDetailsPincodeEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/custDetailsCompanyAreaSpinner"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="15dp"
            android:hint="@string/pincode_cust_all_add"
            android:inputType="number"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/custDetailsPhone1EditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/custDetailsPincodeEditText"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="15dp"
            android:hint="@string/phone_1_cust_all_add"
            android:inputType="phone"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/custDetailsPhone2EditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/custDetailsPhone1EditText"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="15dp"
            android:hint="@string/phone_2_cust_all_add"
            android:inputType="phone"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/custDetailsMobileNo1EditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/custDetailsPhone2EditText"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="15dp"
            android:hint="@string/mobile_no_1_cust_all_add"
            android:inputType="phone"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/custDetailsMobileNo2EditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/custDetailsMobileNo1EditText"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="15dp"
            android:hint="@string/mobile_no_2_cust_all_add"
            android:inputType="phone"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/custDetailsContactPerson1EditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/custDetailsMobileNo2EditText"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="15dp"
            android:hint="@string/contact_person_1_cust_all_add"
            android:inputType="text"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/custDetailsContactPerson2EditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/custDetailsContactPerson1EditText"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="15dp"
            android:hint="@string/contact_person_2_cust_all_add"
            android:inputType="text"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/custDetailsTinNoEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/custDetailsContactPerson2EditText"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="15dp"
            android:hint="@string/tin_no_cust_all_add"
            android:inputType="text"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/custDetailsCstNoEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/custDetailsTinNoEditText"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="15dp"
            android:hint="@string/cst_no_cust_all_add"
            android:inputType="text"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <RadioGroup
            android:id="@+id/custDetailsVTVRRadioGroup"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/custDetailsCstNoEditText"
            android:layout_marginTop="15dp"
            android:orientation="horizontal" >

            <TextView
                android:id="@+id/custDetailsVTVRLableTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/vt_vr_cust_all_add"
                android:textAppearance="?android:attr/textAppearanceMedium" />

            <RadioButton
                android:id="@+id/custDetailsVTRadioButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:checked="true"
                android:text="@string/vt_cust_all_add" />

            <RadioButton
                android:id="@+id/custDetailsVRRadioButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/vr_cust_all_add" />
        </RadioGroup>

        <RadioGroup
            android:id="@+id/custDetailsCFormRadioGroup"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/custDetailsVTVRRadioGroup"
            android:layout_marginTop="15dp"
            android:orientation="horizontal" >

            <TextView
                android:id="@+id/custDetailsCFormLableTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/c_form_cust_add_all"
                android:textAppearance="?android:attr/textAppearanceMedium" />

            <RadioButton
                android:id="@+id/custDetailsCFormYesRadioButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:checked="true"
                android:text="@string/yes_cust_add_all" />

            <RadioButton
                android:id="@+id/custDetailsCFormNoRadioButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/no_cust_add_all" />
        </RadioGroup>
    </RelativeLayout>

</ScrollView>

styles.xml in values folder:

<resources xmlns:android="http://schemas.android.com/apk/res/android">

</resources>

styles.xml in values-11 folder:

    <resources>

</resources>

styles.xml in values-14 folder:

<resources>

</resources>

And also I have a custom theme file:

In values folder named styles_apptheme.xml and styles_myactionbar.xml,
In values-v11 folder named styles_apptheme.xml,
In values-v14 folder named styles_myactionbar.xml

What should I change?

Body:
just add in root    tools:ignore="ContentDescription"

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:ignore="ContentDescription" >


问:
how to edit comment within article's page - keep getting error about nil
I have typical article and comment blog format. It's a typical has_many/belongs_to, ie, the Guide's blog type.

However, I'm trying to edit the comment within the article, and I'm clueless about building the right form for this.

It's also in a partial which makes it more complicated for me.

Any help and/or educating me would be appreciated.

Comment's model

```<code>class Comment < ApplicationRecord
  belongs_to :article
end
</code>```

Article's model

```<code>class Article < ApplicationRecord

    has_many :comments

    validates :title, presence: true, length: { minimum: 5}

end
</code>```

Article's Show page

```<code><p>
  <strong>Title:</strong>
  <%= @article.title %>
</p>

<p>
  <strong>Text:</strong>
  <%= @article.text %>
</p>

<h2>Comments</h2>
<%= render @article.comments %>

<h2>Add a comment:</h2>
<%= render 'comments/form' %>

<%= link_to 'Edit', edit_article_path(@article) %> |
<%= link_to 'Back', articles_path %>
</code>```

Comment's _comment.html.erb page

```<code><p>
  <strong>Commenter:</strong>
  <%= comment.commenter %>
</p>

<p>
  <strong>Comment:</strong>
  <%= comment.body %>
</p>

<p>
  <%= link_to 'Destroy Comment', [comment.article, comment],
               method: :delete,
               data: { confirm: 'Are you sure?' } %>
</p>

<p>
    <%= link_to 'Edit', edit_article_comment_path(@article, comment) %>
</p>
</code>```

Comment's _form.html

```<code><%= form_for([@article, @comment]) do |f| %>
  <p>
    <%= f.label :commenter %><br>
    <%= f.text_field :commenter %>
  </p>
  <p>
    <%= f.label :body %><br>
    <%= f.text_area :body %>
  </p>
  <p>
    <%= f.submit %>
  </p>
<% end %>
</code>```

Error

It comes from Comment's _form.html.erb page in reference to this line: <%= form_for([@article, @comment]) do |f| %> ... and the error is: First argument in form cannot contain nil or be empty ...

Articles Controller

```<code>class ArticlesController < ApplicationController

    def index
        @articles = Article.all
    end

    def new
        @article = Article.new
    end

    def edit
        @article = Article.find(params[:id])
    end

    def create
        #render plain: params[:article].inspect
        #@article = Article.new(params[:article])
        #@article = Article.new(params.require(:article).permit(:title, :text))
        @article = Article.new(article_params)

        if @article.save
            redirect_to @article
        else
            render 'new'
        end
    end

    def update
        @article = Article.find(params[:id])

        if @article.update(article_params)
            redirect_to @article
        else
            render 'edit'
        end
    end

    def show
        @article = Article.find(params[:id])
    end

    def destroy
        @article = Article.find(params[:id])
        @article.destroy

        redirect_to articles_path
    end

    private
        def article_params
            params.require(:article).permit(:title, :text)
        end

end
</code>```

Comments Controller

```<code>class CommentsController < ApplicationController
  def create
    @article = Article.find(params[:article_id])
    @comment = @article.comments.create(comment_params)
    redirect_to article_path(@article)
  end

  def destroy
    @article = Article.find(params[:article_id])
    @comment = @article.comments.find(params[:id])
    @comment.destroy
    redirect_to article_path(@article)
  end

  private
    def comment_params
      params.require(:comment).permit(:commenter, :body)
    end
end
</code>```

答:
First argument in form cannot contain nil or be empty

The error is due to @article and @comment being nil in the form. Since you are rendering the form with a partial, you need send variables to the partial as well

Change <%= render 'comments/form' %> to <%= render 'comments/form', article: @article, comment: @comment %>

and in the form have this <%= form_for([article, comment]) do |f| %>

Also in the show method of articles controller, you should define @comment

```<code>def show
  @article = Article.find(params[:id])
  @comment = Comment.new
end
</code>```

Body:
I have typical article and comment blog format. It's a typical has_many/belongs_to, ie, the Guide's blog type.

However, I'm trying to edit the comment within the article, and I'm clueless about building the right form for this.

It's also in a partial which makes it more complicated for me.

Any help and/or educating me would be appreciated.

Comment's model

class Comment < ApplicationRecord
  belongs_to :article
end

Article's model

class Article < ApplicationRecord

    has_many :comments

    validates :title, presence: true, length: { minimum: 5}

end

Article's Show page

  Title:
  <%= @article.title %>

  Text:
  <%= @article.text %>

Comments

<%= render @article.comments %>

Add a comment:

<%= render 'comments/form' %>

<%= link_to 'Edit', edit_article_path(@article) %> |
<%= link_to 'Back', articles_path %>

Comment's _comment.html.erb page

  Commenter:
  <%= comment.commenter %>

  Comment:
  <%= comment.body %>

  <%= link_to 'Destroy Comment', [comment.article, comment],
               method: :delete,
               data: { confirm: 'Are you sure?' } %>

    <%= link_to 'Edit', edit_article_comment_path(@article, comment) %>

Comment's _form.html

<%= form_for([@article, @comment]) do |f| %>

    <%= f.label :commenter %>

    <%= f.text_field :commenter %>

    <%= f.label :body %>

    <%= f.text_area :body %>

    <%= f.submit %>

<% end %>

Error

It comes from Comment's _form.html.erb page in reference to this line: <%= form_for([@article, @comment]) do |f| %> ... and the error is: First argument in form cannot contain nil or be empty ...

Articles Controller

class ArticlesController < ApplicationController

    def index
        @articles = Article.all
    end

    def new
        @article = Article.new
    end

    def edit
        @article = Article.find(params[:id])
    end

    def create
        #render plain: params[:article].inspect
        #@article = Article.new(params[:article])
        #@article = Article.new(params.require(:article).permit(:title, :text))
        @article = Article.new(article_params)

        if @article.save
            redirect_to @article
        else
            render 'new'
        end
    end

    def update
        @article = Article.find(params[:id])

        if @article.update(article_params)
            redirect_to @article
        else
            render 'edit'
        end
    end

    def show
        @article = Article.find(params[:id])
    end

    def destroy
        @article = Article.find(params[:id])
        @article.destroy

        redirect_to articles_path
    end

    private
        def article_params
            params.require(:article).permit(:title, :text)
        end

end

Comments Controller

class CommentsController < ApplicationController
  def create
    @article = Article.find(params[:article_id])
    @comment = @article.comments.create(comment_params)
    redirect_to article_path(@article)
  end

  def destroy
    @article = Article.find(params[:article_id])
    @comment = @article.comments.find(params[:id])
    @comment.destroy
    redirect_to article_path(@article)
  end

  private
    def comment_params
      params.require(:comment).permit(:commenter, :body)
    end
end

Body:
First argument in form cannot contain nil or be empty

The error is due to @article and @comment being nil in the form. Since you are rendering the form with a partial, you need send variables to the partial as well

Change <%= render 'comments/form' %> to <%= render 'comments/form', article: @article, comment: @comment %>

and in the form have this <%= form_for([article, comment]) do |f| %>

Also in the show method of articles controller, you should define @comment

def show
  @article = Article.find(params[:id])
  @comment = Comment.new
end


问:
modern events calendar excerpt
is there any way to add characters/words for this wordpress plug-in?
http://webnus.co/plugins/modern-events-calendar/list-view-standard-style/

I would like it to have 3 sentences as the summary.

答: Solved by using the wordpress default excerpt</p>

Title: modern events calendar excerpt