text:
Q: Hibernate @Embedded vs ManyToOne Mapping I am trying to create hibernate mapping between two tables User and Country as shown below in below image.
The Country table is used only for the user and not anywhere else so should i use embedded and Embeddable to create these tables or simply perform many to one mapping once tables get created.

A: It depends on how you'll use it. If you embed the country data it will be in User table and will be loaded with user data.
If in most cases you don't need the country data each time you work with user data you can do OneToMany mapping with lazy initialization. In that case country data will be loaded only when need with the cost of additional DB hit (which may be reduced to a join).

A: It depends on when you want to load country data.If you use embedded then the country data will be loaded at the time of user data load.But if you go with OneToMany mapping with lazy initialization then country data will be loaded when you need it.
So that is based on you use.

A: This is something more personal. Some people prefer to use Embedded to abstract some information and other people are more purist.
By my experience, I prefer to map the entities very close to their representation on tables. The reasons are simple:

*

*Maintenance: it's easier to understand what't happening on the mapping if some new developer enter on the team and he don't have many experience with hibernate.

*Queries more similar to SQL: your JPQL/Criteria queries will be more closest to the generated SQL. The abstraction of a embedded can bring some confusion, even for people familiar with the framework.

And as the other answers already mentioned, you will always bring the Country information with User using embedded. This is a EAGER behavior, what is generally something to avoid on JPA/Hibernate.
So, in your case, I would use a many-to-one relationship.


text:
Q: How to force user to insert only numbers in a string if I force the first and the last to be letters in a 10 length string? Example S2351566A Int char10];// length of string
{
   if (!isalpha(str[0]) || !isalpha(str[8]))// force 1st and last array to be alphabet
    {
        printf("invalid input\n"); exit(1); // invalid
    }
}

A: if only 1st and last elements must be characters , then u can try this,
but if u want 1st and last element to be char and all middle to be digits then add another if statement after first "if"
boolean b=false;
while(b!=true){
take input in ch[10];
if(ch[0]>='A'&&ch[0]<='Z' && ch[9]>='A'&&ch[0]<='9'){
//means 1st and last are char
b=true;//will break because of this
}
else {
print f("Wrong input, enter again");
b=false;}
}
//this will run until user does not give correct input

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pytorch batch indexing So the output of my network looks like this:
output = tensor([[[ 0.0868, -0.2623],
     [ 0.0716, -0.2668],
     [ 0.0584, -0.2549],
     [ 0.0482, -0.2386],
     [ 0.0410, -0.2234],
     [ 0.0362, -0.2111],
     [ 0.0333, -0.2018],
     [ 0.0318, -0.1951],
     [ 0.0311, -0.1904],
     [ 0.0310, -0.1873],
     [ 0.0312, -0.1851],
     [ 0.0315, -0.1837],
     [ 0.0318, -0.1828],
     [ 0.0322, -0.1822],
     [ 0.0324, -0.1819],
     [ 0.0327, -0.1817],
     [ 0.0328, -0.1815],
     [ 0.0330, -0.1815],
     [ 0.0331, -0.1814],
     [ 0.0332, -0.1814],
     [ 0.0333, -0.1814],
     [ 0.0333, -0.1814],
     [ 0.0334, -0.1814],
     [ 0.0334, -0.1814],
     [ 0.0334, -0.1814]],

    [[ 0.0868, -0.2623],
     [ 0.0716, -0.2668],
     [ 0.0584, -0.2549],
     [ 0.0482, -0.2386],
     [ 0.0410, -0.2234],
     [ 0.0362, -0.2111],
     [ 0.0333, -0.2018],
     [ 0.0318, -0.1951],
     [ 0.0311, -0.1904],
     [ 0.0310, -0.1873],
     [ 0.0312, -0.1851],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164]],

    [[ 0.0868, -0.2623],
     [ 0.0716, -0.2668],
     [ 0.0584, -0.2549],
     [ 0.0482, -0.2386],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164]],

    [[ 0.0868, -0.2623],
     [ 0.0716, -0.2668],
     [ 0.0584, -0.2549],
     [ 0.0482, -0.2386],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164]],

    [[ 0.0868, -0.2623],
     [ 0.0716, -0.2668],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164]],

    [[ 0.0868, -0.2623],
     [ 0.0716, -0.2668],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164]],

    [[ 0.0868, -0.2623],
     [ 0.0716, -0.2668],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164]],

    [[ 0.0868, -0.2623],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164],
     [ 0.1003, -0.2164]]])

Which is a shape of [8, 24, 2]
Now 8 is my batch size. And i would like to get a data point from every batch, at the following locations:
index = tensor([24, 10,  3,  3,  1,  1,  1,  0])

So the 24th value from the first batch, the 10th value from the second batch, and so on.
Now i have problems figuring out the syntax.
I've tried
torch.gather(output, 0, index)

But it keeps telling me, that my dimensions don't match.
And trying
output[ : ,index]

Just gets me the values at all the indexes for each batch.
What would be the correct syntax here, to get these values?

A: To select only one element per batch you need to enumerate the batch indices, which can be done easily with torch.arange.
output[torch.arange(output.size(0)), index]

That essentially creates tuples between the enumerated tensor and your index tensor to access the data, which results in indexing output[0, 24], output[1, 10] etc.

A: First a small note, for an output shape [8, 24, 2], the largest index on the secoond dimention can be 23, so I'm modifying your indexes to be
index = torch.tensor([23, 10,  3,  3,  1,  1,  1,  0])
output = torch.randn((8,24,2)) # Toy data to represent your output

The simplest solution is to use a for loop
data_pts = torch.zeros((8,2)) # Tensor to store desired values

for i,j in enumerate(index):
    data_pts[i, :] = output[i, j, :]

However, if you want to vectorize the indexing, you simply need indices for all dimensions. For example,
data_pts_vectorized = output[range(8), index, :]

Since your index vector is in order, you can generate the first dimension index with range.
You can confirm that the two approaches have the same results
assert(torch.all(data_pts == data_pts_vectorized))


text:
Q: How to determine which Python class provides attributes when inheriting What's the easiest way to determine which Python class defines an attribute when inheriting? For example, say I have:
class A(object):

    defined_in_A = 123

class B(A):
    pass

a = A()
b = B()

and I wanted this code to pass:
assert hasattr(a, 'defined_in_A')
assert hasattr(A, 'defined_in_A')
assert hasattr(b, 'defined_in_A')
assert hasattr(B, 'defined_in_A')

assert defines_attribute(A, 'defined_in_A')
assert not defines_attribute(B, 'defined_in_A')

How would I implement the fictional defines_attribute function? My first thought would be to walk through the entire inheritance chain, and use hasattr to check for the attribute's existence, with the deepest match assumed to be the definer. Is there a simpler way?

A: (Almost) Every python object is defined with it's own instance variables (instance variables of a class object we usually call class variables) to get this as a dictionary you can use the vars function and check for membership in it:
>>> "defined_in_A" in vars(A)
True
>>> "defined_in_A" in vars(B)
False
>>> "defined_in_A" in vars(a) or "defined_in_A" in vars(b)
False

the issue with this is that it does not work when a class uses __slots__ or builtin objects since it changes how the instance variables are stored:
class A(object):
    __slots__ = ("x","y")
    defined_in_A = 123

>>> A.x
<member 'x' of 'A' objects>
>>> "x" in vars(a)
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    "x" in vars(a)
TypeError: vars() argument must have __dict__ attribute
>>> vars(1) #or floats or strings will raise the same error
Traceback (most recent call last):
   ...
TypeError: vars() argument must have __dict__ attribute

I'm not sure there is a simple workaround for this case.


text:
Q: vb.net I got (Unable to read data from the transport connection) error message from socket I'm trying to use a non-synchronous connection server on the client, but occasionally I get an error message on the client. How can I solve the problem?
How to change to callback?
Error code :

unable to read data from the transport connection the connection was
  closed
at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)
  at TFD_SoftPhone.MD_Function.ConnectionInfo.DoReadData(IAsyncResult
  result)

Public Class ConnectionInfo

    Private _AppendMethod As Action(Of String)
    Private _Client As TcpClient
    Private _Stream As NetworkStream
    Private _LastReadLength As Integer
    Private _Buffer(5120) As Byte

    Public ReadOnly Property AppendMethod As Action(Of String)
        Get
            Return _AppendMethod
        End Get
    End Property

    Public ReadOnly Property Client As TcpClient
        Get
            Return _Client
        End Get
    End Property

    Public ReadOnly Property Stream As NetworkStream
        Get
            Return _Stream
        End Get
    End Property

    Public ReadOnly Property LastReadLength As Integer
        Get
            Return _LastReadLength
        End Get
    End Property

    Public Sub New(address As IPAddress, port As Integer, append As Action(Of String))

        _AppendMethod = append
        _Client = New TcpClient
        Try
            _Client.SendTimeout = 45000
            _Client.ReceiveTimeout = 45000
            _Client.Connect(address, port)
            _Stream = _Client.GetStream
        Catch ex As Exception

            If _Client.Connected Then _Client.Close()
            If Not IsNothing(_Client) Then _Client = Nothing
            If Not IsNothing(_Stream) Then _Stream = Nothing
        End Try

    End Sub

    Public Sub AwaitData()

        Try
            If Not IsNothing(_Stream) Then
                _Stream.ReadTimeout = 45000
                _Stream.WriteTimeout = 45000
                _Stream.BeginRead(_Buffer, 0, _Buffer.Length, AddressOf DoReadData, Me)
            End If
        Catch ex As Exception

        End Try

    End Sub

    Public Sub Close()

        If _Client IsNot Nothing Then _Client.Close()
        _Client = Nothing
        _Stream = Nothing

    End Sub

    Private Sub DoReadData(result As IAsyncResult)

        Dim info As ConnectionInfo = CType(result.AsyncState, ConnectionInfo)

        Try
            If info._Stream IsNot Nothing AndAlso info._Stream.CanRead Then
                info._LastReadLength = info._Stream.EndRead(result)
                ReDim Preserve _Buffer(info._LastReadLength - 1)
                If info._LastReadLength > 0 Then
                    Dim message As String = Encoding.GetEncoding("Big5").GetString(info._Buffer)
                    info._AppendMethod(message)
                    ReDim Preserve _Buffer(5120)
                Else

                End If
                info.AwaitData()
            Else

            End If
        Catch ex As Exception
            info._LastReadLength = -1
            info._AppendMethod(ex.Message)
        End Try

    End Sub

End Class


text:
Q: Spree Commerce, Perform a search for payment methods using zone In my region, we use a different way to organize countries/states and zones.
It is way more relevant to ask the customer directly for his zone on the address form.. This is why I need to perform a search for all shipping methods that correspond to said zone. The problem is that I cannot understand the way the relationship is made, maybe due to lack of knowledge with apis. Thanks!

A: Basically, Spree zone is a bunch of states (one or many). So for a given coutry, you can have many zones.
Then for a Spree shipping method, you can associate it to one or more zones.


text:
Q: Loading data with ajax when open many tabs at the same time shows wrong data in tabs I write an application with C# MVC which is loading some data with AJAX request to a partial view with different IDs,
my problem is that if I click on two links(with ctrl to open in new tabs) at the same time, first tab load first link constant data but the partial view which load data by AJAX load the second link data!
is there anyway to solve this issue ?

A: as  Andrés Nava comment on my Question I found that
The problem is that I use tempData to send some data between actions, I have changed my strategy and now it works well.


