问:
Cleaning up orphaned docker containers after Jenkins job is terminated
I work at a large organization that runs hundreds of jobs in a shared Jenkins cluster.

My Jenkins job needs to run integration tests against untrusted code running inside Docker containers. I am fearful that that when my Jenkins job gets terminated abruptly (e.g. job aborted or times out) I will be left with orphaned containers.

I have tried https://github.com/moby/moby/issues/1905 and ulimits does not work for me (this is because it only works for containers that run bash, and I cannot guarantee that mine will do so).

I tried https://stackoverflow.com/a/26351355/14731 but --lxc-conf is not a recognized option for Docker for Windows (this needs to run across all platforms supported by docker).

Any ideas?

答:
By the looks of things, people are handling this outside of docker.

They are adding Jenkins post-build steps that clean up orphaned docker containers on aborted or failed builds.

See Martin Kenneth's build script as an example.


来源: stackexchange

问:
Prevent files from opening with the solution
When you close VS with project files open, the next time you open that solution, it opens the same files.

Is there a way to prevent this?  Currently I try to remember to close all the open tabs before I exit.

答: Delete the .suo file in the solution directory :D</p>

ContentLicense: CC BY-SA 2.5


问:
When to use re.compile
Bear with me, I can't include my 1,000+ line program, and there are a couple of questions in the description.

So I have a couple types of patterns I am searching for:

```<code>#literally just a regular word
re.search("Word", arg)

#Varying complex pattern
re.search("[0-9]{2,6}-[0-9]{2}-[0-9]{1}", arg)

#Words with varying cases and the possibility of ending special characters
re.search("Supplier [Aa]ddress:?|Supplier [Ii]dentification:?|Supplier [Nn]ame:?", arg)

#I also use re.findall for the above patterns as well
re.findall("uses patterns above", arg
</code>```

I have about 75 of these in total, and some need to be moved to deeply nested functions

When and where should I compile the patterns?

Right now I am trying to improve my program by compiling everything in main, then pass the correct list of compiled RegexObjects to the function that uses it. Would this increase my performance?

Would doing something like the following increase the speed of my program?

```<code>re.compile("pattern").search(arg)
</code>```

Does the compiled patterns stay in memory so if a function is called multiple times with this in it would it skip the compiling part? So I wouldn't have to move data from function to function.

Is it even worth compiling all of the patterns if I move the data so much?

Is there a better way to match regular words without regex?

Short example of my code:

```<code>import re

def foo(arg, allWords):
   #Does some things with arg, then puts the result into a variable,
   # this function does not use allWords

   data = arg #This is the manipulated version of arg

   return(bar(data, allWords))

def bar(data, allWords):
   if allWords[0].search(data) != None:
      temp = data.split("word1", 1)[1]
      return(temp)

   elif allWords[1].search(data) != None:
      temp = data.split("word2", 1)[1]
      return(temp)

def main():

   allWords = [re.compile(m) for m in ["word1", "word2", "word3"]]

   arg = "This is a very long string from a text document input, the provided patterns might not be word1 in this string but I need to check for them, and if they are there do some cool things word3"

   #This loop runs a couple million times
   # because it loops through a couple million text documents
   while True:
      data = foo(arg, allWords)
</code>```

答:
This is a tricky subject: many answers, even some legitimate sources such as David Beazley's Python Cookbook, will tell you something like:

[Use compile()] when you’re going to perform a lot of matches using the same pattern.  This lets you compile the regex only once versus at each match. [see p. 45 of that book]

However, that really hasn't been true since sometime around Python 2.5.  Here's a note straight out of the re docs:

Note The compiled versions of the most recent patterns passed to re.compile() and the module-level matching functions are cached, so programs that use only a few regular expressions at a time needn’t worry about compiling regular expressions.

There are two small arguments against this, but (anecdotally speaking) these won't result in noticeable timing differences the majority of the time:

The size of the cache is limited.

Using compiled expressions directly avoids the cache lookup overhead.

Here's a rudimentary test of the above using the 20 newsgroups text dataset.  On a relative basis, the improvement in speed is about 1.6% with compiling, presumably due mostly to cache lookup.

```<code>import re
from sklearn.datasets import fetch_20newsgroups

# A list of length ~20,000, paragraphs of text
news = fetch_20newsgroups(subset='all', random_state=444).data

# The tokenizer used by most text-processing vectorizers such as TF-IDF
regex = r'(?u)\b\w\w+\b'
regex_comp = re.compile(regex)

def no_compile():
    for text in news:
        re.findall(regex, text)

def with_compile():
    for text in news:
        regex_comp.findall(text)

%timeit -r 3 -n 5 no_compile()
1.78 s ± 16.2 ms per loop (mean ± std. dev. of 3 runs, 5 loops each)

%timeit -r 3 -n 5 with_compile()
1.75 s ± 12.2 ms per loop (mean ± std. dev. of 3 runs, 5 loops each)
</code>```

That really only leaves one very defensible reason to use re.compile():

By precompiling all expressions when the module is loaded, the compilation work is shifted to application start time, instead of to a point when the program may be responding to a user action. [source; p. 15]. It's not uncommon to see constants declared at the top of a module with compile.  For example, in smtplib you'll find OLDSTYLE_AUTH = re.compile(r"auth=(.*)", re.I).

Note that compiling happens (eventually) whether or not you use re.compile().  When you do use compile(), you're compiling the passed regex at that moment.  If you use the module-level functions like re.search(), you're compiling and searching in this one call.  The two processes below are equivalent in this regard:

```<code># with re.compile - gets you a regular expression object (class)
#     and then call its method, `.search()`.
a = re.compile('regex[es|p]')  # compiling happens now
a.search('regexp')             # searching happens now

# with module-level function
re.search('regex[es|p]', 'regexp')  # compiling and searching both happen here
</code>```

Lastly you asked,

Is there a better way to match regular words without regex?

Yes; this is mentioned as a "common problem" in the HOWTO:

Sometimes using the re module is a mistake. If you’re matching a fixed
string, or a single character class, and you’re not using any re
features such as the IGNORECASE flag, then the full power of regular
expressions may not be required. Strings have several methods for
performing operations with fixed strings and they’re usually much
faster, because the implementation is a single small C loop that’s
been optimized for the purpose, instead of the large, more generalized
regular expression engine. [emphasis added]

...

In short, before turning to the re module, consider whether your
problem can be solved with a faster and simpler string method.

ContentLicense: CC BY-SA 4.0

Title: When to use re.compile

Body:
Bear with me, I can't include my 1,000+ line program, and there are a couple of questions in the description.

So I have a couple types of patterns I am searching for:

#literally just a regular word
re.search("Word", arg)

#Varying complex pattern
re.search("[0-9]{2,6}-[0-9]{2}-[0-9]{1}", arg)

#Words with varying cases and the possibility of ending special characters
re.search("Supplier [Aa]ddress:?|Supplier [Ii]dentification:?|Supplier [Nn]ame:?", arg)

