text:
Q: Java Generics Function Return Declaration I am new to Java generics and have managed to get a getKeyByValue function working with a HashMap<String, String>, but I don't understand how the function declaration can be ambiguous/redundant and still work.   For example both of these declaration work but the first does not make a lot of sense to me:
    private <T, E> String getKeyByValue(Map<String, E> map, String value) {
        for (Entry<String, E> entry : map.entrySet()) {
            if (value.equals(entry.getValue())) {
                return entry.getKey();
            }
        }
        return null;
    }

Example with just <E>:
    private <E> String getKeyByValue(Map<String, E> map, String value) {
        for (Entry<String, E> entry : map.entrySet()) {
            if (value.equals(entry.getValue())) {
                return entry.getKey();
            }
        }
        return null;
    }

A: Your first example is just declaring Type parameters that are never used - you can declare as many as you like!
private <T, E, F, G> String getKeyByValue(Map<String, E> map, String value) {
    for (Entry<String, E> entry : map.entrySet()) {
        if (value.equals(entry.getValue())) {
            return entry.getKey();
        }
    }
    return null;
}

A: For the first sample, the generic format type T is not used, hence can be removed which brings the implementation to be as you second method implementation.
In the second implementation, the Java Generics use is with no utility as the equals method (you are calling with a typed parameter E) for the java.lang.String class accepts an Object argument, hence any object would fit in there.
private <E> String getKeyByValue(Map<String, E> map, String value) {
    for (Map.Entry<String, E> entry : map.entrySet()) {
        if (value.equals(entry.getValue())) { // there is no type checking needed over the value as it can be any acceptable object
            return entry.getKey();
        }
    }
    return null;
}

The same method could be rewritten using a ? wildcard as the formal type since there is no type-bounded operations that are needed over the Map values:
private String getKeyByValue(Map<String, ?> map, String value) {
    for (Map.Entry<String, ?> entry : map.entrySet()) {
        if (value.equals(entry.getValue())) {
            return entry.getKey();
        }
    }
    return null;
}

A: For the first case, type parameter T is obviously redundant.
From another point of view, a similar case is declaring method input parameter without using it. You may think the compiler should not allow us to do so. But sometimes such "flexibility" can be useful. For example, we may have parent class having a method with input parameter only used in child class. Although I can't think of a scenario for redundant type parameter to be useful, someone may make use of such language flexibility to solve their problem.
I would say the first case should be considered as code smell, just like empty if statement, or declaring unused variable. IDE and linter are the right tool to tackle them, not the compiler.


text:
Q: Observable keyup event only when user enter key I have below code
 Observable.fromEvent(this.inputref.nativeElement, 'keyup')
      .map((evt: any) => evt.target.value)
      .filter(res => {
        if (res.length > 1) {
          return true;
        } else {
        }
      }).debounceTime(1000)
      .distinctUntilChanged()
      .subscribe((text: string) => this.callmethod(text.trim()));
  }

The above code is working fine, but issue is it also gets fired when input is filled by coding like
this.inputref.nativeElement.value = "value"

or when binbding varible change like below
<input type="text" #inputref value="{{input_val}}" />

this.input_val = "text value"

How to make it fire only when user press key not when input by logic.
Thanks

A: Try the following code:
.html file:
<input type="text" [formControl]="testControl" (input)="testMethod()">

In .ts file:
Create Form control:
 testControl: FormControl = new FormControl('');

create input change method:
testMethod(){
    console.log('Test control Change event', this.testControl.value);
}

Following code for set the value from code side:
this.testControl.setValue('Hello');

redpajama_set_name: RedPajamaStackExchange


text:
Q: Extjs Message Box Center Align As the title says, I would like the message of Ext.Msg.alert() to in center align. I tried this:
 Ext.Msg.alert({
        title: 'Success',
        msg: 'Deleted',
        buttons: Ext.Msg.OK,
        baseCls: 'msgbox'
    });

CSS:
 .msgbox {
      text-align: center;
  }

It is still on left align. How do I do this?

A: The displayed text is a displayfield component that has the same size that its text then, even when it is centered, you cannot see it aligned as you want.
So, the solution is to make it bigger. In my example i do it using a css class. Take a look at it:
var w = Ext.Msg.alert({
        title: 'Success',
        msg: 'Deleted',
        buttons: Ext.Msg.OK,
        autoShow: false,
        cls: 'msgbox'
});

w.down('.displayfield' ).addCls('displayfield-fullsize');

and the class is, as you can imagine:
.displayfield-fullsize{
       width: 100% !important;
}

See it working here: http://jsfiddle.net/lontivero/F7HE3/3/


text:
Q: Divide and conquer algorithm for finding the smallest value in the array an array a[1..n] of elements of some ordered type (i.e. x < y is always defined) and i want to find the smallest value in the array using a "divide and conquer" algorithm.
What does the assignment really mean?

A: Divide-and-conquer is an algorithmic technique that solves a problem by splitting the problem into smaller pieces, solving the problem in each piece, and combining the results together to form an overall answer.  When the problem becomes sufficiently simple, it can be solved directly.
In this case, think about what would happen if you split the array in half.  If you knew the minimum value in each half, could you figure out the minimum value overall?  And when there's just one element left in the array, what's the minimum value in the array?  If you answer this question, you can directly come up with a recursive divide-and-conquer algorithm for the problem.
Hope this helps!

A: The divide-and-conquer strategy solves a problem by:

*

*Breaking it into subproblems that are themselves smaller instances of the same type of
problem

*Recursively solving these subproblems

*Appropriately combining their answers
A good example is merge-sort!
http://en.wikipedia.org/wiki/Merge_sort

A: *

*If the contents of an array are random, that means you have to search each element until you find the one you're looking for. The longer the array, the longer the search time.   This is called a "linear search".

*If the contents of an array are already in some kind of order, you can take advantage of this order to optimize your search (and reduce your search time).  For example, names in a phone book are sorted alphabetically.  You can open the phone book in the middle: if you name you're looking for is "lower than" the name in the middle, then continue searching in the left side of the book.  If it's higher, then search the right half.  This is called a "binary search", or "Divide and Conquer".

*It's possible to quantify how efficient or inefficient a given search algorithm is. This is called "Asymptotic", or "Big O-Notation":

    Class                         Search algorithm
    -----                         ----------------
    Data structure                Array
    Worst case performance        O(log n)
    Best case performance         O(1)
    Average case performance      O(log n)
    Worst case space complexity   O(1)

A: In general, "divide and conquer" means to divide a problem into smaller (and often simpler) problems, solve each one separately, and then combine the solutions in some way.
In your specific example, you should divide the array into smaller arrays in some manner (e.g., divide it in half), find the smallest value in each smaller array, and then pick the smallest solution of these sub-problems as the solution to the overall problem. Each sub-problem can be solved using the same divide-and-conquer approach, with the limiting case being an array of sufficiently small size (e.g., 1 or 2) that you can solve the problem directly.

A: U can go with the following algorithm.
getSmallest(int a[])
{
  int n=a.length;
  if(n==1)
    return a[0];
  else
   {
        x=remove first element from a;
        create another array b with a size smaller by 1 than array a
        if(x<getSmallest(b))
            return x;
        else
           return the smallest returned by the recursive call
   }
}

A: http://ankzcode.blogspot.in/2012/11/find-minimum-without-linear-search.html
Code at the link implements the same.


text:
Q: Using stub in rspec to test output of a rand I have a class Weather, that should return random results and I'd like to test it using method stub. I read the article written by Martin Flower on this page and I feel it would be the easiest solution. But it's difficult to find any examples of syntax.
Could you give me an example of a test? This is part of my homework.
class Weather

  def conditions
   return :good if chance > 0.3
   :stormy
  end

  def chance
   rand
  end

end

A: Based on your example, you want to test the behavior of chance not the implementation.
describe Weather do
  it 'returns good' do
    weather = Weather.new
    allow(weather).to receive(:chance).and_return(0.8)
    expect(weather.conditions).to eq :good
  end
end


