Q: Jmeter - pass command-line parameter that contains hyphen I run my jmeter tests via bat file
  %JMETER_HOME%\jmeter -n -t %RUNNER%\My.jmx -Jusers=1 -Jloop=1 etc.

But today I had to add some more parameters, and one of them was
-Jclient_id=450a-b58d-204ebfe22d1e

I've started getting error "Java SE has stopped working" (which in debug appeared to be "Unhandled exception at 0x012A96E0 in java.exe: 0xC0000005: Access violation reading location 0x58B86598."
I do understand that it's because of hyphen in the new parameter, but how can i deal with it?
Any advice would be appreciated.

A: I cannot reproduce it on my system (bash 3.2.57, Java 1.8.0.65)
You can try working it around as follows:

*

*Surround cliend id with quotation marks like
-Jclient_id="450a-b58d-204ebfe22d1e"

*Define the values in user.properties file (lives under "bin" folder of your JMeter installation) like:
users=1
loops=1
client_id=450a-b58d-204ebfe22d1e

See Apache JMeter Properties Customization Guide for more information on different JMeter properties types and ways of working with them


Q: Replace word with special characters from string in Java I am writing a method which should replace all words which matches with ones from the list with '****'
characters. So far I have code which works but all special characters are ignored.
I have tried with "\\W" in my expression but looks like I didn't use it well so I could use some help.
Here's code I have so far:
        for(int i = 0; i < badWords.size(); i++) {
        if (StringUtils.containsIgnoreCase(stringToCheck, badWords.get(i))) {
            stringToCheck = stringToCheck.replaceAll("(?i)\\b" + badWords.get(i) + "\\b", "****");
        }
    }

E.g. I have list of words ['bad', '@$$'].
If I have a string: "This is bad string with @$$" I am expecting this method to return "This is **** string with ****"
Note that method should be aware of case sensitive words, e.g. TesT and test should handle same.

A: I'm not sure why you use the StringUtils you can just directly replace words that match the bad words.  This code works for me:
public static void main(String[] args) {
    ArrayList<String> badWords = new ArrayList<String>();
    badWords.add("test");
    badWords.add("BadTest");
    badWords.add("\\$\\$");
    String test = "This is a TeSt and a $$ with Badtest.";
    for(int i = 0; i < badWords.size(); i++) {
            test = test.replaceAll("(?i)" + badWords.get(i), "****");
    }
    test = test.replaceAll("\\w*\\*{4}", "****");
    System.out.println(test);
}

Output:
This is a **** and a **** with ****.

A: The problem is that these special characters e.g.  $ are regex control characters and not literal characters. You'll need to escape any occurrence of the following characters in the bad word using two backslashes:
{}()\[].+*?^$|

A: My guess is that your list of bad words contains special characters that have particular meanings when interpreted in a regular expression (which is what the replaceAll method does).  $, for example, typically matches the end of the string/line.  So I'd recommend a combination of things:

*

*Don't use containsIgnoreCase to identify whether a replacement needs to be done.  Just let the replaceAll run each time - if there is no match against the bad word list, nothing will be done to the string.

*The characters like $ that have special meanings in regular expressions should be escaped when they are added into the bad word list.  For example, badwords.add("@\\$\\$");

A: Try something like this:
    String stringToCheck = "This is b!d string with @$$";
    List<String> badWords = asList("b!d","@$$");
    for(int i = 0; i < badWords.size(); i++) {
        if (StringUtils.containsIgnoreCase(stringToCheck,badWords.get(i))) {
            stringToCheck = stringToCheck.replaceAll("["+badWords.get(i)+"]+","****");
        }
    }
    System.out.println(stringToCheck);

A: Another solution: bad words matched with word boundaries (and case insensitive).
    Pattern badWords = Pattern.compile("\\b(a|b|ĉĉĉ|dddd)\\b",
            Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
    String text = "adfsa a dfs bb addfdsaf ĉĉĉ adsfs dddd asdfaf a";
    Matcher m = badWords.matcher(text);
    StringBuffer sb = new StringBuffer(text.length());
    while (m.find()) {
        m.appendReplacement(sb, stars(m.group(1)));
    }
    m.appendTail(sb);
    String cleanText = sb.toString();
    System.out.println(text);
    System.out.println(cleanText);
}

private static String stars(String s) {
    return s.replaceAll("(?su).", "*");
    /*
    int cpLength = s.codePointCount(0, s.length());
    final String stars = "******************************";
    return cpLength >= stars.length() ? stars : stars.substring(0, cpLength);
    */
}

And then (in comment) the stars with the correct count: one star for a Unicode code point giving two surrogate pairs (two UTF-16 chars).


Q: Eliminate each duplicate value from columns I have a table including some rows. If the row in its column is duplicate value, I don't want it. Let me exemplify.
ColA ColB ColC ColD
1     X     Q    9
2     Y     W    9
3     Z     E    9
3     X     R    9
3     Y     T   null
2     Z    null null

I expect (ordering is negligible)
ColA ColB ColC ColD
1     X     Q    9
2     Y     W    null
3     Z     E    null
null  null  R    null
null  null  T    null
null  null  null  null

I would write for each column almost same select clauses but I don't think it is efficient.

A: This seems to do it (but I wonder about the purpose of it ):
WITH CTE AS (
   SELECT 1 as ColA, 'X' as ColB,'Q' as ColC,'9' as ColD
   UNION
   SELECT 2,'Y','W',9
   UNION
   SELECT 3,'Z','E',9
   UNION
   SELECT 3,'X','R',9
   UNION
   SELECT 3,'Y','T',null
   UNION
   SELECT 2,'Z',null,null)

select
   AA.ColA,
   BB.ColB,
   CC.ColC,
   DD.ColD
from
   (select ColA, ROW_NUMBER() over (order by ColA) RowA from (
       select DISTINCT ColA from CTE)  A) AA
FULL JOIN
   (select ColB, ROW_NUMBER() over (order by ColB) RowB from (
       SELECT DISTINCT ColB from CTE) B ) BB
   ON BB.RowB = AA.RowA
FULL JOIN
   (select ColC, ROW_NUMBER() over (order by ColC) RowC from (
       SELECT DISTINCT ColC from CTE) C ) CC
   ON CC.RowC = AA.RowA
FULL JOIN
   (select ColD, ROW_NUMBER() over (order by ColD) RowD from (
       SELECT DISTINCT ColD from CTE) D ) DD
   ON DD.RowD = AA.RowA

DBFIDDLE

A: You want to suppress values when selecting data from the table? This is typically not done in SQL, but in the app displaying the data.
But if you want to, you can do this in SQL (using windw functions). For this to work you'd have to specify the order in which to select the rows. You say, you don't care about the order, so in below query I simply generate some row number we can base this on:
with numbered as
(
  select t.*, row_number() over order by (newid()) as rn
  from mytable
)
select
  case when count(*) over (partition by cola order by rn) = 1 then cola end as a,
  case when count(*) over (partition by colb order by rn) = 1 then colb end as b,
  case when count(*) over (partition by colc order by rn) = 1 then colc end as c,
  case when count(*) over (partition by cold order by rn) = 1 then cold end as d
from numbered
order by rn;

A: If you have a column that specifies the ordering, then you can use row_number():
select (case when row_number() over (partition by colA order by ordcol) = 1 then colA end),
       (case when row_number() over (partition by colB order by ordcol) = 1 then colB end),
       (case when row_number() over (partition by colC order by ordcol) = 1 then colC end),
       (case when row_number() over (partition by colD order by ordcol) = 1 then colD end)
from tablename t;

If you don't have such a column, then it becomes tricker.  You can generate one:
with t as (
      select t.*,
             row_number() over (order by (select null)) as ordcol
      from tablename t
     )
select (case when row_number() over (partition by colA order by ordcol) = 1 then colA end),
       (case when row_number() over (partition by colB order by ordcol) = 1 then colB end),
       (case when row_number() over (partition by colC order by ordcol) = 1 then colC end),
       (case when row_number() over (partition by colD order by ordcol) = 1 then colD end)
from t;


Q: unbuffered read from stdin in python I'm writing  a python script that can read input through a pipe from another command like so
batch_job | myparser