#I also use re.findall for the above patterns as well
re.findall("uses patterns above", arg

I have about 75 of these in total, and some need to be moved to deeply nested functions

When and where should I compile the patterns?

Right now I am trying to improve my program by compiling everything in main, then pass the correct list of compiled RegexObjects to the function that uses it. Would this increase my performance?

Would doing something like the following increase the speed of my program?

re.compile("pattern").search(arg)

Does the compiled patterns stay in memory so if a function is called multiple times with this in it would it skip the compiling part? So I wouldn't have to move data from function to function.

Is it even worth compiling all of the patterns if I move the data so much?

Is there a better way to match regular words without regex?

Short example of my code:

import re

def foo(arg, allWords):
   #Does some things with arg, then puts the result into a variable,
   # this function does not use allWords

   data = arg #This is the manipulated version of arg

   return(bar(data, allWords))

def bar(data, allWords):
   if allWords[0].search(data) != None:
      temp = data.split("word1", 1)[1]
      return(temp)

   elif allWords[1].search(data) != None:
      temp = data.split("word2", 1)[1]
      return(temp)

def main():

   allWords = [re.compile(m) for m in ["word1", "word2", "word3"]]

   arg = "This is a very long string from a text document input, the provided patterns might not be word1 in this string but I need to check for them, and if they are there do some cool things word3"

   #This loop runs a couple million times
   # because it loops through a couple million text documents
   while True:
      data = foo(arg, allWords)

Body:
This is a tricky subject: many answers, even some legitimate sources such as David Beazley's Python Cookbook, will tell you something like:

[Use compile()] when you’re going to perform a lot of matches using the same pattern.  This lets you compile the regex only once versus at each match. [see p. 45 of that book]

However, that really hasn't been true since sometime around Python 2.5.  Here's a note straight out of the re docs:

Note The compiled versions of the most recent patterns passed to re.compile() and the module-level matching functions are cached, so programs that use only a few regular expressions at a time needn’t worry about compiling regular expressions.

There are two small arguments against this, but (anecdotally speaking) these won't result in noticeable timing differences the majority of the time:

The size of the cache is limited.

Using compiled expressions directly avoids the cache lookup overhead.

Here's a rudimentary test of the above using the 20 newsgroups text dataset.  On a relative basis, the improvement in speed is about 1.6% with compiling, presumably due mostly to cache lookup.

import re
from sklearn.datasets import fetch_20newsgroups

# A list of length ~20,000, paragraphs of text
news = fetch_20newsgroups(subset='all', random_state=444).data

# The tokenizer used by most text-processing vectorizers such as TF-IDF
regex = r'(?u)\b\w\w+\b'
regex_comp = re.compile(regex)

def no_compile():
    for text in news:
        re.findall(regex, text)

def with_compile():
    for text in news:
        regex_comp.findall(text)

%timeit -r 3 -n 5 no_compile()
1.78 s ± 16.2 ms per loop (mean ± std. dev. of 3 runs, 5 loops each)

%timeit -r 3 -n 5 with_compile()
1.75 s ± 12.2 ms per loop (mean ± std. dev. of 3 runs, 5 loops each)

That really only leaves one very defensible reason to use re.compile():

By precompiling all expressions when the module is loaded, the compilation work is shifted to application start time, instead of to a point when the program may be responding to a user action. [source; p. 15]. It's not uncommon to see constants declared at the top of a module with compile.  For example, in smtplib you'll find OLDSTYLE_AUTH = re.compile(r"auth=(.*)", re.I).

Note that compiling happens (eventually) whether or not you use re.compile().  When you do use compile(), you're compiling the passed regex at that moment.  If you use the module-level functions like re.search(), you're compiling and searching in this one call.  The two processes below are equivalent in this regard:

# with re.compile - gets you a regular expression object (class)
#     and then call its method, `.search()`.
a = re.compile('regex[es|p]')  # compiling happens now
a.search('regexp')             # searching happens now

# with module-level function
re.search('regex[es|p]', 'regexp')  # compiling and searching both happen here

Lastly you asked,

Is there a better way to match regular words without regex?

Yes; this is mentioned as a "common problem" in the HOWTO:

Sometimes using the re module is a mistake. If you’re matching a fixed
string, or a single character class, and you’re not using any re
features such as the IGNORECASE flag, then the full power of regular
expressions may not be required. Strings have several methods for
performing operations with fixed strings and they’re usually much
faster, because the implementation is a single small C loop that’s
been optimized for the purpose, instead of the large, more generalized
regular expression engine. [emphasis added]

...

In short, before turning to the re module, consider whether your
problem can be solved with a faster and simpler string method.

ContentLicense: CC BY-SA 3.0


问:
how to split single string and build a StringArray and pass it to ViewPager?
I have String

Lorem ipsum dolor sit amet, consectetur adipiscing elit.\n\nProin rhoncus congue convallis. Quisque fermentum ipsum vitae mauris placerat hendrerit. Nunc ornare fermentum mi, eget blandit massa lobortis quis. Aenean lectus purus, tincidunt eu volutpat nec, malesuada viverra massa. Ut pulvinar tempor ultrices. Vestibulum varius elementum diam sit amet elementum. Phasellus semper tempor massa, non posuere sem semper quis. Aenean ut sem justo. In consequat eleifend magna, iaculis pulvinar dui tincidunt pulvinar. Nullam in est justo, sed sollicitudin eros.\n\nPraesent at ligula quam. Sed lobortis arcu ligula, nec tincidunt diam. Integer ultrices iaculis mi, aliquam rutrum neque pretium nec. Duis vitae orci nulla. Maecenas ac nisl et mauris iaculis ultricies. Aenean imperdiet viverra libero, et ullamcorper arcu scelerisque ut. Vestibulum metus tellus, venenatis in vehicula non, rutrum ut sem. Donec in purus at magna suscipit egestas. Curabitur felis metus, hendrerit nec fermentum nec, tempus condimentum massa. Morbi erat augue, sollicitudin id adipiscing at, porttitor sed ipsum. Duis non massa et elit condimentum cursus vel ut libero.\n\nSed cursus placerat turpis, a ornare turpis porttitor et. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Mauris posuere condimentum sapien, eget facilisis mi faucibus iaculis. Maecenas vitae lectus augue. Pellentesque vitae orci purus. Cras egestas ante nulla. Sed tempus feugiat orci eget sollicitudin. Vestibulum eget risus justo. Etiam ipsum libero, pellentesque non gravida pellentesque, vehicula eget ligula. Etiam id purus massa, sit amet sagittis purus. Etiam sed mattis elit.\n\nIn hac habitasse platea dictumst. Nulla ac pretium diam. Curabitur pharetra magna in mi posuere vulputate. Donec vitae sapien ante. Fusce fermentum diam tempor massa mattis sit amet malesuada metus ullamcorper. Phasellus elementum semper lectus, non adipiscing odio rutrum semper. Nam gravida, velit a blandit ultrices, quam massa consequat neque, sit amet malesuada eros leo eget turpis. Quisque sollicitudin elementum tempor. Maecenas elementum ornare justo, nec malesuada libero accumsan quis. Suspendisse eleifend arcu cursus nulla tincidunt id bibendum enim placerat. Donec eget porttitor nunc. Etiam quis lorem vel dolor interdum hendrerit vel id sapien. Nam ultrices tempus ipsum a dapibus.

I want to this show text like this image see image.
I am facing a problem because ViewPager takes array and creates view according to array size, but here I have a single object string.
So how can i do this? Anyone experience with this?

答: You would have to split the string up yourself. The ViewPager doesn't know how to make this. Probably have it in a ScrollView or using AutoSizing TextViews to make sure all the text can be displayed no matter what screen it's rendered on.</p>


问:
AAD + SAML: Application-specific certificates and metadata
I am quite confused about setting up SAML SSO for an application in Azure Active Directory.

I already have SAML metadata downloaded from the "general" endpoint https://login.microsoftonline.com/[Unique_ID]/FederationMetadata/2007-06/FederationMetadata.xml

However, when I configure my application in AAD, it sets up a signing certificate for the application and there is another link to SAML metadata, which slightly differs from the first, "general", metadata:

The general one contains 3 signing certificates, while the concrete application-specific metadata contains just one: the certificate configured especially for the application on AAD side. The application-specific certificate in not any of the 3 certificates from the general metadata.

The general one is digitally signed, the specific one is not.

Both have the same Entity ID.

I am quite confused about this concept, I haven't seen it on any other IdP server yet. I have already realized I must use the application-specific metadata to configure my Service Party, otherwise the digital signature of SAML assertions will not be verified.

So, my questions are:

Why does AAD provides the option to have application-specific signing certificates and SAML metadata? Why can't I simply use the global metadata/certificates and have all assertions for all applications signed with the same certificate?

Is it somehow possible to disable this feature and only use the global metadata for all Service Parties? The benefit would be clear: having just one IdP metadata instead of N.

答:
Why does AAD provides the option to have application-specific signing certificates and SAML metadata?

One reason this is useful is that you control the certificate rollover. (Not all apps are "well-behaved" and deal correctly with planned certificate rollovers.)

Is it somehow possible to disable this feature and only use the global metadata for all Service Parties?

Sort of.

If you create a new App registration (as opposed to going via Enterprise apps > New app > Custom app), you can do SAML 2.0 against that app, with the details exposed in the "global" federation metadata.

The downside to this approach is that you won't get access to the Enterprise Apps > (app) > Single sign-on section, so you won't be able to do things like choose which attribute is used as the NameID, or have a UI interface to do claims customization (though you can still do custom claims mapping policies).


问:
How do I sort an array of hashes by a value in the hash?
This Ruby code is not behaving as I would expect:

```<code># create an array of hashes
sort_me = []
sort_me.push({"value"=>1, "name"=>"a"})
sort_me.push({"value"=>3, "name"=>"c"})
sort_me.push({"value"=>2, "name"=>"b"})

# sort
sort_me.sort_by { |k| k["value"]}

# same order as above!
puts sort_me
</code>```

I'm looking to sort the array of hashes by the key "value", but they are printed unsorted.

答: You can use sort_me.sort_by!{ |k| k["value"]}. This should work.

Body:
This Ruby code is not behaving as I would expect:

# create an array of hashes
sort_me = []
sort_me.push({"value"=>1, "name"=>"a"})
sort_me.push({"value"=>3, "name"=>"c"})
sort_me.push({"value"=>2, "name"=>"b"})

# sort
sort_me.sort_by { |k| k["value"]}

# same order as above!
puts sort_me

I'm looking to sort the array of hashes by the key "value", but they are printed unsorted.


问:
Ruby/RoR, ActiveRecord - "arrange" method and use "super" in model
System

```<code>[2017-11-13 18:34:46] INFO  WEBrick 1.3.1
[2017-11-13 18:34:46] INFO  ruby 1.9.3 (2012-02-16) [x86_64-linux]
</code>```

Model in Ror, that working (currenct version)

```<code>class Expenditure < ActiveRecord::Base
...
  class << self
    def arrange
      super(:order => :name)
    end
...
</code>```

I tried to add one more field for change order way. "sort_order".
I cannot find method arrange in ActiveRecord, which was redifyned
I have tried unsuccesfully

```<code>super(:order => :sort_order, :name)
</code>```

...

```<code>super.order(:sort_order, :name)
</code>```

答:
Not sure if I understood your question properly, but I think you wanted to use self (not super 'cause there is no arrange method defined in AR) with order method. If you want to order it by sort_order and name in ascending order your method should look like this:

```<code>def arrange
  self.order(:sort_order => :asc, :name => :asc)
end
</code>```

you can even omit self and just use self.order(:sort_order => :asc, :name => :asc)

Body:
System

[2017-11-13 18:34:46] INFO  WEBrick 1.3.1
[2017-11-13 18:34:46] INFO  ruby 1.9.3 (2012-02-16) [x86_64-linux]

Model in Ror, that working (currenct version)

class Expenditure < ActiveRecord::Base
...
  class << self
    def arrange
      super(:order => :name)
    end
...

I tried to add one more field for change order way. "sort_order".
I cannot find method arrange in ActiveRecord, which was redifyned
I have tried unsuccesfully

super(:order => :sort_order, :name)

...

super.order(:sort_order, :name)

Body:
Not sure if I understood your question properly, but I think you wanted to use self (not super 'cause there is no arrange method defined in AR) with order method. If you want to order it by sort_order and name in ascending order your method should look like this:

def arrange
  self.order(:sort_order => :asc, :name => :asc)
end

you can even omit self and just use self.order(:sort_order => :asc, :name => :asc)


问:
Is there an efficient way to find out whether a queue item is "before" another one?
For my Java application, I need some method that finds out if item1 is "before" item2 in my Queue Q. Of course, I can just use an iterator and start traversing the list. However, maybe there is another way of finding this out?

For my specific application, I can't use a LinkedList (which provides indexes and makes it easy to determine if one object is before another).

答: I recommend priority queue that could reference a lookup table.  That way, you get constant performance for the element you want to get, and polynomial insert costs.  However, this may be specialized for your uses if you're simply trying to do a comparision, rather than find the best or worst priority item.  However, the constant performance is always nice. and then you're not iterating an array necessarily, but just looking up.</p>


问:
How to structure an array of multiple outputs in one array (Java)
My code basically runs through an array, finds the maximum, and then locates the indices correlated with it. The issue I have is that I would like the indices in one array instead of multiple.

For example (actual output):

```<code>[1] [2] [3] [4]
</code>```

Wanted output: [1,2,3,4]

Here is my code:

```<code> int index;
    int num = myArray[0];
    for (int i = 0; i < myArray.length; i++) {
        if (num < myArray[i]) {
            num = myArray[i];
        }
    }
    for (int j = 0; j < myArray.length; j++) {
        if(num == myArray[j]){
               index = j;
               System.out.println("[" + j + "]");
        }
    }
</code>```

I don't know how to do this without redoing all the code. Thanks.

答:
```<code>int maxValue = myArray[0];
int countMaxValues = 1;
for (int i = 1; i < myArray.length; i++) {
    if (myArray[i] > maxValue) {
        maxValue = myArray[i];
        countMaxValues = 1;
    }
    else if (myArray[i] == maxValue) {
        countMaxValues++;
    }
}

int maxValueIndices = new int[countMaxValues];
int i = 0;
for (int j = 0; j < myArray.length; j++) {
    if(myArray[j] == maxValue){
        maxValueIndices[i++] = j;
    }
}

System.out.println(Arrays.toString(maxValueIndices));
</code>```

Body:
My code basically runs through an array, finds the maximum, and then locates the indices correlated with it. The issue I have is that I would like the indices in one array instead of multiple.

For example (actual output):

[1] [2] [3] [4]

Wanted output: [1,2,3,4]

Here is my code:

 int index;
    int num = myArray[0];
    for (int i = 0; i < myArray.length; i++) {
        if (num < myArray[i]) {
            num = myArray[i];
        }
    }
    for (int j = 0; j < myArray.length; j++) {
        if(num == myArray[j]){
               index = j;
               System.out.println("[" + j + "]");
        }
    }

I don't know how to do this without redoing all the code. Thanks.


问:
JMeter read file to array
I am trying to read these items from .csv file to array separating variables by comma or dot.

I would like to get:

http://www.example.com/GH001.GH002.KL003.KL010.json

Any ideas?

I tried using Bean Shell PreProcessor, but it doesn't work.

```<code>String Articles = "${__StringFromFile(C:\docs\loadtest\articles.csv,,,)}";

String[] Articles1 = Articles.split(",");

vars.put("Articles1",Articles1);
</code>```

答:
Since JMeter 3.1 it is recommended to use JSR223 Test Elements and Groovy language so I would suggest switching to Groovy.

The relevant code would be something like:

```<code>def lines = new File('C:/docs/loadtest/articles.csv').readLines()
def articles = new String()
lines.each { line ->
    articles += line += '.'
}

vars.put('Articles1',articles);
</code>```

See Apache Groovy - Why and How You Should Use It article for more information, benchmarks, tips and tricks.

Title: JMeter read file to array

Body:
I am trying to read these items from .csv file to array separating variables by comma or dot.

I would like to get:

http://www.example.com/GH001.GH002.KL003.KL010.json

Any ideas?

I tried using Bean Shell PreProcessor, but it doesn't work.

String Articles = "${__StringFromFile(C:\docs\loadtest\articles.csv,,,)}";

String[] Articles1 = Articles.split(",");

vars.put("Articles1",Articles1);

Body:
Since JMeter 3.1 it is recommended to use JSR223 Test Elements and Groovy language so I would suggest switching to Groovy.

The relevant code would be something like:

def lines = new File('C:/docs/loadtest/articles.csv').readLines()
def articles = new String()
lines.each { line ->
    articles += line += '.'
}

vars.put('Articles1',articles);

See Apache Groovy - Why and How You Should Use It article for more information, benchmarks, tips and tricks.


问:
Elegant Solution avoiding Global Variable
I am trying to find an elegant and still readable Way of getting rid of that global Var. But cannot find a way to do it. no jQuery please it should work without any imports.

```

答:
You can bind the property to your ajax function, but really the cleanest way would to use Scott Marcus's answer.</p>

```<code>function ajax(f) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      f(this.responseText);
    }
  };
  xhttp.open("POST", "ajax1.php", true); // SELECT COUNT(*)
  xhttp.send();
}
ajax.anzahlErg = 0; // This is now a property of the ajax object and not the window object

