text:
Q: read -a not working as expected in Bash For some reason when using "read -a" my script is only taking the first element of the line into the array. For example, when inputting a string such as "canada China", the output of the program simply reads:
canada
c
Canada changed to uppercase.

Instead of:
canada China
c
Canada Changed to uppercase.
C
China Already uppercase.

The instructions for my assignment are as follows:
Create a script that reads the user's input and stores it in an Array. Then, loop over the Array and :

*

*If the first character is lowercase, change it to be uppercase and write next to it "Changed to uppercase".

*If the first letter is already uppercase, output the input word then write next to it "Already uppercase".

*If the first character is not a letter, output the input word then write next to it "Doesn't Start with a letter".
Use an Associative Array to do the conversion from lowercase to uppercase [converterArray=([a]=A [b]=B …)]

And here is my code:
#!/bin/bash

declare -A converterArray
converterArray=([a]=A [b]=B [c]=C [d]=D [e]=E [f]=F [g]=G [h]=H [i]=I [j]=J [k]=K [l]=L [m]=M [n]=N [o]=O [p]=P [q]=Q [r]=R [s]=S [t]=T [u]=U [v]=V [w]=W [x]=X [y]=Y [z]=Z)

read -p "Enter elements separated by space, return to end: " -a inputArray

lowercasemsg=" Changed to uppercase."
uppercasemsg=" Already uppercase."
notlettermsg=" Doesn't start with a letter."

echo $inputArray

for word in $inputArray; do
    firstchar=${word:0:1}
    echo $firstchar

    case $firstchar in
    [a-z]*)
        word = ${converterArray[$firstchar]}${word:1}
        echo $word$lowercasemsg
        ;;
    [A-Z]*)
        echo $word$uppercasemsg
        ;;
    *)
        echo $word$notlettermsg
        ;;
    esac

done

EDIT: Thanks to John's help the problem has been solved. I also fixed an issue with checking the case of the letter ([a-z] vs. [[:lower:]]), and removed the unnecessary "echos" for debugging.
#!/bin/bash

declare -A converterArray
converterArray=([a]=A [b]=B [c]=C [d]=D [e]=E [f]=F [g]=G [h]=H [i]=I [j]=J [k]=K [l]=L [m]=M [n]=N [o]=O [p]=P [q]=Q [r]=R [s]=S [t]=T [u]=U [v]=V [w]=W [x]=X [y]=Y [z]=Z)

read -p "Enter elements separated by space, return to end: " -a inputArray

lowercasemsg=" Changed to uppercase."
uppercasemsg=" Already uppercase."
notlettermsg=" Doesn't start with a letter."

for word in "${inputArray[@]}"; do
    firstchar=${word:0:1}

    case $firstchar in
    [[:lower:]]*)
        inputString=${converterArray[$firstchar]}${word:1}
        echo $word$lowercasemsg
        ;;
    [[:upper:]]*)
        echo $word$uppercasemsg
        ;;
    *)
        echo $word$notlettermsg
        ;;
    esac

done

(2nd edit: Fixed line where I forgot to put spaces around equals sign, originally forgotten in previous edit)

A: If $array is an array, "${array[@]}" gives all of the array elements. A bare $array references only the first element.
echo "${inputArray[@]}"

for word in "${inputArray[@]}"; do
    ...
done


text:
Q: Cython slower compared to Python when using OpenCV I am experimenting with Cython and OpenCV and trying to benchmark the performance for image manipulation. I have tried optimizing my Cython code as much as I could, but I still get slower performance with it. I understand most of the code is executed in C because of OpenCV, yet I expected better performance for python loops using Cython. Can anyone tell me if there anything I can do to improve it? Following is my code:
# load_images.py

import cv2
from random import randint
import numpy as np

def fetch_images(n):
    def get_img():
        x = randint(640, 6144)
        y = randint(640, 6144)
        return np.random.rand(x,y, 3).astype(np.uint8)

    return [get_img() for _ in range(n)]

def resize_img(img):
    img = cv2.resize(img, (640, 640))
    return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

def preprocess(images):
    return [resize_img(img) for img in images]

# load_images_cy.pyx

import cv2
from random import randint
import numpy as np
cimport numpy as np
cimport cython
ctypedef np.uint8_t DTYPE_t

@cython.boundscheck(False)
@cython.wraparound(False)

cdef np.ndarray[DTYPE_t, ndim=3] get_img():
    cdef int x = randint(640, 6144)
    cdef int y = randint(640, 6144)
    return np.random.rand(x,y, 3).astype(np.uint8)

cpdef list fetch_images(int n):
    cdef int _;
    return [get_img() for _ in range(n)]

cdef np.ndarray[DTYPE_t, ndim=2] resize_img(np.ndarray[DTYPE_t, ndim=3] img):
    cdef np.ndarray[DTYPE_t, ndim=3] im;
    im = cv2.resize(img, (640, 640))
    return cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

cpdef np.ndarray[DTYPE_t, ndim=3] preprocess(list images):
    cdef np.ndarray[DTYPE_t, ndim=3] img;
    cdef np.ndarray[DTYPE_t, ndim=3] collection = np.empty((len(images), 640, 640), dtype=np.uint8);
    cdef int i;

    for i, img in enumerate(images):
        collection[i] = resize_img(img)

    return collection

# main.py

import load_images_cy
import load_images

import timeit

images = load_images.fetch_images(20)

result_cy = timeit.timeit(lambda: load_images_cy.preprocess(images), number=20)
result_py = timeit.timeit(lambda: load_images.preprocess(images), number=20)
print(f'{result_py/result_cy} times faster')

Output:
0.9192241989059127 times faster

A: Cython is primarily meant for interfacing with C code, and writing Python extension modules more easily. While performance improvements can be obtained through Cython, it is not intended to be a drop-in speed-up for Python code.
PyPy, however, is intended to be a more-or-less drop-in speed-up for Python code. It provides an alternate interpreter which is generally faster than CPython, the reference/default Python implementation.
Also, your decorators here:
@cython.boundscheck(False)
@cython.wraparound(False)

cdef np.ndarray[DTYPE_t, ndim=3] get_img():
    ...

Only apply to get_img - not any of the other functions below. Not sure if that was intentional or not. There should not be a blank line between these.
If you want to stick with Cython, and gain performance improvements through it, consider altering the compilation options, such as providing -O2 or -O3.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can assigning an out value be avoided? My question is theoretical, please do not suggest code edits or alternatives.
I have a method as follows:
private bool SomeMethod(int D, out SomeStruct SXY) {

    if (D<0) {
         return false;
    }

    SXY = new SomeStruct(D);
    return true;
}

And I consume this method in the following way:
if (true) {
    SomeStruct SXY; // Local scope, not used anywhere else.
    if (SomeMethod(12, out SXY)) {
        // Use SXY only when it has a meaningful value
    }
}

The compiler is complaining about the SXY out value not being assigned before return in SomeMethod.
Can we avoid the useless assignment and struct creation in SomeMethod when it is obvious - I would assume, even for the compiler - that the SXY will only be used if it is meaningful?
Could the code analysis go deep enough to allow compile in the above situation?
Edit:
Freggar asked for it, the actual code I used in production is like:
private SomeStruct? SomeMethod(int D) {

    if (D < 0) {
        return null;
    }

    return new SomeStruct(D);
}

Called as:
if (true) {
    SomeStruct? SXY = SomeMethod(12);
    if (SXY != null) {
        // Use SXY only when it is not null
    }
}

Again, this is just a simplified code to demonstrate the gist of it. SomeMethod is more complex and may return with null at multiple places, also calling it is different. My purpose was to understand why Roslyn cannot tell if SomeMethod can safely return without SXY being assigned.

A: There is no corellation between the out parameter and your return value from the compiler's point of view. So it cannot and will not do any compiler magic.
The clean approach would be to split your function into the precondition and object-creation part:
private bool CanCreateSomeStruct(int D) {
    return D >= 0;
}

private SomeStruct CreateSomeStruct(int D) {
    return new SomeStruct(D);
}

And then use it like that:
if (CanCreateSomeStruct(D)) {
     SomeStruct SXY = CreateSomeStruct(D);
}

A: The rules of the C# language don't require that the return value of any method with out parameters be bool nor assign any meaning to the return value such that validity could be determined.
For all the compiler knows both branches of your SomeMethod are meant to assign a real value to SXY. Maybe then the bool result is meant to indicate whether the result provided is a "live" value or one obtained by a cache. So what we currently have is a bug because we forgot to assign a value in the false branch and the compiler caught a bug for us!
That's why there is no meaning ascribed to the result of the method, and we just have a simpler set of rules to abide by - you have to definitely assign out parameters.
If you're concerned about memory usage by having to assign a default(SomeStruct) to SXY, perhaps the issue is that the struct is larger than is recommended and maybe should be a class instead?


text:
Q: spyne - How to get a wrapping element surrounding a complex type I want to recreate the following wsdl type definition
<!-- Existent non spyne specification -->
<s:element name="GetVehiclesResponse">
   <s:complexType>
       <s:sequence>
         <s:element minOccurs="0" maxOccurs="1" ref="s1:vehiclesResponse"/>
         <s:element ... />
    </s:sequence>
  </s:complexType>
</s:element>

How do i get there? Cause when inheriting from ComplexModel my result looks similar to this
<!-- Result from ComplexModel -->
<xs:complexType name="GetVehiclesResponse">
  <xs:sequence>
    <xs:element ... />
    ...
  </xs:sequence>
</xs:complexType>

Should I implement a class that is deriving from ComplexModelBase?

A: The two notations are equivalent.


text:
Q: trying to copy files with extensions, shutil problems When I run my code with shutil in #shutil.copyfile(dst, file), it prints everything out without error. I have issues using shutil
import os
import shutil

src = os.path.expanduser('~/Downloads')
print(src)
os.getcwd()
dst = os.getcwd
print(dst)

for root, dirs, files in os.walk(src):
    for file in files:
        if file.endswith(('.txt', '.md')):
           print(os.path.join(root,file))
           #shutil.copyfile(dst, file)

EDIT:
I made the following changes to my code and it worked! Thank you everyone for your help
from os.path import join

dst = os.getcwd()

shutil.copyfile(join(src, file), join(dst, file))

Can anyone help me copy all the files, including the ones with same name (example 'readme' or other files that would be saved and have the same name)


text:
Q: Using a page variable as an if statements conditon within a control I have the following problem:
I have the variable $GiftID on my page.
I want to cycle through all of my gift objects using my function getGifts().
When the $ID of the gift is equal to the $GiftID of the page then I want something to happen.
Here is an example of my code:
$GiftID
<% control getGifts %>
   <% if CurrentPage.GiftID = ID %>This is it!<% end_if %>
<% end_control %>

Using $CurrentPage.GiftID works when printing inside the control, but how on earth do I access it from within the if statement?
I am using SS 2.9

A: I have not used ss2.9 yet, but as far as I know you can not do <% if Top.GiftID = ID %> in any 2.x version, you can not compare 2 variables, you can only compare with static vaules. (but it is possible in 3.0)
So you have to do it on php side, if you want to only display the slected gift object, then:

*

*if GiftID is actually the DB field for the has_one relation of Gift then you can just do <% control Gift %> and it will scope the Gift object with the GiftID

*If you really have GiftID saved as DB field or otherwise, then can do
public function getGift() { return DataObject::get_by_id('Gift', $this->GiftID); }
both ways you can do <% control Gift %> and it will scope it
If you want to list all gifts and mark the current gift then you need to do it on php side (foreach the set of objects and set a flag on the current object)

A: You should be able to access the current page with Top:
<% control getGifts %>
   <% if Top.GiftID = ID %>This is it!<% end_if %>
<% end_control %>


text:
Q: Application.LoadLevel - Leaves behind multiple instances of scripts / objects I am trying to restart my current level from a script attached to the Main Camera through:
Application.LoadLevel (Application.loadedLevel);

