问:
Edit and Continue on GDB
I know that E&C is a controversial subject and some say that it encourages a wrong approach to debugging, but still - I think we can agree that there are numerous cases when it is clearly useful - experimenting with different values of some constants, redesigning GUI parameters on-the-fly to find a good look... You name it.

My question is: Are we ever going to have E&C on GDB? I understand that it is a platform-specific feature and needs some serious cooperation with the compiler, the debugger and the OS (MSVC has this one easy as the compiler and debugger always come in one package), but... It still should be doable. I've even heard something about Apple having it implemented in their version of GCC [citation needed]. And I'd say it is indeed feasible.

Knowing all the hype about MSVC's E&C (my experience says it's the first thing MSVC users mention when asked "why not switch to Eclipse and gcc/gdb"), I'm seriously surprised that after quite some years GCC/GDB still doesn't have such feature. Are there any good reasons for that? Is someone working on it as we speak?

答:
It is a surprisingly non-trivial amount of work, encompassing many design decisions and feature tradeoffs.  Consider: you are debugging.  The debugee is suspended.  Its image in memory contains the object code of the source, and the binary layout of objects, the heap, the stacks.  The debugger is inspecting its memory image.  It has loaded debug information about the symbols, types, address mappings, pc (ip) to source correspondences.  It displays the call stack, data values.

Now you want to allow a particular set of possible edits to the code and/or data, without stopping the debuggee and restarting.  The simplest might be to change one line of code to another.  Perhaps you recompile that file or just that function or just that line.  Now you have to patch the debuggee image to execute that new line of code the next time you step over it or otherwise run through it.  How does that work under the hood?  What happens if the code is larger than the line of code it replaced?  How does it interact with compiler optimizations?  Perhaps you can only do this on a specially compiled for EnC debugging target.  Perhaps you will constrain possible sites it is legal to EnC.  Consider: what happens if you edit a line of code in a function suspended down in the call stack.  When the code returns there does it run the original version of the function or the version with your line changed?  If the original version, where does that source come from?

Can you add or remove locals?  What does that do to the call stack of suspended frames?  Of the current function?

Can you change function signatures?  Add fields to / remove fields from objects?  What about existing instances?  What about pending destructors or finalizers? Etc.

There are many, many functionality details to attend to to make any kind of usuable EnC work.  Then there are many cross-tools integration issues necessary to provide the infrastructure to power EnC.  In particular, it helps to have some kind of repository of debug information that can make available the before- and after-edit debug information and object code to the debugger.  For C++, the incrementally updatable debug information in PDBs helps.  Incremental linking may help too.

Looking from the MS ecosystem over into the GCC ecosystem, it is easy to imagine the complexity and integration issues across GDB/GCC/binutils, the myriad of targets, some needed EnC specific target abstractions, and the "nice to have but inessential" nature of EnC, are why it has not appeared yet in GDB/GCC.

Happy hacking!

(p.s. It is instructive and inspiring to look at what the Smalltalk-80 interactive programming environment could do.  In St80 there was no concept of "restart" -- the image and its object memory were always live, if you edited any aspect of a class you still had to keep running.  In such environments object versioning was not a hypothetical.)

ContentLicense: CC BY-SA 2.5

Title: Edit and Continue on GDB


来源: stackexchange

问:
Model a bag of liquid in Box 2D
How would I go about modeling a turgid bag of fluid in Box 2D, i.e. what physics equations would be useful in modeling this? The bag of water could move when touched, but that is the only interaction. Any places equations or models would be much appreciated!</p>

答: You could use a library for this. Google's LiquidFun is quite good http://google.github.io/liquidfun/</p>

ContentLicense: CC BY-SA 3.0

Title: Model a bag of liquid in Box 2D


问:
Find combinations of size r from a set with decreasing sum value
I have a set of numbers eg. [100,90,80,70,60,50] and want to find all combinations of size r=3 but in order of decreasing sum.
Arranging the numbers in decreasing order does not work eg.

```<code>(100, 90, 80) 270
(100, 90, 70) 260
(100, 90, 60) 250
(100, 90, 50) **240**
(100, 80, 70) **250**
(100, 80, 60) 240
</code>```

How can i go about finding such a combination set with decreasing sum value.

答:
The first (and naive) solution is to iterate over all posible permutations, and save those sets in a min-heap. At the end just remove all sets one by one.

run time: suppose x = n choose r, so O(xlogx)

The second one is a little more complicated:

* You need to save the minimum number you found out untill now

* now you are iterating exactly like your example with one change, to know what is the next set you are moving to, you have to replace every number in the current set with the next number in the array, and replace the max option that less than the minimum you are saving. and of course set the minimum to the new minimum.

run time: O((n choose r)*r)

Body:
I have a set of numbers eg. [100,90,80,70,60,50] and want to find all combinations of size r=3 but in order of decreasing sum.
Arranging the numbers in decreasing order does not work eg.

(100, 90, 80) 270
(100, 90, 70) 260
(100, 90, 60) 250
(100, 90, 50) **240**
(100, 80, 70) **250**
(100, 80, 60) 240

How can i go about finding such a combination set with decreasing sum value.


问:
SQL - building a certain query (intersect between two conditions)
i have a table that has two columns (that are relevant to my question) - Companies and Products.
It is providing me information about which companies use several Products.

For instance, lets say i want to retrieve all the companies that using Microsoft Office, i will query with a condition - product = Microsoft Office.

now, my question -
I need to build a query that will retrieve me all the companies that are using two products, not just one.
How should i build the query?
I think it should sort of use subquery maybe? because the SQL need to do two queries - one for each product i want, and than intersect both queries in order to find the companies that are in both lists...

Thanks alot for the helpers!

答:
Assuming there are no duplicates in the table, you could do something like:

```<code>SELECT COUNT(*), <name of the company column> FROM <table name> GROUP BY <name of the company column> HAVING COUNT(*) = 2;
</code>```

EDIT
To figure out who is using two specific products, use this instead:

```<code>SELECT COUNT(*), <name of the company column> FROM <table name> WHERE <name of product column> = '<name of 1st product>' OR <name of product column> = '<name of second product>' GROUP BY <name of the company column> HAVING COUNT(*) = 2;
</code>```

Body:
Assuming there are no duplicates in the table, you could do something like:

SELECT COUNT(*), <name of the company column> FROM <table name> GROUP BY <name of the company column> HAVING COUNT(*) = 2;

EDIT
To figure out who is using two specific products, use this instead:

SELECT COUNT(*), <name of the company column> FROM <table name> WHERE <name of product column> = '<name of 1st product>' OR <name of product column> = '<name of second product>' GROUP BY <name of the company column> HAVING COUNT(*) = 2;


问:
Can kotlin define dynamic method when class init?
My class:

```<code>class Demo {
    init {
        // define method here my some array:[a,b,c]
        // such as fun Demo.a,Demo.b...
    }
}
</code>```

Function names are dynamic.

Can Kotlin do this?

答: No, Kotlin is a statically typed language. That means that the type every variable and method must be known at compile-time.</p>

Body:
My class:

class Demo {
    init {
        // define method here my some array:[a,b,c]
        // such as fun Demo.a,Demo.b...
    }
}

Function names are dynamic.

Can Kotlin do this?


问:
How to change buffer size of SqlDataReader in C#?
I am using SqlDataReader for data migration. How can I increase the number of records inserting to the destination at a time?

答:
I want to increase the number of records inserting to the destination at a time.

Then this is unrelated to SqlDataReader, and you'll need to look at whatever tool you're using for the insert. If you're using SqlBulkCopy, then this should be as simple as changing the .BatchSize. If you're using other mechanisms, you'll have to be specific. For example, if you're using an SP to do the inserts that only handles one row at a time, one option might be to use MARS and overlapping async operations; I have a utility method that I use for this type of sequential fixed-depth overlapping (which is very different to what Parallel.ForEach would do, for example, even with a fixed max-DOP). If you're using an insert that works via TDS-based table-parameters, then: just buffer that much data locally before calling the operation. If you're using an ORM such as EF: refer to the ORM's insert documentation.

But: to emphasize: the one thing that doesn't get a vote on this is: the data-reader.


问:
Combining two MS Access queries
I have this query:

```<code>SELECT "I1" & "," & "I2" AS Item_set, Round(Sum([T1].Fuzzy_Value)/Count(*),15) AS Support
    FROM (SELECT *
    FROM Prune AS t
    WHERE t.Trans_ID IN

        (SELECT t1.Trans_ID FROM (

         SELECT *FROM Prune WHERE [Nama]="I1")  AS t1
         INNER JOIN (SELECT * FROM Prune WHERE [Nama]="I2")  AS t2 ON t1.Trans_ID = t2.Trans_ID)

    AND t.Nama IN ("I1","I2"))  AS T1;
</code>```

And ttrans query

```<code>SELECT Count([Trans_ID].[Trans_ID]) AS Expr1
FROM Trans_ID;
</code>```

I need to change Count (*) from :

```<code> SELECT "I1" & "," & "I2" AS Item_set, Round(Sum([T1].Fuzzy_Value)/Count(*),15)
</code>```

into ttrans query.

I've tried using

```<code>SELECT "I1" & "," & "I2" AS Item_set, Round(Sum([T1].Fuzzy_Value)/ttrans.Expr1,15) AS Support
FROM (SELECT *
FROM Prune AS t
WHERE t.Trans_ID IN

    (SELECT t1.Trans_ID FROM (

     SELECT *FROM Prune WHERE [Nama]="I1")  AS t1
     INNER JOIN (SELECT * FROM Prune WHERE [Nama]="I2")  AS t2 ON t1.Trans_ID = t2.Trans_ID)

AND t.Nama IN ("I1","I2"))  AS T1, ttrans;
</code>```

But I got error like this :

```<code>You tried to execute a query that does not include the specified expression
'Round(sum([T1].Fuzzy_Value/ttrans.Expr1,15)' as part of an aggregate function
</code>```

any idea how to fix it?

Note : I'm trying to find 2 combination of all item in transaction database and get a result like this

```<code>ITEM       Support
I1, I2     0.xxxxxxxxx
</code>```

where support is (total transaction containing item I1 and I2 / total transaction) -> note that I'm using ttrans query to get total transaction value

note2: I'm using MS Access
note3:

Ttrans table will look like this

```<code>Expr1
270200
</code>```

答:
somehow i find the answer :

i tried using

```<code>SELECT "I1" & "," & "I2" AS Item_set, Round(Sum([T1].Fuzzy_Value)/sum(ttrans.Expr1),15)
</code>```