My script myparser processes the output of batch_job and write to its own stdout. My problem is that I want to see the output immediately (the output of batch_job is processed line-by-line) but there appears to be this notorious stdin buffering (allegedly 4KB, I haven't verified) which delays everything.
The problem has been discussed already here here and here.
I tried the following:

*

*open stdin using os.fdopen(sys.stdin.fileno(), 'r', 0)

*using -u in my hashbang: #!/usr/bin/python -u

*setting export PYTHONUNBUFFERED=1 right before calling the script

*flushing my output after each line that was read (just in case the problem was coming from output buffering rather than input buffering)

My python version is 2.4.3 - I have no possibility of upgrading or installing any additional programs or packages. How can I get rid of these delays?

A: I've encountered the same issue with legacy code. It appears to be a problem with the implementation of Python 2's file object's __next__ method; it uses a Python level buffer (which -u/PYTHONUNBUFFERED=1 doesn't affect, because those only unbuffer the stdio FILE*s themselves, but file.__next__'s buffering isn't related; similarly, stdbuf/unbuffer can't change any of the buffering at all, because Python replaces the default buffer made by the C runtime; the last thing file.__init__ does for a newly opened file is call PyFile_SetBufSize which uses setvbuf/setbuf [the APIs] to replace the default stdio buffer).
The problem is seen when you have a loop of the form:
for line in sys.stdin:

where the first call to __next__ (called implicitly by the for loop to get each line) ends up blocking to fill the block before producing a single line.
There are three possible fixes:

*

*(Only on Python 2.6+) Rewrap sys.stdio with the io module (backported from Python 3 as a built-in) to bypass file entirely in favor of the (frankly superior) Python 3 design (which uses a single system call at a time to populate the buffer without blocking for the full requested read to occur; if it asks for 4096 bytes and gets 3, it'll see if a line is available and produce it if so) so:
import io
import sys

# Add buffering=0 argument if you won't always consume stdin completely, so you
# can't lose data in the wrapper's buffer. It'll be slower with buffering=0 though.
with io.open(sys.stdin.fileno(), 'rb', closefd=False) as stdin:
    for line in stdin:
        # Do stuff with the line

This will typically be faster than option 2, but it's more verbose, and requires Python 2.6+. It also allows for the rewrap to be Unicode friendly, by changing the mode to 'r' and optionally passing the known encoding of the input (if it's not the locale default) to seamlessly get unicode lines instead of (ASCII only) str.

*(Any version of Python) Work around problems with file.__next__ by using file.readline instead; despite nearly identical intended behavior, readline doesn't do its own (over)buffering, it delegates to C stdio's fgets (default build settings) or a manual loop calling getc/getc_unlocked into a buffer that stops exactly when it hits end of line. By combining it with two-arg iter you can get nearly identical code without excess verbosity (it'll probably be slower than the prior solution, depending on whether fgets is used under the hood, and how the C runtime implements it):
# '' is the sentinel that ends the loop; readline returns '' at EOF
for line in iter(sys.stdin.readline, ''):
    # Do stuff with line

*Move to Python 3, which doesn't have this problem. :-)

A: In Linux, bash, what you are looking for seems to be the stdbuf command.
If you want no buffering (i.e. an unbuffered stream), try this,
# batch_job | stdbuf -o0 myparser

If you want line buffering, try this,
# batch_job | stdbuf -oL myparser

A: You can unbuffer the output:
unbuffer batch_job | myparser


Q: How to focus on one Entry when Using TextChange for multiple entries I have 2 entries. When I tap anything on entry 1 I would like to get "Yess" on entry 2 and when I type anything on entry 2 I would like to get "Noo"
The problem:
When I tap on entry 1, entry 2  change and get the value "Noo"  but entry 1 change too and get the value "yess".
Question :
How can make entry 2 change when tapping on entry 1 without changing entry 1. And the same for entry 2
Here is Xaml code :
 <Entry ClassId="1" x:Name="myWord1"TextChanged="OnEntryTextChange"/>
 <Entry ClassId="2"  x:Name="myWord2"  TextChanged="OnEntryTextChange"/>

Code :
 private async void OnEntryTextChange(object sender, TextChangedEventArgs e)
    {

            var EntryTapped = (Xamarin.Forms.Entry)sender;

            Device.BeginInvokeOnMainThread(() => {

                        if (EntryTapped.ClassId == "1")
                        {

                           myWord2.Text="Noo";

                        }

                        else if (EntryTapped.ClassId == "2")
                        {

                        myWord1.Text="yess";
                        }

            });
    }

Thanks for your help

A: You could use the Focused event instead of TextChanged event.
   <StackLayout>
        <Entry ClassId="1" x:Name="myWord1"  Focused="EntryFocused"/>
        <Entry ClassId="2"  x:Name="myWord2"  Focused="EntryFocused"/>
    </StackLayout>

   private void EntryFocused(object sender, FocusEventArgs e)
    {
        var EntryTapped = (Xamarin.Forms.Entry)sender;

        if (EntryTapped.ClassId == "1")
        {

            myWord2.Text = "Noo";

        }

        else if (EntryTapped.ClassId == "2")
        {

            myWord1.Text = "yess";
        }
    }

A: There are several ways of doing this:

*

*Using bindings

In this case you would have 2 private variables and 2 public variables, and the entries binded to each one. Check this link how to implement INotifyPropertyChanged
    private string entry1String;
    private string entry2String;
    public string Entry1String {
        get => entry1String;
        set
        {
            entry2String = "Noo";
            entry1String = value;
            OnPropertyChanged(Entry1String);
            OnPropertyChanged(Entry2String);
        }
    }
    public string Entry2String {
        get => entry2String;
        set
        {
            entry1String = "Yees";
            entry2String = value;
            OnPropertyChanged(Entry1String);
            OnPropertyChanged(Entry2String);
        }
    }

Another way could be using a variable as a Semaphore. While the variable is True, the method cannot be fired at the same time by another.
private bool semaphoreFlag=false;

private async void OnEntryTextChange(object sender, TextChangedEventArgs e)
{
    if(semaphoreFlag) return;
    semaphoreFlag=true;
        var EntryTapped = (Xamarin.Forms.Entry)sender;

        Device.BeginInvokeOnMainThread(() => {

                    if (EntryTapped.ClassId == "1")
                    {

                       myWord2.Text="Noo";

                    }

                    else if (EntryTapped.ClassId == "2")
                    {

                    myWord1.Text="yess";
                    }

        });
semaphoreFlag=false;
}


Q: How to search for a function in namespaces not 'required' or 'used' in Clojure? How can I search for a function in namespaces not 'required' or 'used' in a Clojure source file?  Basically what I'd like to do is have source files:
main.clj,
a.clj,
b.clj,
c.clj

all compiled together but not directly import / require / use  a, b, or c in main. Instead I have main take a command line parameter that would then search for the right function (perhaps even just a fully qualified symbol).
I looked at ns-publics but it requires a namespace symbol.  I tried bultitude to get all the namespaces from with the src/ dir and I get back the lib.a, lib.b, lib.c, lib.main etc, but since main doesn't use or require or otherwise refer to the other namespaces I get an error using ns-publics. No namespace lib.a found as per the try in the-ns source code.
How can I look at the public interface of code included in the project but not directly referred to by a specific file, or even a dependency of a reference?

A: Here's a simple workaround which might help until a better solution comes up. It returns a list of all public symbols defined in a file. Let's read the file and look for all def sexps. Ignore private ones, i.e. ones like defn-.
(let [file (with-in-str (str "(" (slurp filename) ")") (read))
      defs (filter #(.matches (str (first %)) "^def.*[^-]$") file)
      symbols (map second defs)]
  symbols)

Caveats:

*

*Well, it's simply naïve.

*It doesn't get rid of all private definitions. Ones defined with ^{:private true} or ^:private are not filtered out.

*Definitions can be generated using macros.

The last point is especially troubling. The only reasonable way to detect definitions generated with macros is to evaluate the file with the reader, at least partially.

A: Parsing isn't going to work because clojure is very dynamic.
So, something like this might work...
(load-file "file_with_stuff.clj")
(ns-publics (find-ns 'file-with-stuff))
(remove-ns 'file-with-stuff)

If you want to do everything dynamically, then you can generate the symbols using symbol -- should still work. Removing the ns is optional. It won't do any harm, but it does put you back where you started.


Q: Get ProcessGroup from processor Is there an API to get a ProcessGroup by id from a custom processor or an ExecuteScript processor?
I know that it is possible by using the REST-API, but for security reasons, I don't have the chance to use the credentials to invoke the API from a service.
Regards

A: If you use a InvokeScriptedProcessor using groovy you can use
context.procNode.processGroup

from the ProcessContext
If you want to extract all the parents in a breadcrum way, you can use this:
import groovy.json.*;
import org.apache.nifi.groups.*;

class GroovyProcessor implements Processor {

    def REL_SUCCESS = new Relationship.Builder()
        .name("success")
        .description('FlowFiles that were successfully processed are routed here').build()

    def ComponentLog log

    @Override
    void initialize(ProcessorInitializationContext context) {
        log = context.logger
    }

    @Override
    Set<Relationship> getRelationships() {
        return [REL_SUCCESS] as Set
    }

    void executeScript(ProcessSession session, ProcessContext context) {
        def flowFile = session.get()
        if (!flowFile) { return }

        def breadcrumb = getBreadCrumb(context.procNode.processGroup) + '->' + context.getName()
        flowFile = session.putAttribute(flowFile, 'breadcrumb', breadcrumb)

        // transfer
        session.transfer(flowFile, this.REL_SUCCESS)
    }

    // Recursive funtion that gets the breadcrumb
    String getBreadCrumb(processGroup) {
        def breadCrumb = ''
        if(processGroup.parent != null)
            breadCrumb = getBreadCrumb(processGroup.parent) + '->'

        return breadCrumb + processGroup.name
    }

    @Override
    void onTrigger(ProcessContext context, ProcessSessionFactory sessionFactory) throws ProcessException {
        def session = sessionFactory.createSession()
        try {
            executeScript( session, context)
            session.commit()
        }
        catch (final Throwable t) {
            log.error('{} failed to process due to {}; rolling back session', [this, t] as Object[])
            session.rollback(true)
            throw t
        }
    }

    @Override
    PropertyDescriptor getPropertyDescriptor(String name) { null }

    @Override
    List<PropertyDescriptor> getPropertyDescriptors() {
        return [] as List
     }

    @Override
    void onPropertyModified(PropertyDescriptor descriptor, String oldValue, String newValue) { }

    @Override
    Collection<ValidationResult> validate(ValidationContext context) { null }

    @Override
    String getIdentifier() { null }
}

processor = new GroovyProcessor()


Q: How to slice a value which is inside and obj and pass to next metod which uses it as an object I have a specific situation where I have a method that getting an object as follow
async ({ locale }, ctx) => {
      const lang = await LanguageService(ctx).getLanguage({
        locale,
      });
      return lang.direction ? 'rtl' : 'ltr';
    },

The { locale } is equal to a request as locale: en_US.
The next method I need to use getLanguage accepts { locale } but I have to pass only the en.
So I thought to do slice but if I send it as for example
const sliced = locale.slice(0,2)
const lang = await LanguageService(ctx).getLanguage({
            sliced, // or locale: sliced
          });

From the next method the locale is showed as undefined and I have no clue how to pass only en in this situation I have
The method getLanguage
async getLanguage({ id, locale }) {
    console.log('locale: ', locale);
    if (!id && !locale) {
      const errorMessage = 'Specify ID or locale';
      throw new ApolloError(errorMessage);
    }

    const filter = id ? { id } : { locale };

    try {
      return await this.withDAO(({ languages }) =>
        languages.selectFirst(filter)
      );
    } catch (error) {
      throw new ApolloError(error.message);
    }
  }

This method needs { locale } and I need to pass en and not en_US
I have no clue how to reach that as when I reach this above method the console.log(locale) is showing undefined when I use slice.
There is a way I can use that obj in the way I need


Q: Group by array contents I have a List<Tuple<string,long,byte[]>> and I want to group by the contents of the byte array.
Is there a simple way to do this with GroupBy and a lambda?
Ideally, I want to do this without creating an intermediate data structure (like a string to hold the elements of the array).

A: You can achieve that using custom IEqualityComparer<byte[]> (or even better, generic one: IEqualityComparer<T[]>) implementation:
class ArrayComparer<T> : IEqualityComparer<T[]>
{
    public bool Equals(T[] x, T[] y)
    {
        return x.SequenceEqual(y);
    }

    public int GetHashCode(T[] obj)
    {
        return obj.Aggregate(string.Empty, (s, i) => s + i.GetHashCode(), s => s.GetHashCode());
    }
}

I'm pretty sure GetHashCode could be implemented much better, but it's just an example!
Usage:
var grouped = source.GroupBy(i => i.Item3, new ArrayComparer<byte>())


Q: How to show a message when collection view is empty I`m trying to show a message only when my collection view is empty. Well, I try set return 1 when my if is true but when I have this, it only show one item in my collection view (even if I had more). And when I return this (code bellow) it shows all the items I have in my collection view but when I try to delete it, the last one is not "deletable", I mean, the last one stays there. How can I show this message only if I have no items in my collection view?
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    if self.movies.count > 0 {

        self.favCollectionView.backgroundView = nil

        return self.movies.count
    }
    else {
        let rect = CGRect(x: 0,
                          y: 0,
                          width: self.favCollectionView.bounds.size.width,
                          height: self.favCollectionView.bounds.size.height)
        let noDataLabel: UILabel = UILabel(frame: rect)
        noDataLabel.text = "No favorite movies yet."
        noDataLabel.textAlignment = .center
        noDataLabel.textColor = UIColor.gray
        noDataLabel.sizeToFit()

        self.favCollectionView.backgroundView = noDataLabel

        return 0
    }
}

Update
I did it like this:
func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 2
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    if section == 0 { return self.movies.count}
    else if section == 1 {
        if self.movies.count < 1 { return 1 }
        else { return 0  }
    }
    return 0
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = favCollectionView.dequeueReusableCell(withReuseIdentifier: "FavCollectionCell", for: indexPath) as! FavoritesCollectionViewCell

    if indexPath.section == 0 {

        let movie = movies[indexPath.row]

        let imgStg: String = movie.posterURL!
        let imgURL: URL? = URL(string: imgStg)
        let imgSrc = ImageResource(downloadURL: imgURL!, cacheKey: imgStg)

        cell.favTitleLabel.text = movie.title

        cell.favPosterImageView.layer.cornerRadius = cell.favPosterImageView.frame.size.width/2
        cell.favPosterImageView.clipsToBounds = true

        //image cache with KingFisher
        cell.favPosterImageView.kf.setImage(with: imgSrc)

        return cell

    }

    else {

        let rect = CGRect(x: 0, y: 0, width: self.favCollectionView.frame.width, height: self.favCollectionView.frame.height)
        let noDataLabel: UILabel = UILabel(frame: rect)
        noDataLabel.text = "No favorite movies yet."
        noDataLabel.textAlignment = .center
        noDataLabel.textColor = UIColor.gray
        noDataLabel.sizeToFit()

        let cell = UICollectionViewCell()
        cell.contentView.addSubview(noDataLabel)

        return cell

    }

}

For @Lamar's solution, but the app crashed with error:

A: I make use of the backgroundView in an extension as such:
extension UICollectionView {

    func setEmptyMessage(_ message: String) {
        let messageLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height))
        messageLabel.text = message
        messageLabel.textColor = .black
        messageLabel.numberOfLines = 0;
        messageLabel.textAlignment = .center;
        messageLabel.font = UIFont(name: "TrebuchetMS", size: 15)
        messageLabel.sizeToFit()

        self.backgroundView = messageLabel;
    }

    func restore() {
        self.backgroundView = nil
    }
}

and I use it as such:
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    if (self.movies.count == 0) {
        self.collectionView.setEmptyMessage("Nothing to show :(")
    } else {
        self.collectionView.restore()
    }

    return self.movies.count
}

A: Maybe little bit late but here is little more constraint based solution. Still may help some one.
First create some empty state message (You can also create own, more complex view with image or something).
    lazy var emptyStateMessage: UILabel = {
        let messageLabel = UILabel()
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        messageLabel.textColor = .darkGray
        messageLabel.numberOfLines = 0;
        messageLabel.textAlignment = .center;
        messageLabel.font = UIFont.systemFont(ofSize: 15)
        messageLabel.sizeToFit()
        return messageLabel
    }()

Then add two methods and call them whenever you like.
    func showEmptyState() {
        collectionView.addSubview(emptyStateMessage)
        emptyStateMessage.centerXAnchor.constraint(equalTo: collectionView.centerXAnchor).activate()
        emptyStateMessage.centerYAnchor.constraint(equalTo: collectionView.centerYAnchor).activate()
    }

    func hideEmptyState() {
        emptyStateMessage.removeFromSuperview()
    }

A: Use backgroundView of your Collection View to display the no results message.

A: I would say have two sections in your collectionView, where one is for the actual data to be displayed, then the other one when you don't have any data.

Assuming we are populating data in section 0.

in numberOfRowsInSection you'd have something like:
     if section == 0 { return movies.count}
     else if section == 1 {
          if movies.count < 1 { return 1 }
          else { return 0  }
     }
        return 0

in your cellForItemAt you'd do something like that:
 if indexPath.section == 0 {
      // let cell = ...
      // show your data into your cell
        return cell
     }else {
          // here you handle the case where there is no data, but the big thing is we are not dequeuing
          let rect = CGRect(x: 0, y: 0, width: self.favCollectionView.frame.width, height: self.favCollectionView.frame.height)
        let noDataLabel: UILabel = UILabel(frame: rect)
        noDataLabel.text = "No favorite movies yet."
        noDataLabel.textAlignment = .center
        noDataLabel.textColor = UIColor.gray
        noDataLabel.sizeToFit()

        let cell = UICollectionViewCell()
        cell.contentView.addSubview(noDataLabel)

       return cell
      }

A: Why don't you use:

open var backgroundView: UIView?
// will be automatically resized to track the size of the collection view and placed behind all cells and supplementary views.`

You can show it whenever collection is empty. Example:
var collectionView: UICollectionView!
var collectionData: [Any] {
    didSet {
        collectionView.backgroundView?.alpha = collectionData.count > 0 ? 1.0 : 0.0
    }
}


Q: php menu generator with multidimensial array I need help with my array. For several hours trying to find a solution but I can not cope. I tried to do it in such a way, however, the code turned out to be completely useless.
private function findKey($array, $keySearch,$app,$klucz='')
{
    foreach ($array as $key => $item) {
        if ($key == $keySearch) {
            $c2 = [];
            $cache = [
                'nazwa'=>$app->nazwa,
                'link'=>$app->link,
                'child'=>[]
            ];

            // echo $klucz; echo '
';

            if($klucz && $klucz != '/'){
                // echo $klucz;
                // $k = explode('/',$klucz);
                // $url   = "/2/22/";
                // debug($klucz);
                $parts = explode('/',$klucz);
                debug($klucz);
                debug($parts);

                $x = 0;
                $last = $parts[count($parts)-1];
                $arr = array();
                while ($bottom = array_pop($parts)) {
                    if($bottom != $last){

                        $arr = array($bottom => $arr);
                        $x++;
                    }else{
                        array_push($arr, $cache);
                    }

                }

                // $arr['child'] = $cache;
                debug($arr);
                // exit;

                // print_r($output);
                // exit;

                // self::buildKey($k);

                // print_r($c2);

                echo "
";
            }

        }
        else {
            $klucz = $klucz.'/'.$key;
            if (is_array($item) && self::findKey($item, $keySearch,$app,$klucz)) {
               // return true;
            }
        }
    }

    // return false;
}

I need to create array from loop. From mysql I get data as object, and this data view like this:

|id|nazwa|link|parent|
|1|abc|abcc|0|
|2|aaa|bbb|1|
|3|aas|bbc|2|
|4|asdasd|adsasd|2|
|5|asdasd|serae|4|
|6|rywer|twet|0|

And now I need array whose use data from mysql and display it at array like this:
array(
    [1]=>array(
        id=>1,
        nazwa=>abc
        link=>abcc
        child=>array(

            [2]=>array(
                id=>2,
                nazwa=>aaa
                link=>bbb
                child=>array(

                    [3]=>array(
                        id=>3,
                        nazwa=>aas
                        link=>bbc
                        child=>array(

                        )
                    ),

                    [4]=>array(
                        id=>4,
                        nazwa=>asdasd
                        link=>adsasd
                        child=>array(

                            [5]=>array(
                                id=>5,
                                nazwa=>asdasd
                                link=>serae
                                child=>array(

                                )
                            ),
                        )
                    ),
                )
            )
        )
    ),

    [6]=>array(
        id=>6,
        nazwa=>rywer
        link=>twet
        child=>array(

        )
    ),
)

I think just a simple, good loop or function but I can not deal with it.

A: Try my code link to online demo:
<?php
$data = array(
    array(
        'id' => 1,
        'name' => 'abc',
        'link' => 'abcc',
        'parent' => 0
    ),
    array(
        'id' => 2,
        'name' => 'aaa',
        'link' => 'bbb',
        'parent' => 1
    ),
    array(
        'id' => 3,
        'name' => 'aas',
        'link' => 'bbc',
        'parent' => 2
    ),
    array(
        'id' => 4,
        'name' => 'asdasd',
        'link' => 'adsasd',
        'parent' => 2
    ),
    array(
        'id' => 5,
        'name' => 'asdasd',
        'link' => 'serae',
        'parent' => 4
    ),
    array(
        'id' => 6,
        'name' => 'rywer',
        'link' => 'twet',
        'parent' => 0
    )
);

function buildMenu($data) {
    usort($data, function($a, $b) {
        if ($a['parent'] == $b['parent']) {
            if ($a['id'] == $b['id']) {
                return 0;
            }
            return ($a['id'] < $b['id']) ? -1 : 1;
        }
        return ($a['parent'] < $b['parent']) ? -1 : 1;
    });

    $shortcuts = array();
    $menu = array();

    foreach($data as &$row) {
        if ($row['parent'] <= 0) {
            $menu[] = &$row;
            $shortcuts[$row['id']] = &$row;
            continue;
        } else {
            $parent = $row['parent'];
            if (!isset($shortcuts[$parent])) {
                throw new \Exception("Menu cannot be build");
            }
            $parentItem = &$shortcuts[$parent];
        }
        if (!isset($parentItem['child'])) {
            $parentItem['child'] = array();
        }
        $parentItem['child'][] = &$row;
        $shortcuts[$row['id']] = &$row;
    }
    return $menu;
}

print_r(buildMenu($data));

It uses references to keep it clean. On the beggining of buildMenu function I have also sorted your sorce array to have data sorted by parent ID, increasingly.
Please also consider using english variable names.
If you would like to generate
 menu from this array, use this code:
$menu = '
';
function buildUl($data) {
    $menuHtml = '';
    foreach ($data as $menuItem) {
        $menuHtml .= '
';
        $menuHtml .= ''.$menuItem['name'].'';
        if (!empty($menuItem['child'])) {
            $menuHtml .= '
';
            $menuHtml .= buildUl($menuItem['child']);
            $menuHtml .= '
';
        }
        $menuHtml .= '
';
    }

    return $menuHtml;
}
$menu .= buildUl(buildMenu($data));
$menu .= '
';

echo $menu;

Updated example: http://sandbox.onlinephpfunctions.com/code/27cfa95c066be9b1526b71566e2ec2f2093bdc34

A: Things are way easier when you use objects:
$data = [
    ['id' => 1, 'nazwa' => 'abc',    'link' => 'abcc',   'parent' => 0],
    ['id' => 2, 'nazwa' => 'aaa',    'link' => 'bbb',    'parent' => 1],
    ['id' => 3, 'nazwa' => 'aas',    'link' => 'bbc',    'parent' => 2],
    ['id' => 4, 'nazwa' => 'asdasd', 'link' => 'adsasd', 'parent' => 2],
    ['id' => 5, 'nazwa' => 'asdasd', 'link' => 'serae',  'parent' => 4],
    ['id' => 6, 'nazwa' => 'rywer',  'link' => 'twet',   'parent' => 0],

];

$objectTree = [];
$objects = [];

foreach ($data as $row) {
    $obj = (object)$row;
    $obj->childs = [];
    $objects[$obj->id] = $obj;
}

foreach ($objects as $obj) {
    if ($obj->parent == 0) {
        $objectTree[] = $obj;
    } else {
        $objects[$obj->parent]->childs[] = $obj;
    }
}

var_export($objectTree);

Demo: http://rextester.com/RZRQLX19028


Q: Clean tuple to string I have a variable p which print(p) = ('180849', '104735') and I want it to be p = 180849 104735
So, basically get rid off ( and ' and ,
Any help with that please?

A: You can directly unpack the elements to print function. By default print function insert space between the values(this can be controlled via sep argument)
>>> p = ('180849', '104735')
>>> print(*p)
180849 104735
>>> print(*p, sep='-')
180849-104735

A: How about this, it is the easier way!
tup = ('this', 'is', 'a', 'tuple')
res = " ".join(tup)

I hope you like it.


Q: Access listbox from another class? I made a class so when the user selects item from listbox it uninstalls that item, except the problem is I can't access the list box. I tried public aswell, but in the code of form1.cs  the only thing clostest to that list box is
keep in mind name of listbox is ProgramslistBox
Ok guys I re edited this post;
  private void button1_Click(object sender, EventArgs e)
    {
        if(ProgramsListbox.SelectedIndex == -1)
        {
            MessageBox.Show("Please select an item to uninstall!");
        }
        else
        {
            ProgramsListbox_SelectedIndexChanged("",EventArgs.Empty);
        }
    }

this code is the FORM1.CS class, and I have another class called UninstallItem.cs is where I want my code to be, this below is my other class
namespace PC_TECH_Registery_Cleaner
{
class UninstallItem
{
    public void uninstallSelectedItem()
    {
        Form1 c = new Form1();

    }
}

}
And this below is still in my FORM1.CS class, I was experimenting with it :
 public void ProgramsListbox_SelectedIndexChanged(object sender, EventArgs e)
    {

        //this will access the Uninstall item class so we can uninstall selected item.
        UninstallItem c = new UninstallItem();
        c.uninstallSelectedItem();
    }

A: The 2 easy ways to think about this are either

*

*Call the method in your class from the event handler in your form

*Have a method on your class which matches the signature of an event handler, and subscribe to the event.

The first requires no major change
private MyClass myClass = new MyClass();
public void ProgramsListbox_SelectedIndexChanged(object sender, EventArgs e)
{
    myClass.DoSomething();
}

The second requires your class to have a specific method that matches the signature of that event handler currently in your form
public class MyClass
{
    public void DoSomething(object sender, EventArgs e)
    {
        var listBox = (ListBox)sender;
        // read selected index perhaps, or selected item maybe
    }
}

And then in your form
private MyClass myClass = new MyClass();
protected override void OnLoad(EventArgs e)
{
    this.ProgramsListBox.SelectedIndexChanged += myClass.DoSomething;
}

A: Within your Form1.cs create instance of UnIstallItem class and use it. Then on Button Click call "RemoveSelected" method of UnInstaItem class by passing programsListBox to it and it should remove the selected item.
public class Form1:Form
{
    ListBox ProgramsListbox;
    UninstallItem unistall;

    public Form1(){
       InitializeComponent();
       uninstall = new UninstallItem();
       button1.Click+= button1_Click;
    }

    void button1_Click(object sender, EventArgs e){
        unistall.RemoveSelected(ProgramsListbox);
    }
}

Then in your external class;
public class UninstallItem{
   public UninstallItem{}

   public void RemoveSelected(ListBox list)
    {
        if(list.SelectedIndex==-1)
        {
            MessageBox.Show("Please Select Item from List");
            return;
        }
        list.Items.RemoveAt(list.SelectedIndex);

    }
}


Q: Obtaining destination ip address in Powershell (Invoke-WebRequest) I'm writing script for automation of TCP connections and I have a question. Is there an option to get destination IP address, when you call (for example):
Invoke-WebRequest google.com

Problem is, when I call this command, destination IP address is always different, so I can't use command like ''test-connection''. I would like to hear further explanation. I know that Google has multiple public addresses, but why are they different when I call Invoke-WebRequest, or Test-Connection?
Example:
1.
Destination IP from wireshark capture
2.
IP address from Test-Connection command:
 google.com      172.217.18.78
Greetings

A: Google has a huge userbase. They want to be reachable via multiple addresses, as that provides robust connections and some load balancing too. The technique is called DNS Round Robin. In case one of the multiple IP addresses doesn't work, most modern browsers will automatically try and use other addresses.
If you would like to test a connection to particular IP, you could do a name lookup and pick one of the results. Like so,
# Get a list of all Google IPs
$googles = [Net.Dns]::GetHostAddresses("www.google.com")
# Use IP address for the 1st entry
test-connection $googles[0].IPAddressToString


Q: Joi Schema should contain one or another chema I'm looking into using Joi for api validation.
So it must be like one or another chema
Joi.object({
            email: Joi.string().required(),
            notes: Joi.object({
                title: Joi.string().required(),
                details: Joi.string().required()
            })
        })

try for another
Joi.object({
            first_name: Joi.string().prefs({ convert: false }),
            last_name: Joi.string().prefs({ convert: false }),
            cell_phone_1: Joi.number().min(1e9).max(9999999999).prefs({ convert: false }),
        }).or('first_name', 'last_name'))

Thanks


Q: How can I add the class name of an object as the index of the serializated json in JMSSerialize I have a simple class like:
class Car
{
    public doors;
    public color;
    public seats;
}

If I serialize a new object with:
$this->get('jms_serializer')->serialize($newCar, 'json');

I will get something like:
{doors:1, color: 'red', seats: 4}

I wonder if it's possible to have this instead (Edit: and to be able to deserialize the same string):
car:{doors:1, color: 'red', seats: 4}

Thanks

A: You can try this:
// Encode
$className = get_class($newCar);
$jmsSerialize = $this->get('jms_serializer')->serialize($newCar, 'json');
$resultJSONEncode = json_encode([$className=>$jmsSerialize]);
var_dump($resultJSONEncode);

// Decode
$resultJSONDecode = json_decode($resultJSONEncode, true);
$jmsDesrialize = $this->get('jms_serializer')->deserialize($resultJSONDecode[$className], $className, 'json');
var_dump($jmsDesrialize);


Q: How to deploy a python webapp with dependencies using virtualenv? I'm looking for a way to automate deployment of web applications written in Python to a server. I would like to use virtualenv to have a clean environment for this application.
However, I am wondering how to manage dependencies when deploying to the server ?
In development, I have a virtualenv in which I install external libraries using pip, so I am looking for a way to automatically install those dependencies in production ?
Thank you for your time

A: With pip you can create a requirements file:
$ pip freeze > requirements.txt

Then in the server to install all of these you do:
$ pip install -r requirements.txt

And with this (if the server has everything necessary to build the binary packages that you might have included) all is ready.


Q: javafx shape3d texturing: Don't strectch the image I'm working now with javafx to build a maze and I want the walls to be textured with some seamless texture (that can be repeated). The maze is randomly generated so I don't know the size of any walls. I started by using a PhongMaterial with the desired texture, but it expand the image to fill the whole wall (a Box), so my texture is totally stretched. Is there any way to force the Material to replicate the texture as needed ?
The code is like:
Image img = new Image(new FileInputStream("img.jpg"), 400, 400, true, false);
Material mat = new PhongMaterial(Color.WHITE, img, null, null, null);
Box w = new Box(100,10,10);
w.setMaterial(mat);

Something like an ImagePattern seems a good idea, but there is no Material that accept it.
Thanks in advance for any help

A: As @fabian mentioned, Box is not suitable for customizing the texture. By default the image you set as diffuse map will be applied for each of its six faces, and, as you already discovered, this means that it will stretch the image to accommodate the different sides.
Using the FXyz library, we can easily try the Carbon-Kevlar pattern. But obviously we have to select a size for it. Like 100 x 30.

 @Override
public void start(Stage primaryStage) {
    Box box = new Box(100, 30, 50);
    PhongMaterial material = new PhongMaterial();
    Patterns pattern = new Patterns(100, 30);
    material.setDiffuseMap(pattern.createPattern(Patterns.CarbonPatterns.CARBON_KEVLAR, false));
    box.setMaterial(material);

    Scene scene = new Scene(new Group(box), 500, 400, true, SceneAntialiasing.BALANCED);
    primaryStage.setScene(scene);
    primaryStage.show();
}

While the texture fits perfectly fine the front face with dimensions 100x30, this image is distorted to fit in the same way the other faces 50x50 and 100x50.
Solution 1
We can try to generate our own Box, so we can decide how to apply the diffuse map.
Creating a TriangleMesh for a cuboid is easy in terms of vertices and faces or normals.
The tricky part is setting the texture coordinates. In the following snippet I set them based on one of the different possible 2D net images of the 3D cuboid:
public MeshView createCuboid(float w, float h, float d) {
    float hw = w / 2f;
    float hh = h / 2f;
    float hd = d / 2f;

    float points[] = {
             hw,  hh,  hd,
             hw,  hh, -hd,
             hw, -hh,  hd,
             hw, -hh, -hd,
            -hw,  hh,  hd,
            -hw,  hh, -hd,
            -hw, -hh,  hd,
            -hw, -hh, -hd};

    float L = 2 * w + 2 * d;
    float H = h + 2 * d;

    float tex[] = {
                  d / L,          0f,
            (d + w) / L,          0f,
                     0f,       d / H,
                  d / L,       d / H,
            (d + w) / L,       d / H,
        (2 * d + w) / L,       d / H,
                     1f,       d / H,
                     0f, (d + h) / H,
                  d / L, (d + h) / H,
            (d + w) / L, (d + h) / H,
         (2 *d + w) / L, (d + h) / H,
                     1f, (d + h) / H,
                  d / L,          1f,
            (d + w) / L,          1f};

    float normals[] = {
         1f,  0f,  0f,
        -1f,  0f,  0f,
         0f,  1f,  0f,
         0f, -1f,  0f,
         0f,  0f,  1f,
         0f,  0f, -1f,
    };

    int faces[] = {
            0, 0, 10, 2, 0,  5, 1, 0,  9,
            2, 0,  5, 3, 0,  4, 1, 0,  9,
            4, 1,  7, 5, 1,  8, 6, 1,  2,
            6, 1,  2, 5, 1,  8, 7, 1,  3,
            0, 2, 13, 1, 2,  9, 4, 2, 12,
            4, 2, 12, 1, 2,  9, 5, 2,  8,
            2, 3,  1, 6, 3,  0, 3, 3,  4,
            3, 3,  4, 6, 3,  0, 7, 3,  3,
            0, 4, 10, 4, 4, 11, 2, 4,  5,
            2, 4,  5, 4, 4, 11, 6, 4,  6,
            1, 5,  9, 3, 5,  4, 5, 5,  8,
            5, 5,  8, 3, 5,  4, 7, 5,  3};

    TriangleMesh mesh = new TriangleMesh();
    mesh.setVertexFormat(VertexFormat.POINT_NORMAL_TEXCOORD);
    mesh.getPoints().addAll(points);
    mesh.getTexCoords().addAll(tex);
    mesh.getNormals().addAll(normals);
    mesh.getFaces().addAll(faces);

    return new MeshView(mesh);
}

Now we can generate the image, but using the net dimensions:
    @Override
public void start(Stage primaryStage) {
    MeshView box = createCuboid(100, 30, 50);
    PhongMaterial material = new PhongMaterial();
    Patterns pattern = new Patterns(300, 160);
    material.setDiffuseMap(pattern.createPattern(Patterns.CarbonPatterns.CARBON_KEVLAR, false));
    box.setMaterial(material);
    box.getTransforms().addAll(rotateX, rotateY);
    Scene scene = new Scene(new Group(box), 500, 400, true, SceneAntialiasing.BALANCED);

    primaryStage.setScene(scene);
    primaryStage.show();
}

Note that the image is not distorted anymore.

You can play with its size to get a more fine or dense pattern (with a bigger image pattern).
Note that you can find this Cuboid primitive in the FXyz library, among many other 3D primitives.
Also you can find different texture modes (density maps, images, patterns...)


Q: Bit shifting 16 bit from left to right C# I have an array of 8 bit with the following representation.  Data[i] = 192=11000000, data[i+1]= 85=01010101, i need to transform the represenatation into 16bit array where newArr[i] =343=101010111.  The same numbers only shifted to right. My first idea was to use the field i have bpp (number of bits =10). So var t=16-10. Data[i] >>t. And Data[i+1]>>t however this doesn't give the correct answer.  Please help

A: I have these two functions for you, to shift in a byte-array:
static public void ShiftLeft(this byte[] data, int count, bool rol)
{
    if ((count <0) || (count > 8))
        throw new ArgumentException("Count must between 0 and 8.");
    byte mask = (byte)(0xFF << (8 - count));
    int bits = rol ? data[0] & mask : 0;
    for (int i = data.Length - 1; i >= 0; i--)
    {
        int b = data[i] & mask;
        data[i] = (byte)((data[i] << count) | (bits >> (8 - count)));
        bits = b;
    }
}

static public void ShiftRight(this byte[] data, int count, bool rol)
{
    if ((count <0) || (count > 8))
        throw new ArgumentException("Count must between 0 and 8.");
    byte mask = (byte)(0xFF >> (7 - count));
    int bits = rol ? data[data.Length - 1] & mask : 0;
    for (int i = 0; i < data.Length; i++)
    {
        int b = data[i] & mask;
        data[i] = (byte)((data[i] >> count) | (bits << (8 - count)));
        bits = b;
    }
}

For your code example, call them like this:
byte[] data = ...;
ShiftLeft(data, 2, false);

Assuming you want to copy 2 bytes into 1 ushort, you can use this code (make sure it is even in length!):
byte[] data = ...;
short[] sdata = new short[data.Length / 2];
Buffer.BlockCopy(data, 0, sdata, 0, dataLen);

If you want to copy 1 byte into 1 ushort, then this would be the answer:
byte[] data = ...;
short[] sdata = Array.ConvertAll(data, b => (short)b);

A: I take your question to mean you want to do this conversion: combine aaaaaaaa and bbbbbbbb into bbbbbbbbaaaaaaaa and then apply a right-shift by 6, yielding 000000bbbbbbbbaa.
Then this will be your code:
using System;

public class Test
{
  public static void Main()
  {
    byte[] src = new byte[2] { 192, 85 };
    ushort[] tgt = new ushort[1];

    for ( int i = 0 ; i < src.Length ; i+=2 )
    {
      tgt[i] = (ushort)( ( src[i+1]<<8 | src[i] )>>6 );
    }
    System.Console.WriteLine( tgt[0].ToString() );
  }
}

If what you want to do is combine to aaaabbbbbbbbaa, then this will require |-ing a src[i]<<10 in a second step, as there is no circular shift operator in C#.

A: my final code :D
 public override short[] GetShortDataAlignedRight()
    {
        short[] ReturnArray = new short[_channels[0].Data.Length / 2];
        if (_channels[0].Bpp == 8)
        {
            Buffer.BlockCopy(_channels[0].Data, 0, ReturnArray, 0, _channels[0].Data.Length);
        }
        else
        {
            short tempData;
            int offsetHigh = 8 - (16 - _channels[0].Bpp);
            int offsetLow = (16 - _channels[0].Bpp);
            for (int i = 0, j = 0; i < _channels[0].Data.Length; i += 2, j++)
            {
                tempData = (short)(_channels[0].Data[i] >> offsetLow);
                tempData |= (short)(_channels[0].Data[i + 1] << offsetHigh);
                ReturnArray[j] = tempData;
            }
        }
        return ReturnArray;
    }


Q: How does the connection manager discard unconsumed connection? I am trying to debug a connection leak issue in my app where the connection manager is using more connections than I would have wanted. One lead I have is the following:
According to Apache HttpClient quick start, if response content is not fully consumed for any reason, the pooling connection manager can not safely reuse the underlying connection and will discard it.
Can anyone point me to the code block that does the checking of unconsumed content in a connection and the discarding of the connection?
// Please note that if response content is not fully consumed the underlying
    // connection cannot be safely re-used and will be shut down and discarded
    // by the connection manager.
    try (CloseableHttpResponse response1 = httpclient.execute(httpGet)) {
        System.out.println(response1.getCode() + " " + response1.getReasonPhrase());
        HttpEntity entity1 = response1.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        EntityUtils.consume(entity1);
    }

A: HttpClient version 4.x and 5.x wrap HTTP response entity with a proxy that releases the underlying connection back to the pool upon reaching the end of the message stream. In all other cases HttpClient assumes the message has not been fully consumed and the underlying connection cannot be re-used.
https://github.com/apache/httpcomponents-client/blob/master/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/ResponseEntityProxy.java


Q: Reading data from a BLE smartband failed with app inventor I have a smartband (DS-D6) that communicates values through AT commands with the use of two UUIDs (0000190b-0000-1000-8000-00805f9b34fb and  0000190a-0000-1000-8000-00805f9b34fb). I confirmed these two UUIDs are working using a Serial BLE Terminal App. However, only one of the UUID (0000190b-0000-1000-8000-00805f9b34fb) is working, with app inventor (using latest BLE extension). I don’t know what is going wrong. The device is connected but there is no response to AT commands when I use 0000190a-0000-1000-8000-00805f9b34fb service UUID, while everything works well using the other UUID. I double checked the UUID numbers carefully and also confirmed them using nRFconnect app. I tried to interchange characteristic UUID values, still it didn't work. I don't understand what is causing this behavior that only of the service UUIDs is working with app inventor while both of them are working with BLE serial APP. I attached here the relevant blocks from App inventor. Please note that I am using only of the service UUIDs at a time. More information about the smartband can be found in the following link
https://github.com/fanoush/ds-d6/wiki/Bracelet-commands


Q: Detect faces in python with MTCNN, Opencv and multithreading I'm here because I'm really stuck on my project. At the beginning of my project, it was just a simple face detection that worked pretty well using Python, Opencv, and the MTCNN model. The problem was that the program was pretty slow and I tried to make it faster.  My research then, unfortunately, led me to multithreading and I didn't really know what I was getting into.
In my program, I'm using
1 function: process_frame()
2 variables: frame and frame_buffer
The purpose of this program is therefore to have both image processing and simultaneous playback of video streams in order to gain performance. The problem is that imshow() of my function "process_frame" works very well,  I have pictures with a face detected. However, as soon as I enter my main loop, I have a simple video stream without detection. I was just wondering if my problem would not come from a problem with the synchronization of my threads.
I know that adding multithreading can slow down my program more than anything else but you have to practice to understand ahah
I would be pleased to have a little help because I admit to being stuck for a long time
Below is the code:
    import cv2
    import numpy as np
    from mtcnn import MTCNN
    import threading
    import time
    import tensorflow as tf
    from threading import Lock
    #import pdb

    #pdb.set_trace()
    lock = Lock()
    cap = cv2.VideoCapture(0)
    frame_buffer = []
    frame = None

    def process_frame():
        global frame_buffer, stop_event, lock, frame
        while not stop_event.is_set():
            try:
                lock.acquire()
                if frame is None:
                    print("frame vide")
                    continue
                print ("frame copié avec succes")
                frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                frame = cv2.resize(frame, (320,240))
                frame = frame_buffer
            except Exception as e:
                print("Une exception a été levée lors du traitement de l'image :", e)
                continue
            finally :
                lock.release()

            try:
                model = MTCNN(min_face_size=10)
                predictions = model.detect_faces(frame)
                print(f"{len(predictions)} visages détectés")
            except Exception as e:
                print("Une exception a été levée lors de la détection des visages :", e)

            try:
                predictions = [prediction for prediction in predictions if prediction['confidence'] > 0.5]
                print(f"{len(predictions)} visages filtrés")
            except Exception as e:
                print("Une exception a été levée lors de la filtration des prédictions :", e)

            for face in predictions:
                try:
                    x, y, w, h = face['box']
                    with lock :
                        cv2.rectangle(frame, (x,y), (x+w, y+h), (255, 0, 0), 2)
                        cv2.imwrite("parth/image_traitee_process_frame.jpg", frame_buffer,     [cv2.IMWRITE_JPEG_QUALITY, 100])
                except Exception as e:
                    print("Une exception a été levée lors de l'ajout de l'annotation du rectangle :", e)
            print ("frame mis a jour avec succes")
            #frame_buffer = frame
            print ("Copie de la liste de frame : ", frame, "dans frame_buffer : ", frame_buffer)
            time.sleep(0.01)

    stop_event = threading.Event()
    thread = threading.Thread(target=process_frame)
    thread.daemon = True
    thread.start()

    start_time = time.perf_counter()
    frame_count = 0

    def stop_thread():
        stop_event.set()
        thread.join()

    while True:

        ret, frame = cap.read()
        if ret:
            frame_buffer = frame.copy()
        else :
            frame = frame_buffer
        frame = frame_buffer
        print ("valeur de frame_buffer après cap.read : ", frame_buffer)
        print (cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        print (cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
        cv2.imwrite("parth/image_traitee_boucle_while.jpg", frame_buffer, [cv2.IMWRITE_JPEG_QUALITY, 50])

        if not ret:
            break
        lock.acquire()
        #frame_buffer = frame
        lock.release()
        frame_count += 1
        elapsed_time = time.perf_counter() - start_time
        if elapsed_time > 1.0:
            print("Frames par seconde : ", frame_count / elapsed_time)
            start_time = time.perf_counter()
            frame_count = 0
        lock.acquire()
        #print(frame_buffer.shape)
        cv2.imshow("Output", frame_buffer)
        lock.release()
        key = cv2.waitKey(1) & 0xFF
        if key == ord("q"):
            break

    cap.release()
    cv2.destroyAllWindows()
    stop_thread()

I tried a lot of things like catching some exceptions with try-except but I have nothing.
with some print statements, ret is set to true, frame in my loop got the position in cap.read() but I don't know where is the problem.


Q: Using Insert Iterators when reading from file can you use Insert Iterators while reading from a file to put the data into STL container?
for example:
FILE *stream;
fread(back_inserter(std::list), sizeof(int), 1, stream);

A: C++ streams are not compatible with C stdio streams.  In other words, you can't use C++ iterators with FILE* or fread.  However, if you use the C++ std::fstream facilities along with istream_iterator, you can use an insertion iterator to insert into a C++ container.
Assuming you have an input file "input.txt" which contains ASCII text numbers separated by whitespace, you can do:
#include <iostream>
#include <fstream>
#include <vector>
#include <iterator>

int main()
{
 std::ifstream ifs("input.txt");
 std::vector<int> vec;
    // read in the numbers from disk
 std::copy(std::istream_iterator<int>(ifs), std::istream_iterator<int>(), std::back_inserter(vec));
    // now output the integers
 std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, "\n"));
}

A: no you can't. And it's fundamentally not-portable to store int like that. Your code will break if you write your file with a big-endian machine and try to read it with a little-endian machine.
But nobody prevents you to. Just define your own forward iterator that reads binary from a istream. You will likely want to stop using FILE and fread/fopen/fclose function as they are from C era.
then you will be able to write :
std::copy_n(your_custom_forward_iterator, count, back_inserter<std::list<....> >);


Q: Get the most value from another column I want to get data historical and  the production. My stored procedure is as follows:
ALTER PROCEDURE [dbo].[pCaRptACInactivas](
                    @CodAsesor      VARCHAR(15),
                    @CodOficina     VARCHAR(4))

    AS
    SET NOCOUNT ON

    DECLARE @CodArbolConta VARCHAR(25)

    IF @CodOficina = '%'
        SET @CodArbolConta = '%'
    ELSE
        SELECT @CodArbolConta = CodArbolConta + '%'     FROM   tClOficinas  WHERE  CodOficina LIKE @CodOficina

    SELECT
        tabACInactivas.CodOficina,
        tabACInactivas.NomOficina,
        tabACInactivas.NomAsesor,
        MAX(tabACInactivas.CodPrestamo) CodPrestamo,
        tabACInactivas.CodAsociacion,
        tabACInactivas.NombreAsociacion,
        MAX(tabACInactivas.Ciclo) AS Ciclo,
        COUNT(DISTINCT tabACInactivas.CodUsuario) AS CantSocias,
        MAX(tabACInactivas.FechaEstado) AS FechaCancelacion--,

    FROM (      SELECT          tClOficinas.CodOficina,             tClOficinas.NomOficina,             tCaClAsesores.CodAsesor,                        tCaClAsesores.NomAsesor,            tCaPrestamos.CodPrestamo,           tCaAsociacion.CodAsociacion,            tCaAsociacion.NombreAsociacion,             tCaPrestamos.Ciclo,             tCaPrCliente.CodUsuario,            tCaPrestamos.FechaEstado,           tClParametros.FechaProceso      FROM            tCaPrestamos WITH(NOLOCK)           INNER JOIN tCaProducto WITH(NOLOCK) ON tCaProducto.CodProducto = tCaPrestamos.CodProducto           INNER JOIN tClOficinas WITH(NOLOCK) ON tClOficinas.CodOficina = tCaPrestamos.CodOficina             INNER JOIN tCaAsociacion WITH(NOLOCK) ON tCaAsociacion.CodAsociacion = tCaPrestamos.CodAsociacion           INNER JOIN tCaPrCliente WITH(NOLOCK) ON tCaPrCliente.CodPrestamo = tCaPrestamos.CodPrestamo             INNER JOIN tClParametros WITH(NOLOCK) ON tClParametros.CodOficina = tClOficinas.CodOficina          INNER JOIN tCaClAsesores ON tCaClAsesores.CodAsesor = tCaAsociacion.CodAsesor       WHERE           tCaPrestamos.Estado = 'CANCELADO'           AND DATEDIFF(DAY, tCaPrestamos.FechaEstado, tClParametros.FechaProceso) > 30            AND NOT EXISTS(SELECT 1
                           FROM tCaPrestamos Pr
                           INNER JOIN tCaPrCliente PrCl ON PrCl.CodPrestamo = Pr.CodPrestamo
                           WHERE Pr.Estado NOT IN ('TRAMITE', 'APROBADO')
                           AND Pr.FechaDesembolso >= tCaPrestamos.FechaEstado
                           AND Pr.CodAsociacion = tCaPrestamos.CodAsociacion
                          )             AND tCaProducto.Tecnologia = 3          AND tCaPrestamos.CodAsesor LIKE @CodAsesor              AND tCaPrestamos.CodOficina IN (SELECT CodOficina FROM tClOficinas WHERE CodArbolConta LIKE @CodArbolConta)

        UNION ALL

        SELECT          tClOficinas.CodOficina,             tClOficinas.NomOficina,             tCaClAsesores.CodAsesor,            tCaClAsesores.NomAsesor,            tCaHPrestamos.CodPrestamo,          tCaAsociacion.CodAsociacion,            tCaAsociacion.NombreAsociacion,             tCaHPrestamos.Ciclo,            tCaHPrCliente.CodUsuario,           tCaHPrestamos.FechaEstado,          tClParametros.FechaProceso          FROM            tCaHPrestamos WITH(NOLOCK)          INNER JOIN tCaProducto WITH(NOLOCK) ON tCaProducto.CodProducto = tCaHPrestamos.CodProducto          INNER JOIN tClOficinas WITH(NOLOCK) ON tClOficinas.CodOficina = tCaHPrestamos.CodOficina            INNER JOIN tCaAsociacion WITH(NOLOCK) ON tCaAsociacion.CodAsociacion = tCaHPrestamos.CodAsociacion          INNER JOIN tCaHPrCliente WITH(NOLOCK) ON tCaHPrCliente.CodPrestamo = tCaHPrestamos.CodPrestamo          INNER JOIN tClParametros WITH(NOLOCK) ON tClParametros.CodOficina = tClOficinas.CodOficina          INNER JOIN tCaClAsesores ON tCaClAsesores.CodAsesor = tCaAsociacion.CodAsesor       WHERE           tCaHPrestamos.Estado = 'CANCELADO'          AND DATEDIFF(DAY, tCaHPrestamos.FechaEstado, tClParametros.FechaProceso) > 30           AND NOT EXISTS(SELECT 1
                           FROM tCaHPrestamos Pr
                           INNER JOIN tCaHPrCliente PrCl ON PrCl.CodPrestamo = Pr.CodPrestamo
                           WHERE Pr.Estado NOT IN ('TRAMITE', 'APROBADO')
                           AND Pr.FechaDesembolso >= tCaHPrestamos.FechaEstado
                           AND Pr.CodAsociacion = tCaHPrestamos.CodAsociacion
                          )             AND tCaProducto.Tecnologia = 3          AND tCaHPrestamos.CodAsesor LIKE @CodAsesor             AND tCaHPrestamos.CodOficina    IN (SELECT CodOficina FROM tClOficinas WHERE CodArbolConta LIKE @CodArbolConta)

    )tabACInactivas
    GROUP BY            tabACInactivas.CodAsociacion,           tabACInactivas.NombreAsociacion,            tabACInactivas.NomOficina,          tabACInactivas.CodOficina,          tabACInactivas.NomAsesor

I want the CantSocias column takes the most value of the Ciclo column, but not working

A: That stored procedure that you have posted up is way too large and blocky to even try to interpret and understand.  So I will go off of your last sentence:

I want the CantSocias column takes the most value of the Ciclo column,
  but not working

Basically if you want to set a specific column to that, you can do something like this:
update YourTable
set CantSocias =
(
  select max(Ciclo)
  from YourOtherTable
)
-- here is where you can put a conditional WHERE clause

A: You may need to create a sub query to get the most value of Ciclo and join back to your query.
An example of what I mean is here:
create table #Product
(
    ID int,
    ProductName varchar(20)
)

insert into #Product(ID, ProductName)
    select 1,'ProductOne'
    union
    select 2,'ProductTwo'

create table #ProductSale
(
    ProductID int,
    Number int,
    SalesRegion varchar(20)
)

insert into #ProductSale(ProductID,Number,SalesRegion)
    select 1,1500,'North'
    union
    select 1, 1200, 'South'
    union
    select 2,2500,'North'
    union
    select 2, 3200, 'South'

--select product sales region with the most sales
select * from #Product p

select ProductId, Max(Number) as Bestsale   from #ProductSale ps group by ProductID

--combining
select
    p.ID,
    p.ProductName,
    tp.Bestsale,
    ps.SalesRegion
from
    #Product p
inner join
    (select ProductId, Max(Number) as Bestsale   from #ProductSale ps group by ProductID) as tp on p.ID = tp.ProductID
inner join
    #ProductSale ps on p.ID = ps.ProductID and tp.Bestsale = ps.Number


Q: How to pair a Windows 10 phone with PC for debugging? I get a code on my phone - but where do I enter it?
I tried connecting by usb, entering the wifi url into my PC's browser ("insecure connection"),...

A: Edited (May2016):
With later Win10 mobile its now possible to debug a phone running Windows 10 Mobile via WIFI.
Follow the guidance here: https://msdn.microsoft.com/en-us/windows/uwp/debug-test-perf/device-portal-mobile


Q: Combo box automatically assigns a value, when not wanted. C# Windows Forms I'm having this issue with ComboBox controls. I select a value for the combo box (Already pre-setted) and it AUTOMATICALLY assigns the same value to another ComboBox next to it. Despite their data source is the same List, I want to select two different values (from that same list) for those two combo boxes.
cmbEmpresas.DataSource = Empresa.listaDeEmpresas;
cmbEmpresas.DisplayMember = "NombreEmpresa"; //This works OK

cmbLlegada.DataSource = Locacion.listaDeLocaciones;
cmbLlegada.DisplayMember = "Ciudad";

//These two represent a starting and arriving location for a trip
//they both have objects of the type "Locación"

cmbSalida.DataSource = Locacion.listaDeLocaciones;
cmbSalida.DisplayMember = "Ciudad";

As it is shown in the previous image, both cmbLlegada and cmbSalida have the same value, I did not want this to happen, I just selected cmbSalida's value and it automatically changed cmbLlegada's value.


Q: Xamarin form: How display activityindicator instantly while in async task?     public async Task ShowIndicator(Func<Task> action)
    {
        actionEnabled = false;
        IndicatorVisibility = true;
        await Task.Delay(5000);
        await action.Invoke();
        IndicatorVisibility = false;
        actionEnabled = true;
    }

I am using the above code to run some Task while showing the indicator by setting the viewmodel properties of the IndicatorVisibility. If I placed the Task.Delay, it will ok but will slow down the code. If I am not placed it, the indicator won't show straightaway coz it will set to second to last indicator visibility to false.
Is it possible to wait the indicator displayed itself before execute the action from the above code?

A: I had the same issue. This has the exact problem, the activity indicator never appers or appears too late:
async void GoDetail(object obj)
{
    Busy = true;

    DetailsViewModel.Initialize(_items, this.SelectedItem);

    await App.Current.MainPage.Navigation.PushAsync(new xxxPage());

    Busy = false;

}

This fixes it, activity indicator appears instantly...:
async void GoDetail(object obj)
{
    Busy = true;
    Device.BeginInvokeOnMainThread(async () =>
    {
        DetailsViewModel.Initialize(_items, this.SelectedItem);

        await App.Current.MainPage.Navigation.PushAsync(new xxxPage());

        Busy = false;
    });

}

A: Try this code
 public Task ShowIndicator(Func<Task> action)
    {
        actionEnabled = false;
        IndicatorVisibility = true;

        Device.BeginInvokeOnMainThread(async () =>
        {
            await action.Invoke();
            IndicatorVisibility = false;
            actionEnabled = true;
        });
    }


Q: Get Join table data as a result of ActiveRecord:Relation I am using rails 5 and oracle as a database. My query look like this..
DefaultConfig.where("role_id = ?","1001").joins(:config_param)

Now i want to get the result object as a config_param object not a default_config..
is it possible to do? Thanks for any help
class DefaultConfig < ApplicationRecord
    self.table_name = "default_config"
    belongs_to :role
    belongs_to :config_param
end

class ConfigParam < ApplicationRecord
    self.table_name = "config_param"
    has_many :default_configs, foreign_key: "param_id"
end

A: ConfigParam.joins(:default_configs).where(default_config: { role_id: 1001 })


Q: XAML adding text based on a trigger <dxg:GridControl Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" ItemsSource="{Binding Notes}" AutoGenerateColumns="None" ColumnGeneratorTemplateSelector="{StaticResource ColumnTemplateSelector}" dependencyProperties:BestFitColumn.IsEnabled="True" SelectedItem="{Binding SelectedRow}">
            <dxg:GridControl.Columns>
                <dxg:GridColumn FieldName="Priority" Header="{x:Static meta:MetaCommon.Importance}">
                    <dxg:GridColumn.CellTemplate>
                        <DataTemplate>
                            <Image>
                                <Image.Style>
                                    <Style BasedOn="{StaticResource SmallIcon}" TargetType="Image">
                                        <Style.Triggers>
                                            <DataTrigger Binding="{Binding RowData.Row.Priority}" Value="H">
                                                <Setter Property="Source" Value="{x:Static helper:IconHelper.HighImportance}" />
                                                <Setter Property="ToolTip" Value="{x:Static meta:MetaCommon.High}" />
                                            </DataTrigger>
                                    </Style.Triggers>
                                </Style>
                            </Image.Style>
                        </Image>
                    </DataTemplate>

I'm wondering if it's possible to add text in the case where RowData.Row.Priority=H. I can't seem to find any way myself and was wondering if I just missed something or if have to create a work around and do something outside of this statement.

A: You can move your DataTrigger under DataTemplate.Triggers.
Have it set the Visibility for a new TextBlock with the text you want.
<DataTemplate>
<Grid>
<Image/>
<TextBlock Visibility="Collapsed"/>
</Grid>
<DataTemplate.Triggers>
</DataTemplate.Triggers>
</DataTemplate>


Q: Facebook Login Invalid Key Hash After First Login I have added the key hash logged by this call (plus an equals sign) to the settings for my app on the Facebook developer site.
Log.d("MyApp", FacebookSdk.getApplicationSignature(this));
I can repeat the following steps indefinitely. Facebook login works the first time, but fails on all subsequent attempts.
Facebook App (v91.0.0.17.68)
Facebook Android SDK (v4.15.0)

*

*Revoke Facebook Login at https://www.facebook.com/settings?tab=applications

*Login with Facebook

*

*Success

*Login with Facebook

*

*Invalid key hash. The key hash KEY_HASH does not match any stored key hashes. Configure your app key hashes at http://developers.facebook.com/apps/FACEBOOK_APP_ID

The KEY_HASH in the error messages exactly matches one of the key hashes I have saved to the app on the Facebook developer site (at the link listed in the error message).
This only happens when the Facebook app is installed on the device. Facebook login succeeds multiple times in a row using the fallback web login.
I've found this and this question that have a combined single answer of "revoke Facebook Login manually in the app before trying to log in again" which seems like a hacky workaround to me.
Why do you have to revoke Facebook Login before logging in again? With the web fallback login it just says "you've already authorized this app". I would expect the same behavior here.
Edit: This only happens with a debug build. I can login repeatedly with the Facebook app installed if I use a release build (minify disabled just to reduce the changes).

A: Same thing happened to me and I had generated hash from debugkey for debugging in dev enviroment but when building it for Google Play the problem was appearing. You need to generate hash with the certificate and alias that you will sign the app for publishing in Google Play.
Edit: You need to add key hash for both debug key and release key.


Q: Cannot insert the value NULL into column 'X', table 'DB139.dbo.Y'; column does not allow nulls. INSERT fails I'm working on a SQL Server.
I have created the following table:
CREATE TABLE Payment(
    Cust_ID                 CHAR(4),
    Credit_Card_Number      CHAR(16),
    Payment_Number          INTEGER,
    Date                    DATE,
    Fee                     MONEY,
    PRIMARY KEY (Cust_ID, Credit_card_number, Payment_number))

ALTER TABLE Payment
    ADD CONSTRAINT FK_CustPays
        FOREIGN KEY (Cust_ID)
        REFERENCES Customer(Cust_ID) ON DELETE CASCADE
;

ALTER TABLE Payment
    ADD CONSTRAINT FK_CardPayment
        FOREIGN KEY (Credit_Card_Number)
        REFERENCES Credit_card(Credit_card_number) ON DELETE CASCADE
;

As you can probably tell, this is a weak entity. I suspect this is the reason why I can't insert values into it with the INSERT INTO statement, like this:
Insert into Payment(Payment_number,Date,Fee) Values ('918702','2016-08-12',93);

I get the error

Cannot insert the value NULL into column 'Cust_ID', table 'DB139.dbo.Payment'; column does not allow nulls. INSERT fails.

I have successfully inserted data into all of my other tables this way. The only 2 tables that have also been affected by this are the other 2 weak entities (the tables Savings_account and Checking_account). As you can tell, I haven't included any NULL values, so I'm not sure what this error is about.
Here are the 2 other weak entities, for reference (after the "Account" table):
CREATE TABLE  Account(
   Account_number           CHAR(10),
   Balance                  MONEY,
   Name_of_bank             VARCHAR(50),
   Date_of_creation         DATE,
   PRIMARY KEY  (Account_number))

ALTER TABLE Account
    ADD Account_number CHAR(16)
    CONSTRAINT FK_AccountNumberDouble
        FOREIGN KEY (Credit_card_number)
        REFERENCES Credit_card(Credit_card_number) ON DELETE CASCADE
;

ALTER TABLE Account
    ADD Cust_ID CHAR(4)
    CONSTRAINT FK_CustIDTriple
        FOREIGN KEY (Cust_ID)
        REFERENCES Customer(Cust_ID)
;

CREATE TABLE Savings_account(
  Account_number      CHAR(10),
  Interest_rate       INTEGER,
  PRIMARY KEY  (Account_number))

ALTER TABLE Savings_account
    ADD CONSTRAINT FK_SavingsAccount
        FOREIGN KEY (Account_number)
        REFERENCES Account(Account_number)
;

CREATE TABLE Checking_account(
  Account_number        CHAR(10),
  Overdraft_limit       MONEY,
  PRIMARY KEY  (Account_number))

ALTER TABLE Checking_account
    ADD CONSTRAINT FK_CheckingAccount
        FOREIGN KEY (Account_number)
        REFERENCES Account(Account_number)
;

Any help is appreciated.

A: you should be insert value for Cust_ID because it not identity and it primary key..
or you alter Cust_ID to identity


Q: ThreadStart, field initializer cannot reference the non-static field I am trying to use Threads in my app but i get a error. I searched a solution at MSDN and other forums but i didn't get it.
public class ClickingThread
    {
        private const int MOUSEEVENTF_LEFTDOWN = 0x0002;
        private const int MOUSEEVENTF_LEFTUP = 0x0004;

        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);

        public ClickingThread()
        {
        }

        public void MouseClicking()
        {
            int X = Cursor.Position.X;
            int Y = Cursor.Position.Y;
            Thread.Sleep(100);
            mouse_event(MOUSEEVENTF_LEFTUP, X, Y, 0, 0);
            mouse_event(MOUSEEVENTF_LEFTDOWN, X, Y, 0, 0);
        }

        public void Click()
        {
            while (true)
            {
                MouseClicking();
            }
        }
    }

And when i try to use method from this class like this
ClickingThread clicker = new ClickingThread();
Thread click = new Thread(new ThreadStart(clicker.Click));

I get an error (second line -> clicker.Click)"A field initializer cannot reference the non-static field, method etc."
Thanks for advices.


Q: Web Scraping an Image I was thinking about the applications of web scraping (still quite new to it) and came up with a question.  Can you get an image from a page if there are advertisements on the page (like can you avoid advertisements and only look for the correct image content on the page)?  Also, if the image is also a link to another page, can you say go to the next page and get that image (and then go from there until you either reach a certain amount or get all of the images)?  This would mean avoiding going to the advertisements pages.

A: Absolutely. If you use a tool like kimonolabs.com this can be relatively easy. You click the data that you want on the page, so instead of getting all images including advertisements, Kimono uses the CSS selectors of the data you clicked to know which data to scrape.
You can use Kimono to scrape data within links as well. It's actually a very common use. Here's a break-down of that strategy: https://help.kimonolabs.com/hc/en-us/articles/203438300-Source-URLs-to-crawl-from-another-kimono-API
This might be a helpful solution for you, especially if you're not a programmer because it doesn't require coding experience. It's a pretty powerful tool.

A: I think if you are ok with PHP programming then give a look into php simple html dome parser. I have used it a lot and scrapped number of websites.


Q: setBackgroundResource on ImageView return null I'm using ListFragment in my android project. I decided to make a listView, each listview item consist of music frequency imageView. I will try to animate the imageView of music frequency. Each listView has a button called play, once the play is clicked, the music frequency start to animate.
public View onCreateView(LayoutInflater inflater,
         ViewGroup container,  Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragmentmusiclist, container, false);
    lv = (ListView) v.findViewById(R.id.list);

    mp = new MediaPlayer();
    mp = null;

    Song s1 = new Song("Love Story",(float) 2.5, onMusicPlayListener);
    Song s2 = new Song("Sad Story",(float) 1.0, onMusicPlayListener);
    Song s3 = new Song("Breakup Story",(float) 3.5, onMusicPlayListener);

    songs = new ArrayList<Song>();
    songs.add(s1);
    songs.add(s2);
    songs.add(s3);

    adapter = new MusicListAdapter(getActivity(),songs);
    setListAdapter(adapter);

    return super.onCreateView(inflater, container, savedInstanceState);
}

OnClickListener onMusicPlayListener = new OnClickListener() {

@Override
public void onClick(View v) {
  final int position = getListView().getPositionForView((LinearLayout)v.getParent());
  animMusicFreq = (ImageView) v.findViewById(R.id.music_anim);
  animMusicFreq.setBackgroundResource(R.anim.anim_music);
  animMusicFreq.post(new Runnable() {

    @Override
    public void run() {
        AnimationDrawable frameAnimation =
            (AnimationDrawable) animMusicFreq.getBackground();
                    frameAnimation.start();
    }

});

A: You are inflating your view inside onCreateView, but you don't pass it to the system. Instead you tell it to inflate its own (you return super). It doesn't make any sense.
You should return your v view like so:
public View onCreateView(LayoutInflater inflater,
                         ViewGroup container,  Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragmentmusiclist, container, false);
    // ...
    return v;
}


Q: Silverlight Multithreading; Need to Synchronize? I have a Silverlight app where I've implemented the M-V-VM pattern so my actual UI elements (Views) are separated from the data (Models).  Anyways, at one point after the user has gone and done some selections and possible other input, I'd like to asyncronously go though the model and scan it and compile a list of optiions that the user has changed (different from the default), and eventually update that on the UI as a summary, but that would be a final step.
My question is that if I use a background worker to do this, up until I actually want to do the UI updates, I just want to read current values in one of my models, I don't have to synchronize access to the model right?  I'm not modifying data just reading current values...
There are Lists (ObservableCollections), so I will have to call methods of those collections like "_ABCCollection.GetSelectedItems()" but again I'm just reading, I'm not making changes. Since they are not primitives, will I have to synchronize access to them for just reads, or does that not matter?
I assume I'll have to sychronize my final step as it will cause PropertyChanged events to fire and eventually the Views will request the new data through the bindings...
Thanks in advance for any and all advice.

A: You are correct. You can read from your Model objects and ObservableCollections on a worker thread without having a cross-thread violation. Getting or setting the value of a property on a UI element (more specifically, an object that derives from DispatcherObject) must be done on the UI thread (more specifically, the thread on which the DispatcherObject subclass instance was created). For more info about this, see here.


Q: How to set the background color for specified row in datagridview? I want to set the background color for specified Row in datagridview ..
My need is i have a for loop (i=0;i<10;i++) .Inside this for loop i write the logic
as
if(i=1)
{
//Want to Set Color For This Specified Row..
dataGridView1.SelectedRows[1].DefaultCellStyle.SelectionBackColor = Color.Yellow;
}

if(i=1)
{
//Want to Set Color For This Specified Row..
dataGridView1.SelectedRows[2].DefaultCellStyle.SelectionBackColor = Color.Blue;
}

if(i=1)
{
//Want to Set Color For This Specified Row..
dataGridView1.SelectedRows[3].DefaultCellStyle.SelectionBackColor = Color.Red;
}

But i didn't get the expected o/p . I hope U understand My need . Please Help Me.

A: Instead of using SelectedRows property of the DataGridview you can use as follows
dataGridView1.Rows[1].DefaultCellStyle.ForeColor = Color.Red;

Because SelectedRows property will return rows when row(s) has been selected by the User only, if no rows are selected then your code will throw exception.
EDIT :
For your doubt here am providing a sample code, hope it will help you.
for (int i = 0; i < 10; i++)
 {
   if (dataGridView1.Rows.Count > i)
    {
      if (i == 1)
         dataGridView1.Rows[i].DefaultCellStyle.ForeColor = Color.Red;
      else if (i == 2)
         dataGridView1.Rows[i].DefaultCellStyle.ForeColor = Color.Blue;
      else
         dataGridView1.Rows[i].DefaultCellStyle.ForeColor = Color.Green;
     }
 }

A: You may handle different events of your datagrid and set cell style
Here is example from related question
private void dgvStatus_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.ColumnIndex != color.Index)
        return;

    e.CellStyle.BackColor = Color.Red;
}


Q: Spring Boot Mail send email using acces token I have simple mail sending functionality in project which configured in one bean.
@Bean
public JavaMailSender javaMailSender() {
    JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();

    Properties properties = new Properties();
    properties.setProperty("mail.smtp.auth", "false");
    properties.setProperty("mail.smtp.socketFactory.port", "465");
    properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    properties.setProperty("smtp.socketFactory.fallback", "false");
    properties.setProperty("mail.smtp.starttls.enable", "true");
    properties.setProperty("mail.smtp.starttls.required", "true");

    javaMailSender.setHost("smtp.gmail.com");
    javaMailSender.setProtocol("smtp");
    javaMailSender.setUsername("username");
    javaMailSender.setPassword("password");
    javaMailSender.setJavaMailProperties(properties);

    return javaMailSender;
}

and it works great.
Now I want to add functionality for sending emails via accessToken/refreshToken of specific email.
How to do it? What should I extend in my bean or add another bean for sending with token? I couldn't find some example which is full explained. As I understand I should add setFrom() and in setPassword() put accessToken

A: The use of OAUTH2 with JavaMail is explained on the JavaMail project page.
Also, you should fix these common mistakes in your code.


Q: Rxjs synchronous? I recently started working on a new project and I have seen this twice now, am I crazy or will never work under any circumstance?
protected get reportView(): any {
    let convertedView = null;
    this.store
      .pipe(select(fromStore.getTransferOrderConverted), rxjs.take(1))
      .subscribe((convertedOrder) => (convertedView = convertedOrder));
    return convertedView;
  }

A:
am I crazy or will never work under any circumstance?

Q) Are you crazy?
A) Yes. Absolutely. That looks bonkers!
Q) Will this never work under any circumstance?
A) Oh, there are times this will work. Some observables are synchronous.
For example, this will always log a 2, so this works as expected.
let convertedView = null;