text:
Q: HTML RADIO BUTTON SELECTING BOTH OPTIONS INSTEAD OF ONE
                Kindly Select the service you require
            <input type="radio" id="currConverter" name="currConverter" value="currConverter" />
            Currency Converter

            <input type="radio" id="pbChecker" name="pbChecker" value="pbChecker" />
            Prize Bond Checker

            <input type="submit" class="submit" />
        </form>

I have a form element inside which i have put two radio buttons but want the user to select only one option.When i am clicking on these one by one , both options are getting selected instead of the one on which i clicked.Any solution to this ?

A: Link to w3School
You have to keep same name. in your case:

<input type="radio" id="currConverter" name="pbChecker"value="currConverter"/>
            Currency Converter

            <input type="radio" id="pbChecker" name="pbChecker" value="pbChecker" />
            Prize Bond Checker

            <input type="submit" class="submit" />
        </form>


text:
Q: How $\tan{\frac{A}{2}}\tan{\frac{B}{2}}=\frac{1}{2}$,then find $\angle C$ In $\Delta ABC$, if $$\tan{\dfrac{A}{2}}\tan{\dfrac{B}{2}}=\dfrac{1}{2}\\\sin{\dfrac{A}{2}}\sin{\dfrac{B}{2}}\sin{\dfrac{C}{2}}=\dfrac{1}{10}$$
Find the $\angle C$
My try: since
$$2\sin{\dfrac{A}{2}}\sin{\dfrac{B}{2}}=\cos{\dfrac{A}{2}}\cos{\dfrac{B}{2}}$$
$$\left(\cos{(\dfrac{A-B}{2})}-\cos{(\dfrac{A+B}{2})}\right)\sin{\dfrac{C}{2}}=\dfrac{1}{5}$$
since
$$\cos{(\dfrac{A+B}{2})}=\sin{\dfrac{C}{2}}$$
so
$$\left(\cos{(\dfrac{A-B}{2})}-\sin{\dfrac{C}{2}}\right)\sin{\dfrac{C}{2}}=\dfrac{1}{5}$$
Then I can't go on.

A: Denote $~~a=\tan\dfrac{A}{2}$, $~~b=\tan\dfrac{B}{2}$ $($let $a\le b$$)$.

$\sin\dfrac{A}{2}\sin\dfrac{B}{2}\sin\dfrac{C}{2}=\dfrac{1}{10}$;
$\sqrt{\dfrac{1-\cos A}{2}} \cdot \sqrt{\dfrac{1-\cos B}{2}} \cdot \sqrt{\dfrac{1-\cos C}{2}}  = \dfrac{1}{10}$;
$(1-\cos A) (1-\cos B)(1-\cos C) = \dfrac{2}{25}$;
$(1-\cos A) ~ (1-\cos B) ~ (1+\cos(A+B)) = \dfrac{2}{25}$;
$\dfrac{2a^2}{1+a^2} \cdot \dfrac{2b^2}{1+b^2} \cdot \dfrac{2(1-ab)^2}{(1+a^2)(1+b^2)} = \dfrac{2}{25}$;
$\dfrac{ab|1-ab|}{(1+a^2)(1+b^2)}=\dfrac{1}{10}$.