text:
Q: Checking divisors $k$ of 60 to determine if $A_5$ has subgroups of order $k$ up to isomorphism For every divisor $k$ of $60$ $(1 < k < 60)$, $(k = 1,2,3,4,5,6,10,12,15,20,30,60)$
I want to determine whether $A_5$ (Alternating group) has subgroups of order of $k$ of (up to isomorphism If so, describe the structure (by giving the isomorphism type of the group) at least one subgroup of that order.
Also, if not, I want to show why $A_5$ contains no subgroup of that order.
Would like to know if my approach is correct:
My approach:
Each non-trivial subgroup of $A_5$ is isomorphic to one of the following:
$$ \mathbb Z/2\mathbb Z, \space \mathbb Z/3\mathbb Z, \space \mathbb Z/2\mathbb Z \times \mathbb Z/2\mathbb Z,  \space \mathbb Z/5\mathbb Z, \space  S_3, \space  D_{10},  \space PSL_2(5)$$
And $A_5$ doesn't have subgroups of order $15, 20, and \space 30$.
Side note: The number of Sylow $2,3,and \space5 $ -subgroups of $A_5$ is $5,10, 6$ respectively.

Order $1:$

The trivial group is isomorphic to any group.

Order $2,3,4,5:$

I'll show that the group $A_5$ has subgroups of the orders $2,3,4,5$ and they're isomorphic to $ \mathbb Z/2\mathbb Z, \space \mathbb Z/3\mathbb Z, \space \mathbb Z/2\mathbb Z \times \mathbb Z/2\mathbb Z,  \space \mathbb Z/5\mathbb Z$ respectively.
We know that by Cauchy's theorem, $A_5$ must have elements of order $2$, $2$, and $5$, for e.g. $(1\space 2)(3\space 4), (1\space 2\space 3)$, $(1\space 2\space 3\space 4\space 5))$. Also, these generate cyclic subgroups of orders $2,3,5$. A sylow 2-subgroup of $A_5$ is of order $4$, and since $A_5$ has no elements of order $4$ - because elements of order in $S_4$ are odd permutations, these subgroups must be isomorphic to the Klein 4-group $\mathbb Z/2\mathbb Z \times \mathbb Z/2\mathbb Z$

Order $6:$

If $\pi\in S_5$ is a permutaion of $\{1,2,3\}$, then either $\pi$ or $\pi\circ (4\,5)$ is an even permutation, i.e., $\in A_5$. This allows us to embed $S_3\to A_5$.
Some geometry: $A_5$ is the symmetry group of the dodekahedron.
It is possible to select $4$ of its $20$ vertices that make up a regular tetrahedron $T_1$. A rotation of the dodekahedron by $72^\circ$ turns $T_1$ into another such tetrahedron $T_2$. Then the subgroup of $A_5$ that fixes $T_1\cup T_2$ turns out to be of isomorphic to $S_3$.
Without geometry: There is no element of order $6$ in $A_5$, thus if there's a subgroup of order $6$, it would be isomorphic to $S_3 \cong D_6$. Thus, (because we know that a simple of order $60$ has six Sylow 5-subgroups, 24 elements of order $5$, ten Sylow 3-subgroups, and $20$ elements of order $3$) if $Q \in Syl_3(G)$, then $|N_G(Q) : Q| = |Syl_3(G)| = 10$. Thus, $N_G(Q)$ is a subgroup of order $6$ isomorphic to $S_3$.

Order $10:$
  The group $A_5$ has subgroups of order $10$, and any subgroup is isomorphic to $D_{10}$.

The number of Sylow $5$-subgroups of $A_5$ is $6$. That means that if $P \in Syl_5(G)$, thus $|G:N_G(P)| = 6$. Thus, the normalizer of a Sylow 5-subgroup is a subgroup of order $10$. Also, we know that a group of order $10$ is either cyclic or isomorphic to $D_{10}$. The group $A_5$ doesn't have elements of order $10$, and so all subgroups of order $10$ in $A_5$ must be isomorphic to $D_{10}$.
Let's be more precise, if we consider the natural definition of $D_{10}$ as the symmetries of a pentagon, we see that it is generated by a rotation and a reflection. The former is a $5$-cycle, while the latter is the product of two $2$-cycles. Both of these generators are even permutations and hence elements of $A_5$.

Order $12:$
  I will show that a simple group of order $60$ must have a subgroup of order $12$, and thus it's isomorphic to $A_5$.

$G$ is a simple group of order $60$. If I can show that $G$ has a subgroup of order $12$, then $G \cong A_5$.
Let $P \in Syl_2(G).$ Let's look at two cases (because we know that the number of Sylow 2-subgroups of a simple group of order $60$ is either $5$ or $15$. In the latter case, at least two Sylow 2-subgroups intersect non-trivially.)
Case 1: Let's assume that the number of Sylow 2-subgroups of $G$ is $5$. Thus, $|G: N_G(P)| = 5$, so $N_G(P)$ is a subgroup of $G$ of order $12$, done.
Case 2: Let's assume that the number of Sylow 2-subgroups of $G$ is $15$. Thus, (because we know that the number of Sylow 2-subgroups of a simple group of order $60$ is either $5$ or $15$. In the latter case, at least two Sylow 2-subgroups intersect non-trivially), we will find two distinct Sylow 2-subgroups $R$ and $S$ of order $4$. such that $|R\cap S| = 2$.
Let $x$ be the non-identity element of order $2$ in $R\cap S$. We'll find $|C_G(x)|$. every group of order $4$ is abelian, thus, both $R$ and $S$ are subgroups of $C_G(x)$. Thus, $|C_G(x)|$ is divisble by $4$ and is a divisor of $60$. Thus, $|C_G(x)|$ is $12, 20,$ or $60$. Also, we know that $G$ doesn't have a subgroup of order $20$ (see my proof below for that order). Also, $|C_G(x)| = 60$ means that $x$ is non-trivial element of the center of $G$. But $G$ is simple and non-abelian, and so its center is trivial. We conclude that $|C_G(x)| = 12$, so now we have a subgroup of order 12. done.
Also, the subgroups of order $12$ in $A_5$ are isomorphic to $A_4$. because $A_5$ has a subgroup of order $12$, we also know that $A_4 \le A_5$. Hence, we can say now that $A_5$ does have subgroups of order $12$ isomorphic to $A_4$. ($A_4$ is the even permutation on four objects and hence there are at least five copies of $A_4$ in $A_5$).

Order 15, 20, 30 all together:

The only (proper) divisors of $|A_5|=60=2^2\cdot 3\cdot 5$ greater than $12$ are $15=3\cdot 5, 20=2^2\cdot 5,$ and $30=2\cdot 3 \cdot 5$.  Any subgroup of index $2$ is necessarily normal, and groups whose order is the product of three primes are solvable, so since $A_5$ is not solvable so it may not contain a subgroup of order $30$.  If $H$ is a subgroup of order $15$, then $H$ is cyclic, but an easy computation shows that in $A_5$ elements of order $5$ and elements of order $3$ do not commute.  Therefore it remains to be shown that $A_5$ can't have a subgroup of order $20$.
Now, notice that $A_5$ does have a subgroup $K$ of order $12$ - in particular, $K$ is an isomorphic copy of $A_4$.  Suppose that there exists a $J\leqslant A_5$ of order $20$ and notice that $[A_5:J]$ and $[A_5:K]$ are coprime.  Then $A_5=JK$ and $[J:J\cap K]=[A_5:K]$.  So $|J\cap K|=4$.  Thus $J\cap K\in\operatorname{Syl}_2(J)\cap\operatorname{Syl}_2(K)$.  We observe that any $H_3\in\operatorname{Syl}_3(K)$ normalizes $J \cap K$, and in particular, $H_3$ acts fixed point freely on $J \cap K$.  We see that the Sylow $5$-subgroup $H_5$ of $J$ must normal in $J$, so $J\cap K$ acts nontrivially on $H_5$.  It follows that $H_3$ acts faithfully on $H_5$, but this is impossible since $\operatorname{Aut}(H_5)$ has order $4$.  This completes the proof.

Order $20:$ (another interesting proof)

A group of order 20 has a normal Sylow 5-subgroup that is cyclic, $C_5$. We know that the Sylow 2-subgroup of $A_5$ is isomorphic to the Klein 4-group (no 4-cycles in $A_5$).
Assume $G$ is a group of order 20 with the above properties: $C_5\lhd G$, and $V_4\le G$. Then
conjugation in $G$ gives an action of $V_4$ on $C_5$, and hence a homomorphism
$\phi: V_4\rightarrow Aut(C_5)$. We can easily check that the automorphism group of $C_5$ is cyclic of order 4. It is generated by the automorphism $\sigma:x\mapsto x^2$. This implies that $\phi$ cannot be injective, in other words there is an element $g\in V_4$, $g\neq1_G,$ such that
$g$ commutes with all the elements of $C_5$. The group $\langle C_5\cup\{g\}\rangle$ is thus cyclic of order $10$.
But the group $A_5$ has no elements of order ten. Therefore it cannot have a subgroup like $G$ either. Therefore it cannot have any subgroups of order $20$.

Order $60:$ (with $PSL_2(5)$)

$PSL_2(5)$ can be considered as group of Mobius transformations
$$z\mapsto \frac{az+b}{cz+d}, (a,b,c,d\in\mathbb{Z}_5, ad-bc=1)$$
for $z\in \{0,1,2,3,4\}\cup\{\infty\}$, where $\{0,1,2,3,4\}=\mathbb{Z}_5$ and $\infty=1/0=2/0=...=4/0$, and some conventions similar to this.
The group $PSL_2(5)$ acts on these six symbols, whereas we want an action on $5$ symbols to show that it is isomorphic to $A_5$. So how to proceed.
The way I would like to proceedis to do the following:
In $PSL_2(5)$, find an element $A$ of order $2$, $B$ of order $3$ such that product $AB$ has order $5$.
This is quite easier: consider $A(z)=-1/z$. You see that it is of order $2$.
To get element of order $3$, note that if $B^3=I$ in $2\times 2$ matrix  form then $B$ satisfies polynomial $t^3-1=(t-1)(t^2+t+1)$; the second factor is irreducible over $Z_5$; so take companion matrix $\begin{bmatrix} 0 & -1 \\ 1 & -1\end{bmatrix}$.
The corresponding Mobius map is $B(z)=(0.z-1)/(1.z-d)=-1/(z-1)$; check- this is of order $3$ (i.e. $B^3(z)=z$)
Finally, consider $AB(z)$; it is $AB(z)=z-1$, great! this is of order $5$ since this permutes $0,1,2,3,4$ in fashion of cycle of order $5$ and leaves $\infty$ fixed (by additive convention with $\infty$: $\infty+a=a+\infty=\infty$).
Thus, we found elements $A,B$ of order $2,3$ respectively such that $AB$ has order $5$. The group $A_5$ has presentation of this form:
$$A_5=\langle x_1,x_2: x_!^2=1, x_2^3=1, (x_1x_2)^5=1\rangle.$$
This gives a surjective homomorphism from $PSL_2(5)$ to $A_5$ ($A\mapsto x_1, B\mapsto x_2$).
Finally $PSL_2(5)$ and $A_5$ have same orders; the surjective homomorphism should be isomorphism. Thus, $PSL_2(5) \cong A_5$.


text:
Q: How to change background color in ttk python I've made a simple gui age converter app but i want to change its bg color to black.
The problem is in the ttk frame.i don't know how to configure its bg color.
I have tried different methods but that didn't work.
i would be grateful if you guys could help.
here is the code
from tkinter import *
from tkinter import ttk
from PIL import Image

def calculate(*args):
        try:
            age_sec = int(age.get())
            age_sec = age_sec * 12 * 365 * 24 * 60 * 60
            age_seconds.set(age_sec)
        except:
            age_seconds.set('Either the field is empty or \n value is not numeric.')

root = Tk()
root.title("Converter")
root.configure(background="black")
mainframe = ttk.Frame(root, padding = "6 6 12 12")
mainframe.grid(column = 0, row = 0, sticky = (N, W, E, S))
mainframe.columnconfigure(0, weight = 1)
mainframe.rowconfigure(0, weight = 1)

#mainframe['borderwidth'] = 2
#mainframe['relief'] = 'groove'

age = StringVar()
age_seconds  = StringVar()

ttk.Label(mainframe,  foreground = "#4D4E4F", text = "Enter your Age: ").grid(column = 1, row = 1, sticky = E)
age_entry = ttk.Entry(mainframe, width = 30, textvariable = age)
age_entry.grid(column = 2, row = 1, sticky = (W, E))

ttk.Label(mainframe, foreground = "#4D4E4F", text = "your age in seconds is ").grid(column = 1, row  = 2, sticky = (E))

ttk.Label(mainframe, textvariable = age_seconds, background = "lightyellow", foreground = "#727475", width = 30).grid(column = 2, row  = 2, sticky = W)

#Mouse Events...\\

butt_image = PhotoImage(file = 'images.gif')
ttk.Button(mainframe, compound = TOP, text = "Hit Now", image =butt_image,  cursor = "hand2", width= 30, command = calculate).grid(column = 2, row  = 4,  sticky = W)
l2 = ttk.Label(mainframe,foreground = "#4D4E4F", text = "Mouse Events: ").grid(column = 1, row = 3, sticky = E)
l = ttk.Label(mainframe,background = "lightyellow", foreground = "#727475", text = 'Measurement is starting...', width = 30)
l.grid(column = 2, row = 3, sticky = W)
l.bind('<Enter>', lambda e: l.configure(text = 'Moved Mouse Inside'))
l.bind('<Leave>', lambda e: l.configure(text = 'Mouse Moved Out'))
l.bind('<1>', lambda e: l.configure(text = 'left Mouse clicked'))
l.bind('<Double-1>', lambda e: l.configure(text = 'Double clicked'))
l.bind('<B1-Motion>', lambda e: l.configure(text = 'Left button drag to %d, %d' %(e.x, e.y)))
image = PhotoImage(file = 'waves.gif')
ttk.Label(mainframe, compound = CENTER, text = "Image text", font = ('roman', 9, 'normal'), foreground ='green', image = image).grid(column = 3, row = 1, sticky = (N, E))
#if '__name__' == '__main__':
for child in mainframe.winfo_children(): child.grid_configure(padx = 15, pady =  15)
age_entry.focus()
root.bind('<Return>', calculate)
root.mainloop()

A: A ttk.Frame does not have a background / bg option. To change it you need to use style.
See ttk.Frame Info
If you don't really need to use a ttk.Frame you can just switch to a tkinter.Frame


text:
Q: What causes libdispatch error EVFILT_MACHPORT in MacOSX Sierra? Good morning,
I am facing a crash in my application. When the user tries to start it, he waits like a minute and then a std::exception is raised. Really I could not reproduce the bug by myself, but it seems quite a common problem.
The only thing I could track is the following line in syslog:
BUG in libdispatch client: kevent[EVFILT_MACHPORT] monitored resource vanished before the source cancel handler was invoked
Then, I start to google it and I can not find much more...I can only "suppose" that is some problem with GCD (that I do not use afaik, or at least not directly...). What I saw in Internet is that it is related with MacOSX Sierra. But the majority of forum have no answer, just a lot of tries without a unique result. Maybe the only web page that seems a bit clear about a workaround (that I have not tested, and anyway I do not want to use) is this.
So...:

*

*someone has clear what can cause the exception in libdispatch?

*someone can give me some good link, official documentation or something?

*Is true that can be a bug in Sierra without updates?

*Could it be related with the installer of an application?

*Someone knows a way to reproduce this exception with a test program?

A: This libdispatch log message is not fatal, and is almost certainly not related to your crash, which sounds like an abort due to an uncaught C++ exception (without a crashreport/backtrace it is difficult to say anything more). libdispatch does not itself generate any C++ exceptions FWIW.
As to the meaning of that specific log message, it relates to the following section in the dispatch_source_create(3) manpage:

CANCELLATION:
       Important: a cancellation handler is required for file descriptor and mach port based sources in order
       to safely close the descriptor or destroy the port. Closing the descriptor or port before the cancellation handler has run may result in a race condition: if a new descriptor is allocated with the same
       value as the recently closed descriptor while the source's event handler is still running, the event
       handler may read/write data to the wrong descriptor.

If you see the EVFILT_MACHPORT "vanished" log message, somebody in your process has violated that API contract and deallocated a machport while a dispatch source was still monitoring it (causing the kernel to generate an EV_VANISHED kevent), see the source code.


text:
Q: iltering a list and storing result as named ranges _method Range of _global Failed I've used the code from this question:
VBA: Filtering a list and storing result as named ranges but it gave error 1004.
Dim DoesNamedRangeExistFlag As Boolean

Sub NameTheRanges()

ClearAllNamedRanges
Dim c As Range
For Each c In Sheets("Sheet1").Range("B2:B10")

    If Not DoesNamedRangeExist(c.Value) Then
        c.Offset(0, -1).Name = c.Value
    Else
        Union(Range(c.Value), c.Offset(0, -1)).Name = c.Value
    End If
Next c

End Sub

Function DoesNamedRangeExist(NR As String) As Boolean
Dim checker As Range
On Error Resume Next
Set checker = Sheets("Sheet1").Range(NR)

On Error GoTo 0
If checker Is Nothing Then
    DoesNamedRangeExist = False
Else
    DoesNamedRangeExist = True
End If

End Function

Sub ClearAllNamedRanges()
Dim NR
For Each NR In ActiveWorkbook.Names
    NR.Delete
Next
End Sub

A: You may be attempting an illegal name for the named range.
What is the value of c when the error occurs?
If it is, R or C or anything that already exists as a range reference i.e. A1 through XFD1048576 (in 2016), you will get the error described.
B2:B10 cannot contain something that is a valid cell reference.
The same thing will occur if there are any illegal characters or spaces (at start or within string) in the cell which are not allowed in named ranges e.g if starts with a number.

To find out more about naming conventions and illegal names see:

*

*Illegal range names

*And this excellent resource I just found by Martin Trummer: Excelnames

A: My problem was indeed on illegal names , but I caused another issue by changing an option to break on all errors which caused my to halt the whole code even on correct names. so disabling that option and debugging code where it breaks allowed me to fix the codes , thanks a lot for  Qhrr and Mr. Brian i'm sorry it was my first time to post on stackoverflow


text:
Q: Symfony 4: Updating an existing entity through a deserialized entity ends up with a new related item or with an ORMInvalidArgumentException That's my first question here on Stackoverflow.com and before I'll write to much. First the controller function:
/**
 * @Rest\Patch("/identifiers/v2/{id}")
 *
 * @ParamConverter("identifier")
 * @ParamConverter("identifierPatch", converter="fos_rest.request_body")
 */
public function patchAction(Identifier $identifier, Identifier $identifierPatch)
{
    $identifier->setLandingPage($identifierPatch->getLandingPage());
    $identifier->setIdentifier($identifierPatch->getIdentifier());
    $identifier->setIsUsed($identifierPatch->getIsUsed());

    $this->entityManager->flush();

    /**
     * Just for debugging...
     */
    $view = $this->view([
        'identifier' => $identifier,
        'identifierPatch' => $identifierPatch
    ]);

    return $this->handleView($view);
}

When i try to UPDATE an existing entity this way I get an ORMInvalidArgumentException with a message "A new entity was found through the relationship (...)"
When I set cascade={"persist"} on the related entity:
/**
 * @ORM\ManyToOne(targetEntity="App\Entity\LandingPage", inversedBy="identifiers")
 * @ORM\JoinColumn(nullable=false)
 * @Assert\NotNull()
 * @Serializer\Type("App\Entity\LandingPage")
 */
private $landing_page;

... the related entity will be inserted as new entity and that's not what I am looking for.
I could use $this->entityManager->merge($identifier) but that's not what I am looking for aswell, because I'll need to do some manual validations in future and I would like to return the entity as response (the related entity will be null when not updated) and $this->entityManager->merge() will be deprecated in Doctrine 3.
Question: Is there any way to update the given entity with the deserialized entity?
Greetings,
Danny Endert

EDIT (1):
Well, I guess i found a solution regarding this "issue".
services.yaml
jms_serializer.object_constructor:
    alias: jms_serializer.doctrine_object_constructor
    public: false

Now I'm not getting any exception and the related entity will not be inserted as new entity.


text:
Q: set Windows Defender protection in manual mode in Windows 10 I would like to set the Windows Defender protection service in manual mode (NOT disabled completely) so that:

*

*when Windows starts it is disabled

*i can run custom scans with MpCmdRun.exe

*i can temporally enable or disable protection according to my needs with some command like net start ...


text:
Q: Re-position locate me button on google maps [Android] I have a bottom sheet that has a visible peak of 200dp. I positioned the locate me button of google map over the bottom sheet, like this:

Sometimes i need to dismiss the bottom sheet, and I want to re-position the locate me button. To do this I call the same code which I called to position first the button, with different  value for bottom:
 val rlp = locationButton.layoutParams as (RelativeLayout.LayoutParams)
        rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0)
        rlp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE)
        rlp.setMargins(0, 0, 30, bottomValue)

