text:
Q: HQL query returns different results comparing to same logic criteria query I need some HQL guru to help me with a complicated query. My mappings are AccountingDocument:
AccountingDocument extends Document

@ManyToOne
@JoinColumn(name = "gestiune_id", nullable = false)
private Gestiune gestiune;

@OneToMany(fetch = FetchType.LAZY, mappedBy = "accDoc", cascade = CascadeType.ALL)
private Set<Operatiune> operatiuni = new HashSet<>();

Document:
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Document

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@ManyToOne
@JoinColumn(name = "partner_id", nullable = true)
private Partner partner;

@Column(columnDefinition = "text")
private String name;

@Enumerated(EnumType.STRING)
@Column(nullable = false)
private TipDoc tipDoc;

@Column(precision = 16, scale = 2, nullable = true)
private BigDecimal total;

Operation:
@Entity
public class Operatiune

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@ManyToOne
@JoinColumn(name = "accounting_doc_id", nullable = false)
private AccountingDocument accDoc;

@Enumerated(EnumType.STRING)
@Column(nullable = false)
private TipOp tipOp;

@Column(nullable = false)
private String barcode; // taken from product
private String name; // taken from product
private String uom; // taken from product

@Column(precision = 12, scale = 2, nullable = false)
private BigDecimal valoareVanzareFaraTVA;

@Column(precision = 10, scale = 2, nullable = false)
private BigDecimal valoareVanzareTVA;

Partner:
@Entity
public class Partner
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@Column(nullable = false, unique = true)
private String name;

@OneToMany(fetch = FetchType.LAZY, mappedBy = "partner")
private List<Document> documents = new ArrayList<>();

Basically the Operation class is a sale operation and AccountingDocument class can be both a sale document(example: Invoice) or a cash document(example: Receipt).
For Invoices the AccountingDocument.total is null. In this case we add the total from all the operations.
Operation total=Operatiune.valoareVanzareFaraTVA+Operatiune.valoareVanzareTVA
For Receipts the operatiuni set is empty. In this case AccountingDocument.total is filled.
Requirement: Return all Partners(clients) which haven't fully paid us. totalCashed < totalSold => is not fully paid
I have created a CriteriaQuery+Java filtering for this but it is too slow so I am trying to convert it to HQL.
Expectation: CriteriaQuery+Java filtering returns same result as HQL.
Result: CriteriaQuery+Java filtering returns 29 partners while HQL returns 6 partners.
CriteriaQuery+Java filtering (note: 'incasat' means 'cashed'):
final ImmutableList<Partner> unpaidPartners = allUnpaidPartners(); // 29

public ImmutableList<Partner> allUnpaidPartners() {
    final CriteriaBuilder cb = em.getCriteriaBuilder();
    final CriteriaQuery<Partner> cq = cb.createQuery(Partner.class);
    final Root<Partner> rootEntry = cq.from(Partner.class);
    final CriteriaQuery<Partner> all = cq.select(rootEntry);
    final TypedQuery<Partner> allQuery = em.createQuery(all);
    final List<Partner> allPartners = allQuery.getResultList();

    return allPartners.stream()
            .filter(partner -> globalIsMatch(partner.getName(), Partner.L1_L2, TextFilterMethod.NOT_EQUALS))
            .filter(partner -> globalIsMatch(partner.getName(), Partner.OP_INTERNA, TextFilterMethod.NOT_EQUALS))
            .filter(partner -> globalIsMatch(partner.getName(), Partner.STAT_PLATA, TextFilterMethod.NOT_EQUALS))
            .filter(partner -> globalIsMatch(partner.getName(), Partner.MARFA, TextFilterMethod.NOT_EQUALS))
            .filter(partner -> globalIsMatch(partner.getName(), Partner.CARD_NAME, TextFilterMethod.NOT_EQUALS))
            .filter(partner -> globalIsMatch(partner.getName(), Partner.STANDARD_PARTNER_NAME, TextFilterMethod.NOT_EQUALS))
            .filter(VanzariBean::isNotPaid)
            .sorted(Comparator.comparing(Partner::getName))
            .collect(toImmutableList());
}

protected static boolean isNotPaid(final Partner partner)
{
    final Optional<BigDecimal> totalIncasat = partner.getDocuments().stream()
            .filter(AccountingDocument.class::isInstance)
            .filter(doc -> doc.getTipDoc().equals(TipDoc.INCASARE))
            .map(Document::getTotal)
            .collect(Collectors.reducing(BigDecimal::add));

    final Optional<BigDecimal> totalSold = partner.getDocuments().stream()
            .filter(AccountingDocument.class::isInstance)
            .filter(doc -> doc.getTipDoc().equals(TipDoc.VANZARE))
            .map(Document::getTotal)
            .collect(Collectors.reducing(BigDecimal::add));

    return totalIncasat.orElse(BigDecimal.ZERO).compareTo(totalSold.orElse(BigDecimal.ZERO)) < 0;
}

public BigDecimal Document.getTotal()
{
    return total;
}

@Override
public BigDecimal AccountingDocument.getTotal()
{
    final BigDecimal total = super.getTotal();

    if (total == null)
        return add(getVanzareTotalFaraTva(), getVanzareTotalTva());

    return total;
}

public BigDecimal AccountingDocument.getVanzareTotalFaraTva()
{
    return getOperatiuni().stream()
            .map(Operatiune::getValoareVanzareFaraTVA)
            .reduce(BigDecimal::add)
            .orElse(BigDecimal.ZERO);
}

public BigDecimal AccountingDocument.getVanzareTotalTva()
{
    return getOperatiuni().stream()
            .map(Operatiune::getValoareVanzareTVA)
            .reduce(BigDecimal::add)
            .orElse(BigDecimal.ZERO);
}

HQL('incasat'='cashed', 'vandut'='sold'):
final StringBuilder sb = new StringBuilder();
    sb.append("SELECT p FROM Partner p");
    sb.append(" LEFT JOIN AccountingDocument incasat WITH incasat.partner = p AND incasat.tipDoc = :qIncasatDoc");
    sb.append(" LEFT JOIN AccountingDocument vandut WITH vandut.partner = p AND vandut.tipDoc = :qVandutDoc");
    sb.append(" LEFT JOIN vandut.operatiuni opVandut");
    sb.append(" WHERE p.name != :qL1L2 AND p.name != :qOpInterna AND p.name != :qStatPlata AND p.name != :qMarfa AND p.name != :qCard AND p.name != :qStandard");
    // totalIncasat < totalSold => is not fully paid
    sb.append(" AND (select COALESCE(SUM(doc.total), 0) from AccountingDocument doc WHERE doc=incasat) < ")
        .append("(select COALESCE(SUM(op.valoareVanzareFaraTVA)+SUM(op.valoareVanzareTVA), 0) from Operatiune op WHERE op=opVandut)");
    sb.append(" GROUP BY p");

    final Query query = em.createQuery(sb.toString());
    query.setParameter("qL1L2", Partner.L1_L2);
    query.setParameter("qOpInterna", Partner.OP_INTERNA);
    query.setParameter("qStatPlata", Partner.STAT_PLATA);
    query.setParameter("qMarfa", Partner.MARFA);
    query.setParameter("qCard", Partner.CARD_NAME);
    query.setParameter("qStandard", Partner.STANDARD_PARTNER_NAME);

    query.setParameter("qIncasatDoc", TipDoc.INCASARE);
    query.setParameter("qVandutDoc", TipDoc.VANZARE);

    final List result = query.getResultList(); // 6 partners

A: Okay, so it seems the logic of the HQL was inherently wrong. It was actually checking if any cashed total of any AccDoc of that Partner is smaller than any sold total of AccDocs of that Partner, instead of actually comparing the cashed total and sold total of all AccDocs of each Partner.
So, because subqueries in the JOIN clause are not supported in HQL, I had to change to a native query. So the correct query is:
SELECT * FROM Partner p
    LEFT JOIN
    (
        SELECT doc.partner_id, SUM(doc.total) incasat
        FROM Document doc
        INNER JOIN AccountingDocument accDoc ON accDoc.id = doc.id
        WHERE doc.tipDoc = 'INCASARE'
        GROUP BY doc.partner_id
    ) i ON p.id = i.partner_id
    INNER JOIN
    (
        SELECT doc.partner_id, SUM(op.valoareVanzareFaraTVA)+SUM(op.valoareVanzareTVA) vandut
        FROM Document doc
        INNER JOIN AccountingDocument accDoc ON accDoc.id = doc.id
        INNER JOIN Operatiune op ON op.accounting_doc_id = accDoc.id
        WHERE doc.tipDoc = 'VANZARE'
        GROUP BY doc.partner_id
    ) v ON p.id = v.partner_id
    WHERE p.name != 'L1<->L2' AND p.name != 'OP INTERNA' AND p.name != 'STAT DE PLATA' AND p.name != 'MARFA' AND p.name != 'CARD INCASARE' AND p.name != 'STANDARD'
    AND COALESCE(i.incasat, 0) < COALESCE(v.vandut, 0)

And in Java this would be:
final StringBuilder sb = new StringBuilder();
    sb.append("SELECT * FROM Partner p").append(NEWLINE);
    sb.append(" LEFT JOIN ").append(NEWLINE)
        .append("(").append(NEWLINE)
        .append("SELECT doc.partner_id, SUM(doc.total) incasat ").append(NEWLINE)
        .append("FROM Document doc ").append(NEWLINE)
        .append("INNER JOIN AccountingDocument accDoc ON accDoc.id = doc.id ").append(NEWLINE)
        .append("WHERE doc.tipDoc = :qIncasatDoc ").append(NEWLINE)
        .append("GROUP BY doc.partner_id ").append(NEWLINE)
        .append(") i ON p.id = i.partner_id").append(NEWLINE);
    sb.append(" INNER JOIN ").append(NEWLINE)
        .append("(").append(NEWLINE)
        .append("SELECT doc.partner_id, SUM(op.valoareVanzareFaraTVA)+SUM(op.valoareVanzareTVA) vandut ").append(NEWLINE)
        .append("FROM Document doc ").append(NEWLINE)
        .append("INNER JOIN AccountingDocument accDoc ON accDoc.id = doc.id ").append(NEWLINE)
        .append("INNER JOIN Operatiune op ON op.accounting_doc_id = accDoc.id ").append(NEWLINE)
        .append("WHERE doc.tipDoc = :qVandutDoc ").append(NEWLINE)
        .append("GROUP BY doc.partner_id ").append(NEWLINE)
        .append(") v ON p.id = v.partner_id").append(NEWLINE);
    sb.append(" WHERE p.name != :qL1L2 AND p.name != :qOpInterna AND p.name != :qStatPlata AND p.name != :qMarfa AND p.name != :qCard AND p.name != :qStandard").append(NEWLINE);
    // totalIncasat < totalSold => is not fully paid
    sb.append(" AND COALESCE(i.incasat, 0) < COALESCE(v.vandut, 0)");

    final Query query = em.createNativeQuery(sb.toString(), Partner.class);
    query.setParameter("qL1L2", Partner.L1_L2);
    query.setParameter("qOpInterna", Partner.OP_INTERNA);
    query.setParameter("qStatPlata", Partner.STAT_PLATA);
    query.setParameter("qMarfa", Partner.MARFA);
    query.setParameter("qCard", Partner.CARD_NAME);
    query.setParameter("qStandard", Partner.STANDARD_PARTNER_NAME);

    query.setParameter("qIncasatDoc", TipDoc.INCASARE.toString());
    query.setParameter("qVandutDoc", TipDoc.VANZARE.toString());

Small tip here! em.createNativeQuery returns a non-generic query so if you want the result as a stream and you want to process that stream and cast the elements you need to do the following trick:
final Stream<?> resultStream = query.getResultStream();

and then you can process it:
resultStream
            .map(Partner.class::cast)
            .flatMap(Partner::getDocumentsStream)


text:
Q: Optimization Problem: Karush-Kuhn-Tucker Condition I am working on the question displayed below. I know that the method of Lagrange Multipliers is used to find the solution for optimization problems constrained to one or more equalities and when our constraints also have inequalities, we need to extend the method to the KKT conditions. But I don't know where to start.