of(1).pipe(
    map(v => v + 1)
).subscribe(convertedOrder => convertedView = convertedOrder);

console.log(convertedView);

That's because of(1) is a synchronous observable.

This, however, will never work
let convertedView = null;

of(1).pipe(
    delay(0),
    map(v => v + 1)
).subscribe(convertedOrder => convertedView = convertedOrder);

console.log(convertedView);

This will print null. Even though delay(0) conceptually takes no time, it still uses JSs event loop and therefore doesn't get executed until the current code completes.

I think it's best practise to assume all observables are asynchronous. Any code that assume otherwise is likely to be brittle.

A: Your store.subscribe is asynchronous and the rest of your code is not.
You can resolve it with a Promise like the example below.
protected get reportView(): Promise < any > {
    return new Promise((resolve, reject) => {
        this.store
            .pipe(select(fromStore.getTransferOrderConverted), rxjs.take(1))
            .subscribe((convertedOrder) => resolve(convertedOrder));
    });
}

reportView.then(convertedOrder => {
    // do your stuff
});

Also you can get the convertedOrder with Async/Await. But remember, the parent function must be async.
const convertedOrder = await reportView();

A: Convert a stream to synchronous isn't a good ideal.
However, you can use method toPromise of a subject (subscription) for convert it to a promise and await for resolve.