Now we get system:
$$
\left\{ \begin{array}{l}
ab=\dfrac{1}{2};\\
\dfrac{ab|1-ab|}{(1+a^2)(1+b^2)}=\dfrac{1}{10}.
\end{array}
\right.
$$
$b=\dfrac{1}{2a}$ $\implies$ $\dfrac{a^2}{(1+a^2)(4a^2+1)}=\dfrac{1}{10}$ ;
$4a^4-5a^2+1=0$;
$(2a-1)(2a+1)(a-1)(a+1)=0$.
there are $2$ positive roots for this eq.:
$a=\dfrac{1}{2}$ and $a=1$.
If $a=\dfrac{1}{2}$, then $b=1$, then $A = \arctan\dfrac{4}{3}=\arcsin\dfrac{4}{5}=\arccos\dfrac{3}{5}$, $~B=\pi/2$, $~C=...$;
If $a=1$, then $b=\dfrac{1}{2}$ (simply permutation of $a,b$).
(don't know if this is the simplest way, but at least this is $\approx$ clear :)

Finally,
$C=\arctan\dfrac{3}{4}=\arcsin\dfrac{3}{5}=\arccos\dfrac{4}{5} = 0.643501108793...$.


text:
Q: C++ multi-thread memory leak issue Once the following code is running, it will eat all my memory and cause OOM issue on my ARM 64-bit processor.  it seems that some 'delete' operations do not work... it confused me. Could any experts help to analysis what is the root cause? Ttoolchain or libc?
I run the same code in another two platforms, one is x64, one is another ARM 32-bit chip; they all fine except my IPQ ARM chip.
environment:

*

*libc version: musl libc 1.1.16

*gcc version: 5.2.0

*cpu chip: IPQ ARM 64bit

*os: linux 4.1

#include <iostream>
#include <cstring>
#include <list>
#include <memory>
#include <pthread.h>

void *h(void *param)
{
    while(1)
    {
        char *p = new char[4096];
        delete[] p;
    }
    return NULL;
}

int main(int argc, char *argv)
{
    pthread_t th[50];
    int thread_cnt = 2;
    for(int i = 0; i < thread_cnt; i++)
        pthread_create(th+i, NULL, h, NULL);

    for(int i = 0; i < thread_cnt; i++)
        pthread_join(th+i, NULL);

    return 0;
}

*

*If I use a mutex in the header-file thread callback, the issue will disappear; there is no memory leak.

std::mutex thlock;
void *h(void *param)
{
    while(1)
    {
        std::lock_guard<std::mutex> lk(thlock);
        char *p = new char[4096];
        delete[] p;
    }
    return NULL;
}

*If I change the memory allocation size to 1024, then a weird thing happed. 2 threads do not leak memory, but 20 threads will cause memory leak.  Whatever the allocation size, there's no issue with only 1 thread.

void *h(void *param)
{
    while(1)
    {
        //char *p = new char[4096];
        char *p = new char[1024];
        delete[] p;
    }
    return NULL;
}

*If I replace new/delete to std::malloc/std::free, the issue will disappear; no memory leak.

void *h(void *param)
{
    while(1)
    {
        //char *p = new char[4096];
        char *p = (char *)std::malloc(4096);
        std::free(p);
        //delete[] p;
    }
    return NULL;
}

*So I thought if I overload operator new/delete and my "new/delete" allocate memory by using std::malloc/free, maybe the issue could be solved. But
the weird thing happened again; the memory leak still exists.

void* operator new(std::size_t sz) // no inline, required by [replacement.functions]/3
{
    std::printf("global op new called, size = %zu\n", sz);
    if (sz == 0)
        ++sz; // avoid std::malloc(0) which may return nullptr on success

    if (void *ptr = std::malloc(sz))
        return ptr;

    throw std::bad_alloc{}; // required by [new.delete.single]/3
}
void operator delete(void* ptr) noexcept
{
    std::puts("global op delete called");
    std::free(ptr);
}

void *h(void *param)
{
    while(1)
    {
        char *p = new char[4096];
        delete[] p;
    }
    return NULL;
}

*So I thought the memory leak may be caused by my operator new/delete rather than malloc/free, so I changed the code to look like what's shown below. I don't really call malloc/free but return a pre-allocated buffer. But the memory leak issue disappeared, so it seems the issue not only comes from new/delete...

char pp[4096];
void* operator new(std::size_t sz) // no inline, required by [replacement.functions]/3
{
    std::printf("global op new called, size = %zu\n", sz);
    if (sz == 0)
        ++sz; // avoid std::malloc(0) which may return nullptr on success

    return (void *)pp;
    //if (void *ptr = std::malloc(sz))
        //return ptr;

    throw std::bad_alloc{}; // required by [new.delete.single]/3
}
void operator delete(void* ptr) noexcept
{
    std::puts("global op delete called");
    //std::free(ptr);
}

So, what happened? Could any experts give me some idea? I guess it maybe caused musl libc thread lib; it seems that thread synchronization does not work fine... or is there a patch that already fixed this issue?

A: this issue is involved by musl libc, and has been fixed by the following patch.
https://git.musl-libc.org/cgit/musl/commit/src/malloc?id=3e16313f8fe2ed143ae0267fd79d63014c24779f
above patch involved a buffur overflow issue of realloc and has been fixed by below 2 patches:
https://git.musl-libc.org/cgit/musl/commit/src/malloc?id=cb5babdc8d624a3e3e7bea0b4e28a677a2f2fc46
https://git.musl-libc.org/cgit/musl/commit/src/malloc?id=fca7428c096066482d8c3f52450810288e27515c


text:
Q: How do I make Canon imageCLASS D420 work in Ubuntu? How can I install a driver for the printer Canon imageCLASS D420? The default drivers shipped with Ubuntu do not work with it.
I tried to install Canon's drivers, but I got the message:

There was an error during the CUPS operation client error format not supported.

Canon support told me that their drivers can't support Linux.

A: You should be able to get the answers you're looking for here...
http://ubuntuforums.org/showthread.php?t=1427330&p=11871878&highlight=#post11871878
and here
http://ubuntuforums.org/showthread.php?t=1723101&page=4&p=11680367#post11680367


text:
Q: how to write hql with in clauses I need to write an hql query like :
select * from User aliasUser where ? in aliasUser.roles

All examples of IN clause I'm finding use collection as parameters, how can I write this query? Obviously doesn't work as it stands right now, I've tried already.


text:
Q: What is EGL and GL mtrack in Android Memory Dump I'm currently working on a hybrid application that is exhibiting some peculiar memory usage that I'm trying to debug. As soon as the application starts, it appears to be immediately using close to 250MB of memory, which seems excessively given that all we have loaded at that point is the login screen. I've been looking at a few memory profiling tools for Android (the Xamarin profiler and the android profiler shipped with the SDK), but all of them show relatively low heap usage (~10-15MB, which I'm trying to get down). I ran "adb shell dumpsys meminfo APPNAME -d' and got the following trace:
** MEMINFO in pid 24925 [APPNAME] **
                   Pss  Private  Private  Swapped     Heap     Heap     Heap
                 Total    Dirty    Clean    Dirty     Size    Alloc     Free
                ------   ------   ------   ------   ------   ------   ------
  Native Heap    19439    19396        0        0    28672    22915     5756
  Dalvik Heap    15441    14992        0        0    37319    36837      482
 Dalvik Other      542      368        0        0
        Stack      432      432        0        0
       Ashmem    17388    16508      880        0
      Gfx dev    40538    34504        0        0
    Other dev        4        0        4        0
     .so mmap     6211      224     3080        0
    .apk mmap    10531        0    10232        0
    .ttf mmap      453        0      260        0
    .dex mmap     1263        0      980        0
    .oat mmap      635        0      152        0
    .art mmap      707      516       24        0
   Other mmap      452        4       52        0
   EGL mtrack    63508    63508        0        0
    GL mtrack    79116    79116        0        0
      Unknown    21756    21756        0        0
        TOTAL   278416   251324    15664        0    65991    59752     6238

I've been trying to understand what this means by using the documentation provided at: https://developer.android.com/tools/debugging/debugging-memory.html, but that page doesn't seem to have any info on the biggest culprits: Gfx dev, EGL mtrack, GL mtrack, and Unknown. Is there some documentation on what these categories are or why they would grow to be so big?
Thanks

A: GL mtrack is driver-reported GL memory usage. It's primarily the sum of GL texture sizes, GL command buffers, fixed global driver RAM overheads, etc.
EGL mtrack is gralloc memory usage. It's primarily the sum of the  SurfaceView/TextureView.

A: EGL and GL shows here memory consumed by Graphics layer basically. I am sure you are running adb shell dumpsys meminfo command on Android lollipop device. Actually dumpsys meminfo tool/command has been modified in lollipop to calculate and display graphics memory.
In old version (KitKat or older) you can not find EGL and GL information although graphics consumed memory in KitKat or older versions also.
This is we can request Google to update their documentation to explain new memory components also. In short you can say it is bug in documentation of Android. They should update it as per latest implementation of adb shell dumpsys meminfo tool/command.
References:
EGL - http://en.wikipedia.org/wiki/EGL_(API)
GL - http://en.wikipedia.org/wiki/OpenGL


text:
Q: In phpmyadmin, how would I link two specific rows to each other from two different tables inside a single database and keep it automated? I have 2 tables within a single phpmyadmin database- one that stores basic user account info when they sign up (username, email, etc.) and another that stores whatever the user types in the text field where they input the names of their classes but also takes the username from the first table and stores it in another row inside the second table next to all the classes. The first table does what its supposed to and the user data appears there after they click sign up. After the user clicks sign up, they are directed to the classes page where they type the data for the second table. However after you click submit, there is an "object not found" error message and the second table is completely empty. Not even the username from the first table appeared within the second. For reference- inside the URL of the webpage whatever the user typed into the class boxes appears, however the end of the URL it says "submit=".
I tried searching for a few hours but really couldn't find a solution (hence what brought me here). I tinkered with my code a lot, but still couldn't figure out the issue. From what I could tell everything seemed to be right- but obviously the result wasn't. I had my connection file that connects my code to the phpymadmin database, my HTML file that provides the basic text layout which must be working fine since everything appears, and finally my file that provides the backend mechanics written exclusively in PHP- which is where I'm guessing the problem(s) most likely is/are. I've tried several functions for hours to no avail, watched videos to try to get a better idea but still cannot change the result- not even the error "object not found". I also made it so that the user has to retype their username on the classes page, which also ended with the exact same result. For reference, I am using sublimetext3, the latest version of XAMPP (Running Apache and MySQL) which comes with PHPmyadmin (where my database and tables are that store user info).
This is my backend PHP code (I have some required files that define the buttons, and names like "class1".
if (isset($_GET['submit'])) {
    $box1 = $_GET['class1'];
    $box2 = $_GET['class2'];
    $box3 = $_GET['class3'];
    $box4 = $_GET['class4'];

    $username = $_POST['uid'];
    $stmt = mysqli_stmt_init($conn);
    $result = mysqli_stmt_get_result($stmt);
    if ($row = mysqli_fetch_assoc($result)) {
    $userCheck = username_verify($username, $row['uid']);

    if ($userCheck == true) {
        header("Location: ../class_result.php?");
    exit();
}

/n order to recreate the text fields the user types into known as "classes" see the code below (NOTE THIS IS A SEPARATE FILE):
<form action="classcreation.inc.php" method="GET">

<input type="text" name="uid" placeholder="Username">
<input type="text" name="class1" placeholder="">
<input type="text" name="class2" placeholder="">
<input type="text" name="class3" placeholder="">
<input type="text" name="class4" placeholder="">

<input type="text" name="class5" placeholder="">
<input type="text" name="class6" placeholder="">
<input type="text" name="class7" placeholder="">
<input type="text" name="class8" placeholder="">

<button type="submit" name="submit">Submit</button>

</form>

//And finally my connection file- though I am almost certain this is correct, I'm posting it in order for answerers to see that I have established a connection and the method in which I did so:
$dbservername = "localhost";
$dBUsername = "root";
$dBPassword = "";
$dBName = "loginsystem";

$conn = mysqli_connect($dbservername, $dBUsername, $dBPassword, $dBName);

As previously stated, after the user clicks submit on the classes page, whatever they inputted in the text fields known as "classes", should appear in the corresponding second table. In addition to that, the second table should receive the username of the user typing the information- which was already collected from the first table. But instead the second table is completely empty. Furthermore, they are to be directed to another page that for now just says "Welcome!" (using simple echo statements for the message), but instead receive an "object not found error. Whether the last part is related to the database emptiness I am not 100% sure, but I believe that it is.

A: You never executed a SQL query with the class data.
I recommend changing the HTML so you name all the class input fields name="class[]". This will make $_GET['class'] an array that you can loop over.
if (isset($_GET['submit'])) {
    $username = $_GET['uid'];

    $stmt = $conn->prepare("SELECT username FROM users WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $stmt->bind_result($result_user);
    $userCheck = username_verify($username, $result_user);

    if ($userCheck) {
        $stmt = $conn->prepare("INSERT INTO user_classes (username, class) VALUES (?, ?)");

        $class = null;
        $stmt->bind_param("ss", $username, $class);
        foreach ($_GET['class'] AS $class) {
            if (!empty($class)) { // skip empty input fields
                $stmt->execute();
            }
        }
    }
}

Of course, change the table and column names in the query to match your actual table.
When creating the form from the login page, you can fill in the uid input like this:
<input type="text" name="uid" value="<?php echo $username; ?>" placeholder="Username">

However, putting the username in the form is a bad idea, since the user can edit it to submit data for a different user. Making it readonly or hidden doesn't help much, since the user can still change it using Developer Tools.
It would be better if the login page put it in a session variable, and used that on all subsequent pages. This can't be modified by the user.


text:
Q: Stop firing event SelectionChange (Intersect already used) if it intersects with another range I am using the code below to run a macro Calendar_Advanced if any cell is selected in column M.
Problem: If I select any cell in the same time with Range M:M , the event also fires, like if I selected all row.
Private Sub worksheet_SelectionChange(ByVal Target As Excel.Range)

    Dim LastRow As Long: LastRow = ActiveSheet.Cells(Rows.Count, "B").End(xlUp).Row

    If Not Intersect(Target, Range("M3:M" & LastRow)) Is Nothing Then
        Call Calendar_Advanced
    End If
End Sub

I tried to add to the If condition And Selection.Cells.Count = 1.
It works, but prevents multi selection (Calendar_Advanced) to run on column M.

A: Count the columns to make sure it is just M.
Private Sub worksheet_SelectionChange(ByVal Target As Excel.Range)

    Dim LastRow As Long: LastRow = ActiveSheet.Cells(Rows.Count, "B").End(xlUp).Row
    If Not Intersect(Target, Range("M3:M" & LastRow)) Is Nothing Then
        If Target.Columns.Count = 1 Then
            Calendar_Advanced
        End If
    End If
End Sub


text:
Q: Failure Installing VS 2008 SP1 I am trying to install VS 2008 on Windows 7 x64 and am running into a fatal exception during the installation. The relevant error message is the following:

C:\Users\jayna\AppData\Local\Temp\Microsoft
  Visual Studio 2008
  SP1\VC_IA64Runtime.exe - Exe
  installer's log file/hint
  (%temp%\dd_VC_IA64Runtime*.txt|%temp%..\dd_VC_IA64Runtime*.txt)
  does not exist or is invalid.

I have found several articles on this, the most promising of which indicates that the remote debugger should be uninstalled. I run into another issue when trying to do this which indicates that there are "invalid characters in the Program Files path".

--------------------------- Microsoft Visual Studio 2008 Remote Debugger
  (x64) Setup
  --------------------------- Error 1324.The folder path 'Program Files' contains an invalid character.

Another article suggested turning off Virtual Clone Drive to resolve the latter issue,  which i have done to no avail.
As you can see, I'm hitting some dead ends here. Any suggestions or advice would be most appreciated at this point.

A: Finally got this worked out, and I had to uninstall visual studio 2008. I used the  visual studio 2008 uninstall tool.
Still go the mysterious "Error 1324.The folder path 'Program Files' contains an invalid character." error but finally got to the bottom of that with help from this article. Seems that the installer is trying to write to a location that cannot be written to. I disabled my DVD drive and my SD slot as well as disabling Virtual Clone Drive and any other drives on my machine that I cannot write to, and finally, the uninstall didn't crash on me...
Wow...

A: Before doing anything drastic, what I would recommend is turning off (i.e., uninstalling) all things related to IA64, by using a custom install (or removing already installed items via maintenance). If you are not going to target the Itanium processor (i.e., IA64), there's no point in installing all the junk that comes with VS for it and running into install issues like the one that broke your upgrade (to SP1).

A: I had the error of VS2008 SP1 not installing. The error was 'trying to write to "D:\program files..." ' which was a simulated CD drive with the SP1 iso in it.
I copied the install files from the D: to C:\local and unmounted the image (which removed the D: drive) and installed it successfully from the c: drive.


text:
Q: "Enable foldable display" not showing even if updated android studio to version 3.5 and updated android emulator to 29.1.12 Can anyone tell me why I'm unable to see the "Enable foldable display" option in my emulator settings?
First of all, let me give you the link that describes "How to setup foldable emulator?"
https://androidstudio.googleblog.com/2019/04/emulator-2901-canary.html
Above link has the screenshot attached below where you can see the highlighted portion that describes "Enable foldable display" option:

Own emulator settings screenshot which does not give me the "Enable foldable display" option.

Below are the attached screenshots where you can see that I have updated all the things which required for foldable emulators:
Updated android studio screenshot

Screenshot while updating the android emulator

Below are the two foldable screenshots but where you can see that it is not auto-adjusting itself.

Below is the final un-foldable screenshot

If I'm trying to fold/unfold device than the device is folding/unfolding properly but the graphics part remains to be same. so I guess the issue is of "Enable foldable display" option. so can any help me? Thanks in advance.

A: i had the same problem.
So i installed the canary version of android studio https://developer.android.com/studio/preview
Unistalled the emulator from the sdk manager of android studio and re-installed it.
Now it works!


text:
Q: piping variables into res.render function parameter names in express I have just written some code which loads JSON data into the DOM. This is the full code:
var express = require('express');
var router = express.Router();

// var money = require('./routes/money');

var duckStorySection = {
  para1: "I first met Boa-Duck through Lene-Cow's intervention. I had been scoping out the possibility of an illicit affair with The Green Party of England And Wales' Amelia Womack, but the party propaganda machine had other ideas. Indeed, as soon as I began to show interest the militant ecological wing and more threatening sections of The Womens' Society and LGBTQI (I have a suspicion many election posts are only contested by a single candidate because of internal factional bullying and whispering campaigns, mainly originating from these factions, but I have no direct evidence of causation in these cases) began a concerted campaign of what is, in the parlance of certain political operatives, known as 'this.'",
  para2: "But this is not a story about The Green Party of England and Wales, it is a story of a group of forest animals and their one human companion: myself (Dragon-Bear), Boa-Duck, Lene-Cow and The Master Priest. As I may have alluded to already, I have recently begun an affair with Boa-Duck, and it is with Lene-Cow, my fiancee's, mildly mixed-blessing. She is an anarchist revolutionary and due to her youth and certain affectations about her countenance I had thought her to be naive. She is not. She is slowly developing a network of squatters and upper-middle class drop-outs which she will be using as informants. She also kisses incredibly well, the silk-like seams between her lips opening just a fraction to allow me the merest suggestion of her tongue (I've plagiarised that line from somewhere, but my concern with this piece is far more to inform than to entertain, so you'll have to bear with me).",
  para3: "Boa-Duck is a fairly small duck, by duck standards. She has subtle, delicate fur that is particularly pleasant to run your hands over and around, though I was careful not to brush too fast or with too much urgency as I am an older dragon-bear and I am stridently aware that the possibility of breaking a much younger duck with overly strong affection is ever-present. This, of course, risks overplaying my hand and making me out to be much more powerful than I am, so for balance I must mention several things about myself. The first is that I am poor, excessively so, that I work for a living creating websites which make no money for me whatsoever, as yet, and exist only on the charity of those who understand my situation. The second, which is a particularly galling consideration considering the first issue, and the occasional flareups of dragon temper and temperament which I am occasionally prone to, is that I have for some considerable time been the victim of a concerted campaign of character assassination which began when I started working on my first, never completed, website: Lake of Birds, but which seems to stem from times further past, from my work in technical support and my ever dwindling length of employment, spurred on by my trade union activism, anarchist disruption campaigns, alcoholism, mental health issues or my increasing inability to keep and hold friends, depending on who you believe (I maintain the first two, as a matter of course and, for my perspective at least, certain and unerring truth).",
  para4: "Oh yes, and when I searched her bag I found an envelope addressed to the local DCI, in which no letter had yet been placed.",
  para5: ""
};

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('stories', { title: 'Order Of The Mouse: Phase 1.7 -- Operation Silk Scarf (Narratives)' });
});

router.get('/BoaDuck/:id', function(req, res, next) {
  var id = req.params.id;
  res.render('Boa-Duck/BoaDuckA', { storyText: duckStorySection.para1 });
});

module.exports = router;

At the moment it only loads the JSON data for para1, as you'd expect. What I need is: where I have written duckStorySection.para1 I would like to pipe in the id variable, so that if the address input is, for example, /BoaDuck/2, the res.render renders the JSON data corresponding with the 'para2' key/value pair within duckStorySection. So it should do something roughly like:
res.render('Boa-Duck/BoaDuckA', { storyText: duckStorySection.para[id] })

Only with whatever the correct syntax is for piping in the id parameter. How is this done?

A: you can take an extra step, so instead of having var id = req.params.id; you would instead have var id = 'Para'+req.params.id;, then you can call res.render('Boa-Duck/BoaDuckA', { storyText: duckStorySection[id]}); that would fix your problem. Although given that you're relying on integer indices, this solution wouldn't really be appropriate. I'd suggest just indexing the object with the integer IDs directly

A: Given that your web service API relies on numerical indices (/BoaDuck/:id where :id is a non-negative integer), using keys like those in your story object is inappropriate for your problem. Just give each entry the exact key that you want them to be retrieved by:
var duckStorySection = {
  0: "I first met Boa-Duck ...",
  1: "But this is not a story about...",
  2: "Boa-Duck is a fairly small duck, ...",
  3: "Oh yes, and when I searched her ...",
  4: ""
};

Alternatively, use an array:
var duckStorySection = [
  "I first met Boa-Duck ...",
  "But this is not a story about...",
  "Boa-Duck is a fairly small duck, ...",
  "Oh yes, and when I searched her ...",
  ""
];

Then use the id key directly over the dictionary:
router.get('/BoaDuck/:id', function(req, res, next) {
  var id = req.params.id;
  res.render('Boa-Duck/BoaDuckA', {
    storyText: duckStorySection[id]
  });
});


text:
Q: Count regex matches with streams I am trying to count the number of matches of a regex pattern with a simple Java 8 lambdas/streams based solution. For example for this pattern/matcher :
final Pattern pattern = Pattern.compile("\\d+");
final Matcher matcher = pattern.matcher("1,2,3,4");

There is the method splitAsStream which splits the text on the given pattern instead of matching the pattern. Although it's elegant and preserves immutability, it's not always correct :
// count is 4, correct
final long count = pattern.splitAsStream("1,2,3,4").count();

// count is 0, wrong
final long count = pattern.splitAsStream("1").count();

I also tried (ab)using an IntStream. The problem is I have to guess how many times I should call matcher.find() instead of until it returns false.
final long count = IntStream
        .iterate(0, i -> matcher.find() ? 1 : 0)
        .limit(100)
        .sum();

I am familiar with the traditional solution while (matcher.find()) count++; where count is mutable. Is there a simple way to do that with Java 8 lambdas/streams ?

A: To use the Pattern::splitAsStream properly you have to invert your regex. That means instead of having \\d+(which would split on every number) you should use \\D+. This gives you ever number in your String.
final Pattern pattern = Pattern.compile("\\D+");
// count is 4
long count = pattern.splitAsStream("1,2,3,4").count();
// count is 1
count = pattern.splitAsStream("1").count();

A: The rather contrived language in the javadoc of Pattern.splitAsStream is probably to blame.

The stream returned by this method contains each substring of the input sequence that is terminated by another subsequence that matches this pattern or is terminated by the end of the input sequence.

If you print out all of the matches of 1,2,3,4 you may be surprised to notice that it is actually returning the commas, not the numbers.
    System.out.println("[" + pattern.splitAsStream("1,2,3,4")
            .collect(Collectors.joining("!")) + "]");

prints [!,!,!,]. The odd bit is why it is giving you 4 and not 3.
Obviously this also explains why "1" gives 0 because there are no strings between numbers in the string.
A quick demo:
private void test(Pattern pattern, String s) {
    System.out.println(s + "-[" + pattern.splitAsStream(s)
            .collect(Collectors.joining("!")) + "]");
}

public void test() {
    final Pattern pattern = Pattern.compile("\\d+");
    test(pattern, "1,2,3,4");
    test(pattern, "a1b2c3d4e");
    test(pattern, "1");
}

prints
1,2,3,4-[!,!,!,]
a1b2c3d4e-[a!b!c!d!e]
1-[]

A: You can extend AbstractSpliterator to solve this:
static class SpliterMatcher extends AbstractSpliterator<Integer> {
    private final Matcher m;

    public SpliterMatcher(Matcher m) {
        super(Long.MAX_VALUE, NONNULL | IMMUTABLE);
        this.m = m;
    }

    @Override
    public boolean tryAdvance(Consumer<? super Integer> action) {
        boolean found = m.find();
        if (found)
            action.accept(m.groupCount());
        return found;
    }
}

final Pattern pattern = Pattern.compile("\\d+");

Matcher matcher = pattern.matcher("1");
long count = StreamSupport.stream(new SpliterMatcher(matcher), false).count();
System.out.println("Count: " + count); // 1

matcher = pattern.matcher("1,2,3,4");
count = StreamSupport.stream(new SpliterMatcher(matcher), false).count();
System.out.println("Count: " + count); // 4

matcher = pattern.matcher("foobar");
count = StreamSupport.stream(new SpliterMatcher(matcher), false).count();
System.out.println("Count: " + count); // 0

A: Shortly, you have a stream of String and a String pattern : how many of those strings match with this pattern ?
final String myString = "1,2,3,4";
Long count = Arrays.stream(myString.split(","))
      .filter(str -> str.matches("\\d+"))
      .count();

where first line can be another way to stream List<String>().stream(), ...
Am I wrong ?

A: Java 9
You may use Matcher#results() to get hold of all matches:

Stream<MatchResult>      results()
Returns a stream of match results for each subsequence of the input sequence that matches the pattern. The match results occur in the same order as the matching subsequences in the input sequence.

Java 8 and lower
Another simple solution based on using a reverse pattern:
String pattern = "\\D+";
System.out.println("1".replaceAll("^" + pattern + "|" + pattern + "$", "").split(pattern, 0).length); // => 1

Here, all non-digits are removed from the start and end of a string, and then the string is split by non-digit sequences without reporting any empty trailing whitespace elements (since 0 is passed as a limit argument to split).
See this demo:
String pattern = "\\D+";
System.out.println("1".replaceAll("^" + pattern + "|" + pattern + "$", "").split(pattern, 0).length);    // => 1
System.out.println("1,2,3".replaceAll("^" + pattern + "|" + pattern + "$", "").split(pattern, 0).length);// => 3
System.out.println("hz 1".replaceAll("^" + pattern + "|" + pattern + "$", "").split(pattern, 0).length); // => 1
System.out.println("1 hz".replaceAll("^" + pattern + "|" + pattern + "$", "").split(pattern, 0).length); // => 1
System.out.println("xxx 1 223 zzz".replaceAll("^" + pattern + "|" + pattern + "$", "").split(pattern, 0).length);//=>2


text:
Q: Is Rebol suited to fill up on-line web forms? The title says it almost all.
There are tools like AutoHotKey and AutoIt that allow one to send text to fill up on-line web forms and process the the POST answer.
I know that Rebol can do the latter.  But what about the former?

A: There's a script I wrote which was to look at web forms, extract the various variables, and allow you to POST the form, and then capture the output.  This was just a test prior to figuring out how to automate the login to Stackoverflow which has since been done.


text:
Q: Adding class to dynamically appended elements with jQuery function in ie8 Have tried a few options with no luck. I am using jQuery 1.9.1
Here is my function's code:
(function ($) {
    $.fn.createGallery = function(options) {
        var theObject = $(this);
        var settings = $.extend({
            // These are the defaults.
            server: 'http://localhost/jQuery%20Gallery/images/galleries/',
            galleryName: 'Test',
            galleryWidth: 800,
            galleryImageMargin: 20,
            galleryImageColumns: 2,
            galleryTargetFolder: 'homepage_gallery',
            imageQuality: 100
        }, options);

        var galleryImageWidth = settings.galleryWidth / settings.galleryImageColumns;
        var imageUrl = settings.server+settings.galleryTargetFolder;

        var otherMargin = Math.round(settings.galleryImageMargin / 2);
        var finalImageWidth = Math.round(galleryImageWidth - settings.galleryImageMargin);
        var finalImageHeight = Math.round(galleryImageWidth / 1.4);
        var finalGalleryWidth = settings.galleryWidth - settings.galleryImageMargin;

        $(this).before('');

        $.ajax({
            url: imageUrl,
            success: function(data){
                var extension = '.jpg';
                $(data).find("a:contains("+extension+")").each(function(){
                    // will loop through
                    var filename = $(this).attr("href");
                    $('

').html('').appendTo(theObject);
                });
            }
        });

    };
}(jQuery));

Which is called like this, and works perfectly:
HTML:

jQuery:
$('#images').createGallery({
    server: 'http://localhost/jQuery%20Gallery/images/galleries/',
    galleryName: 'Test',
    galleryWidth: 800,
    galleryImageMargin: 20,
    galleryImageColumns: 2,
    galleryTargetFolder: 'homepage_gallery',
    imageQuality: 100
});

Now, what i want to do is add a class to the new elements so that i can target them in ie8 to add a class to it. I have tried this:
$(document).on('DOMNodeInserted', function(e) {
    $(e.target).addClass('triggerMargin');
});

Which i have placed in the bottom of the function and it works fine in firefox and chrome etc, yet it is totally ignored in ie8. Any ideas?

A: This was fixed by doing the following
theObject.children('li:nth-child(2n+1)').addClass('triggerMargin');
where theObject is equal to $(this) for the object being targeted to add a class to it's children


text:
Q: select not null values from table Mysql guys i have problems with select not null values from my table
$tabelka = mysql_fetch_array(mysql_query("select * from ".$server_db.".paczka_przedmiot where cos = ".$losuj['test1']."
or cos = ".$losuj['test2']."
or cos = ".$losuj['test3']."
or cos = ".$losuj['test4']."
or cos = ".$losuj['test5']."
or cos = ".$losuj['test6']." order by rand() limit 1"));
$szansa = rand(1,100000);

i arleady try with add and (cos IS NOT NULL)
but doesnt work here is my full code
$tabelka = mysql_fetch_array(mysql_query("select * from ".$server_db.".paczka_przedmiot where cos = ".$losuj['test1']."
or cos = ".$losuj['test2']."
or cos = ".$losuj['test3']."
or cos = ".$losuj['test4']."
or cos = ".$losuj['test5']."
or cos = ".$losuj['test6']."  and (cos IS NOT NULL) order by rand() limit 1"));
$szansa = rand(1,100000);

A: You can use alternative query but its not a standard:
SELECT *
FROM table
WHERE NOT (YourColumn <=> NULL);

You also should use uppercase "AND"
You can try this also:
mysql_fetch_array(mysql_query("select * from ".$server_db.".paczka_przedmiot where cos IS NOT NULL AND (cos = ".$losuj['test1']. "
OR cos = ".$losuj['test2']. "
OR cos = ".$losuj['test3']. "
OR cos = ".$losuj['test4']. "
OR cos = ".$losuj['test5']. "
OR cos = ".$losuj['test6']. ") ORDER BY rand() LIMIT 1"));

A: I am afraid that the problem is in the parenthesis. This correction should work (pay attention to the parenthesis):
$tabelka = mysql_fetch_array(mysql_query("select * from ".$server_db.".paczka_przedmiot where (cos = ".$losuj['test1']."
or cos = ".$losuj['test2']."
or cos = ".$losuj['test3']."
or cos = ".$losuj['test4']."
or cos = ".$losuj['test5']."
or cos = ".$losuj['test6']." ) and (cos IS NOT NULL) order by rand() limit 1"));
$szansa = rand(1,100000);


text:
Q: Vue router is not loading the page in Laravel app I am trying to load the vue router pages. Not sure what is wrong. Here is what I have done.
In router.js file I have
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
import testPage from './test.vue';

const defaultRoutes = [
    {path: '/test', component: testPage}
 ]

 export default new Router({
    mode: 'history',
    defaultRoutes
  })

and in app.js file I have
require('./bootstrap');
window.Vue = require('vue');
Vue.component('mainapp', require('./mainapp.vue').default);
import router from './router'
const app = new Vue({
    el: '#app',
    router
});

in mainapp.vue file I have
<template>

this is the main app !

     <router-view></router-view>

</template>

In test.vue I have
<template>

this is the test page

</template>

I can see the h1 text loaded when I hit /test url but the testPage component is not loaded.
Anyone can help? Thanks.

A: Change the name of defaultRoutes to routes.


text:
Q: Terraform EC2 instance does not appear in AWS I've just begun using Terraform and I ran terraform apply on a very simple template. This is the entire content of main.tf:
provider "aws" {
    region = "us-east-1"
}

resource "aws_instance" "marcellusWallace" {
    ami = "ami-2d39803a"
    instance_type = "t2.micro"

    tags {
        Name = "terraform-example"
    }
}

The output from Terraform says that the instance has been created. The state says an instance exists.
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

The problem is, I cannot see it in the AWS EC2 console. Also, the instance is missing in the output of aws ec2 describe-instances.
Where is the instance?

A: try changing the region on top right .
You need to check the region on which you've created your ec2 instance.
you probably are trying to find it somewhere else.

A: main.tf is using us-east-1.
AWS Console and CLI were using us-west-2.
How embarassing.


text:
Q: QML Repeater: parent/child vs ownership can anyone help my clarify what QML Repeater docs mean firstly saying

"Items instantiated by the Repeater are inserted, in order, as children of the Repeater's parent.",

and then

"Note: A Repeater item owns all items it instantiates. Removing or dynamically destroying an item created by a Repeater results in unpredictable behavior."?

Aren't child/parent relationship and ownership the same for visual objects in QML?

A: Object parent (ownership) and visual parent are not the same in QtQuick.  The object parent is set at creation time and is never changed.  The visual parent can be changed at any time via the 'parent' property.
The Repeater creates the delegates and sets ownership to itself and the visual parent to its parent.  In other words, the Repeater owns the delegates, but leaves the visual presentation to its parent (in most cases, a positioner).
The Qt 5 documentation is being improved in this area.  Here is a snippet (the Qt 5 doc snapshot hasn't been updated recently - this is from the source):

There are two separate kinds of parenting in a QML application which
  uses Qt Quick. The first kind is the ownership-parent (also known as
  the QObject parent) which determines object lifetime semantics. The
  second kind is the visual-parent which determines where on the canvas
  an item is drawn, and also certain properties (for example, opacity
  applies to visual children).
In almost all cases, the visual-parent is identical to the
  ownership-parent. See the documentation about the Visual Parentfor
  more in-depth information on the topic.

Unfortunately the  "Visual Parent" topic hasn't been written yet.


text:
Q: I need all the employee under a supervisor i have a below described situation
EmpID      Name        SupervisorID
1          A           9
2          B           8
3          C           1
4          D           3

I need all the employees under supervisor ID 1
Here EmployeeID 3 is under 1 i need 4 is is also under 3
Following output is required.
EmpID   Name    SupervisorID
3       C       1
4       D       3

A: You need to Use Recursive CTE for this.Try this,
With CTE as
(
select EmpID,Name,SupervisorID from Emp
where SupervisorID  =1
Union All

select a.EmpID,a.Name,a.SupervisorID from Emp as a
    inner join CTE b on a.SupervisorID= b.EmpID

)

select * from CTE

Fiddle Demo Here
Please take a look at this question also, it is same like your question. Sql server CTE and recursion example

A: Nobody expects the Spanish Inquisition a HierarchyId. These days, whenever I see an org structure (like the one you have here), I reach for the HierarchyId datatype. In essence, it allows you to answer questions like "which value(s) are 'under' this one?" and "which value(s) does this one belong to?". Here's how I'd implement it:
alter table dbo.Employee add OrgStructure HierarchyId null;

with h as (
   select EmployeeId, SupervisorId, '/' + cast(EmployeeId as varchar) + '/' as h
   from dbo.Employee as e
   where e.SupervisorId is null --employees w/o a supervisor

   union all

   select e.EmployeeId, e.SupervisorId, h.h + '/' + cast(EmployeeId as varchar) + '/'
   from dbo.Employee as e
   join h
      on e.SupervisorId = h.SupervisorId
)
update e
set OrgStructure = h.h
from dbo.Employee as e
join h
   on e.EmployeeId = h.EmployeeId;

create index [IX_Employee_OrgStructure] on dbo.Employee (OrgStructure)

Now that the heavy lifting is done, actually answering your problem is trivial:
select *
from dbo.Employee as supervisor
join dbo.Employee as reports
   on reports.OrgStructure.IsDescendantOf(supervisor.OrgStructure)
where supervisor.EmployeeId = 1

The advantage that I see is that you're not calculating the hierarchy on the fly every time you need to answer this type of question. You do it once and you're done.


text:
Q: How to create a websocket endpoint in an existing spring application I'm trying to make available a new websocket endpoint in an existing spring application.
I'm following the documentation at https://docs.spring.io/spring/docs/4.3.2.RELEASE/spring-framework-reference/html/websocket.html#websocket-server-handler . But based on documentation I should configure the DispatcherServlet or use WebSocketHttpRequestHandler.
How can I make available the websocket endpoint without any change in the web.xml config file ?
This is what I tried, but not working (Client error 404 not found).
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ws="http://jax-ws.dev.java.net/spring/core" xmlns:wss="http://jax-ws.dev.java.net/spring/servlet"
  xmlns:websocket="http://www.springframework.org/schema/websocket"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
                           http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd
                           http://jax-ws.dev.java.net/spring/core http://jax-ws.dev.java.net/spring/core.xsd
                           http://jax-ws.dev.java.net/spring/servlet http://jax-ws.dev.java.net/spring/servlet.xsd
                           http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket.xsd">

    <websocket:handlers  allowed-origins="*">
        <websocket:mapping path="/ws" handler="websocketService"/>
        <websocket:handshake-interceptors>
            <bean class="org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor"/>
        </websocket:handshake-interceptors>
    </websocket:handlers>

    <bean id="websocketService" class="com.krios.SocketHandler"/>

</beans>

Class file:
public class SocketHandler extends TextWebSocketHandler {

    List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message)
            throws InterruptedException, IOException {

        for(WebSocketSession webSocketSession : sessions) {
            Map value = new Gson().fromJson(message.getPayload(), Map.class);
            webSocketSession.sendMessage(new TextMessage("Hello " + value.get("name") + " !"));
        }
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //the messages will be broadcasted to all users.
        sessions.add(session);
    }

}

A: I can provide you the java configuration (you can then change it to xml yourself or use it as java class and scan it from xml)
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
    @Bean
    public MessagingWebSocketHandler webSocketHandler() {
        //handler of your websocket. should be a class implementing WebSocketHandler.
        //You could also extend AbstractWebSocketHandler or TextWebSocketHandler and override methods
        return new MessagingWebSocketHandler();
    }

    @Bean
    public WebSocketContainerFactoryBean createWebSocketContainer() {
        WebSocketContainerFactoryBean container = new WebSocketContainerFactoryBean();
        container.setMaxTextMessageBufferSize(StaticConfig.MAXIMUM_WS_TEXT_BUFFER_SIZE);
        container.setMaxBinaryMessageBufferSize(StaticConfig.MAXIMUM_WS_BINARY_BUFFER_SIZE);
        container.setMaxSessionIdleTimeout(StaticConfig.MAXIMUM_WS_SESSION_IDLE_TIMEOUT);
        container.setAsyncSendTimeout(StaticConfig.MAXIMUM_WS_ASYNC_SEND_TIMEOUT);
        return container;
    }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
        webSocketHandlerRegistry.addHandler(webSocketHandler(), "/message").setAllowedOrigins("*"); // you could also get handler from context
    }

}

I hope it hepls.
update
I myself don't use xml based  configuration. But the simplest way is to add this java code then scan it from xml. For example, by adding this line to your spring servlet configuration xml you can scan your configuration package or whole project package.
<context:component-scan base-package="com.my.company.config" />

Then your WebSocketConfig class must be under com.my.company.config
Documentation Of Websocket support and configuration is here. On section Create and Configure a WebSocketHandler you can read about xml configuration. I havent test it myself tho.


text:
Q: Run grpc Java example: Connection refused: no further information: localhost/[0:0:0:0:0:0:0:1]:50051
Log
Microsoft Windows [Version 10.0.19045.2604]
(c) Microsoft Corporation. All rights reserved.

C:\Users\admin\Downloads\grpc-java-1.53.0\examples>gradle installDist

BUILD SUCCESSFUL in 25s
22 actionable tasks: 22 executed
C:\Users\admin\Downloads\grpc-java-1.53.0\examples>dir
 Volume in drive C is OS
 Volume Serial Number is E2F9-6397

 Directory of C:\Users\admin\Downloads\grpc-java-1.53.0\examples

22/02/2023  11:18 SA    <DIR>          .
22/02/2023  11:18 SA    <DIR>          ..
22/02/2023  11:18 SA    <DIR>          .gradle
09/02/2023  05:49 SA    <DIR>          android
22/02/2023  11:18 SA    <DIR>          build
09/02/2023  05:49 SA             3.911 BUILD.bazel
09/02/2023  05:49 SA             6.619 build.gradle
09/02/2023  05:49 SA    <DIR>          example-alts
09/02/2023  05:49 SA    <DIR>          example-gauth
09/02/2023  05:49 SA    <DIR>          example-hostname
09/02/2023  05:49 SA    <DIR>          example-jwt-auth
09/02/2023  05:49 SA    <DIR>          example-orca
09/02/2023  05:49 SA    <DIR>          example-servlet
09/02/2023  05:49 SA    <DIR>          example-tls
09/02/2023  05:49 SA    <DIR>          example-xds
09/02/2023  05:49 SA    <DIR>          gradle
09/02/2023  05:49 SA             8.070 gradlew
09/02/2023  05:49 SA             2.763 gradlew.bat
09/02/2023  05:49 SA             4.254 pom.xml
09/02/2023  05:49 SA             9.175 README.md
09/02/2023  05:49 SA               267 settings.gradle
09/02/2023  05:49 SA    <DIR>          src
09/02/2023  05:49 SA             1.686 WORKSPACE
               8 File(s)         36.745 bytes
              15 Dir(s)  91.353.567.232 bytes free

C:\Users\admin\Downloads\grpc-java-1.53.0\examples>build\install\examples\bin\hello-world-client
thg 2 22, 2023 11:24:41 SA io.grpc.examples.helloworld.HelloWorldClient greet
INFO: Will try to greet world ...
thg 2 22, 2023 11:24:41 SA io.grpc.examples.helloworld.HelloWorldClient greet
WARNING: RPC failed: Status{code=UNAVAILABLE, description=io exception, cause=io.grpc.netty.shaded.io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: no further information: localhost/[0:0:0:0:0:0:0:1]:50051
Caused by: java.net.ConnectException: Connection refused: no further information
        at java.base/sun.nio.ch.Net.pollConnect(Native Method)
        at java.base/sun.nio.ch.Net.pollConnectNow(Net.java:672)
        at java.base/sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:973)
        at io.grpc.netty.shaded.io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:337)
        at io.grpc.netty.shaded.io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:334)
        at io.grpc.netty.shaded.io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:710)
        at io.grpc.netty.shaded.io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:658)
        at io.grpc.netty.shaded.io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:584)
        at io.grpc.netty.shaded.io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:496)
        at io.grpc.netty.shaded.io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:997)
        at io.grpc.netty.shaded.io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
        at io.grpc.netty.shaded.io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
        at java.base/java.lang.Thread.run(Thread.java:1589)
}
C:\Users\admin\Downloads\grpc-java-1.53.0\examples>java -version
java version "19.0.2" 2023-01-17
Java(TM) SE Runtime Environment (build 19.0.2+7-44)
Java HotSpot(TM) 64-Bit Server VM (build 19.0.2+7-44, mixed mode, sharing)

