问:
Can not import name from X in python
i want use Temp-mail lib to create a user. i installed it by pip install.
when i want to call the class , it caused an error:

```<code>import email
File "C:\Users\11\Desktop\email.py", line 4, in <module>

from tempmail import TempMail
ImportError: cannot import name TempMail
</code>```

the code is :

```<code>import requests
from tempmail import TempMail

tm = TempMail(login='denis', domain='@gnail.pw')
print tm.get_mailbox()  # list of emails in denis@gnail.pw
</code>```

I'm sure there is a class TempMail in tempmail.py.

I have read about circular dependency but i do not figure out what the problem is.

edit:

totally , i want to use this site (temp-mail.ru/en) or something like this to generate email address , open it and confirm my registration from others website by click on the link, everything should be done in python and this process again and again when the new email arrived .
what library do you suggest ? temp-mail ?

last edit i added some lib and the error has been changed /

http://uupload.ir/files/48vt_untitled.jpg

http://uupload.ir/files/dfig_untitled2.jpg

I used another class mail (pythons guerrilla mail) and this error is appeared about the class name.

答:
There are 2 modules that install a package called tempmail make sure you install only one of those.

temp-mail

tempMail

You can install temp-mail: (you will need this)

```<code>pip install temp-mail
</code>```

You can install tempMail:

```<code>pip install tempMail
</code>```

or

```<code>pip install tempmail
</code>```

NOTE:

If you installed the second one try to remove it first:

```<code>pip uninstall tempMail
pip install temp-mail
</code>```

if it is not working try this:

```<code>pip uninstall tempmail
pip install temp-mail
</code>```

Title: Can not import name from X in python

Body:
i want use Temp-mail lib to create a user. i installed it by pip install.
when i want to call the class , it caused an error:

import email
File "C:\Users\11\Desktop\email.py", line 4, in <module>

from tempmail import TempMail
ImportError: cannot import name TempMail

the code is :

import requests
from tempmail import TempMail

tm = TempMail(login='denis', domain='@gnail.pw')
print tm.get_mailbox()  # list of emails in denis@gnail.pw

I'm sure there is a class TempMail in tempmail.py.

I have read about circular dependency but i do not figure out what the problem is.

edit:

totally , i want to use this site (temp-mail.ru/en) or something like this to generate email address , open it and confirm my registration from others website by click on the link, everything should be done in python and this process again and again when the new email arrived .
what library do you suggest ? temp-mail ?

last edit i added some lib and the error has been changed /

http://uupload.ir/files/48vt_untitled.jpg

http://uupload.ir/files/dfig_untitled2.jpg

I used another class mail (pythons guerrilla mail) and this error is appeared about the class name.

Body:
There are 2 modules that install a package called tempmail make sure you install only one of those.

temp-mail

tempMail

You can install temp-mail: (you will need this)

pip install temp-mail

You can install tempMail:

pip install tempMail

or

pip install tempmail

NOTE:

If you installed the second one try to remove it first:

pip uninstall tempMail
pip install temp-mail

if it is not working try this:

pip uninstall tempmail
pip install temp-mail


来源: stackexchange

问:
Class has no instance of setter '_scheduler'
I have a class which has a ViewChild _scheduler.  Im not really sure why it needs a setter though since i am only wanting to use it to get the markup related to it.  I am having some issues reading the error code since it isnt quite relating back to my files entirely as it is tracing X.template.dart so i cant quite see which line the issues are on.

I was looking at the html file, but it is actually just pointing to the closing tag to the Div.

答:
Any variable in dart that is prefixed with an "_" makes a variable private to that class.

https://www.dartlang.org/guides/language/language-tour (see important concepts bullet 6)

From the perspective of the parent class, the variable does not exist so the error is valid.

ContentLicense: CC BY-SA 3.0


问:
Using Groovy-Eclipse plugin to develop in Grails
I am evaluating Groovy/Grails for a new project and I am wondering: Can the free Groovy-Eclipse plugin be used to develop Grails applications, and if so, what are the limitations? I am aware of the SpringSource Tool Suite, which includes full support for Grails in Eclipse, but it also includes a bunch of other stuff I don't care about, so I'm looking for a lighter-weight alternative. </p>

答:
STS does have more features/plugins/etc. than regular Eclipse, but they're lazily-loaded on demand, so you don't notice them at all - STS is just as fast as regular Eclipse.

There is a lot of work being done to support Grails in STS (v2.5.2 will be released soon) that won't be a part of the Groovy-Eclipse plugin since it focuses more on Groovy. Also I've seen questions on the groovy-eclipse-user mailing list about differences in behavior between the plugin and STS where features are only available in STS.

So I don't see any reason to use plain Eclipse + Groovy plugin over STS.

ContentLicense: CC BY-SA 2.5


问:
Jackson does not convert nested Java 8 Optional from Javers Change object, what is special about it?
I am trying to send a list of Javers Changes as JSON via a REST api. While Jackson can handle Java 8 Optionals via loading the respective module it fails to serialize the Change object. When i create a class with Optionals myself the serialization works as expected.

To reproduce one can run the following groovy script:

```<code>import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module
import org.javers.core.JaversBuilder
import org.javers.repository.jql.QueryBuilder

@Grapes([
  @Grab("com.fasterxml.jackson.core:jackson-core:2.8.3"),
  @Grab(group='com.fasterxml.jackson.datatype', module='jackson-datatype-jdk8', version='2.8.3'),
  @Grab('org.javers:javers-core:2.3.0')]
)

class Test {
  def bar
  def baz

  Test(){
    baz = "baz"
    bar = "bar"
  }
}

def test = new Test()

def javers = JaversBuilder.javers().build()

javers.commit("user", test)

test.bar = "foo"

javers.commit("user", test)

def objectMapper = new ObjectMapper()

objectMapper.registerModule(new Jdk8Module())

println objectMapper.writeValueAsString(javers.findChanges(QueryBuilder.anyDomainObject().build()))
</code>```

This outputs:

```<code>[
  {
    "commitMetadata": {
      "empty": false,
      "present": true
    },
    "propertyName": "bar",
    "left": "bar",
    "right": "foo",
    "affectedGlobalId": {
      "typeName": "Test"
    },
    "affectedLocalId": null,
    "affectedObject": {
      "empty": true,
      "present": false
    }
  }
]
</code>```

A custom class gets serialzed as expected:

```<code>import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module

@Grapes([
        @Grab("com.fasterxml.jackson.core:jackson-core:2.8.3"),
        @Grab(group='com.fasterxml.jackson.datatype', module='jackson-datatype-jdk8', version='2.8.3')]
)

class Test2 {
  def bar
  def baz
  Test2(){
    baz = Optional.of("baz")
    bar = "bar"
  }
}

def test = new Test2()

def objectMapper = new ObjectMapper()

objectMapper.registerModule(new Jdk8Module())

println objectMapper.writeValueAsString(test)
</code>```

Output:

```<code>{
  "bar": "bar",
  "baz": "baz"
}
</code>```

What is special about the Javers Change class, that Jackson refuses to serialze the Optionals?

答:
Just had a similar problem again and remembered my question here. In case someone needs a solution. Here is a custom Jackson Serializer for the Javers Optional:</p>

```<code>import java.io.IOException;
import org.javers.common.collections.Optional;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

@SuppressWarnings("rawtypes")
public class JaversOptionalSerializer extends StdSerializer<Optional> {

  private static final long serialVersionUID = 8330773428393250826L;

  public JaversOptionalSerializer() {
    super(Optional.class);
  }

  @Override
  public void serialize(final Optional value, final JsonGenerator gen, final SerializerProvider provider) throws IOException {
    if(value.isPresent()){
      JsonSerializer<Object> serializer = provider.findValueSerializer(value.get().getClass());
      serializer.serialize(value.get(), gen, provider);
    } else {
      gen.writeNull();
    }
  }
}
</code>```

Body:
I am trying to send a list of Javers Changes as JSON via a REST api. While Jackson can handle Java 8 Optionals via loading the respective module it fails to serialize the Change object. When i create a class with Optionals myself the serialization works as expected.

To reproduce one can run the following groovy script:

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module
import org.javers.core.JaversBuilder
import org.javers.repository.jql.QueryBuilder

@Grapes([
  @Grab("com.fasterxml.jackson.core:jackson-core:2.8.3"),
  @Grab(group='com.fasterxml.jackson.datatype', module='jackson-datatype-jdk8', version='2.8.3'),
  @Grab('org.javers:javers-core:2.3.0')]
)

class Test {
  def bar
  def baz

  Test(){
    baz = "baz"
    bar = "bar"
  }
}

def test = new Test()

def javers = JaversBuilder.javers().build()

javers.commit("user", test)

test.bar = "foo"

javers.commit("user", test)

def objectMapper = new ObjectMapper()

objectMapper.registerModule(new Jdk8Module())

println objectMapper.writeValueAsString(javers.findChanges(QueryBuilder.anyDomainObject().build()))

This outputs:

[
  {
    "commitMetadata": {
      "empty": false,
      "present": true
    },
    "propertyName": "bar",
    "left": "bar",
    "right": "foo",
    "affectedGlobalId": {
      "typeName": "Test"
    },
    "affectedLocalId": null,
    "affectedObject": {
      "empty": true,
      "present": false
    }
  }
]

A custom class gets serialzed as expected:

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module

@Grapes([
        @Grab("com.fasterxml.jackson.core:jackson-core:2.8.3"),
        @Grab(group='com.fasterxml.jackson.datatype', module='jackson-datatype-jdk8', version='2.8.3')]
)

class Test2 {
  def bar
  def baz
  Test2(){
    baz = Optional.of("baz")
    bar = "bar"
  }
}

def test = new Test2()

def objectMapper = new ObjectMapper()

objectMapper.registerModule(new Jdk8Module())

println objectMapper.writeValueAsString(test)

Output:

{
  "bar": "bar",
  "baz": "baz"
}

What is special about the Javers Change class, that Jackson refuses to serialze the Optionals?

Body:
Just had a similar problem again and remembered my question here. In case someone needs a solution. Here is a custom Jackson Serializer for the Javers Optional:

import java.io.IOException;
import org.javers.common.collections.Optional;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

@SuppressWarnings("rawtypes")
public class JaversOptionalSerializer extends StdSerializer<Optional> {

  private static final long serialVersionUID = 8330773428393250826L;

  public JaversOptionalSerializer() {
    super(Optional.class);
  }

  @Override
  public void serialize(final Optional value, final JsonGenerator gen, final SerializerProvider provider) throws IOException {
    if(value.isPresent()){
      JsonSerializer<Object> serializer = provider.findValueSerializer(value.get().getClass());
      serializer.serialize(value.get(), gen, provider);
    } else {
      gen.writeNull();
    }
  }
}


问:
Navigating Python modules with ctags in Vim?
I'm using Vim with ctags for Python and that works very well for classes, fields, etc, but what it doesn't seem to include are Python file names aka module names.  Is this possible?  I'd far prefer to type ta <module> to jump to a module, rather than navigate level-by-level with a file browser like NERDtree, and I'm very accustomed to doing this in Java, which works out since class names are file names.

答:
Exuberant tags (with --extra=+f) generates tags for python file-names (e.g. my_module.py), but not for the module name (e.g. my_module).  I ended up creating a modified version of the ptags script.  Save the following to a file named ptags somewhere in your path and make it executable:

```<code>#! /usr/bin/env python

# ptags
#
# Create a tags file for Python programs, usable with vi.
# Tagged are:
# - functions (even inside other defs or classes)
# - classes
# - filenames
# Warns about files it cannot open.
# No warnings about duplicate tags.

import sys, re, os
import argparse

tags = []    # Modified global variable!

def main():
    for root, folders, files in os.walk(args.folder_to_index):
        for filename in files:
            if filename.endswith('.py'):
                full_path = os.path.join(root, filename)
                treat_file(full_path)
        if not args.recursive:
            break

    if tags:
        fp = open(args.ctags_filename, 'w')
        tags.sort()
        for s in tags: fp.write(s)

expr = '^[ \t]*(def|class)[ \t]+([a-zA-Z0-9_]+)[ \t]*[:\(]'
matcher = re.compile(expr)

def treat_file(filename):
    try:
        fp = open(filename, 'r')
    except:
        sys.stderr.write('Cannot open %s\n' % filename)
        return
    base = os.path.basename(filename)
    if base[-3:] == '.py':
        base = base[:-3]
    s = base + '\t' + filename + '\t' + '1\n'
    tags.append(s)
    while 1:
        line = fp.readline()
        if not line:
            break
        m = matcher.match(line)
        if m:
            content = m.group(0)
            name = m.group(2)
            s = name + '\t' + filename + '\t/^' + content + '/\n'
            tags.append(s)

if __name__ == '__main__':
    p = argparse.ArgumentParser()
    p.add_argument('-f', '--ctags-filename', type=str, default='tags')
    p.add_argument('-R', '--recursive', action='store_true')
    p.add_argument('folder_to_index', type=str, default='.')
    args = p.parse_args()
    main()
</code>```

Now run the following to generate a tags file by recursively processing the current directory:

ptags -R -f tags_file_to_create /path/to/index

Body:
Exuberant tags (with --extra=+f) generates tags for python file-names (e.g. my_module.py), but not for the module name (e.g. my_module).  I ended up creating a modified version of the ptags script.  Save the following to a file named ptags somewhere in your path and make it executable:

#! /usr/bin/env python

# ptags
#
# Create a tags file for Python programs, usable with vi.
# Tagged are:
# - functions (even inside other defs or classes)
# - classes
# - filenames
# Warns about files it cannot open.
# No warnings about duplicate tags.

import sys, re, os
import argparse

tags = []    # Modified global variable!

def main():
    for root, folders, files in os.walk(args.folder_to_index):
        for filename in files:
            if filename.endswith('.py'):
                full_path = os.path.join(root, filename)
                treat_file(full_path)
        if not args.recursive:
            break

    if tags:
        fp = open(args.ctags_filename, 'w')
        tags.sort()
        for s in tags: fp.write(s)

expr = '^[ \t]*(def|class)[ \t]+([a-zA-Z0-9_]+)[ \t]*[:\(]'
matcher = re.compile(expr)

def treat_file(filename):
    try:
        fp = open(filename, 'r')
    except:
        sys.stderr.write('Cannot open %s\n' % filename)
        return
    base = os.path.basename(filename)
    if base[-3:] == '.py':
        base = base[:-3]
    s = base + '\t' + filename + '\t' + '1\n'
    tags.append(s)
    while 1:
        line = fp.readline()
        if not line:
            break
        m = matcher.match(line)
        if m:
            content = m.group(0)
            name = m.group(2)
            s = name + '\t' + filename + '\t/^' + content + '/\n'
            tags.append(s)

if __name__ == '__main__':
    p = argparse.ArgumentParser()
    p.add_argument('-f', '--ctags-filename', type=str, default='tags')
    p.add_argument('-R', '--recursive', action='store_true')
    p.add_argument('folder_to_index', type=str, default='.')
    args = p.parse_args()
    main()

Now run the following to generate a tags file by recursively processing the current directory:

ptags -R -f tags_file_to_create /path/to/index


问:
How to ensure lower server load in Django
I'm working on a Django web app. The app includes messages that will self-delete after a certain amount of time. I'm using timezone.now() as the sent time and the user inputs a timedelta to display the message until. I'm checking to see if the message should delete itself by checking if current time is after sent time plus the time delta. Will this place a heavy load on the server? How frequently will it automatically check? Is there a way that I can tell it to check once a minute (or otherwise set the frequency)?

Thanks

答:
How frequently will it automatically check?

who is "it" ? If you mean "the django process", then it will NOT check anything by itself. You will have to use either a cronjob or some async queue to take care of removing "dead" messages.

Is there a way that I can tell it to check once a minute (or otherwise set the frequency)?

Well yes, cf above. cronjobs are the simplest solution, async queues (like celery) are much more heavy-weight but if you have a lot of "off-band" processing (processes you want to launch from the request/response cycle BUT execute outside of it) then it's the way to go.

Will this place a heavy load on the server?

It's totally impossible to answer this. It depends on your exact models, the way you write the "check & clean" code, and, of course, data volumes. But using either a cronjob or an async queue this won't run within the django server process(es) itself, and can even be runned on another server as long as it can access the database. IOW the load will be on the database mostly (well, on the server running the process too of course but given your problem description a simple SQL delete query should be enough so..).


问:
Memory-efficient filtering of `DataFrame` rows
I have a large DataFrame object (1,440,000,000 rows). I operate at memory (swap includet) limit.

I need to extract a subset of the rows with certain value of a field. However if i do like that:

```<code>>>> SUBSET = DATA[DATA.field == value]
</code>```

I end with either MemoryError exception or crash.
Is there any way to filter rows explicitely - without calculating intermediate mask (DATA.field == value)?

I have found DataFrame.filter() and DataFrame.select() methods, but they operate on column labels/row indices rather than on the row data.

答:
Use query, it should be a bit faster:

```<code>df = df.query("field == value")
</code>```

Body:
I have a large DataFrame object (1,440,000,000 rows). I operate at memory (swap includet) limit.

I need to extract a subset of the rows with certain value of a field. However if i do like that:

>>> SUBSET = DATA[DATA.field == value]

I end with either MemoryError exception or crash.
Is there any way to filter rows explicitely - without calculating intermediate mask (DATA.field == value)?

I have found DataFrame.filter() and DataFrame.select() methods, but they operate on column labels/row indices rather than on the row data.

Body:
Use query, it should be a bit faster:

df = df.query("field == value")


问:
How do I make these three aligning divs responsive?
On my website home page (https://abbaproperty.000webhostapp.com/) I have three divs inline that look like this:

But when viewed on a slightly smaller scree (not mobile), it looks like this:

They're no longer the same height. Although I have added some responsive CSS so it does look like this on a smaller mobile device.

So my question here is that there is a sweet spot where these divs are not displayed very well responsively and I can't think of even the logical CSS to get around this.

HTML:

```<code><div class="container" style="width:100%; background-color:#205ba0; padding:30px;">

    <div class="col-md-offset-3 col-md-2" align="center" style="color:white; border:2px solid white; font-size:12px; padding:10px;">
        <div class="trip" style="background-color:white; margin-bottom:10px; padding-bottom:5px;">
            <img src="https://abbaproperty.000webhostapp.com/wp-content/uploads/2017/05/rent.png" style="height:100px;">
        </div>
        <h2 style="font-weight:bold;">Renting? Landlords welcome.</h2>
        A swift liason between landlords and tenants as a fair, independeant party, is just one of our services.<br><br>
        <a href="https://abbaproperty.000webhostapp.com/index.php/property-management/" style="color:white;">Find out more ></a>
    </div>

    <div class="col-md-2" align="center" style="color:white; border:2px solid white; font-size:12px; padding:10px;">
        <div class="trip" style="background-color:white; margin-bottom:15px;">
            <img src="https://abbaproperty.000webhostapp.com/wp-content/uploads/2017/05/val.png" style="height:100px;">
        </div>
        <h2 style="font-weight:bold;">Valuation? Sorted quickly.</h2>
        Providing some of the most effecient valuations in town, we're here to help you sort out an important step.<br><br>
        <a href="https://abbaproperty.000webhostapp.com/index.php/valuations/" style="color:white;">Find out more ></a>
    </div>

    <div class="col-md-2" align="center" style="color:white; border:2px solid white; font-size:12px; padding:10px;">
        <div class="trip" style="background-color:white; margin-bottom:10px; padding-bottom:5px;">
            <img src="https://abbaproperty.000webhostapp.com/wp-content/uploads/2017/05/sale.png" style="height:100px;">
        </div>
        <h2 style="font-weight:bold;">Selling? Now uncomplicated.</h2>
        We aim to make selling easy. Our trained estate agents are constantly available to help.<br><br>
        <a href="https://abbaproperty.000webhostapp.com/index.php/sell/" style="color:white;">Find out more ></a>
    </div>

</div>
</code>```

答:
Defined .container as flexbox and added additional styling properties as defined in CSS.

.container {
display: flex;
justify-content: space-around;
align-items: stretch;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container" style="width:100%; background-color:#205ba0; padding:30px;">

    <div class="col-md-offset-3 col-md-2" align="center" style="color:white; border:2px solid white; font-size:12px; padding:10px;">
        <div class="trip" style="background-color:white; margin-bottom:10px; padding-bottom:5px;">
            <img src="https://abbaproperty.000webhostapp.com/wp-content/uploads/2017/05/rent.png" style="height:100px;">
        </div>
        <h2 style="font-weight:bold;">Renting? Landlords welcome.</h2>
        A swift liason between landlords and tenants as a fair, independeant party, is just one of our services.<br><br>
        Find out more >
    </div>

    <div class="col-md-2" align="center" style="color:white; border:2px solid white; font-size:12px; padding:10px;">
        <div class="trip" style="background-color:white; margin-bottom:15px;">
            <img src="https://abbaproperty.000webhostapp.com/wp-content/uploads/2017/05/val.png" style="height:100px;">
        </div>
        <h2 style="font-weight:bold;">Valuation? Sorted quickly.</h2>
        Providing some of the most effecient valuations in town, we're here to help you sort out an important step.<br><br>
        Find out more >
    </div>

    <div class="col-md-2" align="center" style="color:white; border:2px solid white; font-size:12px; padding:10px;">
        <div class="trip" style="background-color:white; margin-bottom:10px; padding-bottom:5px;">
            <img src="https://abbaproperty.000webhostapp.com/wp-content/uploads/2017/05/sale.png" style="height:100px;">
        </div>
        <h2 style="font-weight:bold;">Selling? Now uncomplicated.</h2>
        We aim to make selling easy. Our trained estate agents are constantly available to help.<br><br>
        Find out more >
    </div>

</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
On my website home page (https://abbaproperty.000webhostapp.com/) I have three divs inline that look like this:

But when viewed on a slightly smaller scree (not mobile), it looks like this:

They're no longer the same height. Although I have added some responsive CSS so it does look like this on a smaller mobile device.

So my question here is that there is a sweet spot where these divs are not displayed very well responsively and I can't think of even the logical CSS to get around this.

HTML:

Renting? Landlords welcome.

        A swift liason between landlords and tenants as a fair, independeant party, is just one of our services.

        Find out more >

Valuation? Sorted quickly.

        Providing some of the most effecient valuations in town, we're here to help you sort out an important step.

        Find out more >

Selling? Now uncomplicated.

        We aim to make selling easy. Our trained estate agents are constantly available to help.

        Find out more >

Body:
Defined .container as flexbox and added additional styling properties as defined in CSS.

.container {
display: flex;
justify-content: space-around;
align-items: stretch;
}

<div class="container" style="width:100%; background-color:#205ba0; padding:30px;">

    <div class="col-md-offset-3 col-md-2" align="center" style="color:white; border:2px solid white; font-size:12px; padding:10px;">
        <div class="trip" style="background-color:white; margin-bottom:10px; padding-bottom:5px;">
            <img src="https://abbaproperty.000webhostapp.com/wp-content/uploads/2017/05/rent.png" style="height:100px;">
        </div>
        <h2 style="font-weight:bold;">Renting? Landlords welcome.</h2>
        A swift liason between landlords and tenants as a fair, independeant party, is just one of our services.<br><br>
        <a href="https://abbaproperty.000webhostapp.com/index.php/property-management/" style="color:white;">Find out more ></a>
    </div>

    <div class="col-md-2" align="center" style="color:white; border:2px solid white; font-size:12px; padding:10px;">
        <div class="trip" style="background-color:white; margin-bottom:15px;">
            <img src="https://abbaproperty.000webhostapp.com/wp-content/uploads/2017/05/val.png" style="height:100px;">
        </div>
        <h2 style="font-weight:bold;">Valuation? Sorted quickly.</h2>
        Providing some of the most effecient valuations in town, we're here to help you sort out an important step.<br><br>
        <a href="https://abbaproperty.000webhostapp.com/index.php/valuations/" style="color:white;">Find out more ></a>
    </div>

    <div class="col-md-2" align="center" style="color:white; border:2px solid white; font-size:12px; padding:10px;">
        <div class="trip" style="background-color:white; margin-bottom:10px; padding-bottom:5px;">
            <img src="https://abbaproperty.000webhostapp.com/wp-content/uploads/2017/05/sale.png" style="height:100px;">
        </div>
        <h2 style="font-weight:bold;">Selling? Now uncomplicated.</h2>
        We aim to make selling easy. Our trained estate agents are constantly available to help.<br><br>
        <a href="https://abbaproperty.000webhostapp.com/index.php/sell/" style="color:white;">Find out more ></a>
    </div>

</div>


问:
use C++ functions in .so file which is also placed in .aar
I have an Android project which is developed by using NDK. I have a A.cpp file inside cpp folder. For this project, I have imported another project as .aar library and dependent it for my first project.

So the project which is imported, is also developed by using NDK and it has B.cpp file. There are .so files for all arms (armeabi-v7a .etc) in this project. Now i want to call functions in B.cpp from A.cpp. How can I achieve this?

答:
You need the first SO file->A in the compile time of B.

Specifically in the linking stage. You cannot build a component B which links to A, without having no access to A in compile time.

Your library should link against A which you can manually extract from the aar, and you can use them for compile time, then ship your app by only providing your (B.so) file.


问:
Spring multiple autowire candidates
I would like to solve the following problem. Working on a spring project where I have a spring bean configuration class.

```<code>package package.bean_config_java;

@Configuration
@ComponentScan("package.bean_config_java")
public class Beans {

  @Bean
  public Customer customerHashmark() {
    Customer c = new Customer();
    c.setFormatter(hashmarkNameFormatter());

    return c;
  }

  @Bean
  public Customer customerUnderscore() {
    Customer c = new Customer();
    c.setFormatter(underscoreNameFormatter());

    return c;
  }

  @Bean
  public Formatter hashmarkNameFormatter() {
    return new HashmarkNameFormatter();
  }

  @Primary
  @Bean
  public Formatter underscoreNameFormatter() {
    return new UnderscoreNameFormatter();
  }
}
</code>```

After I ask for any of the customers from the container it returns with a customer with underscoreNameFormatter.

I tried to debug this, and found that spring calls customer.setFormatter only once during app start and the origin is my configuration class, so that looks ok, but in the end, when i get back my bean from the ctx.getBean method the formater is underscoreNameFormatter in all cases.

So is it even possible to override the injected value?

Note: With xml config it's possible to do this

```<code><bean class="package.Customer">
  <property name="formatter">
    <bean class="package.HashmarkNameFormatter" />
  </property>
</bean>
</code>```

答:
Name all your bean and inject them with @Qualifier.

```<code>package package.bean_config_java;

@Configuration
@ComponentScan("package.bean_config_java")
public class Beans {

  @Bean(name="hashmarkNameCustomer")
  public Customer customerHashmark() {
    Customer c = new Customer();
    c.setFormatter(hashmarkNameFormatter());

    return c;
  }

  @Bean(name="underscoreNameCustomer")
  public Customer customerUnderscore() {
    Customer c = new Customer();
    c.setFormatter(underscoreNameFormatter());

    return c;
  }

  @Bean
  public Formatter hashmarkNameFormatter() {
    return new HashmarkNameFormatter();
  }

  @Primary
  @Bean
  public Formatter underscoreNameFormatter() {
    return new UnderscoreNameFormatter();
  }
}
</code>```

When you need a Customer with HashmarkNameFormatter you just have to do :

```<code>@Autowired
@Qualifier("hashmarkNameCustomer")
Customer customer1;
</code>```

For Customer with UnderscoreNameFormatter :

```<code>@Autowired
@Qualifier("underscoreNameCustomer")
Customer customer2;
</code>```

Title: Spring multiple autowire candidates

Body:
I would like to solve the following problem. Working on a spring project where I have a spring bean configuration class.

package package.bean_config_java;

@Configuration
@ComponentScan("package.bean_config_java")
public class Beans {

  @Bean
  public Customer customerHashmark() {
    Customer c = new Customer();
    c.setFormatter(hashmarkNameFormatter());

    return c;
  }

  @Bean
  public Customer customerUnderscore() {
    Customer c = new Customer();
    c.setFormatter(underscoreNameFormatter());

    return c;
  }

  @Bean
  public Formatter hashmarkNameFormatter() {
    return new HashmarkNameFormatter();
  }

  @Primary
  @Bean
  public Formatter underscoreNameFormatter() {
    return new UnderscoreNameFormatter();
  }
}

After I ask for any of the customers from the container it returns with a customer with underscoreNameFormatter.

I tried to debug this, and found that spring calls customer.setFormatter only once during app start and the origin is my configuration class, so that looks ok, but in the end, when i get back my bean from the ctx.getBean method the formater is underscoreNameFormatter in all cases.

So is it even possible to override the injected value?

Note: With xml config it's possible to do this

<bean class="package.Customer">
  <property name="formatter">
    <bean class="package.HashmarkNameFormatter" />
  </property>
</bean>

Body:
Name all your bean and inject them with @Qualifier.

package package.bean_config_java;

@Configuration
@ComponentScan("package.bean_config_java")
public class Beans {

  @Bean(name="hashmarkNameCustomer")
  public Customer customerHashmark() {
    Customer c = new Customer();
    c.setFormatter(hashmarkNameFormatter());

    return c;
  }

  @Bean(name="underscoreNameCustomer")
  public Customer customerUnderscore() {
    Customer c = new Customer();
    c.setFormatter(underscoreNameFormatter());

    return c;
  }

  @Bean
  public Formatter hashmarkNameFormatter() {
    return new HashmarkNameFormatter();
  }

  @Primary
  @Bean
  public Formatter underscoreNameFormatter() {
    return new UnderscoreNameFormatter();
  }
}

When you need a Customer with HashmarkNameFormatter you just have to do :

@Autowired
@Qualifier("hashmarkNameCustomer")
Customer customer1;

For Customer with UnderscoreNameFormatter :

@Autowired
@Qualifier("underscoreNameCustomer")
Customer customer2;


问:
Saving Password with Md5
I am using Postgresql,hibernate and Java and I need to store a password. Can someone suggest me how to encrypt the password with md5. Else is there a better way to store secure password in the database

Thanks

答:
MD5 isn't an encryption algorithm - it is a cryptographic hash function. This is very different! You can store the hashed password in the database, but you cannot (in general) recover the password from the password's hash. This is by design.

In some cases it is possible to get the password back from the hash - for example if the password is a dictionary word it could be recovered using a dictionary attack. If the password is short enough and uses a characters from a limited range a brute force or rainbow table attack could recover the password. When you store a hashed password you should use a salt and key strengthening (for example PBKDF2) to make these attacks more difficult.

You should also be aware that MD5 is considered broken and it is recommended not to use it for new applications. There are better alternatives, for example SHA-256.

Title: Saving Password with Md5


答: Just add display: flex to .container (without wrap)

Title: How do I make these three aligning divs responsive?


问:
How do I trigger the browser's Basic Authentication dialog from an AJAX call?
I'm using basic authentication to secure a set of WCF web services exposed only inside our corporate network, and I was wondering if there was a way to trigger the browser's credentials dialog to appear from an AJAX call when the web service returns with a 401 error?

Currently my AJAX call receives the 401 as a regular failed request and doesn't prompt the browser to do anything. However, if I take the same URI and copy-paste it into into the browser's URL bar, the returned 401 correctly triggers the Basic Authentication dialog.

Is there any way to get the AJAX callback to tell the browser to pop up that dialog?

答:
I have faced almost the same 401 problem, except for my request was cross domain. But I hope the reason is the same. Following the instructions on developer.mozilla - Access control CORS I have finally succeeded with simple:

```<code>var xhttp=new XMLHttpRequest();
xhttp.withCredentials = true;
xhttp.open("GET", "https://my.foo.server/app/resource", true);
xhttp.send();
</code>```

I think the xhttp.withCredentials is the solution. It is not header! You let browser to communicate with server through cookies. The following answer explains a lot XHR2 withCredentials - which cookies are sent?

Without xhttp.withCredentials there was always 401 (Unauthorized). But using it, the browser added the required header Authorization:Basic dGVFooFooFooFoosaWVudA== or triggered the login dialog, when credentials were not available yet.

Body:
I have faced almost the same 401 problem, except for my request was cross domain. But I hope the reason is the same. Following the instructions on developer.mozilla - Access control CORS I have finally succeeded with simple:

var xhttp=new XMLHttpRequest();
xhttp.withCredentials = true;
xhttp.open("GET", "https://my.foo.server/app/resource", true);
xhttp.send();

I think the xhttp.withCredentials is the solution. It is not header! You let browser to communicate with server through cookies. The following answer explains a lot XHR2 withCredentials - which cookies are sent?

Without xhttp.withCredentials there was always 401 (Unauthorized). But using it, the browser added the required header Authorization:Basic dGVFooFooFooFoosaWVudA== or triggered the login dialog, when credentials were not available yet.


问:
Change color if repeated record
What formula can I use to change the color of the font when the sames value already appears previously in the document?</p>

答:
On the field you try to check if it has a previous match (for example ID)

```<code>{ID} = previous({ID}) Then crRed Else crBlack
</code>```

Hope it works

Title: Change color if repeated record

Body:
On the field you try to check if it has a previous match (for example ID)

{ID} = previous({ID}) Then crRed Else crBlack

Hope it works


问:
Unable to detect back press button click
I have viewpager with couple of fragments inside. I need to get confirmation when user presses back button. However, it doesn't get called unless I visit last page.

```<code>public class Create_Safety_CheckList_MainFragment extends Fragment
        implements View.OnClickListener, Observer {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_create_safety_checklist_pager_main, container, false);
        initializeUI();

        return view;
    }

    private void initializeUI() {
        setHeader(getResources().getString(R.string.safety_check_list_checklist_screen_name));
        addFragments();
        mPager = (ViewPager) view.findViewById(R.id.viewPager_home_screen_activity);
        mPagerAdapter = new ScreenSlidePagerAdapter(getChildFragmentManager());
        mPager.setOffscreenPageLimit(fragmentArrayList.size());
        mPager.setOnPageChangeListener(onPageChangeListener);
        mPager.setAdapter(mPagerAdapter);
//        mPager.setOnTouchListener(new View.OnTouchListener() {
//
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                v.getParent().requestDisallowInterceptTouchEvent(true);
//                return false;
//            }
//        });

        customTextViewChecklistName = (CustomTextView) view.findViewById(R.id.textView_New_Checklist_Name);
        if (createChecklistObservationModel.getChecklistName() != null)
            customTextViewChecklistName.setText(createChecklistObservationModel.getChecklistName());

    }

    private void addFragments() {
        createChecklistAdditionalTabFragment = new CreateChecklistAdditionalTabFragment();
        fragmentArrayList.add(createChecklistAdditionalTabFragment);

        Bundle bundle = getArguments();
        if (bundle != null) {
            if (bundle.containsKey("***")) {
                String response = spcl_databaseHandler.getSpecificChecklistAdditionals(bundle.getString("checklistID"));
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    JSONObject dataJsonObject = jsonObject.getJSONObject("Data");

                    JSONArray checkListAdditionalFieldDtoJsonArray = dataJsonObject.getJSONArray("***");
                    int additionalsLength = checkListAdditionalFieldDtoJsonArray.length();
                    if (additionalsLength > 0) {
dataJsonObject.getJSONArray("***").toString());
                        additionalInfoFragment = new Additional_Information_Fragment();
                        fragmentArrayList.add(additionalInfoFragment);
                    }

                    JSONArray jsonGroupsArray = dataJsonObject.getJSONArray("***");
                    int groupsLength = jsonGroupsArray.length();
                    for (int i = 0; i < groupsLength; i++) {
                        JSONObject groupJsonObject = (JSONObject) jsonGroupsArray.get(i);
                        JSONArray questionsJsonArray = groupJsonObject.getJSONArray("Questions");
                        int questionsLength = questionsJsonArray.length();
                        for (int j = 0; j < questionsLength; j++) {
                            checklistGroupsDiscussionQuestionOneFragment = new ChecklistGroupsDiscussionQuestionOneFragment();
                            checklistGroupsDiscussionQuestionOneFragment.setArguments(bundle1);
                            fragmentArrayList.add(checklistGroupsDiscussionQuestionOneFragment);
                        }

                        JSONArray subGroupsJsonArray = groupJsonObject.getJSONArray("SubGroups");
                        int subGroupsJsonArrayLength = subGroupsJsonArray.length();
                        for (int j = 0; j < subGroupsJsonArrayLength; j++) {
                            JSONObject subGroupObject = subGroupsJsonArray.getJSONObject(j);
                            JSONArray subGroupQuestionsJsonArray = subGroupObject.getJSONArray("Questions");
                            int subGroupQuestionsJsonArrayLength = subGroupQuestionsJsonArray.length();
                            for (int k = 0; k < subGroupQuestionsJsonArrayLength; k++) {
checklistGroupsDiscussionQuestionOneFragment = new ChecklistGroupsDiscussionQuestionOneFragment();                                fragmentArrayList.add(checklistGroupsDiscussionQuestionOneFragment);
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        questionsFragment = new Other_Questions_Fragment();
        membersFragment = new Inspection_Members_Fragment();

        fragmentArrayList.add(questionsFragment);
        fragmentArrayList.add(membersFragment);
    }

    private void setHeader(String headerTitle) {
    }

    ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int pageNumber) {
        }

        @Override
        public void onPageScrolled(int pageNumber, float positionOffset,
                                   int positionOffsetPixels) {
//            mPager.getParent().requestDisallowInterceptTouchEvent(true);
            showArrows(pageNumber);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imageView_Next:
                break;

            case R.id.imageView_Previous:
                break;

            case R.id.textView_Cancel :
                callToCloseDialog();
                break;

            default:
                break;
        }
    }

    private void callToCloseDialog() {
        if (SystemClock.elapsedRealtime() - mLastClickTime < 1000) {
            return;
        }
        mLastClickTime = SystemClock.elapsedRealtime();

        final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage(getResources().getString(R.string.cancel_dialog_message))
                .setTitle("Warning");

        builder.setPositiveButton(getResources().getString(R.string.cancel_dialog_yes_button), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked OK button
                getActivity().getSupportFragmentManager().popBackStackImmediate(getResources().getString(R.string.new_checklist_fragment), FragmentManager.POP_BACK_STACK_INCLUSIVE);
            }
        });

        builder.setNegativeButton(getResources().getString(R.string.cancel_dialog_no_button), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked cancel button
                dialog.dismiss();
            }
        });

        AlertDialog alert = builder.create();
        alert.show();
    }

    @Override
    public void update(Observable observable, Object o) {
    }

    /**
     * A simple pager adapter that represents 3 objects, in sequence.
     */
    private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
        public ScreenSlidePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentArrayList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentArrayList.size();
        }
    }

    private void showArrows(int pageNumber) {
    }

    @Override
    public void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
        getView().setFocusableInTouchMode(true);
        getView().requestFocus();
        getView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                callToCloseDialog();
                return true;
            }
        });
    }

    @Override
    public void onPause() {
        EventBus.getDefault().unregister(this);
        super.onPause();
    }

    @Subscribe
    public void onEvent(QuestionResponsesModel questionResponsesModel){
    }

}
</code>```

Kept only code for Viewpager & fragments loading.

答:
You can override this method in activity and listen backpress</p>

```<code>public class MainActivity extends Activity {
        ...
        @Override
        public boolean dispatchKeyEvent(KeyEvent event)
        {
            int action = event.getAction();
            int keyCode = event.getKeyCode();
            switch (keyCode)
            {
                case KeyEvent.KEYCODE_BACK:
                    if (action == KeyEvent.ACTION_DOWN)
                    {
                        Log.v("myApp", "Back button pressed.");
                        return true;
                    }
                default:
                    return false;
            }
            return false;
        }
    }
</code>```

Body:
I have viewpager with couple of fragments inside. I need to get confirmation when user presses back button. However, it doesn't get called unless I visit last page.

public class Create_Safety_CheckList_MainFragment extends Fragment
        implements View.OnClickListener, Observer {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_create_safety_checklist_pager_main, container, false);
        initializeUI();

        return view;
    }

    private void initializeUI() {
        setHeader(getResources().getString(R.string.safety_check_list_checklist_screen_name));
        addFragments();
        mPager = (ViewPager) view.findViewById(R.id.viewPager_home_screen_activity);
        mPagerAdapter = new ScreenSlidePagerAdapter(getChildFragmentManager());
        mPager.setOffscreenPageLimit(fragmentArrayList.size());
        mPager.setOnPageChangeListener(onPageChangeListener);
        mPager.setAdapter(mPagerAdapter);
//        mPager.setOnTouchListener(new View.OnTouchListener() {
//
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                v.getParent().requestDisallowInterceptTouchEvent(true);
//                return false;
//            }
//        });

        customTextViewChecklistName = (CustomTextView) view.findViewById(R.id.textView_New_Checklist_Name);
        if (createChecklistObservationModel.getChecklistName() != null)
            customTextViewChecklistName.setText(createChecklistObservationModel.getChecklistName());

    }

    private void addFragments() {
        createChecklistAdditionalTabFragment = new CreateChecklistAdditionalTabFragment();
        fragmentArrayList.add(createChecklistAdditionalTabFragment);

        Bundle bundle = getArguments();
        if (bundle != null) {
            if (bundle.containsKey("***")) {
                String response = spcl_databaseHandler.getSpecificChecklistAdditionals(bundle.getString("checklistID"));
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    JSONObject dataJsonObject = jsonObject.getJSONObject("Data");

                    JSONArray checkListAdditionalFieldDtoJsonArray = dataJsonObject.getJSONArray("***");
                    int additionalsLength = checkListAdditionalFieldDtoJsonArray.length();
                    if (additionalsLength > 0) {
dataJsonObject.getJSONArray("***").toString());
                        additionalInfoFragment = new Additional_Information_Fragment();
                        fragmentArrayList.add(additionalInfoFragment);
                    }

                    JSONArray jsonGroupsArray = dataJsonObject.getJSONArray("***");
                    int groupsLength = jsonGroupsArray.length();
                    for (int i = 0; i < groupsLength; i++) {
                        JSONObject groupJsonObject = (JSONObject) jsonGroupsArray.get(i);
                        JSONArray questionsJsonArray = groupJsonObject.getJSONArray("Questions");
                        int questionsLength = questionsJsonArray.length();
                        for (int j = 0; j < questionsLength; j++) {
                            checklistGroupsDiscussionQuestionOneFragment = new ChecklistGroupsDiscussionQuestionOneFragment();
                            checklistGroupsDiscussionQuestionOneFragment.setArguments(bundle1);
                            fragmentArrayList.add(checklistGroupsDiscussionQuestionOneFragment);
                        }

                        JSONArray subGroupsJsonArray = groupJsonObject.getJSONArray("SubGroups");
                        int subGroupsJsonArrayLength = subGroupsJsonArray.length();
                        for (int j = 0; j < subGroupsJsonArrayLength; j++) {
                            JSONObject subGroupObject = subGroupsJsonArray.getJSONObject(j);
                            JSONArray subGroupQuestionsJsonArray = subGroupObject.getJSONArray("Questions");
                            int subGroupQuestionsJsonArrayLength = subGroupQuestionsJsonArray.length();
                            for (int k = 0; k < subGroupQuestionsJsonArrayLength; k++) {
checklistGroupsDiscussionQuestionOneFragment = new ChecklistGroupsDiscussionQuestionOneFragment();                                fragmentArrayList.add(checklistGroupsDiscussionQuestionOneFragment);
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        questionsFragment = new Other_Questions_Fragment();
        membersFragment = new Inspection_Members_Fragment();

        fragmentArrayList.add(questionsFragment);
        fragmentArrayList.add(membersFragment);
    }

    private void setHeader(String headerTitle) {
    }

    ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int pageNumber) {
        }

        @Override
        public void onPageScrolled(int pageNumber, float positionOffset,
                                   int positionOffsetPixels) {
//            mPager.getParent().requestDisallowInterceptTouchEvent(true);
            showArrows(pageNumber);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imageView_Next:
                break;

            case R.id.imageView_Previous:
                break;

            case R.id.textView_Cancel :
                callToCloseDialog();
                break;

            default:
                break;
        }
    }

    private void callToCloseDialog() {
        if (SystemClock.elapsedRealtime() - mLastClickTime < 1000) {
            return;
        }
        mLastClickTime = SystemClock.elapsedRealtime();

        final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage(getResources().getString(R.string.cancel_dialog_message))
                .setTitle("Warning");

        builder.setPositiveButton(getResources().getString(R.string.cancel_dialog_yes_button), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked OK button
                getActivity().getSupportFragmentManager().popBackStackImmediate(getResources().getString(R.string.new_checklist_fragment), FragmentManager.POP_BACK_STACK_INCLUSIVE);
            }
        });

        builder.setNegativeButton(getResources().getString(R.string.cancel_dialog_no_button), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked cancel button
                dialog.dismiss();
            }
        });

        AlertDialog alert = builder.create();
        alert.show();
    }

    @Override
    public void update(Observable observable, Object o) {
    }

    /**
     * A simple pager adapter that represents 3 objects, in sequence.
     */
    private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
        public ScreenSlidePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentArrayList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentArrayList.size();
        }
    }

    private void showArrows(int pageNumber) {
    }

    @Override
    public void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
        getView().setFocusableInTouchMode(true);
        getView().requestFocus();
        getView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                callToCloseDialog();
                return true;
            }
        });
    }

    @Override
    public void onPause() {
        EventBus.getDefault().unregister(this);
        super.onPause();
    }

    @Subscribe
    public void onEvent(QuestionResponsesModel questionResponsesModel){
    }

}

Kept only code for Viewpager & fragments loading.

Body:
You can override this method in activity and listen backpress

public class MainActivity extends Activity {
        ...
        @Override
        public boolean dispatchKeyEvent(KeyEvent event)
        {
            int action = event.getAction();
            int keyCode = event.getKeyCode();
            switch (keyCode)
            {
                case KeyEvent.KEYCODE_BACK:
                    if (action == KeyEvent.ACTION_DOWN)
                    {
                        Log.v("myApp", "Back button pressed.");
                        return true;
                    }
                default:
                    return false;
            }
            return false;
        }
    }


问:
JOptionPane won't show its dialog on top of other windows
I have problem currently for my swing reminder application, which able to minimize to tray on close. My problem here is, I need JOptionPane dialog to pop up on time according to what I set, but problem here is, when I minimize it, the dialog will pop up, but not in the top of windows when other application like explorer, firefox is running, anyone know how to pop up the dialog box on top of windows no matter what application is running?</p>

答:
You might think about using a JFrame instead.  It may give you a little more flexibility.

If you are using a JFrame and you want it to popup on top of the other windows use:

```<code>myFrame.setVisible(true);
myFrame.setState(Frame.NORMAL);
</code>```

The setState will show the window to the user if it was in minimized state previously.

OwnerDisplayName: Dickson

Body:
You might think about using a JFrame instead.  It may give you a little more flexibility.

If you are using a JFrame and you want it to popup on top of the other windows use:

myFrame.setVisible(true);
myFrame.setState(Frame.NORMAL);

The setState will show the window to the user if it was in minimized state previously.

OwnerDisplayName: ShawnD


问:
Swap! value doesn't resolve
While parsing an xml file, I normalize values and save them via swap! into an atom. Additional I build a tree to reflect the original structure.

When I call the function, it returns only a part of the data, but not the normalized values. When I deref the atom, the data is completely written.

Here the parts of the code, which seems to be critical to that behaviour.

```<code>(defn normalize-values
  "Save the dataset to the atom and returns the reference"
  [tour-id key value]
  (swap! db assoc-in [tour-id (query-key key :name) value] {:title value})
  {key [(query-key key) value]})

(defn extract-tags
  "Differs between unique and normalizable values"
  [node tour-id]
  (let [data (zip/xml-zip node)
        key (:tag node)
        value (zx/xml1-> data key zx/text)
        res (if (some #{key} [:sound :map :video :creator])
              (normalize-values tour-id key value)
              {key value})]
    res))

(defn panorama->map
  "Creates a panorama map from the xml data"
  [node tour-id]
  (let [xml-node (zip/node node)
        tag-values (into {} (map #(extract-tags % tour-id) (:content xml-node)))]
    (merge tag-values
           {:id     (get-file-id (:file tag-values))
            :hidden (read-string (get-in xml-node [:attrs :hidden]))})))

(defn menu->map
  "Loops over the xml tree and builds the structure"
  [tour-id menu]
  (for [entry menu]
    (let [children (childs-of-child entry)]
      (if (not-empty children)
        (let [{:keys [id] :as category-map} (category->map entry)]
          (swap! db assoc-in [tour-id (query-key :categorie :id) id] category-map)
          {:loc      [:categories/by-id id]
           :children (menu->map tour-id children)})

        (let [{:keys [id] :as panorama-map} (panorama->map entry tour-id)]
          (swap! db assoc-in [tour-id (query-key :pano :id) id] panorama-map)

          {:loc [:panos/by-id id]})))))

(defn parse-menu
  "Starting function which resets the db and saves all data to the atom "
  [path id]
  (swap! db dissoc id)
  (logging/debug "Parse Menu: " path)

  (let [xml (xml->map path)
        menu-data (menu->map id (:content xml))]

    (swap! db assoc-in [id :title] (tour-title xml))
    (swap! db assoc-in [id :tree] menu-data)

    (get @db id)))
</code>```

How can I realize, that the atom is resolved correctly?

答:
As @Alan Thompson commented, where the source of the error the lazy evaluation. After prepending a (vec) before the (for) loops, the problem has gone.

```<code>(defn menu->map
  "Loops over the xml tree and builds the structure"
  [tour-id menu]

  (vec    ;;forcing the evaluation of the loop

   (for [entry menu]
     (let [children (childs-of-child entry)]
       (if (not-empty children)
         (let [{:keys [id] :as category-map} (category->map entry)]
           (swap! db assoc-in [tour-id (query-key :categorie :id) id] category-map)
           {:loc      [:categories/by-id id]
            :children (menu->map tour-id children)})

         (let [{:keys [id] :as panorama-map} (panorama->map entry tour-id)]
           (swap! db assoc-in [tour-id (query-key :pano :id) id] panorama-map)

           {:loc [:panos/by-id id]}))))))
</code>```