I have debuged and the locationButton position has new values, but it is still on the same position, so the map looks like this:

What I possible do wrong?


text:
Q: how do I add a field set to a custom visual force page running a quote wizard I am new at this, 10 days on the job, so, please forgive me if I am asking something obvious.
I have a Custom Visual Force Page that runs within a QuoteWizard.  I need to add some fields to this page, and, I was thinking the best way was to create a field set, and add that to the page, but, I haven't figured out how to do that yet, lots of information on the internet, but, I haven't been able to nail down the exact issue I am dealing with.
Thanks,
Mark

A: Field sets can be directly referenced in Visualforce by combining the $ObjectType global variable with the keyword FieldSets. For example, if your Contact object has a field set called properNames that displays three fields, your Visualforce page can reference the field data through the following iteration:
<apex:page standardController="Contact">
    <apex:repeat value="{!$ObjectType.Contact.FieldSets.properNames}" var="f">
        <apex:outputText value="{!Contact[f]}" /><br/>
    </apex:repeat>
</apex:page>

you can access the labels and data types for the fields in properNames like this:
<apex:page standardController="Contact">
    <apex:pageBlock title="Fields in Proper Names">
        <apex:pageBlockTable value="{!$ObjectType.Contact.FieldSets.properNames}" var="f">
            <apex:column value="{!f}">
                <apex:facet name="header">Name</apex:facet>
            </apex:column>
            <apex:column value="{!f.Label}">
                <apex:facet name="header">Label</apex:facet>
            </apex:column>
            <apex:column value="{!f.Type}" >
                <apex:facet name="header">Data Type</apex:facet>
            </apex:column>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:page>


text:
Q: Mocking two maps in a class I have to test a class that injects two maps with springs.
I would like to mock both maps.
I use the Mock notation as follows :
@Mock
private Map<String, Integer> map1;

@Mock
private Map<String, Date> map2;

but I get the following error :
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.util.Date

It seems that only the first mocked map is used for both maps.
What am I doing wrong ?

A: As long as the type of the two fields are the same, mockito doesn't know to how to inject your mock by types. So it tries to inject it by name. In this case, looks like the name of fields in your class under test does not match to the mock object that you have created.
Here is the doc for @InjectMocks:

Field injection; mocks will first be resolved by type (if a single
  type match injection will happen regardless of the name), then, if
  there is several property of the same type, by the match of the field
  name and the mock name.

You can either rename your filed or use explicit mock names:
@Mock(name="foo")
private Map<String, Integer> map1;

@Mock(name="bar")
private Map<String, Date> map2;

But I don't think that this is the best solution. In case if the filed name will be renamed you will got the false negative test result: functionality works correct but test fails.
For me, the best solution is to refactor your code so the class under test receive the dependencies in the constructor. After that you can mock it like this:
@Mock
private Map<String, Integer> map1;

@Mock
private Map<String, Date> map2;

private ClassUnderTets cut;

@Before
public void setUp() throws Exception {
    cut = new ClassUnderTets(map1, map2);
}

Or even:
@Mock
private Map<String, Integer> map1;

@Mock
private Map<String, Date> map2;

@InjectMocks
private ClassUnderTets cut;

As mentioned in the docs:

Constructor injection; the biggest constructor is chosen, then arguments are resolved with
  mocks declared in the test only

A: Probably you have problem because you try to inject two mocks with the same interface (variable names does not match to properties for example)
Please take a look at second post from this topic for reference.

Property setter injection; mocks will first be resolved by type, then,
  if there is several property of the same type, by the match of the
  property name and the mock name.

A: try
@Mock
private Map map1;

@Mock
private Map map2;

instead
@Mock
private Map<String, Integer> map1;

@Mock
private Map<String, Date> map2;

Then you will just need to mock a behavior like:
when(map1).get("hello").thenReturn(25);
when(map2).get("birthday").thenReturn(new Date(2000, 07, 24));


text:
Q: JPA Named query join I've got an issue with JPA, I need to return a list of users but I always get the user the id is from
This one is working correctly and returns the users that you are following:
@NamedQuery(name = "User.findByFollowing",
                        query = "select User from User user join user.followers f where f.id=:id"),

This query always returns the user of the id parameter (param=1 returns user1 instead of all the users you are followed by)
  @NamedQuery(name = "User.findFollower",
            query = "select User, f from User user join user.followers f where user.id=:id")

The table looks like this, both columns are id's of the user table.
As you can see:

*

*user4 got 2 followers

*user3 got 1 follower

*user 2 is following 2 users

*user 1 is following 1 user

This is the user table

The follower table is generated by JPA with a arraylist
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    private List<User> followers = new ArrayList();

Now you've got some background info I will get to the point.
As user 2 I can see that i am following user3 and user 4. But if I am user 3 I can't see that user2 is following me (This always returns user3 in some way)
If you need more information feel free to ask

A: Why don't you do "select u from User u where u.id = :id" and access the followers via u.getFollowers() in your java code? You don't explicitly need the join if your entities have the relationship.


text:
Q: How to declare type/interface with dynamic props I'm trying to type an interface (or type) with the following logic:
interface MyArgs<Name, Id> {
  items: {
    [Name]: string,
    [Id]: string
  }[];
  idKey: string;
  nameKey: string;
}