function anfang(response) {
  ajax.anzahlErg = response;
}

function nachher(response) {
  if (ajax.anzahlErg != 0 && response != ajax.anzahlErg) {
    location.reload();
  }
}

window.onload = ajax(anfang);
  setInterval(function() {
    return ajax(nachher)
}, 250); //Polling Interval
</code>```

Body:
You can bind the property to your ajax function, but really the cleanest way would to use Scott Marcus's answer.

function ajax(f) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      f(this.responseText);
    }
  };
  xhttp.open("POST", "ajax1.php", true); // SELECT COUNT(*)
  xhttp.send();
}
ajax.anzahlErg = 0; // This is now a property of the ajax object and not the window object

function anfang(response) {
  ajax.anzahlErg = response;
}

function nachher(response) {
  if (ajax.anzahlErg != 0 && response != ajax.anzahlErg) {
    location.reload();
  }
}

window.onload = ajax(anfang);
  setInterval(function() {
    return ajax(nachher)
}, 250); //Polling Interval


问:
colon misplaced by tkinter BiDi
I'm working on a cross-platform python GUI application, using tkinter.

I created a Label with a Hebrew text, ending with ':', but, on Windows - the ':' is placed at the start of the string: שלום: instead of :שלום.

I even tried constructing the string as follows:

```<code>hebrewString  = 'ש'
hebrewString += 'ל'
hebrewString += 'ו'
hebrewString += 'ם'
hebrewString += ':'
</code>```

Debugging, step-by-step in the IDE (PyCharm) displays the construction of the string correctly - :שלום.

I understand that tkinter doesn't implement BiDi on Linux: see this, so on Linux I'm using bidi.algorithm.get_display(hebrewString), and it's displayed correctly.

答:
The += operator will simply append the string you give it to the variable you declare.

This means that saying:

```<code>hebrewString  = 'שלום'
hebrewString += ':'
</code>```

Is the same as saying:

```<code>hebrewString  = 'שלום' + ':'
</code>```

Which would return שלום:.

Instead you can do something like the below:

```<code>hebrewString  = 'שלום'
hebrewString  = ':' + hebrewString

print(hebrewString)
</code>```

If you simply run the below:

```<code>hebrewString = 'ם'
hebrewString += ':'

print(hebrewString)
</code>```

You'll see that Python simply appends the colon to the end of the string, not the beginning as it should be in hebrew.

Title: colon misplaced by tkinter BiDi

Body:
I'm working on a cross-platform python GUI application, using tkinter.

I created a Label with a Hebrew text, ending with ':', but, on Windows - the ':' is placed at the start of the string: שלום: instead of :שלום.

I even tried constructing the string as follows:

hebrewString  = 'ש'
hebrewString += 'ל'
hebrewString += 'ו'
hebrewString += 'ם'
hebrewString += ':'

Debugging, step-by-step in the IDE (PyCharm) displays the construction of the string correctly - :שלום.

I understand that tkinter doesn't implement BiDi on Linux: see this, so on Linux I'm using bidi.algorithm.get_display(hebrewString), and it's displayed correctly.

Body:
The += operator will simply append the string you give it to the variable you declare.

This means that saying:

hebrewString  = 'שלום'
hebrewString += ':'

Is the same as saying:

hebrewString  = 'שלום' + ':'

Which would return שלום:.

Instead you can do something like the below:

hebrewString  = 'שלום'
hebrewString  = ':' + hebrewString

print(hebrewString)

If you simply run the below:

hebrewString = 'ם'
hebrewString += ':'

print(hebrewString)

You'll see that Python simply appends the colon to the end of the string, not the beginning as it should be in hebrew.


问:
Unable to connect to local RabbitMQ on Windows 10
I've installed RabbitMQ (latest version downloadable from RabbitMQ website) on my Windows 10 machine. It installed with ERlang 19.1.

I'm trying to install RabbitMQ Web UI Management Tools using the following command (using RabbitMQ Command Prompt):

```<code>rabbitmq-plugins enable rabbitmq_management
</code>```

I'm getting the following error:

```<code>The directory name is invalid.
The filename, directory name, or volume label syntax is incorrect.
The filename, directory name, or volume label syntax is incorrect.
Plugin configuration unchanged.

Applying plugin configuration to rabbit@[0x7FF9A8527044]... failed.
 * Could not contact node rabbit@[0x7FF9A8527044].
   Changes will take effect at broker restart.
 * Options: --online  - fail if broker cannot be contacted.
            --offline - do not try to contact broker.
</code>```

I've looked up on SO and tried stopping and restarting, overriding erlang cookie, but nothing helps.

I think there's a problem with RabbitMQ itself. The service itself is marked as started, but if I try to telnet the default port (5672) then it fails (it's not a firewall issue - I've disabled it).

Also I don't see an  log files created for RabbitMQ or any related Event Logs messages. So it's hard to diagnose exactly the problem.

I also tried uninstalling and re-install both erlang and RabbitMQ. Still didn't help.

How do I further diagnose the problem?

答:
In my case I had to trash the local account config located at : %APPDATA%\RabbitMQ\.
Deleting the entire folder and reinstalling the service did the trick.

Rabbitmq 3.6.14

Erlang 20.1 OTP

Body:
I've installed RabbitMQ (latest version downloadable from RabbitMQ website) on my Windows 10 machine. It installed with ERlang 19.1.

I'm trying to install RabbitMQ Web UI Management Tools using the following command (using RabbitMQ Command Prompt):

rabbitmq-plugins enable rabbitmq_management

I'm getting the following error:

The directory name is invalid.
The filename, directory name, or volume label syntax is incorrect.
The filename, directory name, or volume label syntax is incorrect.
Plugin configuration unchanged.

Applying plugin configuration to rabbit@[0x7FF9A8527044]... failed.
 * Could not contact node rabbit@[0x7FF9A8527044].
   Changes will take effect at broker restart.
 * Options: --online  - fail if broker cannot be contacted.
            --offline - do not try to contact broker.

I've looked up on SO and tried stopping and restarting, overriding erlang cookie, but nothing helps.

I think there's a problem with RabbitMQ itself. The service itself is marked as started, but if I try to telnet the default port (5672) then it fails (it's not a firewall issue - I've disabled it).

Also I don't see an  log files created for RabbitMQ or any related Event Logs messages. So it's hard to diagnose exactly the problem.

I also tried uninstalling and re-install both erlang and RabbitMQ. Still didn't help.

How do I further diagnose the problem?


问:
Check how long was a button pressed
I am making a simulator in which I have a button with different behavior depending on the duration of the press.

If the button is pressed less than 3 seconds, prints nothing, between 3 and 10, prints 1 and higher than 10 prints 2.

Should I try with MouseListener or ActionListener? Any example code would be great! Thanks.

答:
Listen to changes in the pressed property:</p>

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

    private long startTime;

    @Override
    public void start(Stage primaryStage) {

        Button btn = new Button("Hold");
        Label label= new Label();
        btn.pressedProperty().addListener((obs, wPressed, pressed) -> {
            if (pressed) {
               startTime =  System.nanoTime();
               label.setText("");
            } else {
                label.setText("Button was pressed for "+ (System.nanoTime() - startTime) + " nanos");
            }
        });
        Pane root = new VBox(btn, label);
        Scene scene = new Scene(root, 300, 100);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch();
    }
}
</code>```

Title: Check how long was a button pressed

Body:
Listen to changes in the pressed property:

public class StageTest extends Application{

    private long startTime;