A: Let $\mathcal{L}=x+y+\lambda(x^2-(2-y)^3) + \mu y$
Then the necessary conditions of KKT are:
$\frac{d \mathcal{L}}{dx}=1+2\lambda x=0$ and
$\frac{d \mathcal{L}}{dy}=1-3\lambda(2-y)^2 + \mu=0 $ and
$\lambda \geq 0, \ \mu \geq 0$ and
$\lambda(x^2-(2-y)^3)=0$ and
$\mu y=0$
Now you can consider several cases. For instance you can consider the case that $x^2-(2-y)^2=0$ but $y \neq 0$ (so that only one of the constraints holds with equality). This case is the most plausible, since if $y=0$ would hold, our solution would become quite trivial, so probably not correct (you can verify this by also considering that case later, but I won't do that).
You then have to solve the system of equations
$\begin{cases}
\mu=0\\
1+2\lambda x=0\\
1-3\lambda(2-y)^2=0\\
x^2-(2-y)^2=0
\end{cases}$
Can you take it from here?

redpajama_set_name: RedPajamaStackExchange


text:
Q: A simple hangman game on tkinter gui gets stuck from tkinter import*
import random
wlist ="monday friday sunday blue orange red brown ".split()
sword = random.choice(wlist)
def lets_begin():
    guess = ent.get()
    lb2["text"]= ent.get()
    ent.delete(0,5)
    guesses=""
    turns = 5
    while turns > 0:
        failed = 0
        for char in sword:
            if char in guesses:
                lb1["text"] = char
            else:
                lb1["text"] = "-"
                failed += 1
        if failed==0:
            lb1["text"]="you won"
            break
        guesses += guess
        if guess not in sword:
            turns -= 1
            lb2["text"]="you are wrong"
        if turns == 0:
            lb2["text"]="game is over.The answer was {0}".format(sword)
wn=Tk()
wn.geometry("400x300+10+10")
wn.config(bg="silver")
but1=Button(wn,text="playx",command=lets_begin)
but1.place(x=20,y=95)
ent=Entry(wn,width=12)
ent.place(x=10,y=70)
lb1=Label(bg="pink",width=10)
lb1.place(x=10,y=10)

lb2=Label(bg="yellow",width=28)
lb2.place(x=110,y=5)
lb2["text"]="Days of the week\n and some colors...."+sword
wn.mainloop()

I am trying to code a simple "hangman" game in Python using Tkinter GUI. it works on console IDE. I just wanted to modify and test it on TKINTER GUI, But I failed to make it run...I will be happy if you help me.
lb1["text"] doesn't print as many "-" as "the secret word" is supposed to have.
and it stucks every time I enter the correct character8((

A: I made version which use button only to check it once - without while loop which stops mainloop() and tkinter can't work correctly. After you put char in entry you have to press button, it checks this char (and other variables) and it ends work so mainloop() can run it again and it can wait when you press button next time.
I use global to keep values outside function so they will be not deleted between two executions.
I don't set sword and other values at start but in reset() so I can run it many times to set new sword before next game.
I add some spaces and empty lines to make code more readable.
import tkinter as tk
import random

wlist = "monday friday sunday blue orange red brown ".split()

def reset():
    '''reset values before first and next game'''
    global turns
    global guesses
    global sword

    turns = 5
    guesses = ""
    sword = random.choice(wlist)

def check():
    ''' check only once when button is pressed'''
    global turns
    global guesses
    global sword

    # get value from entry
    guess = ent.get()
    guesses += guess

    # check new char in sword to display '-'
    failed = 0
    lb1["text"] = ''

    for char in sword:
        if char in guesses:
            lb1["text"] += char
        else:
            lb1["text"] += "-"
            failed += 1

    # check result
    if failed == 0:
        lb1["text"] = "you won"
        # end of game - set variables before next game
        reset()
        # display after reset because it needs value in `sword`
        lb2["text"] = "Days of the week\n and some colors.... " + sword
    else:
        if guess not in sword:
            turns -= 1
            lb2["text"] = "you are wrong"
        else:
            lb2["text"] = "good choice"

        if turns == 0:
            lb2["text"] = "Game is over.\nThe answer was {0}".format(sword)
            # end of game - set variables before next game
            reset()
            # display after reset because it needs value in `sword`
            lb2["text"] = "Days of the week\n and some colors.... " + sword

    # clear entry before next char
    ent.delete(0,'end')

# --- main ---

wn = tk.Tk()
wn.geometry("400x300+10+10")
wn.config(bg="silver")

but1 = tk.Button(wn, text="Check char", command=check)
but1.place(x=20, y=95)

ent = tk.Entry(wn, width=12)
ent.place(x=10, y=70)

lb1 = tk.Label(bg="pink", width=10)
lb1.place(x=10, y=10)

lb2 = tk.Label(bg="yellow", width=28)
lb2.place(x=110, y=5)

# set variables before first game
reset()
# display after reset because it needs value in `sword`
lb2["text"] = "Days of the week\n and some colors.... " + sword

wn.mainloop()


text:
Q: Почему ACF поля не отображаются в редакторе постов/страниц? У меня есть последняя версия WordPress и плагина ACF(не Pro). Я создал группу полей и два поля. Но в редакторе их не существует. В чем дело?

A: В acf вы задали неправильное условие отображение. У вас:
Выводить если постайп равен странице и постайп равен посту - этого быть не может. Надо задать отношение или:
Выводить если постайп равен странице или постайп равен посту


text:
Q: Bounty started but not found While performing some janitorial cleanup on an answer (as it has been deleted and I think only 10K users can see it, here is the link to the question), I came through the following comment from an infuriated user:
You never promised an example. You said "figure it out yourself". Look at my rep points- I gave them away to a meaningless question out of frustration. – Anonymous yesterday
I found evidence (-300 rep points) in his rep history that he started a bounty on this question., but the bounty is not showing there, and I don't understand what is happening.
Help appreciated.

A: see
https://stackoverflow.com/posts/3120078/revisions

A: The user awarded the bounty to his own answer, as evidenced by the revision history of the question. To prevent gaming of the bounty system (because it gives these questions extra notice), self-awards are not given the bounty.


text:
Q: Why does my Fibonacci series using Ruby's inject doesn't work? This is embarrassing, I don't get why this line of code isn't returning to me the Fibonnacci series, but instead just a series of ones.
(1..5).inject([1]) { |arr, x| x > 1 ? arr << arr.last + arr.last-1 : arr << 1; arr }

The code above is supposed to find the 1st six numbers in the series.
Could you please tell me what am I doing wrong?
Thank you as always.

A: arr.last-1 doesnt work, try  arr[-2] instead:
p (1..5).inject([1]) { |arr, x| x > 1 ? arr << arr.last + arr[-2] : arr << 1 }
#=>[1, 1, 2, 3, 5, 8]

-edit-
btw you don't need that ;arr at the end, << returns the array by default

A: arr.last-1 doesn't give you the second-to-last element of the array. It takes the last element and just subtracts one from it.
You want something like arr[arr.length - 2] or the fancy Ruby shortcut arr[-2].

A: I don't know Ruby, so this may be completely off, but it seems like this might be your culprit:
arr.last + arr.last-1

I don't think that this means "the last array element plus the element before it," but rather
arr.last + (arr.last)-1

Note that if you seed the array with 1, this would give you back 1 + 1 - 1 = 1, which means that your terms always evaluate to one, which probably isn't what you want.
Let me know if this is totally off, and hope this helps!

A: First off let's not forget the series actually starts with 0 and there is a far easier way to do this:
1.9.2-p290 :009 > 4.times.inject([0,1]) {|s| s + [s[-1] + s[-2]]}
 => [0, 1, 1, 2, 3, 5]

Enjoy!

A: And yet another way in case you really like to use inject :)
(1..20).inject( [0, 1] ) { | fib | fib << fib.last(2).inject(:+) }
=> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946]

A: Shortest way:
(1..10).inject( [0, 1] ) { |sum| sum << sum.last(2).sum }
=> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]


text:
Q: PHP 5.2.12 - Interesting Switch Statement Bug With Integers and Strings <?php
$var = 0;
switch($var) {
   case "a":
      echo "I think var is a";
   break;
   case "b":
      echo "I think var is b";
   break;
   case "c":
      echo "I think var is c";
   break;
   default:
      echo "I know var is $var";
   break;
}
?>

Maybe someone else will find this fascinating and have an answer. If you run this, it outputs I think the var is a when clearly it's 0. Now, I'm most certain this has something to do with the fact that we're using strings in our switch statement but the variable we're checking is an integer. Does anyone know why PHP behaves this way? It's nothing too major, but it did give me a bit of a headache today.
Thanks folks!

A: If you compare an integer with a string, the string is converted to a number. So effectively your snippet is equivalent to:
$var = 0;
switch($var) {
   case 0: // "a" gets converted to 0.
      echo "I think var is a";
   break;
   case 0: // "b" gets converted to 0.
      echo "I think var is b";
   break;
   case 0: // "c" gets converted to 0.
      echo "I think var is c";
   break;
   default:
      echo "I know var is $var";
   break;
}

Which will produce I think var is a as output as the first case body gets executed. Even though there are 3 candidates, the first one is selected because it appears at the top.

A: In PHP, when you compare a string and an integer, whether it be in a switch statement or using the regular comparison operators, the string is converted to an integer (unless you're using the === operator).
And when converting a string to an integer, a string that doesn't start with either a digit or a sign is always converted to 0.
See the documentation here and here.


text:
Q: AWS service-role unauthorized, until opened in the console and saved I'm trying to set up a codeBuild project through the nodejs AWS-SDK. I'm able to create a new IAM role with policies attached, but when I use it in the .createProject() it gives me an error:
CodeBuild is not authorized to perform: sts:AssumeRole on arn:aws:iam::[account]:role/service-role/[role-name]
The weird thing is that, when I open the trusted relationships JSON of the role and save it (without any changes) it suddenly works.
the AssumeRole JSON file:
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "codebuild.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

I'm using a federated user. I don't know if that makes a difference (the process of requesting a regular account takes a few days, so I haven't tried that yet).
I tried to copy the before and after save to see what was going on, but when I store it in a file it has the exact same bytes. I'm really confused, I've been trying to fix this for almost half a day now.

A: I figured out what the problem was. Apparently, when you create a role and immediately start using it you'll get a "not authorized" error. But you also get this when the role doesn't even exist.
I added a manual wait of 10 seconds, not it works.
The SDK has a function for this called "waitfor", which can be used on roles and policies.


text:
Q: Let $S_n$ be A Sequence that Converges I am confused with these problems
Let $S_n$ be a sequence that converges
How do I:
a) Show that if $S_n \geq a$ for all but finitely many $n$, then $lim_{n\to\infty} S_n\geq a$
b) Show that if $S_n \leq b$ for all but finitely many $n$, then $lim_{n\to\infty} S_n\leq b$
c) Conclude that if all but finitely many $S_n$ belong to $[a,b]$, then $lim_{n\to\infty} S_n$ belongs to $[a,b]$

A: By contradiction, suppose that $\lim_{n\rightarrow \infty}S_{n}=S<a.$ Since $S_n \geq a$ for all but finitely many $n$, let $N_0$ the largest integer with this property. Since $S_n$ converges, then $\forall \, \epsilon >0, \exists \, N\in \mathbb{N}$ such that $n>N \Rightarrow |S_n - S|<\epsilon.$ Let $M=\max(N_0,N)$.Then $$\forall \, n>M \Rightarrow S_n \geq a \wedge |S_n - S|<\epsilon, $$
and let $\epsilon=a-S>0$ (since $S<a$). So you've $S_n - S<a-S$ then $S_n<a$ for all $n>M$. Which is a contradiction, because we already show that $S_n \geq a$ $\forall n >M.$ Thus $S\geq a.$


text:
Q: Why my caption package version is too old I am using MikTex 2.9.6942. After \usepackage{caption}, I tried to use the \captionsetup command. But it gives "Undefined control sequence" error. I searched online and most of people suggest that the caption package is outdated. I checked the package version in MiKTex Console, which looks like this:

I do not think the installed package is outdated. But when I check the output of LaTeX log, it looks like this
    (caption.sty
Package: caption 1995/04/05 v1.4b caption package (HS)

Package: caption v1.4b <1995/04/05> (Harald Sommerfeldt)
\captionmargin=\skip43
\as@captionbox=\box27
\as@captionwidth=\skip44
)
! Undefined control sequence.
<recently read> \captionsetup

l.6 \captionsetup
                 [table]{name=New Table Name}

It seems that it is using v1.4b by default. I then tried to include the package with \usepackage{caption}[2018/05/01], but then it gives warning
LaTeX Warning: You have requested, on input line 5, version
               `2018/05/01' of package caption,
               but only version
               `1995/04/05 v1.4b caption package (HS)'
               is available.

I do not know if it is an issue of the latest caption package as I did not see anything regarding this in the package gitLab issue section. Is there anyone else experiencing this error? Thank you for any suggestions.


text:
Q: Make centered text start from the same horizontal position as non-centered text I have a ul and h2 element. The container that both elements are in has padding-left: 4%.
I want the h2 and ul elements to both start from the same horizontal position so that they're directly below each other. The problem is that as the contents of the li elements are centered, the first element is not directly below the h2 - there's a gap:

If I add margin-left: -3% to the first li element, it pushes it to the left and removes the gap:

But they're not exactly aligned and I'd have to fiddle around with the margin to make it exact. Is there an alternative way to make them directly start from the same point?

#menu {
  background: #bb1919;
  padding: 0 4%;
}

#menu h1 {
  margin: 0;
  font-weight: normal;
  padding-top: 10px;
}

#menu ul {
  list-style-type: none;
  padding: 0;
  display: flex;
  align-items: center;
  margin: 0;
}

#menu li {
  display: inline-block;
  border-bottom: 4px solid transparent;
  cursor: pointer;
  text-align: center;
}

#menu li:first-of-type {
  /* margin-left: -2%; */
}

#menu li:hover {
  border-bottom: 4px solid #fff;
}

#menu li:first-of-type p {
  border-left: none;
}

#menu li p {
  border-left: 1px solid #d0d0d06b;
  padding: 0 14px;
  margin: 14px 0 8px 0;
}

NEWS

Home

Coronavirus

UK

World

Business

Politics

JsFiddle: https://jsfiddle.net/naq0mb48/

A: Use :first-of-type rules for li and the p inside li to set margin-left and padding-left to 0 and text-align to left.
ADDITION after comment:
You can add margin-left: -14px; text-indent: 14px; to the #menu li:first-of-type rule to achieve the desired underline left of the left-aligned first menu entry on hover.

#menu {
  background: #bb1919;
  padding: 0 4%;
}

#menu h1 {
  margin: 0;
  font-weight: normal;
  padding-top: 10px;
}

#menu ul {
  list-style-type: none;
  padding: 0;
  display: flex;
  align-items: center;
  margin: 0;
}

#menu li {
  display: inline-block;
  border-bottom: 4px solid transparent;
  cursor: pointer;
  text-align: center;
}
#menu li:hover {
  border-bottom: 4px solid #fff;
}

#menu li p {
  border-left: 1px solid #d0d0d06b;
  padding: 0 14px;
  margin: 14px 0 8px 0;
}

#menu li:first-of-type {
  text-align: left;
  padding-left: 0px;
  margin-left: -14px;
  text-indent: 14px;

}
#menu li:first-of-type p {
  border-left: none;
  padding-left: 0px;
}

NEWS

Home

Coronavirus

UK

World

Business

Politics


text:
Q: powershell command Join-Path
*

*Join-Path 'abc' 'deg' '*'   ---doesnt work

*Join-Path 'abc' 'deg' | Join-Path -ChildPath '*'   ---works

*Output required abc\deg\*

What to know whats the issue here for 1. ?

A: In PowerShell before version 7, Join-Path takes only 2 args, where 1st (-Path) can be array of strings that are left part of path, and 2nd (-ChildPath) is single string that is right part of path.
You can do this, but I think this is not what you expect to get
> Join-Path @('abc', 'deg') '*'
# abc\*
# deg\*

To achieve what you want, you can use native method Path.Combine which has overloads for 3, 4 and array of path parts. But I'd recommend avoid using it if you plan running on Windows 7 for more than 2 parts because those overloads were introduced in .net 4.0, and on .net 3.5 or lower this will fail.
# Variant1
$result = [System.IO.Path]::Combine('abc', 'deg', '*')

# Variant2
$parts = @('abc', 'deg', '*')
$result = [System.IO.Path]::Combine([string[]]$parts)

# Variant3 supported in .net before 4.0
$result = [System.IO.Path]::Combine('abc', [System.IO.Path]::Combine('deg', '*'))
# [System] is omitted, because it is loaded already
$result = [IO.Path]::Combine('abc', [IO.Path]::Combine('deg', '*'))

# Variant 4 ..meh...
$result = [String]::Join([IO.Path]::DirectorySeparatorChar, @('abc', 'deg', '*'))
$result = @('abc', 'deg', '*') -join [IO.Path]::DirectorySeparatorChar

In PowerShell version 7 and up, Join-Path has additional third argument -AdditionalChildPath and can take any number of args.
# Short version based on positional args
> Join-Path 'abc' 'deg' '*' 'sub'
# abc\deg\*\sub

# Long version based on named args
Join-Path -Path 'abc' -ChildPath 'deg' -AdditionalChildPath @('*', 'sub')
# abc\deg\*\sub

A: join-path only takes 2 arguments, unless you're in powershell 7.


text:
Q: @Autowire using singleton vs prototype Take a look at the following code:
@Controller
public class HomeController
{
    @Autowired
    private FacadeRemote fr;

// code omitted
}

|
@Component("user-details")
public class CustomUserServiceDetails implements UserDetailsService
{

    @Autowired
    private FacadeRemote fr;

    @Override
    public UserDetails loadUserByUsername(String email)
            throws UsernameNotFoundException
    {
        // omitted
    }

}

configuration:
<!-- JNDI Properties -->
    <util:properties id="jndiProps">
        <beans:prop key="java.naming.factory.initial">org.jboss.naming.remote.client.InitialContextFactory</beans:prop>
        <beans:prop key="java.naming.factory.url.pkgs">org.jboss.ejb.client.naming</beans:prop>
        <beans:prop key="java.naming.provider.url">remote://127.0.0.1:4447</beans:prop>
        <beans:prop key="java.naming.client.ejb.context">true</beans:prop>
        <beans:prop key="boss.naming.client.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT">false</beans:prop>
    </util:properties>

    <!-- EJB look up -->
    <jee:remote-slsb id="ns" jndi-name="Layer//myejb!com.uni.ag.FacadeRemote"
        environment-ref="jndiProps" resource-ref="false"
        business-interface="com.uni.ag.FacadeRemote"
        lookup-home-on-startup="true">
    </jee:remote-slsb>

In the following example how does @Autowire works:
Are the two classes using the same instance of FacadeRemote ?
In general how can I learn @Autowire behaviour in relation to thread-safety ?

A: There is almost no relation between @Autowired and thread-safety. The only responsibility of Spring IoC is to inject declared dependencies, taking into account their scope etc. It's your responsibility to make sure, that all beans will work correctly in multi-threaded applications. It means for example that for singleton beans all state that this bean holds should be synchronized.
Regarding your first question: there will be injected a proxy to FacadeRemote (to allow for example transations of checked exception RemoteException to an unchecked exception). According to the Spring Spec inside this proxy will be a cached instance of remote interface to FacadeRemote.


text:
Q: Eclipse-Marketplace Error Once i go to Eclipse Marketplace option i get this error message:
    MarketplaceDiscoveryStrategy failed with an error
    Unable to read repository at http://marketplace.eclipse.org/api/p?product=org.eclipse.epp.package.java.product&os=linux&runtime.version=3.6.0.v20100505&client=org.eclipse.epp.mpc.core&java.version=1.6.0_26&product.version=1.3.2.20110218-0812&        ws=gtk.
No route to host
This in my linux machine can i know why am i getting this message, i am not able to choose any new softwares from Marketplace

A: Please, add this line on eclipse ini, restart eclipse, open Marketplace and good installations: -Dorg.eclipse.epp.internal.mpc.core.service.DefaultCatalogService.url=https://marketplace.eclipse.org/catalogs/api/p
This problem is that link without ssl is not working.
For me that is working normal.

A: Try removing RelaventKnowledge software from your machine. Mine is Windows 10. I am not getting that error once i removed that software from the machine.


text:
Q: Include OpenSSL library from Brew in Xcode 8 project So I have this new iMac with macOS Sierra 10.12.5. I installed Xcode 8 and brew. Then I installed openSSL via brew:
brew install openssl
brew link --force openssl

But --force no longer works. Apparently I need to set some flags according to brew info openssl
For compilers to find this software you may need to set:
LDFLAGS:  -L/usr/local/opt/openssl/lib
CPPFLAGS: -I/usr/local/opt/openssl/include

So the question is where do I put these flags in Xcode ?

A: In fact,by setting
xcode->targets->build settings->other linker flags

to
-L/usr/local/opt/openssl/lib

and setting
xcode->targets->build settings->

header search path to
/usr/local/opt/openssl/include

the xcode will work for you successfully.
for my setting.
Header search path:

Other linker flags:


text:
Q: Error; Cross-Domain iframe failing when it attempts to access property of element in parent window I have a a link on click of which I open a div as a pop up. While opening the content, I first load a page from similar domain into an iFrame in that div.
On the basis of some conditions, that page further redirects to an another cross domain page. Now there are some dynamic properties being used in that page which are trying to access the property of the parent window but due to some Cross Domain rules, we get the JavaScript error :- "Error: Permission denied to access property 'ug'".
It is trying to access this property through window.parent.ug and here the parent element is my page.
Is there any work around for this like either we can inject some JavaScript function into our iFrame to handle this or something else.

A: a cross-domain request will produce an error, I don't think any browser will allow this in the 21st century. . What that page is trying to do is load an attribute 'ug' from one of the elements in it's parent window. . .what that attribute is? you'll have to figure that out yourself, unless there's a tutorial that you were referencing while doing what you were doing, then I suggest you refer to it and go over the details once more, because you're obviously missing something.
you cannot change the contents of an iframe from the parent window for security reasons, modern browsers will not allow this. hackers would use such functionality to exploit users.
from what the error says, something like this is happenning in that iframe;
var parentWindowTextElementsUGProperty = window.parent.getElementById('#myInputTextElement').ug;


text:
Q: I have two questions about relating events to functions What does the following expression mean?

variable.DOMevent = function

Why does it not fire up handler1 and only fires up handler2?

var a = document.querySelector("a");

var container1 = a;
container1.onmouseover = container1.onmouseout = handler1;

var container2 = a;
container2.onmouseover = container2.onmouseout = handler2;

function handler1 (event) {
   console.log('handler1: '+event.type);
}

function handler2 (event) {
   console.log('handler2: '+event.type);
}
a {
  cursor: pointer;
}

  hover me

A: You are overwriting the onmouseover of the element. Both container1 and container2 are still pointing to the same anchor element. Assigning to different variables won't make any difference.
To fix this, you could create a new superHandler function which will call the other handler functions inside it.

function handler1(event) {
  console.log('handler1: ' + event.type);
}

function handler2(event) {
  console.log('handler2: ' + event.type);
}

function superHandler(e) {
  handler1(e)
  handler2(e)
}

const a = document.querySelector("a");

a.onmouseover = a.onmouseout = superHandler;
a {
  cursor: pointer;
}

  hover me

A: container1 and container2 refers to the same object, so you are just overwriting the callback for the event listener.
If for example you target two different elements, you will be able to see both the callbacks

var a = document.querySelector("a");
var b = document.querySelector("span");

var container1 = a;
container1.onmouseover = container1.onmouseout = handler1;

var container2 = b;
container2.onmouseover = container2.onmouseout = handler2;

function handler1 (event) {
   console.log('handler1: '+event.type);
}

function handler2 (event) {
   console.log('handler2: '+event.type);
}
a {
  cursor: pointer;
}

  hover me 1
  hover me 2