Once I complete it, multiple instances of one script are running (There may be many I haven't checked yet). For example, I use one script that subscribes to events from multiple scripts to decrease the "bullets left" and "score".
When I noticed that they get decreased or increased by multiple numbers instead of having one step at a time, I printed using Debug.Log() for when I shoot. It prints twice after the first Application.loadLevel, then thrice after the 2nd reset and so on. Every time I restart the scene , the script is running that many times with that many decrease or increase in "Score" / "bullets left".
There's one more script that has a null animator issue which I believe is due to the multiple instances issue as well.
Everything looks like it's getting messed up due to multiple instances issue. ALSO I HAVE ABSOLUTELY NO DontDestroyOnLoad anywhere in my game.
I use events and delegates. In the place from where I publish the event, when I use Debug.Log() to see if it publishes so many times, it only prints it once as expected. But the scripts which listens to these events :
void OnEnable()
{
    BulletController.scoreUP += scoreIncrease;
    BulletController.bulletCreated += bulletDecrease;
}
void OnDisable()
{
    BulletController.scoreUP -= scoreIncrease;
    BulletController.bulletCreated -= bulletDecrease;
}

listens and executes twice, or thrice or so on for every restart of scene.

A: You're issue is to do with your OnDisable function. When destroying objects, OnDisable doesn't get called.
You need a function called OnDestroy which unsubscribes from those events in the same way (You probably want to keep your OnDisable function in case there are any objects you do disable).


text:
Q: partial derivative of a function I need help with this problem. its finding the partial derivative of a function but i tried it two ways and just couldn't seem to get the right answer.
For the function
$z=(6xy^2)/(x^2y^3+10)$
the first partial derivative $∂z/∂y$ is?
when i did the problem i got $-((6*x*y(x^2*y^3-20))/(x^2*y^3+10)^2)$ but it wasn't right can anyone maybe take me in the right direction? I just seem to have messed up the derivation somewhere and would really like some help understanding what I did wrong and how I can do better at these problems

A: Function:
$$z(x,y)=\frac{6xy^2}{x^2y^3+10}$$
Find:
$$\frac{\partial z(x,y)}{\partial y}=\frac{\partial}{\partial y}\left(\frac{6xy^2}{x^2y^3+10}\right)=6x\cdot\frac{\partial}{\partial y}\left(\frac{y^2}{x^2y^3+10}\right)$$
Now, use the quotient rule:
$$\frac{\text{d}}{\text{d}y}\left(\frac{u}{v}\right)=\frac{v\cdot\frac{\text{d}u}{\text{d}y}\left(\frac{u}{v}\right)-u\cdot\frac{\text{d}v}{\text{d}y}\left(\frac{u}{v}\right)}{v^2}$$
Then, use the power rule:
$$\frac{\text{d}}{\text{d}y}\left(y^n\right)=ny^{n-1}$$
Then, differentiate sums term by term and factor out constants.


text:
Q: Programs doesn't add more than one Node to the tree. Searching comes Up with only one node info #include<iostream>
#include <conio.h>

using namespace std;

class Student_Node{
public:
    Student_Node *right,*left;
    int ID;
    string First_Name;
    int Age;
    float Test_Score,CGPA;

};

class Student_Tree{
Student_Node *root;

public:
    Student_Tree()
    {
        root=NULL;
    }
    void take_input();
    void build_tree(int id,string name,int age,float score,float cgpa);
    void BST_search();
    void input_sort(Student_Node *n, Student_Node *r);
    void Search (int id);
    void searching(int id,Student_Node *r);
    void Node_Depth(int id);
    void FindHeight();
    int Height(Student_Node* root);
};

/////////////////////////////////////////////////////////////////////////

This is my build function. In take_input() i apply a loop to give the user choice to add as many nodes as he wants. In the loop the user gives data which is passed the obj.build_tree(int id,string name,int age,float score,float cgpa); But it adds only one Node and nothing more. When i call my Search (int id) it only outputs the data of first node.
 void Student_Tree::build_tree(int id,string name,int age,float score,float
  cgpa)
  {
  Student_Node *n= new Student_Node();
    n->ID=id;
  n->First_Name=name;
 n->Age=age;
 n->CGPA=cgpa;
 n->Test_Score=score;
 if(root==NULL)
 {
    root=n;
 }
 else
 {
    input_sort(n,root);
 }
 }

void Student_Tree::input_sort(Student_Node *n, Student_Node *r)
{
if(r->ID>=n->ID)
{
    if(r->left!=NULL)
    {
        input_sort(n,r->left);
    }
    else
    {
        n=r->left;
    }
}

if(r->ID<=n->ID)
{
    if(r->right!=NULL)
    {
        input_sort(n,r->right);
    }
    else
    {
        n=r->right;
    }
    }
}

/////// inout takes input from user, then sends it to the build fucntion
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
void Student_Tree::Search (int id)
{
Student_Node *n=new Student_Node();
n=root;
if(n==NULL)
{
    cout<<"Tree is empty"<<endl;
}
else
{
    searching(id,root);
}
}
void Student_Tree::searching(int id,Student_Node *r)
{
if(r->ID>=id)
{
    if(r->ID==id)
    {
        cout<<"ID"<<" "<<"Age"<<" "<<"CGPA"<<" "<<"First Name"<<" "<<"Test
Score"<<endl;
        cout<<"-------------------------------------------------------------
---------"<<endl;
        cout<<r->ID<<" "<<r->Age<<" "<<r->CGPA<<" "<<r->First_Name<<" "<<r->
Test_Score;
    }
    else
    {
        searching(id,r->left);
    }
}
else if(r->ID<=id)
{
    if(r->ID==id)
    {
        cout<<r->ID;
    }
    else
    {
        searching(id,r->right);
    }
}
else
{
    cout<<"Roll No Not found"<<endl;
   }
}

void Student_Tree::FindHeight()
{
Height(root);
}

 int Student_Tree::Height(Student_Node *r)
{
if(r==NULL)
{
    return 0;
}

else
{
    int lb=Height(r->left);
    int rb=Height(r->right);
    cout<<max(lb,rb)+1;
    return max(lb,rb)+1;
}
}
/////////////////////////////////////////////////////////////////////////
void Student_Tree::Node_Depth(int id)
{
int depth = 0;
Student_Node *temp = new Student_Node;
temp = root;
// Run the loop untill temp points to a NULL pointer.
while(temp != NULL)
{
    depth++;
    if(temp->ID == id)
    {
        cout<<"\nData found at depth: "<<depth<<endl;
        return;
    }
    // Shift pointer to left child.
    else if(temp->ID > id)
        temp = temp->left;
    // Shift pointer to right child.
    else
        temp = temp->right;
}

cout<<"\n Data not found";
return;
}

void take_input()
{
Student_Tree obj;
    int ID;
    string First_Name;
    int Age;
    float Test_Score,CGPA;
    cout<<"How many students data do you want to enter?"<<endl;
    int no; cin>>no;
    for(int i=0;i<no;i++)
    {
    cout<<"\t\t\t\tEnter Student Id"<<endl;
    cout<<"\t\t\t\t";cin>>ID;
    cout<<"\t\t\t\tEnter Student First Name"<<endl;
    cout<<"\t\t\t\t";cin>>First_Name;
    cout<<"\t\t\t\tEnter Student Age"<<endl;
    cout<<"\t\t\t\t";cin>>Age;
    cout<<"\t\t\t\tTest Student Score"<<endl;
    cout<<"\t\t\t\t";cin>>Test_Score;
    cout<<"\t\t\t\tEnter Student CGPA"<<endl;
    cout<<"\t\t\t\t";cin>>CGPA;
    obj.build_tree(ID,First_Name,Age,Test_Score,CGPA);
    }
}
int main()
{
Student_Tree obj;
take_input();
cout<<"Enter node"<<endl;
int n; cin>>n;
obj.Node_Depth(n);
obj.FindHeight();
cout<<"\nEnter id to search"<<endl; int id; cin>>id;
obj.Search(id);

return 0;
}

A: Your build_tree function calls input_sort to add an additional node. But input_sort never adds anything to anything else. What code do you think actually attaches a second node into the tree? There doesn't seem to be any.
 if(root==NULL)
 {
    root=n;
 }
 else
 {
    input_sort(n,root);
 }

The first part of this code adds n to the tree if the tree is empty. The second part is expected to add n to the three if the tree is not empty.
void Student_Tree::input_sort(Student_Node *n, Student_Node *r)
{
    if(r->ID>=n->ID)
    {
        if(r->left!=NULL)
        {
            input_sort(n,r->left);
        }
        else
        {
            n=r->left;

We're already hosed right here. This function was called with n being the new node to be added and no other pointer to that node was stored anywhere. If we change the value of n here, we lose the only pointer we had to the node we were supposed to add.
Even if we don't get hosed here, there's no code in input_sort anywhere to actually add a node to the tree, and build_tree is expecting it to.


text:
Q: Examples of quadratic extensions K, L of $\mathbb{Q}$ such that KL has some properties. Let $p$ be a prime integer, I want to find $p$ and K, L  extensions of $\mathbb{Q}$ such that

*

*K, L contain each a unique prime lying over $p$ but KL does not.

Another, different, triplet such that

*The residue field extension of $\mathbb{Z}_p$ is trivial for K and L but not for KL.

Is there a way to easily compute such examples?
I can give examples of other cases (e.g p totally ramified in K and L but not in KL or inert in K and L but not in KL) but I'm finding the two above a bit more difficoult.

A: (Answering the edited version with the misunderstanding cleared. The answer to the misunderstood version has been deleted, but can be seen in the edit history.)
Observe that because $K/\Bbb{Q}$ and $L/\Bbb{Q}$ are Galois, cyclic of order two, the extension $KL/\Bbb{Q}$ is also Galois with Galois group $C_2\times C_2$. Therefore:

*

*for each prime $p$, the equation $efg=4$ holds, and

*it is impossible to have $f=4$ for any prime $p$, because then the Galois group should have a subquotient isomorphic to $C_4$.

*Consequently $KL$ will have a third intermediate quadratic field $F$ that we can use as a tool for studying the primes of the compositum.

The second point is a bit more advanced, and not needed to answer this. But it does play a role.

*

*Namely, if $f(K/\Bbb{Q},p)=2=f(L/\Bbb{Q},p)$ then the condition (1) is automatic. So we can simply pick two integers $m,n$, coprime to $p$, such that neither is a quadratic residue modulo $p$. Then $K=\Bbb{Q}(\sqrt n)$ and
$L=\Bbb{Q}(\sqrt m)$ will work. For example with $p=5$, $n=2$, $m=7$ we see that
$p$ is inert in $K=\Bbb{Q}(\sqrt2)$ and in $L=\Bbb{Q}(\sqrt7)$. As a product of two quadratic non-residues $2\cdot7=14$ is a quadratic residue modulo $5$, and therefore $5$ splits in $F=\Bbb{Q}(\sqrt{14})\subset KL$. Consequently, $p=5$ is a product of two prime ideals of $\Bbb{Q}(\sqrt2,\sqrt7)$, both with inertia degree $f=2$.

*To find an example of (2) we need to use ramification. The prime $p=3$ is ramified in both $K=\Bbb{Q}(\sqrt3)$ and $L=\Bbb{Q}(\sqrt{15})$, so $f(K/\Bbb{Q},3)=f(L/\Bbb{Q},3)=1$. But $\sqrt{3}\cdot\sqrt{15}=3\sqrt{5}$, so we see that $F=\Bbb{Q}(\sqrt5)\subseteq KL$. As $5$ is not a quadratic residue modulo $3$, it follows that $3$ is inert in $F$. Therefore $f(KL/\Bbb{Q},3)=2$ as well.

It may be worth noting that we cannot get (2) when $p$ splits in both $K$ and $L$. For in that case $p$ will split compeletely in $KL$ (the product of two quadratic residues is a quadratic residue). The combination of ramified in $K$ + split in $L$ obviously won't work either. Ramified in both $K$ and $L$ is the only combo that works here. Of course, we still need to be careful for the prime $p$ might still split in the third quadratic intermediate field $F$.


text:
Q: Spring Boot enable  like in web.xml I have a problem with Spring Boot configuration. I got exception on some mobile devices which should use sockets:
java.lang.IllegalArgumentException: Async support must be enabled on a servlet and for all filters involved in async request processing. This is done in Java code using the Servlet API or by adding "<async-supported>true</async-supported>" to servlet and filter declarations in web.xml. Also you must use a Servlet 3.0+ container
    at org.springframework.util.Assert.isTrue(Assert.java:65)
    at org.springframework.http.server.ServletServerHttpAsyncRequestControl.<init>(ServletServerHttpAsyncRequestControl.java:59)
    at org.springframework.http.server.ServletServerHttpRequest.getAsyncRequestControl(ServletServerHttpRequest.java:202)
    at org.springframework.web.socket.sockjs.transport.session.AbstractHttpSockJsSession.handleInitialRequest(AbstractHttpSockJsSession.java:202)
    at org.springframework.web.socket.sockjs.transport.handler.AbstractHttpSendingTransportHandler.handleRequestInternal(AbstractHttpSendingTransportHandler.java:66)
    at org.springframework.web.socket.sockjs.transport.handler.AbstractHttpSendingTransportHandler.handleRequest(AbstractHttpSendingTransportHandler.java:58)
    at org.springframework.web.socket.sockjs.transport.TransportHandlingSockJsService.handleTransportRequest(TransportHandlingSockJsService.java:254)
    at org.springframework.web.socket.sockjs.support.AbstractSockJsService.handleRequest(AbstractSockJsService.java:322)
    at org.springframework.web.socket.sockjs.support.SockJsHttpRequestHandler.handleRequest(SockJsHttpRequestHandler.java:88)
    at org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter.handle(HttpRequestHandlerAdapter.java:51)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    ...

As I see from the exception, I have to enable async processing by adding true into the web.xml file. But this is the problem because I don't have it - our project uses Spring Boot.
Is there any way to provide the same functionality in Spring Boot like  does?

A: Maybe it worth to mention that Spring Boot has async-support enabled by default for dispatcher servlet and all filters
Quotation from github:

We automatically set async-supported to true
  because the DispatcherServlet knows how to work with such requests and
  it's basically up to individual controller methods to return something
  like a DeferredResult. Furthermore, we also set async-supported for
  any filter (provided via getServletFilters) along with setting the
  DispatcherType for each filter to include ASYNC.

At least my practice supports this statement

A: Even though I am late to the party I am posting my working solution for posterity.
I had faced the same issue and tried the solution suggested by @Artem Bilan. But after debugging the code, I came to know that the servletRegistrationBean.isAsyncSupported() is by default true.
.
The actual error is being generated by the code block is from the method org.springframework.web.context.request.async.StandardServletAsyncWebRequest.startAsync()  and we are getting this error when getRequest().isAsyncSupported() is false. Despite the ServletRegistrationBean#asyncSupported value is true, HttpServletRequest#isAsyncSupported() method value is always set to false for all API requests.
The Exerpt of the code block Code Reference
Assert.state(getRequest().isAsyncSupported(),
                "Async support must be enabled on a servlet and for all filters involved " +
                "in async request processing. This is done in Java code using the Servlet API " +
                "or by adding \"<async-supported>true</async-supported>\" to servlet and " +
                "filter declarations in web.xml.");

When analyzing further, I came to know that requestAttributes -> Globals.ASYNC_SUPPORTED_ATTR decides whether the request has to be processed in an Async way or not.
During the normal scenario, the requests do not have Globals.ASYNC_SUPPORTED_ATTR requestAttribute, hence request.asyncSupported will be false, if we manually add that requestAttribute ASYNC_SUPPORTED_ATTR value as true for all the requests using something like filters then request#asyncSupported value will be set to true as per the below code block Code Reference
specialAttributes.put(Globals.ASYNC_SUPPORTED_ATTR,
                new SpecialAttributeAdapter() {
                    @Override
                    public Object get(Request request, String name) {
                        return request.asyncSupported;
                    }

                    @Override
                    public void set(Request request, String name, Object value) {
                        Boolean oldValue = request.asyncSupported;
                        request.asyncSupported = (Boolean)value;
                        request.notifyAttributeAssigned(name, value, oldValue);
                    }
                });

Though there is no explicit answer, I have implemented a workaround for this issue. To Summarize all the required changes are listed below:

*

*Add a filter to set the request attribute as request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR, true)

@Component
public class AsyncSupportFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR, true);
        chain.doFilter(request, response);
    }
}