    @Override
    public void start(Stage primaryStage) {

        Button btn = new Button("Hold");
        Label label= new Label();
        btn.pressedProperty().addListener((obs, wPressed, pressed) -> {
            if (pressed) {
               startTime =  System.nanoTime();
               label.setText("");
            } else {
                label.setText("Button was pressed for "+ (System.nanoTime() - startTime) + " nanos");
            }
        });
        Pane root = new VBox(btn, label);
        Scene scene = new Scene(root, 300, 100);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch();
    }
}


问:
Why does a numpy int16 take 24 bytes
I am trying to figure out the system memory some python variables take

In the following code:

```<code>    >>> a = numpy.int16(1)
    >>> a.nbytes
    2
    >>> sys.getsizeof(a)
    24
</code>```

Why does a numpy int16 take 24 bytes of space according to sys.getsizeof() ?

答:
From the docs:

getsizeof() calls the object’s __sizeof__ method and adds an additional garbage collector overhead if the object is managed by the garbage collector.

So:

sys.sizeof is the size of the whole object, warts and all;

nbytes returns the memory used just by the array's actual data only, no frills.

Title: Why does a numpy int16 take 24 bytes

Body:
I am trying to figure out the system memory some python variables take

In the following code:

    >>> a = numpy.int16(1)
    >>> a.nbytes
    2
    >>> sys.getsizeof(a)
    24

Why does a numpy int16 take 24 bytes of space according to sys.getsizeof() ?


问:
Closing a channel at the producer end when all the jobs are finished
For my Mandelbrot explorer project, I need to run several expensive jobs, ideally in parallel. I decided to try chunking the jobs, and running each chunk in its own thread, and end ended up with something like

```<code>(defn point-calculator [chunk-size points]
  (let [out-chan (chan (count points))
        chunked (partition chunk-size points)]

    (doseq [chunk chunked]
      (thread
        (let [processed-chunk (expensive-calculation chunk)]
          (>!! out-chan processed-chunk))))

    out-chan))
</code>```

Where points is a list of [real, imaginary] coordinates to be tested, and expensive-calculation is a function that takes the chunk, and tests each point in the chunk. Each chunk can take a long time to finish (potentially a minute or more depending on the chunk size and the number of jobs).

On my consumer end, I'm using

```<code>(loop []
  (when-let [proc-chunk (<!! result-chan)]
   ; Do stuff with chunk
   (recur)))
</code>```

To consume each processed chunk. Right now, this blocks when the last chunk is consumed since the channel is still open.

I need a way of closing the channel when the jobs are done. This is proving difficult because of asynchronicity of the producer loop. I can't simply put a close! after the doseq since the loop doesn't block, and I can't just close when the last-indexed job is done, since the order is indeterminate.

The best idea I could come up with was maintaining a (atom #{}) of jobs, and disj each job as it finishes. Then I could either check for the set size in the loop, and close! when it's 0, or attach a watch to the atom and check there.

This seems very hackish though. Is there a more idiomatic way of dealing with this? Does this scenario suggest I'm using async incorrectly?

答:
You may want to use async/pipeline(-blocking) to control parallelisms. And use aysnc/onto-chan to close the input channel automatically after all the chunks are copied.

E.g. below example shows a 16x improvement on elapsed time when parallelisms is set to 16.

```<code>(defn expensive-calculation [pts]
  (Thread/sleep 100)
  (reduce + pts))

(time
 (let [points     (take 10000 (repeatedly #(rand 100)))
       chunk-size 500
       inp-chan   (chan)
       out-chan   (chan)]
   (go-loop [] (when-let [res (<! out-chan)]
                 ;; do stuff with chunk
                 (recur)))
   (pipeline-blocking 16 out-chan (map expensive-calculation) inp-chan)
   (<!! (onto-chan inp-chan (partition-all chunk-size points)))))
</code>```

Body:
For my Mandelbrot explorer project, I need to run several expensive jobs, ideally in parallel. I decided to try chunking the jobs, and running each chunk in its own thread, and end ended up with something like

(defn point-calculator [chunk-size points]
  (let [out-chan (chan (count points))
        chunked (partition chunk-size points)]

    (doseq [chunk chunked]
      (thread
        (let [processed-chunk (expensive-calculation chunk)]
          (>!! out-chan processed-chunk))))

    out-chan))

Where points is a list of [real, imaginary] coordinates to be tested, and expensive-calculation is a function that takes the chunk, and tests each point in the chunk. Each chunk can take a long time to finish (potentially a minute or more depending on the chunk size and the number of jobs).

On my consumer end, I'm using

(loop []
  (when-let [proc-chunk (<!! result-chan)]
   ; Do stuff with chunk
   (recur)))

To consume each processed chunk. Right now, this blocks when the last chunk is consumed since the channel is still open.

I need a way of closing the channel when the jobs are done. This is proving difficult because of asynchronicity of the producer loop. I can't simply put a close! after the doseq since the loop doesn't block, and I can't just close when the last-indexed job is done, since the order is indeterminate.

The best idea I could come up with was maintaining a (atom #{}) of jobs, and disj each job as it finishes. Then I could either check for the set size in the loop, and close! when it's 0, or attach a watch to the atom and check there.

This seems very hackish though. Is there a more idiomatic way of dealing with this? Does this scenario suggest I'm using async incorrectly?

Body:
You may want to use async/pipeline(-blocking) to control parallelisms. And use aysnc/onto-chan to close the input channel automatically after all the chunks are copied.

E.g. below example shows a 16x improvement on elapsed time when parallelisms is set to 16.

(defn expensive-calculation [pts]
  (Thread/sleep 100)
  (reduce + pts))

(time
 (let [points     (take 10000 (repeatedly #(rand 100)))
       chunk-size 500
       inp-chan   (chan)
       out-chan   (chan)]
   (go-loop [] (when-let [res (<! out-chan)]
                 ;; do stuff with chunk
                 (recur)))
   (pipeline-blocking 16 out-chan (map expensive-calculation) inp-chan)
   (<!! (onto-chan inp-chan (partition-all chunk-size points)))))


问:
How do I know if `collapse_key` is working on FCM/GCM?
I am using a collapse key in my payload to FCM
https://firebase.google.com/docs/cloud-messaging/concept-options#collapsible_and_non-collapsible_messages

Is there somewhere on google services where I can verify these are configured correctly?

I don't see any indication in the docs on how to tell if it is configured right.  I know I can turn off a device and seeing what happens when you stack them up.  It seems straight forward since it is just a key value pair, but I would love to verify implementation before launching.

The notifications I am sending still come through so that is a good sign.

答: You can look at them in the GCM/FCM console and it will tell you there.  You just need the unique id of one of your pushes that is returned on a successful request.  </p>


问:
super.super.func()? - Java polymorphism
Say that I in Java have 3 classes, wheres the super one has a function named func(), I now make a subclass which overrides this, and a subclass to my subclass, now working on my sub-sub-class how will I call the 'func()' of the sub class, and the superclass?

I tried casting the 'this' "pointer", but Java 'fixes' it at runtime and calls the subsub func().

Edit:
Thanks everyone; 'Skeen is back at the drawing board'.

答:
This example is the only way to call a "grandparent" super method.

```<code>class A{
    public void foo(){ System.out.println("Hi"); }
}

class B extends A{
    public void foo(){ super(); }
}

class C extends B{
    public void foo(){ super(); }
}
</code>```

This would be a different story if B doesn't override foo().

Another option would be to have a "protected helper" method in the middle class.

```<code>class D{
    public void foo(){ System.out.println("Hi"); }
}

class E extends D{
    public void foo(){ System.out.println("Hello"); }
    protected void bar(){ super.foo(); }
}

class F extends E{
    public void foo(){ super.bar(); }
}
</code>```

Title: super.super.func()? - Java polymorphism

Body:
This example is the only way to call a "grandparent" super method.

class A{
    public void foo(){ System.out.println("Hi"); }
}

class B extends A{
    public void foo(){ super(); }
}

class C extends B{
    public void foo(){ super(); }
}

This would be a different story if B doesn't override foo().

Another option would be to have a "protected helper" method in the middle class.

class D{
    public void foo(){ System.out.println("Hi"); }
}

class E extends D{
    public void foo(){ System.out.println("Hello"); }
    protected void bar(){ super.foo(); }
}

class F extends E{
    public void foo(){ super.bar(); }
}


问:
Java Swing Resizing the JFrame and JPanel with all drawn Elements
I'm developing a game in Java Swing. I use absolut coords and a fixed window size in order to set every element in its place. But if I resize the JFrame, the drawn elements dont scale. How can I achieve that?
In my example I would set the default window size to 1280 x 720 and develop the game according to this size. Then it'd be perfect to just let java automatically resize the elements.</p>

答:
If you want a fixed size window, you can use JFrame.setResizable(boolean) API to make your window non-resizable. Example:</p>

```<code>public class FixedSizeJFrame
{
  public static void main(String[] args)
  {
    JFrame frame = new JFrame("My Title");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setBounds(100, 100, 1280, 720);
    frame.getContentPane().add(new JLabel("My Label"), BorderLayout.NORTH);
    frame.getContentPane().add(new JTextArea("Sample text"), BorderLayout.CENTER);
    frame.setResizable(false);
    frame.setVisible(true);
  }
}
</code>```

Body:
If you want a fixed size window, you can use JFrame.setResizable(boolean) API to make your window non-resizable. Example:

public class FixedSizeJFrame
{
  public static void main(String[] args)
  {
    JFrame frame = new JFrame("My Title");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setBounds(100, 100, 1280, 720);
    frame.getContentPane().add(new JLabel("My Label"), BorderLayout.NORTH);
    frame.getContentPane().add(new JTextArea("Sample text"), BorderLayout.CENTER);
    frame.setResizable(false);
    frame.setVisible(true);
  }
}


问:
Value of getSpeed() function is different to the calculated value
I use OMNeT++-4.6, sumo-0.22.0 and Veins-4a2.

I am interested to calculate the speed of the vehicle when a message is received. I used getSpeed() function to do it. But the problem is that when I calculated manually the speed basing on the time and the distance (using the formula  s = d / t), the value is different.

For example, at t= 55.104470531278 s and the distance d= 29.0477 m, the speed obtained by calling the function getSpeed() is s= 3.34862 m/s = 10.8 km/h.
On the other hand the one calculated manually is s= 0.52713 m/s = 1.9 km/h.

I need help to understand why the value obtained by using getSpeed() is different please.

答: getSpeed() returns the current speed of the vehicle (to be precise the one in the last simulation step which is by default 1s) while your calculation gives the average speed over the last ~55s (assuming your simulation started at time 0).


问:
Display time data with telerik chart
We need to visualize the number of forms submitted over a 2 week period where it is broken down by day/hour.

I have the query returning data such as:

My question is, how do I tell MS chart to display this data?  When I bind it I get the following:

I'd like it to expand out and show the hours between the dates.

答:
You could create a List of DateTime objects, each object could add the DateCompletedHour to the DateCompleted value and then bind your chart to the List:</p>

```<code>        IList<DateTime> ChartData = new List<DateTime>();
        foreach (var row in formDataSource)
        {
            DateTime dt = DateTime.Parse(row["DateCompleted"]);
            dt.AddHours(Convert.ToInt16(row["DateCompletedHour"]));
            ChartData.Add(dt);
        }

        FormChart chart = new FormChart();
        chart.DataSource = ChartData;
        chart.DataBind();
</code>```

Title: Display time data with telerik chart

Body:
You could create a List of DateTime objects, each object could add the DateCompletedHour to the DateCompleted value and then bind your chart to the List:

        IList<DateTime> ChartData = new List<DateTime>();
        foreach (var row in formDataSource)
        {
            DateTime dt = DateTime.Parse(row["DateCompleted"]);
            dt.AddHours(Convert.ToInt16(row["DateCompletedHour"]));
            ChartData.Add(dt);
        }

        FormChart chart = new FormChart();
        chart.DataSource = ChartData;
        chart.DataBind();


问:
BottomSheetDialogFragment setupDialog restricted to library group
I'm using BottomSheetDialogFragment from the support library and it warns me that the function setupDialog() should only be used within the library group. But this function is the place where I initialize my dialog:

```<code>@Override
public void setupDialog(final Dialog dialog, int style) {
    super.setupDialog(dialog, style);
    FragmentArgs.inject(this);

    dialog.setOnShowListener(dialogINterface -> {
        if(dialog.getWindow() != null) {
            dialog.getWindow().setLayout(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
        }
    });

    BottomSheetStatisticsExportBinding binding = DataBindingUtil.inflate(
            LayoutInflater.from(getContext()),
            R.layout.bottom_sheet_statistics_export,
            null,
            false
    );

    View contentView = binding.getRoot();
    dialog.setContentView(contentView);

    CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) ((View) contentView.getParent()).getLayoutParams();
    CoordinatorLayout.Behavior behavior = params.getBehavior();

    if( behavior != null && behavior instanceof BottomSheetBehavior )
        ((BottomSheetBehavior) behavior).setBottomSheetCallback(bottomSheetBehaviorCallback);

    for (Export export : exports)
        binding.flexbox.addView(new ExportItemView(getContext(), export));
}
</code>```

The warning is because I'm using the super method. But what should I do instead? Should I move my code inside another function (onCreateDialog(), onResume()...?), should I remove the call to the super?

Anyone knows?

答:
Should I move my code inside another function (onCreateDialog(),
  onResume()...?)

Yes. As it demonstrates in the DialogFragment documentation (which BottomSheetDialogFragment extends), you should use onCreateView() to set up your dialog.

The View you return from this method will be set as the content view for the dialog provided by onCreateDialog(). And the getDialog() method can be used from within onCreateView() to make any adjustments to the aforementioned Dialog.

onCreateDialog() would be used to replace the default Dialog. Which in your case you probably don't want to do; considering that is the method BottomSheetDialogFragment uses to replace the default Dialog with a BottomSheetDialog (in fact, it is the only method BottomSheetDialogFragment overrides).

Here are the BottomSheetDialog and BottomSheetDialogFragment classes I created to replace the support library versions (see comments for more information).

Body:
I'm using BottomSheetDialogFragment from the support library and it warns me that the function setupDialog() should only be used within the library group. But this function is the place where I initialize my dialog:

@Override
public void setupDialog(final Dialog dialog, int style) {
    super.setupDialog(dialog, style);
    FragmentArgs.inject(this);

    dialog.setOnShowListener(dialogINterface -> {
        if(dialog.getWindow() != null) {
            dialog.getWindow().setLayout(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
        }
    });

    BottomSheetStatisticsExportBinding binding = DataBindingUtil.inflate(
            LayoutInflater.from(getContext()),
            R.layout.bottom_sheet_statistics_export,
            null,
            false
    );

    View contentView = binding.getRoot();
    dialog.setContentView(contentView);

    CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) ((View) contentView.getParent()).getLayoutParams();
    CoordinatorLayout.Behavior behavior = params.getBehavior();

    if( behavior != null && behavior instanceof BottomSheetBehavior )
        ((BottomSheetBehavior) behavior).setBottomSheetCallback(bottomSheetBehaviorCallback);

    for (Export export : exports)
        binding.flexbox.addView(new ExportItemView(getContext(), export));
}

The warning is because I'm using the super method. But what should I do instead? Should I move my code inside another function (onCreateDialog(), onResume()...?), should I remove the call to the super?

Anyone knows?


问:
Value set by +uvm_set_config_int is not matched
I am trying to set configuration by using this command line option:

```<code>+uvm_set_config_int= \*,path_index,1
</code>```

In a sequence body task, I am looking for the value:

```<code>if (!uvm_config_db#(int)::get(null, "", "path_index", i)) begin
end
</code>```

The value is not found.

If instead of a command line option, I am setting the value in the build phase of the test:

```<code>uvm_config_db #(int)::set(null, "*", "path_index", 1)
</code>```

The value is found by the sequence.

I checked the UVM configuration viewer, and it looks like in both cases scope pattern is the same.  Please advise.

答:
Try uvm_bitstream_t instead of int:

```<code>if (!uvm_config_db#(uvm_bitstream_t)::get(null, "", "path_index",i)) begin
end
</code>```

Body:
I am trying to set configuration by using this command line option:

+uvm_set_config_int= \*,path_index,1

In a sequence body task, I am looking for the value:

if (!uvm_config_db#(int)::get(null, "", "path_index", i)) begin
end

The value is not found.

If instead of a command line option, I am setting the value in the build phase of the test:

uvm_config_db #(int)::set(null, "*", "path_index", 1)

The value is found by the sequence.

I checked the UVM configuration viewer, and it looks like in both cases scope pattern is the same.  Please advise.

Body:
Try uvm_bitstream_t instead of int:

if (!uvm_config_db#(uvm_bitstream_t)::get(null, "", "path_index",i)) begin
end


问:
Error:android-apt plugin is incompatible with the Android Gradle plugin. Please use 'annotationProcessor' configuration instead

i got this error Error:android-apt plugin is incompatible with the
  Android Gradle plugin.  Please use 'annotationProcessor' configuration
  instead.  when i am adding butterknife
  is ther any thing wrong i am doing with dependency adding what dependancy should i use  for latest android studio

build.gradle(module:app) file below

```<code>apply plugin: 'com.android.application'
apply plugin: 'android-apt'
android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "com.example.sony.welcomefilemanager"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation 'com.android.support:support-v4:26.1.0'
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support:design:26.+'
    compile 'com.android.support:support-vector-drawable:26.+'
    compile 'com.android.support:design:26+'
    compile 'com.android.support:recyclerview-v7:26+'
    compile 'com.android.support:cardview-v7:26.+'
    compile 'com.jakewharton:butterknife:7.0.1'
    apt 'com.jakewharton:butterknife-compiler:8.0.1'
    testCompile 'junit:junit:4.12'
}
</code>```

build.gradle(project) file below

```<code>buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        google()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

答:
The android-apt plugin has been deprecated.

As of the Android Gradle plugin version 2.2, all functionality that was previously provided by android-apt is now available in the Android plugin.

Make sure you are on the Android Gradle 2.2 plugin or newer.

Remove the android-apt plugin from your build scripts

Change all (if any) apt, androidTestApt and testApt dependencies to their new format

Body:
i got this error Error:android-apt plugin is incompatible with the
  Android Gradle plugin.  Please use 'annotationProcessor' configuration
  instead.  when i am adding butterknife
  is ther any thing wrong i am doing with dependency adding what dependancy should i use  for latest android studio

build.gradle(module:app) file below

apply plugin: 'com.android.application'
apply plugin: 'android-apt'
android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "com.example.sony.welcomefilemanager"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation 'com.android.support:support-v4:26.1.0'
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support:design:26.+'
    compile 'com.android.support:support-vector-drawable:26.+'
    compile 'com.android.support:design:26+'
    compile 'com.android.support:recyclerview-v7:26+'
    compile 'com.android.support:cardview-v7:26.+'
    compile 'com.jakewharton:butterknife:7.0.1'
    apt 'com.jakewharton:butterknife-compiler:8.0.1'
    testCompile 'junit:junit:4.12'
}

build.gradle(project) file below

buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        google()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}


问:
Using shift function from cats effect
I am trying to use cats effect shift function to run the code asynchronous.

The function implementation:

```<code>  def asyncSendMsg(producer: KkProducer)(record: KkRecord) : IO[Either[String, RecordMetadata]] =
    for {
      res <- trySendMsg(producer)(record).shift(BlockingFileIO).shift(Main)
    } yield(res)

  def trySendMsg(producer: KkProducer)(record: KkRecord): IO[Either[String, RecordMetadata]] =
    IO {
      try {
        Right(producer.send(record).get())
      } catch {
        case e: Exception => Left(e.getMessage())
      }
    }
</code>```

Trying to compile, I receive:

```<code>[error] /home/developer/Desktop/scala/PureProducer/src/main/scala/TheProducer.scala:51:43: value shift is not a member of cats.effect.IO[Either[String,org.apache.kafka.clients.producer.RecordMetadata]]
[error]       res <- trySendMsg(producer)(record).shift(BlockingFileIO).shift(Main)
[error]                                           ^
[error] one error found
[error] (compile:compileIncremental) Compilation failed
[error] Total time: 2 s, completed Nov 13, 2017 2:18:06 PM
</code>```

Which library do I have to import to use shift function?

答:
IO.shift is defined on the companion object of IO (the API has changed between versions of cats), and you can use it in a for comprehension prior to invoking your IO call:

```<code>val nonBlockingExecContext = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(10))

val res = for {
  _ <- IO { println(Thread.currentThread().getName) }
  _ <- IO.shift(nonBlockingExecContext)
  _ <- IO { println(Thread.currentThread().getName) }
} yield ()

res.unsafeRunSync()
</code>```

Yields:

```<code>main
pool-1-thread-1
</code>```

Title: Using shift function from cats effect

Body:
I am trying to use cats effect shift function to run the code asynchronous.

The function implementation:

  def asyncSendMsg(producer: KkProducer)(record: KkRecord) : IO[Either[String, RecordMetadata]] =
    for {
      res <- trySendMsg(producer)(record).shift(BlockingFileIO).shift(Main)
    } yield(res)

  def trySendMsg(producer: KkProducer)(record: KkRecord): IO[Either[String, RecordMetadata]] =
    IO {
      try {
        Right(producer.send(record).get())
      } catch {
        case e: Exception => Left(e.getMessage())
      }
    }

Trying to compile, I receive:

[error] /home/developer/Desktop/scala/PureProducer/src/main/scala/TheProducer.scala:51:43: value shift is not a member of cats.effect.IO[Either[String,org.apache.kafka.clients.producer.RecordMetadata]]
[error]       res <- trySendMsg(producer)(record).shift(BlockingFileIO).shift(Main)
[error]                                           ^
[error] one error found
[error] (compile:compileIncremental) Compilation failed
[error] Total time: 2 s, completed Nov 13, 2017 2:18:06 PM

Which library do I have to import to use shift function?

Body:
IO.shift is defined on the companion object of IO (the API has changed between versions of cats), and you can use it in a for comprehension prior to invoking your IO call:

val nonBlockingExecContext = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(10))

val res = for {
  _ <- IO { println(Thread.currentThread().getName) }
  _ <- IO.shift(nonBlockingExecContext)
  _ <- IO { println(Thread.currentThread().getName) }
} yield ()

res.unsafeRunSync()

Yields:

main
pool-1-thread-1


问:
jQuery Syntax Help
I'm looking for some help explaining exactly what this line of code does in jQuery;

```<code>myString += $(settings.mySelector,this).css('display') === 'none' ? 'closed' : 'not-closed';
</code>```

I'm unfamiliar with the syntax and some of the operators used.

答:
it's a tertiary if/then statement. it says, that myString+= (myString=myString+) the result of the first evaluation,  $(settings.mySelector,this).css('display') === 'none'

if that statement evaluates as true, meaning that they referenced element is hidden, then pass back 'closed' else pass back 'open'

so myString either +='closed' or myString+='open'

Title: jQuery Syntax Help

Body:
I'm looking for some help explaining exactly what this line of code does in jQuery;

myString += $(settings.mySelector,this).css('display') === 'none' ? 'closed' : 'not-closed';

I'm unfamiliar with the syntax and some of the operators used.


问:
Issue with google sheets API quickstart (v4)
I'm trying to go through the following tutorial:
https://developers.google.com/sheets/api/quickstart/nodejs#

And when I get to the step to run the quick start file
node quickstart.js I get the following error message:
Olivers-MacBook-Pro:incrementum oliverpike$ node quickstart.js

```<code>undefined:1

SyntaxError: Unexpected end of JSON input
    at Object.parse (native)
    at /Volumes/github-image/bitcoin-core/quickstart.js:43:39
    at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:445:3)
</code>```

quickstart.js is trying to read from ~/.credentials/sheets.googleapis.com-nodejs-quickstart.json but that file is empty which is resulting in the unexpected end of JSON input error.

How do I determine what needs to go in that file?

答: Remove the file and the code will trigger an else condition to get authentication.

Body:
I'm trying to go through the following tutorial:
https://developers.google.com/sheets/api/quickstart/nodejs#

And when I get to the step to run the quick start file
node quickstart.js I get the following error message:
Olivers-MacBook-Pro:incrementum oliverpike$ node quickstart.js

undefined:1

SyntaxError: Unexpected end of JSON input
    at Object.parse (native)
    at /Volumes/github-image/bitcoin-core/quickstart.js:43:39
    at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:445:3)

quickstart.js is trying to read from ~/.credentials/sheets.googleapis.com-nodejs-quickstart.json but that file is empty which is resulting in the unexpected end of JSON input error.

How do I determine what needs to go in that file?


问:
PHP/XML - checking if a node is set
I have an XML document structured like this:

```<code><produkter>
    <produkt>
        <forhandler></forhandler>
        <produktnavn></produktnavn>
        and so on...
    </produkt>
</produkter>
</code>```

I am pulling out data like this:

```<code>$produktnavn = utf8_decode($xmlObject->item($i)->getElementsByTagName('produktnavn')->item(0)->childNodes->item(0)->nodeValue);
</code>```

Now I am looking to do a check to see if the node is present in the XML document at all.

For example... I only want to make the operation above if there actually IS a node called "produktnavn".

I am trying with:

```<code>if (isset($xmlObject->item($i)->forhandler)) {
</code>```

But this doesn't seem to work.

What an I doing wrong?

答:
The result of getElementsByTagName is always a DOMNodeList; that class has a member length, described as:

The number of nodes in the list. The range of valid child node indices is 0 to length - 1 inclusive.

So to check if there is at least one item in the list, check that length is > 0:

```<code>$produktnavn_nodes = $xmlObject->item($i)->getElementsByTagName('produktnavn');
if ( $produktnavn_nodes->length > 0 ) {
    $produktnavn = utf8_decode($produktnavn_nodes->item(0)->childNodes->item(0)->nodeValue);
    // ... do something with $produktnavn
}
</code>```

Title: PHP/XML - checking if a node is set

Body:
I have an XML document structured like this:

<produkter>
    <produkt>
        <forhandler></forhandler>
        <produktnavn></produktnavn>
        and so on...
    </produkt>
</produkter>

I am pulling out data like this:

$produktnavn = utf8_decode($xmlObject->item($i)->getElementsByTagName('produktnavn')->item(0)->childNodes->item(0)->nodeValue);

Now I am looking to do a check to see if the node is present in the XML document at all.

For example... I only want to make the operation above if there actually IS a node called "produktnavn".

I am trying with:

if (isset($xmlObject->item($i)->forhandler)) {

But this doesn't seem to work.

What an I doing wrong?

Body:
The result of getElementsByTagName is always a DOMNodeList; that class has a member length, described as:

The number of nodes in the list. The range of valid child node indices is 0 to length - 1 inclusive.

So to check if there is at least one item in the list, check that length is > 0:

$produktnavn_nodes = $xmlObject->item($i)->getElementsByTagName('produktnavn');
if ( $produktnavn_nodes->length > 0 ) {
    $produktnavn = utf8_decode($produktnavn_nodes->item(0)->childNodes->item(0)->nodeValue);
    // ... do something with $produktnavn
}


问:
Dependency Injection Issue of Two MVC Projects in the Same solution
I had a web solution with a single MVC project. I have used Ninject binding in this project for constructor injection and it worked fine. Now I added another MVC project to the same solution and used construction injection in this new project too. The new project became the start Up project. But when the project is run, it will give an error called "No parameterless constructor defined for this object.". If I add a parameterless constructor in the corresponding controller, this error will go away. But constructor binding will not occur as the parameterless constructor is called at this time. I even tried to create a separate library for dependency resolving and use that DLL in the MVC project. But this will create a circular dependency, hence it wasn't successful.
What should be the solution for this situation?</p>

答:
I've resolved this in the past by calling MapperConfig.RegisterMaps(); in Global.asax.cs and defining the RegisterMaps() method as the following:

```<code>public class MapperConfig
  {
    public static void RegisterMaps()
    {
      //get all projects' AutoMapper profiles using reflection
      var assembliesToScan = System.AppDomain.CurrentDomain.GetAssemblies();
      var allTypes = assembliesToScan.SelectMany(a => a.ExportedTypes).ToArray();

      //depending on your solution, you may need allTypes to be defined as:
      //var allTypes = assembliesToScan.Where(x => !x.IsDynamic).SelectMany(a => a.ExportedTypes).ToArray();

      var profiles =
          allTypes
              .Where(t => typeof(Profile).GetTypeInfo().IsAssignableFrom(t.GetTypeInfo()))
              .Where(t => !t.GetTypeInfo().IsAbstract);

      //add each profile to our static AutoMapper
      Mapper.Initialize(cfg =>
      {
        foreach (var profile in profiles)
        {
          cfg.AddProfile(profile);
        }
      });
    }
  }
</code>```

then in each project in the solution, you can have separate automapper profiles (which I like so that your automapper bindings are defined in the layer that uses them instead of throwing all mappings into 1 enormous file) like this:

```<code>  public class AutoMapperServicesConfig : Profile
  {
    public AutoMapperServicesConfig()
    {
      CreateMap<Entity, EntityViewModel>();
    }

    public override string ProfileName
    {
      get { return this.GetType().ToString(); }
    }
  }
</code>```

Body:
I've resolved this in the past by calling MapperConfig.RegisterMaps(); in Global.asax.cs and defining the RegisterMaps() method as the following:

public class MapperConfig
  {
    public static void RegisterMaps()
    {
      //get all projects' AutoMapper profiles using reflection
      var assembliesToScan = System.AppDomain.CurrentDomain.GetAssemblies();
      var allTypes = assembliesToScan.SelectMany(a => a.ExportedTypes).ToArray();

      //depending on your solution, you may need allTypes to be defined as:
      //var allTypes = assembliesToScan.Where(x => !x.IsDynamic).SelectMany(a => a.ExportedTypes).ToArray();

      var profiles =
          allTypes
              .Where(t => typeof(Profile).GetTypeInfo().IsAssignableFrom(t.GetTypeInfo()))
              .Where(t => !t.GetTypeInfo().IsAbstract);

      //add each profile to our static AutoMapper
      Mapper.Initialize(cfg =>
      {
        foreach (var profile in profiles)
        {
          cfg.AddProfile(profile);
        }
      });
    }
  }

then in each project in the solution, you can have separate automapper profiles (which I like so that your automapper bindings are defined in the layer that uses them instead of throwing all mappings into 1 enormous file) like this:

  public class AutoMapperServicesConfig : Profile
  {
    public AutoMapperServicesConfig()
    {
      CreateMap<Entity, EntityViewModel>();
    }

    public override string ProfileName
    {
      get { return this.GetType().ToString(); }
    }
  }


问:
Outlook Auto Response
I have a rule set up in outlook that auto responds to emails with a specific ID number in the subject. Is there a way to get this ID from the original email and then use it to personalize the response email?

i.e

```<code>(Original Email)
Subject: Completed ID 110101
Message: This is the completed ID 110101

(Auto response email)
Subject: Submission
Message: Thank you, the submission of ID 110101 has been Received.
</code>```

答:
Yes, if you know VBA you can do it. Google VBA Outlook read subject line
Here is one answer to get you started ...
https://www.mrexcel.com/forum/excel-questions/536942-outlook-macro-read-subject-line.html

Title: Outlook Auto Response

Body:
I have a rule set up in outlook that auto responds to emails with a specific ID number in the subject. Is there a way to get this ID from the original email and then use it to personalize the response email?

i.e

(Original Email)
Subject: Completed ID 110101
Message: This is the completed ID 110101

(Auto response email)
Subject: Submission
Message: Thank you, the submission of ID 110101 has been Received.


问:
Run specific Android instrumentation test with Gradle
I need to execute certain Android test case (Class or method) with gradle from console.
It is located at src/androidTest/java/com/example/CertainTest.java.

Android Studio makes this available via complicated adb shell am instrument.

Is it possible to invoke certain Android Test only via Gradle?

I have read about How to run only one test class on gradle, Test from the Command Line but is it quite complicated way of doing that.

This is how Android Studio launches specific Test Class:

```<code>Launching Tests
$ adb push /.../app/build/outputs/apk/app-debug.apk /data/local/tmp/com.example.andrii.espressotutorial
$ adb shell pm install -r "/data/local/tmp/com.example.andrii.espressotutorial"
    pkg: /data/local/tmp/com.example.andrii.espressotutorial
Success
$ adb push /.../app/build/outputs/apk/app-debug-androidTest.apk /data/local/tmp/com.example.andrii.espressotutorial.test
$ adb shell pm install -r "/data/local/tmp/com.example.andrii.espressotutorial.test"
    pkg: /data/local/tmp/com.example.andrii.espressotutorial.test
Success
Running tests
$ adb shell am instrument -w -r   -e debug false -e class com.example.andrii.espressotutorial.ExampleInstrumentedTest2 com.example.andrii.espressotutorial.test/android.support.test.runner.AndroidJUnitRunner
Client not ready yet..
Started running tests
Tests ran to completion.
</code>```

答:
You can write a gradle task like this:

In the main gradle file

```<code>apply from: "$project.rootDir/tools/script-integration-tests.gradle"
</code>```

Then create a directory tools and a file script-integration-tests.gradle in the project directory. Then fill it with the test class name like this.

```<code>apply plugin: 'com.android.application'

task integrationTest(type: Exec) {
    def adb = android.getAdbExe().toString()
    commandLine "$adb", 'shell', 'am', 'instrument', '-w', '-r', '-e',
            'debug', 'false', '-e', 'class', 'de.app.id.PullRequestTests',
            'de.app.id.app_test.debug.test/android.support.test.runner.AndroidJUnitRunner'
}
</code>```

Body:
I need to execute certain Android test case (Class or method) with gradle from console.
It is located at src/androidTest/java/com/example/CertainTest.java.

Android Studio makes this available via complicated adb shell am instrument.

Is it possible to invoke certain Android Test only via Gradle?

I have read about How to run only one test class on gradle, Test from the Command Line but is it quite complicated way of doing that.

This is how Android Studio launches specific Test Class:

Launching Tests
$ adb push /.../app/build/outputs/apk/app-debug.apk /data/local/tmp/com.example.andrii.espressotutorial
$ adb shell pm install -r "/data/local/tmp/com.example.andrii.espressotutorial"
    pkg: /data/local/tmp/com.example.andrii.espressotutorial
Success
$ adb push /.../app/build/outputs/apk/app-debug-androidTest.apk /data/local/tmp/com.example.andrii.espressotutorial.test
$ adb shell pm install -r "/data/local/tmp/com.example.andrii.espressotutorial.test"
    pkg: /data/local/tmp/com.example.andrii.espressotutorial.test
Success
Running tests
$ adb shell am instrument -w -r   -e debug false -e class com.example.andrii.espressotutorial.ExampleInstrumentedTest2 com.example.andrii.espressotutorial.test/android.support.test.runner.AndroidJUnitRunner
Client not ready yet..
Started running tests
Tests ran to completion.

Body:
You can write a gradle task like this:

In the main gradle file

apply from: "$project.rootDir/tools/script-integration-tests.gradle"

Then create a directory tools and a file script-integration-tests.gradle in the project directory. Then fill it with the test class name like this.

apply plugin: 'com.android.application'

task integrationTest(type: Exec) {
    def adb = android.getAdbExe().toString()
    commandLine "$adb", 'shell', 'am', 'instrument', '-w', '-r', '-e',
            'debug', 'false', '-e', 'class', 'de.app.id.PullRequestTests',
            'de.app.id.app_test.debug.test/android.support.test.runner.AndroidJUnitRunner'
}


问:
Memory Game doesn't restart after winning
I'm trying to rebrand this cool Memory Game developed by Nate Wiley.

I'm having an issue with it though. When you win, it allows you to restart, but the game become unplayable when the cards re-appear for a second time.

The restart button code calls this function:

```<code>reset: function(){
    this.hideModal();
    this.shuffleCards(this.cardsArray);
    this.setup();
    this.$game.show();
},
</code>```

This correctly hides the modal, shuffles the card, runs the setup function, and shows the game again.

The Setup Function looks like this:

```<code>setup: function(){
    this.html = this.buildHTML();
    this.$game.html(this.html);
    this.$memoryCards = $(".card");
    this.paused = false;
    this.guess = null;
},
</code>```

I'm not getting any errors in the console. How would I go about diagnosing an error in this situation?

I've created a codepen with only 2 matching pairs to make testing a lot quicker but I'm at a loss for how to figure this out.

https://codepen.io/nolaandy/pen/wPeGgo

答:
Udpated Codepen.

All you need to do is binding the click event using the event delegation on like :

```<code>$('body').on("click", ".card", this.cardClicked);
</code>```

Instead of :

```<code>this.$memoryCards.on("click", this.cardClicked);
</code>```

So when you reset the cards dynamically from the reset() function, the click event will persist and could deal with the new card elements.

Hope this help.

Body:
I'm trying to rebrand this cool Memory Game developed by Nate Wiley.

I'm having an issue with it though. When you win, it allows you to restart, but the game become unplayable when the cards re-appear for a second time.

The restart button code calls this function:

reset: function(){
    this.hideModal();
    this.shuffleCards(this.cardsArray);
    this.setup();
    this.$game.show();
},

This correctly hides the modal, shuffles the card, runs the setup function, and shows the game again.

The Setup Function looks like this:

setup: function(){
    this.html = this.buildHTML();
    this.$game.html(this.html);
    this.$memoryCards = $(".card");
    this.paused = false;
    this.guess = null;
},

I'm not getting any errors in the console. How would I go about diagnosing an error in this situation?

I've created a codepen with only 2 matching pairs to make testing a lot quicker but I'm at a loss for how to figure this out.

https://codepen.io/nolaandy/pen/wPeGgo

Body:
Udpated Codepen.

All you need to do is binding the click event using the event delegation on like :

$('body').on("click", ".card", this.cardClicked);

Instead of :

this.$memoryCards.on("click", this.cardClicked);

So when you reset the cards dynamically from the reset() function, the click event will persist and could deal with the new card elements.

Hope this help.


问:
Recusive Lazy Loading Problem
How to avoid recursive mapping in Lazy loading technique at self join Entity?</p>

答:
You'll have to modify the T4 templates. Classes.tt is responsible for generating the object models.  The implementation of relationship properties (that is where the lazy loading happens) is in that file.

It's an ugly solution, but the only work around I am aware of.

We ended up defining an array of table+field names that should be generated as one-way relationships, and modified the Classes.tt file to not generate relationships in both directions.  In fact, we've made many modifications to the templates to work around issues inherent to SubSonic.

Title: Recusive Lazy Loading Problem


问:
Add camera icon in SearchView on Android
I´m going to try to explain, although my English is a bit bad.

Estoy utilizando MaterialSearchView de Miguel Catalan: MaterialSearchView

I'm new to StackOverflow and they do not let me upload images. I will try to explain it. The main screen of my application has a MaterialSearchView in the Toolbar. After pressing the search icon, it takes me to the text box where you can search

I`d like to put a camera icon to the right of the 'X' of the SerchView.

Can anybody help me? Or tell me some other search component that allows you to add icons in the search bar when searching?

EDIT

I have got the solution. It is not the most professional way, but it is valid.
In the SearchView control, I have put two images, one for the X to delete the searched text (The original icon stays behind the camera) and another for the camera (both invisible).

 layout/app_bar_home.xml:

```<code>        <com.miguelcatalan.materialsearchview.MaterialSearchView
            android:id="@+id/searchView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            >

            <ImageView android:id="@+id/imgClearSearch"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_gravity="right"
                android:src="@drawable/ic_close_grease_small"
                android:visibility="invisible"
                android:layout_marginTop="18dp"
                android:layout_marginRight="50dp" />

            <ImageView
                android:id="@+id/imgCamera"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_gravity="right"
                android:src="@drawable/ic_menu_camera"
                android:visibility="invisible"
                android:layout_marginTop="14dp"
                android:layout_marginRight="8dp"
                />
        </com.miguelcatalan.materialsearchview.MaterialSearchView>
</code>```

Then, in the java class, in the listener, we show images when the searcher is shown, and hide them when hiding the searcher.

```<code>    //Creamos los listeners de los buscadores
    searchView = (MaterialSearchView) findViewById(R.id.searchView);
    searchView.setVoiceSearch(false);
    searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {

            //Cuando pulsamos en buscar
            String aa = "";

            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {

            //Cuando teclemamos en el buscador
            String aa = "";

            if (newText.length() > 20)
                searchView.setQuery(newText.substring(0, 20), false);

            return false;
        }
    });
    searchView.setOnSearchViewListener(new MaterialSearchView.SearchViewListener() {
        @Override
        public void onSearchViewShown() {

            imgCamera.setVisibility(View.VISIBLE);
            imgClearSearch.setVisibility(View.VISIBLE);

            //ImageView searchClose = (ImageView) searchView.findViewById(android.support.v7.appcompat.R.id.search_close_btn);
            //searchClose.setImageResource(R.drawable.ic_close_white);
            Drawable closeIcon = getResources().getDrawable(R.drawable.ic_close_white);
            searchView.setCloseIcon(closeIcon);

            //Cuando mostramos el buscador
            String aa = "";
        }

        @Override
        public void onSearchViewClosed() {

            //Cuando cerramos el buscador (tras haber buscado)
            String aa = "";
            imgCamera.setVisibility(View.INVISIBLE);
            imgClearSearch.setVisibility(View.INVISIBLE);
        }
    });
</code>```

The only problem is that the X that was displayed by default to clean the text of the searcher was still showing, so I did a little trick. I replaced the icon that came out by default with a white one, so it is not visible. I've put that on the line:

```<code>            Drawable closeIcon = getResources().getDrawable(R.drawable.ic_close_white);
            searchView.setCloseIcon(closeIcon);
</code>```

Este es el resultado:

答:
I have got the solution. It is not the most professional way, but it is valid.
In the SearchView control, I have put two images, one for the X to delete the searched text (The original icon stays behind the camera) and another for the camera (both invisible).

 layout/app_bar_home.xml:

```<code>        <com.miguelcatalan.materialsearchview.MaterialSearchView
            android:id="@+id/searchView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            >

            <ImageView android:id="@+id/imgClearSearch"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_gravity="right"
                android:src="@drawable/ic_close_grease_small"
                android:visibility="invisible"
                android:layout_marginTop="18dp"
                android:layout_marginRight="50dp" />

            <ImageView
                android:id="@+id/imgCamera"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_gravity="right"
                android:src="@drawable/ic_menu_camera"
                android:visibility="invisible"
                android:layout_marginTop="14dp"
                android:layout_marginRight="8dp"
                />
        </com.miguelcatalan.materialsearchview.MaterialSearchView>
</code>```

Then, in the java class, in the listener, we show images when the searcher is shown, and hide them when hiding the searcher.

```<code>    //Creamos los listeners de los buscadores
    searchView = (MaterialSearchView) findViewById(R.id.searchView);
    searchView.setVoiceSearch(false);
    searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {

            //Cuando pulsamos en buscar
            String aa = "";

            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {

            //Cuando teclemamos en el buscador
            String aa = "";

            if (newText.length() > 20)
                searchView.setQuery(newText.substring(0, 20), false);

            return false;
        }
    });
    searchView.setOnSearchViewListener(new MaterialSearchView.SearchViewListener() {
        @Override
        public void onSearchViewShown() {

            imgCamera.setVisibility(View.VISIBLE);
            imgClearSearch.setVisibility(View.VISIBLE);

            //ImageView searchClose = (ImageView) searchView.findViewById(android.support.v7.appcompat.R.id.search_close_btn);
            //searchClose.setImageResource(R.drawable.ic_close_white);
            Drawable closeIcon = getResources().getDrawable(R.drawable.ic_close_white);
            searchView.setCloseIcon(closeIcon);

            //Cuando mostramos el buscador
            String aa = "";
        }

        @Override
        public void onSearchViewClosed() {

            //Cuando cerramos el buscador (tras haber buscado)
            String aa = "";
            imgCamera.setVisibility(View.INVISIBLE);
            imgClearSearch.setVisibility(View.INVISIBLE);
        }
    });
</code>```

The only problem is that the X that was displayed by default to clean the text of the searcher was still showing, so I did a little trick. I replaced the icon that came out by default with a white one, so it is not visible. I've put that on the line:

```<code>            Drawable closeIcon = getResources().getDrawable(R.drawable.ic_close_white);
            searchView.setCloseIcon(closeIcon);
</code>```

Result in my own question

Body:
I´m going to try to explain, although my English is a bit bad.

Estoy utilizando MaterialSearchView de Miguel Catalan: MaterialSearchView

I'm new to StackOverflow and they do not let me upload images. I will try to explain it. The main screen of my application has a MaterialSearchView in the Toolbar. After pressing the search icon, it takes me to the text box where you can search

I`d like to put a camera icon to the right of the 'X' of the SerchView.

Can anybody help me? Or tell me some other search component that allows you to add icons in the search bar when searching?

EDIT

I have got the solution. It is not the most professional way, but it is valid.
In the SearchView control, I have put two images, one for the X to delete the searched text (The original icon stays behind the camera) and another for the camera (both invisible).

 layout/app_bar_home.xml:

        <com.miguelcatalan.materialsearchview.MaterialSearchView
            android:id="@+id/searchView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            >

            <ImageView android:id="@+id/imgClearSearch"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_gravity="right"
                android:src="@drawable/ic_close_grease_small"
                android:visibility="invisible"
                android:layout_marginTop="18dp"
                android:layout_marginRight="50dp" />

            <ImageView
                android:id="@+id/imgCamera"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_gravity="right"
                android:src="@drawable/ic_menu_camera"
                android:visibility="invisible"
                android:layout_marginTop="14dp"
                android:layout_marginRight="8dp"
                />
        </com.miguelcatalan.materialsearchview.MaterialSearchView>

Then, in the java class, in the listener, we show images when the searcher is shown, and hide them when hiding the searcher.

    //Creamos los listeners de los buscadores
    searchView = (MaterialSearchView) findViewById(R.id.searchView);
    searchView.setVoiceSearch(false);
    searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {

            //Cuando pulsamos en buscar
            String aa = "";

            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {

            //Cuando teclemamos en el buscador
            String aa = "";

            if (newText.length() > 20)
                searchView.setQuery(newText.substring(0, 20), false);

            return false;
        }
    });
    searchView.setOnSearchViewListener(new MaterialSearchView.SearchViewListener() {
        @Override
        public void onSearchViewShown() {

            imgCamera.setVisibility(View.VISIBLE);
            imgClearSearch.setVisibility(View.VISIBLE);

            //ImageView searchClose = (ImageView) searchView.findViewById(android.support.v7.appcompat.R.id.search_close_btn);
            //searchClose.setImageResource(R.drawable.ic_close_white);
            Drawable closeIcon = getResources().getDrawable(R.drawable.ic_close_white);
            searchView.setCloseIcon(closeIcon);

            //Cuando mostramos el buscador
            String aa = "";
        }

        @Override
        public void onSearchViewClosed() {

            //Cuando cerramos el buscador (tras haber buscado)
            String aa = "";
            imgCamera.setVisibility(View.INVISIBLE);
            imgClearSearch.setVisibility(View.INVISIBLE);
        }
    });

The only problem is that the X that was displayed by default to clean the text of the searcher was still showing, so I did a little trick. I replaced the icon that came out by default with a white one, so it is not visible. I've put that on the line:

            Drawable closeIcon = getResources().getDrawable(R.drawable.ic_close_white);
            searchView.setCloseIcon(closeIcon);

Este es el resultado:

Body:
I have got the solution. It is not the most professional way, but it is valid.
In the SearchView control, I have put two images, one for the X to delete the searched text (The original icon stays behind the camera) and another for the camera (both invisible).

 layout/app_bar_home.xml:

        <com.miguelcatalan.materialsearchview.MaterialSearchView
            android:id="@+id/searchView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            >

            <ImageView android:id="@+id/imgClearSearch"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_gravity="right"
                android:src="@drawable/ic_close_grease_small"
                android:visibility="invisible"
                android:layout_marginTop="18dp"
                android:layout_marginRight="50dp" />

            <ImageView
                android:id="@+id/imgCamera"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_gravity="right"
                android:src="@drawable/ic_menu_camera"
                android:visibility="invisible"
                android:layout_marginTop="14dp"
                android:layout_marginRight="8dp"
                />
        </com.miguelcatalan.materialsearchview.MaterialSearchView>

Then, in the java class, in the listener, we show images when the searcher is shown, and hide them when hiding the searcher.

    //Creamos los listeners de los buscadores
    searchView = (MaterialSearchView) findViewById(R.id.searchView);
    searchView.setVoiceSearch(false);
    searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {

            //Cuando pulsamos en buscar
            String aa = "";

            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {

            //Cuando teclemamos en el buscador
            String aa = "";

            if (newText.length() > 20)
                searchView.setQuery(newText.substring(0, 20), false);

            return false;
        }
    });
    searchView.setOnSearchViewListener(new MaterialSearchView.SearchViewListener() {
        @Override
        public void onSearchViewShown() {

            imgCamera.setVisibility(View.VISIBLE);
            imgClearSearch.setVisibility(View.VISIBLE);

            //ImageView searchClose = (ImageView) searchView.findViewById(android.support.v7.appcompat.R.id.search_close_btn);
            //searchClose.setImageResource(R.drawable.ic_close_white);
            Drawable closeIcon = getResources().getDrawable(R.drawable.ic_close_white);
            searchView.setCloseIcon(closeIcon);

            //Cuando mostramos el buscador
            String aa = "";
        }

        @Override
        public void onSearchViewClosed() {

            //Cuando cerramos el buscador (tras haber buscado)
            String aa = "";
            imgCamera.setVisibility(View.INVISIBLE);
            imgClearSearch.setVisibility(View.INVISIBLE);
        }
    });

The only problem is that the X that was displayed by default to clean the text of the searcher was still showing, so I did a little trick. I replaced the icon that came out by default with a white one, so it is not visible. I've put that on the line:

            Drawable closeIcon = getResources().getDrawable(R.drawable.ic_close_white);
            searchView.setCloseIcon(closeIcon);

Result in my own question


问:
Postgres select record stored as epoch from yesterday
I need to select all records from yesterday. Date in table is stored as epoch timestamp. I tried something like this, but it's not working.</p>

```<code>select to_char((SELECT TIMESTAMP WITH TIME ZONE 'epoch' + history.clock * INTERVAL '1 second') , 'YYYY-MM-DD HH24:MI:SS ') AS Data
from history
WHERE
history.clock >=  EXTRACT( epoch FROM current_timestamp - interval '1 day') and
history.clock <=  EXTRACT( epoch FROM current_timestamp - interval '1 day') ;
</code>```

答:
Well your problem is that you're saying "everything where clock >= 1510444800 and clock <= 1510444800". You're giving yourself a single second range.

The following query should do what you need. Increase the upper bound of the range by 86399 (There are 86400 seconds in a day, but we already have the first second of the day from our extract when combined with a ::date cast)

```<code>select
    to_char(to_timestamp(history.clock), 'YYYY-MM-DD HH24:MI:SS ') as Data
from
    history
where
    history.clock between extract(epoch from 'yesterday'::date)::integer and (extract(epoch from 'yesterday'::date)::integer + 86399)
</code>```

I've also included a few what I consider to be improvements. No need to mess around with intervals for getting yesterday when Postgres has support for casting 'yesterday' to a date. Comparing a value to an upper and lower bound is what the between keyword was made for, and there's a built in function for converting from a unix timestamp.

Body:
I need to select all records from yesterday. Date in table is stored as epoch timestamp. I tried something like this, but it's not working.

select to_char((SELECT TIMESTAMP WITH TIME ZONE 'epoch' + history.clock * INTERVAL '1 second') , 'YYYY-MM-DD HH24:MI:SS ') AS Data
from history
WHERE
history.clock >=  EXTRACT( epoch FROM current_timestamp - interval '1 day') and
history.clock <=  EXTRACT( epoch FROM current_timestamp - interval '1 day') ;

Body:
Well your problem is that you're saying "everything where clock >= 1510444800 and clock <= 1510444800". You're giving yourself a single second range.

The following query should do what you need. Increase the upper bound of the range by 86399 (There are 86400 seconds in a day, but we already have the first second of the day from our extract when combined with a ::date cast)

select
    to_char(to_timestamp(history.clock), 'YYYY-MM-DD HH24:MI:SS ') as Data
from
    history
where
    history.clock between extract(epoch from 'yesterday'::date)::integer and (extract(epoch from 'yesterday'::date)::integer + 86399)

I've also included a few what I consider to be improvements. No need to mess around with intervals for getting yesterday when Postgres has support for casting 'yesterday' to a date. Comparing a value to an upper and lower bound is what the between keyword was made for, and there's a built in function for converting from a unix timestamp.