In more detail:
I'm getting an array of items of an unknown type/interface (it's dynamic, they can be anything). While I could just type them as any[], I'd like to know if it's possible to be a bit more specific about their type, and pass Typescript the information that I do have:
each item will be having an id property (e.g: guid, id, uuid) and a name property (e.g: name, label, title). The exact idKey and nameKey are provided as arguments (idKey, nameKey).
I want to declare the values provided in idKey and nameKey as valid keys for items records (e.g:  { [idKey]: string; [nameKey]: string }(
What I tried above doesn't work. I also tried this:
interface MyArgs<Name, Id> {
  items: { <Name>: string; <Id> : string }[]
  idKey: string
  nameKey: string
}

which is, too, invalid.
How can I achieve this?
Note: if the above would be possible without having to type the values twice (once inside <> and once in the values of idKey and nameKey, that would be even more awesome).

A: Intersect mapped types (or rather, Records) to create the correct object type:
interface MyArgs<Name extends string, Id extends string> {
  items: (
    { [_ in Name]: string; } &
    { [_ in Id]: string; }
  )[];
  idKey: string;
  nameKey: string;
}

If you need to, you can also constrain Name and Id to more specific keys:
interface MyArgs<Name extends "name" | "label" | "title", Id extends "guid" | "id" | "uuid"> {

You could also use Records to simplify it further:
  items: (
    Record<Name, string> & Record<Id, string>
  )[];

Or even just:
  items: Record<Id | Name, string>[];


text:
Q: a.s. convergence to constant and expectation Is it true that, if $X_n$ converges a.s. to a constant $c$, then $\displaystyle\lim_{n\to\infty}\mathbb{E}(X_n) = c$? If yes, please, can you prove that?
Update: If it is false, is there a condition I can set to prove that it is true?

A: Suppose this was true. Then we would get the statement that if $|X_n - X| \to 0$ a.s., then $E(|X_n - X|) \to 0$. This is saying that almost sure convergence implies $L^1$ convergence. But this is false; convergence a.s. does not imply convergence in $L^1$. One counterexample is $X_n = n1_{(0, 1/n)}$ defined on $[0, 1]$. $X_n \to 0$ a.s. but $E(X_n) = \int_{0}^{1}n1_{(0, 1/n)} = 1$.


text:
Q: How to place divs on top of each other aligned horizontal I currently have this;

But what I want is this;

How do I css everything, I have tried but I fail to accomplish this. To start with, I need to split my svg in such a way that the top part is behind the login form, and the bottom part in front of the login form. But how to I get to get them over each other in the fist place?
My html;

            <form action="xxxx" method="post">

Wsdfgdfgb

                <input class="input" type="text" name="_username" placeholder="xxxx"
               value="xxxx" required />
                <input class="input" type="password" name="_password"
               placeholder="xxxx" required />

                    <input type="checkbox" id="remember_me" name="_remember_me" value="on" />
            Remember me

                <button>Log In</button>
            </form>

            <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
         width="500px" height="250px" viewBox="0 0 1920 960" enable-background="new 0 0 1920 960" xml:space="preserve">
                <g>
                    <path fill-rule="evenodd" clip-rule="evenodd" fill="#000" d="M64.91,510.275c1.152,15.744,5.364,30.809,10.41,45.648......"/>
                </g>
            </svg>

And my CSS;
body {
    background: #1AB394; /* fallback for old browsers */
    background: -webkit-linear-gradient(right, #1AB394, #008374);
    background: -moz-linear-gradient(right, #1AB394, #008374);
    background: -o-linear-gradient(right, #1AB394, #008374);
    background: linear-gradient(to left, #1AB394, #008374);
    font-family: "Roboto", sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

.container {
    position: absolute;
    left: 50%;
}

.login-page {
    position: relative;
    left: -50%;
    width: 360px;
    padding: 8% 0 0;
    margin: auto;
}

.svg-container {
    position: relative;
    left: -50%;
    z-index: 1000;
}

form {
    position: relative;
    z-index: 1;
    background: #FFFFFF;
    max-width: 360px;
    margin: 0 auto 100px;
    padding: 45px;
    box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.2), 0 5px 5px 0 rgba(0, 0, 0, 0.24);
}

form h1 {
    text-align: center;
    margin: 0 0 15px;
    padding: 0;
    font-size: 36px;
    font-weight: 300;
    color: #1a1a1a;
}

form input[type="text"], form input[type="password"] {
    font-family: "Roboto", sans-serif;
    outline: 0;
    background: #f2f2f2;
    width: 100%;
    border: 0;
    margin: 0 0 15px;
    padding: 15px;
    box-sizing: border-box;
    font-size: 14px;
}

form input[type="checkbox"] {
    font-family: "Roboto", sans-serif;
    outline: 0;
    background: #f2f2f2;
    border: 0;
    margin: 0 0 15px;
    padding: 15px;
    box-sizing: border-box;
    font-size: 14px;
}

form .text {
    color: #b3b3b3;
    font-size: 14px;
}

form .err {
    color: #EF3B3A;
    font-size: 14px;
    text-align: center;
    margin: 0 0 15px;
}

form button {
    font-family: "Roboto", sans-serif;
    text-transform: uppercase;
    outline: 0;
    background: #1AB394;
    width: 100%;
    border: 0;
    padding: 15px;
    color: #FFFFFF;
    font-size: 14px;
    -webkit-transition: all 0.3 ease;
    transition: all 0.3 ease;
    cursor: pointer;
}

form button:hover,form button:active,form button:focus {
    background: #18A689;
}

A: Let both .login-page and .svg-container have position: absolute, give them both a z-index, make the z-index of .svg-container higher than the other one and adjust the positions accordingly.

A: If you don't have a complicated design for it, this is what you could try out, using float and centering with margin, width, and height. Then use padding for the north face to keep it at the position you want it at, both the divs.
For example, something simple would be:

#one
    {
    background-color: rgba(0,0,0,0.5);
    width: 60%%;
    height: 50vw;
    margin: auto;
    padding: 20vw 0 0 0;
    }

#two
    {
    float: left;
    background-color: rgba(0,255,38,0.6);
    width: 110%;
    height: 10vw;
    margin: auto;
    margin: 10vw 0 0 0;
    padding: 30vw 0 0 0;
    }

test

test

This is roughly how I would do it. I generally don't overlay things unless it's necessary, I'm better off directly editing both images and overlaying one on the other, and replace it with the edited one.
I'm still learning, there are definitely way better and easier and less confusing ways to do it, but this is my method. I can understand this very easily, so I go with it.
I hope this helps in any way at all.


text:
Q: Domain is currently unable to handle this request I'm not really good with HTML, PHP, or other coding things. I really don't know how to make this work, but I made a submit form for my website. I did change the email already but I still get an error:
the 'domain' is currently unable to handle this request.
I got this code from here too and now I don't know what to do
THIS IS THE HTML FORM

<form class="form-horizontal" role="form" method="post" action="share.php">

    Name

        <input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name" value="">

    Email

        <input type="email" class="form-control" id="email" name="email" placeholder="example@domain.com" value="">

  Category

 <select id="category" name="category" class="form-control">
  <option value="">Student</option>
  <option value="">Parent</option>
  <option value="">School</option>
  </select>

    Message

        <textarea class="form-control" rows="4" name="message"></textarea>

    2 + 3 = ?

        <input type="text" class="form-control" id="human" name="human" placeholder="Your Answer">

        <input id="submit" name="submit" type="submit" value="Send" class="btn btn-primary">

        <! Will be used to display an alert to the user>

THIS IS THE PHP
<?php
if (isset($_POST["submit"])) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $category = $_POST['category'];
    $message = $_POST['message'];
    $human = intval($_POST['human']);
    $from = 'IKB FORM';
    $to = 'EMAIL';
    $subject = 'Importante Ka Ba User ';

    $body = "From: $name\n E-Mail: $email\n Message:\n $message";

    // Check if name has been entered
    if (!$_POST['name']) {
        $errName = 'Please enter your name';
    }

    // Check if email has been entered and is valid
    if (!$_POST['email'] || !filter_var($_POST['email'],    FILTER_VALIDATE_EMAIL)) {
        $errEmail = 'Please enter a valid email address';
    }

    if (!$_POST['category'] {
        $errCategory = 'Please enter a valid email address';
    }

    //Check if message has been entered
    if (!$_POST['message']) {
        $errMessage = 'Please enter your message';
    }
    //Check if simple anti-bot test is correct
    if ($human !== 5) {
        $errHuman = 'Your anti-spam is incorrect';
    }

// If there are no errors, send the email
    if (!$errName && !$errEmail && !$errCategory && !$errMessage && !$errHuman) {
       if (mail ($to, $subject, $body, $from)) {
        $result='
Thank You! I will be in    touch
';
}      else {
        $result='
Sorry there was an error sending your message. Please try again later
';
    }
}
    }
?>

A: You forgot a closing parentheses ) in the following if statement:
if (!$_POST['category'] {

change it to
if (!$_POST['category']) {

If you have problems with scripts in the future make sure you enable error reporting. These error reports will provide a lot of information on what has happened and make debugging a lot easier. This answer explains how you can enable it.


text:
Q: How can I tell whether a network interface is physical (device) or virtual (alias)? I have a small home router running OpenWrt (Kind of embedded Linux for routers). It has five Ethernet ports, one labeled WAN and four labeld LAN 1 to 4. It has the following Network Interfaces defined as per ifconfig:
root@TIBERIUS: ~ > ifconfig | grep Link
br-lan    Link encap:Ethernet  HWaddr 00:23:CD:20:C3:B0
eth0      Link encap:Ethernet  HWaddr 00:23:CD:20:C3:B0
lan1      Link encap:Ethernet  HWaddr 00:23:CD:20:C3:B0
lan2      Link encap:Ethernet  HWaddr 00:23:CD:20:C3:B0
lan3      Link encap:Ethernet  HWaddr 00:23:CD:20:C3:B0
lan4      Link encap:Ethernet  HWaddr 00:23:CD:20:C3:B0
lo        Link encap:Local Loopback
pppoe-wan Link encap:Point-to-Point Protocol
wan       Link encap:Ethernet  HWaddr 00:23:CD:20:C3:B0
wlan0     Link encap:Ethernet  HWaddr 00:23:CD:20:C3:B0

As you can see, quite a number of devices, but only one MAC address.
I understand some of those devices are virtual. Let's put aside lo and pppoe-wan, that's the loopback device and my PPPoE Connection. But for the rest of those, how am I supposed to be able to tell whether they are physical or virtual? I understand there is a naming convention for labeling virtual Interfaces like eth0.1, but that is obviously not adhered to here. Let's see the Output of ifconfig for two of these interfaces:
root@TIBERIUS: ~ > ifconfig wan
wan       Link encap:Ethernet  HWaddr 00:23:CD:20:C3:B0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:15007 errors:0 dropped:0 overruns:0 frame:0
          TX packets:12055 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:13341276 (12.7 MiB)  TX bytes:1831757 (1.7 MiB)

root@TIBERIUS: ~ > ifconfig eth0
eth0      Link encap:Ethernet  HWaddr 00:23:CD:20:C3:B0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:25799 errors:0 dropped:0 overruns:23 frame:0
          TX packets:25294 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:15481996 (14.7 MiB)  TX bytes:15160380 (14.4 MiB)
          Interrupt:4

Apart from the obscure Detail of txqueuelen having a non-zero for eth0, the only striking difference is that eth0 has an Interrupt entry, which as far as I know is a Hardware Feature. So is that how you tell a Network Interface is physical or not, by looking for an Interrupt entry in ifconfig? Or is there a better way? A simple and straightforward way to find out whether a network device is physical or virtual?
Note there is a related question but while it does have an accepted answer, it isn't conclusive.
Update
In reply to derobert's answer, here's information derivd from ls -l /sys/class/net:
br-lan      -> ../../devices/virtual/net/br-lan
eth0        -> ../../devices/platform/ag71xx.0/net/eth0
lan1        -> ../../devices/platform/dsa.0/net/lan1
lan2        -> ../../devices/platform/dsa.0/net/lan2
lan3        -> ../../devices/platform/dsa.0/net/lan3
lan4        -> ../../devices/platform/dsa.0/net/lan4
lo          -> ../../devices/virtual/net/lo
pppoe-wan   -> ../../devices/virtual/net/pppoe-wan
wan         -> ../../devices/platform/dsa.0/net/wan

[Addendum to this list: wlan0 would have shown up as well as wlan0 -> ../../devices/platform/ath9k/net/wlan0, but when I copied the above list I had WLAN disabled, which is why it didn't show up.]
I would say eth0 is the only device. Not clear what dsa.0 is.
And in reply to Bryan Agee's answer:
root@TIBERIUS: ~ > cat /etc/config/network

config interface 'loopback'
        option ifname 'lo'
        option proto 'static'
        option ipaddr '127.0.0.1'
        option netmask '255.0.0.0'

config interface 'eth'
        option ifname 'eth0'
        option proto 'none'

config interface 'lan'
        option ifname 'lan1 lan2 lan3 lan4'
        option type 'bridge'
        option proto 'static'
        option ipaddr '192.168.33.1'
        option netmask '255.255.255.0'

config interface 'wan'
        option ifname 'wan'
        option proto 'pppoe'
        option username '…'
        option password '…'

A: Per sysfs man page

/sys/class/net

Each of the entries in this directory is a symbolic link representing one of the real or virtual networking devices that are visible in the network namespace of the process that is accessing the directory.  Each of these symbolic links refers to entries in the /sys/devices directory.

So, all one needs to do is check if there is a pyhiscal device linked to the network interface in the sysfs filesystem, e.g. /sys/class/net/eth0/device
A simple script if you know the interface name:
#!/bin/bash

iface=eth0

if test -e /sys/class/net/${iface}/device; then
        echo $iface
fi

If you want to print the interface names for all physical devices:
#!/bin/bash

while IFS='\n' read p1 line ;do
        iface=$(echo "$p1" | sed -n 's/[0-9]: \(.*\):.*/\1/p')

        if test -n $iface && ip addr show dev $iface >/dev/null 2>&1; then
                if test -e /sys/class/net/${iface}/device; then
                        echo $iface
                fi
        fi
done < <(ip address)

And here's a one-liner that will do the trick:
echo $(cd /sys/class/net; dirname */device)

suitable for use in for loops and such, like:
for interface in $(cd /sys/class/net; dirname */device); do
    echo $interface
    # Do whatever else you may need to do with $interface
done

A: I would start by looking in /etc/network/config ; most distros have a similar file to define and configure network devices. In debian/Ubuntu, it's /etc/network/interfaces. If you were to post the contents of that, we could identify alias, bond, and bridge entries; the rest would be your physical devices.
By looking at the ifconfig output, you can tell (as you mentioned) by the devices that have interrupts (IRQs); many also have memory assigned, which virtual interfaces don't.
You can't ever judge by mac addresses alone, since bonds (link aggregation) will override the mac of individual devices, and bridges will use the same. So if you have two devices bonded and bridged--a common configuration for HA virtual hosts and routers--there will be four devices with the same mac:
eth0  - physical device 1
eth1  - physical device 2
bond0 - the virtual device that uses either or both of the above
br0   - the bridge that uses bond0 and allows sharing/forwarding across bond0

Clearly the aliases used in openwrt are not the ones above, but the concept holds; I used these because they are standard practice.

A: You can check /sys:
anthony@Zia:/sys/class/net$ ls -l /sys/class/net/
total 0
lrwxrwxrwx 1 root root 0 Dec 11 15:38 br0 -> ../../devices/virtual/net/br0
lrwxrwxrwx 1 root root 0 Dec 11 15:38 lan -> ../../devices/pci0000:00/0000:00:1e.0/0000:07:01.0/net/lan
lrwxrwxrwx 1 root root 0 Dec 11 15:38 lo -> ../../devices/virtual/net/lo
lrwxrwxrwx 1 root root 0 Dec 11 15:38 tun0 -> ../../devices/virtual/net/tun0

So, actual devices show in /sys/class/net. Note that aliases (like lan:0) do not (so you can tell which are aliases). And you can clearly see which are actual hardware (lan) and which aren't (br0, lo, tun0).
to clarify
You can tell which are real in the above because the virtual ones are all in virtual. And lan is on the PCI bus.
In your case, you have six: eth0, wan, and lan1–4. This is rather odd, since you say you only have five ports total. I'd guess eth0 is actually hardwired to a a switch-ish chip, and the other 5 ports are ports on that switch. wlan0 is probably real as well (would be the wireless adapter), though it isn't showing in /sys….
So, I'd say that for all practical purposes, your real ports are wan, lan1–4, and wlan0. br-lan is a bridge set up to make all 4 lan ports function as a switch (so you might be able to split that switch).

A: I was trying to figure out how to get a list of virtual can (vcan) devices and came up with the following:
ip -details -oneline link | grep vcan

This will list only the virtual can devices.
If you are interested in only getting back a list of vcan device names, then this should work:
ip -details -oneline link | grep vcan | awk -F': ' '{print $2}'

A: Assuming your interface MAC address was not spoofed, you can try to use ethtool:
ethtool -P {Network interface name}

"Permanent address: 00:00:00:00:00:00" will indicate it's a virtual network interface.
The following bash loop will display MAC address for all network interfaces:
for i in $(ip -o link show | awk -F': ' '{print $2}'); \
do mac=$(ethtool -P $i) \
&& printf '%-10s %-10s\n' "$i" "$mac"; \
done

lo         Permanent address: 00:00:00:00:00:00
enp5s0f0   Permanent address: 44:1e:a1:73:39:c8
enp4s0f0   Permanent address: 00:9c:02:b0:ef:20
enp5s0f1   Permanent address: 44:1e:a1:73:39:c9
enp4s0f1   Permanent address: 00:9c:02:b0:ef:24
virbr1     Permanent address: 00:00:00:00:00:00
virbr1-nic Permanent address: 00:00:00:00:00:00
virbr0     Permanent address: 00:00:00:00:00:00
virbr0-nic Permanent address: 00:00:00:00:00:00
vnet0      Permanent address: 00:00:00:00:00:00
vnet1      Permanent address: 00:00:00:00:00:00

A: I think that just checking if the value of /sys/class/net/<interface>/type is 1 (ARPHRD_ETHER) should be enough to understand if the device is a physical one.
http://lxr.linux.no/linux+v3.0/include/linux/if_arp.h#L30
eg.
basename $(dirname grep -l ^1$ /sys/class/net/*/type)


text:
Q: Changing output text for dice rolls I am trying to code digital dice that outputs something like this:

1: 1 of 36 Rolls  2.7777%
2: 2 of 36 Rolls  5.5555%
3: 3 of 36 Rolls  8.3333%

Not quite sure how to do that but this is the code I have.
import random
import colorama

from colorama import Fore, Style

random.seed()

ROLLED = {i: 0 for i in range(1, 7)}
ITERATIONS = int(input(Fore.LIGHTRED_EX + "How many times would you like to roll the dice?\n"))

Style.RESET_ALL

def probability():
    print(Fore.LIGHTWHITE_EX+"Calculation of probability:")
    for key, count in ROLLED.items():
        print("\t{}: {:.2f}".format(key, count*100./ITERATIONS*1.))

for _ in range(ITERATIONS):#for the inputted range for the iterations
    ROLLED[random.randint(1, 6)] += 1

probability()

I don't know how to do that. could use help/tips to find out.

A: You can change the for loop in which you are rolling to this:
for roll in range(1,ITERATIONS+1):
    ROLLED[random.randint(1, 6)] += 1
    print("{} of {} Rolls {}%".format(roll,ITERATIONS,round(100/ITERATIONS*roll,4)))

Also don't forget to import random somewhere
Output
How many times would you like to roll the dice?
36
1 of 36 Rolls 2.7778%
2 of 36 Rolls 5.5556%
3 of 36 Rolls 8.3333%
4 of 36 Rolls 11.1111%
5 of 36 Rolls 13.8889%
6 of 36 Rolls 16.6667%
7 of 36 Rolls 19.4444%
8 of 36 Rolls 22.2222%
9 of 36 Rolls 25.0%
10 of 36 Rolls 27.7778%
11 of 36 Rolls 30.5556%
12 of 36 Rolls 33.3333%
13 of 36 Rolls 36.1111%
14 of 36 Rolls 38.8889%
15 of 36 Rolls 41.6667%
16 of 36 Rolls 44.4444%
17 of 36 Rolls 47.2222%
18 of 36 Rolls 50.0%
19 of 36 Rolls 52.7778%
20 of 36 Rolls 55.5556%
21 of 36 Rolls 58.3333%
22 of 36 Rolls 61.1111%
23 of 36 Rolls 63.8889%
24 of 36 Rolls 66.6667%
25 of 36 Rolls 69.4444%
26 of 36 Rolls 72.2222%
27 of 36 Rolls 75.0%
28 of 36 Rolls 77.7778%
29 of 36 Rolls 80.5556%
30 of 36 Rolls 83.3333%
31 of 36 Rolls 86.1111%
32 of 36 Rolls 88.8889%
33 of 36 Rolls 91.6667%
34 of 36 Rolls 94.4444%
35 of 36 Rolls 97.2222%
36 of 36 Rolls 100.0%
Calculation of probability:
    1: 13.89
    2: 22.22
    3: 13.89
    4: 22.22
    5: 11.11
    6: 16.67

As additional info:
Because you are using python 3 the / is a "normal" division. Basically: 5/2 = 2.5 while //is the integer division: 5//2 = 2
So you can change count*100./ITERATIONS*1. to count*100/ITERATIONS without the float casting magic.


text:
Q: react antd Loading Branch dropdown after selecting company drop down in table inline edit I have a table which displays the list of company related information, while we are trying to edit a company related information in table, Changing the company id, needs to fetch and populate branch dropdown associated with the changed company value
Here is the code for company dropdown and branch dropdown.
var companyData =[];
var branchData =[];

axios.get('http://localhost:8000/masters/selectcompany').then((result) => {
    companyData = result.data;
)};

const handleChangebranchid = (e) => {
  var value = e;
  axios.get('http://localhost:8000/masters/branchselect?companyid='+value).then((result) => {
    branchData = result.data;

})}

const BranchSelect = () => {
  return (
    <Select
    placeholder="branch"
     onChange={(value) => handleChange(value)}
    allowClear
    >
      {branchData.map(branch =>
      <Option value={branch.value}>{branch.value}</Option>
    )}
    </Select>
  )
}

const CompSelect = () => {
  return (
    <Select
    placeholder="companyid"
    onChange={handleChangebranchid}
    allowClear
  >{companyData.map(company =>
    <Option value={company.value}>{company.name}</Option>
  )}
  </Select>
  )
}
})

return(
      <Form.Item
        style={{
          margin: 0,
        }}
        name='company_id'
        rules={[
          {
            required: true,
            message: `Company is required.`,
          },
        ]}
      >
        <CompSelect />
      </Form.Item>
      <Form.Item
        style={{
          margin: 0,
        }}
        name='branch_id'
        rules={[
          {
            required: true,
            message: `Branch is required.`,
          },
        ]}
      >
        <BranchSelect />
      </Form.Item>
)

Please anyone help me to get rid from this.
Thanks in advance.

A: e refers to the entire event in handleChangebranchid. You have to use e.target.value to execute the code
change the following
const handleChangebranchid = (e) => {
  var value = e;
  axios.get('http://localhost:8000/masters/branchselect?companyid='+value).then((result) => {
    branchData = result.data;

})}

to
const handleChangebranchid = (e) => {
  var value = e.target.value;
  axios.get('http://localhost:8000/masters/branchselect?companyid='+value).then((result) => {
    branchData = result.data;

})}


text:
Q: Grails formRemote - how to avoid redirect on multi form? I have a master controller named Screening.
I have build view workflow for this controller (e.g : create, edit, list, show).
On my edit view I'm using Jquery TABS (each tab get content from a template associated to a domain). So to sum up :
Controller (Screening) -> Edit View -> tabs -> Eligibility Inclusion(tab - template/domain)
                                               Eligibility Exclusion(tab - template/domain)
                                               Demographics(tab - template/domain)

So, in my Screening edit view, I'm using formRemote to add template part, ex :

Demographics

<g:formRemote url="[controller:'demographics', action:'update']" update="ajaxMessage" name="demographicsForm">
<g:actionSubmit value="Save" action="update" />
<g:render template="/demographics/editDemographics" model="[demographicsInstance:demographicsInstance]" />
</g:formRemote>

I would like to keep validations/saving on Screening view, how can I handle this ?
Actually, if users try save (or if validation failed), they are redirected to demographics controller/view ; how to avoid this ? I don't want users to be redirected.
Is there a best way to handle multi-forms (with template/domain association) in one controller/domain ?

A: This sounds doing the stuff :
Controller :
def saveRemote = {

    def remoteT1Instance = new RemoteT1(params)
    if (remoteT1Instance.save(flush: true)) {
        flash.message = "${message(code: 'default.created.message', args: [message(code: 'remoteT1.label', default: 'RemoteT1'), remoteT1Instance.id])}"
    }
    else {
        flash.message = null
    }
    render(template: "remote", model: [remoteT1Instance: remoteT1Instance])
}

index.gsp :

  <g:render template="/remoteT1/remote"/>

_remote.gsp (template) :
<g:if test="${flash.message}">

${flash.message}

            </g:if>
            <g:hasErrors bean="${remoteT1Instance}">

                <g:renderErrors bean="${remoteT1Instance}" as="list" />

            </g:hasErrors>

            <g:formRemote
              name="editForm"
              url="[controller:'remoteT1', action:'saveRemote']"
              update="updateArea">

                                    <g:message code="remoteT1.nom.label" default="Nom" />

                                    <g:textField name="nom" value="${remoteT1Instance?.nom}" />

                                    <g:message code="remoteT1.prenom.label" default="Prenom" />

                                    <g:textField name="prenom" value="${remoteT1Instance?.prenom}" />

                                    <g:message code="remoteT1.password.label" default="Password" />

                                    <g:textField name="password" value="${remoteT1Instance?.password}" />

                    <input type="submit" value="Register"/>

            </g:formRemote>

If I try to use :
update="[success:'reply2', failure:'updateArea']" in my g:formRemote, it sound not working, I get 2 div (the old one and new one). I think it's a javascript issue.
Did somebody get something better ?


text:
Q: Cannot build cordova android app Today I wanted to update my app in google play store but got the following error:

My config.xml looks like:
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<widget
    id="com.bla.blabla.bla"
    version="1.3.8"
    xmlns="http://www.w3.org/ns/widgets"
    xmlns:cdv="http://cordova.apache.org/ns/1.0"
    xmlns:gap="http://phonegap.com/ns/1.0">

    <name>MyApp</name>

    <author>MyName</author>

    <preference name="AutoHideSplashScreen" value="false" />

    <content src="index.html"/>

    <access origin="*"/>
    <allow-navigation href="*" />

    <!-- START: Android and iOS Quirks -->
    <preference name="FadeSplashScreen" value="false"/>

    <!-- START: Android section -->
    <preference name="android-minSdkVersion" value="17" />

    <!-- android quirks -->
    <preference name="SplashScreen" value="screen" />
    <preference name="SplashScreenDelay" value="10000" />

    <platform name="android">
        <splash src="www/resources/device/android/splash/land/hdpi.png" density="land-hdpi"/>
        <splash src="www/resources/device/android/splash/land/hdpi.png" density="land-ldpi"/>
        <splash src="www/resources/device/android/splash/land/hdpi.png" density="land-mdpi"/>
        <splash src="www/resources/device/android/splash/land/hdpi.png" density="land-xhdpi"/>

        <splash src="www/resources/device/android/splash/port/hdpi.png" density="port-hdpi"/>
        <splash src="www/resources/device/android/splash/port/ldpi.png" density="port-ldpi"/>
        <splash src="www/resources/device/android/splash/port/mdpi.png" density="port-mdpi"/>
        <splash src="www/resources/device/android/splash/port/xhdpi.png" density="port-xhdpi"/>

        <icon src="www/resources/device/android/ldpi.png" density="ldpi" />
        <icon src="www/resources/device/android/mdpi.png" density="mdpi" />
        <icon src="www/resources/device/android/hdpi.png" density="hdpi" />
        <icon src="www/resources/device/android/xhdpi.png" density="xhdpi" />
    </platform>
     <!-- END: Android section -->

</widget>

My build script looks like:
    call cordova platform add android

    call cordova plugin add cordova-plugin-device
    call cordova plugin add cordova-plugin-file
    call cordova plugin add cordova-plugin-file-transfer
    call cordova plugin add cordova-plugin-network-information
    call cordova plugin add cordova-plugin-splashscreen
    call cordova plugin add cordova-plugin-inappbrowser
    call cordova plugin add cordova-plugin-whitelist
    call cordova plugin add cordova-plugin-file-opener2

    call cordova build android

What could be the problem? Some months ago this script worked. I searched a lot in the web but did not find the solution. Mostly I read that the solution is to edit the AndroidManifest.xml but I am in cordova and not in a native android app development so I cannot edit the AndroidManifest.xml.

A: Ok now I resolved it by installing specific version of cordova:
npm install -g cordova@5.4.0

Before there was cordova 6.0.0 installed. I have no idea what changed from 5.4.0 to 6.0.0.


text:
Q: Graph Connectivity Proof Suppose we have an adjacency matrix G representing an n-node graph.  So G[i, j] is 1 if there's an edge from i to j and 0 otherwise.  We can think of each entry as a turned over slip of paper with a 1 or 0 on it.
My text claims the lower bound on the number of times we need to query the matrix to determine if the graph is connected is n * (n-1) / 2.  I'm a bit confused by the proof of this.
Proof: here is the strategy for the adversary: when the algorithm asks us to flip over a slip of paper, we return 0 unless that would force the graph to be disconnected.
1) This seems to imply that in some cases, if we return a 0, it's impossible for us to add edges later that would lead to a path from u to v.  But surely the graph can still be connected even if we return a 0 above...right?
Claim: we maintain the invariant that for an y un-asked pair (u, v) the graph revealed so far has no path from u to v
Proof: Suppose there were a path from u to v.  Then we can remove the last edge (u', v') revealed on that path.  We could have answered 0 for that and kept the same connectivity in the graph by having an edge (u, v).  This contradicts the definition of our adversary strategy.
End of proof: Suppose there were an algorithm that finished without examining every slip of paper.  Consider some unasked pair (u, v).  If the algorithm claims the graph is connected, we show all-zeroes for the remaining unasked edges and this means there is no path from u to v, so the algorithm is wrong.
2. Could someone explain the italics?  I'm not seeing the connection...
On the other hand, if the algorithm says disconnected, we show all-ones for the remaining edges and the algorithm is wrong by the definition of our adversary strategy.
3. Couldn't the graph still be disconnected even if we show all ones?
Thanks!

A: *

*Suppose that we have a four-node graph. If the algorithm has queried and gotten "0" answers to 13 and 14, and then it asks about 12, then if the answer is "0", that means that the graph cannot be connected, because 1 is not connected to 2 (there's no direct path, and 1 has no other possible connection).

*At any given time, you can think of an edge as being a "yes", a "maybe", or a "no". Initially all edges are "maybes". Whenever the algorithm asks about an edge, it becomes a "yes" or a "no". The graph with the yes and maybe edges is the most connected input consistent with observations. The graph with the yes edges only is the least connected input consistent with the observations. The algorithm can return only when these graphs have the same connectivity status.


text:
Q: i have created link between list of students name and there profile The link is working  well when i click on any name of student it's going to profile page but in profile page its not fetching data from database through id and the link is not passing id can anyone solve it. Thanks in advance.
This is name list page
<?php

    $query="SELECT id,name,fname,phone FROM  student";
$resultset=$connection->query($query);

$count=0;
while($r=$resultset->fetch_assoc()){
    $count++;
echo "
".$count."	".$r["name"]."	".$r["fname"]."		".$r["phone"]."	<input type='checkbox' name='chb".$count."' value='".$r["id"]."'>

";

}
?>

This is profile page
$id = intval($_GET['id']);

$result=$connection->query("SELECT name,fname,gender,email,phone,address,image FROM student WHERE id=".$id."");

$rs=$result->fetch_assoc();

A: In your code you put a ' after id=' which means your href link ended after id=
Try removing the '
From this
_profile.php?id='".$r["id"]."'>

To this
_profile.php?id=".$r["id"]."'>


text:
Q: Binary Search in MongoDB array without index Ok, so I have a very big number of documents in a sharded collection, let's say 1million. Each document holds a SORTED array of documents of size 10000.
In order to access the top-level documents fastly, MongoDB uses the shard order plus the index to quickly find the document in question. Nonetheless, once I reach the document, then I have to look which set of sub-documents(in the array) satisfy my query. Now, I know this array is sorted but MongoDB doesn't. Also, creating 1Million indices is too expensive.
Therefore, my question is the following, is there a way to force MongoDB to binary search a sorted array without an index?

A: I think that using $where and passing in some custom javascript is your only hope:
https://docs.mongodb.org/manual/reference/operator/query/where/


text:
Q: android: remove a view from a gallery I'm using a Gallery view in my app. The app is designed so that I can drag and drop a view from that Gallery.
How can I remove the dragged view from the Gallery?

A: You remove it from the underlying adapter. If you do this correctly, the Gallery will refresh itself. Otherwise, call notifyDataSetChanged() on the adapter to trigger a Gallery update.

A: If you override ImageAdapter you can modify the contents at will by adding methods to delete or add items to your image list(s) or in the case of the example, completely swap lists on the fly.  I am displaying a app banner at startup, and then changing the Gallery to display the mode the app is in as a slider.  Whenever you call a method that modifies the dataset in the ImageAdapter, call imageAdapter.notifyDataSetChanged() as CommonsWare says above :
    // in onCreate
    _gallery = (Gallery) this.findViewById(R.id.gallery_header);
    _imageAdapter = new ImageAdapter(getApplicationContext(),screen_width,screen_height);
    _imageAdapter.setBannerMode(true);
    _gallery.setAdapter(_imageAdapter);

    // the main activity, in my case in a message handler.

    _imageAdapter.setBannerMode(false);
    _imageAdapter.notifyDataSetChanged();
    _gallery.setSelection(0,true);

    // this is my extended image adapter class

   import android.content.Context;
   import android.view.View;
   import android.view.ViewGroup;
   import android.widget.BaseAdapter;
   import android.widget.Gallery;
   import android.widget.ImageView;
   import android.widget.ImageView.ScaleType;

public class ImageAdapter extends BaseAdapter
{
    private Context _context = null;
    private int[] imageIds = { R.drawable.add_banner,R.drawable.subtract_banner,R.drawable.multiply_banner,R.drawable.divide_banner };
    private int[] bannerIds = { R.drawable.mathpiggie_banner };
    private static boolean bannerEnabled = true;

    int _screen_width;
    int _screen_height;

    public ImageAdapter(Context context, int screen_width, int screen_height) {
        this._context = context;
        _screen_width = screen_width;
        _screen_height = screen_height;
    }

    public void setBannerMode(boolean val)
    {
        bannerEnabled = val;
    }

    @Override
    public int getCount()
        {
            if (bannerEnabled)
                return bannerIds.length;
            else
                return imageIds.length;
        }

    @Override
    public Object getItem(int index)
        {
            if (bannerEnabled)
                    return bannerIds[index];
            else
                return imageIds[index];
        }

    @Override
    public long getItemId(int index)
        {
            return index;
        }

    @Override
    public View getView(int postion, View view, ViewGroup group)
        {
            ImageView imageView = new ImageView(_context);
            if (bannerEnabled)
                imageView.setImageResource(bannerIds[postion]);
            else
                imageView.setImageResource(imageIds[postion]);

             return imageView;
        }
}


text:
Q: Kotlin smart cast fails but only with operator function The following is an example of this problem. Why am I unable to invoke supplier using the operator function? If I make supplier non-nullable Supplier<Int> I have no search problem
operator fun <T> Supplier<T>.invoke(): T = this.get()

val supplier: Supplier<Int>? = (Supplier<Int> { 5 })

if (supplier != null) {
    // Fails: Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type Supplier<Int>?
    supplier()
    supplier.invoke() // fine, smart casts
    supplier.get() // fine, smart casts
}

A: This problem was fixed for me in a later of version of IntelliJ + Kotlin plugin


text:
Q: Resizing uploaded image in Drupal using imagecopyresampled I'm trying to resize an image that is uploaded to Drupal via a form. The code I have for it is:
//Image resizing
//Get file and if it's not the default one - resize it.
$img = file_load($form_state['values']['event_image']);
if($img->fid != 1) {
  //Get the image size and calculate ratio
  list($width, $height) = getimagesize($img->uri);
  if($width/$height > 1) {
    $new_width = 60;
    $new_height = $height/($width/60);
  } else if($width/$height < 1) {
    $new_height = 60;
    $new_width = $width/($height/60);
  } else {
    $new_width = 60;
    $new_height = 60;
  }
  //Create image
  $image_p = imagecreatetruecolor($new_width, $new_height);
  $ext = strtolower(pathinfo($img->uri, PATHINFO_EXTENSION));
  if($ext == 'jpeg' || $ext == 'jpg') {
    $image = imagecreatefromjpeg($img->uri);
  } else {
    $image = imagecreatefrompng($img->uri);
  }
  //Resize image
  imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
  //Save image as jpeg
  imagejpeg($image_p, file_create_url($img->uri), 80);
  //Clean up
  imagedestroy($image_p);
  //Store the image permanently.
  $img->status = FILE_STATUS_PERMANENT;
}
file_save($img);

So what I'm trying to achieve is to save the new file (with the smaller size) over the old one that got uploaded.
The problem I'm getting is PHP throws a warning on imagejpeg($image_p, file_create_url($img->uri), 80); saying:
Warning: imagejpeg() [function.imagejpeg]: Unable to open 'http://localhost:8888/drupal/sites/default/files/pictures/myimage.png' for writing: No such file or directory in event_creation_form_submit()
Because of this, the image isn't resizing. Does anyone know what I'm doing wrong?
Thanks,

A: As Clive pointed out - the fix was to use image_scale. Here is an extract of working code:
//Image resizing
//Get file and if it's not the default one - resize it.
$img = file_load($form_state['values']['event_image']);
if($img->fid != 1) {
  //Get the image size and calculate ratio
  $newImage = image_load($img->uri);
  list($width, $height) = getimagesize($img->uri);
  if($width/$height >= 1) {
    image_scale($newImage, 60);
  } else {
    image_scale($newImage, null, 60);
  }
  //Save image
  image_save($newImage);
  $img->status = FILE_STATUS_PERMANENT;
  }


text:
Q: Shaping image pixel by pixel in OpenCV So the idea is that I have and image recorded from cylindrical camera through a rectangular window in it. Image we get is a rectangular picture though it must be circular. I'm using OpenCV to move image pixel by pixel, line by line into a circle from a given rectangular picture. Problem is that pixel distribution is uneven depending on a radius. What algorithm you'd suggest to make distribution more even? Here's the code:
int main( int argc, char** argv ) {

Mat src = imread( "srcImg.jpg", 1 );
Mat dst = imread( "dstImg.jpg", 1 );

int srcH = src.rows; int srcW = src.cols;
int dstH = dst.rows; int dstW = src.cols;

//convert chamber radius to pixels
double alpha, alpha_double, alpha_triple;
int r = 1500;
double k = 210 / (500 * PI);
int l = 1;
//take pixels from source and arrange them into circles

    for (int i = srcH - 1; i > 0; i--) {
        for (int j = 1; j <= srcW ; j++) {
            alpha = (double) (2 * PI * (r * k + i)) / j;
            alpha_double = (double) (2 * PI * ((r + 15) * k + i)) / j;
            alpha_triple = alpha_double = (double) (2 * PI * ((r + 30) * k + i)) / j;

            int x_new = abs((int) (dstW / 2 - (r * k + i) * cos(alpha)) - 200);
            int y_new = abs((int) (dstH / 2 - (3.5*(r * k + i)  * sin(alpha))) + 1000);

            int x_new_double = abs((int) (dstW / 2 - (r * k + i) * cos(alpha_double)) - 200);
            int y_new_double = abs((int) (dstH / 2 - (3.5*(r * k + i)  * sin(alpha_double))) + 1000);

            int x_new_triple = abs((int) (dstW / 2 - (r * k + i) * cos(alpha_triple)) - 200);
            int y_new_triple = abs((int) (dstH / 2 - (3.5*(r * k + i)  * sin(alpha_triple))) + 1000);

            dst.at<uchar>(x_new, y_new) = src.at<uchar>(srcH - i, srcW - j);
            dst.at<uchar>(x_new_double, y_new_double) = src.at<uchar>(srcH - i, srcW - j);
            dst.at<uchar>(x_new_triple, y_new_triple) = src.at<uchar>(srcH - i, srcW - j);
        }
    }

//make dst image grey and show all images
Mat dstGray;
cvtColor(dst, dstGray, CV_RGB2GRAY);
imshow("Source", src);
imshow("Result", dstGray);

waitKey();
return 0;

And the

A: This is hardly a full answer, but I would try some kind of projection mapping instead of manually accessing every pixel. There must be an openCV way to create a destination shape then say : "Take my original image and make it fit the destination shape"
This is rather trivial for rectangles as you can see here, but your hole in the middle makes it harder.


text:
Q: match event windows (in month) using sas sql I have two files, one with event date, the other one is the security prices I need to match the month with event month 0, -1 (previous month), and +1 (the month after event month). So e.g., one observation has event date 1/1/2010, I have the daily bond prices from 1/1/2009 to 1/20/2010, but I need to match January,2010 to December 2009 prices and February 2010. I have the following codes to do that,
PROC SQL;
CREATE TABLE test AS
  select *
  FROM bondprice as a, sdc as b
where b.Participant_CUSIP=a.cusip
& INTCK('MONTH',b.Alliance_Date,a.time)>=-1
& INTCK('MONTH',b.Alliance_Date,a.time)<=1 ;
QUIT;

DATA test1;
SET test;
BY deal_number CUSIP code time;
IF first.code  THEN price1=price;
IF first.code  THEN day1=time;
IF last.code  THEN price0=price;
IF last.code  THEN day0=time;
RUN;

clearly this observation should be only matched in 1-month Jan 2010 (0,0) and 2-month Dec 2009 to Jan 2010 (-1,0), because it does not have 3-month Feb 2010's prices. However, if using my codes above, it will yield as a valid obs who has 3-month price since it fell into the range of >=-1 and <=1.
So the first part of code is not accurate (the >= and <= range): it yields any prices that falls into December 2009 to Feb 2010, this is wrong because of two situations. First, if the bond prices stops in between Dec 2009 and Jan 2010, it will be counting as a valid 2-month and 3-month observations. Second, if the bond prices begins in between Jan 2010 and Feb 2010, it will be counting as a valid 3-month observation. Both of these two situation will yield invalid observations, since the first situation do not have Feb 2010 prices but still counts as 2-month and 3-month, and the second situation do not have either Dec 2009 or Jan 2010 prices, but still counts as 3-month.
Will someone help me with this? How can I modify the code so that the 3-month window and 2-month window contains the relative months?
I hope I describe the problem clearly. Please let me know if anything is unclear.
I've uploaded an example to this problem here.
https://www.dropbox.com/s/hx9ahst7nts4k0q/ex1.xlsx?dl=0


text:
Q: Swift functions I am learning Swift and I got problem with understanding how functions work.
Let's say I got a simple function:
func sayHello() {
  println("hello there")
}

And I can assign this function to variable or constant in that way:
var hello = sayHello

So now variable hello is type of function which can be written in that way:
var hello:() -> () = sayHello

And now I can run/execute (is it a proper wording?) sayHello function by typing:
hello()

which prints my output "hello there"
The question is whats the difference between this:
var hello1 = sayHello()
hello1 // it prints out hello there string

and that:
var hello2 = sayHello
hello2() // it prints out hello there string as well

A: In a nutshell,
hello1 is the result of the execution of sayHello. But because your function does not return anything, its value will be a Void.
hello2 on the other hand is a reference to the function sayHello. It is of type () -> (). That's why you need to execute it (the trailing '()' in your example) to get the result.
This is what we call First Class Function. One of the characteristics is that functions can be passed around and used like a variable.


text:
Q: How to gain ownership of external HDD (and all files/folders) mounted to /mnt I've plugged in a USB Hard Drive to my new Debian Jessie machine.  I've got it to auto-mount by updating /etc/fstab:
UUID=21AE-9B96 /mnt/local/ext001 vfat defaults 0 2

...but it's owner is root and won't let me change anything.  I've mounted it as /mnt/local/ext001 and have tried to:
sudo chown -R 1000:1000 ext001

...it grants me ownership over ext001, but nothing in it or below it, giving me:
Changing ownership of xyz, : Operation not permitted

I've attempted this using sudo and su.  Where am I going wrong?


text:
Q: How to get value of dynamic id in an html loop with javascript? I am creating a drag and drop system using redips javascript.
This is my script using html and php to generate the data

       <?php
          foreach($deviceID as $row)
          {
             echo '

'.$row['description'].'<input type="hidden" id="bus" value="'.$row['description'].'">

';
          }
        ?>

This is the fragment of my javascript file.
var redips_init;
redips_init = function () {
    // reference to the REDIPS.drag
    var rd = REDIPS.drag;
    // initialization
    rd.init();
        rd.drop_option = 'shift';
    rd.animation_shift = true;

        rd.myhandler_dropped = function () {
            alert($('#bus').val());
        }
};

A: I am not good with php but what i usually do in jsp is create a local index variable and append it to each of the ID attribute in the loop.
So your code would look something like this
  <?php
      $index=0;
      foreach($deviceID as $row)
          {
             echo '

'.$row['description'].'<input type="hidden" id="bus'.$index++.'" value="'.$row['description'].'">

';
          }
        ?>

In javascript, your dragAndDrop event should return an index location by which u can get appropriate value.
Now you can use this dynamic ID in your JavaScript to do whatever you want to do.

A: REDIPS.drag contains save_content() method to scan all DIV elements in a table and to return the result as Query string or JSON object. Input parameters are table id and type of returned result (default is query string). If this is not good enough, you can search for save_content() source and make customization. Method is simple and it uses several loops to scan table content.
On the other hand, if you need to know ID of dropped DIV element that can be written inside myhandler_dropped event hander. Here is code snippet:
rd.myhandler_dropped = function () {
    // define DIV id
    var id = rd.obj.id;
    // write DIV id to the console
    console.log(id)
};

Hope this answer will be helpful.


text:
Q: Will using async/await in an express server block all the routes while one is being used? Imagine I have multiple routes
/login
/register
/verify

And it happens that /login route has an async function somewhere
What if for example, during the await of an async function in /login (because an user is logging in) , another user is using at the same time the route /verify . Will this user experience a delay because of the await? Or does node use some sort of multithreading to avoid the issue? Or should I simply use a promise and a .then instead?


text:
Q: How to resolve error message "There was an issue looking up your account. Tap Next to try again." on Azure AD We added Windows Azure AD authentication SAML into our ASP.NET application for a few years now. Our Azure AD has the application registrations, our web.config has been configured, etc. The setup is a bit old but it has been working for a few years now.
THE PROBLEM
However, just recently whenever we are redirected to the login page on Microsoft, we get the error 'There was an issue looking up your account. Tap Next to try again.'
WHAT I'VE TRIED
I can't find any further information on this error [trying to enable diagnostics (in the little bottom-right popup with the correlation ID, trace ID) tell me 'something went wrong'].
I thought maybe it had do to with the passwords, but I've verified the credential use is working (directly logging into portal.azure.com is fine). And the error happens for ALL credentials.
I do know that Microsoft Azure recently changed the AD app registrations, but I've tried re-creating a new registration, and I still get the same error.
Lastly, oddly enough, our applications that are using OAuth 2.0 work.
Anyone have any idea?

A: It seems the domain for the WS-Fed Endpoint has changed from sts.windows.net to login.microsoftonline.com . Changing the address in our web.config finally got this resolved.


text:
Q: jquery events not firing on returning back to a page? I have a mobile application which uses ajax for fetching data and showing that on screen. The application works fine.
I have a search_member page. when i click a button, it shows a list of customers, on clicking each customer, it goes to a details page and there is a button on the details page which navigates to create_new_ loan page to fill in some info.
I am using a side panel menu in all the pages.

Home

New Application

Member Search

Settings

When I select the Member Search menu, its navigating to that page, but the document.ready() or button click events on that page are not firing.
 $(document).ready(function () {

            debugger;
});

What is the reason for that?


text:
Q: Independence of spacing of order statistics of exponential distribution Let $X_{1}$,$X_{2}$ and $X_{3}$ be a random sample from exponential distribution with density function - $$f(x) = \lambda e^{-\lambda x}$$
$x>0$ and $\lambda>0$
Show that $X_{(1)}$,$X_{(2)}$-$X_{(1)}$ and $X_{(3)}$-$X_{(2)}$ are independent,where $X_{(i)}$ , i=1,2,3 are order statistics.

A: The pdf of $\mathbf{X}=(X_{(1)}, X_{(2)}, X_{(3)})$ is $f_{\mathbf{X}}(x_1, x_2, x_3)=6\lambda^3 e^{-\lambda (x_1+x_2+x_3)}I_{(0<x_1<x_2<x_3)}$.
Setting $\mathbf{Y}=(Y_1, Y_2, Y_3)=(X_{(1)}, X_{(2)}-X_{(1)}, X_{(3)}-X_{(2)})$, we have $\det(\displaystyle\frac{\partial \mathbf{x}}{\partial \mathbf{y}})=1$. Also, $0<x_1<x_2<x_3$ is equivalent to $y_1, y_2, y_3>0$. Thus the pdf of $\mathbf{Y}$ is
$\begin{align*}
f_{\mathbf{Y}}(y_1, y_2, y_3)
&=6\lambda^3 e^{-\lambda (3y_1+2y_2+y_1)}I_{(y_1, y_2, y_3>0)}\\
&=(3\lambda e^{-3\lambda y_1}I_{(y_1>0)})(2\lambda e^{-2\lambda y_2}I_{(y_2>0)})(\lambda e^{-\lambda y_3}I_{(y_3>0)})\\
&=f_{Y_1}(y_1)f_{Y_2}(y_2)f_{Y_3}(y_3)
\end{align*}$
where $f_{Y_i}$ is a pdf of $Y_i, i=1,2,3$. Thus $Y_1, Y_2, Y_3$ are independent.


text:
Q: Convergence of a self-consistent multivariable integral equation I want to solve the following integral equation
$$\mathbf v(\mathbf r)=\int_V \mathbf v(\mathbf r^\prime)\cdot \mathbf F(\mathbf r, \mathbf r^\prime) \mathrm ~d^3r^\prime +\mathbf g(\mathbf r)$$
using a self consistency iterative method. Namely,
$$\mathbf v_0=\mathbf g,$$
$$\mathbf v_1=\int_V \mathbf v_0\cdot \mathbf F \mathrm ~d^3r^\prime +\mathbf g,$$
$$\mathbf v_2=\int_V \mathbf v_1\cdot \mathbf F \mathrm ~d^3r^\prime+\mathbf g,$$
$$\vdots$$
Is there a condition that can be applied to determine if $$\lim_{n\to\infty}\mathbf v_n(\mathbf r)=\mathbf v(\mathbf r)~\text{?}$$
EDIT: I don't know if it's relevant, but note that $\mathbf F$ is a rank 2 tensor, and $\mathbf v$ and $\mathbf g$ are vectors.


text: Q: How to run Oracle Client 10g from non Administrator account? Hi I have 2 users configured on my Windows 10 Home machine. One is Administrator and another is my own user. Although my user is configured as an Administrator, I can use Oracle Client 10g from my Administrator account only. Is there any way in which I do not have to switch to the Administrator account and still be able to use Oracle Client 10g from my own account ?


text:
Q: In a GatsbyJS application How can I conditionally Navigate to a URL using data from state? In a GatsbyJs application I'm trying to navigate to a login page if the user information is not available in the state of a component. I do not need to navigate to the login page if the user information is available in the state
The componenent is as follows
import React from 'react';
import axios from 'axios';
import { navigate } from 'gatsby';

export default class UserLogin extends React.Component {
  constructor() {
    super()
    this.state = {
      userInfo: {}
    }
  }

  componentWillMount(){
    var objlength = Object.keys(this.state.userInfo).length;
    if(objlength === 0){
      navigate('https://localhost:3000/login'); //express server to login page
    }
  }

  componentDidUpdate(){
    console.log("User information", this.state.userInfo);
    axios.get("https://localhost:3000/users", { withCredentials: true })
    .then(response => response.data)
    .then((response) => {
      this.setState({userInfo:response})
    })
  }

  render() {
    return (
    <React.Fragment>

This is user information page

    </React.Fragment>
    )
  }
}

Initially the userInfo state is empty so the length is found to be 0, in that case the app will redirect to login page - https://localhost:3000/login and will provide an API with user information - https://localhost:3000/users. Once the API is providing the user information the state is updated and length will become valid.
But here the following lines of code called continuously(like inside a loop) even though the state is updated with user information
if(objlength === 0){
   navigate('https://localhost:3000/login'); //express server to login page
}

A: Here's a pretty generic example of a Session component that does what you're looking for, but instead of merely rendering the single page, it provides the session as React Context to be consumed in any descendent component:
import React, { useContext } from "react"
import { navigate } from "gatsby"
import deepEqual from "deep-equal"
import api from "lib/api"

export const SessionState = React.createContext()
const { Provider, Consumer } = SessionState

export default class Session extends React.Component {
  state = {
    user: null,
    isLoading: true,
  }

  componentDidMount() {
    this.loadData()
  }

  updateSession = user => {
    if (!deepEqual(user, this.state.user)) {
      this.setState({ user })
    }

    this.setState({ isLoading: false })
  }

  handleError = () => {
    this.setState({
      user: null,
      isLoading: false,
    })
  }

  signIn = props =>
    api
      .signIn(props)
      .then(props => this.updateSession(props))
      .catch(error => {
        this.handleError()
      })

  signOut = () =>
    api
      .signOut()
      .then(() => {
        this.setState({ user: null })
      })
      .then(() => {
        navigate("/dashboard/")
      })
      .catch(this.handleError)

  loadData = () =>
    api
      .user()
      .then(this.updateSession)
      .catch(this.handleError)

  render() {
    return (
      <Provider
        value={{
          ...this.state,
          signIn: this.signIn,
          signOut: this.signOut,
          reload: this.loadData,
        }}
      >
        {this.props.children}
      </Provider>
    )
  }
}

export const useSession = () => useContext(SessionState)

Instead of duplicating this logic or making additional requests in a descendent component, you can consume the state in a simple function-based component like so:
import { useSession } from "./Session"

const Example = () => {
  const { user, isLoading } = useSession()

  if (user) {
    // show user content when user present, even if isLoading
    return
User content here

  } else {
    if (isLoading) {
      return
Loading…

    }

    // no user and not loading
    navigate("/login")
    return null
  }
}

A: It's difficult to debug without seeing a live CodeSandbox. However, one approach that may help you to avoid that call (objlength === 0) is setting a helper in your state to check if the API request has ended or not. Initially:
this.state = {
  userInfo: {},
  isApiRequestDone: false
}

Then, in your promise:
.then((response) => {
  this.setState({userInfo:response})
  this.setState({isApiRequestDone:true})
})

Finally:
if(objlength === 0 && !isApiRequestDone){
   navigate('https://localhost:3000/login'); //express server to login page
}

This is an initial workaround but for now, it may help you to bypass the redirection.


text:
Q: Query to find occurrence of at least one value in a set of columns In the below table, how do I filter out records with at least one 1 and at least one 2 in any of the columns. I also only want records for columns with the string 2nd row in the Name column.
Col1 Col2 Col3 Col4 Name
1    1    1    1    1st row
1    2    1    2    2nd row
2    1    1    1    3rd row
1    2              2nd row

I want the output to be -
Col1 Col2 Col3 Col4 Name
1    2    1    2    2nd row
1    2              2nd row

A: You can use IN as a shortcut for "col1" = 1 OR ....
SELECT *
       FROM "elbat"
       WHERE 1 IN ("col1",
                   ...,
                   "col4")
             AND 2 IN ("col1",
                       ...,
                       "col4")
             AND "name" = '2nd row';

A: You can use Postgres' arrays for that:
select *
from the_table
where array[1,2] <@ array[coalesce(col1, -1), coalesce(col2, -1), coalesce(col3, -1), coalesce(col4, -1)]
  and name = '2nd row';

The <@ operator checks, if all elements of the left hand array are included in the right hand array. The coalesce() is necessary because you can't put null values into an array.
Online example: https://rextester.com/CLXWK64603
If you want you can create an index on the array expression to speed things up.


text:
Q: How disable dynatrace for debug builds android I want to disable dynatrace to collect debug builds
In my build.gradle (android):
dynatrace {
    configurations {
        debug {
            enabled false
        }
        release {
            enabled true
            autoStart {
                autoStart.enabled false
            }
        }
    }
}

but in tasks trace I see next
> Task :dynatrace:preBuild UP-TO-DATE
> Task :dynatrace:preDebugBuild UP-TO-DATE
> Task :dynatrace:compileDebugAidl NO-SOURCE
> Task :dynatrace:packageDebugRenderscript NO-SOURCE
> Task :dynatrace:generateDebugResValues FROM-CACHE
> Task :dynatrace:generateDebugResources UP-TO-DATE
> ...

A: Use this acticle.
You have to create 2 separate apps in Dynatrace and use this config. After that your development data(debug) removes from the production data.
dynatrace {
    configurations {
        debug {
            variantFilter "[dD]ebug"
            autoStart {
                applicationId '<DebugApplicationID>'
                beaconUrl '<ProvidedBeaconURL>'
            }
        }
        prod {
            variantFilter "[rR]elease"
            autoStart {
                applicationId '<ProductionApplicationID>'
                beaconUrl '<ProvidedBeaconURL>'
            }
        }
    }
}


text:
Q: Clustering: Finding a Average Reading I am looking into finding algorithm within the area of clustering or machine learning which will facilitate or creating a typical data reading for a group of readings. The issue is that it must facilitate time series data; thus some traditional (k-means) techniques are not as useful.
Can anyone recommend places to look or particular algorithms that would provide a typical reading and relatively simple to implement (in Java), manipulate and understand?

A: As an idea. Try to convert all data types into time, then you will have vectors of the same type (time), then any clustering strategy will work fine.
By converting to time I actually mean that any measurement or data type we know about has a time in its nature. Time is not a 4-th dimension, as many think! Time is actually 0-dimension. Even a point of no physical dimensions which may not exist in space, exists in time.
Distance, weight, temperature, pressure, directions, speed... all measures we do can be converted into certain functions of time.
I have tried this approach on several projects and it payed back with really nice solutions.
Hope, this might help you here as well.

A: For most machine learning problems in Java, weka usually works pretty well.
See, for example: http://facweb.cs.depaul.edu/mobasher/classes/ect584/weka/k-means.html