A: Rxjs take(1), first() operator should work absolutely fine
These 2 operators takes the latest value from store selector or BehaviourSubject in synchronous way.


Q: java.util.NoSuchElementException when run with Semaphore I have a Queue containing 10 elements, and I start 100 threads of which 6 may run concurrently, controlled by a Semaphore.  When each thread runs, it takes the head element then adds it to the tail.   But sometimes I get this exception:
java.util.NoSuchElementException
 at java.util.LinkedList.removeFirst(LinkedList.java:270)
 at java.util.LinkedList.remove(LinkedList.java:685)
 at IBM.SemApp$1.run(SemApp.java:27)
 at java.lang.Thread.run(Thread.java:745)

import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import java.util.concurrent.Semaphore;

public class SemApp {
public static void main(String[] args) {

    Queue queueB = new LinkedList<>();
    for (int i = 0; i < 10; i++) {
        queueB.add("Object " + i);
    }

    Runnable limitedCall = new Runnable() {
        final Random rand = new Random();
        final Semaphore available = new Semaphore(6);
        int count = 0;

        public void run() {
            int time = rand.nextInt(15);

            try {
                available.acquire();
                String A = (String) queueB.remove();
                queueB.add(A);
                available.release();
                count++;
                System.out.println(count);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };

    for (int i = 0; i < 100; i++) {
        new Thread(limitedCall).start();
    }
}
}

What am I doing wrong?

A: The problem is that LinkedList is not a thread-safe structure.
Therefore, it should not be shared and modified by multiple concurrent threads as the changes on queueB might not be properly "communicated" to other threads.
Try using a LinkedBlockingQueue instead.
Also, use an AtomicLong for count for the same reason: it is shared in between several threads and you want to avoid race conditions.

A: The fact that up to six threads may be operating on the queue concurrently means that modifications are not safe.


Q: How to pass context to AdMob InterstitialAd in LibGDX Does smb knows how to pass a context to InterstitialAd in LibGDX?
In Android it is simply
InterstitialAd interstitial = new InterstitialAd(this);

My class extended from Screen. or I can intialize it in class extended Game.. Or how to pass the context in this case?
And if smb knows any problem related to this, I'll be very thankfull to any advice!

A: To show ads from inside other classes not from the main activity you need to use a facade. Basically, you make use of a listener to load/display the ads.
Follow this libgdx official tutorial guide. It covers both banner and interstitial ads and it isn't outdated. It uses the new admob via the google play services


Q: What is the best variable scope I should use in servlet operation I am working on workflow management system.
Have one separate java class which contains logic method. One of this is:
public static in get_nxt_stg(int current_stg,int action)
{
}

and define static variable cur_stg and nxt_stg. used in servlet. call this method.
When multiple users log in and do some action these variables get not proper value. It seems like it is shared between all user requests.
What is best way to use variable in servlet, which is remain specific for that request?

A: You should not use static in such a way. If you need to share state, consider using the singleton pattern; but try to avoid static. Unwise use of "static" can turn into a nightmare (for example regarding unit testing).
In addition: it seems that you are a beginner with the Java language. But creating servlets is definitely a "advanced" java topic. I really recommend you to start learning more about Java as preparation for working on servlets. Otherwise the user of your server might have many unpleasant experiences ...

A: What you are doing is wrong. You should use Servlets only for the purpose of reading request parameters and sending responses. What you are trying to do, should be implemented in the Business layer of your application and if you have it implemented with EJBs, then your problem can easily be solved with an Stateful EJB.


Q: Load XML into mxml (Flex AS3) I am trying to display content of an xml file in a textarea (using Flex 4.7).
But I am getting errors and I am not sure why.
This is my code:
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
                       xmlns:s="library://ns.adobe.com/flex/spark"
                       xmlns:mx="library://ns.adobe.com/flex/mx">
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>
    <fx:Script>
        <![CDATA[

            var xmlLoader:URLLoader = new URLLoader();
            xmlLoader.addEventListener(Event.COMPLETE, loadXML); // 1st error here
            xmlLoader.load(new URLRequest("books.xml")); // 2nd error here

            var xmlData:XML = new XML();

            function loadXML(e:Event):void{
                xmlData = new XML (e.target.data);
            }
        ]]>
    </fx:Script>

    <s:VGroup>
        <s:TextArea id="txtArea">
        </s:TextArea>
    </s:VGroup>

</s:WindowedApplication>

Here are my errors:

Multiple markets at this line:
-1120: Access of undefined propertyloadXML (1st error)
-1120: Access of undefined property xmlLoader (2nd error)

This is the app structure:

Tester
- src
-- (default package)
--- Tester.mxml
-- books.xml
-- Tester-app.xml

I am not sure what I am doing wrong. Could anyone please get me on the right track?
Thank you!

A: Most of your ActionScript code must go inside a method; and you have code that must be put in a method.  Variable definitions are okay.  Import statements are okay.  I think some directives, such as include are okay. But, other code must be in a method.
This is your annotated code:
<fx:Script>
    <![CDATA[

        // this is a variable definition so it is good
        var xmlLoader:URLLoader = new URLLoader();

        // these two lines are code that executes; so they must be put inside a method; something you did not do.  Comment them out
        //xmlLoader.addEventListener(Event.COMPLETE, loadXML); // 1st error here
        //xmlLoader.load(new URLRequest("books.xml")); // 2nd error here

        // this is a variable definition so it is okay
        var xmlData:XML = new XML();

        // this is a function definition so it is okay
        function loadXML(e:Event):void{
            xmlData = new XML (e.target.data);
        }

        // move your executing code into a method
        public function load():void{
         xmlLoader.addEventListener(Event.COMPLETE, loadXML);
         xmlLoader.load(new URLRequest("books.xml"));
        }
    ]]>
</fx:Script>

I bet that removes your errors.  However, you'll also want to / need to do something to execute that load method.  When you do this depends on how the data is used in your app and the current component.  But, I'd probably add a preinitialize event listener:
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
                       xmlns:s="library://ns.adobe.com/flex/spark"
                       xmlns:mx="library://ns.adobe.com/flex/mx"
                       preinitialize="load()">

If preinitialize doesn't work; I'd move the code to the initialize event.  If that doesn't work; I'd go to the creationComplete event.


Q: Where is the tail position in my Clojure loop? Clojure is saying that I can't call recur from a non-tail-position.
Is this not the tail position?
What is the tail position in my loop then?
(loop [i 20]
    (for [x (range 1 21)]
      (if (zero? (rem i x))
        i
        (recur (+ i 1)))))

A: for does not do what you think it does; it is not an imperative loop. It is a list comprehension, or sequence-generator. Therefore, there is not a return or iterate call at its end, so you cannot place recur there.
It would seem you probably do not need either loop or recur in this expression at all; the for is all you need to build a sequence, but it's not clear to me exactly what sequence you wish to build.

A: Further to @JohnBaker's answer, any recur refers to the (nearest) enclosing loop or fn (which may be dressed as a letfn or a defn). There is no such thing in your snippet. So there is nothing for the recur to be in tail position to.
But just replace the for with loop, and you get
(loop [i 20]
  (loop [x 1]
    (if (zero? (rem i x))
      i
      (recur (+ i 1)))))

... which evaluates to 20,no doubt what you intended.
However, the outer loop is never recurred to, so might at well be a let:
(let [i 20]
  (loop [x 1]
    (if (zero? (rem i x))
      i
      (recur (+ i 1)))))

The recur is in tail position because there is nothing left to do in that control path through the loop form: the recur form is the returned value. Both arms of an if have their own tail position.
There are some other disguised ifs that have their own tail position: ors and ands are such.