text:
Q: Intersection of two rectangles with NumPy I have the following function to find the intersection of two rectangles. It's a little bit slow, I don't know if it's due to the OR condition or the >, < operators. I wonder if there's a way to improve the performance of the is_intersect() function. Maybe with NumPy? Or Cython?
import numpy as np

def is_intersect(rect1, rect2):
    xmin1, xmax1, ymin1, ymax1 = rect1
    xmin2, xmax2, ymin2, ymax2 = rect2
    if xmin1 > xmax2 or xmax1 < xmin2:
        return False
    if ymin1 > ymax2 or ymax1 < ymax2:
        return False
    return True

N_ELEMS = 100000000
rects1 = np.random.rand(N_ELEMS,4)
rects2 = np.random.rand(N_ELEMS,4)

temp_dct = dict()

for i in range(N_ELEMS):
    rect1 = rects1[i,:]
    rect2 = rects2[i,:]
    if is_intersect(rect1, rect2):
        temp_dct[i] = True

I can't profit from caching results as the points will be incremental, that is, one rectangle will move in space (never the same place). In this example, I used NumPy's random() function, but that's not the case for my real use. I will call the is_intersect() function 100 000 000 times or more.

A: You can improve performance by avoiding the for loop using vectorized comparison and np.any:
result = (1 - np.any([rects1[:,0] > rects2[:,1],
                      rects1[:,1] < rects2[:,0],
                      rects1[:,2] > rects2[:,3],
                      rects1[:,3] < rects2[:,2]],
                     axis=0)).astype(bool)

You don't get a dictionary, yet you can access result by index.
Performance with 100M elements:
import numpy as np
import timeit

N_ELEMS = 100_000_000
rects1 = np.random.rand(N_ELEMS,4)
rects2 = np.random.rand(N_ELEMS,4)

start_time = timeit.default_timer()
result = (1 - np.any([rects1[:,0] > rects2[:,1],
                      rects1[:,1] < rects2[:,0],
                      rects1[:,2] > rects2[:,3],
                      rects1[:,3] < rects2[:,2]],
                     axis=0)).astype(bool)

print(timeit.default_timer() - start_time)
2.9162093999999996


text:
Q: Keeping track of source code variants I am soon starting to maintain a line of products containing variants of the same embedded software. Since I've been playing with git for one year and appreciate it very much, I'm likely to use it for source control.
There are several options I can see for maintaining the variants of the firmware, but none pleases me too much. What are the best practices you apply for your own work?
Alternatives I can think of:

*

*defines. Pre-processing.
Pros: everything is always present in the source code, it is harder to miss the update of one of the products.
Cons: harder to read. It might be ok while we have only two variants, when it becomes four or more it will be a pain. Also, it seems harder to apply the DRY principle (Don't Repeat Yourself).

*one branch per product variant.
When changes that apply to all products are included, the change must be merged to the other products.
Cons: if a commit contains both changes for all products and changes for the specific variant, there will be trouble. Of course, you can make sure that a commit contains only one kind of change: this-product-changes, or the-whole-family-changes. But try to force that on a team?? Plus then merging wouldn't work, we should be cherry-picking instead. Right?

*a core repository as a submodule.
Make all files that contain core functionality a repository on its own.
All products contain a version of the core repository as a sub-module.
Cons: I can't see that there wouldn't eventually be variants of the core submodule. Then we're in trouble again, and then we'd use defines or something bad again.
A core repository with branches? Then we're back to the previous alternative: a change that applies to all branches must be merged but merging includes also the product specific stuff.

*create a repository per module.
For example a repository for a display driver, another one for the power management hardware, yet another for the user input interface, ...
Pros: good modularity. Make a new product by just picking up the modules you need as submodules! All submodules might have branches, if for example a variant uses the hardware in a different way.
Cons: Lots and lots of modules, each keeping track of a couple of files (an include file and a source file). A hassle.
Someone makes an important update in some module? Then someone needs to include the change in the other branches of this module, if appropriate. Then someone must also update the submodule in every product repository.
Quite some work, and we kindof lose the snapshot side of git.
How do you do it, and how has it been working? Or how would you do it?
I have a feeling that I should get experienced with cherry picking.

A: You should strive to, as much as possible, keep each variant's custom code in its own set of files. Then your build system (Makefile or whatever) selects which sources to use based on which variant you are building.
The advantage to this is that when working on a particular variant, you see all of its code together, without other variants' code in there to confuse things. Readability is also much better than littering the source with #ifdef, #elif, #endif, etc.
Branches work best when you know that in the future you will want to merge all of the code from the branch into the master branch (or other branches). It doesn't work as well for only merging some changes from branch to branch (although it can certainly be done). So keeping separate branches for each variant will probably not yield good results.
If you use the aforementioned approach, you don't need to try to use such tricks in your version control to support your code's organization.

A: I'd try to go for #defines as much as possible. With a proper code you can minimize the impact on readability and repetitions.
But at the same time #define approach can safely be combined with splitting and branching, application of which depends on the nature of the codebase.

A: I am not sure if that's "best practice", but the Scintilla project uses something for years that is still quite manageable. It has only one branch common to all platforms (mostly Windows/GTK+/Mac, but with variants for VMS, Fox, etc.).
Somehow, it uses the first option which is quite common: it uses defines to manage little platform specific portions inside the sources, where it is impractical or impossible to put common code.
Note that this option is not possible with some languages (eg. Java).
But the main mechanism for portability is using OO: it abstracts some operations (drawing, showing context menu, etc.) and uses a Platform file (or several) per target, providing the concrete implementation.
The makefile compiles only the proper file(s) and uses linking to get the proper code.

A: I think that the appropriate answer depends in part on how radically different the variants are.
If there are small portions that are different, using conditional compilation on a single source file is reasonable.  If the variant implementations are only consistent at the call interface, then it may be better to use separate files.  You can include radically variant implementations in a single file with conditional compilation; how messy that is depends on the volume of variant code.  If it is, say, four variants of about 100 lines each, maybe one file is OK.  If it is four variants of 100, 300, 500 and 900 lines, then one file is probably a bad idea.
You don't necessarily need the variants on separate branches; indeed, you should only use branches when necessary (but do use them when they are necessary!).  You can have the four files, say, all on a common branch, always visible.  You can arrange for the compilation to pick up the correct variant.  One possibility (there are many others) is compiling a single source file that knows which source variant to include given the current compilation environment:
#include "config.h"
#if defined(USE_VARIANT_A)
#include "variant_a.c"
#elif defined(USE_VARIANT_B)
#include "variant_b.c"
#else
#include "basecase.c"
#endif

A: You are in for a world of hurt!
Whatever you do, you need an automatic build environment.  At the very least you need some automatic way of building all the different versions of your firmware.  I've had issues of fixing a bug in one version and breaking the build of a different version.
Ideally you would be able to load the different targets and run some smoke tests.
If you go the #define route, I would put the following someplace where the variant is checked:
#else
    #error You MUST specify a variant!
#endif

This will make sure all the files are built for the same variant during the build process.

A: I'm facing the same issue.   I want to share source not just among targets, but across platforms (e.g Mono vs. Visual studio.   It seems like there isn't any wway to easily do that with just the version the branching/tagging provide by Git.   Because ideally, you'd like to maintain a common code branch, and host/target specific branches and just merge the common code in and out of those branches.
But I don't know how to do that.   Maybe a combination of branching and tagging?  Anybody?
Obviously, I would use condition compilation if it was needed where I could, so that there would only be one source file under version control, but for the other stuff files that should only appear in one host/target branch, or where the contents would be completely different, a different mechanism is needed.   If you can use OO techniques to side step the problem that too would be desirable.
So the answer seems to be you need some sort of configuration/build management mechanism on top
of git to manage this.   But that would seem to add a lot of complexity, so maybe cherry picking
merges into a common branch wouldn't be a bad way to go.  Especially if you use other techniques to keep the source variants to a minimum.   (Could tagging help automate this?).


text:
Q: Problems on the sequence of tenses I feel really confused with the sequence of tenses sometimes. I am trying to explain where my problem is. Suppose, I have three different sentences which I want to express in two sentences.
1) I played cricket on Sunday.
2) I watched a movie before playing cricket.
3)I met my cousin on Sunday morning.
After joing first two sentences, we get :
"I had watched a movie before playing cricket on Sunday. "
Now for the third sentence which I want to join in the second line, which tense should I use?
Will it be past perfect again as it happend before another action?
"I had watched a movie before playing cricket on Sunday. I had met my cousin on Sunday morning. "
Even after 5 or 6 sentences if I want to say something which happend even beofre Sunday,  which tense should I use?
Could someone please explain how I can solve my problem?

A:
After joining the first two sentences, we get : "I had watched a movie before playing cricket on Sunday. "

As general guidance, we only get this in written narrative. The past perfect is used mainly in written narrative, in a slightly formal manner, in order to set the scene and/or give the context to an event that will be recounted in the simple past. (In your example, this is "playing cricket.")
In spoken narrative, e.g. talking to a friend, the simple past is enough, and thus you will have "I watched a movie before playing cricket on Sunday."

Now for the third sentence, which I want to join in the second line, which tense should I use?

In written narrative it will be
"I had met my cousin on Sunday morning and we had watched a movie, we then played cricket."
In conversation, it would be
"I met my cousin on Sunday morning, we watched a movie and then we played cricket."


text:
Q: Hoare Logic Loop variant on user specified value I have the following problem:
pre-condition is True
int n = askUser();
int i = 0;
while(i<n){
  ...
  i++;
}

The variant I am thinking of is: n-i.
However, I don't think there is anything that stops the user from supplying a negative value, and in that case the variant will be negative (which contradicts its definition).
Is it possible to specify the invariant as |n| - i, or does n>=0 has to be included as pre-condition?
Any help or suggestions will be greatly appreciated.


text:
Q: ASP.NET MVC2 in the web farm - slow page load with high traffic We have a web application written in MVC2 + Linq2SQL + MS SQL SERVER 2008 hosted on the web farm. Almost like stackoverflow.com
We have 4 x IIS7  + 1 SQL SERVER 2008 load balanced with MS NLB
Static content is cached by external cache provider - Akamai, which reduces 86% of the requests.
Each web server has 32 GB of RAM and  4 x quad core CPUs so there are 64 cores on the front-end.
We save a session state in tables.
It works prefectly with medium traffic (page load = 0.2 s) but the company does the tv ads and during those ads the traffic hits up to 20,000 users within 20-30 seconds.
In this moment the page slows down to 8 - 10 seconds. However, the usage of CPU's and the memory doesn't even arrive to 40% on any machine.
The bandwidth of the data centre does not arrive to the half of its limits.
Pages which are slow generate data from simple SELECTs of maximum 10 records from 1-2 tables only.
Clearly there is a bottleneck somewhere and trying to figure out where.
Anyone has any advice for me where to look for a problem?

A: I found the problem sometime ago but didn't have a time to post it here. I have tried almost every possible thing I could think of: indexes, optimizing sql, monitoring disk i/o, revising the code. Nothing of the above solved my problem. I run the web stress test from 2 workstations on our lan and I could freeze the whole page in seconds! While running tests I have noticed something odd. I created a separate controller for testing and I put 2 methods. Both doing the same thing: asking for the same data our database server.
Action A)
public ActionResult Index(){
var model = new SomeModel();
// Get data
....
return View(model);
}

Action B)
public ActionResult Index() {
 var model = new SomeModel();
// Get data
....
return View("Index",model);
}

The difference in page load:
A) ~ 297 ms
B) ~ 39.47 s
This occurs only during the high concurrency, otherwise is fine.
Seems like the search of default View in MVC2 library is causing the problem as once it is specified it all works great.
I have described it on my blog:
http://arturito.net/2011/10/24/asp-net-mvc2-in-the-web-farm-slow-page-load-with-high-traffic-where-is-the-bottleneck/
I have posted it in Issue Tracker of asp.net on codeplex but nobody has commented/responded to it yet.
http://aspnet.codeplex.com/workitem/9396

A: For some smaller performance benefits, you may try some of the tweaks Rico Mariani mentions at http://blogs.msdn.com/b/ricom/archive/2007/06/22/dlinq-linq-to-sql-performance-part-1.aspx. Specifically try using CompiledQuery and turning off change tracking for display only objects.


text:
Q: Arguments are not sufficiently instantiated while trying to get combinations I'm learning Prolog and I want to build a recipe recommendation based on calories. So base on how many calories you put as input, I want to return the combinations of a breakfast, a lunch, and a dinner.
The breakfast, the dinner, and the lunch are composed differently, so in this case, the breakfast is composed of a drink and a dish, and the dish itself is composed of cereal, a fruit or a vegetable, and an animal origin food.
Right now, I'm trying to get all the possible breakfast I have the following Prolog code
dish([Cereal, FruitOrVegetable, AnimalOrigin], Calories) :-
  cereal(Cereal, CerealCalories),
  (
      fruit(FruitOrVegetable, FruitOrVegetableCalories);
      vegetable(FruitOrVegetable, FruitOrVegetableCalories)
  ),
  animalOrigin(AnimalOrigin, AnimalOriginCalories),
  Calories >= CerealCalories + FruitOrVegetableCalories + AnimalOriginCalories.

breakfast([Drink, Dish], Calories) :-
  drink(Drink, DrinkCalories),
  dish(Dish, DishCalories),
  Calories >= DrinkCalories + DishCalories.

If I execute the dish function, just with 600 calories it works, it returns the combination of the given food, but when I tried to implement the same logic to compose the breakfast function it throws me the following error
Arguments are not sufficiently instantiated

And I search for a while, and I found that it because of a var that is inst initialized but I didn't found the origin of the problem.
An example of the declaration of the knowledge data base is
cereal(flakes, 386).
fruit(apple, 52).
vegetable(broccoli, 31).
animalOrigin(chicken_breast, 134).
drink(water, 0).

where the first is the name of the food, and the second the calories

A: The problem is that you call
dish(Dish, DishCalories)

from breakfast/2, but DishCalories is at that point an uninstantiated variable.
So when the Prolog Processor hits
Calories >= CerealCalories + FruitOrVegetableCalories + AnimalOriginCalories.

the variable Calories, which is the same as the earlier DishCalories, will be uninstantiated. There is nothing to compare!
You can either:

*

*Compute the calorific sum in dish/2 and "pass it back out" so that a complete
sum of drink + disk can be computed breakfast/2 and then compare against Calories as you would in other programming languages; or

*USe constraint logic programming which doesn't need to "compute immediately" and internally constructs datastructures corresponding to partially-filled in expressions which can be evaluated "later" (and possibly failed) when more is known:

:- use_module(library(clpfd)).

dish([Cereal, FruitOrVegetable, AnimalOrigin], Calories) :-
  cereal(Cereal, CerealCalories),
  (
      fruit(FruitOrVegetable, FruitOrVegetableCalories);
      vegetable(FruitOrVegetable, FruitOrVegetableCalories)
  ),
  animalOrigin(AnimalOrigin, AnimalOriginCalories),
  %
  % Compare if we know enough, otherwise delay the decision on >=
  % and proceed optimistically
  %
  Calories #>=
     CerealCalories +
     FruitOrVegetableCalories +
     AnimalOriginCalories.

breakfast([Drink, Dish], Calories) :-
  drink(Drink, DrinkCalories),
  dish(Dish, DishCalories),
  format("Calories: ~q, DrinkCalories: ~q, DishCalories: ~q~n",
          [Calories,DrinkCalories,DishCalories]),
  Calories #>= DrinkCalories + DishCalories.

And so:
As usual:
?- dish(List,600).
List = [flakes, apple, chicken_breast] ;
List = [flakes, broccoli, chicken_breast].

But this works too, now:
?- breakfast(List,600).
Calories: 600, DrinkCalories: 0, DishCalories: _21370
List = [water, [flakes, apple, chicken_breast]] ;
Calories: 600, DrinkCalories: 0, DishCalories: _22506
List = [water, [flakes, broccoli, chicken_breast]].

If you don't even specify the Calories:
Calories is a number larger than 572:
?- breakfast(List,Calories).
Calories: _23482, DrinkCalories: 0, DishCalories: _23990
List = [water, [flakes, apple, chicken_breast]],
_25276 in 572..sup,
Calories#>=_25276,
Calories in 572..sup ;

or Calories is a number larger than 551:
Calories: _23482, DrinkCalories: 0, DishCalories: _26724
List = [water, [flakes, broccoli, chicken_breast]],
_28010 in 551..sup,
Calories#>=_28010,
Calories in 551..sup.


text:
Q: Why does SSL handshaking sometimes kill my CPU? We are running in to a very strange problem: we're using a modified version of the Selenium HTTP proxy (more akin to the BrowserMob Proxy) and finding that in some circumstances, which we can't reliably reproduce, CPU grinds to a halt when handling SSL connections.
A stack dump reveals that that the thread gets either stuck here:
"ProxyHandler$SslRelay3-1" prio=10 tid=0x09f9a400 nid=0x81f runnable [0xb2e69000]
   java.lang.Thread.State: RUNNABLE
    at java.math.BigInteger.multiply(BigInteger.java:1144)
    at java.math.BigInteger.lucasLehmerSequence(BigInteger.java:820)
    at java.math.BigInteger.passesLucasLehmer(BigInteger.java:750)
    at java.math.BigInteger.primeToCertainty(BigInteger.java:730)
    at java.math.BitSieve.retrieve(BitSieve.java:188)
    at java.math.BigInteger.largePrime(BigInteger.java:606)
    at java.math.BigInteger.<init>(BigInteger.java:511)
    at org.bouncycastle.crypto.generators.DHParametersHelper.generateSafePrimes(Unknown Source)
    at org.bouncycastle.crypto.generators.DHParametersGenerator.generateParameters(Unknown Source)
    at org.bouncycastle.jcajce.provider.asymmetric.dh.KeyPairGeneratorSpi.generateKeyPair(Unknown Source)
    at com.sun.net.ssl.internal.ssl.DHCrypt.<init>(DHCrypt.java:76)
    at com.sun.net.ssl.internal.ssl.ServerHandshaker.setupEphemeralDHKeys(ServerHandshaker.java:797)
    at com.sun.net.ssl.internal.ssl.ServerHandshaker.trySetCipherSuite(ServerHandshaker.java:702)
    at com.sun.net.ssl.internal.ssl.ServerHandshaker.chooseCipherSuite(ServerHandshaker.java:633)
    at com.sun.net.ssl.internal.ssl.ServerHandshaker.clientHello(ServerHandshaker.java:425)
    at com.sun.net.ssl.internal.ssl.ServerHandshaker.processMessage(ServerHandshaker.java:139)
    at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:516)
    at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:454)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:884)
    - locked <0x8a18f238> (a com.sun.net.ssl.internal.ssl.SSLSocketImpl)
    - locked <0x8a18f2c0> (a java.lang.Object)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1112)
    - locked <0x8a18f2c8> (a java.lang.Object)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:744)
    at com.sun.net.ssl.internal.ssl.AppInputStream.read(AppInputStream.java:75)
    - locked <0x8a18f300> (a com.sun.net.ssl.internal.ssl.AppInputStream)
    at org.openqa.jetty.util.LineInput.fill(LineInput.java:477)
    at org.openqa.jetty.util.LineInput.fillLine(LineInput.java:555)
    at org.openqa.jetty.util.LineInput.readLineBuffer(LineInput.java:301)
    at org.openqa.jetty.util.LineInput.readLineBuffer(LineInput.java:285)
    at org.openqa.jetty.http.HttpRequest.readHeader(HttpRequest.java:239)
    at org.openqa.jetty.http.HttpConnection.readRequest(HttpConnection.java:866)
    at org.openqa.jetty.http.HttpConnection.handleNext(HttpConnection.java:912)
    at org.openqa.jetty.http.HttpConnection.handle(HttpConnection.java:837)
    at org.openqa.jetty.http.SocketListener.handleConnection(SocketListener.java:243)
    at org.openqa.jetty.util.ThreadedServer.handle(ThreadedServer.java:357)
    at org.openqa.jetty.util.ThreadPool$PoolThread.run(ThreadPool.java:534)

Multiple stack dumps reveal that generateSafePrimes() is continually running and each subsequent stack dump shows slightly different places in java.math.BigInteger that is running. However, it's hard to tell where exactly things are getting stuck or if there is a legit infinite loop (I doubt it though).
Investigating further, I was able to capture the relevant output with -Djavax.net.debug=ssl set, for both a working example and a broken example.
When things work, the handshaking happens almost instantly and we see this debug output, resulting in a proper Diffie-Hellman key exchange:
ProxyHandler$SslRelay3-9, setSoTimeout(10000) called
ProxyHandler$SslRelay3-9, READ: TLSv1 Handshake, length = 171
*** ClientHello, TLSv1
RandomCookie:  GMT: 1320359479 bytes = { 176, 253, 143, 106, 114, 151, 90, 1, 9, 53, 221, 254, 160, 42, 176, 239, 1, 222, 180, 41, 56, 115, 203, 185, 74, 68, 2, 27 }
Session ID:  {}
Cipher Suites: [Unknown 0x0:0xff, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, Unknown 0x0:0x88, Unknown 0x0:0x87, TLS_DHE_RSA_WITH_AES_256_CBC_SHA, TLS_DHE_DSS_WITH_AES_256_CBC_SHA, TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, Unknown 0x0:0x84, TLS_RSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, Unknown 0x0:0x45, Unknown 0x0:0x44, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, TLS_ECDH_RSA_WITH_RC4_128_SHA, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS_ECDH_ECDSA_WITH_RC4_128_SHA, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, Unknown 0x0:0x96, Unknown 0x0:0x41, SSL_RSA_WITH_RC4_128_MD5, SSL_RSA_WITH_RC4_128_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA]
Compression Methods:  { 0 }
Unsupported extension server_name, [host_name: REDACTED]
Extension elliptic_curves, curve names: {secp256r1, secp384r1, secp521r1}
Extension ec_point_formats, formats: [uncompressed]
Unsupported extension type_35, data:
***
%% Created:  [Session-10, TLS_DHE_RSA_WITH_AES_128_CBC_SHA]
*** ServerHello, TLSv1
RandomCookie:  GMT: 1320359480 bytes = { 85, 189, 191, 119, 135, 205, 134, 161, 254, 164, 83, 102, 9, 149, 182, 59, 83, 201, 110, 233, 114, 168, 166, 192, 80, 250, 204, 121 }
Session ID:  {79, 179, 22, 56, 209, 63, 115, 246, 134, 192, 16, 222, 203, 184, 204, 251, 145, 49, 200, 163, 218, 68, 78, 13, 96, 106, 79, 11, 93, 61, 187, 48}
Cipher Suite: TLS_DHE_RSA_WITH_AES_128_CBC_SHA
Compression Method: 0
***
Cipher suite:  TLS_DHE_RSA_WITH_AES_128_CBC_SHA
*** Certificate chain
chain [0] = [
[
  Version: V3
  Subject: CN=REDACTED, OU=Test, O=CyberVillainsCA, L=Seattle, ST=Washington, C=US
  Signature Algorithm: SHA1withRSA, OID = 1.2.840.113549.1.1.5

  Key:  RSA Public Key
            modulus: 9fff00e7f363191e3d3dc0aa85a2791776ecab2d8365ab4026a5e051ff60b6ce11e484a6279f5e123559dfa44479797c7b04a97d1bcfa0e10479d616deeb48cd5c40890041786106a4e88b365585113b107a80be9b3bdf19672a3ffb40a7fac583cae69d262bad1a74ce888f84643733affdbd4f939178eb060f3a32a34345d7
    public exponent: 10001

  Validity: [From: Sun May 22 02:45:42 UTC 2011,
               To: Thu Apr 20 02:45:42 UTC 2017]
  Issuer: C=US, OU=CyberVillians Certification Authority, O=CyberVillians.com
  SerialNumber: [    01375389 64a8]

Certificate Extensions: 5
[1]: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: D1 6A D0 8E B2 7E B4 90   C3 7C 30 D1 5B F2 70 71  .j........0.[.pq
0010: 94 B4 3F A8                                        ..?.
]
]

[2]: ObjectId: 2.5.29.35 Criticality=false
AuthorityKeyIdentifier [
KeyIdentifier [
0000: 0A BC 17 95 34 6B BC 87   1B 5B 4C FD F5 63 85 2D  ....4k...[L..c.-
0010: B4 8F F5 6C                                        ...l
]

]

[3]: ObjectId: 2.5.29.31 Criticality=false
CRLDistributionPoints [
  [DistributionPoint:
     [URIName: http://127.0.0.1:4444/selenium-server/sslSupport/blank_crl.pem]
]]

[4]: ObjectId: 2.5.29.37 Criticality=false
ExtendedKeyUsages [
  serverAuth
  clientAuth
  2.16.840.1.113730.4.1
  1.3.6.1.4.1.311.10.3.3
]

[5]: ObjectId: 2.5.29.19 Criticality=true
BasicConstraints:[
  CA:false
  PathLen: undefined
]

]
  Algorithm: [SHA1withRSA]
  Signature:
0000: 13 CA C0 80 2D BE AC 9D   3F 58 EF A9 C9 C4 E3 43  ....-...?X.....C
0010: FE ED 5A 14 0A 04 6B 67   ED 19 EF 8D C2 14 53 6D  ..Z...kg......Sm
0020: 1A 3F B8 99 8E 2B B1 0F   50 83 F1 5A 56 43 5F 8B  .?...+..P..ZVC_.
0030: 8B 0A EE 98 04 D7 32 FC   B9 FE 43 57 97 0B FC 46  ......2...CW...F
0040: 02 4E A4 8F F3 F0 65 BD   20 28 76 DB 29 16 B6 16  .N....e. (v.)...
0050: 3B 57 D3 B3 24 21 C5 AC   64 8E 95 C9 92 06 DC 95  ;W..$!..d.......
0060: F8 B4 62 74 8C 44 8D 96   83 94 0F 5C EE B0 A4 8B  ..bt.D.....\....
0070: 5A EA 1E 58 B2 A3 8B 0E   E1 79 5F 06 BF EE E3 A9  Z..X.....y_.....

]
***
*** Diffie-Hellman ServerKeyExchange
DH Modulus:  { 189, 165, 218, 21, 118, 110, 155, 89, 53, 21, 128, 88, 254, 47, 40, 106, 51, 167, 219, 167, 68, 153, 230, 233, 63, 125, 198, 5, 12, 230, 7, 156, 21, 89, 142, 17, 146, 200, 33, 197, 86, 116, 41, 212, 22, 176, 162, 138, 121, 124, 107, 57, 27, 209, 42, 131, 182, 254, 178, 211, 86, 112, 32, 222, 185, 43, 212, 180, 71, 200, 174, 22, 11, 172, 213, 135, 217, 124, 40, 120, 218, 170, 182, 151, 131, 89, 191, 59, 214, 52, 56, 119, 212, 5, 163, 107 }
DH Base:  { 173, 84, 126, 57, 69, 157, 241, 124, 0, 60, 149, 36, 136, 75, 82, 91, 142, 16, 240, 117, 1, 146, 23, 25, 218, 139, 127, 216, 27, 183, 252, 214, 189, 253, 2, 42, 125, 1, 73, 84, 49, 69, 80, 239, 179, 134, 236, 96, 175, 244, 36, 206, 203, 163, 251, 64, 83, 253, 74, 94, 114, 248, 210, 145, 130, 225, 252, 33, 56, 100, 6, 53, 163, 138, 154, 7, 142, 209, 10, 230, 107, 233, 77, 189, 151, 46, 115, 77, 93, 57, 47, 178, 121, 240, 183, 255 }
Server DH Public Key:  { 36, 153, 18, 99, 95, 39, 135, 103, 245, 21, 20, 161, 159, 246, 67, 6, 183, 101, 8, 62, 161, 21, 211, 95, 193, 13, 248, 152, 101, 138, 143, 247, 29, 176, 255, 165, 78, 140, 108, 243, 219, 222, 59, 181, 4, 71, 51, 164, 1, 80, 97, 70, 66, 189, 175, 19, 248, 11, 77, 84, 112, 134, 139, 222, 81, 12, 45, 173, 173, 102, 141, 195, 80, 244, 20, 251, 109, 246, 24, 194, 140, 201, 29, 251, 26, 191, 9, 201, 45, 107, 59, 28, 148, 25, 220, 215 }
Signed with a DSA or RSA public key
*** ServerHelloDone
ProxyHandler$SslRelay3-9, WRITE: TLSv1 Handshake, length = 1332

However, when things are broken things are very different and we never even get to attempt the DH exchange:
ProxyHandler$SslRelay3-1, setSoTimeout(10000) called
ProxyHandler$SslRelay3-1, READ: TLSv1 Handshake, length = 171
*** ClientHello, TLSv1
RandomCookie:  GMT: 1320358903 bytes = { 148, 198, 81, 98, 2, 66, 235, 221, 74, 170, 130, 205, 43, 139, 18, 60, 121, 148, 234, 153, 3, 89, 48, 153, 168, 196, 80, 54 }
Session ID:  {}
Cipher Suites: [Unknown 0x0:0xff, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, Unknown 0x0:0x88, Unknown 0x0:0x87, TLS_DHE_RSA_WITH_AES_256_CBC_SHA, TLS_DHE_DSS_WITH_AES_256_CBC_SHA, TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, Unknown 0x0:0x84, TLS_RSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, Unknown 0x0:0x45, Unknown 0x0:0x44, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, TLS_ECDH_RSA_WITH_RC4_128_SHA, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS_ECDH_ECDSA_WITH_RC4_128_SHA, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, Unknown 0x0:0x96, Unknown 0x0:0x41, SSL_RSA_WITH_RC4_128_MD5, SSL_RSA_WITH_RC4_128_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA]
Compression Methods:  { 0 }
Unsupported extension server_name, [host_name: REDACTED]
Extension elliptic_curves, curve names: {secp256r1, secp384r1, secp521r1}
Extension ec_point_formats, formats: [uncompressed]
Unsupported extension type_35, data:
***
Finalizer, called close()
Finalizer, called closeInternal(true)
Finalizer, called close()
Finalizer, called closeInternal(true)
INFO 05/16 02:46:23 b.n.w.a.LoadTestTra~ - Reported 0 slices representing 0 transactions
INFO 05/16 02:46:23 b.n.w.a.LoadTestTra~ - Collected 0 transactions
Finalizer, called close()
Finalizer, called closeInternal(true)
Finalizer, called close()
Finalizer, called closeInternal(true)
INFO 05/16 02:46:33 b.n.w.a.LoadTestTra~ - Reported 0 slices representing 0 transactions
INFO 05/16 02:46:33 b.n.w.a.LoadTestTra~ - Collected 0 transactions
Finalizer, called close()
Finalizer, called closeInternal(true)
Finalizer, called close()
Finalizer, called closeInternal(true)
INFO 05/16 02:46:43 b.n.w.a.LoadTestTra~ - Reported 0 slices representing 0 transactions
INFO 05/16 02:46:43 b.n.w.a.LoadTestTra~ - Collected 0 transactions
Finalizer, called close()
Finalizer, called closeInternal(true)
Finalizer, called close()
Finalizer, called closeInternal(true)
INFO 05/16 02:46:53 b.n.w.a.LoadTestTra~ - Reported 0 slices representing 0 transactions
INFO 05/16 02:46:53 b.n.w.a.LoadTestTra~ - Collected 0 transactions
Finalizer, called close()
Finalizer, called closeInternal(true)
Finalizer, called close()
Finalizer, called closeInternal(true)
INFO 05/16 02:47:03 b.n.w.a.LoadTestTra~ - Reported 0 slices representing 0 transactions
INFO 05/16 02:47:03 b.n.w.a.LoadTestTra~ - Collected 0 transactions
Finalizer, called close()
Finalizer, called closeInternal(true)
Finalizer, called close()
Finalizer, called closeInternal(true)
Acceptor [SSL: ServerSocket[addr=0.0.0.0/0.0.0.0,port=0,localport=35182]], setSoTimeout(10000) called
ProxyHandler$SslRelay2-0, setSoTimeout(10000) called
ProxyHandler$SslRelay2-0, READ: TLSv1 Handshake, length = 165
*** ClientHello, TLSv1
RandomCookie:  GMT: 1320359212 bytes = { 59, 24, 42, 178, 241, 201, 150, 61, 101, 15, 153, 40, 167, 176, 22, 250, 205, 245, 89, 8, 156, 34, 122, 161, 4, 99, 40, 108 }
Session ID:  {}
Cipher Suites: [Unknown 0x0:0xff, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, Unknown 0x0:0x88, Unknown 0x0:0x87, TLS_DHE_RSA_WITH_AES_256_CBC_SHA, TLS_DHE_DSS_WITH_AES_256_CBC_SHA, TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, Unknown 0x0:0x84, TLS_RSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, Unknown 0x0:0x45, Unknown 0x0:0x44, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, TLS_ECDH_RSA_WITH_RC4_128_SHA, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS_ECDH_ECDSA_WITH_RC4_128_SHA, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, Unknown 0x0:0x96, Unknown 0x0:0x41, SSL_RSA_WITH_RC4_128_MD5, SSL_RSA_WITH_RC4_128_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA]
Compression Methods:  { 0 }
Unsupported extension server_name, [host_name: sb-ssl.google.com]
Extension elliptic_curves, curve names: {secp256r1, secp384r1, secp521r1}
Extension ec_point_formats, formats: [uncompressed]
Unsupported extension type_35, data:
***
Acceptor [SSL: ServerSocket[addr=0.0.0.0/0.0.0.0,port=0,localport=53331]], setSoTimeout(10000) called
ProxyHandler$SslRelay3-0, setSoTimeout(10000) called
ProxyHandler$SslRelay3-0, READ: TLSv1 Handshake, length = 171
*** ClientHello, TLSv1
RandomCookie:  GMT: 1320359212 bytes = { 124, 252, 208, 200, 213, 33, 188, 186, 19, 175, 247, 227, 126, 10, 57, 66, 29, 66, 230, 145, 66, 28, 210, 98, 167, 31, 240, 85 }
Session ID:  {}
Cipher Suites: [Unknown 0x0:0xff, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, Unknown 0x0:0x88, Unknown 0x0:0x87, TLS_DHE_RSA_WITH_AES_256_CBC_SHA, TLS_DHE_DSS_WITH_AES_256_CBC_SHA, TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, Unknown 0x0:0x84, TLS_RSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, Unknown 0x0:0x45, Unknown 0x0:0x44, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, TLS_ECDH_RSA_WITH_RC4_128_SHA, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS_ECDH_ECDSA_WITH_RC4_128_SHA, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, Unknown 0x0:0x96, Unknown 0x0:0x41, SSL_RSA_WITH_RC4_128_MD5, SSL_RSA_WITH_RC4_128_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA]
Compression Methods:  { 0 }
Unsupported extension server_name, [host_name: REDACTED]
Extension elliptic_curves, curve names: {secp256r1, secp384r1, secp521r1}
Extension ec_point_formats, formats: [uncompressed]
Unsupported extension type_35, data:
***
INFO 05/16 02:47:13 b.n.w.a.LoadTestTra~ - Reported 0 slices representing 0 transactions
INFO 05/16 02:47:13 b.n.w.a.LoadTestTra~ - Collected 0 transactions
Finalizer, called close()
Finalizer, called closeInternal(true)
Finalizer, called close()
Finalizer, called closeInternal(true)
INFO 05/16 02:47:23 b.n.w.a.LoadTestTra~ - Reported 0 slices representing 0 transactions
INFO 05/16 02:47:23 b.n.w.a.LoadTestTra~ - Collected 0 transactions
Finalizer, called close()
Finalizer, called closeInternal(true)
Finalizer, called close()
Finalizer, called closeInternal(true)
INFO 05/16 02:47:33 b.n.w.a.LoadTestTra~ - Reported 0 slices representing 0 transactions
INFO 05/16 02:47:33 b.n.w.a.LoadTestTra~ - Collected 0 transactions
INFO 05/16 02:47:43 b.n.w.a.LoadTestTra~ - Reported 0 slices representing 0 transactions
INFO 05/16 02:47:43 b.n.w.a.LoadTestTra~ - Collected 0 transactions
Finalizer, called close()
Finalizer, called closeInternal(true)
Finalizer, called close()
Finalizer, called closeInternal(true)
INFO 05/16 02:47:53 b.n.w.a.LoadTestTra~ - Reported 0 slices representing 0 transactions
INFO 05/16 02:47:53 b.n.w.a.LoadTestTra~ - Collected 0 transactions
INFO 05/16 02:48:03 b.n.w.a.LoadTestTra~ - Reported 0 slices representing 0 transactions
INFO 05/16 02:48:03 b.n.w.a.LoadTestTra~ - Collected 0 transactions
Finalizer, called close()
Finalizer, called closeInternal(true)
Finalizer, called close()
Finalizer, called closeInternal(true)
Finalizer, called close()
Finalizer, called closeInternal(true)
Finalizer, called close()
Finalizer, called closeInternal(true)
INFO 05/16 02:48:13 b.n.w.a.LoadTestTra~ - Reported 0 slices representing 0 transactions
INFO 05/16 02:48:13 b.n.w.a.LoadTestTra~ - Collected 0 transactions
INFO 05/16 02:48:14 o.o.s.s.SeleniumDri~ - Got result: Timed out after 120000ms on session 5a7b389b01c041fcb3632c2f5056043b

That log spans a time range of 2 minutes, in which almost nothing happens. There is some additional SSL logging related to sb-ssl.google.com (which also blocks), but that can be ignored - it's just the Firefox browser checking in to Google's safe browsing API.
I should note: similar complaints had been levied against the Selenium proxy about a month ago, but they were resolved by upgrading to the latest version of BouncyCastle. However, we are finding that the problem occasionally still happens and we can't figure out why.
I'm hoping the StackOverflow family can shed some light on why sometimes the thread gets stuck in org.bouncycastle.crypto.generators.DHParametersHelper.generateSafePrimes and other times the logging shows that we proceed directly to this key line right away:
%% Created:  [Session-10, TLS_DHE_RSA_WITH_AES_128_CBC_SHA]

Thanks for any insight!
Edit: I should add that we're using Java 1.6.0_18-b07 on Linux (32bit and 64bit are affected), Selenium 2.21, and BouncyCastle 1.47.
Edit #2: I just confirmed that this problem doesn't exist when using Java 7.

A: So check the full comment thread, but basically after a lot of debugging I discovered that upgrading to Java 7 resolved the issue. Not sure what the original issue was with Java 6, but we're just going to go ahead with Java 7. I hope this helps someone in the future!


text:
Q: Does the event "onWindowFocusChanged" work for Widgets on Home screen? I am a biginner to Android development.
In iOS, the widget receives View lifecycle events when seen.
Similarly, if the event "onWindowFocusChanged" works for Widgets in Android Homescreen ? If so can someone provide me any tutorials.
Thanks

A: If you are the author of the app widget — in other words, you are the one with the AppWidgetProvider class — then you do not receive this event.
If you are the host of the app widget, such as the home screen, you will receive this event. App widgets are ordinary views in the home screen's UI, and so the home screen will receive normal events.


text:
Q: In which order SOLR returns results if no keyword specified? For multiple Drupal content types There is Drupal installation which uses SOLR via apachesolr module.
In which order are results sorted if I go just to search/site link?

A: Found out that it is sorted by Node id.


text:
Q: Writing a wordpress plugin: add_meta_box vs. add_settings_field? I'm writing a custom wordpress plugin and trying to incorporate some functionality from a third-party plugin. That plugin seems to use add_meta_box to create the fields for settings options on the plugin admin pages.  I searched the entire source code of the plugin for add_settings_field and it doesn't occur once.  Are the two functions basically interchangeable?  From the WP Codex, it seems that add_meta_box is primarily for the purpose of adding "a custom section to the post and page editing screens" -- i.e. not so much intended for the admin settings/options forms.  On the other hand, the 3rd-party plugin seems to work very well, which is why I'm borrowing from it...
So in short my question is this: can someone please explain correct usage for the add_meta_box and add_settings_field functions?  Thanks!  Please let me know if anything about this question is unclear and I will do my best to rephrase.

A: This is a settings field (Slug):

This is 2 Meta Boxes (publish and categories):


text:
Q: How can i select data from two tables I selected two different data from same tables but i need this two different datas merge to one table as select.
For example i have this:
SELECT DISTINCT db.nazev, db.skupina, db.datum_od1, db.datum_do1, db.mnozstvi, db.cena_bez_dph, db.datum_od, db.datum_do2, db.mnozstvi2, db.cena_bez_dph2
FROM (
SELECT s.nazev as nazev, s.kod as skupina, (select (DATE '<<datum_od1>>')) as datum_od1, (select (DATE '<<datum_do1>>')) as datum_do1,  sum(f.mnozmj) as mnozstvi, sum(f.sumZkl) as cena_bez_dph FROM dpolfak as f
LEFT OUTER JOIN ddoklfak hla ON hla.iddoklfak = f.iddoklfak
LEFT OUTER JOIN ccenik c ON c.kod = f.kod
LEFT OUTER JOIN cskupzboz s ON s.idskupzboz = c.idskupzboz
where f.modul = 'FAV' and f.datvyst >= '<<datum_od1>>' and f.datvyst <= '<<datum_do1>>'
GROUP BY s.nazev, s.kod
UNION ALL
SELECT s.nazev as nazev, s.kod as skupina, (select (DATE '<<datum_od2>>')) as datum_od2, (select (DATE '<<datum_do2>>')) as datum_do2,  sum(f.mnozmj) as mnozstvi2, sum(f.sumZkl) as cena_bez_dph2 FROM dpolfak as f
LEFT OUTER JOIN ddoklfak hla ON hla.iddoklfak = f.iddoklfak
LEFT OUTER JOIN ccenik c ON c.kod = f.kod
LEFT OUTER JOIN cskupzboz s ON s.idskupzboz = c.idskupzboz
where f.modul = 'FAV' and f.datvyst >= '<<datum_od2>>' and f.datvyst <= '<<datum_do2>>'
GROUP BY s.nazev, s.kod
) db

But problem is that fuction "UNION ALL" merge all data to one so but i need select diferent data from table two into new columns which can you see that in main select.
Main problem is that this dont work "db.datum_do2, db.mnozstvi2, db.cena_bez_dph2" with function union all (it still write me that column doesnt exists). How can i fix it?
This is my actually result:
nazev                   skupina   Datum       Datum        Množství Cena bez DPH
Směsi éterických olejů | SL024 | 01.12.2014 | 19.12.2014 | 1 798,00 | 208 142,79

Směsi éterických olejů | SL024 | 20.11.2014 | 07.01.2015 | 662,00   | 86 374,52

and i want this:
nazev                   skupina   Datum       Datum        Množství Cena bez DPH  Datum 2      Datum 2       Množství 2  Cena bez DPH 2
Směsi éterických olejů | SL024 | 01.12.2014 | 19.12.2014 | 1 798,00 | 208 142,79 |20.11.2014 | 07.01.2015 | 662,00   | 86 374,52

A: If you really want the UNION ALL's different queries' columns separated, you can either do something like this:
select col1, case when q = 1 then colA end, case when q = 2 then colA end,...
(select col1, colA as colA, 1 as q
 from...
 union all
 select col1, colB as colA, 2 as q
 from...
) db

or
select col1, col2 etc
(select col1, colA, null from...
 UNIOM ALL
 select col1, null, colB from...)


text:
Q: remove columns with string match bash I'm encountering the following issue.
I need to remove columns within a file that contain a specific string in the header.
The semi-colon are acting as column limit
Examples below
file 1
ADM_THO_CVL2000,ZO,AT;BS-CCI-BAL,ARA,EL;BS-TLI-MS,ARA,BG;
1;2;3;
4;5;6;

file 2
BS-CCI-BAL,ARA,EL;BS-TLI-MS,ARA,BG;ADM_THO_CVL2000,OZ,ES;BAG-AL,W,SE;
1;2;3;5;
4;5;6;7;

ADM_THO_CVL2000 is the specific string I need to remove. The results , once string and the subsequent columns are removed, are below:
BS-CCI-BAL,ARA,EL;BS-TLI-MS,ARA,BG;
2;3;
5;6;

BS-CCI-BAL,ARA,EL;BS-TLI-MS,ARA,BG;BAG-AL,W,SE;
1;2;5;
4;5;7;

I had a look on the internet.
awk can do the job that but the results I'm having, are not the one that I expect. I'm giving you the code below:
awk '
FNR==1{
    for(i=1;i<=NF;i++)
        if ($i ~ str) {
          h=(h)?h FS $i:$i
          f=(f)?f FS i:i
        }
    print h
    nf=split(f,fA,FS);next
 }
 {
 for(i=1;i<=nf;i++)
       printf("%s%c",$fA[i], (i==nf)?ORS:FS)
}' str=ADM_THO_CVL2000, 'FS=;' filename.csv

I'm all ears for any of your suggestions.
Cheers

A: You need some enhancements in my earlier solution. Since you could not resolve it I am posting my answer:
awk -F';' '/ADM_THO_CVL2000/{delete a; for (i=1; i<NF; i++)
   if ($i ~ /ADM_THO_CVL2000/) a[i]; else printf "%s%s", $i, OFS; print $i; next}
   {for (i=1; i<NF; i++) if (!(i in a)) printf "%s%s", $i, OFS; print $i }' OFS=';' file

file 1
BS-CCI-BAL,ARA,EL;BS-TLI-MS,ARA,BG;
2;3;
5;6;

file 2
BS-CCI-BAL,ARA,EL;BS-TLI-MS,ARA,BG;BAG-AL,W,SE;
1;2;5;
4;5;7;


text:
Q: Angular route loading with async redirect I need to wait for some API call before letting page in my route to load. Basically we have A/B testing enabled (which is API call) and based on that will have to either load Component assosiated with that route or redirect to different url.
To do that I was trying to use resolver that returns Observable<boolean>. Here is code:
export class RedirectResolveService implements Resolve<Observable<boolean>> {
  private empty = new Observable<boolean>();
  constructor(private apiService: ApiService, private router: Router) {}

  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> {
    return this.apiService.get("/api/abtest/mypage").pipe(
      tap((isOn) => {
        if (!isOn) {
          window.location.href = "/welcome-page";
        }
      }),
      first()
    );
  }
}

Then I add this in the route:
{
  path: 'new-page',
  component: NewPageComponent,
  resolve: {
    redirect: RedirectResolveService,
  },
},

And then in NewPageComponent I add subscription in the constructor:
export class NewPageComponent {
  constructor(private route: ActivatedRoute) {
    this.route.data.subscribe();
  }
}

It works but for the case when redirect happens I see first NewPageComponent rendered and then redirect happening. That makes sense since I subscribe to my Observable when Component initializes and thus only start redirect after that.
Is there way to make redirect logic without Component being initialized?

A: Using route guard it would be something like this
@Injectable({
  providedIn: "root",
})
export class RedirectGuard implements CanActivate {
  constructor(
    private _authService: AuthService,
    private _router: Router,
    private apiService: ApiService
  ) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean | UrlTree>
    | Promise<boolean | UrlTree>
    | boolean
    | UrlTree {
    return this.apiService.get("/api/abtest/mypage").pipe(
      tap(isOn => isOn || this._router.parseUrl("/welcome-page")),
      first()
    );
  }
}


text:
Q: Rendering a partial with jQuery within Users model I am relatively new to Rails, and so I am not sure if I am correctly routing/structuring my controller and view.
Simply, I am just trying to use tabs within the user/show.html.erb page to render partial in the content area below it with jQuery.
However, when I refresh the page with my code, I get the following error:
undefined local variable or method `userprofile_path' for #<#<Class:0x007f8c181e9ff0>:0x007f8c171662a0>

My app>views>users>show.html.erb :

        <%= link_to "
Current
".html_safe, userprofile_path, remote: true %>
        <%= link_to "
Offers
".html_safe, userprofile_path, remote: true %>
        <%= link_to "
Sales
".html_safe, userprofile_path, remote: true %>

My app>controllers>users_controller.rb :
class UsersController < ApplicationController

def show
    @user = User.find(params[:id])
end

def userprofile
    respond_to do |format|
        format.js
    end
end

end

My app>assets>javascripts>userprofile.js :
$(function() {
        $("li.tab").click(function(e) {
          e.preventDefault();
          $("li.tab").removeClass("selected");
          $(this).addClass("selected");
          $("#profile-content").html("<%= escape_javascript(render partial:
"users/offers")%>");
        });
    });

I am also using Devise, so here is my routes.rb file:
devise_for :admin_users, ActiveAdmin::Devise.config

devise_for :users, :path => '', :path_names => {:sign_in => 'login', :sign_out => 'logout'}

resources :users

Since I am new to Rails, I am not sure if its an issue with bad or missing code, the files not being named correctly, if I need a new file somewhere to make it work, or what exactly it is.
If anyone could point me in the right direction in terms of the code I need and the structure of the app, I would greatly appreciate it.

A: You have to declare a route before using an action... resources only creates standard restful routes, you have to add a custom one in this case. Example :
resources :users do
  collection do
    get :userprofile # it would create a helper like userprofile_users_path
  end
end

see the rails guides on routing for more info.
As a side note, if your action concerns only one user, use member instead of collection

A: For adding userprofile_path route, do this:
devise_for :users, :path_names => {:sign_in => 'login', :sign_out => 'logout'} do
   match '/profile', :to => 'users#userprofile', :as => 'userprofile'
end


text:
Q: What does "I/O Reads or Writes" and "I/O Read Bytes or Write Bytes" mean? In Task Manager (and Sysinternals' Process Explorer) there are columns called "I/O Reads", "I/O Writes", "I/O Read Bytes" and "I/O Write Bytes". So what do these counters mean exactly? What else, besides disk and network activity, do they include?
In Process Explorer I see a number of processes which have zero "Disk Read Bytes" and "Network Receive Bytes", but a non-zero "I/O Read Bytes". And conversely, some processes have a "Disk Read Bytes" value larger than "I/O Read Bytes". How is this possible?

A: How is it possible that I have a process with 4 MiB "I/O Read Bytes" and zero "Disk Read Bytes"?
I/O Read Bytes is more than just Disk Read Bytes:

*

*It includes File, Network and Device I/O

*It does not include Console I/O

I/O Read Bytes - The number of bytes read in input/output operations generated by a process, including file, network, and device I/Os. I/O Read Bytes directed to CONSOLE (console input object) handles are not counted.

What does I/O data mean?

I/O Columns of Process Explorer

*

*I/O Delta - The change in I/O operations since the last measurement

*I/O Delta Bytes - The change in I/O bytes since the last measurement.

*I/O Other - The number of input/output operations generated by a process that are neither reads nor writes, including file, network,
  and device I/Os. An example of this type of operation would be a
  control function. I/O Others directed to CONSOLE (console input
  object) handles are not counted.

*I/O Other Bytes - The number of bytes transferred in input/output operations generated by a process that are neither reads nor writes,
  including file, network, and device I/Os. An example of this type of
  operation would be a control function. I/O Other Bytes directed to
  CONSOLE (console input object) handles are not counted.

*I/O Read Bytes - The number of bytes read in input/output operations generated by a process, including file, network, and device I/Os. I/O
  Read Bytes directed to CONSOLE (console input object) handles are not
  counted.

*I/O Reads - The number of read input/output operations generated by a process, including file, network, and device I/Os. I/O Reads
  directed to CONSOLE (console input object) handles are not counted.

*I/O Write Bytes - The number of bytes written in input/output operations generated by a process, including file, network, and device
  I/Os. I/O Write Bytes directed to CONSOLE (console input object)
  handles are not counted.

*I/O Writes - The number of write input/output operations generated by a process, including file, network, and device I/Os. I/O Writes
  directed to CONSOLE (console input object) handles are not counted.

Source Trying to understand Process Explorer's I/O data


text:
Q: C compiler cannot create executables when brew install Saw below error when running brew install hub and brew install gh
configure: error: in `/tmp/pkg-config-20220914-13522-pwtaq4/pkg-config-0.29.2':
configure: error: C compiler cannot create executables
See `config.log' for more details

READ THIS: https://docs.brew.sh/Troubleshooting

When I look at config.log, I found below errors:
configure:3434: gcc-7 -V >&5
gcc-7: error: unrecognized command line option '-V'
configure:3445: $? = 1
configure:3434: gcc-7 -qversion >&5
gcc-7: error: unrecognized command line option '-qversion'; did you mean '--version'?

I think it's because we should use -v instead -V or -qversion, but how can I change that?


text:
Q: Django distinct() generates query for not one column (as needed) When I do this queryset:
Club.objects.values('district').distinct()

I expect to get this SQL:
SELECT DISTINCT `club_club`.`district` FROM `club_club` ORDER BY `club_club`.`name` ASC

But Django generates this query (adds 'name' column):
>>> print Club.objects.values('district').distinct().query
SELECT DISTINCT `club_club`.`district`, `club_club`.`name` FROM `club_club` ORDER BY `club_club`.`name` ASC

What is wrong?

A: Query you are expecting is invalid order by column has to be in select list if you are using distinct keyword, or else you will get this standard SQL error
Msg 145, Level 15, State 1, Line 1
ORDER BY items must appear in the select list if SELECT DISTINCT is specified.


text:
Q: What is the name of scripts in Android.mk file and how to say Android Studio colorize the text inside? What is the name of script/language written in Android.mk and application.mk files?
My Android Studio does not recognize it and shows it as a text file. Is it possible to make it easier to read and add autocomplete capability?

A: Please, follow the official documentation guide: https://developer.android.com/ndk/guides/android_mk.html
By the Way, as far as I can go, there's not a ready to use edit tool with auto completion and such but there's enough documentation and references online:
How to use my own Android.mk file with Android Sudio
http://android.mk/


text:
Q: Storing username with post confirmation trigger (AWS, Lambda, DynamoDB) I try to store some parameters in a AWS DynamoDB with Cognito post confirmation trigger.
The lambda is written in node.js but I am not able to store the username of the signed up cognito user.
const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB.DocumentClient({region: 'eu-central-1'});

exports.handler = async (event, context, callback) => {
    console.log(event);

    const username = event.userName;

    await createMessage(username).then(() => {
        callback(null, {
            statusCode: 201,
            body: '',
            headers: {
                'Access Control Allow Origin' : '*'
            }
        });
    }).catch((err) => {
        console.error(err);
    });
};

function createMessage(username){
    const familyid = (new Date()).getTime().toString(36) + Math.random().toString(36).slice(2);
    const params = {
        TableName: 'eldertech',
        Item: {
            'UserId' : username,
            'message' : familyid
        }
    };
    return dynamodb.put(params).promise();
}

My test:
{
"username":"admin",
"email":"admin@admin.com",
"userId": "AD87S"
}

The error:
ERROR   ValidationException: One or more parameter values were invalid: Missing the key UserId in the item
Can somebody please help a newbie?

A: Okay, I just had a typo....
const username = event.username;

No capital n in username...


text:
Q: How does openvpn client get data on the wire if physicall interface is blocked by firewall? Reading about Tun/Tap from kernel documentation https://www.kernel.org/doc/Documentation/networking/tuntap.txt it is clear that this interface is not backed by hardware. If I setup iptables firewall to deny in/out traffic on all interfaces except tun0, how does OpenVPN client actually get the data on the wire?
When the kernel decides its time to put data on the wire, for tun0 interface it sends the data to a userspace program (openvpn client). I assume that this program must prepare the data for tunneling then open a socket and actually send data out using a non-virtual interface like eth0. But this is supposed to be blocked by firewall. Yet it works.
Does OpenVPN client somehow bypass the firewall mechanism (iptables)?

A: iptables blocks all traffic including openvpn, client cannot establish tunnel unless it's on the whitelist. However, it requires only openvpn port to be opened to bypass any kind of traffic/ports, once the tunnel is established. As all packets will be encapsulated in openvpn package regardless of the underlying traffic.


text:
Q: React app deployment through tom cat server? How to deploy react app in tomcat server by creating war file.
We tried npm run compile
In package.json
"compile" : "npm run build && cd build && jar -cvf web.war"
Its creating build  in war file after deploying in tomcat webinf
But its not getting react content only title is displaying
React Ui and Javabackend should get deploy in tomcat


text:
Q: regionDidChangeAnimated not working I am trying to run just a simple print function when the user moves the map around using gesture or search (moves the map in general) I've followed the apple ref guides and i get errors. Ive followed other stack overflow posts and other google search results. I don't know if it is because im using swift 2 or something in my code elsewhere that is contradicting. If somebody could help me that would be greatly appreciated. Here is my code
import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, MKMapViewDelegate,
CLLocationManagerDelegate, UISearchBarDelegate
{

@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var searchBar: UISearchBar!

let locationManager = CLLocationManager()

@IBAction func showSearchBar(sender: AnyObject) {
    searchController = UISearchController(searchResultsController: nil)
    searchController.hidesNavigationBarDuringPresentation = false
    self.searchController.searchBar.delegate = self
    presentViewController(searchController, animated: true, completion: nil)
}

@IBAction func locateMe(sender: AnyObject) {

    self.locationManager.delegate = self
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
    self.locationManager.requestWhenInUseAuthorization()
    self.locationManager.startUpdatingLocation()

    self.mapView.showsUserLocation = true

}

@IBAction func photographer(sender: AnyObject) {
}

@IBAction func buyer(sender: AnyObject) {
}

var searchController:UISearchController!
var annotation:MKAnnotation!
var localSearchRequest:MKLocalSearchRequest!
var localSearch:MKLocalSearch!
var localSearchResponse:MKLocalSearchResponse!
var error:NSError!
var pointAnnotation:MKPointAnnotation!
var pinAnnotationView:MKPinAnnotationView!

override func viewDidLoad()
{
    super.viewDidLoad()

    self.locationManager.delegate = self
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
    self.locationManager.requestWhenInUseAuthorization()
    self.locationManager.startUpdatingLocation()

    self.mapView.showsUserLocation = true

    func mapView(mapView: MKMapView!, regionDidChangeAnimated animated: Bool) {
        hobo()
    }

}

override func didReceiveMemoryWarning()
{
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

//     MARK: - Location Delegate Methods

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
    let location = locations.last

    let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

    self.mapView.setRegion(region, animated: true)

    self.locationManager.stopUpdatingLocation()
}

func locationManager(manager: CLLocationManager, didFailWithError error: NSError)
{
    print("Error: " + error.localizedDescription)
}

func searchBarSearchButtonClicked(searchBar: UISearchBar){
    //1
    searchBar.resignFirstResponder()
    dismissViewControllerAnimated(true, completion: nil)
    if self.mapView.annotations.count != 0{
        annotation = self.mapView.annotations[0]
        self.mapView.removeAnnotation(annotation)
    }
    //2
    localSearchRequest = MKLocalSearchRequest()
    localSearchRequest.naturalLanguageQuery = searchBar.text
    localSearch = MKLocalSearch(request: localSearchRequest)
    localSearch.startWithCompletionHandler { (localSearchResponse, error) -> Void in

        if localSearchResponse == nil{
            let alertController = UIAlertController(title: nil, message: "Place Not Found", preferredStyle: UIAlertControllerStyle.Alert)
            alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default, handler: nil))
            self.presentViewController(alertController, animated: true, completion: nil)
            return
        }
        //3
        self.pointAnnotation = MKPointAnnotation()
        self.pointAnnotation.title = searchBar.text
        self.pointAnnotation.coordinate = CLLocationCoordinate2D(latitude: localSearchResponse!.boundingRegion.center.latitude, longitude:     localSearchResponse!.boundingRegion.center.longitude)

        self.pinAnnotationView = MKPinAnnotationView(annotation: self.pointAnnotation, reuseIdentifier: nil)
        self.mapView.centerCoordinate = self.pointAnnotation.coordinate
        self.mapView.addAnnotation(self.pinAnnotationView.annotation!)
    }
}

func hobo(){
    print("testing")
}

}

A: Make sure you set yourself as your map view's delegate in IB. Also, I'd try moving regionDidChangeAnimated out of viewDidLoad.