Title: Swap! value doesn't resolve

Body:
While parsing an xml file, I normalize values and save them via swap! into an atom. Additional I build a tree to reflect the original structure.

When I call the function, it returns only a part of the data, but not the normalized values. When I deref the atom, the data is completely written.

Here the parts of the code, which seems to be critical to that behaviour.

(defn normalize-values
  "Save the dataset to the atom and returns the reference"
  [tour-id key value]
  (swap! db assoc-in [tour-id (query-key key :name) value] {:title value})
  {key [(query-key key) value]})

(defn extract-tags
  "Differs between unique and normalizable values"
  [node tour-id]
  (let [data (zip/xml-zip node)
        key (:tag node)
        value (zx/xml1-> data key zx/text)
        res (if (some #{key} [:sound :map :video :creator])
              (normalize-values tour-id key value)
              {key value})]
    res))

(defn panorama->map
  "Creates a panorama map from the xml data"
  [node tour-id]
  (let [xml-node (zip/node node)
        tag-values (into {} (map #(extract-tags % tour-id) (:content xml-node)))]
    (merge tag-values
           {:id     (get-file-id (:file tag-values))
            :hidden (read-string (get-in xml-node [:attrs :hidden]))})))

(defn menu->map
  "Loops over the xml tree and builds the structure"
  [tour-id menu]
  (for [entry menu]
    (let [children (childs-of-child entry)]
      (if (not-empty children)
        (let [{:keys [id] :as category-map} (category->map entry)]
          (swap! db assoc-in [tour-id (query-key :categorie :id) id] category-map)
          {:loc      [:categories/by-id id]
           :children (menu->map tour-id children)})

        (let [{:keys [id] :as panorama-map} (panorama->map entry tour-id)]
          (swap! db assoc-in [tour-id (query-key :pano :id) id] panorama-map)

          {:loc [:panos/by-id id]})))))

(defn parse-menu
  "Starting function which resets the db and saves all data to the atom "
  [path id]
  (swap! db dissoc id)
  (logging/debug "Parse Menu: " path)

  (let [xml (xml->map path)
        menu-data (menu->map id (:content xml))]

    (swap! db assoc-in [id :title] (tour-title xml))
    (swap! db assoc-in [id :tree] menu-data)

    (get @db id)))

How can I realize, that the atom is resolved correctly?

Body:
As @Alan Thompson commented, where the source of the error the lazy evaluation. After prepending a (vec) before the (for) loops, the problem has gone.

(defn menu->map
  "Loops over the xml tree and builds the structure"
  [tour-id menu]

  (vec    ;;forcing the evaluation of the loop

   (for [entry menu]
     (let [children (childs-of-child entry)]
       (if (not-empty children)
         (let [{:keys [id] :as category-map} (category->map entry)]
           (swap! db assoc-in [tour-id (query-key :categorie :id) id] category-map)
           {:loc      [:categories/by-id id]
            :children (menu->map tour-id children)})

         (let [{:keys [id] :as panorama-map} (panorama->map entry tour-id)]
           (swap! db assoc-in [tour-id (query-key :pano :id) id] panorama-map)

           {:loc [:panos/by-id id]}))))))


问:
Electron window handler didn't work with Unity on win10
I try to launch an unity exe in an electron window.

For that:

I get my window handler ID with win.getNativeWindowHandle() from electron.

I launch my unity exe with :
./unity/Child.exe  -parentHWND {window_handler_id} delayed from unity doc.

On win7 and win8 my window display the unity application, but with win10 I get a blinking window who sometime display my unity exe.

If I launch my unity exe on another window, Firefox for example, it works. But not on Slack or Atom (electron apps).

Do you got an idea ?

答:
Are you sure win.getNativeWindowHandle() returns the actual handler ID of your Electron window ?

In this case, did you try to pass this handler to another exe (not the Unity build) ?


问:
React-native currency input
I'm trying to create a currency input, that starts as something like

```<code>" $00.00"
</code>```

and then when you start typing, it types the cents first, then moves on to the dollars (ie, updates the right side numbers first), e.g

```<code>" $00.50"
</code>```

So far I have it implemented, where the user types in one box, and the correctly formatted output displays in a second box.

Code :

```<code>constructor(props) {
    super(props);

    this.state = {
        amount: '',
    };

}

formatValue(value) {
    return accounting.formatMoney(parseFloat(value) / 100, "$ ");
}

render() {
    return (
        <ScrollView>

            <Text style={styles.text}> Enter the Amount to be payed</Text>
                <TextInput
                    onChangeText={(amount) => this.setState({amount})}>
                </TextInput>

                <TextInput
                    onChangeText = {amount => this.setState({amount})}
                    value={this.formatValue(this.state.amount)}>
                </TextInput>

        </ScrollView>

    );

}
</code>```

However, I want the currency formatting to apply to the same box the user is typing into. I have tried something like this:

```<code><TextInput
        onChangeText={(amount) => this.setState({amount})}
        value = {this.formatValue(this.state.amount)}>
</TextInput>
</code>```

but this simply sets the input to zero, and it cannot be changed. I am clearly not understanding this correctly.

Does anyone have any insight on this?

答:
Maybe this package can help you out. It lets you store change value in state.

https://www.npmjs.com/package/react-currency-input

Or since you only want to mask the input and not do any mutation/converting to the input you can of course do something like this;

https://www.npmjs.com/package/react-input-mask

Title: React-native currency input

Body:
I'm trying to create a currency input, that starts as something like

" $00.00"

and then when you start typing, it types the cents first, then moves on to the dollars (ie, updates the right side numbers first), e.g

" $00.50"

So far I have it implemented, where the user types in one box, and the correctly formatted output displays in a second box.

Code :

constructor(props) {
    super(props);

    this.state = {
        amount: '',
    };

}

formatValue(value) {
    return accounting.formatMoney(parseFloat(value) / 100, "$ ");
}

render() {
    return (
        <ScrollView>

            <Text style={styles.text}> Enter the Amount to be payed</Text>
                <TextInput
                    onChangeText={(amount) => this.setState({amount})}>
                </TextInput>

                <TextInput
                    onChangeText = {amount => this.setState({amount})}
                    value={this.formatValue(this.state.amount)}>
                </TextInput>

        </ScrollView>

    );

}

However, I want the currency formatting to apply to the same box the user is typing into. I have tried something like this:

<TextInput
        onChangeText={(amount) => this.setState({amount})}
        value = {this.formatValue(this.state.amount)}>
</TextInput>

but this simply sets the input to zero, and it cannot be changed. I am clearly not understanding this correctly.

Does anyone have any insight on this?


答:
You can do it with display:table and display:table-cell. Only use flex when you can't do it any other way.

* {
  box-sizing: border-box;
}
.table {
  display: block;
  table-layout:fixed;
}
.table-cell {
  display: block;
  width:100%;
}
@media screen and (min-width: 640px) {
  .table {
    display: table;
    table-layout:fixed;
  }
  .table-cell {
    display: table-cell;
    width:33.333%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container table" style="width:100%; background-color:#205ba0; padding:30px;">

    <div class="col-md-offset-3 col-md-2 table-cell" align="center" style="color:white; border:2px solid white; font-size:12px; padding:10px;">
      <div class="trip" style="background-color:white; margin-bottom:10px; padding-bottom:5px;">
        <img src="https://abbaproperty.000webhostapp.com/wp-content/uploads/2017/05/rent.png" style="height:100px;">
      </div>
      <h2 style="font-weight:bold;">Renting? Landlords welcome.</h2>
      A swift liason between landlords and tenants as a fair, independeant party, is just one of our services.<br><br>
      Find out more >
    </div>

    <div class="col-md-2 table-cell" align="center" style="color:white; border:2px solid white; font-size:12px; padding:10px;">
      <div class="trip" style="background-color:white; margin-bottom:15px;">
        <img src="https://abbaproperty.000webhostapp.com/wp-content/uploads/2017/05/val.png" style="height:100px;">
      </div>
      <h2 style="font-weight:bold;">Valuation? Sorted quickly.</h2>
    Providing some of the most effecient valuations in town, we're here to help you sort out an important step.<br><br>
      Find out more >
    </div>

    <div class="col-md-2 table-cell" align="center" style="color:white; border:2px solid white; font-size:12px; padding:10px;">
      <div class="trip" style="background-color:white; margin-bottom:10px; padding-bottom:5px;">
        <img src="https://abbaproperty.000webhostapp.com/wp-content/uploads/2017/05/sale.png" style="height:100px;">
      </div>
      <h2 style="font-weight:bold;">Selling? Now uncomplicated.</h2>
      We aim to make selling easy. Our trained estate agents are constantly available to help.<br><br>
      Find out more >
    </div>

</div></code>```

Body:
You can do it with display:table and display:table-cell. Only use flex when you can't do it any other way.

* {
  box-sizing: border-box;
}
.table {
  display: block;
  table-layout:fixed;
}
.table-cell {
  display: block;
  width:100%;
}
@media screen and (min-width: 640px) {
  .table {
    display: table;
    table-layout:fixed;
  }
  .table-cell {
    display: table-cell;
    width:33.333%;
  }
}

<div class="container table" style="width:100%; background-color:#205ba0; padding:30px;">

    <div class="col-md-offset-3 col-md-2 table-cell" align="center" style="color:white; border:2px solid white; font-size:12px; padding:10px;">
      <div class="trip" style="background-color:white; margin-bottom:10px; padding-bottom:5px;">
        <img src="https://abbaproperty.000webhostapp.com/wp-content/uploads/2017/05/rent.png" style="height:100px;">
      </div>
      <h2 style="font-weight:bold;">Renting? Landlords welcome.</h2>
      A swift liason between landlords and tenants as a fair, independeant party, is just one of our services.<br><br>
      <a href="https://abbaproperty.000webhostapp.com/index.php/property-management/" style="color:white;">Find out more ></a>
    </div>

    <div class="col-md-2 table-cell" align="center" style="color:white; border:2px solid white; font-size:12px; padding:10px;">
      <div class="trip" style="background-color:white; margin-bottom:15px;">
        <img src="https://abbaproperty.000webhostapp.com/wp-content/uploads/2017/05/val.png" style="height:100px;">
      </div>
      <h2 style="font-weight:bold;">Valuation? Sorted quickly.</h2>
    Providing some of the most effecient valuations in town, we're here to help you sort out an important step.<br><br>
      <a href="https://abbaproperty.000webhostapp.com/index.php/valuations/" style="color:white;">Find out more ></a>
    </div>

    <div class="col-md-2 table-cell" align="center" style="color:white; border:2px solid white; font-size:12px; padding:10px;">
      <div class="trip" style="background-color:white; margin-bottom:10px; padding-bottom:5px;">
        <img src="https://abbaproperty.000webhostapp.com/wp-content/uploads/2017/05/sale.png" style="height:100px;">
      </div>
      <h2 style="font-weight:bold;">Selling? Now uncomplicated.</h2>
      We aim to make selling easy. Our trained estate agents are constantly available to help.<br><br>
      <a href="https://abbaproperty.000webhostapp.com/index.php/sell/" style="color:white;">Find out more ></a>
    </div>

</div>


问:
Formidable is not defined in Node.js
I am trying to create an HTTP server that the user can upload images and archives, and for that I am using formidable for handling the upload part.

My code :

requestHandler.js

```<code> // Request Handlers (will handle all requests that happen)

    // Allows Node.js to make use of a non-blocking operation: exec ();
    var exec = require("child_process").exec;
    var querystring = require("querystring");
    fs = require("fs");
    var fomidable = require("formidable");

    function start(response, postData) {
        console.log("Request handler 'start' was called");
        var body = '<html>' +
        '<head>' +
        '<meta http-equiv = "Content-Type" content = "text/html";'+
        'charset="UTF-8"/>' +
        '</head>' +
        '<body>' +
        '<form action = "/upload" enctype = "multipart/form-data"' +
        'method = "post">' +
        '<input type ="file" name = "upload multiple = "multiple">' +
        '<input type = "submit" value ="Upload file" />' +
        '</form>' +
        '</body>' +
        '</html>';

        response.writeHead(200, {"Content-Type" : "text/html"});
        response.write(body);
        response.end();
    }

        // What is being passed between router.js and requestHandler.js is the entire body of the POST data request.

    function upload(response, request) {
        console.log("Request handler 'upload' was called");

        var form = new formidable.IncomingForm();
        console.log("about to parse");
        form.parse(request, function(error, fields, files) {
        console.log("parsing done");

        /*Possible error on Windows systems; tried to rename to an already existing file*/

        fs.rename(files.upload.path, "/tmp/test.png", function(err) {
            if(err) {
                fs.unlink("/tmp/test.png");
                fs.rename(files.upload.path, "/tmp/test.png");
            }
        });
        response.writeHead(200, {"Content-Type" : "text/plain"});
        response.write("You've sent the text : " + querystring.parse(postData).text);
        response.write("\nHello Upload");
        response.end();
    });
    }

    function show(response) {
        console.log("Request handler 'show' was called.");
        fs.readFile("/tmp/test.png", "binary", function(error,file) {
            if(error) {
                response.writeHead(500, {"Content-Type" : "text/plain"});
                response.write(err + "\n");
                response.end();
            } else {
                response.writeHead(200, {"Content-Type" : "image/png"});
                response.write(file, "binary");
                reponse.end();
            }
        });
    }
    exports.start = start;
    exports.upload = upload;
    exports.show = show;
</code>```

I am using too formidable in the another part of my code, in my server.js but there for some reason works (And for that reason I am not posting the code), the error point out to requestHandler.js in line 35 :

var form = new formidable.IncomingForm();

formidable is not defined

How can I make formidable defined ? When I am already doing that calling in the first place in :

```<code>var formidable = require("formidable");
</code>```

答:
I think you have a typo...

```<code>var fomidable = require("formidable");
</code>```

Should probably be:

```<code>var formidable = require("formidable");
</code>```

Hence the formidable is not defined... you defined it as fomidable.

Title: Formidable is not defined in Node.js

Body:
I am trying to create an HTTP server that the user can upload images and archives, and for that I am using formidable for handling the upload part.

My code :

requestHandler.js

 // Request Handlers (will handle all requests that happen)

    // Allows Node.js to make use of a non-blocking operation: exec ();
    var exec = require("child_process").exec;
    var querystring = require("querystring");
    fs = require("fs");
    var fomidable = require("formidable");

    function start(response, postData) {
        console.log("Request handler 'start' was called");
        var body = '' +
        '' +
        '<meta http-equiv = "Content-Type" content = "text/html";'+
        'charset="UTF-8"/>' +
        '' +
        '' +
        '<form action = "/upload" enctype = "multipart/form-data"' +
        'method = "post">' +
        '<input type ="file" name = "upload multiple = "multiple">' +
        '<input type = "submit" value ="Upload file" />' +
        '</form>' +
        '' +
        '';

        response.writeHead(200, {"Content-Type" : "text/html"});
        response.write(body);
        response.end();
    }

        // What is being passed between router.js and requestHandler.js is the entire body of the POST data request.

    function upload(response, request) {
        console.log("Request handler 'upload' was called");

        var form = new formidable.IncomingForm();
        console.log("about to parse");
        form.parse(request, function(error, fields, files) {
        console.log("parsing done");

        /*Possible error on Windows systems; tried to rename to an already existing file*/

        fs.rename(files.upload.path, "/tmp/test.png", function(err) {
            if(err) {
                fs.unlink("/tmp/test.png");
                fs.rename(files.upload.path, "/tmp/test.png");
            }
        });
        response.writeHead(200, {"Content-Type" : "text/plain"});
        response.write("You've sent the text : " + querystring.parse(postData).text);
        response.write("\nHello Upload");
        response.end();
    });
    }

    function show(response) {
        console.log("Request handler 'show' was called.");
        fs.readFile("/tmp/test.png", "binary", function(error,file) {
            if(error) {
                response.writeHead(500, {"Content-Type" : "text/plain"});
                response.write(err + "\n");
                response.end();
            } else {
                response.writeHead(200, {"Content-Type" : "image/png"});
                response.write(file, "binary");
                reponse.end();
            }
        });
    }
    exports.start = start;
    exports.upload = upload;
    exports.show = show;

I am using too formidable in the another part of my code, in my server.js but there for some reason works (And for that reason I am not posting the code), the error point out to requestHandler.js in line 35 :

var form = new formidable.IncomingForm();

formidable is not defined

How can I make formidable defined ? When I am already doing that calling in the first place in :

var formidable = require("formidable");

Body:
I think you have a typo...

var fomidable = require("formidable");

Should probably be:

var formidable = require("formidable");

Hence the formidable is not defined... you defined it as fomidable.


问:
Empty space in ImageButton
I have a field for the game Tic-Tac-Toe. Each cell is an ImageButton. When clicked, a picture is inserted. But there are some empty space on the Top and Bottom:

Before

After

fragment_game.xml

```<code><TableLayout
        android:id="@+id/tableGame"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="50dp"
        android:background="@android:color/black">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1">

            <ImageButton
                android:id="@+id/button1"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_margin="2dp"
                android:layout_weight="1"
                android:background="@android:color/white" />

            <ImageButton
                android:id="@+id/button3"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_margin="2dp"
                android:layout_weight="1"
                android:background="@android:color/white" />

            <ImageButton
                android:id="@+id/button2"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_margin="2dp"
                android:layout_weight="1"
                android:background="@android:color/white" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1">

            <ImageButton
                android:id="@+id/button9"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_margin="2dp"
                android:layout_weight="1"
                android:background="@android:color/white" />

            <ImageButton
                android:id="@+id/button5"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_margin="2dp"
                android:layout_weight="1"
                android:background="@android:color/white" />

            <ImageButton
                android:id="@+id/button4"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_margin="2dp"
                android:layout_weight="1"
                android:background="@android:color/white" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1">

            <ImageButton
                android:id="@+id/button8"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_margin="2dp"
                android:layout_weight="1"
                android:background="@android:color/white" />

            <ImageButton
                android:id="@+id/button7"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_margin="2dp"
                android:layout_weight="1"
                android:background="@android:color/white" />

            <ImageButton
                android:id="@+id/button6"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_margin="2dp"
                android:layout_weight="1"
                android:background="@android:color/white" />
        </TableRow>

    </TableLayout>
</code>```

And Fragment_game.java

```<code>final ImageButton btn = (ImageButton) V.findViewById(R.id.button5);
btn.setScaleType(ImageButton.ScaleType.FIT_CENTER);
btn.setAdjustViewBounds(true);
btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
         btn.setImageResource(R.drawable.qwe);
    }
});
</code>```

I want the picture to stretch to the size of the cell.

答:
```<code>android:layout_margin="2dp"
</code>```

You use Margin Padding Please remove Margin and Padding then You can Eaisly do Your Job anotherwise cont

Title: Empty space in ImageButton

Body:
I have a field for the game Tic-Tac-Toe. Each cell is an ImageButton. When clicked, a picture is inserted. But there are some empty space on the Top and Bottom:

Before

After

fragment_game.xml

<TableLayout
        android:id="@+id/tableGame"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="50dp"
        android:background="@android:color/black">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1">

            <ImageButton
                android:id="@+id/button1"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_margin="2dp"
                android:layout_weight="1"
                android:background="@android:color/white" />

            <ImageButton
                android:id="@+id/button3"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_margin="2dp"
                android:layout_weight="1"
                android:background="@android:color/white" />

            <ImageButton
                android:id="@+id/button2"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_margin="2dp"
                android:layout_weight="1"
                android:background="@android:color/white" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1">

            <ImageButton
                android:id="@+id/button9"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_margin="2dp"
                android:layout_weight="1"
                android:background="@android:color/white" />

            <ImageButton
                android:id="@+id/button5"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_margin="2dp"
                android:layout_weight="1"
                android:background="@android:color/white" />

            <ImageButton
                android:id="@+id/button4"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_margin="2dp"
                android:layout_weight="1"
                android:background="@android:color/white" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1">

            <ImageButton
                android:id="@+id/button8"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_margin="2dp"
                android:layout_weight="1"
                android:background="@android:color/white" />

            <ImageButton
                android:id="@+id/button7"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_margin="2dp"
                android:layout_weight="1"
                android:background="@android:color/white" />

            <ImageButton
                android:id="@+id/button6"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_margin="2dp"
                android:layout_weight="1"
                android:background="@android:color/white" />
        </TableRow>

    </TableLayout>

And Fragment_game.java

final ImageButton btn = (ImageButton) V.findViewById(R.id.button5);
btn.setScaleType(ImageButton.ScaleType.FIT_CENTER);
btn.setAdjustViewBounds(true);
btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
         btn.setImageResource(R.drawable.qwe);
    }
});

I want the picture to stretch to the size of the cell.

Body:
android:layout_margin="2dp"

You use Margin Padding Please remove Margin and Padding then You can Eaisly do Your Job anotherwise cont


问:
its it possible to have two ELSEIF clauses in a IF ternary?
can this be made into an IF ternary to shorten the code? I don't know how to do it with multiple elseif clause

```<code>if ($ext == "m") {
 $extype = "mp3";
}elseif ($ext == "w") {
 $extype = "wav";
}elseif ($ext == "a"){
 $extype = "aac";
}
</code>```

the is the full function

```<code>function loc($id,$type,$ext) //loc($id,'n',$ext)
{
  if (($query = mysql_query("SELECT loc FROM names WHERE id = '".(int)$id."'")) !== false)
  {
    if (mysql_num_rows($query) > 0)
     if ($ext == "m") {
     $extype = ".mp3";
     }elseif ($ext == "w") {
     $extype = ".wav";
     }elseif ($ext == "a") {
     $extype = ".aac";
     }
      return '/rec/'.mysql_result($query,0,'loc').$id.'-'.($type=='n'?'n':'s').$extype);

  }
  return 'Error Not Found';
}
</code>```

答:
There's this thing called a "switch" statement.

Don't be afraid of it - it's your friend.

Body:
can this be made into an IF ternary to shorten the code? I don't know how to do it with multiple elseif clause

if ($ext == "m") {
 $extype = "mp3";
}elseif ($ext == "w") {
 $extype = "wav";
}elseif ($ext == "a"){
 $extype = "aac";
}

the is the full function

function loc($id,$type,$ext) //loc($id,'n',$ext)
{
  if (($query = mysql_query("SELECT loc FROM names WHERE id = '".(int)$id."'")) !== false)
  {
    if (mysql_num_rows($query) > 0)
     if ($ext == "m") {
     $extype = ".mp3";
     }elseif ($ext == "w") {
     $extype = ".wav";
     }elseif ($ext == "a") {
     $extype = ".aac";
     }
      return '/rec/'.mysql_result($query,0,'loc').$id.'-'.($type=='n'?'n':'s').$extype);

  }
  return 'Error Not Found';
}


问:
Highcharts xAxis labels do not auto rotate
My chart has some custom x-axis labels using tick positions the labels are displayed as they should but the problem is that upon window resize they do not rotate I would like to rotate them on screen size less then 399 px
jsfiddle</p>

```<code>$(function () {
    $('#container').highcharts({
        title: {
            text: 'Monthly Average Temperature',
            x: -20 //center
        },
        subtitle: {
            text: 'Source: WorldClimate.com',
            x: -20
        },
        xAxis: {
            type: 'datetime',
                tickPositions: [1454329239000, 1465906839000, 1468844439000, 1469708439000, 1474892439000, 1476879639000, 1478607639000],
                labels: {

                  style: {
                    fontSize: '0.75em'
                  },
                  formatter: function() {
                    return Highcharts.dateFormat('%b %e', this.value);
                  }
                }

        },
        yAxis: {
            title: {
                text: 'Temperature (°C)'
            },
            plotLines: [{
                value: 0,
                width: 1,
                color: '#808080'
            }]
        },
        tooltip: {
            valueSuffix: '°C'
        },
        legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'middle',
            borderWidth: 0
        },
        series: [{
            name: 'Tokyo',
            data: [[1454329239000, 09], [1465906839000, 08], [1468844439000, 07], [1469708439000, 10], [1474892439000, 17], [1476879639000, 8], [1478607639000, 20]]
        }]
    });
});
</code>```

答:
My experience dealing with a similar issue is that the autoRotation setting only works on category charts, whereas in your case, the x-axis labels are being rendered dynamically based on how much space is available.

However, I can't find any documentation or conversation on the interwebs to confirm my theory. Does anyone else know?

Body:
My chart has some custom x-axis labels using tick positions the labels are displayed as they should but the problem is that upon window resize they do not rotate I would like to rotate them on screen size less then 399 px
jsfiddle

$(function () {
    $('#container').highcharts({
        title: {
            text: 'Monthly Average Temperature',
            x: -20 //center
        },
        subtitle: {
            text: 'Source: WorldClimate.com',
            x: -20
        },
        xAxis: {
            type: 'datetime',
                tickPositions: [1454329239000, 1465906839000, 1468844439000, 1469708439000, 1474892439000, 1476879639000, 1478607639000],
                labels: {

                  style: {
                    fontSize: '0.75em'
                  },
                  formatter: function() {
                    return Highcharts.dateFormat('%b %e', this.value);
                  }
                }

        },
        yAxis: {
            title: {
                text: 'Temperature (°C)'
            },
            plotLines: [{
                value: 0,
                width: 1,
                color: '#808080'
            }]
        },
        tooltip: {
            valueSuffix: '°C'
        },
        legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'middle',
            borderWidth: 0
        },
        series: [{
            name: 'Tokyo',
            data: [[1454329239000, 09], [1465906839000, 08], [1468844439000, 07], [1469708439000, 10], [1474892439000, 17], [1476879639000, 8], [1478607639000, 20]]
        }]
    });
});


问:
Security access in NativeScript Angular app
I'm starting to learn NativeScript Angular (I'm used to develop webapp/websites using Angular) and I'm still kind of confused on how to create some restricted access on the NativeScript app, or to restrict a specific route and/or sets of routes.

For example, in Angular I use uiRouter to define some data, like this:

```<code>data: {
    requireLogin: true
}
</code>```

In each page transition I check if there is a valid token to garantee access to that user. On the NativeScript I was thinking about it and could do the same thing, I just don't know, since I'm very new to NativeScript and I don't know if this would go against any best practices, or common security scenarios.

For example, I'll be setting the token on the Application Settings after the login, something like this:

```<code>submit() {
    // process the login here
    if ( success ) {
        setString(AppSettings.authToken, authToken );
    }
}
</code>```

And then I would set the routes to have a parent route with a parent component where I will check for this token, eg:

```<code>export class ParentComponent implements OnInit {
    constructor() {}

    ngOnInit() {
        if ( !getString(AppSettings.authToken)) {
            return this.router.navigate(["/login"]);
        }
    }
}
</code>```

This way I would check if the user has a valid session when accessing the app on a restricted area.

However, for example, in a normal Angular Application I also make use of interceptor, to check in every http request if the authToken is still valid.

How am I supposed to do in this case?

I tried to find any material on NativeScript Angular security but didn't found any. is there any place where I can read more about this?

What should I have in mind when dealing with this type of scenario?

答:
You can use the Angular's route guards

Basic example for canActivate route guard in NativeScript

```<code>class AuthGuard implements CanActivate {
    constructor(
        private loginService: LoginService,
        private nav: RouterExtensions) {
    }

    canActivate() {
        if (this.loginService.isLogged) {
            console.log("AuthGuard: authenticated");
            return true;
        } else {
            console.log("AuthGuard: redirecting to login");
            this.nav.navigate(["/login"]);
            return false;
        }
    }
}
</code>```

Based on this test application

The same deal in a real demo application. Here is the actual usage of this guard in the Sample-Groceries app.

Body:
I'm starting to learn NativeScript Angular (I'm used to develop webapp/websites using Angular) and I'm still kind of confused on how to create some restricted access on the NativeScript app, or to restrict a specific route and/or sets of routes.

For example, in Angular I use uiRouter to define some data, like this:

data: {
    requireLogin: true
}

In each page transition I check if there is a valid token to garantee access to that user. On the NativeScript I was thinking about it and could do the same thing, I just don't know, since I'm very new to NativeScript and I don't know if this would go against any best practices, or common security scenarios.

For example, I'll be setting the token on the Application Settings after the login, something like this:

submit() {
    // process the login here
    if ( success ) {
        setString(AppSettings.authToken, authToken );
    }
}

And then I would set the routes to have a parent route with a parent component where I will check for this token, eg:

export class ParentComponent implements OnInit {
    constructor() {}

    ngOnInit() {
        if ( !getString(AppSettings.authToken)) {
            return this.router.navigate(["/login"]);
        }
    }
}

This way I would check if the user has a valid session when accessing the app on a restricted area.

However, for example, in a normal Angular Application I also make use of interceptor, to check in every http request if the authToken is still valid.

How am I supposed to do in this case?

I tried to find any material on NativeScript Angular security but didn't found any. is there any place where I can read more about this?

What should I have in mind when dealing with this type of scenario?

Body:
You can use the Angular's route guards

Basic example for canActivate route guard in NativeScript

class AuthGuard implements CanActivate {
    constructor(
        private loginService: LoginService,
        private nav: RouterExtensions) {
    }

    canActivate() {
        if (this.loginService.isLogged) {
            console.log("AuthGuard: authenticated");
            return true;
        } else {
            console.log("AuthGuard: redirecting to login");
            this.nav.navigate(["/login"]);
            return false;
        }
    }
}

Based on this test application

The same deal in a real demo application. Here is the actual usage of this guard in the Sample-Groceries app.


问:
DBF OLEDB C#: select with to_char
Is it possible to do a to_char in a query with a DBF database ? It's not working and can't find the syntax on internet

This query not working, i have a message

invalid function to_char :
  SELECT t.*, to_char(d_volume) as d_volume_2
                          FROM [deal] t

Thanks a lot

答: You use whatever the source DB syntax is. To_Char is an Oracle function, try STR() function instead</p>

Title: DBF OLEDB C#: select with to_char