it worked wonder

Title: Combining two MS Access queries

Body:
I have this query:

SELECT "I1" & "," & "I2" AS Item_set, Round(Sum([T1].Fuzzy_Value)/Count(*),15) AS Support
    FROM (SELECT *
    FROM Prune AS t
    WHERE t.Trans_ID IN

        (SELECT t1.Trans_ID FROM (

         SELECT *FROM Prune WHERE [Nama]="I1")  AS t1
         INNER JOIN (SELECT * FROM Prune WHERE [Nama]="I2")  AS t2 ON t1.Trans_ID = t2.Trans_ID)

    AND t.Nama IN ("I1","I2"))  AS T1;

And ttrans query

SELECT Count([Trans_ID].[Trans_ID]) AS Expr1
FROM Trans_ID;

I need to change Count (*) from :

 SELECT "I1" & "," & "I2" AS Item_set, Round(Sum([T1].Fuzzy_Value)/Count(*),15)

into ttrans query.

I've tried using

SELECT "I1" & "," & "I2" AS Item_set, Round(Sum([T1].Fuzzy_Value)/ttrans.Expr1,15) AS Support
FROM (SELECT *
FROM Prune AS t
WHERE t.Trans_ID IN

    (SELECT t1.Trans_ID FROM (

     SELECT *FROM Prune WHERE [Nama]="I1")  AS t1
     INNER JOIN (SELECT * FROM Prune WHERE [Nama]="I2")  AS t2 ON t1.Trans_ID = t2.Trans_ID)

AND t.Nama IN ("I1","I2"))  AS T1, ttrans;

But I got error like this :

You tried to execute a query that does not include the specified expression
'Round(sum([T1].Fuzzy_Value/ttrans.Expr1,15)' as part of an aggregate function

any idea how to fix it?

Note : I'm trying to find 2 combination of all item in transaction database and get a result like this

ITEM       Support
I1, I2     0.xxxxxxxxx

where support is (total transaction containing item I1 and I2 / total transaction) -> note that I'm using ttrans query to get total transaction value

note2: I'm using MS Access
note3:

Ttrans table will look like this

Expr1
270200

Body:
somehow i find the answer :

i tried using

SELECT "I1" & "," & "I2" AS Item_set, Round(Sum([T1].Fuzzy_Value)/sum(ttrans.Expr1),15)

it worked wonder


问:
HTTP Error 500.19 - Internal Server Error?
I'm moving a pretty basic site from Win 2003 to Win 2008 R2.  The site is getting the error listed below.  How can I diagnose this?  I moved a number of other sites between these 2 servers & this is the only on that is receiving this error.

I've seen the other posts on this issue, but none of them list a solution that works for me.

HTTP Error 500.19 - Internal Server Error

Error Code 0x8007000d

Config Source -1: 0:

UPDATE:

Here are some notes on what I checked:

1) Permissions via Process Monitor.  The config file is being opened correctly.

2) .Net version - Tried multiple settings
3) Integrated vs classic pipeline

4) change enabled 32 bit to true

5) I have not tried Aspnet_regiis.exe yet because the other sites on the new box work fine.

Next I'm going to try & comment out various items in the config file

答: In my case the issue was solved by running VS2017 in admin mode.</p>


问:
Python wrapper install gives "Command "python setup.py egg_info" failed with error code 1"
I've been trying to install this Python wrapper for the past two days. I went through all the other questions here on Stack Overflow. Tried literally everything, and nothing seems to work.

```<code>Processing /../../../../../wrappers/Python
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/private/tmp/pip-twPZdY-build/setup.py", line 50, in <module>
    **cffi_args
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/core.py", line 111, in setup
    _setup_distribution = dist = klass(attrs)
  File "/usr/local/lib/python2.7/site-packages/setuptools/dist.py", line 319, in __init__
    _Distribution.__init__(self, attrs)
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dist.py", line 287, in __init__
    self.finalize_options()
  File "/usr/local/lib/python2.7/site-packages/setuptools/dist.py", line 386, in finalize_options
    ep.load()(self, ep.name, value)
  File "/private/tmp/pip-twPZdY-build/.eggs/cffi-1.10.0-py2.7-macosx-10.11-x86_64.egg/cffi/setuptools_ext.py", line 188, in cffi_modules
    add_cffi_module(dist, cffi_module)
  File "/private/tmp/pip-twPZdY-build/.eggs/cffi-1.10.0-py2.7-macosx-10.11-x86_64.egg/cffi/setuptools_ext.py", line 49, in add_cffi_module
    execfile(build_file_name, mod_vars)
  File "/private/tmp/pip-twPZdY-build/.eggs/cffi-1.10.0-py2.7-macosx-10.11-x86_64.egg/cffi/setuptools_ext.py", line 25, in execfile
    exec(code, glob, glob)
  File "../ffi_build.py", line 34, in <module>
    ffi.set_source('../_ffi', None)
  File "/private/tmp/pip-twPZdY-build/.eggs/cffi-1.10.0-py2.7-macosx-10.11-x86_64.egg/cffi/api.py", line 612, in set_source
    raise ValueError("'module_name' must not contain '/': use a dotted "
ValueError: 'module_name' must not contain '/': use a dotted name to make a 'package.module' location

----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /private/tmp/pip-twPZdY-build/
</code>```

I've reinstalled everything at least twice, updated, tried sudo -H, but nothing seems to work. It seems like a problem with setuptools, but I have no idea how to fix it.

Mac OSX 10.11.6 (El Capitan)

Python 2.7.13

Pip 9.0.1

答: After carefully reading through the error message, I managed to find the file called ffi_build.py under the Python folder I was trying to bind. As stated in the error message, at line 34 there was a module naming statement that contained a '/'. By replacing that '/' with a '.' I solved the issue and managed to bind the Python wrapper with no issue whatsoever.</p>

Body:
I've been trying to install this Python wrapper for the past two days. I went through all the other questions here on Stack Overflow. Tried literally everything, and nothing seems to work.