C:\Users\admin\Downloads\grpc-java-1.53.0\examples>javac -version
javac 19.0.2

C:\Users\admin\Downloads\grpc-java-1.53.0\examples>gradle -version

------------------------------------------------------------
Gradle 8.0.1
------------------------------------------------------------

Build time:   2023-02-17 20:09:48 UTC
Revision:     68959bf76cef4d28c678f2e2085ee84e8647b77a

Kotlin:       1.8.10
Groovy:       3.0.13
Ant:          Apache Ant(TM) version 1.10.11 compiled on July 10 2021
JVM:          19.0.2 (Oracle Corporation 19.0.2+7-44)
OS:           Windows 10 10.0 amd64

C:\Users\admin\Downloads\grpc-java-1.53.0\examples>date
The current date is: 22/02/2023
Enter the new date: (dd-mm-yy)

C:\Users\admin\Downloads\grpc-java-1.53.0\examples>


text:
Q: Excel: I want to find cells that have duplicate text WITHIN the cell itself I know how to find duplicate cells using conditional formatting, but that's comparing text between 2 or more cells.
I need to bring back cells that have duplicate text within each of the cells.
Example:
-allstar company allstar co
-best products inc
-chemical corporation chemical corp
-dumont petro
-EPT corp E P T corp

Here are 5 cells with text.  Cells 1,3, and 5 have duplicate text and should be brought back, or highlighted.
I don't know VBA so if it can be avoided, that would be best.
Thanks all