*Add filter to into your filter chain, in my case I have registered my filter into the spring context as below.

@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
   @Autowired
   private AsyncSupportFilter asyncSupportFilter = null;
   @Override
   public void configure(HttpSecurity httpSecurity) {

       httpSecurity.addFilter(asyncSupportFilter);
       // we can add the filter before any filter like as httpSecurity.addFilterBefore(asyncSupportFilter , BasicAuthenticationFilter.class);
   }
}

A: You just need to define dispatcherServlet @Bean:
@Bean
public ServletRegistrationBean dispatcherServlet() {
    ServletRegistrationBean registration = new ServletRegistrationBean(
            new DispatcherServlet(), "/");
    registration.setAsyncSupported(true);
    return registration;
}

It overrides that default one from DispatcherServletAutoConfiguration.

A: mysolution:
@WebFilter(value = {"/subscriberinfo/query/single/*"})
public class ...Filter{
}

TO
@WebFilter(value = {"/subscriberinfo/query/single/*"}, asyncSupported = true)
public class ...Filter{
}


text:
Q: How do you get logstash to output to elasticsearch on a private ip? Unfortunately, Logstash is not attempting to output to Elasticsearch at the correct IP address. Elasticsearch is configured at a private ip address on port 9200. Logstash is attempting to output to Elasticsearch at localhost:9200. This is shown in the log below.
{:timestamp=>"2016-02-08T16:27:58.572000-0500", :message=>"Attempted to send a bulk request to Elasticsearch configured at '[\"http://localhost:9200/\"]', but Elasticsearch appears to be unreachable or down!", :client_config=>{:hosts=>["http://localhost:9200/"], :ssl=>nil, :transport_options=>{:socket_timeout=>0, :request_timeout=>0, :proxy=>nil, :ssl=>{}}, :transport_class=>Elasticsearch::Transport::Transport::HTTP::Manticore, :logger=>nil, :tracer=>nil, :reload_connections=>false, :retry_on_failure=>false, :reload_on_failure=>false, :randomize_hosts=>false}, :error_message=>"Connection refused", :class=>"Manticore::SocketException", :level=>:error}

My configuration files are below:
/etc/elasticsearch/elasticsearch.yml
network.host: PRIVATE_IP_ADDRESS

/opt/logstash/conf.d/logstash.conf
input {
  beats {
    port => 5044
  }
}

output {
  elasticsearch {
    hosts => ["PRIVATE_IP_ADDRESS:9200"]
    manage_template => false
    index => "%{[@metadata][beat]}-%{+YYYY.MM.dd}"
    document_type => "%{[@metadata][type]}"
  }
}

I have the same file at /etc/logstash/conf.d/logstash.conf because I didn't know where to put the logstash configuration file.
When I run curl PRIVATE_IP_ADDRESS:9200, I get the following output
{
  "name" : "Gabriel Summers",
  "cluster_name" : "elasticsearch",
  "version" : {
    "number" : "2.1.1",
    "build_hash" : "40e2c53a6b6c2972b3d13846e450e66f4375bd71",
    "build_timestamp" : "2015-12-15T13:05:55Z",
    "build_snapshot" : false,
    "lucene_version" : "5.3.1"
  },
  "tagline" : "You Know, for Search"
}

How can I configure Logstash to output to the Elasticsearch at PRIVATE_IP_ADDRESS:9200 instead of localhost:92000?

A: I would double check that logstash is actually using that configuration file.

A: Just use follwing snippet to you conf file and it will work.
output {
  elasticsearch {
     hosts => "PRIVATE_IP_ADDRESS:9200"
  }
}

A: It turns out that when I was restarting logstash all of the processes weren't being terminated. My config files weren't the problem.
Here are the commands I ran to solve this:
ps -ef | grep logstash
sudo kill EACH_PID
sudo kill -9 PID_THAT_WASNT_KILLED_BEFORE
sudo /etc/init.d/logstash start

A: If you use the RPM installation then your configuration should be located under /etc/logstash/conf.d/.
So try to move the file you mentioned ( opt/logstash/conf.d/logstash.conf ) into the /etc/logstash/conf.d directory then restart your logstash service and check it out.


text:
Q: Cannot change hive.exec.max.dynamic.partitions in Spark I'm trying to insert some data in a table that will have 1500 dynamic partitions and I receive this error:
 Caused by: org.apache.hadoop.hive.ql.metadata.HiveException:
 Number of dynamic partitions created is 1500, which is more than 1000.
 To solve this try to set hive.exec.max.dynamic.partitions to at least 1500.

So, I try to: SET hive.exec.max.dynamic.partitions=2048 but I still get the same error.
How can I change this value from Spark?
Code:
this.spark.sql("SET hive.exec.dynamic.partition=true")
this.spark.sql("set hive.exec.dynamic.partition.mode=nonstrict")
this.spark.sql("SET hive.exec.max.dynamic.partitions=2048")
this.spark.sql(
    """
      |INSERT INTO processed_data
      |PARTITION(event, date)
      |SELECT c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,event,date FROM csv_data DISTRIBUTE BY event, date
    """.stripMargin
).show()

Using Spark 2.0.0 standalone mode.
Thank you!

A: From spark 2.x version, adding hive set properties in Spark CLI may not work. Please add your hive set properties in hive-site.xml of your both spark and hive conf directories.
adding below property in hive-site.xml file should resolve your issue.
<name>hive.exec.max.dynamic.partitions</name>
<value>2048</value>
<description></description>

Note: restart hiveserver2 and spark history server if it didn't work.


text:
Q: Is it true that the closed convex hull of a compact subset of the dual equipped with the w*-topology is compact? Let $X$ be a Banach space.  Consider the dual $X^*$ equipped with the weak*-topology.
Is it true that the closed convex hull of a compact subset $K$ of the dual $X^*$ is compact?
ps: I know that the closed convex hull of a compact subset of a Banach space is compact.


text:
Q: Wrap text in datagrid cell I have a datagrid include 10 columns,and the eighth column is the template
column created by asp label .Now I would like to display long text string and wrap the text in this template column .I used the property " itemstyle-wrap=true" in my page ,but
can not work .
so can any1 tell me how to get it ?


text:
Q: How do I fill the contents of a matrix using 9 other matrixes? I am creating a sudoku game
I have 9 3x3 matrixes and a large 9x9 matrix. The methods I tried didn't work so please help me:
void matrix_full_creation()
 {
    for(i=0;i<3;i++)
        {
            for(j=0;j<3;j++)
            {

                matrix_full[i][j]==matrix1[i][j];
                matrix_full[i][j+3]=matrix2[i][j];
                matrix_full[i][j+6]=matrix3[i][j];

                matrix_full[i+3][j]=matrix4[i][j];
                matrix_full[i+3][j+3]=matrix5[i][j];
                matrix_full[i+3][j+3]=matrix6[i][j];

                matrix_full[i+6][j]=matrix7[i][j];
                matrix_full[i+6][j+3]=matrix8[i][j];
                matrix_full[i+6][j+6]=matrix9[i][j];
            }
        }
}

A: *

*Given a submatrix index n, and a pair of indexes within that submatrix, i.e. row index i and column index j, and

*considering you want to place each submatrix at positions (0,0), (0,1)..., (3,3) of the full matrix,

*you can walk each cell of each submatrix, and

*use the following formula to calculate the destination cell in the full matrix:

matrix_full[3*(n / 3) + i][3*(n % 3) + j] = submatrix[i][j];

[Demo]

A: I have corrected your code. Try this:
for(i=0;i<3;i++)
    {
        for(j=0;j<3;j++)
        {

            matrix_full[i][j]=matrix1[i][j];
            matrix_full[i][j+3]=matrix2[i][j];
            matrix_full[i][j+6]=matrix3[i][j];

            matrix_full[i+3][j]=matrix4[i][j];
            matrix_full[i+3][j+3]=matrix5[i][j];
            matrix_full[i+3][j+6]=matrix6[i][j];

            matrix_full[i+6][j]=matrix7[i][j];
            matrix_full[i+6][j+3]=matrix8[i][j];
            matrix_full[i+6][j+6]=matrix9[i][j];
        }
    }

Hope this helps! :D

A: Let's break your task into smaller pieces.
First, write a function that copies your small matrix into specific position
void Copy(int** small, int i, int j);

So if you pass 0, 0 for i, j... It should copy contents of small into top left 3x3 submatrix of the big 9x9 matrix.
When you complete this task, just run a for loop (similar to the one you already did)
int** bigMatrix; // assume we have it here

void Copy(int** small, int i, int j) {
    for(int ii = 0; ii < 3; ++ii) {
        for(int jj = 0; jj < 3; ++jj) {
            bigMatrix[i + ii][j + jj] = small[ii][jj];
        }
    }
}

int main() {
    int smalls[3][3][3] = {...}; // assume we have 3x3 init here

    for(int i = 0; i < 9; i += 3) {
        for(int j = 0; j < 9; j += 3) {
            Copy(smalls[0], i, j];
        }
    }
    return 0;
}

Good tip: divide and conquer!


text:
Q: catching a broken socket in python I'm having problems detecting a broken socket when a broken pipe exception occurs.  See the below code for an example:
The Server:
import errno, select, socket, time, SocketServer

class MetaServer(object):
    def __init__(self):
        self.server = Server(None, Handler, bind_and_activate=False)
    def run(self, sock, addr):
        rfile = sock.makefile('rb', 1)
        self.server.process_request(sock, addr)
        while 1:
            r, _, _ = select.select([rfile], [], [], 1.0)
            if r:
                print 'Got %s' % rfile.readline()
            else:
                print 'nothing to read'

class Server(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    allow_reuse_address = True
    daemon_threads = True

class Handler(SocketServer.StreamRequestHandler):
    def handle(self):
        print 'connected!'
        try:
            while 1:
                self.wfile.write('testing...')
                time.sleep(1)
        except socket.error as e:
            if e.errno == errno.EPIPE:
                print 'Broken pipe!'
        self.finish()
        self.request.close()

if __name__ == '__main__':
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(('127.0.0.1', 8081))
    s.listen(5)
    ms = MetaServer()
    while 1:
        client, address = s.accept()
        ms.run(client, address)

The Client:
import select, socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 8081))
while 1:
    r, _, _ = select.select([s], [], [], 1.0)
    if not r:
        continue
    msg = s.recv(1024)
    print 'Got %s' % (msg,)

Now, if I run the server and client, all is well, and I get a "nothing is read" message every second.  As soon as I CTRL-C out of the client, the server goes crazy and starts to "read" from what should be a busted socket, dumping a lot of "Got " messages.
Is there some way to detect this broken socket in the MetaServer.run() function to avoid the above said behavior?

A: Yes, that's something which is not really in the documentation but old Un*x behavior: You need to abort when you get an empty string.


text:
Q: Creating a context menu on drag complete in WPF I am working on a node-graph-view similar to Maya's HyperGraph in which I can connect Nodes with drag and drop. Because the target-node can have several Inputs, I want to create a temporary ContextMenu to select the input as suggesting in the following mock-up:
http://www.pixtur.org/images/uploaded/0000/0696/large.jpg
I tried for quite a time to trigger the creation or opening of a context-menu. It looks like the Win32 TrackPopupMenu does roughly, what I'm looking for. Is there an WPF / C# equivalent?
Thanks
pixtur

A: I would suggest another solution:
In this example a button will raise a context menu with one entry ("Copy") on right click. If the "Copy" context menu item is clicked, a console output is generated.
[..]
var button = new Button();
button.Content = "SomeButtonName";
button.MouseUp += HandleMouseUp;
[..]

private void HandleMouseUp(object sender, MouseButtonEventArgs e)
{
    var senderUIControl = sender as Control;

    var contextMenu = new ContextMenu();

    var item = new MenuItem();
    item.Header = "Copy";
    item.Click += (o, a) => {
        Console.WriteLine("Copy item clicked");
    };
    contextMenu.Items.Add(item);

    senderUIControl.ContextMenu = contextMenu;
}

A: I use the following code to attach a contextmenu to a listview gricolumn header:
<ListView ... MouseUp="ListView_MouseUp">

In the codebehind i set the ContextMenu property of the list on the mouse up event, in order to show the context menu:
    private void ListView_MouseUp(object sender, MouseButtonEventArgs e)
    {
        DependencyObject depObj = e.OriginalSource as DependencyObject;

        while (depObj != null && (!(depObj is GridViewColumnHeader)))
        {
            depObj = VisualTreeHelper.GetParent(depObj);
        }

        if (depObj is GridViewColumnHeader && e.ChangedButton == MouseButton.Left)
        {
            ((GridViewColumnHeader)depObj).ContextMenu = ContextMenu;
        }
    }

The variable ContextMenu refers to a contextmenu instance that i created bfeorehand, you could also create the ContextMenu in the Mouse event handler.
I'm not sure if this helps as I dont know how you do the drag/drop, but it is worth a try


text:
Q: I want to prove $f$ in continuous on $[a,b]$ implies $F(x)=\sup f([a,x])$ is continuous on $[a,b]$? Goal: I want to prove $f$ in continuous on $[a,b]$ implies $F(x)=\sup f([a,x])$ is continuous on $[a,b]$.
Proof:
Suppose $f$ in continuous on $[a,b]$.
Let $c \in (a,b)$. Let $\epsilon>0$.
By the continuity of $f$ at $c$, there exists $\delta>0$,
such that
$-\epsilon/2 +f(c)<f(x)<\epsilon/2 +f(c)$
for all $x \in (c-\delta, c+\delta)$
so  $f(x)<\epsilon/2 +f(c)$
for all $x \in [c , c+ \frac{\delta}{2}]$
hence, $\sup f([c , c+ \frac{\delta}{2}]) \le\epsilon/2+f(c) \le \epsilon/2 +\sup f([a,c])$.
so if $y \in f([c , c+ \frac{\delta}{2}]) \cup f([a,c])$, then $y \le \epsilon/2 +\sup f([a,c])$
hence, $\sup f([a ,c+ \frac{\delta}{2}]) \le \epsilon/2 +\sup f([a,c])< \epsilon +\sup f([a,c])$.
by the monotone property of suprema we have $\sup f([a ,x])< \epsilon +\sup f([a,c])$ for all $x \in (c- \frac{\delta}{2},c+ \frac{\delta}{2})$
moreover,
suppose $\sup f([a,c])-\sup f([a,c-\frac{\delta}{2}])\ge \epsilon$
in this case we must have: $\sup f([c-\frac{\delta}{2},c])-\sup f([a,c-\frac{\delta}{2}])\ge \epsilon$ because otherwise $0 \ge \epsilon >0$
then, $\sup f([c-\frac{\delta}{2},c])\ge \epsilon +\sup f([a,c-\frac{\delta}{2}]) \ge \epsilon + f(c-\frac{\delta}{2})$
by the extreme value theorem, there exists $t \in [c-\frac{\delta}{2},c]$ s.t.
$|f(t)-f(c-\frac{\delta}{2})| \ge \epsilon$
but $|f(t)-f(c)|<\epsilon/2$ and $|f(c-\frac{\delta}{2})-f(c)|<\epsilon/2$
so, $|f(t)-f(c-\frac{\delta}{2})|\le|f(t)-f(c)|+|f(c-\frac{\delta}{2})-f(c)|<\epsilon/2+\epsilon/2=\epsilon$, which is a contradiction.
so we must have $\sup f([a,c])-\sup f([a,c-\frac{\delta}{2}])< \epsilon$.
by the monotone property of suprema $\sup f([a,c])-\epsilon< \sup f([a,c-\frac{\delta}{2}])\le \sup f([a,x])$ for all $x \in (c- \frac{\delta}{2},c+ \frac{\delta}{2})$
in conclusion, $|x-c|<\delta/2 \implies \sup f([a,c])-\epsilon< \sup f([a,x])< +\sup f([a,c])+\epsilon \implies |\sup f([a,x])-\sup f([a,c])|<\epsilon$
$$$$
I would really appreciate it if community members could check the details of my proof. Are there any mistakes? Is there anything weird about it? What are your general thoughts? I have tried to include as much justification as I thought reasonable, but is there anything you find lacking? Note that I have only attempted to prove continuity on $(a,b)$ and will update to deal with the endpoints later.

A: Your proof is correct, but somewhat laborious. Here is my suggestion.
We have to show that for each $c \in [a,b]$ and each $\epsilon > 0$ there exists $\delta > 0$ such that $\lvert x - c \rvert < \delta$ implies $\lvert F(x) - F(c) \rvert < \epsilon$, i.e. $F(c) - \epsilon < F(x) <  F(c) + \epsilon$. Since $F$ is monotonically increasing, this is equivalent to the existence of $\delta > 0$ such that

*

*For $x$ such that $c \le x < c + \delta$ we have $F(x) < F(c) + \epsilon$.

*For $x$ such that $c - \delta < x \le c$ we have $F(c) < F(x) + \epsilon$.

Since $f$ is continuous, there exists $\delta > 0$ such that $\lvert  \xi - c \rvert < \delta$ implies $\lvert f(\xi) - f(c) \rvert < \epsilon/3$. This $\delta$ will do for 1. and 2.
1.:
For $c \le x < c + \delta$ we have
$$F(x) = \sup f([a,x]) = \max(\sup f([a,c]), \sup f([c,x]) = \max(F(c),\sup f([c,x]).$$
If $\xi \in [c,x]$ we have $\lvert  \xi - c \rvert < \delta$, thus $f(\xi) < f(c) + \epsilon/3$ which implies $\sup f([c,x]) \le f(c) + \epsilon/3 < f(c) + \epsilon \le F(c) + \epsilon$. Therefore $\max(F(c),\sup f([c,x]) < F(c) + \epsilon$.
2.:
For $c - \delta < x \le c$ we have
$$F(c) = \sup f([a,c]) = \max(\sup f([a,x]), \sup f([x,c]) = \max(F(x),\sup f([x,c]).$$
If $\xi \in [x,c]$ we have $\lvert  \xi - c \rvert \le \lvert  x- c \rvert < \delta$, thus
$$f(\xi)  = f(x) + f(\xi) - f(x) \le  f(x) + \lvert f(\xi) - f(x)  \rvert \le f(x) + \lvert f(\xi) - f(c)  \rvert + \lvert f(c) - f(x)  \rvert \\ < f(x) + \epsilon/3 + \epsilon/3$$
which implies $\sup f([x,c]) \le f(x) + 2\epsilon/3 < f(x) + \epsilon \le F(x) + \epsilon$, hence $\max(F(x),\sup f([x,c]) < F(x) + \epsilon$.
Note that these arguments also cover the cases $c = a$ and $c = b$.


text:
Q: How to display divs in a different order depending on screen size in Bootstrap 3? I have a Bootstrap two column layout which collapses to one on narrow screens.
Bad ASCII art:
+-------------------+-------------------+
|  Div A            |  Div B1           |
|                   +-------------------+
|                   |  Div B2           |
|                   +-------------------+
|                   |  Div B3           |
+-------------------+-------------------+

collapsing to
+-------------------|
|  Div B1           |
+-------------------+
|  Div B2           |
+-------------------+
|  Div B3           |
+-------------------+
|  Div A            |
|                   |
|                   |
|                   |
|                   |
+-------------------+

A has class col-md-6, B1-B3 are contained in a div B with class col-md-6 col-md-push-6. This works just fine, but the layout would be even nicer as
+-------------------|
|  Div B1           |
+-------------------+
|  Div A            |
|                   |
|                   |
|                   |
|                   |
+-------------------+
|  Div B2           |
+-------------------+
|  Div B3           |
+-------------------+

Is that achievable with reasonable amounts of code?

A: It makes more sense when you design it thinking about what is going to look like on mobile first. A simple pull-right and pull-left and the right classes and architecture and you have no media hacks to use at all.
Disclaimer: Be careful, as the only downside to this is losing the tab sequence A1- B1- B2- B3 ;)
See the code

B1

A1

B2

B3

CSS (this is only for demo beautification and distinction of boxes. You wont need this except the no-padding reset)
.container div{
    padding:0;
}
.box{
    background:red;
    height:40px;
    color:#fff;
    padding:10px;
    text-align:center;
    border:1px solid #111;
}
.box.a1{
    background:blue;
    height:120px;
}

See the demo

A: Use a media query to specify the new layout when it collapses. You can find all the information you need on media queries here: https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries
Barebones example:
@media (max-width: 700px) {
    collapsed layout here
}


text:
Q: GoogleApiClient parameter is required (Getting current location inside asynctask) I have a method with an asynctask inside.
 public void getNearest(){
    new AsyncTask() {
        @Override
        protected void onPreExecute(){
            super.onPreExecute();
        }

        @Override
        protected Object doInBackground(Object[] objects){
            buildGoogleApiClient();
            if (ContextCompat.checkSelfPermission(MapsActivity.this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                        mGoogleApiClient);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            Collections.sort(marker, new Comparator<Location>() {
                @Override
                public int compare(Location a, Location b) {
                    Location locationA = new Location("point A");
                    Location locationB = new Location("point B");
                    float distanceOne = mLastLocation.distanceTo(locationA);
                    float distanceTwo = mLastLocation.distanceTo(locationB);
                    return Float.compare(distanceOne, distanceTwo);
                }
            });
        }
    }.execute();
}

I want the doInBackground method to get the current location. This whole method is to be called in the onCreate method so I can have a variable for the current location. However, the app crashes and says that GoogleApiClient should be a parameter. It points to the doInBackground method. I am new to coding with the google maps api so I'm really having a hard time. Any help will be appreciated thank you very much!
buildGoogleApiClient():
protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
}


text:
Q: python-mysql-connector throws error while executing command I'm rewriting my codebase and converting all f-strings to C-like string formatting (%s), but this error is there every time:
>>> import mysql.connector as mc
>>> conn = mc.connect(username = "root", password = "root")
>>> cursor = conn.cursor()
>>> cursor.execute("use %s", ("test",))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\whode\AppData\Local\Programs\Python\Python39\lib\site-packages\mysql\connector\cursor.py", line 569, in execute
    self._handle_result(self._connection.cmd_query(stmt))
  File "C:\Users\whode\AppData\Local\Programs\Python\Python39\lib\site-packages\mysql\connector\connection.py", line 599, in cmd_query
    result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
  File "C:\Users\whode\AppData\Local\Programs\Python\Python39\lib\site-packages\mysql\connector\connection.py", line 487, in _handle_result
    raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''test'' at line 1

A: Database names should not be quoted.  Just do
cursor.execute( "use test;" )

Alternatively, specify the database name in the connect call.


text:
Q: Enums, DataContracts and WCF question I am new to WCF and have a simple question...
My DataContract class returns an Enum type to the consumer from one of it's exposed methods.
The consumer is able to see the enum type, and instantiate variables of that typel.
However, I have not provided a [DataContract] nor [EnumMember]s for the enum in the service.
My question is, why is the client still able to see it??
I thought that I would have had to make it a [DataContract] for it to be serialized along with the business object, no?

A: Yes - you had to - up to .NET 3.5 SP1.
Microsoft "loosened" the rules and now the DataContractSerializer will behave like the XmlSerializer, if you don't put any [DataContract] and [DataMember] attributes on anything: it will just simply serialize all public properties and necessary types.
While this might be a "simpler" approach for the simple scenario, you also loose lots of control over namespace, ordering etc. - so I prefer to still apply those attributes explicitly, just to clearly express (and document!) my intent. But with .NET 3.5 SP1, it's no longer required and enforced by the DataContractSerializer.

A: if we don't put any [DataContract] and [DataMember] attributes on anything it will automatically serialize all public properties and necessary types.This feature is supported from higher version of .NET3.5 SP1.


text:
Q: Material Design, AppCompat, and Backwards Compatibility I'm trying to understand the principles of using Material Design a bit better (I'm new to this area and have been reading documentations and tutorials, but the subject is still a bit vague to me), and I'll be glad for some help. What I've tried so far is having 2 folders (values and values-21) with a styles.xml file per each of them -
values/styles.xml:
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"></style>

values-v21/styles.xml:
<style name="AppTheme" parent="android:Theme.Material.NoActionBar"></style>

The problem begins where I try to use activities that inherit from AppCompatActivity (To my understanding, that's what I need to do in order to support backwards compatibility on devices before Lollipop for things such as Material Design? Am I correct? More info here would be great). If I do that, the app won't run on devices that  have API 21 or above, since "AppTheme" has to inherit from AppCompat.
What I can do to solve that, is to create a base theme that inherits from AppCompat , and then make the style in both files to inherit from that base theme... But then I'm not inheriting from Material anymore.... which brings me to the question(s) -
Is Material Design just a given theme? And if so, how do I solve my problem? And what does using AppCompatActivity exactly accomplish here? Or is Material Design essentially just a set of rules and principles I'm supposed to follow? And if so, why do we need Theme.Material.* at all? I'll be glad for any extra info anyone can give me on the subject.
Thanks!

A: The whole point of AppCompat is that you only need one theme (you don't need a separate one in values-v21) and it will be the same experience on all devices.
Theme.AppCompat already extends android:Theme.Material on API 21+ - it is just handling all of the version checking for you.


text:
Q: Chern Classes of a Trivial Bundle Could someone explain to me why the chern classes of a trivial bundle are zero?
(I'm studying it from Bott & Tu book) To be more specific I can't understand why, given the vector bundle $E$ on $M$, it must be $C_1(S^*_E)^n=0$. $S^∗_E$ is the dual of the tautological subbundle of the pullback of $E$ on $P(E)$.

A: At least rationally you can also see this easily since any trivial bundle admits a flat connection. But then by Chern Weil theory you see that any chern class has to be zero, since it can be computed in terms of the curvature which is $0$ in our case.

A: This is a trivial consequence of the naturality (or functoriality) of the Chern classes, which should be clear no matter which definition of the Chern classes you are using.
Fix a space $X$.  Let $P$ be a one-point space, and let $E \rightarrow P$ be the trivial $n$-dimensional complex vector bundle.  There is a unique map $f : X \rightarrow P$, and it is easy to see that the trivial $n$-dimensional complex vector bundle over $X$ is exactly the pullback $f^{\ast}(E) \rightarrow X$.  All the Chern classes of $E \rightarrow P$ have to be trivial since the cohomology groups of $P$ are trivial.  Thus by the naturality of Chern classes we have
$$c_i(f^{\ast}(E)) = f^{\ast}(c_i(E)) = 0.$$

A: I assume you're looking for a non-technical answer, one that will somehow tell you the intuative reason for why the Chern classes of a trivial bundle are zero without going into serious calculations. I can't promise you this will be that answer, but we'll damn well do our best. For the record, what I'll say makes sense in the algebraic and analytic categories. I think it does as well in the smooth one, but I wouldn't bet my life on it.
For the setup, I'll take my manifold $X$ to be compact and smooth, and I'll take a smooth vector bundle $E \to X$ over it. Now, what are the Chern classes of the bundle $E$ really?
Suppose we have a section $\sigma$ of the bundle $E$ and suppose also that the section $\sigma$ is not the zero section, but that it still has some zeros. Then we can consider the subvariety $(\sigma)_0$ of points of $X$ where the section $\sigma$ is zero. This subvariety defines a cohomology class on $X$; it's easiest to define it by duality, that is by simply integrating differential forms that represent different classes over the subvariety $(\sigma)_0$.
This cohomology class is the first Chern class of the vector bundle $E$. Thus the first Chern class measures, in some sense, how "often" a general section of $E$ is zero.
To get a feel for the second Chern class, take two sections $\sigma_1$ and $\sigma_2$ of $E$. Locally these are just vectors in a vector space, so they can be colinear or not. Let $(\sigma_{12})$ be the subvariety of $X$ which consists of the points where the sections $\sigma_1$ and $\sigma_2$ are colinear. This subvariety again defines a cohomology class, which is exactly the second Chern class of $E$.
The same happens for the higher Chern classes. Intuitively, the $k^{th}$ Chern class of a vector bundle measures, in some sense, how "likely" it is that $k$ generic sections of the bundle are linearly dependent.
I'm told this is more or less the original historical definition of Chern classes. This point of view is exposed in great detail in a forthcoming book of Harris and Morrison called "Intersection theory". Until that book comes out, Harris talks about this a great deal in his lectures available here: http://mate.dm.uba.ar/~visita16/ELGA-2011/version/v1/images-en.shtml
Now, this is relevant to our interests. Indeed, suppose the vector bundle $E$ is trivial, or $E = \mathbb R^r$. Then it is somehow clear that we have an incredible amount of room in which to fit our sections, as there are no global obstructions coming from the structure of the bundle itself. In vague but suggestive terms, we can take a global frame, or basis, of our vector bundle. If we need to find $k$ linearly independent sections of the bundle, we just take the $k$ first vectors of that basis. These are linearly independent everywhere, thus the subvariety which defines the $k^{th}$ Chern class is empty, so the $k^{th}$ Chern class of the bundle is zero.
This was all incredibly imprecise. I do suggest you look at Harris' lectures to get a better idea of what is going on.

A: This is a late answer to the question. I just wanted to explain how Bott & Tu deduced it in the book. In the chapter they computed the cohomology of $P(V)$ and showed that $H^*(P(V))=\frac{\mathbb{R[x]}}{(x^n)}$.
They write:

If $E$ is the trivial bundle $M \times V$ over $M$ then $P(E)=M \times P(V)$ so $x^n=0$.

In there construction of the chern class they are using the Leray–Hirsch theorem to represent $H^*(P(E))$ as a free module over $H^*(M)$ with basis $\{1, \dots, x^{n-1}\}$. But in this case we can use Kunneth formula for cohomology to deduce:
$$H^n(P(E)) \cong \left(\sum_{i + j = n} H^i(M) \otimes H^j(P(V))\right)$$
From this and the knowledge of the cohomology ring of $P(V)$ we deduce that $x^n=0$.
Edit: The answers to the question in the comment gos as follows.
At page 270 in there book the construct the following exact sequence
$$0 \to S \to \pi^{-1}E \to Q \to 0$$
Where $\pi^{-1}E $ is the pullback bundle over $P(E)$. If $E$ was the trivial bundle over $M$ then $\pi^{-1}E $ will be the trivial bundle over $P(E)$. Now we ask what will be $c_1(S^*) \in H^2(P(E))$?
If $\rho_2$ is the projection $M \times P(V)\to P(V)$. Then we can show that $\rho_2^{-1}\tilde{S} \cong S$, where $\tilde{S}$ is the universal sub-bundle of $P(V)$. Thus we have $c_1(S^*)=-\rho_2^*(c_1(\tilde{S}))$. Thus
we now have
$$x^n = \left(c_1(S^*)\right)^n=-\rho_2^*(c_1(\tilde{S})^n)=-\rho_2^*(0)=0.$$


text:
Q: Binary search algo for leetcode heater question I was trying following leetcode heater problem (easy difficulty).
I wrote an algorithm which didn't work (I realised what I did wrong) so I went to see solution in discussion.
There I stumbled upon people using binary search but  wasn't able to comprehend their logic. Can someone please explain me (algo) on how we can solve this using binary search (google search wasn't any help)
This was my non binary search algo which didn't work
/**
 * @param {number[]} houses
 * @param {number[]} heaters
 * @return {number}
 */
var findRadius = function(houses, heaters) {
    let maximumDist = 1
  let currentDist = i = cHeaterIndex = 0
  while (i<houses.length){
    const cHeaterPosition = heaters[cHeaterIndex]
    if (houses[i] === cHeaterPosition || i === houses.length-1) {
      if (houses[i] === cHeaterPosition) {
        if (maximumDist < currentDist) {
          maximumDist = parseInt((currentDist - 1)/2)
        }
      } else {
        maximumDist = currentDist - 1
      }
        currentDist = 1
        cHeaterIndex++
    }
    i++
    currentDist++
   }
   return maximumDist
};

A: Logic behind binary search is :
Find the left and right position of heater which best suits a particular house.
Now, consider that if we are given sorted numbers and you have to find a value in that you will use binary search.
Same goes over here, you are given sorted numbers in terms of heater positions and search value is particular house position . Now, you have to find an index of heater position value which is nearest to this house position.
Example :
heaters[] = {1,2,3,8} house_position = 5.
So, closest value of heater from left is 3 (index = 2) which we can find by binary search . Now, this is left position of heater which can heat this house. Right positioned heater can also heat the house which is at next index(index=3) whose value is 8. So, this particular house can be heated by both heaters at position 3 and 8. Out of this we will find best heater position which has minimum distance from the house (since that will have minimum radius). In this case it is heater at position 3(index=2), whose distance from house is 2.
This is the logic of binary search for this question.
Here is the working example of the same (JAVA code).
 /**
 * @param {number[]} houses
 * @param {number[]} heaters
 * @return {number}
 */
var findRadius = function(houses, heaters) {
    var totalhouses = houses.length, totalheaters = heaters.length, index=0, currindex=0, max = 0, currmin;
    heaters.sort((a, b) => a - b);
    while(index< totalhouses) {
        currindex = search(heaters, houses[index], 10);
        if(currindex==-1) {  //if left positioned heater is not present
            currmin = heaters[0] - houses[index];
        } else {
            if(currindex+1 < totalheaters) {
                currmin = Math.min(heaters[currindex+1] - houses[index], houses[index] - heaters[currindex]);
            } else {   //if right positioned heater is not present
                currmin = houses[index] - heaters[currindex];
            }
        }
        max = Math.max(max, currmin);
        index++;
    }
    return max;
};

var search = function(heaters, value) {  //binary search to find best possible left positioned heater for the house
    var start=0,end = heaters.length-1, mid=0;
    while(start<=end) {
        mid = Math.floor((start + end) / 2);
        if(heaters[mid] == value){
            return mid;
        } else if(heaters[mid] > value) {
            end = mid-1;
        } else {
            start = mid+1;
        }
    }
    return end;
}


text:
Q: Is it safe to call TimeZone.setDefault in @Before method in JUnit? Here is comment about setting default timezone for test code in @Before method of JUnit test. But TimeZone.setDefault is static method. Can it affect other test which are run after test with @Before and TimeZone.setDefault completes successful?

A: There are many things to check here, it depends on how do you run the tests.
The following factors may come into considerations:

*

*Since you've tagged "maven" in a question: Maven's surefire/failsafe plugins responsible for running the tests can run multiple tests simultaneously in 1 or many JVMs, it all depends on their configurations.
So tests may start failing sporadically during the build even if they pass locally.

*@Before and @After are called before and after each test in the test case respectively. @After is called even if the test fails. So probably memorizing the default timezone and setting it back after the test should be ok, but not "re-setting" the state in an "@After" block may lead to incorrect definitions in subsequent tests.
The better approach IMHO is using java.time.Clock abstraction. See this question for examples
Another possible option is refactoring a code to use some "factory" for providing current date / time. Then in Unit Test you could instantiate this factory and "inject" it as a dependency into the code-under-test. A kind of hand-crafted Clock

A: It will effect the other tests (as you assumed), as it won't be reset after running a single test.
Either reset it to "normal" by an @After method, or maybe change the code to take/inject the timestamp for "now" and make the code do it's calculation from there. From my experience this will give you alot more flexibility.


text:
Q: Can't compare specific positions in a list I was working on making a wordle bot to challenge my ability to program, but I am at a standstill.
List<string> wordsA = new List<string>();
List<string> letters = new List<string>();
letters.Add("");
wordsA.Add("");
if (letters[8] == "1")
{
   for (int i = 0; i < words.Length; i++)
   {
       wordsA.Add(words[i]);
       if (letters[7] == wordsA[4])
       {
          possiblewords1.Add(words[i]);
          wordsA.Remove(words[i]);
       }

   }
}

Every guess, it breaks up the guess into 10 parts. For example, ERASE would  turn into E2R1A3S2E1, with the numbers representing if the letter was correct. And I was trying to compare "wordsA" to "letters". These are both lists. Almost every time it tries to check, I get the error

Unhandled exception. System.ArgumentOutOfRangeException: Index was out
of range. Must be non-negative and less than the size of the
collection. (Parameter 'index')    at
System.Collections.Generic.List`1.get_Item(Int32 index)

This only occurs at the lines where it's comparing "wordsA" to "letters"

A: I have no idea about wordle, but the error is quite obvious... your letters list has one element - empty string. So, when you write if (letters[8] == "1") - your index is out of bounds


text:
Q: The reference component could not be found - yellow triangle (visual studio 2017) There are two projects in my solution. The references in the first one are detected, while the same references in the second one are not detected. Yellow triangles indicates that those references are not found.

Red is my second project, and blue is the reference to the first project.
Both projects are using same target framework 4.6 (checked in the properties)
The first project is compiled successfully.

A: Answering to my own question. Be aware that it is not probably the issue from path of the references. There should be some other problems, which in my case was the missing Nuget library in the package directory that is referenced in package.config file.
You could restore Nuget Package or simply uninstall and reinstall another version of the Nuget library.


text:
Q: COUNTING IN VBA I have a number of clients in an excel spreadsheet (by client name), each associated with a particular item. For example
12345     1
12345     2
12345     2
23451     1
23451     3
55667     1
55667     2
89001     3
99999     1
99999     2
I need to count the number of distinctly different items for each client - in the above example, client 12345 has bought 3 items (output is 3); client 23451 has bought 2 items (output 2); client 89001 has bought one item (output 1). I'm sure it's a COUNT feature which looks to the previous column A and breaks/restarts the count if the client number changes, but I'm having a devil of a time doing it. Any help would be deeply appreciated.

A: Have you considered the SUM function instead? The COUNT function counts the amount of cells that are being used, the SUM adds up the integers within the cells.
Check out this link -> Here
Yes, or a better suggestion from David in the comments, the SumIf function.
Thanks David!


text:
Q: Symbolic computation of a region boundary Consider the three disk regions plotted here, where of course I had to set a single radius (scale) to make an actual plot:

But in my actual problem, the scale is not set.  For instance, we can set the radius of the large green disk to be $x>0$, and without loss of generality place its center at the origin.
I'm interested in the area of the dark orange wedge, as well as the length of its perimeter.
Thus I define the regions symbolically as follows:
\[ScriptCapitalR]left = Disk[{0, x/2}, x/2];
\[ScriptCapitalR]top = Disk[{x/2, x}, x/2];
\[ScriptCapitalR]big = Disk[{0, 0}, x];
\[ScriptCapitalR]goal =
  RegionDifference[
   RegionIntersection[\[ScriptCapitalR]top, \[ScriptCapitalR]big], \
\[ScriptCapitalR]left];
Assuming[x > 0, RegionMeasure[\[ScriptCapitalR]goal]]

I get the RegionMeasure (i.e., area) just as I seek... in terms of $x$:
$$\frac{1}{8} x^2 \left(-2+\pi -\tan ^{-1}\left(\frac{44}{117}\right)\right)$$
Fine.
Now I try to find its perimeter.  First I define its boundary:
\[ScriptCapitalR]goalBoundary =
  Assuming[x > 0, RegionBoundary[\[ScriptCapitalR]goal]];

Now, I try to find the length of its perimeter:
ArcLength[\[ScriptCapitalR]goalBoundary]

or
RegionMeasure[\[ScriptCapitalR]goalBoundary]

and I get no answer.
However, if I set a particular value for $x$, I get the perimeter fine:
ArcLength[\[ScriptCapitalR]goalBoundary] /. x -> 1

$$\frac{1}{4} \left(\pi +2 \sin ^{-1}\left(\frac{3}{5}\right)+4 \sin
   ^{-1}\left(\frac{4}{5}\right)\right)$$
(Of course I can plot and visualize the boundary only if I set a value for $x$, as in:  RegionPlot[\[ScriptCapitalR]goalBoundary /. x -> 1].  Again, fine.)
How do I compute the perimeter symbolically for arbitrary $x>0$?
Of course I could solve for $x \to 1$ and then exploit my knowledge that the perimeter scales as $x$, but I'm looking for a more general solution (applicable to other problems) that relies on symbolic computation, not my "human understanding" of dimensional scaling.

A: For this particular example expressing the region as ImplicitRegion returns an arclength.
One such way to find defining implicit conditions for a region is through RegionMember. Unfortunately it does not know the conditions for the boundary of our region:
RegionMember[\[ScriptCapitalR]goalBoundary, {a, b}] // Head

(* RegionMember *)

However there's a trick to find the implicit boundary of a semialgebraic region. Find the implicit representation of the region itself and then find its boundary through CylindricalDecomposition.
Rcond = RegionMember[\[ScriptCapitalR]goal, {a, b}];

Rbdcond = CylindricalDecomposition[Rcond, {x, b, a}, "Boundary"];

Rimplicit = ImplicitRegion[Rbdcond, {a, b}];

And the arclength, which comes back after some time on my machine:
Assuming[x > 0, ArcLength[Rimplicit]] // AbsoluteTiming

{17.7282, x ArcTan[4/3] + x ArcTan[2]}

A: We want to calculate the arc length of the path along A-B-C-A.  There are two paths from C to A.  Both paths have the some length, so we choose the one along the top circle.  We first calculate the length of the chord from A to B.  The chord length is used calculate the arc length from A to B along the big circle and the arc length from B to A along the top circle.  The left disk is not used in this solution.

The easy way to get the coordinates of B is to reflect A across the line from the center of the big circle to the center of the top circle.  The formulas for the arc length and included angle are from here.  $\theta_1$ is the central angle of the top circle subtended by the chord $A B$.    $\theta_2$ is the central angle of the big circle subtended by the chord $A B$.

Here is the calculation:
cTop = {x/2, x};
v1 = Simplify[Normalize[cTop], x > 0] ;
v2 = RotationTransform[π/2][v1] ;
ptA = {0, x} ;
ptB = ReflectionMatrix[v2].ptA;
chord = Simplify[Norm[ptB - ptA], x > 0];
θ1 = 2 ArcSin[chord/(x)];
s1 = x θ1/2;
θ2 = 2 ArcSin[chord/2/x];
s2 = x θ2;
perimeter = s1 + s2
perimeter /. x -> 1.0

The resulting arc length is $$x \sin
   ^{-1}\left(\frac{2}{\sqrt{5}}\right)+2 x \sin
   ^{-1}\left(\frac{1}{\sqrt{5}}\right)$$
Code for the graphics follows
With[{x = 1}, Graphics[{{Opacity[.1], Blue, Disk[{0, x/2}, x/2],
    Orange, Disk[{x/2, x}, x/2], Green, Disk[{0, 0}, x]},
   {Red, Text["A", {0, x}],
    Text["B", {4 x/5, 3 x/5}],
    Text["C", {x/2, x/2}]}},
  PlotRange -> {{0, 1}, {0, 3/2}}, Axes -> True,
  ImageSize -> Small, Frame -> True]
 ]

disks = {Opacity[.2], Green, Disk[{0, x/2}, x/2],
   Disk[{x/2, x}, x/2], Disk[{0, 0}, x]};
lines = {Black, Line[{{0, 0}, {x/2, x}}], Dashed,
   Line[{{0, x}, {2 x, 0}}]};
points = {PointSize[.015], Red, Point[ptA], Magenta, Point[ptB]};
vectors = {Red, Arrow[{{0, 0}, v1/2}], Blue, Arrow[{{0, 0}, v2/2}]};

Graphics[{disks, lines, vectors, points} /. x -> 1,
 PlotRange -> {{-1, 2}, {0, 3/2}}, Axes -> True,
 GridLines -> {Range[-1, 2, .5], Range[0, 1.4, .2]},
 ImageSize -> Medium, Frame -> True]


text:
Q: what is the behavior of (.)+ in a regex? We just found a bug in some code where the programmer had used the equivalent of (.)+ when they should have used (.+). An easy enough fix, but we're unable to explain the behavior of (.)+. Can anyone explain why this matches "e", the last letter, and not "b", the first letter after the "a" in the regex? How would you explicate (.)+?
my $s = 'abcde';

if ($s =~ m{ a (.)+  }x ){
    print "s '$s' matched '$1'\n";
}else{
    print "total match fail\n";
}

__END__
output:
s 'abcde' matched 'e'

A: There's a huge difference between (.)+ and (.+) but only in terms of what is captured, not what is matched.
(.)+ looks for one or more instances of a single character and captures the last of these.
(.+) looks for one or more single characters and captures all of them at once.


text:
Q: is there a way to block access to Settings on an iPhone? A family member (... with little fingers...) keeps accessing my phone (which is fine by me), but she also changes the Settings, plays with the Fingerprints and that causes a shockwave effect to all my logins to other apps.
Is there a way to block the access to Settings with a separate Passcode or otherwise? Maybe move it to a protected folder, if there is such thing?


text:
Q: Understanding a lambda construct that contains dot followed by brackets This is the function declaration for rememberCoilPainter:
@Composable
fun rememberCoilPainter(
    request: Any?,
    imageLoader: ImageLoader = CoilPainterDefaults.defaultImageLoader(),
    shouldRefetchOnSizeChange: ShouldRefetchOnSizeChange = ShouldRefetchOnSizeChange { _, _ -> false },
    requestBuilder: (ImageRequest.Builder.(size: IntSize) -> ImageRequest.Builder)? = null,
    fadeIn: Boolean = false,
    fadeInDurationMs: Int = LoadPainterDefaults.FadeInTransitionDuration,
    @DrawableRes previewPlaceholder: Int = 0,
): LoadPainter<Any> {

}

The line of code I am having difficulty understanding is:
requestBuilder: (ImageRequest.Builder.(size: IntSize) -> ImageRequest.Builder)? = null
A dot appears after Builder followed by (size: IntSize)
This is the first time I've seen this construct in Kotlin and am not sure how to interpret it. This is a lambda. Normally the dot after an object refers to a sub component of a class or a package. But the ( ) after the dot isn't clear.
How do I implement the requestBuilder parameter?

A: This is a function with receiver type as described here: https://kotlinlang.org/docs/lambdas.html#function-types

Function types can optionally have an additional receiver type, which is specified before a dot in the notation: the type A.(B) -> C represents functions that can be called on a receiver object of A with a parameter of B and return a value of C. Function literals with receiver are often used along with these types.

It could be tricky to understand at first, but this is like you are providing a function/lambda that is a method of ImageRequest.Builder. Or in other words: your lambda receives one additional parameter of type ImageRequest.Builder and it is available in the lambda as this.
You can provide requestBuilder as any other lambda, but note that inside it you will have access to properties and methods of ImageRequest.Builder object that was provided to you.

A: What you are looking at is a "function literal with receiver". Speaking generically, a type A.(B) -> C represents a function that can be called on a receiver object of A with a parameter of B and return a value of C. Or in your example:

requestBuilder: (ImageRequest.Builder.(size: IntSize) -> ImageRequest.Builder)?

We have a function requestBuilder which can be called on a ImageRequest.Builder with a parameter size: IntSize and returns another ImageRequest.Builder.
Calling this function is just like calling any other function with a lambda as a parameter. The difference: You have access to ImageRequest.Builder as this inside your lambda block.

A: Hope the following example helps understand lambdas with receiver type:
data class Person(val name: String)

fun getPrefixSafely(
    prefixLength: Int,
    person: Person?,
    getPrefix: Person.(Int) -> String): String
{
    if (person?.name?.length ?: 0 < prefixLength) return ""
    return person?.getPrefix(prefixLength).orEmpty()
}

// Here is how getPrefixSafely can be called
getPrefixSafely(
    prefixLength = 2,
    person = Person("name"),
    getPrefix = { x -> this.name.take(x) }
)

How do I implement the requestBuilder parameter?

Hope this part of the code snippet answers the above:
getPrefix = { x -> this.name.take(x) }
PS: These lambdas with receiver types are similar to extension functions IMO.


text:
Q: Excel Add In's Custom Ribbon Tab Will Not Display I've created an application level add-in for Excel to automate some tasks. I used the VS2012 template Visual C# > Office > 2010 > Excel 2010 Add-In.
Rather than having an action pane open every time Excel does, I've opted to create a custom ribbon tab following these instructions:
http://msdn.microsoft.com/en-us/library/vstudio/bb386104.aspx
However, when I build my project, the tab does not display. I have verified the add-in is loading, and all of its features function properly, except the Ribbon. I created a simple form to test this, which loads as expected.
I then tried creating an Excel 2010 Workbook project. After adding the Ribbon (using the same steps as before) and building the project, it simply works; the ribbon tab appears as expected.
I've tried overriding ThisAddIn.CreateRibbonExtensibilityObject() to return my ribbon object, created via Globals.Factory.GetRibbonFactory().CreateRibbonManager. Again, no dice.
I'm at a loss now.

A: I also had this problem, where my VSTO ribbon wasn't being displayed.
Here's my solution, using Excel 2013 and VS2015.
What you need to do is:

*

*Open the Ribbon Designer window

*Select the RibbonTab object

*In the "Properties" window, expand "ControlId" branch, and change the ControlIdType from "Office" to "Custom"

Ridiculous, hey ?
But, strangely, it works...

A: After much pain, I found that the Position property of the RibbonGroup must be Default.

A: I had this happen with using the xml ribbon developer tool. You have to add this code (or similar functionality into ThisAddIn.cs (or primary add in class)
    protected override Microsoft.Office.Core.IRibbonExtensibility CreateRibbonExtensibilityObject()
    {
      return new Ribbon1();
    }

A: Default tab's visible property value is False, set it to True.

A: I switched back to Visual Studio 2017 Community edition and it worked for me.
As an up-gradation process, I'd migrated my VSTO Add-Ins from VS 2017 to VS 2019.
When I compiled my Add-Ins on VS 2019 Community Add-Ins worked well for MS Word and Outlook, but MS Excel was not showing the Add-In (Ribbon)
Tried many suggestions but did not work. After switching back to VS 2017 Community it started working well.


text:
Q: Can implicit DSolve solution be made to fit known solutions of SBVP? Note:  Some of the comments below (about 9) refer to an older version of this thread.  I updated it to refer to the DSolve/NDSolve question.
Also:  See All solutions to Lane-Edmon with n=5 for a complete set of general solutions to Lane-Edmon.
Consider the Lane-Edmon singular boundary-value problem:
$$
y''+\frac{2}{t} y'+y^5=0,\quad y(1)=\sqrt{3/4},\quad y'(0)=0
$$
There are two solutions: $y_1(t)=\sqrt{\frac{3}{3+t^2}}$, $y_2=-\sqrt{\frac{3}{3+t^2}}$ although DSolve can not obtain these particular solutions it can and does return two extremely-complicated (implicit) general solutions, a part of one is shown below:
eqn1 = y''[t] + 2/t y'[t] + y[t]^5 == 0;
dSol = DSolve[eqn1, y[t], t]; (* takes about a minute *)

Solve[(2 Sqrt[3] Sqrt[t]
    EllipticF[
    ArcSin[Sqrt[((-Root[-12 C[1] - 3 t #1 + 4 t^3 #1^3 &, 1] +
        Root[-12 C[1] - 3 t #1 + 4 t^3 #1^3 &, 3]) y[t]^2)/(
     Root[-12 C[1] - 3 t #1 + 4 t^3 #1^3 &,
       3] (-Root[-12 C[1] - 3 t #1 + 4 t^3 #1^3 &, 1] + y[t]^2))]] . . .

For simpler expressions, we can fit an NDSolve solution to the implicit solution to confirm the accuracy of both.  For example this thread:  Implicit DSolve solution.  And another thread:  Implicit integral solution
Is it possible to do so in this case, that it, fit the two solutions returned by DSolve above by suitable values of the constants, to $y_1$ and $y_2$ and perhaps identify which of the seven families of solutions to Lane-Edmon the DSolve results belong to (see reference above)?


text:
Q: Is it safe to execute `DROP DATABASE mykeyspace CASCADE` in DSE Hive? Is it safe to execute DROP DATABASE mykeyspace CASCADE in DSE Hive? Will it remove Cassandra data? Or can I safely be sure that only Hive metadata is removed? When I try executing this I have a table snapshot created around the same time, which makes me worried.
This question is somewhat related to Can't connect to CFS node.

A: Yes, I tried dropping a table and the equivalent table in Cassandra is still there.


text:
Q: Loop insert with select I have the following structures
Tickets
+----+---------------------+-----------+---------------+
| id | price               | seat_id   |    flight_id  |
+----+---------------------+-----------+---------------+

Seats
+----+--------+-----------+
| id | letter |  number   |
+----+--------+-----------+
| 1  | A      |     1     |
| 2  | A      |     2     |
| 3  | A      |     3     |
+----+--------+-----------+

I want to insert 2 tickets using only one query where the letter is A and the number is between 1 and 2, I guess to make more than 1 insert at time I have to use some plsql loop but I don't know how to do it and i don't know if this is the approach

A: Not sure what you are actually wanting to do, but from your description I'll assume you want 2rows in tickets referencing id 1 and 2 from seats.
SQL works in sets NOT in individual rows and loop (yes those are available via plpgsql) but avoid loops when ever possible. Inserting 2 rows does not require one; in fact it is almost exactly the same as inserting a single row. Since you didn not specify values for price and flight, I'll just omit them. But to insert 2 rows:
Insert into tickets(id,seat_id) values (1,1),(2,2);


text:
Q: I am unable to use padRight Im trying to add zeros when necessary to a mapping but it is not working.
This is the payload im working with:
[
    {

        "groupName": "POSCH",

        "groupMembers": [
            {
                "dealerNumber": "262",

                "mainDealer": true
            },
            {
                "dealerNumber": "243",

                "mainDealer": false
            }
        ]
    },
    {

        "groupName": "PRUCKNER",

        "groupMembers": [
            {
                "dealerNumber": "213",

                "mainDealer": true
            },
            {
                "dealerNumber": "262",

                "mainDealer": false
            }
        ]
    }]

Im currently writting this in order to filter the dealerNUmber that contains true in maindealer only. I believe that is in a good state but i cant add the zeros
%dw 2.0
output application/json
---
payload map {
    groupName: $.groupName,
    dealers: $.groupMembers filter $.mainDealer == true map {
        dealerNumber: $.dealerNumber padRight(5, "0"),
        locationName: $.locationName
    }
}

In order to get the 262 becoming 00262.
But it is giving me this error :
Invalid input ',', expected ')' for the enclosed expression. (line 7, column 48):

7|         dealerNumber: $.dealerNumber padRight(5, "0"),
                                                  ^
Location:
main (line: 7, column:48)

A: There are a
couple of problems with the provided DataWeave script.

*

*As per your requirement you need leftPad and not rightPad since you are trying to add zeros to the left of your string. You need to import it as it is in the dw::core::Strings module.

*You are mixing infix and prefix notations. You can use only one of them at a time and infix is only possible when you want to call the function with 2 params.
Refer this documentation

DataWeave supports both prefix notation (function (param1, param2))
and infix notation (param1 function param2) for function calls. Note
that you can use infix notation only with functions that accept only
two parameters.

Your DataWeave should look like this after the suggested changes:
%dw 2.0
import leftPad from dw::core::Strings
output application/json
---
payload map {
    groupName: $.groupName,
    dealers: $.groupMembers filter $.mainDealer == true map {
        dealerNumber: leftPad($.dealerNumber,5, "0"),
        locationName: $.locationName
    }
}


text:
Q: centering a div vertically breaks on refresh I am centering a div vertically in another div using the following code:
 var heightf = $('.cx1').height();
 var heightg = $('.cx2').height();
 heighth = (heightf - heightg) / 2;
 if (heighth > 0) {
    $('.cx2').css({ "marginTop": heighth });
 }

I have this within a document ready wrapper, and a window resize wrapper so that as the screen size changes the image remains centered (responsive).
This seems to work fine in all browsers, however when I refresh on Chrome and Kindle Fire, the div gets pushed down to the bottom rather than remaining in the center.
Can anyone explain why?

A: I don't see all the code that you have, so I can't tell why it would do that in Chrome (because my code doesn't do it).
It might be possible that you have a "collapsing margin" for the two divs.  You can add a padding: 1px 0 to the outer div so that the vertical margins don't collapse.
I think you use a window resize handler because your outer div is tied to the size of the window?  So I make it the same height as the window in the following code.
This code works on Chrome on a Mac:
<!DOCTYPE html>

            hello


text:
Q: Primavera P6 - Where Project Start/Finish dates are stored Does anyone know where Primavera P6 stores the project start dates and the project finish dates in the database?
I tried to find this information in different tables, including but not limited to, Project, Task, ProjWBS, but it is not there.
Thanks in advance.

A: look in the TASK table for target_end_date / target_start_date. Here's documentation on the P6 db schema (for v8).https://docs.oracle.com/cd/E20686_01/helpmain.htm?toc.htm?schema_documentation.htm


text:
Q: HandleError vs. ProvideFault inconsistencies in workflow service, how to handle? In our WF4 workflow service, we try to be as robust as possible. One of the things we do is to log errors inside HandleError and ProvideFault (IErrorhandler). The documentation states clearly that HandleError would be the right place to do the logging, but I see some strange things happen:

*

*I see some errors that only trigger ProvideFault, but never HandleError, one example was:
System.NullReferenceException: Object reference not set to an instance of an object.
at System.ServiceModel.Activities.Dispatcher.DurableInstanceManager.GetInstanceAsyncResult.GetInstance()
at System.ServiceModel.Activities.Dispatcher.DurableInstanceManager.GetInstanceAsyncResult..ctor

*There are also some errors that only trigger HandleError, but never ProvideFault, one example was:
System.ServiceModel.CommunicationException: There was an error reading from the pipe: The pipe has been ended. (109, 0x6d).
at System.ServiceModel.Channels.PipeConnection.Read(Byte[] buffer, Int32 offset, Int32 size, TimeSpan timeout)
at System.ServiceModel.Channels.SessionConnectionReader.Receive(TimeSpan timeout)

*Finally there are errors that trigger both, first ProvideFault and then HandleError (on a background thread)

*If possible, I want to log the corresponding incoming message, too. I do this with OperationContext.Current.RequestContext.RequestMessage.ToString() This usually only works in ProvideFault, in HandleError we don't have the RequestContext any more
So my conclusion was, to log ALL errors, I must log in both methods. But that leads to a lot of duplicated log entries, due to 3..
My current workaround was to "remember" the last logged exception from ProvideFault, and ignore it if the same exception enters HandleError. Looks not very clean to me.
Has anybody a better, reliable method to log all errors that can happen inside a WF service?
And please don't point to Logging exceptions in WCF with IErrorHandler inside HandleError or ProvideFault? as that does not provide any help.

A: I've seen scenario 2 happen in a different context (BizTalk adapter), and it seems that HandleError is called because there's an exception that occurs in the adapter, but ProvideFault is not called because there's no message to actually return - the fault occurred in such a way that it prevent the adapter from actually generating/reading/translating the message and passing it on to the pipeline.  This seems to preclude even a fault message from getting generated.  Having a failure to read from a pipe would seem to constitute this - your service doesn't know if it failed because it never even connected or if it failed because the remote server failed.  Things like TransactionAbortedException could also cause this, or (in my particular case), a SqlException can cause it.
This should give some clue for case #1, which I haven't seen myself or reproduced: it's due to improper exception handling somewhere in the messaging chain.  In this case, a fault message was generated but something higher up the chain failed to handle the exception in such a way that HandleError could be called.  A NullReferenceException makes sense here - if you don't handle null checks properly it's hard to say what else will happen down the line in this kind of case.
As far as resolving this goes, I would probably try to log in both places, with some additional information explaining where the log came from.  That'd be failsafe, even if it does duplicate logging.  On the other hand, if you have a list of exceptions that generate one or both of these scenarios, you might implement logic to check for what kind of exception it is (or where it occurred) - perhaps doing less logging if it's an exception that's likely to be handled by the other method.


text:
Q: Are eigenspaces closed? Suppose $A$ is an operator on a Hilbert space $\mathcal{H}$ and $a$ an eigenvalue of it. Then, is the corresponding eigenspace closed?

Please give a "complete" answer as to when (finite/infinite-dimensional spaces, conditions on the operator $A$, etc.) the answer is affirmative or negative.

A: I guess you're talking about a bounded linear operator $A$, which is hence continuous. For $\lambda$ a scalar, the linear operator $\lambda I$ is also bounded and thus continuous. So $A - \lambda I$ is continuous. The preimage of a closed set under a continuous function is closed. The set $\{0\}$ is closed so the preimage $(A - \lambda I)^{-1}(\{0\})$ is closed. By definition an eigenspace for $\lambda$ is exactly $$(A - \lambda I)^{-1}(\{0\}) = \{v \in \mathcal{H}\ | \ (A - \lambda I)(v)=0\}=\{v \in \mathcal{H}\ | \ Av=\lambda v\}.$$


text:
Q: Passing parameters back and forth between Powershell and Access VBA I am using VBA to kick off a PowerShell script. I am able to pass some parameters from the VBA application to the PowerShell script, however I am unable to figure out how to get powershell to feed data back to the VBA application.
I appreciate any insight you guys might have for me in figuring this out.
Thank you.

A: You should be able to insert something into the Access database like this:
$db = 'C:\path\to\your.mdb'

$value = "..."

$conn = New-Object -COM ADODB.Connection
$conn.open("Provider = Microsoft.Jet.OLEDB.4.0;Data Source=$db")

$cmd = New-Object -COM ADODB.Command
$cmd.ActiveConnection = $conn
$cmd.CommandText = "INSERT INTO [table] ([field]) VALUES ('$value')"
$cmd.Execute()

$conn.Close()


text:
Q: Need more amps to charge a phone I am trying to charge my phone (Samsung galaxy S6) using solar power, I have the output connected to a circuit that takes it from around 20 volts down to about 5.5 volts. When i plug my phone into the circuit it says it is charging but proceeds to loose power. The circuit generates about 100 milliamps but this is not enough. how can I increase the amps of the circuit.

A: Since you need 5.5 volts for charging, and you're not getting enough current, this means that you're also not getting enough power. P=I*V. You can't just "fix" that without breaking a couple of laws of physics.
The only solution is to get a bigger and/or better solar panel.
Since you're only getting about 100 mA, it's not worth trying to improve the efficiency of the converter. It would get you up to at most something like 150 mA.


text:
Q: AWS CLI syntax error: Error parsing parameter '--image': Expected: '=', received: ''' for input: I am trying to follow a walkthrough involving using AWS to use live feed facial recognition (see link below). I have done the 7 previous steps without issue and am currently on step 8, where I have uploaded a picture to a S3 bucket, and I have to do the command in cmd:
aws rekognition index-faces --image '{"S3Object":{"Bucket":"<S3BUCKET>","Name":"<MYFACE_KEY>.jpeg"}}' --collection-id "rekVideoBlog" --detection-attributes "ALL" --external-image-id "<YOURNAME>" --region us-west-2
I have done this, with my own information input in, but I get an error that states:
Error parsing parameter '--image': Expected: '=', received: ''' for input:
'{S3Object:{Bucket:,Name:.jpeg}}'
I have have looked up what could be the issue, with many solutions involving Windows systems having a different style of quotations compared to the walkthrough (i.e. switching single quotes to doubles and doubles to escaped quotes). No matter what I try, I cannot seem to figure out the issue. Does anyone have an idea of what would be the correct syntax for this on a Windows system or if I am doing something else wrong?
Walkthough: https://aws.amazon.com/blogs/machine-learning/easily-perform-facial-analysis-on-live-feeds-by-creating-a-serverless-video-analytics-environment-with-amazon-rekognition-video-and-amazon-kinesis-video-streams/


text:
Q: Triangle Inequality for supremum metric Edited Heavily
Here all functions are from $[0,1]$ to $\mathbb{R}$ and are bounded.
Prove the following Triangle inequality in following case:
$$\sup_{a\in[0,1]}|X(a)-Y(a)|\le\sup_{a\in[0,1]}|X(a)-Z(a)|+\sup_{a\in[0,1]}|Z(a)-Y(a)|$$

A: Let $\alpha = \sup_{a \in [0, 1]} |X(a) - Z(a)|$ and $\beta = \sup_{a \in [0, 1]} |Z(a) - Y(a)|$.
$$
\begin{align*}
\alpha + \beta &\ge |X(a) - Z(a)| + |Z(a) - Y(a)| & \text{ for all $a \in [0, 1]$}\\
&\ge |X(a) - Y(a)| & \text{}
\end{align*}$$
Therefore $\alpha + \beta$ is an upper bound on the set $\{|X(a) - Y(a)| : a \in [0, 1]\}$.
Hence by definition of supremum (least upper bound), $\alpha + \beta \ge \sup_{a \in [0, 1]} |X(a) - Y(a)|$.

A: Note I have abused notation below a little, in that I use $x$ both as a 'free' variable and also as the $\sup$ variable. Hopefully it is clear.
A useful result is that if $f(x) \leq g(x)$ for all $x$, then $\sup_x f(x) \leq \sup_x g(x)$. To see this, note that $g(x) \leq \sup_x g(x)$, hence $f(x) \leq \sup_x g(x)$. Taking $\sup_x$ of the left hand side gives $\sup_x f(x) \leq \sup_x g(x)$.
Another useful and obvious result is that if $c$ is a constant, then $\sup_x (f(x) +c) = c + \sup_x f(x)$.
Now consider $f(x)+g(x)$. You have $f(x)+g(x) \leq f(x) + \sup_x g(x)$. Using the above results, we get $\sup_x (f(x) + g(x)) \leq \sup_x (f(x) + \sup_x g(x)) = \sup_x f(x) + \sup_x g(x)$.
Let $f(a) = |X(a)-Y(a)|$, $g(a) = |X(a)-Z(a)|$ and $h(a) = |Z(a)-Y(a)|$. You know that $f(a) \leq g(a)+h(a)$ for all $a$ by the triangle inequality. Now using the above results you have $\sup_a f(a) \leq \sup_a (g(a)+h(a)) \leq \sup_a g(a) + \sup_a h(a)$, which is the result you were trying to prove.