Processing /../../../../../wrappers/Python
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/private/tmp/pip-twPZdY-build/setup.py", line 50, in <module>
    **cffi_args
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/core.py", line 111, in setup
    _setup_distribution = dist = klass(attrs)
  File "/usr/local/lib/python2.7/site-packages/setuptools/dist.py", line 319, in __init__
    _Distribution.__init__(self, attrs)
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dist.py", line 287, in __init__
    self.finalize_options()
  File "/usr/local/lib/python2.7/site-packages/setuptools/dist.py", line 386, in finalize_options
    ep.load()(self, ep.name, value)
  File "/private/tmp/pip-twPZdY-build/.eggs/cffi-1.10.0-py2.7-macosx-10.11-x86_64.egg/cffi/setuptools_ext.py", line 188, in cffi_modules
    add_cffi_module(dist, cffi_module)
  File "/private/tmp/pip-twPZdY-build/.eggs/cffi-1.10.0-py2.7-macosx-10.11-x86_64.egg/cffi/setuptools_ext.py", line 49, in add_cffi_module
    execfile(build_file_name, mod_vars)
  File "/private/tmp/pip-twPZdY-build/.eggs/cffi-1.10.0-py2.7-macosx-10.11-x86_64.egg/cffi/setuptools_ext.py", line 25, in execfile
    exec(code, glob, glob)
  File "../ffi_build.py", line 34, in <module>
    ffi.set_source('../_ffi', None)
  File "/private/tmp/pip-twPZdY-build/.eggs/cffi-1.10.0-py2.7-macosx-10.11-x86_64.egg/cffi/api.py", line 612, in set_source
    raise ValueError("'module_name' must not contain '/': use a dotted "
ValueError: 'module_name' must not contain '/': use a dotted name to make a 'package.module' location

----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /private/tmp/pip-twPZdY-build/

I've reinstalled everything at least twice, updated, tried sudo -H, but nothing seems to work. It seems like a problem with setuptools, but I have no idea how to fix it.

Mac OSX 10.11.6 (El Capitan)

Python 2.7.13

Pip 9.0.1


问:
iOS: Migration (Upgrade) from Swift 3 to Swift 4
Recent major update in iOS application development tool Xcode 9 supports Swift 3.2 & 4 programming language.

I've my app developed with Swift 3 version and I want to convert/migrate, complete source code from Swift 3 to Swift 4. During migration, it's showing me 354 errors.

These errors are fixable. The solution of error is suggested by Xcode itself. But there are 354 errors. How can I fix them all at once? Manual fixing of each error one-by-one will be a time-consuming activity.

Is there any feasible solution to fix all errors at once.

Here is a snapshot with the sample.

答:
We have a better option to fix this error at once. It can be solved out from Editor menu

Use this option to fix all the error at once in class.

Note: You cannot always rely on Xcode suggestions, but for migration case it will work in most of the case.

ContentLicense: CC BY-SA 4.0


问:
Why are virtual thunks necessary?
This question is about a (possible) implementation for virtual function calls (which I believe it is used by gcc).

Consider the following scenarios:

class F inherits from class D (and maybe others) which inherits from class B (not virtually). D overrides the virtual method f() declared in B; an object of type F is instantiated

class F inherits from class D (and maybe others) which inherits from class B (virtually). D overrides the virtual method f() declared in B; an object of type F is instantiated

(the only difference between these two scenarios is the way class B is inherited)

In scenario 1, in the vtable of object B, at the location destined for f() there is now a (non-virtual) thunk that says:

if you want to call f(), first change the this pointer with offset

(it is actually D that puts this thunk there)

In scenario 2, in the vtable of object B, at the location destined for f() there is now a (virtual) thunk that says:

if you want to call f(), first change the this pointer with the value stored at addr

(D cannot tell B exactly how much this pointer needs to be adjusted because it does not know the position of the B object in the final memory layout of the F object)

These assumptions were made by looking at the output of g++ -fdump-class-hierarchy in combination with g++ -S. Are they correct?

Now my question is: why is a virtual thunk necessary? Why can't F put a non-virtual thunk in B's virtual table (at the location for f())? Because when an F object needs to be instantiated, the compiler knows that f() was declared in B, but it was overridden in D. And it also knows the exact offset between the object B (-in-F) and the object D (-in-F) (which I think is the reason for the virtual thunk in the first place).

EDIT (added output of g++ -fdump-class-hierarchy and g++ -S)

Scenario 1:

g++ -fdump-class-hierarchy:

Vtable for F

...

48    (int (*)(...))D::_ZThn8_N1D1fEv (de-mangled: non-virtual thunk to D::f())

g++ -S:

_ZThn8_N1D1fEv:

.LFB16:

.cfi_startproc

subq    $8, %rdi    #,

jmp .LTHUNK0    #

.cfi_endproc

Scenario 2:

g++ -fdump-class-hierarchy:

Vtable for F

...

64    (int (*)(...))D::_ZTv0_n24_N1D1fEv (de-mangled: virtual thunk to D::f())

g++ -S:

_ZTv0_n24_N1D1fEv:

.LFB16:

.cfi_startproc

movq    (%rdi), %r10    #,

addq    -24(%r10), %rdi #,

jmp .LTHUNK0    #

.cfi_endproc

答:
I think I found the answer here:

"...There are several possible implementations of the thunks given the above information. Note in the following that we assume that prior to calling any vtable entry, the this pointer has been adjusted to point to the subobject corresponding to the vtable from which the vptr is fetched.

A. Since the offsets are always known at compile time, even for virtual bases, each thunk could be distinct, adding the known offset to this and branching to the target function.
  This would result in a thunk for each overrider at a distinct offset. As a result, a branch mispredict and possibly an instruction cache miss would occur each time the actual type changed for a reference at any given point in the code.

B. In the case of virtual inheritance, the offset, although known when the overrider is declared, may differ depending on derivations from the overrider's class. H and I above are the simplest example. H is a primary base for I, but the int member of I means that A is at a different offset from H in I than it was from a standalone H. Because of this, the ABI specifies that the secondary vtable for a virtual base A contain a vcall offset to H, so that a shared thunk can load the vcall offset, adding it to this, and branch to the target function H::f.
  This would result in fewer thunks, since for a inheritance hierarchy where A is a virtual base of H, and H::f overrides A::f, all instances of H in a larger hierarchy can use the same thunk. As a result, these thunks will cause fewer branch mispredictions and instruction cache misses. The tradeoff is that they must do a load before the offset add. Since the offset is smaller than the code for a thunk, the load should miss in cache less frequently, so better cache miss behavior should produce better results in spite of the 2 or more cycles required for the vcall offset load...."

It seems that the virtual thunk exists only for performance reasons. If I am wrong, please correct me.

Title: Why are virtual thunks necessary?


问:
What are the differences between Rust's `String` and `str`?
Why does Rust have String and str? What are the differences between String and str? When does one use String instead of str and vice versa? Is one of them getting deprecated?

答:
I have a C++ background and I found it very useful to think about String and &str in C++ terms:

A Rust String is like a std::string; it owns the memory and does the dirty job of managing memory.

A Rust &str is like a char* (but a little more sophisticated); it points us to the beginning of a chunk in the same way you can get a pointer to the contents of std::string.

Are either of them going to disappear? I do not think so. They serve two purposes:

String keeps the buffer and is very practical to use. &str is lightweight and should be used to "look" into strings. You can search, split, parse, and even replace chunks without needing to allocate new memory.

&str can look inside of a String as it can point to some string literal. The following code needs to copy the literal string into the String managed memory:

```<code>let a: String = "hello rust".into();
</code>```

The following code lets you use the literal itself without a copy (read-only though):

```<code>let a: &str = "hello rust";
</code>```

Body:
I have a C++ background and I found it very useful to think about String and &str in C++ terms:

A Rust String is like a std::string; it owns the memory and does the dirty job of managing memory.

A Rust &str is like a char* (but a little more sophisticated); it points us to the beginning of a chunk in the same way you can get a pointer to the contents of std::string.

Are either of them going to disappear? I do not think so. They serve two purposes:

String keeps the buffer and is very practical to use. &str is lightweight and should be used to "look" into strings. You can search, split, parse, and even replace chunks without needing to allocate new memory.

&str can look inside of a String as it can point to some string literal. The following code needs to copy the literal string into the String managed memory:

let a: String = "hello rust".into();

The following code lets you use the literal itself without a copy (read-only though):

let a: &str = "hello rust";


问:
How to catch which event hides my datepicker?
I have 5 step booking page. First page is to select the resource and quantity. It shows up the Next button and an datepicker is rendered. I can select the date and it shows up my second button Next to proceed. The problem is if i click anywhere on the DOM my datepicker sets to display: none; without specifying to do that anywhere in my code. How can i catch which event is causing that? How can i track what exactly sets display: none; to my datepicker ?

答: the chrome debug tools (right click, inspect, or [F12]) have a break on functionnality. I think if you break on attribute modification, you'll be able to inspect the call stack and find what is going on.


问:
Chat server for Rails
As it is evident that AJAX based chats do not scale, so what would you use for chats? Custom servers? Or any other methods?

Since with Rails each chat connection will take lots of memory, it won't be feasible to even have Rails run for each message. What do you recommend for use here?

答:
People often use Evented Ruby for handling problems like this https://github.com/eventmachine/eventmachine one of the examples in a talk I went to at railsconf 2010.

For example http://playtype.net/past/2009/3/11/mini_an_eventmachine_clone_of/ is a evented ruby implementation of an irc bot

Title: Chat server for Rails


问:
(very long string)modulo to int cpp
How to convert a (very long string) modulo say string="45345543534545623243464534545645" to int. I tried stoi(string)%someno . But compiler is showing "out of range" error.

答:
Process the string yourself, digit by digit. Say the modulo is m.

Start with int firstDigit = firstLetter-'0'; Set x to firstDigit % m.

While there are digits left, repeat nextDigit = nextLetter-'0';
and calculate x = (x*10 + nextDigit)% m.

Title: (very long string)modulo to int cpp


问:
Image does not display on Heroku
I have two images on a static web page in a Ruby on Rails web application. Both images are in the same place:

```<code>/app/assets/images
</code>```

The image tag for both is generated in the same way, barring some attributes:

```<code><%= image_tag("logo.png", alt: "Logo", width: 150) %>

<%= image_tag("image.jpeg", alt: "image", class: "img-responsive") %>
</code>```

Both work fine on the local server, but when I push to production, only the first image displays. The source shows the tag for the second image is not being processed correctly:

```<code><img alt="Logo" width="150" src="/assets/logo-9e9dd9c19ef18b3ef26e23f11d73a8817af6cea78a5d9e1a34691d591a780987.png" />

<img alt="image" class="img-responsive" src="/images/image.jpeg" />
</code>```

I don't understand why one works and the other doesn't?

In terms of context, the first image is PNG and part of the layout, rendered in application.html.erb. The second is part of the page view yielded into application.html.erb. Does that make a difference?

Any pointers in the right direction? Thanks for your help.

Regards,

Jonathan

答:
try below code:

config/environments/production.rb

```<code>config.assets.compile = true
</code>```

then run command:

```<code>RAILS_ENV=production rake assets:precompile
</code>```

then push all compiles files and menifest file to heroku.

Title: Image does not display on Heroku

Body:
I have two images on a static web page in a Ruby on Rails web application. Both images are in the same place:

/app/assets/images

The image tag for both is generated in the same way, barring some attributes:

<%= image_tag("logo.png", alt: "Logo", width: 150) %>

<%= image_tag("image.jpeg", alt: "image", class: "img-responsive") %>

Both work fine on the local server, but when I push to production, only the first image displays. The source shows the tag for the second image is not being processed correctly:

I don't understand why one works and the other doesn't?

In terms of context, the first image is PNG and part of the layout, rendered in application.html.erb. The second is part of the page view yielded into application.html.erb. Does that make a difference?

Any pointers in the right direction? Thanks for your help.

Regards,

Jonathan

Body:
try below code:

config/environments/production.rb

config.assets.compile = true

then run command:

RAILS_ENV=production rake assets:precompile

then push all compiles files and menifest file to heroku.


问:
Generate "Next Number" and add it to char*
I've tried to create a simple program that would allow me to increment a current integer and replace the last "n characters" in a char*.

However, no matter what I do, it simply outputs the same thing all over.

e.g Index = 1

Output:
XX201701
XX201702
XX201703
XX201704
...
XX201710

Could someone possibly tell me what am I doing wrong here?

```<code>#include<iostream>

using namespace std;

int index = 1;
char* GenerateNext()
{
    char* def = new char[9];
    char buffer[9];

    int counter = 0;
    int temp = index;

    while (temp != 0)
    {
        temp /= 10;
        counter++;
    }

    strncpy_s(def, 9, "XX160000", 8 - counter);
    _itoa_s(counter, buffer, 9, 10);
    strcat_s(def, 9, buffer);

    index++;
    return def;
}

int main()
{
    char* generated = GenerateNext();
    char* generated2 = GenerateNext();

    cout << generated << endl << generated2 << endl;

    delete[] generated;
    delete[] generated2;

    generated = nullptr;
    generated2 = nullptr;

    system("PAUSE");
    return 0;
}
</code>```

答:
I think you need to print index instead of a counter:

```<code>_itoa_s(index, buffer, 9, 10);
</code>```

Because value of counter will be 1 for 1..9 index so output string will remain the same.

Body:
I've tried to create a simple program that would allow me to increment a current integer and replace the last "n characters" in a char*.

However, no matter what I do, it simply outputs the same thing all over.

e.g Index = 1

Output:
XX201701
XX201702
XX201703
XX201704
...
XX201710

Could someone possibly tell me what am I doing wrong here?

#include<iostream>

using namespace std;

int index = 1;
char* GenerateNext()
{
    char* def = new char[9];
    char buffer[9];

    int counter = 0;
    int temp = index;

    while (temp != 0)
    {
        temp /= 10;
        counter++;
    }

    strncpy_s(def, 9, "XX160000", 8 - counter);
    _itoa_s(counter, buffer, 9, 10);
    strcat_s(def, 9, buffer);

    index++;
    return def;
}

int main()
{
    char* generated = GenerateNext();
    char* generated2 = GenerateNext();

    cout << generated << endl << generated2 << endl;

    delete[] generated;
    delete[] generated2;

    generated = nullptr;
    generated2 = nullptr;

    system("PAUSE");
    return 0;
}

Body:
I think you need to print index instead of a counter:

_itoa_s(index, buffer, 9, 10);

Because value of counter will be 1 for 1..9 index so output string will remain the same.


问:
Array of Objects Memory Allocation(Stack And Heap)
I have initialised an array of class objects, I'm curious about how they're allocated in memory(stack and heap), I found a piece of code from a textbook, it draws the memory allocation on the left below.

My Question is: why the memory allocation is not the one I draw on the right, in the code below, new Person[]{new Person("Simon", 20)...}, the new Person object would assign its memory address to the per[0],however, the per[0] is created in the heap when Person[] per = new Person[3] is executed.

Initialization of an array of class objects

```<code> class Person {
        private String name;
        private int age;
        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
    }

    public class Main {
        public static void main(String[] args) {
            Person[] per = new Person[]{new Person("Simon", 20), new Person("John", 21), new Person("Willy", 22)};
        }
    }
</code>```

Left(TextBook)

My Thought

答:
why the memory allocation is not the one I draw on the right,

It is on the right, but if you were to use the value

```<code>per
</code>```

or

```<code>per[0]
</code>```

that reference would be brought onto the stack.

Body:
I have initialised an array of class objects, I'm curious about how they're allocated in memory(stack and heap), I found a piece of code from a textbook, it draws the memory allocation on the left below.

My Question is: why the memory allocation is not the one I draw on the right, in the code below, new Person[]{new Person("Simon", 20)...}, the new Person object would assign its memory address to the per[0],however, the per[0] is created in the heap when Person[] per = new Person[3] is executed.

Initialization of an array of class objects

 class Person {
        private String name;
        private int age;
        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
    }

    public class Main {
        public static void main(String[] args) {
            Person[] per = new Person[]{new Person("Simon", 20), new Person("John", 21), new Person("Willy", 22)};
        }
    }

Left(TextBook)

My Thought

Body:
why the memory allocation is not the one I draw on the right,

It is on the right, but if you were to use the value

per

or

per[0]

that reference would be brought onto the stack.


问:
USB 3 XIMEA Camera xiQ: error while installing software package in ubuntu
Hi I recently buy a XIMEA xiQ USB 3 Camera. It's working in windows properly but when I try to use this in ubuntu facing below error although i follow same instruction as recommend in Website

See error:

sipl@sipl-System-Product-Name:~$ /opt/XIMEA/bin/xiCamToolxiAPI: XIMEA Camera API V4.13.18.00
  xiAPI: Adding camera context: dwID=11600851  ptr=880B4000 processID=00000BCA
  xiAPI: Create handles 1 Process 00000BCA
  xiAPI: Enable sensor
  xiAPI: xiReadFileFFS 'SensFPNCorrections' not found
  xiAPI: ScmCorrectorA::LoadAndParseConfigurationFile Warning: file SensFPNCorrections not found
  xiAPI: xiReadFileFFS 'SensFPNCorrections' not found
  xiAPI: ScmCorrectorA::LoadAndParseConfigurationFile Warning: file SensFPNCorrections not found
  xiAPI: Frequency 114 71
  xiAPI: Enabled 1 bandwidth 48000000
  xiAPI: Time needed to read BPL:142ms
  xiAPI: Successfully parsed BPL file, 1829 total corrected pixels
  xiAPI: SetGPIO 1 set to 8
  xiAPI: Frequency 50 31
  xiAPI: Enabled 1 bandwidth 48000000
  xiAPI: SetGPIO 1 set to 0
  xiAPI: AutoSetBandwidth measurement
  xiAPI: CalculateResources : Context 880B4000 ID 11600851 m_maxBytes=512 m_maxBufferSize=524288
  xiAPI: Failed to change thread scheduler, check user limit for realtime priority.
  xiAPI: AutoSetBandwidth measured 393Mbps. Safe margin 10% will be used.
  xiAPI: Current bandwidth limit auto-set to 353 Mbps (min:80Mbps,max:393Mbps)
  xiAPI: Frequency 50 31
  xiAPI: Enabled 1 bandwidth 44125000
  xiAPI: Frequency 46 2d
  xiAPI: Enabled 1 bandwidth 44125000
  xiAPI: ---- Device opened. Model:MQ013CG-E2 SN:11600851 FwF1: API:V4.13.18.00 ----
  xiAPI: XIA(8150):xiGetParam (hdr) Finished with ERROR: 106
  0x7ff69bebd940 ../../src/xiViewer/xiCore/xiApiWrapper.cpp L 338 :  "xiApi_GetParamInt(): xiGetParamInt(hdr) returned 106"
  xiAPI: XIA(8150):xiGetParam (hdr_kneepoint1:min) Finished with ERROR: 106
  0x7ff69bebd940 ../../src/xiViewer/xiCore/xiApiWrapper.cpp L 338 :  "xiApi_GetParamInt(): xiGetParamInt(hdr_kneepoint1:min) returned 106"
  xiAPI: XIA(8150):xiGetParam (hdr_kneepoint1:max) Finished with ERROR: 106
  0x7ff69bebd940 ../../src/xiViewer/xiCore/xiApiWrapper.cpp L 338 :  "xiApi_GetParamInt(): xiGetParamInt(hdr_kneepoint1:max) returned 106"

答:
Please create support ticket in the XIMEA public tracker:
https://www.ximea.com/support where our support personel
will help you to solve this issue. Also please include the
information about installed SW package version, camera model
and serial number. Thank you.

Best regards,
XIMEA Team


问:
Compute a confidence interval from sample data assuming unknown distribution
I have sample data for which I would like to compute a confidence interval, assuming a distribution that is not normal and is unknown. Basically, it looks like the distribution is Pareto.  But I don't know for sure.

The answers for the normal distribution:

Compute a confidence interval from sample data

Correct way to obtain confidence interval with scipy

答:
From the discussion on the other answer, I assume you want a confidence interval for the population mean, yes? (You have to have a confidence interval for some quantity, not the distribution itself.)

For all distributions with finite moments, the sampling distribution of the mean tends asymptotically to a normal distribution with mean equal to the population mean and variance equal to the population variance divided by n. So if you have a lot of data, $\mu \pm \Phi^{-1}(p) \sigma / \sqrt{n}$ should be a good approximation to the p-confidence interval of the population mean, even if the distribution is not normal.


问:
Akka http losing sender reference
After receiving a Future[httpResponse] I'm trying to send the message to the sender but I'm loosing the reference of the sender.

Here is the code of my receive method:

```<code>    def receive = {
        case Seq(method: HttpMethod, endpoint: String, payload: String) ⇒ {
          // I have the correct sender reference
          implicit val materializer: ActorMaterializer = ActorMaterializer(ActorMaterializerSettings(context.system)) // needed by singleRequest method below
          // I have the correct sender reference

          val response: Future[HttpResponse] = Http(context.system).singleRequest(HttpRequest(method = method, uri = endpoint, entity = payload))
          println("http request sent")
          // I have the correct sender reference
          response onSuccess {
            case HttpResponse(statusCode, _, entity, _) ⇒ {
              entity.dataBytes.runFold(ByteString.empty)(_ ++ _).foreach { body ⇒
                // NO Reference to sender
                sender ! HttpConsumerResponse(statusCode = statusCode, contentType = entity.contentType, body = body.utf8String)
              }
            }
            case _ => println("http request success 2")
          }

          response onFailure {
            case exception: Throwable ⇒ {
              println("http request failure")
              throw exception
            } // Adopting let-it-crash fashion by re-throwning the exception
          }
        }
        case _ => println("I am httpConsumerActor and I don't know")
      }
</code>```

If I change the code like this:

```<code>def receive = {
        case Seq(method: HttpMethod, endpoint: String, payload: String) ⇒ {
          // I have the correct sender reference
          implicit val materializer: ActorMaterializer = ActorMaterializer(ActorMaterializerSettings(context.system)) // needed by singleRequest method below
          // I have the correct sender reference

          val response: Future[HttpResponse] = Http(context.system).singleRequest(HttpRequest(method = method, uri = endpoint, entity = payload))
          println("http request sent")
          // I have the correct sender reference
          val mySender = sender
          response onSuccess {
            case HttpResponse(statusCode, _, entity, _) ⇒ {
              entity.dataBytes.runFold(ByteString.empty)(_ ++ _).foreach { body ⇒
                // NO Reference to sender
                mySender ! HttpConsumerResponse(statusCode = statusCode, contentType = entity.contentType, body = body.utf8String)
              }
            }
            case _ => println("http request success 2")
          }

          response onFailure {
            case exception: Throwable ⇒ {
              println("http request failure")
              throw exception
            } // Adopting let-it-crash fashion by re-throwning the exception
          }
        }
        case _ => println("I am httpConsumerActor and I don't know")
      }
</code>```

everything works, but I have to send the reference of the actor like with this line and I know this is not the best way to do this:

```<code>val mySender = sender
</code>```

答:
The reason your fist approach does not work is that you are "closing over mutable state", i.e. the sender() method is executed when the onComplete is executed, and does not contain the reference anymore. This is a fairly common mistake in Akka, we have all been there ! :)

The right solution, as you already found out yourself is to prestore the reference. There are other options such as "becoming" something else, but for your use I'd say that the pre-store is the right approach in terms of tradeoff between "nice" and "simple".

For reference see these resources: SO question, Blog post

Title: Akka http losing sender reference

Body:
After receiving a Future[httpResponse] I'm trying to send the message to the sender but I'm loosing the reference of the sender.

Here is the code of my receive method:

    def receive = {
        case Seq(method: HttpMethod, endpoint: String, payload: String) ⇒ {
          // I have the correct sender reference
          implicit val materializer: ActorMaterializer = ActorMaterializer(ActorMaterializerSettings(context.system)) // needed by singleRequest method below
          // I have the correct sender reference

          val response: Future[HttpResponse] = Http(context.system).singleRequest(HttpRequest(method = method, uri = endpoint, entity = payload))
          println("http request sent")
          // I have the correct sender reference
          response onSuccess {
            case HttpResponse(statusCode, _, entity, _) ⇒ {
              entity.dataBytes.runFold(ByteString.empty)(_ ++ _).foreach { body ⇒
                // NO Reference to sender
                sender ! HttpConsumerResponse(statusCode = statusCode, contentType = entity.contentType, body = body.utf8String)
              }
            }
            case _ => println("http request success 2")
          }

          response onFailure {
            case exception: Throwable ⇒ {
              println("http request failure")
              throw exception
            } // Adopting let-it-crash fashion by re-throwning the exception
          }
        }
        case _ => println("I am httpConsumerActor and I don't know")
      }

If I change the code like this:

def receive = {
        case Seq(method: HttpMethod, endpoint: String, payload: String) ⇒ {
          // I have the correct sender reference
          implicit val materializer: ActorMaterializer = ActorMaterializer(ActorMaterializerSettings(context.system)) // needed by singleRequest method below
          // I have the correct sender reference

          val response: Future[HttpResponse] = Http(context.system).singleRequest(HttpRequest(method = method, uri = endpoint, entity = payload))
          println("http request sent")
          // I have the correct sender reference
          val mySender = sender
          response onSuccess {
            case HttpResponse(statusCode, _, entity, _) ⇒ {
              entity.dataBytes.runFold(ByteString.empty)(_ ++ _).foreach { body ⇒
                // NO Reference to sender
                mySender ! HttpConsumerResponse(statusCode = statusCode, contentType = entity.contentType, body = body.utf8String)
              }
            }
            case _ => println("http request success 2")
          }

          response onFailure {
            case exception: Throwable ⇒ {
              println("http request failure")
              throw exception
            } // Adopting let-it-crash fashion by re-throwning the exception
          }
        }
        case _ => println("I am httpConsumerActor and I don't know")
      }

everything works, but I have to send the reference of the actor like with this line and I know this is not the best way to do this:

val mySender = sender


问:
Add java List in JsonObject return value
I want to add a list in the json return value. Here is my code -

```<code>    @RequestMapping(value = "/servicearea", produces="application/json")
    @ResponseBody
    public String ServiceArea(Model model, HttpServletRequest req, HttpServletResponse res)
    {

        List<ServiceArea> serviceLists = locationService.getAllServiceArea();

        JsonObject result = Json.createObjectBuilder()
                .add("message", "test")
                .add("serviceLists", serviceLists)
                .build();

        return result.toString();
    }
</code>```

'serviceLists' is the one that I want to add. I'm getting error in this line - .add("serviceLists", serviceLists). Error message is that JsonObjectBuilder is not applicable for the arguments.

Thanks in advance.

答:
Just create a pojo like this

```<code>class ReturnPojo {
    private String message;
    private List<ServiceArea> serviceLists;

    //getters and setters
}
</code>```

And from your controller you can do

```<code>ReturnPojo returnPojo = new ReturnPojo;
returnPojo.setMessage("test");
returnPojo.setServiceLists(serviceLists);

return returnPojo;
</code>```

Change the method signature to return ReturnPojo

Body:
I want to add a list in the json return value. Here is my code -

    @RequestMapping(value = "/servicearea", produces="application/json")
    @ResponseBody
    public String ServiceArea(Model model, HttpServletRequest req, HttpServletResponse res)
    {

        List<ServiceArea> serviceLists = locationService.getAllServiceArea();

        JsonObject result = Json.createObjectBuilder()
                .add("message", "test")
                .add("serviceLists", serviceLists)
                .build();

        return result.toString();
    }

'serviceLists' is the one that I want to add. I'm getting error in this line - .add("serviceLists", serviceLists). Error message is that JsonObjectBuilder is not applicable for the arguments.

Thanks in advance.

Body:
Just create a pojo like this

class ReturnPojo {
    private String message;
    private List<ServiceArea> serviceLists;

    //getters and setters
}

And from your controller you can do

ReturnPojo returnPojo = new ReturnPojo;
returnPojo.setMessage("test");
returnPojo.setServiceLists(serviceLists);

return returnPojo;

Change the method signature to return ReturnPojo


问:
Add property to an array of objects
I have an array of objects as shown below

```<code>Object {Results:Array[2]}
     Results:Array[2]
[0-1]
0:Object
       id=1
       name: "Rick"
1:Object
       id=2
       name:'david'
</code>```

I want to add one more property named Active to each element of this array of Objects.

The final outcome should be as follows.

```<code>Object {Results:Array[2]}
     Results:Array[2]
[0-1]
0:Object
       id=1
       name: "Rick"
       Active: "false"
1:Object
       id=2
       name:'david'
       Active: "false"
</code>```

Can someone please let me know how to achieve this.

答:
Use Array.prototype.map()

Results.map(obj => ({ ...obj, Active: 'false' }))
```

Read the documentation for more information.

Title: Add property to an array of objects

Body:
I have an array of objects as shown below

Object {Results:Array[2]}
     Results:Array[2]
[0-1]
0:Object
       id=1
       name: "Rick"
1:Object
       id=2
       name:'david'

I want to add one more property named Active to each element of this array of Objects.

The final outcome should be as follows.

Object {Results:Array[2]}
     Results:Array[2]
[0-1]
0:Object
       id=1
       name: "Rick"
       Active: "false"
1:Object
       id=2
       name:'david'
       Active: "false"

Can someone please let me know how to achieve this.

Body:
Use Array.prototype.map()

Results.map(obj => ({ ...obj, Active: 'false' }))

Read the documentation for more information.


问:
FirebaseApp name [DEFAULT] already exists
I'm trying to manually initialize FirebaseApp on Application but getting this error.

```<code>public class BaseApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        FirebaseOptions firebaseOptions = new FirebaseOptions.Builder()
              .setDatabaseUrl("[DATABASE_URL]")
              .setApiKey("API_KEY")
              .setApplicationId("PROJECT_ID").build();
        FirebaseApp.initializeApp(getApplicationContext(),firebaseOptions);

        if (!FirebaseApp.getApps(this).isEmpty()) {
            FirebaseDatabase.getInstance().setPersistenceEnabled(true);
        }
    }
</code>```

Assume that I set the firebaseOptions value accordingly.
I am expecting that this will set values for FirebaseApp.

Did I missed something? FirebaseApp Documentation

The default app instance is initialized on app startup by
  FirebaseInitProvider. This is added to the app's manifest by Gradle
  manifest merging. If the app is using a different build system the
  provider needs to be manually added to the app's manifest.

Alternatively initializeApp(Context, FirebaseOptions) initializes the
  default app instance. This method should be invoked from Application.
  This is also necessary if it is used outside of the application's main
  process.

```<code>   FATAL EXCEPTION: main
    Process: com.sample.android, PID: 5490
    java.lang.RuntimeException: Unable to create application com.android.tools.fd.runtime.BootstrapApplication: java.lang.IllegalStateException: FirebaseApp name [DEFAULT] already exists!
    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4331)
    at android.app.ActivityThread.access$1500(ActivityThread.java:135)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5001)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:801)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:617)
    at dalvik.system.NativeStart.main(Native Method)
    Caused by: java.lang.IllegalStateException: FirebaseApp name [DEFAULT] already exists!
    at com.google.android.gms.common.internal.zzab.zza(Unknown Source)
    at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
    at com.sample.android.activities.BcodeApplication.onCreate(BcodeApplication.java:21)
    at com.android.tools.fd.runtime.BootstrapApplication.onCreate(BootstrapApplication.java:369)
    at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1007)
    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4328)
    at android.app.ActivityThread.access$1500(ActivityThread.java:135)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5001)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:801)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:617)
    at dalvik.system.NativeStart.main(Native Method)
</code>```

答:
Use this </p>

```<code>FirebaseOptions options = new FirebaseOptions.Builder()
    .setApiKey(apiKey)
    .setApplicationId(appId)
    .setDatabaseUrl(firebaseBaseUrl)
    .build();

boolean hasBeenInitialized=false;
List<FirebaseApp> firebaseApps = FirebaseApp.getApps(mContext);
for(FirebaseApp app : firebaseApps){
    if(app.getName().equals(FirebaseApp.DEFAULT_APP_NAME)){
        hasBeenInitialized=true;
        finestayApp = app;
    }
}

if(!hasBeenInitialized) {
    finestayApp = FirebaseApp.initializeApp(mContext, options);
}
</code>```

Body:
I'm trying to manually initialize FirebaseApp on Application but getting this error.

public class BaseApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        FirebaseOptions firebaseOptions = new FirebaseOptions.Builder()
              .setDatabaseUrl("[DATABASE_URL]")
              .setApiKey("API_KEY")
              .setApplicationId("PROJECT_ID").build();
        FirebaseApp.initializeApp(getApplicationContext(),firebaseOptions);

        if (!FirebaseApp.getApps(this).isEmpty()) {
            FirebaseDatabase.getInstance().setPersistenceEnabled(true);
        }
    }

Assume that I set the firebaseOptions value accordingly.
I am expecting that this will set values for FirebaseApp.

Did I missed something? FirebaseApp Documentation

The default app instance is initialized on app startup by
  FirebaseInitProvider. This is added to the app's manifest by Gradle
  manifest merging. If the app is using a different build system the
  provider needs to be manually added to the app's manifest.

Alternatively initializeApp(Context, FirebaseOptions) initializes the
  default app instance. This method should be invoked from Application.
  This is also necessary if it is used outside of the application's main
  process.

   FATAL EXCEPTION: main
    Process: com.sample.android, PID: 5490
    java.lang.RuntimeException: Unable to create application com.android.tools.fd.runtime.BootstrapApplication: java.lang.IllegalStateException: FirebaseApp name [DEFAULT] already exists!
    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4331)
    at android.app.ActivityThread.access$1500(ActivityThread.java:135)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5001)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:801)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:617)
    at dalvik.system.NativeStart.main(Native Method)
    Caused by: java.lang.IllegalStateException: FirebaseApp name [DEFAULT] already exists!
    at com.google.android.gms.common.internal.zzab.zza(Unknown Source)
    at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
    at com.sample.android.activities.BcodeApplication.onCreate(BcodeApplication.java:21)
    at com.android.tools.fd.runtime.BootstrapApplication.onCreate(BootstrapApplication.java:369)
    at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1007)
    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4328)
    at android.app.ActivityThread.access$1500(ActivityThread.java:135)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5001)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:801)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:617)
    at dalvik.system.NativeStart.main(Native Method)

Body:
Use this

FirebaseOptions options = new FirebaseOptions.Builder()
    .setApiKey(apiKey)
    .setApplicationId(appId)
    .setDatabaseUrl(firebaseBaseUrl)
    .build();

boolean hasBeenInitialized=false;
List<FirebaseApp> firebaseApps = FirebaseApp.getApps(mContext);
for(FirebaseApp app : firebaseApps){
    if(app.getName().equals(FirebaseApp.DEFAULT_APP_NAME)){
        hasBeenInitialized=true;
        finestayApp = app;
    }
}

if(!hasBeenInitialized) {
    finestayApp = FirebaseApp.initializeApp(mContext, options);
}


问:
Two form's error message handling on same page in react.js
I have installed react using "create-react-app" command, and its running fine. I am trying to make login and registration on same page. i have one component file with name Loginregistration.js that have registration form and all related methods.

In LoginRegistration.js I have import "Login.js" that have all login related html and respective submit function.

On html presentation, its showing fine and both form calling there own respective APIs "register / login".

But as i have mapped both forms related error message as per return response code. But as I have import Login.js in LoginRegister.js, its showing message as per LoginRegister.js and respective place also.

please let me know what I m doing wrong. here is both files code  -

LoginRegister.js >>>>>

```<code>import React from 'react';
import DefaultLayout from '../Layout/DefaultLayout';
import { connect } from 'react-redux';
import { userSignupRequest } from '../actions/signupActions';
import { bindActionCreators } from 'redux';
import Login from './Login';

class LoginRegister extends React.Component {
    constructor(props) {
        super(props);
        document.title = "Login-Register";
        this.errorMapping = {"101": "Unexpected error occurred. Please try again later.",
    "102": "This email is already connected to a account.",
    "103": "First name cannot be empty",
    "104": "Incorrect first name",
    "105": "Last Name cannot be empty",
    "106": "Incorrect last name",
    "107": "Email cannot be empty",
    "108": "Incorrect email address",
    "109": "Password cannot be empty",
    "110": "password minimum length is 6 characters",
    "111": "password maximum length is 50 characters",
    "112": "Confirm password does not match",
    "113": "Phone no can not be empty",
    "114": "Incorrect user role"
}

        this.state = {first_name: '',last_name: '',email:'',password:'',c_password:'', phone_no:'',user_role:2, errmsg:''};

        this.handleInputChange = this.handleInputChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleInputChange(event) {
        this.setState({ [event.target.name]: event.target.value});
      }

    handleSubmit(event) {
        event.preventDefault();
        this.props.userSignupRequest(this.state);
    }

    render(){
        console.log(this.props.registerMessage);
        return (
            <DefaultLayout>
                <section id="page-title">

                    <div className="container clearfix">
                        <h1>My Account</h1>
                        <ol className="breadcrumb">
                            <li><a href="/">Home</a></li>
                            <li><a href="/Customer-list">Customer list</a></li>
                            <li className="active">Login</li>
                        </ol>
                    </div>

                </section>

                <section id="content">

                    <div className="content-wrap">

                        <div className="container clearfix">

                            <div className="col_one_third nobottommargin">
                                <Login />
                            </div>

                            <div className="col_two_third col_last nobottommargin">

                                <h3>Don't have an Account? Register Now.</h3>

                                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Unde, vel odio non dicta provident sint ex autem mollitia dolorem illum repellat ipsum aliquid illo similique sapiente fugiat minus ratione.</p>
                                <p id="msg">{this.state.registerMessage}</p>
                                <div>{this.props.registerMessage && this.props.registerMessage.status.map((msg, idx) => {
                                         if(msg === 100) { return <span key={idx} id="succ_msg">{this.errorMapping[msg]}</span>
                                         } else {
                                              return <span key={idx} id="err_msg">{this.errorMapping[msg]}</span>
                                        }
                                    })
                                }</div>

                                <form id="register-form" name="register-form" className="nobottommargin" method="post" onSubmit={this.handleSubmit}>

                                    <div className="col_half">
                                        <label htmlFor="register-form-name">First Name:</label>
                                        <input type="text" id="register-form-firstname" name="first_name" value={this.state.first_name} className="form-control" onChange={this.handleInputChange} />
                                    </div>

                                    <div className="col_half col_last">
                                        <label htmlFor="register-form-email">Last name:</label>
                                        <input type="text" id="register-form-lastname" name="last_name" value={this.state.last_name} className="form-control" onChange={this.handleInputChange} required={true}  />
                                    </div>

                                    <div className="clear"></div>

                                    <div className="col_half">
                                        <label htmlFor="register-form-email">Email Address:</label>
                                        <input type="text" id="register-form-email" name="email" value={this.state.email} className="form-control" onChange={this.handleInputChange} required={true}   />
                                    </div>

                                    <div className="col_half col_last">
                                        <label htmlFor="register-form-repassword">Phone no.:</label>
                                        <input type="text" id="register-form-phone" name="phone_no" value={this.state.phone_no} className="form-control" onChange={this.handleInputChange} />
                                    </div>

                                    <div className="clear"></div>

                                    <div className="col_half">
                                        <label htmlFor="register-form-password">Choose Password:</label>
                                        <input type="password" id="register-form-password" name="password" value={this.state.password} className="form-control" onChange={this.handleInputChange} />
                                    </div>

                                    <div className="col_half col_last">
                                        <label htmlFor="register-form-repassword">Re-enter Password:</label>
                                        <input type="password" id="register-form-repassword" name="c_password" value={this.state.c_password} className="form-control" onChange={this.handleInputChange}  />
                                    </div>
                                    <input type="hidden" name="user_role" value={this.state.user_role} className="form-control" />
                                    <div className="clear"></div>

                                    <div className="col_full nobottommargin">
                                        <button className="button button-3d button-black nomargin" id="reg-submit" name="register-form-submit" value="register">Register Now</button>
                                    </div>

                                </form>

                            </div>

                        </div>

                    </div>
                </section>

            </DefaultLayout>
        )
    }
}

function mapStateToProps(state){
    console.log("View data :"+JSON.stringify(state.data));
    return {
        registerMessage: state.data
    }
}
function mapDispatchToProps(dispatch) {
      return bindActionCreators({userSignupRequest: userSignupRequest}, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps) (LoginRegister);
</code>```

And Login.js is  >>>>>>

```<code>import React from 'react';
import { connect } from 'react-redux';
import { userSignInRequest } from '../actions/signupActions';
import { bindActionCreators } from 'redux';

class Login extends React.Component {
    constructor(props) {
        super(props);
        this.login_errorMapping = { "101": "Unexpected error occurred, Please try again later",
    "102": "Incorrect email or password.",
    "103": "Email cannot be empty",
    "104": "incorrect email address",
    "105": "Password cannot be empty",
    "106": "Your account  is deactivated"}
        this.state = {email:'',password:''};

        this.handleInputChange = this.handleInputChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleInputChange(event) {
        this.setState({ [event.target.name]: event.target.value});
      }

    handleSubmit(event) {
        event.preventDefault();
        this.props.userSignInRequest(this.state);
    }

    render(){
        console.log(this.props.loginMessage);

        return (
            <div className="well well-lg nobottommargin">
                <form id="login-form" name="login-form" className="nobottommargin" action="#" method="post" onSubmit={this.handleSubmit}>

                    <h3>Login to your Account</h3>
                    <div>{this.props.loginMessage && this.props.loginMessage.status.map((msg, idx) => {
                            return <span key={idx} id="err_msg">{this.login_errorMapping[msg]}</span>
                        })
                    }</div>
                    <div className="col_full">
                        <label htmlFor="login-form-username">Email:</label  >
                        <input type="text" id="login-form-username" name="email" value={this.state.email} className="form-control" onChange={this.handleInputChange} />
                    </div>

                    <div className="col_full">
                        <label htmlFor="login-form-password">Password:</label>
                        <input type="password" id="login-form-password" name="password" value={this.state.first_name} className="form-control" onChange={this.handleInputChange} />
                    </div>

                    <div className="col_full nobottommargin">
                        <button className="button button-3d nomargin" id="login-form-submit" name="login-form-submit" value="login">Login</button>
                        <a href="#" className="fright">Forgot Password?</a>
                    </div>

                </form>
            </div>
        );
    }
}

function mapStateToProps(state){
    console.log("View Login data :"+JSON.stringify(state.data));
    return {
        loginMessage: state.data
    }
}
function mapDispatchToProps(dispatch) {
      return bindActionCreators({userSignInRequest: userSignInRequest}, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps) (Login);
</code>```

答:
You Login component also uses the same error message that is set up for register component and hence the problem.

You need to make a few changes,

In you reducer, separate the login and register message into RegisterData and LoginData
and then change the mapStateToProps in the Login.js and LoginRegister.js
to be

```<code>function mapStateToProps(state){
    console.log("View Login data :"+JSON.stringify(state.data));
    return {
        loginMessage: state.LoginData
    }
}
</code>```

and

```<code> function mapStateToProps(state){
    console.log("View Login data :"+JSON.stringify(state.data));
    return {
        registerMessage: state.RegisterData
    }
}
</code>```

respectively

Body:
I have installed react using "create-react-app" command, and its running fine. I am trying to make login and registration on same page. i have one component file with name Loginregistration.js that have registration form and all related methods.

In LoginRegistration.js I have import "Login.js" that have all login related html and respective submit function.

On html presentation, its showing fine and both form calling there own respective APIs "register / login".

But as i have mapped both forms related error message as per return response code. But as I have import Login.js in LoginRegister.js, its showing message as per LoginRegister.js and respective place also.

please let me know what I m doing wrong. here is both files code  -

LoginRegister.js >>>>>

import React from 'react';
import DefaultLayout from '../Layout/DefaultLayout';
import { connect } from 'react-redux';
import { userSignupRequest } from '../actions/signupActions';
import { bindActionCreators } from 'redux';
import Login from './Login';

class LoginRegister extends React.Component {
    constructor(props) {
        super(props);
        document.title = "Login-Register";
        this.errorMapping = {"101": "Unexpected error occurred. Please try again later.",
    "102": "This email is already connected to a account.",
    "103": "First name cannot be empty",
    "104": "Incorrect first name",
    "105": "Last Name cannot be empty",
    "106": "Incorrect last name",
    "107": "Email cannot be empty",
    "108": "Incorrect email address",
    "109": "Password cannot be empty",
    "110": "password minimum length is 6 characters",
    "111": "password maximum length is 50 characters",
    "112": "Confirm password does not match",
    "113": "Phone no can not be empty",
    "114": "Incorrect user role"
}

        this.state = {first_name: '',last_name: '',email:'',password:'',c_password:'', phone_no:'',user_role:2, errmsg:''};

        this.handleInputChange = this.handleInputChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleInputChange(event) {
        this.setState({ [event.target.name]: event.target.value});
      }

    handleSubmit(event) {
        event.preventDefault();
        this.props.userSignupRequest(this.state);
    }

    render(){
        console.log(this.props.registerMessage);
        return (
            <DefaultLayout>

My Account

Home

Customer list

Login

                                <Login />

Don't have an Account? Register Now.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Unde, vel odio non dicta provident sint ex autem mollitia dolorem illum repellat ipsum aliquid illo similique sapiente fugiat minus ratione.

{this.state.registerMessage}

{this.props.registerMessage && this.props.registerMessage.status.map((msg, idx) => {
                                         if(msg === 100) { return {this.errorMapping[msg]}
                                         } else {
                                              return {this.errorMapping[msg]}
                                        }
                                    })
                                }

                                <form id="register-form" name="register-form" className="nobottommargin" method="post" onSubmit={this.handleSubmit}>

                                        First Name:
                                        <input type="text" id="register-form-firstname" name="first_name" value={this.state.first_name} className="form-control" onChange={this.handleInputChange} />

                                        Last name:
                                        <input type="text" id="register-form-lastname" name="last_name" value={this.state.last_name} className="form-control" onChange={this.handleInputChange} required={true}  />

                                        Email Address:
                                        <input type="text" id="register-form-email" name="email" value={this.state.email} className="form-control" onChange={this.handleInputChange} required={true}   />

                                        Phone no.:
                                        <input type="text" id="register-form-phone" name="phone_no" value={this.state.phone_no} className="form-control" onChange={this.handleInputChange} />

                                        Choose Password:
                                        <input type="password" id="register-form-password" name="password" value={this.state.password} className="form-control" onChange={this.handleInputChange} />

                                        Re-enter Password:
                                        <input type="password" id="register-form-repassword" name="c_password" value={this.state.c_password} className="form-control" onChange={this.handleInputChange}  />

                                    <input type="hidden" name="user_role" value={this.state.user_role} className="form-control" />

                                        <button className="button button-3d button-black nomargin" id="reg-submit" name="register-form-submit" value="register">Register Now</button>

                                </form>

            </DefaultLayout>
        )
    }
}

function mapStateToProps(state){
    console.log("View data :"+JSON.stringify(state.data));
    return {
        registerMessage: state.data
    }
}
function mapDispatchToProps(dispatch) {
      return bindActionCreators({userSignupRequest: userSignupRequest}, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps) (LoginRegister);

And Login.js is  >>>>>>

import React from 'react';
import { connect } from 'react-redux';
import { userSignInRequest } from '../actions/signupActions';
import { bindActionCreators } from 'redux';

class Login extends React.Component {
    constructor(props) {
        super(props);
        this.login_errorMapping = { "101": "Unexpected error occurred, Please try again later",
    "102": "Incorrect email or password.",
    "103": "Email cannot be empty",
    "104": "incorrect email address",
    "105": "Password cannot be empty",
    "106": "Your account  is deactivated"}
        this.state = {email:'',password:''};

        this.handleInputChange = this.handleInputChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleInputChange(event) {
        this.setState({ [event.target.name]: event.target.value});
      }

    handleSubmit(event) {
        event.preventDefault();
        this.props.userSignInRequest(this.state);
    }

    render(){
        console.log(this.props.loginMessage);

        return (

                <form id="login-form" name="login-form" className="nobottommargin" action="#" method="post" onSubmit={this.handleSubmit}>

Login to your Account

{this.props.loginMessage && this.props.loginMessage.status.map((msg, idx) => {
                            return {this.login_errorMapping[msg]}
                        })
                    }

                        Email:
                        <input type="text" id="login-form-username" name="email" value={this.state.email} className="form-control" onChange={this.handleInputChange} />

                        Password:
                        <input type="password" id="login-form-password" name="password" value={this.state.first_name} className="form-control" onChange={this.handleInputChange} />

                        <button className="button button-3d nomargin" id="login-form-submit" name="login-form-submit" value="login">Login</button>
                        Forgot Password?

                </form>

        );
    }
}

function mapStateToProps(state){
    console.log("View Login data :"+JSON.stringify(state.data));
    return {
        loginMessage: state.data
    }
}
function mapDispatchToProps(dispatch) {
      return bindActionCreators({userSignInRequest: userSignInRequest}, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps) (Login);

Body:
You Login component also uses the same error message that is set up for register component and hence the problem.

You need to make a few changes,

In you reducer, separate the login and register message into RegisterData and LoginData
and then change the mapStateToProps in the Login.js and LoginRegister.js
to be

function mapStateToProps(state){
    console.log("View Login data :"+JSON.stringify(state.data));
    return {
        loginMessage: state.LoginData
    }
}

and

 function mapStateToProps(state){
    console.log("View Login data :"+JSON.stringify(state.data));
    return {
        registerMessage: state.RegisterData
    }
}

respectively


问:
how to show tick mark and an overlay on image while clicking an image, but when i click other image it should hide and display the same on new image?
i want the image to be overlay-ed with any color and give a tick mark on it(As it is selected) allowing only one image at  a time. while clicking other image it should hide the previous one and show tick and overlay on new image.

```<code><div class="grid-two imageandtext">
                                    <figure>

                                        <img src="assets/images/painting.jpg" class="img-thumbnail">
                                        <div class="caption">
                                            <p>Painting</p>
                                        </div>
                                        <div class="imageandtext image_grid">
                                            <img src="assets/images/photography.jpg" class="img-thumbnail" >
                                            <div class="caption1">
                                                <p>Photography</p>
                                            </div></div>
                                        </figure>
                                    </div>
</code>```

it should display like below image

now it is working like this

https://jsfiddle.net/liza_susan/L8jyum77/

答:
Here is a start, using a pseudo element for the cover, a label and an input of type radio to take care of the selection.

I wrapped the image in a label, and when clicked, it simply checks the input.

In the CSS, when an input is checked, the .image_grid input:checked + .caption::after rule apply the properties to cover and show the check mark.

Updated fiddle

.caption {
  position: absolute;
  top: 0;
  left: 5px;                            /*  changed to match image_grid padding  */
  height: 100%;
  width: calc(100% - 5px);              /*  changed to match image_grid padding  */
  padding: 0 10px;
  box-sizing: border-box;
  pointer-events: none;
}
.caption p {
  display: inline-block;
  padding: 10px;
  color: #fff;
  background: rgba(0,0,0,0.5);
  font-family: 'Myriad Pro regular';
  font-size: 15.31px;
}
.imageandtext {
  position: relative;
}
.image_grid {
  display: inline-block;
  padding-left: 5px;
}
.image_grid img {                       /*  added rule  */
  display: block;
}
.image_grid input {
  display: none;
}
.image_grid input:checked + .caption {
  background: rgba(0,0,0,0.5);
}
.image_grid input:checked + .caption::after {
  content: '✔';
  position: absolute;
  top: 50%; left: 50%;
  width: 70px; height: 70px;
  transform: translate(-50%,-50%);
  color: white;
  font-size: 60px;
  line-height: 80px;
  text-align: center;
  border: 2px solid white;
  border-radius: 50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid-two imageandtext">

  <div class="imageandtext image_grid">
    <label for="selimg1">
      <img src="http://yaitisme.com/images/getImage.jpg" class="img-thumbnail">
    </label>
    <input type="radio" name="selimg" id="selimg1">
    <div class="caption">
      <p>Painting</p>
    </div>
  </div>

  <div class="imageandtext image_grid">
    <label for="selimg2">
      <img src="http://yaitisme.com/images/getImage.jpg" class="img-thumbnail">
    </label>
    <input type="radio" name="selimg" id="selimg2">
    <div class="caption">
      <p>Photography</p>
    </div>
  </div>

</div></code>```

Based on a comment, here is a version where the caption is positioned inside the label, as a span (as label can only have inline element as children).

With this one doesn't need unique id on the input and can drop the for attribute, and no need to compensate for any padding and/or margin set on the image_grid.

Updated fiddle

Stack snippet

.caption {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  padding: 0 10px;
  box-sizing: border-box;
  pointer-events: none;
}
.caption span {
  display: inline-block;
  padding: 10px;
  color: #fff;
  background: rgba(0,0,0,0.5);
  font-family: 'Myriad Pro regular';
  font-size: 15.31px;
}
.image_grid {
  display: inline-block;
  padding-left: 25px;
}
.image_grid label {
  position: relative;
  display: inline-block;
}
.image_grid img {
  display: block;
}
.image_grid input {
  display: none;
}

.image_grid input:checked + .caption {
  background: rgba(0,0,0,0.5);
}
.image_grid input:checked + .caption::after {
  content: '✔';
  position: absolute;
  top: 50%; left: 50%;
  width: 70px; height: 70px;
  transform: translate(-50%,-50%);
  color: white;
  font-size: 60px;
  line-height: 80px;
  text-align: center;
  border: 2px solid white;
  border-radius: 50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid-two imageandtext">

  <div class="imageandtext image_grid">
    <label>
      <img src="http://yaitisme.com/images/getImage.jpg" class="img-thumbnail">
      <input type="radio" name="selimg">
      <span class="caption">
        <span>Painting</span>
      </span>
    </label>
  </div>

  <div class="imageandtext image_grid">
    <label>
      <img src="http://yaitisme.com/images/getImage.jpg" class="img-thumbnail">
      <input type="radio" name="selimg">
      <span class="caption">
        <span>Painting</span>
      </span>
    </label>
  </div>

</div></code>```

Body:
i want the image to be overlay-ed with any color and give a tick mark on it(As it is selected) allowing only one image at  a time. while clicking other image it should hide the previous one and show tick and overlay on new image.

Painting

Photography

it should display like below image

now it is working like this

https://jsfiddle.net/liza_susan/L8jyum77/

Body:
Here is a start, using a pseudo element for the cover, a label and an input of type radio to take care of the selection.

I wrapped the image in a label, and when clicked, it simply checks the input.

In the CSS, when an input is checked, the .image_grid input:checked + .caption::after rule apply the properties to cover and show the check mark.

Updated fiddle

.caption {
  position: absolute;
  top: 0;
  left: 5px;                            /*  changed to match image_grid padding  */
  height: 100%;
  width: calc(100% - 5px);              /*  changed to match image_grid padding  */
  padding: 0 10px;
  box-sizing: border-box;
  pointer-events: none;
}
.caption p {
  display: inline-block;
  padding: 10px;
  color: #fff;
  background: rgba(0,0,0,0.5);
  font-family: 'Myriad Pro regular';
  font-size: 15.31px;
}
.imageandtext {
  position: relative;
}
.image_grid {
  display: inline-block;
  padding-left: 5px;
}
.image_grid img {                       /*  added rule  */
  display: block;
}
.image_grid input {
  display: none;
}
.image_grid input:checked + .caption {
  background: rgba(0,0,0,0.5);
}
.image_grid input:checked + .caption::after {
  content: '✔';
  position: absolute;
  top: 50%; left: 50%;
  width: 70px; height: 70px;
  transform: translate(-50%,-50%);
  color: white;
  font-size: 60px;
  line-height: 80px;
  text-align: center;
  border: 2px solid white;
  border-radius: 50%;
}

<div class="grid-two imageandtext">

  <div class="imageandtext image_grid">
    <label for="selimg1">
      <img src="http://yaitisme.com/images/getImage.jpg" class="img-thumbnail">
    </label>
    <input type="radio" name="selimg" id="selimg1">
    <div class="caption">
      <p>Painting</p>
    </div>
  </div>

  <div class="imageandtext image_grid">
    <label for="selimg2">
      <img src="http://yaitisme.com/images/getImage.jpg" class="img-thumbnail">
    </label>
    <input type="radio" name="selimg" id="selimg2">
    <div class="caption">
      <p>Photography</p>
    </div>
  </div>

</div>

Based on a comment, here is a version where the caption is positioned inside the label, as a span (as label can only have inline element as children).

With this one doesn't need unique id on the input and can drop the for attribute, and no need to compensate for any padding and/or margin set on the image_grid.

Updated fiddle

Stack snippet

.caption {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  padding: 0 10px;
  box-sizing: border-box;
  pointer-events: none;
}
.caption span {
  display: inline-block;
  padding: 10px;
  color: #fff;
  background: rgba(0,0,0,0.5);
  font-family: 'Myriad Pro regular';
  font-size: 15.31px;
}
.image_grid {
  display: inline-block;
  padding-left: 25px;
}
.image_grid label {
  position: relative;
  display: inline-block;
}
.image_grid img {
  display: block;
}
.image_grid input {
  display: none;
}

.image_grid input:checked + .caption {
  background: rgba(0,0,0,0.5);
}
.image_grid input:checked + .caption::after {
  content: '✔';
  position: absolute;
  top: 50%; left: 50%;
  width: 70px; height: 70px;
  transform: translate(-50%,-50%);
  color: white;
  font-size: 60px;
  line-height: 80px;
  text-align: center;
  border: 2px solid white;
  border-radius: 50%;
}

<div class="grid-two imageandtext">

  <div class="imageandtext image_grid">
    <label>
      <img src="http://yaitisme.com/images/getImage.jpg" class="img-thumbnail">
      <input type="radio" name="selimg">
      <span class="caption">
        <span>Painting</span>
      </span>
    </label>
  </div>

  <div class="imageandtext image_grid">
    <label>
      <img src="http://yaitisme.com/images/getImage.jpg" class="img-thumbnail">
      <input type="radio" name="selimg">
      <span class="caption">
        <span>Painting</span>
      </span>
    </label>
  </div>

</div>


问:
OWIN - Authentication.SignOut() doesn't seem to remove the cookie
I'm having some issues with OWIN Cookie authentication. I have a .Net site that has some MVC pages which uses cookie authentication and WebAPI resources protected by a bearer token.

When I log out, I delete the access token on the client, so subsequent API requests will not have the token in the header and will thus fail the authentication. This part is fine.

In the same manner, I would also like the log out to delete the cookie used by the MVC pages. I did the following on the server:

```<code>    [Route("Logout")]
    public IHttpActionResult Logout()
    {
        var ctx = Request.GetOwinContext();
        var authenticationManager = ctx.Authentication;
        authenticationManager.SignOut();
        return Ok();
    }
</code>```

However, after the calling Logout, I can still visit the protected MVC page even though the cookie would have supposedly been deleted by the Logout call.

It seems so simple, so I might have missed something.

Thanks,

答:
```<code> AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
 FormsAuthentication.SignOut();
 Session.Abandon();
</code>```

Body:
I'm having some issues with OWIN Cookie authentication. I have a .Net site that has some MVC pages which uses cookie authentication and WebAPI resources protected by a bearer token.

When I log out, I delete the access token on the client, so subsequent API requests will not have the token in the header and will thus fail the authentication. This part is fine.

In the same manner, I would also like the log out to delete the cookie used by the MVC pages. I did the following on the server:

    [Route("Logout")]
    public IHttpActionResult Logout()
    {
        var ctx = Request.GetOwinContext();
        var authenticationManager = ctx.Authentication;
        authenticationManager.SignOut();
        return Ok();
    }

However, after the calling Logout, I can still visit the protected MVC page even though the cookie would have supposedly been deleted by the Logout call.

It seems so simple, so I might have missed something.

Thanks,


问:
How to Click the label element in selenium
```<code>WebDriver driver=new FirefoxDriver();
driver.get("http://192.168.0.133/tiyorelease3");
driver.findElement(By.id("login_button")).click();
driver.findElement(By.id("login_button")).click();
driver.findElement(By.xpath("id(//label[text() = 'signup']/@for)")).click();
driver.close();
</code>```

答:
First of all please see How to Ask and providing a Minimal, Complete, and Verifiable example.

For clicking on the Register section on your given page, you need to click on the Login first using

```<code> driver.findElement(By.id("login_button")).click();
</code>```

and then wait for some time so that the Registration section is visible. You can then use this

```<code>  driver.findElement(By.cssSelector('i.fa.fa-file-text')).click();
</code>```

to click on the Register section.

Body:
First of all please see How to Ask and providing a Minimal, Complete, and Verifiable example.

For clicking on the Register section on your given page, you need to click on the Login first using

 driver.findElement(By.id("login_button")).click();

and then wait for some time so that the Registration section is visible. You can then use this

  driver.findElement(By.cssSelector('i.fa.fa-file-text')).click();

to click on the Register section.


问:
How to detect if ASP.NET is enabled in IIS 7
The challenge is to determine whether ASP.NET is enabled within IIS7 in a reliable and correct way.

Enabling/Disabling is done in this case by going into:

```<code>Server Manager ->
    Roles ->
        Web Server (IIS) ->
            Remove Role Services ->
                Remove ASP.NET
</code>```

The natural place to determine this should be within the applicationHost.config file. However, with ASP.NET enabled or disabled, we still have the "ManagedEngine" module available, and we still have the isapi filter record in the  tag.

The best I can find at the moment is to check if the <isapiCgiRestriction> tag includes the aspnet_isapi.dll, or that the ASPNET trace provider is available.

However these aren't detecting the presence of the ASP.NET config directly, just a side effect that could conceivably be reconfigured by the user.

I'd rather do this by examining the IIS configuration/setup rather than the OS itself, if possible, although enumerating the Roles & Services on the server might be acceptable if we can guarantee that this technique will always work whenever IIS7 is used.

Update

Thanks for the responses. Clarifying exactly what I want to do, I'm pulling settings from a variety of places in the server's configuration into a single (readonly) view to show what the user needs to have configured to allow the software to work.

One of the settings I need to bring in is this one:

The one highlighted in red.

I don't need to manipulate the setting, just reproduce it. I want to see whether the user checked the ASP.NET box when they added the IIS role to the server, as in this example they clearly didn't.

I'd like to do this by looking at something reliable in IIS rather than enumerating the role services because I don't want to add any platform specific dependencies on the check that I don't need. I don't know if it will ever be possible to install IIS7 on a server that doesn't have the Roles/Services infrastructure, but in preference, I'd rather not worry about it. I also have a load of libraries for scrubbing around IIS already.

However, I'm also having trouble finding out how to enumerate the Roles/Services at all, so if there's a solution that involves doing that, it would certainly be useful, and much better than checking the side effect of having the ASPNET trace provider lying around.

Unfortunately, if you don't check the ASP.NET button, you can still get the ManagedEngine module in the IIS applicationHost.config file, so it's not a reliable check. You can also have ASP.NET mapped as an isapi filter, so checking them isn't enough. These things are especially problematic in the case where ASP.NET was installed but has been removed.

It looks like the best solution would be to examine the Role Services. However, API information on this is looking pretty rare, hence the cry for help.

答:
So do you want the easy way? Make a nice pretty .aspx page that displays as HTML with an error block in a div in a placeholder saying "You need to install ASP.NET" and have it change on ASP.NET being installed to instead say "ASP.NET is installed" and then just have the tool launch this webpage in the default browser after copying it to the directory identified in IIS as the *:80 site (or create the directory mapping in IIS programmatically by altering the XML and then removing it later)

May not be the most elegant but it does ensure that testing shows what features are truly installed versus what's in an XML file.

Because that will scream "do it the lazy ignorant way" I'll remind you that the only way for me to know in javascript what features I can use is to test them before I try to use them, or assume they're there and watch it blow up. My point is, it doesn't matter what gets reported in a file, it matters what you can actually use. Just because C:\Windows\Micrsoft.Net\Framework\v3.xxxxxxxx exists and has files doesn't mean the dll's are registered in the GAC, does it?

Body:
The challenge is to determine whether ASP.NET is enabled within IIS7 in a reliable and correct way.

Enabling/Disabling is done in this case by going into:

Server Manager ->
    Roles ->
        Web Server (IIS) ->
            Remove Role Services ->
                Remove ASP.NET

The natural place to determine this should be within the applicationHost.config file. However, with ASP.NET enabled or disabled, we still have the "ManagedEngine" module available, and we still have the isapi filter record in the  tag.

The best I can find at the moment is to check if the <isapiCgiRestriction> tag includes the aspnet_isapi.dll, or that the ASPNET trace provider is available.

However these aren't detecting the presence of the ASP.NET config directly, just a side effect that could conceivably be reconfigured by the user.

I'd rather do this by examining the IIS configuration/setup rather than the OS itself, if possible, although enumerating the Roles & Services on the server might be acceptable if we can guarantee that this technique will always work whenever IIS7 is used.

Update

Thanks for the responses. Clarifying exactly what I want to do, I'm pulling settings from a variety of places in the server's configuration into a single (readonly) view to show what the user needs to have configured to allow the software to work.

One of the settings I need to bring in is this one:

The one highlighted in red.

I don't need to manipulate the setting, just reproduce it. I want to see whether the user checked the ASP.NET box when they added the IIS role to the server, as in this example they clearly didn't.

I'd like to do this by looking at something reliable in IIS rather than enumerating the role services because I don't want to add any platform specific dependencies on the check that I don't need. I don't know if it will ever be possible to install IIS7 on a server that doesn't have the Roles/Services infrastructure, but in preference, I'd rather not worry about it. I also have a load of libraries for scrubbing around IIS already.

However, I'm also having trouble finding out how to enumerate the Roles/Services at all, so if there's a solution that involves doing that, it would certainly be useful, and much better than checking the side effect of having the ASPNET trace provider lying around.

Unfortunately, if you don't check the ASP.NET button, you can still get the ManagedEngine module in the IIS applicationHost.config file, so it's not a reliable check. You can also have ASP.NET mapped as an isapi filter, so checking them isn't enough. These things are especially problematic in the case where ASP.NET was installed but has been removed.

It looks like the best solution would be to examine the Role Services. However, API information on this is looking pretty rare, hence the cry for help.