A: So assuming that you're looking for whole words, we can separate them by space.  I know you want to avoid VBA, but that is the only way I know how to do this in any sort of automated fashion.  So, if you insert a module to your spreadsheet, you can use this function I wrote here, and then call it from your cell.
Option Explicit
Public Function DuplicateWordCheck(text As String) As Boolean
    Dim textArray As Variant, i As Integer, j As Integer
    DuplicateWordCheck = False
    textArray = Split(text, " ")
    For i = LBound(textArray) To UBound(textArray)
        For j = i + 1 To UBound(textArray)
            If textArray(i) = textArray(j) Then
                DuplicateWordCheck = True
                Exit Function
            End If
        Next
    Next
End Function

So if your examples start in cell A1, in cell B1 put the formula =DuplicateWordCheck(A1)


text:
Q: top command doesn't show me the full path of COMMAND I wrote this shell script named example.sh on Linux.
#!/bin/sh

TOPLOG=/tmp/top.log
date +%H:%M:%S >> ${TOPLOG}
top -b -c -n 1 |head -n 8 |tail -n 2 >> ${TOPLOG}
echo >> ${TOPLOG}

When I run it with the command "sh /tmp/example.sh", texts in top.log is like
  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
17980 cybereas  20   0 1478m  73m  18m S  2.0  0.5   1360:59 /opt/cybereason/sensor/bin/cybereason-sensor

