问:
Redux-way in the real life
I want to ask the community about an ideological problem.
Lets imagine todo-list on react/redux, you have single state where todoItems array is served. But now lets imagine I want to have few components on the page that are render todoItems with different UI. And I need to update each these components on CRUD of todoItems. What is your architectural approach of this issue? Don't forget we have a large database and we can get todoItems with pagination only.

Update:

Lets make it clear. When we implement redux life cycle with this UI we have 2 options:

1) Serve one array of todoItems into singleton redux state object.
Advantages: all our components will updates by object changing.
Problems: we can't get ALL data from our database, but have to show different paginated/filtered data, so we can't implement pagination/filtering on frontend-side. We have a few different components and the have to render different objects collection. So it doesn't fit.

2) We can use different keys into our global redux state.
Advantages: we can independently get data for each component
Problems: other components will not feel when object changing in one of them. In this case we have to write custom code.

I just want to know maybe I'm missing something and we have other option or maybe someone have good architectural approach to this problem.

答:
I bet your complications come from the point of view which unfortunately quite common among redux community: trying to keep redux shape as close to UI shape as possible.

Try no to think about redux state as a substitute for the Component states. What redux should know about is actual todos only (id, title, date of creation, etc.). Let Component-specific data like pagination stuff live in Components state. When user goes to next page in one of the Components what should be updated is this Component state (pageNumber, from, to, amount, etc.). redux should be updated only in case necessary todos are missing.

The useful analogy is to thinking about your redux as good old SQL-database: redux store state is data itself, selectors and actions are queries and stored procedures, React Components are views with selected data.

Update: Ok, seems like what you are looking for is state normalization. Separate todos details from the lists of ids. This way updates of todo fields will be sensed by all the Components. On the other hand you'll be able to keep separate collections of todos in different Components. Namely make state look like this:

```<code>{
   funnyTodos: [ 'id1', 'id2' ],
   boringTodos: [ 'id3', 'id4' ],
   recentlyDoneTodos: [ 'id1' ],
   todos: {
     id1: { name: .... },
     id2: { name: .... },
     id3: { name: .... },
     id4: { name: .... },
   }
}
</code>```

Implementing pagination in this case is just a matter of getting list of todos ids for the next page from back-end and then loading missing todos for given ids.

Title: Redux-way in the real life

Body:
I bet your complications come from the point of view which unfortunately quite common among redux community: trying to keep redux shape as close to UI shape as possible.

Try no to think about redux state as a substitute for the Component states. What redux should know about is actual todos only (id, title, date of creation, etc.). Let Component-specific data like pagination stuff live in Components state. When user goes to next page in one of the Components what should be updated is this Component state (pageNumber, from, to, amount, etc.). redux should be updated only in case necessary todos are missing.

The useful analogy is to thinking about your redux as good old SQL-database: redux store state is data itself, selectors and actions are queries and stored procedures, React Components are views with selected data.

Update: Ok, seems like what you are looking for is state normalization. Separate todos details from the lists of ids. This way updates of todo fields will be sensed by all the Components. On the other hand you'll be able to keep separate collections of todos in different Components. Namely make state look like this:

{
   funnyTodos: [ 'id1', 'id2' ],
   boringTodos: [ 'id3', 'id4' ],
   recentlyDoneTodos: [ 'id1' ],
   todos: {
     id1: { name: .... },
     id2: { name: .... },
     id3: { name: .... },
     id4: { name: .... },
   }
}

Implementing pagination in this case is just a matter of getting list of todos ids for the next page from back-end and then loading missing todos for given ids.


来源: stackexchange

问:
Put file on HDFS with spaces in name
I have a file named file name(1).zip (with the space and parentheses in it) and I want to put this file on the HDFS. But everytime I try to put it via hadoop fs -put ... , I get a an exception.

I have even tried to add quotes around the file and even tried to escape the space and parentheses but it doesn't work.

```<code>hduser@localhost:/tmp$ hadoop fs -put file\ name\(1\).zip /tmp/one
15/06/05 15:57:46 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
put: unexpected URISyntaxException

hduser@localhost:/tmp$ hadoop fs -put "file\ name\(1\).zip" /tmp/one/
15/06/05 15:59:19 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
put: unexpected URISyntaxException

hduser@localhost:/tmp$ hadoop fs -put "file name(1).zip" /tmp/one/
15/06/05 16:00:36 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
put: unexpected URISyntaxException
</code>```

Is there any work-around to put such files on the HDFS or am I missing something here.

答:
HDFS is totally fine with spaces in the file or directory names.

It is the hdfs that does not support putting a file from local disk with spaces in its file name. But there is a trick to achieve this ( reference ):

```<code>cat file\ name\(1\).zip | hadoop fs -put - "/tmp/one/file name(1).zip"
</code>```

Hope this helps those that need this.

ContentLicense: CC BY-SA 3.0

Title: Put file on HDFS with spaces in name

Body:
I have a file named file name(1).zip (with the space and parentheses in it) and I want to put this file on the HDFS. But everytime I try to put it via hadoop fs -put ... , I get a an exception.

I have even tried to add quotes around the file and even tried to escape the space and parentheses but it doesn't work.

hduser@localhost:/tmp$ hadoop fs -put file\ name\(1\).zip /tmp/one
15/06/05 15:57:46 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
put: unexpected URISyntaxException

hduser@localhost:/tmp$ hadoop fs -put "file\ name\(1\).zip" /tmp/one/
15/06/05 15:59:19 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
put: unexpected URISyntaxException

hduser@localhost:/tmp$ hadoop fs -put "file name(1).zip" /tmp/one/
15/06/05 16:00:36 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
put: unexpected URISyntaxException

Is there any work-around to put such files on the HDFS or am I missing something here.

Body:
HDFS is totally fine with spaces in the file or directory names.

It is the hdfs that does not support putting a file from local disk with spaces in its file name. But there is a trick to achieve this ( reference ):

cat file\ name\(1\).zip | hadoop fs -put - "/tmp/one/file name(1).zip"

Hope this helps those that need this.


问:
What is the best way to debug stored procedures (and write sprocs that are easier to debug)?
What are good methodologies for creating sprocs that reduce the pain of debugging? And what tools are out there for debugging stored procedures?

Perhaps most importantly, what are indications to look out for that errors are happening in a sproc and not in the code? I hope I'm not all over the board too terribly bad here. Votes for answers to any of the above. Thanks.

For what it's worth, I work in a .NET environment, SQL servers.

答:
I would strongly suggest that you take a look at the built in tooling in SQL management studio.

i have written a pretty detailed blog post about it here:

http://www.diaryofaninja.com/blog/2010/11/23/debugging-sql-queries-function-amp-stored-procedures-with-sql-management-studio

basically the gist of it is that you enter you sql query to execute your stored procedure, and instead of pressing F5 or hitting the exclamation, you hit the play button and use F10 and F11 to step through and step into your stored procs.

very very handy - and no one seems to use it.

OwnerDisplayName: Thohan

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Torsten Marek


问:
Does BigDecimal#min method qualify as a BinaryOperator?
The Stream.reduce method takes a BinaryOperator as an argument. The function signature of a BinaryOperator is (T,T) -> T. The BigDecimal::min method has only 1 parameter in its method signature (ie. (T) -> T ).

Why doesn't the compiler complain when I pass BigDecimal::min to the Stream.reduce method?

Sample code:

```<code>List<BigDecimal> bigDecimalList = new ArrayList<>();
        bigDecimalList.add(BigDecimal.valueOf(1));
        bigDecimalList.add(BigDecimal.valueOf(2));
        bigDecimalList.add(BigDecimal.valueOf(3));
BigDecimal minResult = bigDecimalList.stream().reduce(BigDecimal::min).orElse(BigDecimal.ZERO);
</code>```

Thanks.

答:
This is actually called Reference to an instance method of an arbitrary object of a particular type.

The compiler takes the calling instance as the first argument and as such these are equivalent:

```<code>    BinaryOperator<BigDecimal> b = (left, right) -> left.min(right);

    BinaryOperator<BigDecimal> b2 = BigDecimal::min;
    b2.apply(left, right);
</code>```

Things are much funner IMO when you have something like this:

```<code>@FunctionalInterface
interface TriFunction<A, B, C, R> {

    R apply(A a, B b, C c);

}
</code>```

and a theoretical class:

```<code>class Test {

    int x;

    int y;

    public Test(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public Test copy(int n, int m) {
        return new Test(m, n);
    }
}
</code>```

Then you could write something like this:

```<code>  TriFunction<Test, Integer, Integer, Test> f = Test::copy;

  TriFunction<Test, Integer, Integer, Test> f2 =
           (test, i, j) -> test.copy(i, j);
</code>```

Body:
The Stream.reduce method takes a BinaryOperator as an argument. The function signature of a BinaryOperator is (T,T) -> T. The BigDecimal::min method has only 1 parameter in its method signature (ie. (T) -> T ).

Why doesn't the compiler complain when I pass BigDecimal::min to the Stream.reduce method?

Sample code:

List<BigDecimal> bigDecimalList = new ArrayList<>();
        bigDecimalList.add(BigDecimal.valueOf(1));
        bigDecimalList.add(BigDecimal.valueOf(2));
        bigDecimalList.add(BigDecimal.valueOf(3));
BigDecimal minResult = bigDecimalList.stream().reduce(BigDecimal::min).orElse(BigDecimal.ZERO);

Thanks.

Body:
This is actually called Reference to an instance method of an arbitrary object of a particular type.

The compiler takes the calling instance as the first argument and as such these are equivalent:

    BinaryOperator<BigDecimal> b = (left, right) -> left.min(right);

    BinaryOperator<BigDecimal> b2 = BigDecimal::min;
    b2.apply(left, right);

Things are much funner IMO when you have something like this:

@FunctionalInterface
interface TriFunction<A, B, C, R> {

    R apply(A a, B b, C c);

}

and a theoretical class:

class Test {

    int x;

    int y;

    public Test(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public Test copy(int n, int m) {
        return new Test(m, n);
    }
}

Then you could write something like this:

  TriFunction<Test, Integer, Integer, Test> f = Test::copy;

  TriFunction<Test, Integer, Integer, Test> f2 =
           (test, i, j) -> test.copy(i, j);


问:
Find Element by Coordinates in Selenium (WebDriver)
I'm aware how to retrieve the coordinates of a web element in Selenium:

```<code>WebElement element = driver.findElement(By.xpath(XPath));
Point location = element.getLocation();
location.x + " " + location.y
</code>```

However I'm trying to do the opposite - locate a web element using its coordinates.

I understand I could find all elements on a web page, loop through the list of elements, get the x,y coordinates of each element in the list and compare it to the expected coordinates. If both x and y coordinates of an element match the expected web element I could return the given web element. However it seems very inefficient to me to need to loop through every web element on a page to find the one matching element.

Is there a more of a direct way of finding an element by coordinates?

Note: Although a similar question has been asked over here: Get element at specified position - JavaScript - my question is different bec I want to be able to do this directly using Selenium without the need to come onto Javscript.

答:
The only possible way is by checking the coordinates against all possible elements (if you don 't know nothing about the element you are looking for, Eg. the tag)

So use findElements like driver.findElements(By.cssSelector("*")) OR driver.findElements(By.xpath("//*")) then for each of the found elements check if their location x , y is the ones you are trying to match and return the element if any.

OR call the js elementFromPoint trough the driver as described here :)

Body:
I'm aware how to retrieve the coordinates of a web element in Selenium:

WebElement element = driver.findElement(By.xpath(XPath));
Point location = element.getLocation();
location.x + " " + location.y

However I'm trying to do the opposite - locate a web element using its coordinates.

I understand I could find all elements on a web page, loop through the list of elements, get the x,y coordinates of each element in the list and compare it to the expected coordinates. If both x and y coordinates of an element match the expected web element I could return the given web element. However it seems very inefficient to me to need to loop through every web element on a page to find the one matching element.

Is there a more of a direct way of finding an element by coordinates?

Note: Although a similar question has been asked over here: Get element at specified position - JavaScript - my question is different bec I want to be able to do this directly using Selenium without the need to come onto Javscript.


问:
How to add "-l" (ell) compiler flag in CMake
Work on Ubuntu 16

I used g++ main.cpp -lpq command for compiler my small project. Now I use Clion and wanna do same what I do with g++. But I can't add compiler flags in cmake file and get compile error.

cmake_minimum_required(VERSION 3.5.1)
project(day_g)

set(CMAKE_CXX_FLAGS "-lpq")

add_definitions(-lpq)

message("CMAKE_CXX_FLAGS is ${CMAKE_CXX_FLAGS}")

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES main.cpp)
add_executable(day_g ${SOURCE_FILES})
```

<p>Also I run only cmake file and get <code>CMAKE_CXX_FLAGS</code> with <em>-lpq</em> flag.</p>

<pre class="lang-js prettyprint-override"><code>CMAKE_CXX_FLAGS is -lpq
-- Configuring done
-- Generating done
</code>```

How properly add compiler flags to cmake file?

答:
Flag -l is for linker, not for compiler. This flag is used for link with libraries. CMake has special command target_link_libraries for that purpose:

```<code>target_link_libraries(day_g pq)
</code>```

Body:
Work on Ubuntu 16

I used g++ main.cpp -lpq command for compiler my small project. Now I use Clion and wanna do same what I do with g++. But I can't add compiler flags in cmake file and get compile error.

cmake_minimum_required(VERSION 3.5.1)
project(day_g)

set(CMAKE_CXX_FLAGS "-lpq")

add_definitions(-lpq)

message("CMAKE_CXX_FLAGS is ${CMAKE_CXX_FLAGS}")

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES main.cpp)
add_executable(day_g ${SOURCE_FILES})

Also I run only cmake file and get CMAKE_CXX_FLAGS with -lpq flag.

CMAKE_CXX_FLAGS is -lpq
-- Configuring done
-- Generating done

How properly add compiler flags to cmake file?

Body:
Flag -l is for linker, not for compiler. This flag is used for link with libraries. CMake has special command target_link_libraries for that purpose:

target_link_libraries(day_g pq)


问:
Android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0-s
I got this Error while using SQLite DATABASE.

```<code>07-16 17:45:13.106: E/AndroidRuntime(7703): Caused by:
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
</code>```

I'm Using SQLite Database to Store Book Objects in it.

```<code>public class MySQLiteHelper extends SQLiteOpenHelper {

    // Database Version
    private static final int DATABASE_VERSION = 1;
    // Database Name
    private static final String DATABASE_NAME = "BookDB";

    public MySQLiteHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // SQL statement to create book table
        String CREATE_BOOK_TABLE = "CREATE TABLE books ( " +
                "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                "title TEXT, "+
                "author TEXT )";

        // create books table
        db.execSQL(CREATE_BOOK_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older books table if existed
        db.execSQL("DROP TABLE IF EXISTS books");

        // create fresh books table
        this.onCreate(db);
    }
    //---------------------------------------------------------------------

    /**
     * CRUD operations (create "add", read "get", update, delete) book + get all books + delete all books
     */

    // Books table name
    private static final String TABLE_BOOKS = "books";

    // Books Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_TITLE = "title";
    private static final String KEY_AUTHOR = "author";

    private static final String[] COLUMNS = {KEY_ID,KEY_TITLE,KEY_AUTHOR};

    public void addBook(Book book){
        Log.d("addBook", book.toString());
        // 1. get reference to writable DB
        SQLiteDatabase db = this.getWritableDatabase();

        // 2. create ContentValues to add key "column"/value
        ContentValues values = new ContentValues();
        values.put(KEY_TITLE, book.getTitle()); // get title
        values.put(KEY_AUTHOR, book.getAuthor()); // get author

        // 3. insert
        db.insert(TABLE_BOOKS, // table
                null, //nullColumnHack
                values); // key/value -> keys = column names/ values = column values

        // 4. close
        db.close();
    }

    public Book getBook(int id){

        // 1. get reference to readable DB
        SQLiteDatabase db = this.getReadableDatabase();

        // 2. build query
        Cursor cursor =
                db.query(TABLE_BOOKS, // a. table
                COLUMNS, // b. column names
                " id = ?", // c. selections
                new String[] { String.valueOf(id) }, // d. selections args
                null, // e. group by
                null, // f. having
                null, // g. order by
                null); // h. limit

        // 3. if we got results get the first one
        if (cursor != null)
            cursor.moveToFirst();

        // 4. build book object
        Book book = new Book();
        book.setId(Integer.parseInt(cursor.getString(0)));
        book.setTitle(cursor.getString(1));
        book.setAuthor(cursor.getString(2));

        Log.d("getBook("+id+")", book.toString());

        // 5. return book
        return book;
    }

    // Get All Books
    public List<Book> getAllBooks() {
        List<Book> books = new LinkedList<Book>();

        // 1. build the query
        String query = "SELECT  * FROM " + TABLE_BOOKS;

        // 2. get reference to writable DB
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(query, null);

        // 3. go over each row, build book and add it to list
        Book book = null;
        if (cursor.moveToFirst()) {
            do {
                book = new Book();
                book.setId(Integer.parseInt(cursor.getString(0)));
                book.setTitle(cursor.getString(1));
                book.setAuthor(cursor.getString(2));

                // Add book to books
                books.add(book);
            } while (cursor.moveToNext());
        }

        Log.d("getAllBooks()", books.toString());

        // return books
        return books;
    }

     // Updating single book
    public int updateBook(Book book) {

        // 1. get reference to writable DB
        SQLiteDatabase db = this.getWritableDatabase();

        // 2. create ContentValues to add key "column"/value
        ContentValues values = new ContentValues();
        values.put("title", book.getTitle()); // get title
        values.put("author", book.getAuthor()); // get author

        // 3. updating row
        int i = db.update(TABLE_BOOKS, //table
                values, // column/value
                KEY_ID+" = ?", // selections
                new String[] { String.valueOf(book.getId()) }); //selection args

        // 4. close
        db.close();

        return i;

    }

    // Deleting single book
    public void deleteBook(Book book) {

        // 1. get reference to writable DB
        SQLiteDatabase db = this.getWritableDatabase();

        // 2. delete
        db.delete(TABLE_BOOKS,
                KEY_ID+" = ?",
                new String[] { String.valueOf(book.getId()) });

        // 3. close
        db.close();

        Log.d("deleteBook", book.toString());

    }
}
</code>```

答:
JUst try below code for single Condition you have to first check cursor is not null then after move to start position don't forgot to close it after work is done

```<code>Cursor cursor = db.query(...);if (cursor != null) {
if (cursor.moveToFirst()) {
    //do your stuff
}
cursor.close();
</code>```

}

Now if you want check for multiple columns just replace while condition insted of if
Thanks

Body:
I got this Error while using SQLite DATABASE.

07-16 17:45:13.106: E/AndroidRuntime(7703): Caused by:
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0

I'm Using SQLite Database to Store Book Objects in it.

public class MySQLiteHelper extends SQLiteOpenHelper {

    // Database Version
    private static final int DATABASE_VERSION = 1;
    // Database Name
    private static final String DATABASE_NAME = "BookDB";

    public MySQLiteHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // SQL statement to create book table
        String CREATE_BOOK_TABLE = "CREATE TABLE books ( " +
                "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                "title TEXT, "+
                "author TEXT )";

        // create books table
        db.execSQL(CREATE_BOOK_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older books table if existed
        db.execSQL("DROP TABLE IF EXISTS books");

        // create fresh books table
        this.onCreate(db);
    }
    //---------------------------------------------------------------------

    /**
     * CRUD operations (create "add", read "get", update, delete) book + get all books + delete all books
     */

    // Books table name
    private static final String TABLE_BOOKS = "books";

    // Books Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_TITLE = "title";
    private static final String KEY_AUTHOR = "author";

    private static final String[] COLUMNS = {KEY_ID,KEY_TITLE,KEY_AUTHOR};

    public void addBook(Book book){
        Log.d("addBook", book.toString());
        // 1. get reference to writable DB
        SQLiteDatabase db = this.getWritableDatabase();

        // 2. create ContentValues to add key "column"/value
        ContentValues values = new ContentValues();
        values.put(KEY_TITLE, book.getTitle()); // get title
        values.put(KEY_AUTHOR, book.getAuthor()); // get author

        // 3. insert
        db.insert(TABLE_BOOKS, // table
                null, //nullColumnHack
                values); // key/value -> keys = column names/ values = column values

        // 4. close
        db.close();
    }

    public Book getBook(int id){

        // 1. get reference to readable DB
        SQLiteDatabase db = this.getReadableDatabase();

        // 2. build query
        Cursor cursor =
                db.query(TABLE_BOOKS, // a. table
                COLUMNS, // b. column names
                " id = ?", // c. selections
                new String[] { String.valueOf(id) }, // d. selections args
                null, // e. group by
                null, // f. having
                null, // g. order by
                null); // h. limit

        // 3. if we got results get the first one
        if (cursor != null)
            cursor.moveToFirst();

        // 4. build book object
        Book book = new Book();
        book.setId(Integer.parseInt(cursor.getString(0)));
        book.setTitle(cursor.getString(1));
        book.setAuthor(cursor.getString(2));

        Log.d("getBook("+id+")", book.toString());

        // 5. return book
        return book;
    }

    // Get All Books
    public List<Book> getAllBooks() {
        List<Book> books = new LinkedList<Book>();

        // 1. build the query
        String query = "SELECT  * FROM " + TABLE_BOOKS;

        // 2. get reference to writable DB
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(query, null);

        // 3. go over each row, build book and add it to list
        Book book = null;
        if (cursor.moveToFirst()) {
            do {
                book = new Book();
                book.setId(Integer.parseInt(cursor.getString(0)));
                book.setTitle(cursor.getString(1));
                book.setAuthor(cursor.getString(2));

                // Add book to books
                books.add(book);
            } while (cursor.moveToNext());
        }

        Log.d("getAllBooks()", books.toString());

        // return books
        return books;
    }

     // Updating single book
    public int updateBook(Book book) {

        // 1. get reference to writable DB
        SQLiteDatabase db = this.getWritableDatabase();

        // 2. create ContentValues to add key "column"/value
        ContentValues values = new ContentValues();
        values.put("title", book.getTitle()); // get title
        values.put("author", book.getAuthor()); // get author

        // 3. updating row
        int i = db.update(TABLE_BOOKS, //table
                values, // column/value
                KEY_ID+" = ?", // selections
                new String[] { String.valueOf(book.getId()) }); //selection args

        // 4. close
        db.close();

        return i;

    }

    // Deleting single book
    public void deleteBook(Book book) {

        // 1. get reference to writable DB
        SQLiteDatabase db = this.getWritableDatabase();

        // 2. delete
        db.delete(TABLE_BOOKS,
                KEY_ID+" = ?",
                new String[] { String.valueOf(book.getId()) });

        // 3. close
        db.close();

        Log.d("deleteBook", book.toString());

    }
}

Body:
JUst try below code for single Condition you have to first check cursor is not null then after move to start position don't forgot to close it after work is done

Cursor cursor = db.query(...);if (cursor != null) {
if (cursor.moveToFirst()) {
    //do your stuff
}
cursor.close();

}

Now if you want check for multiple columns just replace while condition insted of if
Thanks


问:
Is it dangerous to mix ActiveSupport::Concern modules with vanilla modules?
I know there's a dependency management system hidden behind ActiveSupport::Concern. I do not understand it completely (and I'm not sure I am ready to yet), but in a nutshell : is it possible to mix ActiveSupport::Concern with vanilla (non ActiveSupport::Concern) modules, or are there pitfalls ?

Here are some examples of the different usages I can think of

```<code>module Vanilla
  module ModuleIncludedInASC
    # Vanilla module
  end

  module ModuleIncludedInClass
    # Vanilla module
  end

module ASC
  module ConcernIncludedInClass
    extend ActiveSupport::Concern
    ...
  end

  module ConcernIncludedInASC
    extend ActiveSupport::Concern
    ...
  end

  module ConcernIncludingVanillaModulesIncludedInClass
    extend ActiveSupport::Concern
    include Vanilla::VanillaConcernIncludedInASC
  end
  module ConcernIncludingASCConcernIncludedInASC
    extend ActiveSupport::Concern
    include ConcernIncludedInASC
  end
end

class MyFoo
  include Vanilla::ModuleIncludedInClass
  include ASC::ConcernIncludedInClass
  include ASC::ConcernIncludingVanillaModulesIncludedInClass
end

# Ans also possibly, ActiveSupport::Concern modules included in vanilla modules...?
</code>```

Could that potentially lead to problems ?

答:
I haven't had any problem yet, but yes, theoretically there is a potential problem.

The methods that are defined in a normal module are appended to the method lookup chain if you include that module in a class. So the methods defined in the class will override the methods in the normal module.

The methods that are defined in a concern's included block will be added directly to the class that includes the concern.

The result is, even if you include concern earlier than a normal module, the methods in a concern will always override the methods in a normal module.

Example

```<code>module Normal
  def foo
    'normal'
  end
end

module Concern
  extend ActiveSupport::Concern
  included do
    def foo
      'concern'
    end
  end
end

class Bar
  include Concern  # include concern first
  include Normal   # then include normal
end

Bar.new.foo  #=> "concern"
</code>```

Maybe you would expect "normal" to be returned, but that's never gonna happen.

Body:
I know there's a dependency management system hidden behind ActiveSupport::Concern. I do not understand it completely (and I'm not sure I am ready to yet), but in a nutshell : is it possible to mix ActiveSupport::Concern with vanilla (non ActiveSupport::Concern) modules, or are there pitfalls ?

Here are some examples of the different usages I can think of

module Vanilla
  module ModuleIncludedInASC
    # Vanilla module
  end

  module ModuleIncludedInClass
    # Vanilla module
  end

module ASC
  module ConcernIncludedInClass
    extend ActiveSupport::Concern
    ...
  end

  module ConcernIncludedInASC
    extend ActiveSupport::Concern
    ...
  end

  module ConcernIncludingVanillaModulesIncludedInClass
    extend ActiveSupport::Concern
    include Vanilla::VanillaConcernIncludedInASC
  end
  module ConcernIncludingASCConcernIncludedInASC
    extend ActiveSupport::Concern
    include ConcernIncludedInASC
  end
end

class MyFoo
  include Vanilla::ModuleIncludedInClass
  include ASC::ConcernIncludedInClass
  include ASC::ConcernIncludingVanillaModulesIncludedInClass
end

# Ans also possibly, ActiveSupport::Concern modules included in vanilla modules...?

Could that potentially lead to problems ?

Body:
I haven't had any problem yet, but yes, theoretically there is a potential problem.

The methods that are defined in a normal module are appended to the method lookup chain if you include that module in a class. So the methods defined in the class will override the methods in the normal module.

The methods that are defined in a concern's included block will be added directly to the class that includes the concern.

The result is, even if you include concern earlier than a normal module, the methods in a concern will always override the methods in a normal module.

Example

module Normal
  def foo
    'normal'
  end
end

module Concern
  extend ActiveSupport::Concern
  included do
    def foo
      'concern'
    end
  end
end

class Bar
  include Concern  # include concern first
  include Normal   # then include normal
end

Bar.new.foo  #=> "concern"

Maybe you would expect "normal" to be returned, but that's never gonna happen.


问:
How-To Mock WCF Services?
How-to Mock WCF Services Proxies with Rhino Mocks ?</p>

答: Create your service so that it implements an interface.  Then you can either mock the interface in your client or create a fake implementation of the interface to use in your tests.</p>

OwnerDisplayName: Yoann. B

Title: How-To Mock WCF Services?

LastEditorDisplayName: Yoann. B

OwnerDisplayName: tvanfosson


问:
How can I put an icon and an input text on the same line?
I want to put an icon on the left and an input type text on the right occupying all the remaining space.

```<code>----------------------------------------------------
| [ico]  ----------------------------------------  |
|        |   input type="text"                  |  |
|        ----------------------------------------  |
----------------------------------------------------
</code>```

If I set both with display: inline-block and set the input's width to 100% it jumps the line, because 100% is not considering the space - icosize...

I want to expand the input to the remaining available space (I don't care for vertical align). Is there a way to achieve this behavior without using tables?

An example of the problem on jsFiddle.

答: i think the answer is vertical-align: middle but see Understanding vertical-align, or "How (Not) To Vertically Center Content"

Body:
I want to put an icon on the left and an input type text on the right occupying all the remaining space.

----------------------------------------------------
| [ico]  ----------------------------------------  |
|        |   input type="text"                  |  |
|        ----------------------------------------  |
----------------------------------------------------

If I set both with display: inline-block and set the input's width to 100% it jumps the line, because 100% is not considering the space - icosize...

I want to expand the input to the remaining available space (I don't care for vertical align). Is there a way to achieve this behavior without using tables?

An example of the problem on jsFiddle.


问:
How to get absolute path to file in /resources folder of your project
Assume standard maven setup.

Say in your resources folder you have a file abc.

In Java, how can I get absolute path to the file please?

答:
Create the classLoader instance of the class you need, then you can access the files or resources easily.
now you access path using getPath() method of that class.

```<code> ClassLoader classLoader = getClass().getClassLoader();
 String path  = classLoader.getResource("chromedriver.exe").getPath();
 System.out.println(path);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Create the classLoader instance of the class you need, then you can access the files or resources easily.
now you access path using getPath() method of that class.

 ClassLoader classLoader = getClass().getClassLoader();
 String path  = classLoader.getResource("chromedriver.exe").getPath();
 System.out.println(path);


问:
Is there a way of reading HTML tags on the page that are not part of the DOM using javascript?
I have a Chrome Extension that reads meta tags from the current tab in order to display information about the current page to the user.

I've noticed that currently on YouTube, the meta tags containing information about the current video are not accessible via the DOM (open up the Dev Console and check out document.head, no meta tags about the current video are present), yet they are on the page if you look at the page source. I guess they are adding them using document.write as they don't want them part of the DOM.

Is there another way I can access these tags using javascript?

答:
```<code>document.querySelectorAll("meta")
</code>```

Will return all the meta tags.

meta tags to do not have to be inside  tags. That's just a convention not a requirement. It's also a convention that google doesn't follow. See their html style guide

Body:
document.querySelectorAll("meta")

Will return all the meta tags.

meta tags to do not have to be inside <head> tags. That's just a convention not a requirement. It's also a convention that google doesn't follow. See their html style guide


问:
How to create android button bar?
I need to create a horizontal list of buttons without a separating space like this one

each button will contain a text and an icon I know about buttonbarlayout but it didn't work for me, please can someone help me, Thanks in advance

答:
```<code> <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:weightSum="4"
        android:id="@+id/func"
        android:layout_above="@+id/btn_next">

        <Button
            android:id="@+id/btn_bgm"
            android:layout_width="wrap_content"
            android:layout_weight="1"
            android:background="#3279CE"
            android:layout_height="wrap_content"
            android:layout_below="@+id/pager_image"
            android:text="BitRate"/>

        <Button
            android:id="@+id/btn_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="#3279CE"
            android:text="time"
            />

        <Button
            android:id="@+id/btn_effect"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="#3279CE"
            android:text="effect" />
        <Button
            android:id="@+id/frame"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="#3279CE"
            android:text="FRAME" />

    </LinearLayout>
</code>```

Title: How to create android button bar?


问:
python: is there a disadvantage to from package import * besides namespace collision
I'm creating a class to extend a package, and prior to class instantiation I don't know which subset of the package's namespace I need.  I've been careful about avoiding namespace conflicts in my code, so, does

```<code>from package import *
</code>```

create problems besides name conflicts?

Is it better to examine the class's input and import only the names I need (at runtime) in the __init__ ??

Can python import from a set [] ?

does

```<code>for name in [namespace,namespace]:
    from package import name
</code>```

make any sense?

I hope this question doesn't seem like unnecessary hand-ringing, i'm just super new to python and don't want to do the one thing every 'beginnger's guide' says not to do (from pkg import * ) unless I'm sure there's no alternative.

thoughts, advice welcome.

答:
This syntax constructions help you to avoid any name collision:</p>

```<code>from package import somename as another_name
import package as another_package_name
</code>```

Body:
I'm creating a class to extend a package, and prior to class instantiation I don't know which subset of the package's namespace I need.  I've been careful about avoiding namespace conflicts in my code, so, does

from package import *

create problems besides name conflicts?

Is it better to examine the class's input and import only the names I need (at runtime) in the __init__ ??

Can python import from a set [] ?

does

for name in [namespace,namespace]:
    from package import name

make any sense?

I hope this question doesn't seem like unnecessary hand-ringing, i'm just super new to python and don't want to do the one thing every 'beginnger's guide' says not to do (from pkg import * ) unless I'm sure there's no alternative.

thoughts, advice welcome.

Body:
This syntax constructions help you to avoid any name collision:

from package import somename as another_name
import package as another_package_name


问:
How to take array as an input in android?
Actually I am designing an android application in which I would be taking array as an input by using EditText.  so the thing is I am trying a lot by I am not getting how to do it so. Can anyone help me please.
I don't have a proper code so I am not attaching that but please help me with your code.

How can I take input as an array using EditText in android.
I want to insert n elements by EditText and than want to convert them in a single array.
like if I give input 1 and 2 and 3 and 4. than I can have a array like a[4] = {1,2,3,4}

答:
You can type your input and use a character as delimiter.
Here is an example using "," as delimeter.

```<code>    EditText eText = (EditText) findViewById(R.id.edittext);
    String input = eText.getText().toString();
    //split your input using ","
    String[] valuesArray =  input.split(",");
    // now you got a String[] with your values to work with.
    //If you had input 1,2,3,4 your array is like : {"1","2","3","4"}
</code>```

Body:
You can type your input and use a character as delimiter.
Here is an example using "," as delimeter.

    EditText eText = (EditText) findViewById(R.id.edittext);
    String input = eText.getText().toString();
    //split your input using ","
    String[] valuesArray =  input.split(",");
    // now you got a String[] with your values to work with.
    //If you had input 1,2,3,4 your array is like : {"1","2","3","4"}


问:
C# how to "register" class "plug-ins" into a service class?
Update#2 as of year 2022

All these years have passed and still no good answer.
Decided to revive this question.

I'm trying to implement something like the idea I'm trying to show with the following diagram (end of the question).

Everything is coded from the abstract class Base till the DoSomething classes.

My "Service" needs to provide to the consumer "actions" of the type "DoSomethings" that the service has "registered", at this point I am seeing my self as repeating (copy/paste) the following logic on the service class:

```<code>public async Task<Obj1<XXXX>> DoSomething1(....params....)
        {
            var action = new DoSomething1(contructParams);
            return await action.Go(....params....);
        }
</code>```

I would like to know if there is anyway in C# to "register" all the "DoSomething" I want in a different way? Something more dynamic and less "copy/paste" and at the same time provide me the "intellisense" in my consumer class? Somekind of "injecting" a list of accepted "DoSomething" for that service.

Update#1
After reading the sugestion that PanagiotisKanavos said about MEF and checking other options of IoC, I was not able to find exactly what I am looking for.

My objective is to have my Service1 class (and all similar ones) to behave like a DynamicObject but where the accepted methods are defined on its own constructor (where I specify exactly which DoSomethingX I am offering as a method call.

Example:
I have several actions (DoSomethingX) as "BuyCar", "SellCar", "ChangeOil", "StartEngine", etc....
Now, I want to create a service "CarService" that only should offer the actions "StartEngine" and "SellCar", while I might have other "Services" with other combination of "actions". I want to define this logic inside the constructor of each service. Then, in the consumer class, I just want to do something like:

```<code>var myCarService = new CarService(...paramsX...);
var res1 = myCarService.StartEngine(...paramsY...);
var res2 = myCarService.SellCar(...paramsZ...);
</code>```

And I want to offer intellisense when I use the "CarService"....

In conclusion: The objective is how to "register" in each Service which methods are provided by him, by giving a list of "DoSomethingX", and automatically offer them as a "method"... I hope I was able to explain my objective/wish.

In other words: I just want to be able to say that my class Service1 is "offering" the actions DoSomething1, DoSomething2 and DoSomething3, but with the minimum lines as possible. Somehow the concept of the use of class attributes, where I could do something similar to this:

```<code>// THEORETICAL CODE
[RegisterAction(typeOf(DoSomething1))]
[RegisterAction(typeOf(DoSomething2))]
[RegisterAction(typeOf(DoSomething3))]
public class Service1{
    // NO NEED OF EXTRA LINES....
}
</code>```

答:
Maybe RealProxy can help you? If you create ICarService interface which inherits IAction1 and IAction2, you can then create a proxy object which will:

Find all the interfaces ICarService inherits.

Finds realizations of these interfaces (using actions factory or reflection).

Creates action list for the service.

In Invoke method will delegate the call to one of the actions.

This way you will have intellisence as you want, and actions will be building blocks for the services. Some kind of multi-inheritance hack :)

Body:
Update#2 as of year 2022

All these years have passed and still no good answer.
Decided to revive this question.

I'm trying to implement something like the idea I'm trying to show with the following diagram (end of the question).

Everything is coded from the abstract class Base till the DoSomething classes.

My "Service" needs to provide to the consumer "actions" of the type "DoSomethings" that the service has "registered", at this point I am seeing my self as repeating (copy/paste) the following logic on the service class:

public async Task<Obj1<XXXX>> DoSomething1(....params....)
        {
            var action = new DoSomething1(contructParams);
            return await action.Go(....params....);
        }

I would like to know if there is anyway in C# to "register" all the "DoSomething" I want in a different way? Something more dynamic and less "copy/paste" and at the same time provide me the "intellisense" in my consumer class? Somekind of "injecting" a list of accepted "DoSomething" for that service.

Update#1
After reading the sugestion that PanagiotisKanavos said about MEF and checking other options of IoC, I was not able to find exactly what I am looking for.

My objective is to have my Service1 class (and all similar ones) to behave like a DynamicObject but where the accepted methods are defined on its own constructor (where I specify exactly which DoSomethingX I am offering as a method call.

Example:
I have several actions (DoSomethingX) as "BuyCar", "SellCar", "ChangeOil", "StartEngine", etc....
Now, I want to create a service "CarService" that only should offer the actions "StartEngine" and "SellCar", while I might have other "Services" with other combination of "actions". I want to define this logic inside the constructor of each service. Then, in the consumer class, I just want to do something like:

var myCarService = new CarService(...paramsX...);
var res1 = myCarService.StartEngine(...paramsY...);
var res2 = myCarService.SellCar(...paramsZ...);

And I want to offer intellisense when I use the "CarService"....

In conclusion: The objective is how to "register" in each Service which methods are provided by him, by giving a list of "DoSomethingX", and automatically offer them as a "method"... I hope I was able to explain my objective/wish.

In other words: I just want to be able to say that my class Service1 is "offering" the actions DoSomething1, DoSomething2 and DoSomething3, but with the minimum lines as possible. Somehow the concept of the use of class attributes, where I could do something similar to this:

// THEORETICAL CODE
[RegisterAction(typeOf(DoSomething1))]
[RegisterAction(typeOf(DoSomething2))]
[RegisterAction(typeOf(DoSomething3))]
public class Service1{
    // NO NEED OF EXTRA LINES....
}


问:
android dialog call dismiss but is not dismiss
I have a problem with my Android app coding as follows:
I use dismiss() to hide a dialog, but dialog just does not disappear as expected. Dialog remains in activity interface while dismiss() is actually called.

It feels like get stucked or something else. Hardware back button does not work either. App just gets stuck in there.
Can anyone help me out
Thanks in advance.

Example pic

And there are some related code. I use MVP architect.

@Override
    public void editAllNum(Context context, int num, List<ShopCar.GoodListBean> goodList) {
        Subscription s = Observable.just(num)
                .filter(integer -> goodList.size() != 0) //the goodList of size is never equal to 0.
                .subscribeOn(Schedulers.io())
                .compose(TransformerUtil.showLoadingDialog(mView)) //call show dialog.
                .flatMap(new Func1<Integer, Observable<List<ShopCar.GoodListBean>>>() {
                    @Override
                    public Observable<List<ShopCar.GoodListBean>> call(Integer num) {
                        List<ShopCar.GoodListBean> list = new ArrayList<ShopCar.GoodListBean>();
                        for ( ShopCar.GoodListBean item : goodList ) {
                            if ( item.getRemainNum() != 0 ) {
                                if ( item.getRemainNum() > num ) {

                                    if ( item.getLimit() != 0 ) {
                                        item = editNum(item, num); //editNum is not important
                                    } else {
                                        item.setNum(num);
                                    }
                                } else {

                                    if ( item.getLimit() != 0 ) {
                                        item = editNum(item, num);
                                    } else {
                                        item.setNum(item.getRemainNum());
                                    }
                                }
                            }
                            list.add(item);
                        }
                        return Observable.just(list);
                    }
                })
                .flatMap(new Func1<List<ShopCar.GoodListBean>, Observable<List<ShopCar.GoodListBean>>>() {
                    @Override
                    public Observable<List<ShopCar.GoodListBean>> call(List<ShopCar.GoodListBean> temp) {
                        return mPaymentImpl.updateGoodsNumAndQuery(context, temp); //operate databases update some data.
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<ShopCar.GoodListBean>>() {
                    @Override
                    public void onCompleted() {
                    }
                    @Override
                    public void onError(Throwable e) {
                        mView.dismissLoadingDialog();
                    }
                    @Override
                    public void onNext(List<ShopCar.GoodListBean> list) {
                        mView.dismissLoadingDialog();// call dismiss dialog.
                        mView.setShopCarFromDB(list);
                    }
                });
        addSubscription(s);
    }```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>@Override
    public void showLoadingDialog() {
        if ( mLoadingDialog == null ) {
            mLoadingDialog = new LoadingDialog(getContext());
            LogUtils.e(" show loading dialog = " + mLoadingDialog);
        }
        mLoadingDialog.show();
    }

    @Override
    public void dismissLoadingDialog() {
        if ( mLoadingDialog != null ) {
            LogUtils.e(" dismiss loading dialog ");
            mLoadingDialog.dismiss();
        }
    }</code>```

some code of Dialog.

public class LoadingDialog extends Dialog {

    public LoadingDialog(Context context) {
        super(context, android.R.style.Theme_Translucent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.widget_loading_dialog);
        setCanceledOnTouchOutside(true);
        setCancelable(true);

    }
}

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

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="@drawable/loading_dialog_bg"
        >

        <ProgressBar
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            />

    </RelativeLayout>

</RelativeLayout>```

Finally, sorry my English.

答:
Check if the value of mLoadingDialog is null first. Maybe somehow the value is null. ie. the dialog u see on the screen might not be that mLoadingDialog. By change the function below, what did you see in logcat?</p>

```<code>@Override
        public void dismissLoadingDialog() {
            if ( mLoadingDialog != null ) {
                LogUtils.e(" dismiss loading dialog ");
                mLoadingDialog.dismiss();
            }else{
               LogUtils.e("mLoadingDialog is null skip dismiss loading dialog ");
           }
        }
</code>```

Body:
I have a problem with my Android app coding as follows:
I use dismiss() to hide a dialog, but dialog just does not disappear as expected. Dialog remains in activity interface while dismiss() is actually called.

It feels like get stucked or something else. Hardware back button does not work either. App just gets stuck in there.
Can anyone help me out
Thanks in advance.

Example pic

And there are some related code. I use MVP architect.

@Override
    public void editAllNum(Context context, int num, List<ShopCar.GoodListBean> goodList) {
        Subscription s = Observable.just(num)
                .filter(integer -> goodList.size() != 0) //the goodList of size is never equal to 0.
                .subscribeOn(Schedulers.io())
                .compose(TransformerUtil.showLoadingDialog(mView)) //call show dialog.
                .flatMap(new Func1<Integer, Observable<List<ShopCar.GoodListBean>>>() {
                    @Override
                    public Observable<List<ShopCar.GoodListBean>> call(Integer num) {
                        List<ShopCar.GoodListBean> list = new ArrayList<ShopCar.GoodListBean>();
                        for ( ShopCar.GoodListBean item : goodList ) {
                            if ( item.getRemainNum() != 0 ) {
                                if ( item.getRemainNum() > num ) {

                                    if ( item.getLimit() != 0 ) {
                                        item = editNum(item, num); //editNum is not important
                                    } else {
                                        item.setNum(num);
                                    }
                                } else {

                                    if ( item.getLimit() != 0 ) {
                                        item = editNum(item, num);
                                    } else {
                                        item.setNum(item.getRemainNum());
                                    }
                                }
                            }
                            list.add(item);
                        }
                        return Observable.just(list);
                    }
                })
                .flatMap(new Func1<List<ShopCar.GoodListBean>, Observable<List<ShopCar.GoodListBean>>>() {
                    @Override
                    public Observable<List<ShopCar.GoodListBean>> call(List<ShopCar.GoodListBean> temp) {
                        return mPaymentImpl.updateGoodsNumAndQuery(context, temp); //operate databases update some data.
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<ShopCar.GoodListBean>>() {
                    @Override
                    public void onCompleted() {
                    }
                    @Override
                    public void onError(Throwable e) {
                        mView.dismissLoadingDialog();
                    }
                    @Override
                    public void onNext(List<ShopCar.GoodListBean> list) {
                        mView.dismissLoadingDialog();// call dismiss dialog.
                        mView.setShopCarFromDB(list);
                    }
                });
        addSubscription(s);
    }

@Override
    public void showLoadingDialog() {
        if ( mLoadingDialog == null ) {
            mLoadingDialog = new LoadingDialog(getContext());
            LogUtils.e(" show loading dialog = " + mLoadingDialog);
        }
        mLoadingDialog.show();
    }

    @Override
    public void dismissLoadingDialog() {
        if ( mLoadingDialog != null ) {
            LogUtils.e(" dismiss loading dialog ");
            mLoadingDialog.dismiss();
        }
    }

some code of Dialog.

public class LoadingDialog extends Dialog {

    public LoadingDialog(Context context) {
        super(context, android.R.style.Theme_Translucent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.widget_loading_dialog);
        setCanceledOnTouchOutside(true);
        setCancelable(true);

    }
}

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

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="@drawable/loading_dialog_bg"
        >

        <ProgressBar
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            />

    </RelativeLayout>

</RelativeLayout>

Finally, sorry my English.

Body:
Check if the value of mLoadingDialog is null first. Maybe somehow the value is null. ie. the dialog u see on the screen might not be that mLoadingDialog. By change the function below, what did you see in logcat?

@Override
        public void dismissLoadingDialog() {
            if ( mLoadingDialog != null ) {
                LogUtils.e(" dismiss loading dialog ");
                mLoadingDialog.dismiss();
            }else{
               LogUtils.e("mLoadingDialog is null skip dismiss loading dialog ");
           }
        }


问:
ASP.NET Core return excel file (xlsx) directly in one call to the server (on the fly)?
I have found solution for generating excel file (xlsx) on the server.On first call it deletes the file demo.xlsx if it exists and generates new demo.xlsx.

First call
http://localhost:8000/api/importexport/export

it generates excel file (xlsx) and sends url for download

Second call
http://localhost:8000/demo.xlsx

downloads the file.
In Startup class in Configure method you must add
app.UseStaticFiles();

Here is the link for solution
http://www.talkingdotnet.com/import-export-xlsx-asp-net-core/

The problem with this solution is that I have two calls to server.
I want in one call
http://localhost:8000/api/importexport/export
to directly download excel file (xlsx).
I heard that its possible to download excel file (xlsx) in one call without creating file on the server(on the fly).
I would be glad to see better solution in one call to the server.

答:
It's easy, just return File (like of View or Redirect, but File):

```<code>public async Task<ActionResult> Index()
{
    var fileMemoryStream = await GenerateReportAndWriteToMemoryStream(...);
    return File(
        fileMemoryStream,
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        "report.xlsx");
}
</code>```

This method is part of ControllerBase and has several signatures, choose best that fit your needs:

```<code>File(byte[] fileContents, string contentType)
File(Stream fileStream, string contentType)
File(string virtualPath, string contentType)
File(string virtualPath, string contentType, string fileDownloadName)
File(byte[] fileContents, string contentType, string fileDownloadName)
File(Stream fileStream, string contentType, string fileDownloadName)
</code>```

Body:
It's easy, just return File (like of View or Redirect, but File):

public async Task<ActionResult> Index()
{
    var fileMemoryStream = await GenerateReportAndWriteToMemoryStream(...);
    return File(
        fileMemoryStream,
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        "report.xlsx");
}

This method is part of ControllerBase and has several signatures, choose best that fit your needs:

File(byte[] fileContents, string contentType)
File(Stream fileStream, string contentType)
File(string virtualPath, string contentType)
File(string virtualPath, string contentType, string fileDownloadName)
File(byte[] fileContents, string contentType, string fileDownloadName)
File(Stream fileStream, string contentType, string fileDownloadName)


问:
Blank output for an ASP.NET NUnit test application
I am currently working with NUnit to write test cases for an ASP.NET application.

I have created a sample test project and have added NUnit latest version (3.6.1) and NUnitTestAdapter 2.1.1.

If I run the application by clicking on menu Test → Windows → Text Explorer, I am getting a blank screen in the Output Window. Why?

My code is:

```<code>[TestFixture]
public class SampleTest
{
    [Test]
    public void StringCheck()
    {
        string str = "Hello";
        Assert.That(str, Is.EqualTo("Hello"));
    }

    [Test]
    public void EmptyCheck()
    {
        string str = "siva";

        Assert.That(str, Is.EqualTo(string.Empty));
    }

    [Test]
    public void NumberCheck()
    {
        int i = 0;
        Assert.That(i, Is.EqualTo(0));
    }
}
</code>```

答: I found the solution. The problem was with NUnit version (3.6.1). Now I am updated with NUnit 2.6.4. It is working for me.</p>

Body:
I am currently working with NUnit to write test cases for an ASP.NET application.

I have created a sample test project and have added NUnit latest version (3.6.1) and NUnitTestAdapter 2.1.1.

If I run the application by clicking on menu Test → Windows → Text Explorer, I am getting a blank screen in the Output Window. Why?

My code is:

[TestFixture]
public class SampleTest
{
    [Test]
    public void StringCheck()
    {
        string str = "Hello";
        Assert.That(str, Is.EqualTo("Hello"));
    }

    [Test]
    public void EmptyCheck()
    {
        string str = "siva";

        Assert.That(str, Is.EqualTo(string.Empty));
    }

    [Test]
    public void NumberCheck()
    {
        int i = 0;
        Assert.That(i, Is.EqualTo(0));
    }
}


问:
automatically remove indentation, unneeded empty space from html (minify)
I have an asp.net-mvc application, and when I look at the page's source I see the html is indented, has lots of white space,

I think if I will remove all these spaces, my page will become smaller in KB

anybody knows how to remove them automatically ?

答:
As in HTML, multiple whitespaces are treated as one, you could use a regular expression on your response:

```<code>/\s+/ /g
</code>```

which converts any consecutive whitespaces to a single space.

Note that although this will decrease the size of uncompressed page, if you're gzipping the pages, the savings won't be that great.

Caveat: this could break inline JavaScript, as JS treats an endline as command delimiter (that is, like ;). If your JS uses ; for delimiting commands (most JS does), you should be OK.

Also, code     samples in ``` blocks</code> will be affected, as whitespace is displayed there:</p>

```some   code   here {
  more          code }
```

<p>becomes</p>

```some code here { more code }
```

Body:
As in HTML, multiple whitespaces are treated as one, you could use a regular expression on your response:

/\s+/ /g

which converts any consecutive whitespaces to a single space.

Note that although this will decrease the size of uncompressed page, if you're gzipping the pages, the savings won't be that great.

Caveat: this could break inline JavaScript, as JS treats an endline as command delimiter (that is, like ;). If your JS uses ; for delimiting commands (most JS does), you should be OK.

Also, code     samples in <pre> blocks will be affected, as whitespace is displayed there:

some   code   here {
  more          code }

becomes

some code here { more code }


问:
Android PopupMenu in recycleview not worked?
I have tried to add sub menu to recycleview but when click on sub menu in every row A message appears : unfortunately app has stopped
    after that The application is automatically closed

```<code>activity_main.xml

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

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rvAnimals"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

// recycleview_row.xml

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="10dp">
    <TextView
        android:id="@+id/tvAnimalName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"/>
    <TextView
        android:id="@+id/textViewOptions"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:text="⋮"
        android:textAppearance="?android:textAppearanceLarge" />

</LinearLayout>

// MainActivity class

    package com.example.hamoda.recyvlastexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {
    MyRecyclerViewAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // data to populate the RecyclerView with
        ArrayList<String> animalNames = new ArrayList<>();
        animalNames.add("Horse");
        animalNames.add("Cow");
        animalNames.add("Camel");
        animalNames.add("Sheep");
        animalNames.add("Goat");
        // set up the RecyclerView
        RecyclerView recyclerView =(RecyclerView) findViewById(R.id.rvAnimals);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new MyRecyclerViewAdapter(this, animalNames);
        adapter.setClickListener(this);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onItemClick(View view, int position) {
        Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
    }
}

// MyRecyclerViewAdapter class

    package com.example.hamoda.recyvlastexample;
import android.content.Context;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.Collections;
import java.util.List;

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {
    private List<String> mData = Collections.emptyList();
    private LayoutInflater mInflater;
    private ItemClickListener mClickListener;
    // data is passed into the constructor
    public MyRecyclerViewAdapter(Context context, List<String> data) {
        this.mInflater = LayoutInflater.from(context);
        this.mData = data;
    }
    // inflates the row layout from xml when needed
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
         View view = mInflater.inflate(R.layout.recyclerview_row, parent,false);
         ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }
    // binds the data to the textview in each row
    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        String animal = mData.get(position);
        holder.myTextView.setText(animal);
        holder.buttonViewOption.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //  creating a popup menu
              PopupMenu popup = new PopupMenu((Context)mData,holder.buttonViewOption);
            /*
                //inflating menu from xml resource
                popup.inflate(R.menu.options_menu);
                //adding click listener
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id.menu1:
                                //handle menu1 click
                                break;
                            case R.id.menu2:
                                //handle menu2 click
                                break;
                            case R.id.menu3:
                                //handle menu3 click
                                break;
                        }
                        return false;
                    }
                });
                //displaying the popup
                popup.show();
                */
            }
        });
    }
    // total number of rows
    @Override
    public int getItemCount() {
        return mData.size();
    }
    // stores and recycles views as they are scrolled off screen
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        public TextView myTextView;
        public TextView buttonViewOption;
        public ViewHolder(View itemView) {
            super(itemView);
            myTextView = (TextView) itemView.findViewById(R.id.tvAnimalName);
            itemView.setOnClickListener(this);
            //textViewDesc = (TextView) itemView.findViewById(R.id.textViewDesc);
            buttonViewOption = (TextView) itemView.findViewById(R.id.textViewOptions);
        }
        @Override
        public void onClick(View view) {
            if (mClickListener != null) mClickListener.onItemClick(view,getAdapterPosition());
        }

    }
    // convenience method for getting data at click position
    public String getItem(int id) {
        return mData.get(id);
    }
    // allows clicks events to be caught
    public void setClickListener(ItemClickListener itemClickListener) {
        this.mClickListener = itemClickListener;
    }
    // parent activity will implement this method to respond to click events
    public interface ItemClickListener {
        void onItemClick(View view, int position);
    }
}
</code>```

Error log:

```<code>03-31 11:13:57.461 10139-10139/com.example.hamoda.recyvlastexample E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.hamoda.recyvlastexample, PID: 10139
java.lang.ClassCastException: java.util.ArrayList cannot be cast to android.content.Context
at com.example.hamoda.recyvlastexample.MyRecyclerViewAdapter$1.onClick(MyRecyclerViewAdapter.java:38)
at android.view.View.performClick(View.java:5076)
at android.view.View$PerformClick.run(View.java:20279)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5910)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
</code>```

答:
You haven't pass Context in PopupMenu constructor and you have cast data list object in Context that is wrong.

```<code>PopupMenu popup = new PopupMenu((Context)mData,holder.buttonViewOption);
</code>```

use below line :

```<code>PopupMenu popup = new PopupMenu(context,holder.buttonViewOption);
</code>```

In  above line context is reference of Activity context that is passes in MyRecyclerViewAdapter constructor in your code see below :

// data is passed into the constructor

```<code>public MyRecyclerViewAdapter(Context context, List<String> data) {
    this.mInflater = LayoutInflater.from(context);
    this.mData = data;
}
</code>```

So create one global reference of contextand pass in PopupMenu constructor.

Body:
I have tried to add sub menu to recycleview but when click on sub menu in every row A message appears : unfortunately app has stopped
    after that The application is automatically closed

activity_main.xml

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

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rvAnimals"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

// recycleview_row.xml

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="10dp">
    <TextView
        android:id="@+id/tvAnimalName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"/>
    <TextView
        android:id="@+id/textViewOptions"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:text="⋮"
        android:textAppearance="?android:textAppearanceLarge" />

</LinearLayout>

// MainActivity class

    package com.example.hamoda.recyvlastexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {
    MyRecyclerViewAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // data to populate the RecyclerView with
        ArrayList<String> animalNames = new ArrayList<>();
        animalNames.add("Horse");
        animalNames.add("Cow");
        animalNames.add("Camel");
        animalNames.add("Sheep");
        animalNames.add("Goat");
        // set up the RecyclerView
        RecyclerView recyclerView =(RecyclerView) findViewById(R.id.rvAnimals);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new MyRecyclerViewAdapter(this, animalNames);
        adapter.setClickListener(this);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onItemClick(View view, int position) {
        Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
    }
}

// MyRecyclerViewAdapter class

    package com.example.hamoda.recyvlastexample;
import android.content.Context;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.Collections;
import java.util.List;

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {
    private List<String> mData = Collections.emptyList();
    private LayoutInflater mInflater;
    private ItemClickListener mClickListener;
    // data is passed into the constructor
    public MyRecyclerViewAdapter(Context context, List<String> data) {
        this.mInflater = LayoutInflater.from(context);
        this.mData = data;
    }
    // inflates the row layout from xml when needed
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
         View view = mInflater.inflate(R.layout.recyclerview_row, parent,false);
         ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }
    // binds the data to the textview in each row
    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        String animal = mData.get(position);
        holder.myTextView.setText(animal);
        holder.buttonViewOption.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //  creating a popup menu
              PopupMenu popup = new PopupMenu((Context)mData,holder.buttonViewOption);
            /*
                //inflating menu from xml resource
                popup.inflate(R.menu.options_menu);
                //adding click listener
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id.menu1:
                                //handle menu1 click
                                break;
                            case R.id.menu2:
                                //handle menu2 click
                                break;
                            case R.id.menu3:
                                //handle menu3 click
                                break;
                        }
                        return false;
                    }
                });
                //displaying the popup
                popup.show();
                */
            }
        });
    }
    // total number of rows
    @Override
    public int getItemCount() {
        return mData.size();
    }
    // stores and recycles views as they are scrolled off screen
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        public TextView myTextView;
        public TextView buttonViewOption;
        public ViewHolder(View itemView) {
            super(itemView);
            myTextView = (TextView) itemView.findViewById(R.id.tvAnimalName);
            itemView.setOnClickListener(this);
            //textViewDesc = (TextView) itemView.findViewById(R.id.textViewDesc);
            buttonViewOption = (TextView) itemView.findViewById(R.id.textViewOptions);
        }
        @Override
        public void onClick(View view) {
            if (mClickListener != null) mClickListener.onItemClick(view,getAdapterPosition());
        }

    }
    // convenience method for getting data at click position
    public String getItem(int id) {
        return mData.get(id);
    }
    // allows clicks events to be caught
    public void setClickListener(ItemClickListener itemClickListener) {
        this.mClickListener = itemClickListener;
    }
    // parent activity will implement this method to respond to click events
    public interface ItemClickListener {
        void onItemClick(View view, int position);
    }
}

Error log:

03-31 11:13:57.461 10139-10139/com.example.hamoda.recyvlastexample E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.hamoda.recyvlastexample, PID: 10139
java.lang.ClassCastException: java.util.ArrayList cannot be cast to android.content.Context
at com.example.hamoda.recyvlastexample.MyRecyclerViewAdapter$1.onClick(MyRecyclerViewAdapter.java:38)
at android.view.View.performClick(View.java:5076)
at android.view.View$PerformClick.run(View.java:20279)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5910)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)

Body:
You haven't pass Context in PopupMenu constructor and you have cast data list object in Context that is wrong.

PopupMenu popup = new PopupMenu((Context)mData,holder.buttonViewOption);

use below line :

PopupMenu popup = new PopupMenu(context,holder.buttonViewOption);

In  above line context is reference of Activity context that is passes in MyRecyclerViewAdapter constructor in your code see below :

// data is passed into the constructor

public MyRecyclerViewAdapter(Context context, List<String> data) {
    this.mInflater = LayoutInflater.from(context);
    this.mData = data;
}

So create one global reference of contextand pass in PopupMenu constructor.


问:
Garbarge collector order
I know the .Net garbage collector cannot guarantee any order when destroying objects but I am really suprised of the following behaviour:

```<code>using System;
using System.Collections.Generic;

namespace ConsoleApplication2 {
class Program {

    class A {
        public A() { i = 1; }
        private int i;

        // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
        ~A() {
            // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
            Console.WriteLine("Disposed A");
        }
    }

    class B {
        static int p = 0;
        public B(A a) {
            this.a = a;
            j = p++;
        }

        ~B() {
            Console.WriteLine("Disposed " + j.ToString());
        }

        private int j;
        private A a;
    }

    static void Main(string[] args) {
        A a_obj = new A();
        List<B> bs = new List<B>();
        for (int i = 0; i < 10; i++) {
            B b = new B(a_obj);
            bs.Add(b);
        }
    }
}
}
</code>```

This execution has the following (possible) output:

Disposed 9

Disposed 2

Disposed 1

Disposed 0

Disposed A

Disposed 8

Disposed 7

Disposed 6

Disposed 5

Disposed 4

Disposed 3

I can understand that the order of B objects is not deterministic but
how is possible that the garbage collector destroys a_obj, if there are still some B objects that have a reference to a_obj and has not been destroyed still?

答:
If none of the elements that reference a_obj are referenced, the GC can collect it, because the application root has no way of obtaining a reference to it again.

Here is the relevant part of a good tutorial on C# object lifecycle

During a garbage collection process, the runtime will investigate objects on the managed heap to determine whether they are still reachable (rooted) by the application. To do so, the CLR will build an object graph, which represents each reachable object on the heap. Object graphs are used to document all reachable objects.
[...]
Once the graph has been constructed, unreachable objects are marked as garbage.

Title: Garbarge collector order

Body:
I know the .Net garbage collector cannot guarantee any order when destroying objects but I am really suprised of the following behaviour:

using System;
using System.Collections.Generic;

namespace ConsoleApplication2 {
class Program {

    class A {
        public A() { i = 1; }
        private int i;

        // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
        ~A() {
            // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
            Console.WriteLine("Disposed A");
        }
    }

    class B {
        static int p = 0;
        public B(A a) {
            this.a = a;
            j = p++;
        }

        ~B() {
            Console.WriteLine("Disposed " + j.ToString());
        }

        private int j;
        private A a;
    }

    static void Main(string[] args) {
        A a_obj = new A();
        List bs = new List();
        for (int i = 0; i < 10; i++) {
            B b = new B(a_obj);
            bs.Add(b);
        }
    }
}
}

This execution has the following (possible) output:

Disposed 9

Disposed 2

Disposed 1

Disposed 0

Disposed A

Disposed 8

Disposed 7

Disposed 6

Disposed 5

Disposed 4

Disposed 3

I can understand that the order of B objects is not deterministic but
how is possible that the garbage collector destroys a_obj, if there are still some B objects that have a reference to a_obj and has not been destroyed still?


问:
Electron Save Dialog Specify File Type
I have a save dialog in an electron app. At the moment, when a user clicks save it will save with the default name and file extension foo.pdf.

When the name is changed, the file extension isn't added.

Is there a way to make sure that the .pdf file extension is added to all file names?

```<code>document.getElementById("pdf-btn").onclick = function() {
  var webv = document.getElementById('appview');
  dialog.showSaveDialog({
    defaultPath: '~/foo.pdf'
  }, function(file_path) {
    if (file_path) {
      webv.printToPDF({}, function(err, data) {
        if (err) {
          dialog.showErrorBox('Error', err);
          return;
        }
        fs.writeFile(file_path, data, function(err) {
          if (err) {
            dialog.showErrorBox('Error', err);
            return;
          }

          // addext = file_path + ".pdf";
          //
          // save_pdf_path = addext;

          save_pdf_path = file_path;

          var message = "<p> Write PDF file: " + save_pdf_path + " successfully!</p>";

          console.log(message);

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

答:
By adding the following code I was able to specify the file extension.</p>

```<code>dialog.showSaveDialog({
    filters: [{
      name: 'Adobe PDF',
      extensions: ['pdf']
    }]
  },
</code>```

Title: Electron Save Dialog Specify File Type

Body:
I have a save dialog in an electron app. At the moment, when a user clicks save it will save with the default name and file extension foo.pdf.

When the name is changed, the file extension isn't added.

Is there a way to make sure that the .pdf file extension is added to all file names?

document.getElementById("pdf-btn").onclick = function() {
  var webv = document.getElementById('appview');
  dialog.showSaveDialog({
    defaultPath: '~/foo.pdf'
  }, function(file_path) {
    if (file_path) {
      webv.printToPDF({}, function(err, data) {
        if (err) {
          dialog.showErrorBox('Error', err);
          return;
        }
        fs.writeFile(file_path, data, function(err) {
          if (err) {
            dialog.showErrorBox('Error', err);
            return;
          }

          // addext = file_path + ".pdf";
          //
          // save_pdf_path = addext;

          save_pdf_path = file_path;

          var message = "
 Write PDF file: " + save_pdf_path + " successfully!
";

          console.log(message);

        });
      });
    }
  });
}

Body:
By adding the following code I was able to specify the file extension.

dialog.showSaveDialog({
    filters: [{
      name: 'Adobe PDF',
      extensions: ['pdf']
    }]
  },


问:
c# iTextSharp Combine two 'Chunk'
I need to know if its possible to combine two Chunk from iTextSharp

```<code>Phrase phrase = new Phrase();
var text1 = new Chunk("hello");
var text2 = new Chunk("world");

phrase.add();
</code>```

I want to combine text1 and text2, and then add them to a phrase.

答:
FIXED

I already fixed it doing this

```<code>var text1 = new Chunk("hello");
var text2 = new Chunk("world");
var phrase = new Phrase();
phrase.Add(text1);
phrase.Add(text2);
</code>```

Title: c# iTextSharp Combine two 'Chunk'

Body:
I need to know if its possible to combine two Chunk from iTextSharp

Phrase phrase = new Phrase();
var text1 = new Chunk("hello");
var text2 = new Chunk("world");

phrase.add();

I want to combine text1 and text2, and then add them to a phrase.

Body:
FIXED

I already fixed it doing this

var text1 = new Chunk("hello");
var text2 = new Chunk("world");
var phrase = new Phrase();
phrase.Add(text1);
phrase.Add(text2);


问:
Notification is sent when app is started
I implemented a notification builder inside a childEventListener in order for my users to receive notifications when new posts are available... the notification builder method is:

```<code>public void showNotification() {
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.app_logo)
                        .setContentTitle("new post")
                        .setContentText("Check it out guys");
        Intent resultIntent = new Intent(this, MainActivity.class);
        android.support.v4.app.TaskStackBuilder stackBuilder = android.support.v4.app.TaskStackBuilder.create(this);
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);
        mBuilder.setAutoCancel(true);
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        int mId;
        mId = 1;
        mNotificationManager.notify(mId, mBuilder.build());

    }
</code>```

and inside the onCreate() method I have

```<code>mDatabasePosts = FirebaseDatabase.getInstance().getReference().child("posts");
mDatabasePosts.addChildEventListener(new ChildEventListener() {

            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                showNotification();
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
</code>```

my users are notified when a child is added to the database but they are also receiving that notification when they load the app... I tried implementing this on the onPause() but then the notification appear everytime they press the home button. Please advise where do I go wrong.

Thanks!

答:
I've managed to figure it out. In case some of you are stuck as well this is a good way to do it...

so in your activity, create a class

```<code>public static boolean isBackgroundRunning(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
            if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                for (String activeProcess : processInfo.pkgList) {
                    if (activeProcess.equals(context.getPackageName())) {
                        //If your app is the process in foreground, then it's not in running in background
                        return false;
                    }
                }
            }
        }

        return true;
    }
</code>```

Credit Mihir Patel for this beautiful piece of work!

The code above will check if app is running in background or foreground

Then simply add that logic inside the onChildAdded method such as:

```<code>mDatabasePosts = FirebaseDatabase.getInstance().getReference().child("posts");
mDatabasePosts.addChildEventListener(new ChildEventListener() {

            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                if(isBackgroundRunning(MainActivity.this)){

                showNotification();
                }
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
</code>```

and voila, you will only get notified when your app is in the background.

Body:
I implemented a notification builder inside a childEventListener in order for my users to receive notifications when new posts are available... the notification builder method is:

public void showNotification() {
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.app_logo)
                        .setContentTitle("new post")
                        .setContentText("Check it out guys");
        Intent resultIntent = new Intent(this, MainActivity.class);
        android.support.v4.app.TaskStackBuilder stackBuilder = android.support.v4.app.TaskStackBuilder.create(this);
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);
        mBuilder.setAutoCancel(true);
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        int mId;
        mId = 1;
        mNotificationManager.notify(mId, mBuilder.build());

    }

and inside the onCreate() method I have

mDatabasePosts = FirebaseDatabase.getInstance().getReference().child("posts");
mDatabasePosts.addChildEventListener(new ChildEventListener() {

            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                showNotification();
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

my users are notified when a child is added to the database but they are also receiving that notification when they load the app... I tried implementing this on the onPause() but then the notification appear everytime they press the home button. Please advise where do I go wrong.

Thanks!

Body:
I've managed to figure it out. In case some of you are stuck as well this is a good way to do it...

so in your activity, create a class

public static boolean isBackgroundRunning(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
            if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                for (String activeProcess : processInfo.pkgList) {
                    if (activeProcess.equals(context.getPackageName())) {
                        //If your app is the process in foreground, then it's not in running in background
                        return false;
                    }
                }
            }
        }

        return true;
    }

Credit Mihir Patel for this beautiful piece of work!

The code above will check if app is running in background or foreground

Then simply add that logic inside the onChildAdded method such as:

mDatabasePosts = FirebaseDatabase.getInstance().getReference().child("posts");
mDatabasePosts.addChildEventListener(new ChildEventListener() {

            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                if(isBackgroundRunning(MainActivity.this)){

                showNotification();
                }
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

and voila, you will only get notified when your app is in the background.