However, when I run this script with this crontab
*/1 * * * * sh /tmp/example.sh

texts in top.log is shown like
  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
17980 cybereas  20   0 1478m  73m  18m S  2.0  0.5   1360:59 /opt/cybereason/sen

The output of "COMMAND" is omitted when it is a little long.
Is there any solution for this?
I appretiate for any idea.
Thank you.

A: When not printing to a regular file, and not a terminal (>> "$TOPLOG"), top is truncating output to the standard terminal width of 80 columns.
If your top has the -w switch, add -w 512 for a larger maximum width.


text:
Q: Is there any free/open source map engine for iPhone? I have a bunch of map images and i wonder if there is any free/open source map engine that I can use for iPhone development. Just like google map api but they are for native development

A: I would highly recommend using OpenStreetMap as a mapping framework rather then the Google API mapping.

*

*OpenStreetMap is less restrictive in license terms then Google maps.

*You can provide better mapping data with OpenStreetMap then with Google maps using custom or predefined mapping layers.

In regards to engines (frameworks/api's) that access the OSM data. Check out the following.

*

*route-me

*CloudMade
If you would like to find more information on using OSM on the iPhone/iPod Touch check out the OSM iPhone Wiki
Hope this information helps.

A: It looks like there is, and it's called Route-me.  Licensed under licensed under the BSD license.

A: Adding some frameworks/api's that access the OSM data, I recommend you to have a look at  Navit (it's an open source projects) and skobbler's OSM SDK (it's a good solutions with a free tier plan that might be large enough for your needs).

A: Another possibility is cloudmade.com - its a layer on the OSM and includes an iphone library routing toolkit etc.


text:
Q: CoreData - Adding # of months to a NSDate within a NSPredicate I have an entity in my CoreData model that contains these 2 attributes:
startDate (NSDate)
terms (int)

I need to grab all the objects where the start plus the terms (which is months) is within the next 30 days.
Here is what I need to do in some pseudo code:
[NSPredicate predicateWithFormat:@"(startDate.months + terms) <= %@", date30DaysFromNow];

This may not be possible (or I am just being dumb).
I know the alternate solution would be to create a new attribute that creates this date when I import the objects.. but if I can I would rather not have to add another attribute if I don't have to.
Thanks!

A: Add an attribute, which is an NSDate, to your model object. Whenever the date or terms attributes are updated (or on-demand depending on what you use it for ad how often) update this new date to be startDate.months + terms (most likely using NSDateComponents or - (id)dateByAddingTimeInterval:(NSTimeInterval)seconds. Then use this attribute in your predicate.


text:
Q: PhP: Breaking an array into more lines I am programming php since lot's of years. Now I have a new wish. I want to make an array with a long string more readable:
$var = array( 'help' => 'This is a very long help text. This is a very long help text. This is a very long help text.');

First try: I have tried this without success:
$var = array( 'help' => 'This is a very long help text.'
. 'This is a very long help text.'
. 'This is a very long help text.');

Second try: And I have tried this without success:
$var = array( 'help' => 'This is a very long help text.' . 'This is a very long help text. This is a very long help text.');

By the way: There is no chance to build the string before, I have to do it in this line. How can I break the array into more lines?
I was asked to show the real example, here it is:
class JKWerte {
   public static $purifyoptions = array(
     'HTML.Allowed' => 'table, thead, tbody, tfoot, th, tr, td, img[src|alt], div, span, p, br, ul, ol, li, *[class], *[style], *[height], *[width], h1, h2, h3, h4, a[href|title], b, i, em, strong' );

   public function test() {

   }
}

The variable is an attribute of a class and I call it with
    JKWerte::purifyoptions;

A: Static class variables may not be initialized with expressions in PHP.
Here is one way to split the string via HEREDOC-Syntax, so long as it may contain additional spaces and linebreaks:
<?php
class JKWerte {
   public static $purifyoptions = array(
     'HTML.Allowed' => <<<EOT
     table, thead, tbody,
     tfoot, th, tr, td,
     img[src|alt], div,
     span, p, br, ul, ol,
     li, *[class], *[style],
     *[height], *[width], h1,
     h2, h3, h4, a[href|title],
     b, i, em, strong
EOT
   );

   public function test() { }
}

var_dump(JKWerte::$purifyoptions);
?>

Outputs:
array(1) {
  ["HTML.Allowed"]=>
  string(213) "     table, thead, tbody,
     tfoot, th, tr, td,
     img[src|alt], div,
     span, p, br, ul, ol,
     li, *[class], *[style],
     *[height], *[width], h1,
     h2, h3, h4, a[href|title],
     b, i, em, strong"
}

Alternatively you can define the content of your static variable later, e.g. after the class definition:
<?php
class JKWerte {
   public static $purifyoptions = array(
     'HTML.Allowed' => ''
   );

   public function test() { }
}

JKWerte::$purifyoptions['HTML.Allowed'] = 'table, thead, tbody, '
     .'tfoot, th, tr, td, '
     .'img[src|alt], div, '
     .'span, p, br, ul, ol, '
     .'li, *[class], *[style], '
     .'*[height], *[width], h1, '
     .'h2, h3, h4, a[href|title], '
     .'b, i, em, strong';

var_dump(JKWerte::$purifyoptions)
?>

Outputs:
array(1) {
  ["HTML.Allowed"]=>
  string(172) "table, thead, tbody, tfoot, th, tr, td, img[src|alt], div, span, p, br, ul, ol, li, *[class], *[style], *[height], *[width], h1, h2, h3, h4, a[href|title], b, i, em, strong"
}


text:
Q: Why there are unwind symbols present in my shared library I am using readelf on one of the shared libraries I have. When I read the symbols, the list containing lot of unwind symbols like below.

23: 001e0c48 36 FUNC GLOBAL DEFAULT 13 _Unwind_Resume
5998: 00000000 0 FUNC WEAK DEFAULT UND __gnu_Unwind_Find_exidx
5999: 001e0b54 0 FUNC GLOBAL DEFAULT 13 __gnu_Unwind_Restore_VFP_D
6000: 001e0b44 0 FUNC GLOBAL DEFAULT 13 __gnu_Unwind_Restore_VFP
6001: 001e0b64 0 FUNC GLOBAL DEFAULT 13
  __gnu_Unwind_Restore_VFP_D_16_to_31
6002: 001e0b74 0 FUNC GLOBAL DEFAULT 13 __gnu_Unwind_Restore_WMMXD
6003: 001e0bfc 0 FUNC GLOBAL DEFAULT 13 __gnu_Unwind_Restore_WMMXC
6005: 001e0080 8 FUNC GLOBAL DEFAULT 13 _Unwind_GetCFA
6006: 001e0088 164 FUNC GLOBAL DEFAULT 13 __gnu_Unwind_RaiseException
6007: 001e012c 28 FUNC GLOBAL DEFAULT 13 __gnu_Unwind_ForcedUnwind
6008: 001e0148 116 FUNC GLOBAL DEFAULT 13 __gnu_Unwind_Resume
6009: 001e01bc 32 FUNC GLOBAL DEFAULT 13
  __gnu_Unwind_Resume_or_Rethrow
6010: 001e01dc 4 FUNC GLOBAL DEFAULT 13 _Unwind_Complete
6011: 001e01e0 24 FUNC GLOBAL DEFAULT 13 _Unwind_DeleteException
6012: 001e01f8 92 FUNC GLOBAL DEFAULT 13 _Unwind_VRS_Get
6013: 001e027c 92 FUNC GLOBAL DEFAULT 13 _Unwind_VRS_Set
6014: 001e0304 200 FUNC GLOBAL DEFAULT 13 __gnu_Unwind_Backtrace
6018: 001e07d0 864 FUNC GLOBAL DEFAULT 13 _Unwind_VRS_Pop
6019: 001e0b5c 0 FUNC GLOBAL DEFAULT 13 __gnu_Unwind_Save_VFP_D
6020: 001e0b4c 0 FUNC GLOBAL DEFAULT 13 __gnu_Unwind_Save_VFP
6021: 001e0b6c 0 FUNC GLOBAL DEFAULT 13
  __gnu_Unwind_Save_VFP_D_16_to_31
6022: 001e0bb8 0 FUNC GLOBAL DEFAULT 13 __gnu_Unwind_Save_WMMXD
6023: 001e0c10 0 FUNC GLOBAL DEFAULT 13 __gnu_Unwind_Save_WMMXC
6025: 001e0c24 36 FUNC GLOBAL DEFAULT 13 ___Unwind_RaiseException
6026: 001e0c24 36 FUNC GLOBAL DEFAULT 13 _Unwind_RaiseException
6027: 001e0c48 36 FUNC GLOBAL DEFAULT 13 ___Unwind_Resume
6028: 001e0c6c 36 FUNC GLOBAL DEFAULT 13 ___Unwind_Resume_or_Rethrow
6029: 001e0c6c 36 FUNC GLOBAL DEFAULT 13 _Unwind_Resume_or_Rethrow
6030: 001e0c90 36 FUNC GLOBAL DEFAULT 13 ___Unwind_ForcedUnwind
6031: 001e0c90 36 FUNC GLOBAL DEFAULT 13 _Unwind_ForcedUnwind
6032: 001e0cb4 36 FUNC GLOBAL DEFAULT 13 ___Unwind_Backtrace
6033: 001e0cb4 36 FUNC GLOBAL DEFAULT 13 _Unwind_Backtrace
6035: 001e113c 16 FUNC GLOBAL DEFAULT 13 _Unwind_GetRegionStart
6036: 001e114c 28 FUNC GLOBAL DEFAULT 13
  _Unwind_GetLanguageSpecificData
6037: 001e1168 8 FUNC GLOBAL DEFAULT 13 _Unwind_GetDataRelBase
6038: 001e1170 8 FUNC GLOBAL DEFAULT 13 _Unwind_GetTextRelBase

I checked the source code of library but could not find references to these symbols. I am guessing, while compiling the source files or linking into library they might have used some flag to generate these symbols.
Any idea which clang++ flag is used to generate these symbols?
And what is the use of these symbols?

A: I would say it is the exception handling, if you do not use exception, you may compile with -fno-exceptions
see https://refspecs.linuxfoundation.org/LSB_5.0.0/LSB-Core-generic/LSB-Core-generic/libgcc-sman.html


text:
Q: How to validate server side code in Javascript I am getting some value from server , if the value is false i need to show alert message on UI without refreshing or postbacking the page.
What i am doing currently is i get the value from server i declare one hidden control and store that value in hidden control and in aspx page i write one JS method to check if that value is false show the alert message, but the problem is i have to do this on click on a button which is present in code behind
so as soon as i click on that button JS code gets executed before i get value from server.
    function fnvalidation() {
        if (document.getElementById("<%=hdnCtrl.ClientID%>").value == false) {
            alert('Please submit it again');
            return false;
}
}

On page load i am registering like this :
 btnSave.Attributes.Add("onclick", "return fnvalidation()");

C# Code :
bValidate = CommonUtility.ValidateOutput();
hdnCtrl.Value = bValidate.ToString();//Storing value in hidden variable
if(bvalidate == false)
{
//Call javascript method fnvalidation
}

How to call this JS method correctly when value is false coming from server ?
Thanks.

A: I think you can use

Page.ClientScript.RegisterStartupScript

inside your condition if(bvalidate == false) condition like  then no need to rely on the value to be set ( i.e in java script function you can remove checking the hidden field value simply alert the user.
Also you can remove this code  btnSave.Attributes.Add("onclick", "return fnvalidation()")
Page.ClientScript.RegisterStartupScript(this.GetType(), "validateFnscript", "fnvalidation()",
true);

A: If your page needs to fetch data from the server without refreshing the page, then you need to use AJAX.  Which comes down to two things:

*

*Create an AJAX endpoint in server-side code.

*Consume that AJAX endpoint from client-side code.

The server-side code likely has several options.  HTTP Handlers, empty ASPX pages which clear and response and set a new content type, maybe even Web Methods?  It's been a long time since I've used WebForms, so I'm not 100% sure what the recommended approach is right now.  But I think Web Methods are what you're looking for.  So your code-behind would have something like this:
public partial class MyPage : Page
{
    [WebMethod]
    public static string GetValue()
    {
        return "some value";
    }
}

Then, assuming you're using jQuery for example, you would call that endpoint from your client-side code:
$.ajax({
    type: "POST",
    url: "MyPage.aspx/GetValue"
}).done(function (data) {
    // respond to the value in "data"
}).error(function () {
    // there was an error
});

Now your client-side button click handler can use that, or something like it, to fetch the value from the server.  If that's all that button needs to do then don't make it an asp:Button but instead just an input type="button" so that it doesn't post back the whole page.  Keeping it as a server-side button would mean canceling the event propagation in JavaScript, which gets ugly with asynchronous operations because there's no immediate way to resume event propagation, you'd have to manually invoke the post back.


text:
Q: Unable to run migrations VS2015 community edition I've recently tried to make some updates to an ASP MVC project and I can no longer run migrations. This was working fine previously - not sure whats happend that I'm now getting the following error
PM> update-database

update-database : The term 'update-database' is not recognized as the
name of a cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included, verify that the path is
correct and try again.
At line:1 char:1
+ update-database
+ ~~~~~~~~~~~~~~~
+ CategoryInfo          : ObjectNotFound: (update-database:String) [],     CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

What could possible be wrong? This has started after a fresh repo pull. I've tried restarting visual studio but no joy.


text:
Q: Could we produce an expression for such a function? I am looking for a function that takes $n$ parameters $ x_1, x_2, ... x_n $, such that, if and only if
any $i$th parameters are equal, then the outputs are equal. Mathematicaly,
$$ f:R^n \rightarrow R,\ \forall (i = 1,2,...n)  ({x_i}_1={x_i}_2 \leftrightarrow  f(...{x_i}_1...)=f(...{x_i}_2...)) $$
Could we generalize this idea for $n$ parameters? I am looking for a mathematical expression of this function, only satisfying this property. Any operator is plausible as long as it is in mathematical concept (logical, modula , arithmetic etc.).


text:
Q: Signal level (RSSI) Bluetooth from Android Tell me how to programmatically read the signal level (RSSI) of the Bluetooth connection for an already connected device from the Android application?

A: Assuming this is a BLE GATT connection, use readRemoteRssi() on the BluetoothGatt.


text:
Q: Adding pause and resume methods to stopwatch class How do I add pause and resume methods to this class?
When you pause and it is already paused then nothing should happen.
Also if you resume when it is not paused nothing should happen.
public class Stopwatch {
  private final long start;

  public Stopwatch() {
    start = System.currentTimeMillis();}

  public double elapsedTime() {
    long now = System.currentTimeMillis();
    return (now - start) / 1000.0;}

  public static void main(String[] args) {
    Stopwatch watch = new Stopwatch();
    double total = 0.0;

    for (int i = 0; i < 100000000; i++)
      total += Math.random();

    double time = watch.elapsedTime();

    StdOut.println(time);

  }
}

A: Why don't you hold a variable accumulatedTime and when the pause() method is called you append the accumulated time to it
accumulatedTime += System.currentTimeMillis() - start / 1000.0;

When resume() is called you could reset start
start = System.currentTimeMillis();

And then elapsedTime() would add the two:
public double elapsedTime() {
   long now = System.currentTimeMillis();
   return ((now - start) / 1000.0) + accumulatedTime;
}

You'd also need to track the paused state - a isPaused boolean instance variable perhaps? And then your pause()/resume() can response if appropriate
e.g. in pause() method:
if (isPaused) {
   return;   //do nothing
}

A: Paused time is stored in the additionaltime variable, this will be used to remove paused time when called elapsedTime. PauseStart variable stores when the pause is called(After resume call the additionaltime is calculated)
private long additionalTime;

private long pauseStart;

public void pause() {
    if (pauseStart == 0) {
        pauseStart = System.currentTimeMillis();
    }
}

public void resume() {
    if (pauseStart != 0) {

        long stopTime = System.currentTimeMillis() - pauseStart;

        additionalTime += stopTime;

        pauseStart = 0;
    }
}

public double elapsedTime() {
    long now = System.currentTimeMillis();

    if (pauseStart != 0) {

        long stopTime = System.currentTimeMillis() - pauseStart;

        additionalTime += stopTime;

        pauseStart = 0;
    }

    return ((now - start) - additionalTime) / 1000.0;
}

A: It looks like your stopwatch is currently tied to the System time (System.currentTimeMillis()), so to pause the application you would need to subtract the time that you paused from your elapsed time somehow
What you could do though is to have save the time that you pause the clock, and what time it is resumed:
pause() {
  if(!alreadyPaused)
    timePaused = System.currentTimeMillis();
}
resume() {
  timeResumed = System.currentTimeMillis();
  totalTimePaused = previousPausedTimes + (timeResumed-timePaused);
}

and then in your elapsedTime():
  public double elapsedTime() {
    long now = System.currentTimeMillis();
    return (now - start - totalTimePaused) / 1000.0;
  }


text:
Q: What can be said about Schur indices, given only the character table? Let $\chi$ be an irreducible (complex) character of a finite group, $G$. The Schur index $m_{K}(\chi)$ of $\chi$ over the field $K$ is the smallest positive integer $m$ such that $m\chi$ is afforded by a representation over the field $K(\chi)$. The most interesting case is $K=\mathbb{Q}$. Given the character table, or only the particular character one is interested in, one can usually derive bounds for $m(\chi)=m_{\mathbb{Q}}(\chi)$. For example, $m(\chi)$ divides $\chi(1)$ and $n[\chi^n,1_G]$ for all $n\in \mathbb{N}$ (Fein), and the Benard-Schacher Theorem tells us that $\mathbb{Q}(\chi)$ contains a primitive $m(\chi)$-th root of unity.
On the other hand, the example of the quaternion group $Q_8$ and the dihedral group $D_8$ shows that two groups might have identical character tables, but corresponding characters with different Schur indices.  I am curious wether there are examples that are even worse than this.
Notation: To state this more precisely, I'll make the following assumptions: We are given two finite groups $G$ and $H$, such that there is a bijection $\tau\colon {\rm Cl}(G) \to {\rm Cl}(H)$ from the classes of $G$ to the classes of $H$, and such that $\psi \mapsto \psi \circ \tau$ is a bijection ${\rm Irr}(H)\to {\rm Irr}(G)$. Now:

Is there an example with $m(\chi)/m(\chi\circ\tau)\notin \{1,2,1/2\}$ for some $\chi\in {\rm Irr}(H)$?
Is there an example with $G$ of odd order and $m(\chi) / m(\chi\circ\tau)\neq 1$ for some $\chi \in {\rm Irr}(H)$?

Now let us assume that we know the power maps of the character table. These are the maps $\pi_n^G\colon {\rm Cl}(G)\to {\rm Cl}(G)$ induced by $g\mapsto g^n$. (These maps are stored in the tables of the character table library of GAP.) Given these maps, one can compute $[\chi_C, 1_C]$ for cyclic subgroups $C\leq G$, for example. Also we can compute the Frobenius-Schur Indicator and thus the Schur index over $\mathbb{R}$.
Now assume that $\tau\circ \pi_n^G = \pi_n^H\circ \tau$ in the above situation (then $(G,H)$ is called a Brauer pair).

Is there a Brauer pair $(G,H)$ such that $m(\chi)/m(\chi\circ\tau)\neq 1$ for some $\chi\in {\rm Irr}(H)$?

I would appreciate any examples or (pointers to) results that show the impossibility of such examples.
Thanks

A: The following is a theorem of K. Kronstein:

Theorem: for $k$ a number field or a nonarchimedean completion of a number field, if it is possible to detect the Schur index $m_k$ of all finite groups from their character table and power maps, then $m_k(\chi) \leq 2$ for all characters $\chi$ of finite groups.

In particular, for a finite group $G$, the map $\tau: G \times G \to G \times G$ defined by $\tau(x,y) = (x,y^{-1})$ induces a bijection on conjugacy classes preserving the power maps $x \mapsto x^n$ and a bijection on characters, but does not necessarily preserve Schur indices larger than 2. Thus, the map $\tau$ provides a positive answer to the first and third questions. It also provides a positive answer to the second question once one produces an example of a group of odd order with a character with Schur index greater than 2.
I provide Kronstein's proof here:
Suppose $\chi$ is a character of $G$, $k$ is a number field or nonarchimedean completion of a number field, and the Schur index $m = m_k(\chi)$ is at least $3$.
Let $K = k(\chi)$, let $V$ be an irreducible $KG$-module affording the character $m\chi$, and let $D = End_{KG}(V)$. It is a division algebra with order $m$ in the Brauer group of $K$.
Consider the characters $\chi \boxtimes \chi$ and $\chi \boxtimes \chi^\vee$ on $G \times G$. Then
$$End_{K(G\times G)}(V\boxtimes V) = D \otimes_K D.$$
Since $m>2$, $D \otimes_K D$ is not split, so $\chi\boxtimes \chi$ has Schur index greater than 1. However, $$End_{K(G \times G)}(V \boxtimes V^\vee) = D \otimes_K D^{op},$$
which splits over $K$, and thus $\chi \boxtimes \chi^\vee$ has Schur index 1.

Reference:
Karl Kronstein. Character tables and the Schur index. In Representation Theory of Finite Groups and Related Topics,
volume 21 of Proceedings of Symposia in Pure Mathematics, pages 97–98. American Mathematical Soc., 1971


text:
Q: Multiplying two lists leads to stack overflow test :: [Int] -> [Int]
test l   | (length l) > 5 = l
         | otherwise = test l ++ take 1 searchSpace
    where searchSpace = zipWith (*) [100..999] [100..999]

The above code provides me with a stack overflow. I'm assuming that Haskell is fully evaluating and storing the result of zipWith in searchSpace. What would be the lazy way of creating this list, if I just want to have my program progressively apply take 1?

A: You have an infinite loop. If we pass a list like [1..6] (chosen so that length is greater than 5) to test it reduces like this:
test [1..6]
test [1..6] ++ take 1 searchSpace
test [1..6] ++ take 1 searchSpace ++ take 1 searchSpace
test [1..6] ++ take 1 searchSpace ++ take 1 searchSpace ++ take 1 searchSpace
...

The top of the evaluation tree becomes (++) in step two which must evaluate its left argument to proceed.
[]     ++ ys = ys
(x:xs) ++ ys = x : (xs ++ ys)

So the net result is that the function barely does any work at all and spends all of its time repeatedly diving into your infinite loop branch.

A: If l is <= 5, you are calling test l recusrively without a terminating condition.
You rather want something like
test :: [Int] -> [Int]
test l   | (length l) > 5 = l
         | null l = take 1 searchSpace
         | otherwise = test init_of_l ++ take 1 searchSpace
    where searchSpace = zipWith (*) [100..999] [100..999]
          init_of_l = init l

working example here


text:
Q: Last Available value MDX I have a requirement where in i am to extract data from a cube, within the SSRS dataset using the query builder ,with the time dimension in the result set, across a range of dates. The conditions are

*

*The measures are to be displayed for each day of the date range.

*The sub total row should have the last available measures value for that time range.

*There is a time filter (currently a single date filter with a multi select option).

my MDX is as below.

*

*The measure has a 'Sum' as the aggregation type.

*I have a calculated measure with the scope defined as below.
 SCOPE([MEASURES].[Measure1]);
    SCOPE([Date].[Date].MEMBERS);
       THIS = TAIL(EXISTING ([Date].[Date].MEMBERS),1).ITEM(0)  ;
    END SCOPE;
 END SCOPE;

This above scope statement works perfectly. however, when i select in more that one date member this query slows WAYYYYYYY down. Performance numbers are

*

*Across 1 date - 4 seconds

*Across 2 dates - 22 minutes

*Across 3 dates - unknown (in Hours)

This drastic degradation in performance goes away if i remove the scope statement, which makes me thing that there should be a better way to do the same. the final report query is as below.
SELECT
  NON EMPTY
    {[Measures].[Measure1]} ON COLUMNS
  ,NON EMPTY
    { [Dimension1].[Dimension1].[Dimension1].ALLMEMBERS*
      [Dimension2].[Dimension2].[Dimension2].ALLMEMBERS*
      [Dimension3].[Dimension3].[Dimension3].ALLMEMBERS*
      [Date].[Date].[Date].ALLMEMBERS
    } ON ROWS
FROM (
      SELECT {[Date].[Date].&[2014-06-13T00:00:00]
              ,[Date].[Date].&[2014-06-16T00:00:00] } ON COLUMNS
      FROM [Cube]
     )

So the question again is, Is there a way to do the last available value part of the scope statement so as to have a better performance? Also, if there is another way to write the final mdx that would help the performance?.
Please let me know if there are anythings unclear regarding the question.
Thanks
Srikanth

A: The first optimization step would be to change your query to
SELECT
  NON EMPTY
    {[Measures].[Measure1]} ON COLUMNS
  ,NON EMPTY
    { [Dimension1].[Dimension1].[Dimension1].ALLMEMBERS*
      [Dimension2].[Dimension2].[Dimension2].ALLMEMBERS*
      [Dimension3].[Dimension3].[Dimension3].ALLMEMBERS*
      {[Date].[Date].&[2014-06-13T00:00:00], [Date].[Date].&[2014-06-16T00:00:00] }
    } ON ROWS
FROM [Cube]

Furthermore, I am not sure why you added the SCOPE([Date].[Date].MEMEBER); (probably Date].[Date].MEMBERS, actually). Maybe it helps to omit it and the corresponding END SCOPE.


text:
Q: Change body font in moderncv without affecting the other fonts Is there a way to change the body font in moderncv (v0.7) without affecting the other fonts (for example \firstnamefont)?
If I change the font via setting \sfdefault it influences not only the body font but all fonts of sections and title in the document.

A: You have some predefined commands to change the fonts of some elements:
\namefont
\titlefont
\addressfont
\sectionfont
\subsectionfont
\hintfont
\quotefont
Redefining those commands you can change the font attributes for the associated elements. Here's a little example in which I changed the font associated to the first four commmands to use Zapf Chancery:
\documentclass[11pt,a4paper,sans]{moderncv}
\moderncvstyle{classic}
\moderncvcolor{blue}
\usepackage[scale=0.75]{geometry}
\usepackage[T1]{fontenc}

\firstname{John}
\familyname{Doe}
\title{CV}
\address{Baker Street}{Southampton}
\mobile{+1~(234)~567~890}
\phone{+2~(345)~678~901}
\fax{+3~(456)~789~012}
\email{john@doe.org}
\homepage{www.johndoe.com}

\renewcommand*\namefont{\fontfamily{pzc}\fontsize{40}{48}\selectfont}
\renewcommand*\titlefont{\fontfamily{pzc}\fontsize{20}{24}\selectfont}
\renewcommand*\addressfont{\fontfamily{pzc}\selectfont}
\renewcommand*\sectionfont{\fontfamily{pzc}\fontsize{20}{24}\selectfont}

\begin{document}

\maketitle

\section{Test Section}
\cventry{2012}{Title}{Institute}{City}{}{Description}
\cventry{2012}{Title}{Institute}{City}{}{Description}

\section{Test Section}
\cventry{2012}{Title}{Institute}{City}{}{Description}
\cventry{2012}{Title}{Institute}{City}{}{Description}

\end{document}

If you want to change the font for some particular argument(s) of, for example, the \cventry command you can define your own command to include the necessary redefinition(s); here's an example in which I defined a \Mycventry command using Zapf Chancery for the last argument of \cventry:
\documentclass[11pt,a4paper,sans]{moderncv}
\moderncvstyle{classic}
\moderncvcolor{blue}
\usepackage[scale=0.75]{geometry}
\usepackage[T1]{fontenc}
\usepackage{lipsum}
\firstname{John}
\familyname{Doe}
\title{CV}
\address{Baker Street}{Southampton}
\mobile{+1~(234)~567~890}

\phone{+2~(345)~678~901}
\fax{+3~(456)~789~012}
\email{john@doe.org}
\homepage{www.johndoe.com}

\newcommand\Mycventry[6]{%
  \cventry{#1}{#2}{#3}{#4}{#5}{\fontfamily{pzc}\selectfont#6}}

\begin{document}

\maketitle

\section{Test Section}
\Mycventry{2012}{Title}{Institute}{City}{}{\fontfamily{pzc}\selectfont \lipsum[2]}
\cventry{2012}{Title}{Institute}{City}{}{\lipsum[2]}

\end{document}

And the output showing the comparison between \cventrya and \Mycventry: