text:
Q: Why is Button not working in tkinter, when i click it it shows an error I am trying this code. I want to use don function for bind() and command. It is showing don() missing 1 required positional argument: 'Event'. how to fix it
my code
from tkinter import *
root = Tk()
root.geometry("600x500")

def don(Event):
    print("hello")

root.bind("<Return>", don)
btn1 = Button(root, text="check! ", command=don).pack()

root.mainloop()

A: All you need to do is get rid of Event or as the person said above me Event=None. Depends if you are going to build on it later and add some parameters
from tkinter import *
root = Tk()
root.geometry("600x500")

def don():
    print("hello")

root.bind("<Return>", don)
btn1 = Button(root, text="check! ", command=don).pack()

root.mainloop()

A: The root of the problem is that a function called via bind automatically gets an event parameter, but a function called by the command option does not. The trick is to make a function that can be called with or without a parameter, and which doesn't use the parameter (since it isn't guaranteed to be there).
The normal way to do this is to make the event parameter options, which is done like this:
def don(event=None):
    print("hello")

This will cause event to be set to None if it's not passed in, which is harmless since the function doesn't use the event parameter.


text:
Q: Generating an unsorted List Giving a list with $n$ elements, in how many ways can this list be unsorted (Where an unsorted list is defined as a list in which no two adjacent elements are sorted. I.e any two adjacent elements will not be adjacent in the sorted list. As opposed to non-sorted list in which the list is merely non sorted).
Not all lists can be unsorted. In particular if the number of elements in the list $n$ minus the number of repetitions $r$ in the list is less than or equal to 3, the list can't be unsorted. I.e if
$$n - r \le 3$$
Giving the above, I'm interested only in the maximum number of unsorted lists that can be generated from a list of length $n$
Take the list:
$$\{1,2,3,4,5\}$$
Two possible unsorted variants are:
$$\{1,3,5,2,4\}$$
$$\{1,4,2,5,3\}$$
Or even better, the list:
$$\{1,2,3,4\}$$
Can be unsorted into two possible permutations:
$$\{3,1,4,2\}$$
$$\{2,4,1,3\}$$

A: This sounds like a question that is very hard to get right, though I would love to be proven wrong.  Here is an extremely handwavy approach to the asymptotic value for large $n$.  We want to figure the probability that a random permutation will be acceptable.  Imagine placing numbers in the odd positions first, then filling the even ones.  Nothing can go wrong during the odd position fill.  If you fill an even position randomly, you have about $\frac 4n$ chance that it will be next to one of the neighboring numbers and $\frac {n-4}n$ that it will not be.  We have $\frac n2$ even slots to fill, so the chance a random permutation is acceptable is about $\left( 1-\frac 4n\right)^{n/2}=\left( 1-\frac 2{n/2}\right)^{n/2}$.  The limit of this as $n$ gets large is $e^{-2}$.  We have ignored end effects, the chance that two neighboring odd slots share a neighbor, the chance that two neighboring odd slots are neighbors, and correlations between the chance that one placement fails and another fails.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get the brackets in the multirow spanning all three rows? I'm constructing a table, where I have a multirow spanning 3rows in the center of this table. For examples, from row 6 to 8 in center of the table. This is hard because the brackets have to be located only center position.
\begin{table}[]
\centering
\scalebox{0.9}{
\begin{tabular}{c|c|c}
\toprule
Type & VoVNet & Output \\ \hline
\multirow{3}{*}{Stem} & 3$\times$3 conv, 64,  stride=2 & 112$\times$112 \\ \cline{2-3}
 & 3$\times$3 conv, 64,  stride=1 & 112$\times$112 \\ \cline{2-3}
 & 3$\times$3 conv, 128, stride=1 & 112$\times$112 \\ \hline
Pooling & 3$\times$3 max pool, stride=2 & 56$\times$56 \\ \hline
\multirow{3}{*}{\begin{tabular}[c]{@{}c@{}}DRF block\\ stage 2\end{tabular}} & {[}3$\times$3, conv, 128{]} $\times$ 5 & 56$\times$56 \\
 & concatenate \& {[}1$\times$1 conv, 128{]} & 56$\times$56 \\
 & 3$\times$3 max pool, stride=2 & 28$\times$28 \\ \hline
\multirow{3}{*}{\begin{tabular}[c]{@{}c@{}}DRF block\\ stage 3\end{tabular}} & {[}3$\times$3, conv, 160{]} $\times$ 5 & 28$\times$28 \\
 & concatenate \& {[}1$\times$1 conv, 256{]} & 28$\times$28 \\
 & 3$\times$3 max pool, stride=2 & 14$\times$14 \\ \hline
\multirow{2}{*}{\begin{tabular}[c]{@{}c@{}}DRF block\\ stage 4A\end{tabular}} & {[}3$\times$3, conv, 192{]} $\times$ 5 & 14$\times$14 \\
 & concatenate \& {[}1x1 conv, 512{]} & 14$\times$14 \\ \hline
\multirow{3}{*}{\begin{tabular}[c]{@{}c@{}}DRF block\\ stage 4B\end{tabular}} & {[}3$\times$3, conv, 224{]} $\times$ 5 & 14$\times$14 \\
 & concatenate \& {[}1$\times$1 conv, 512{]} & 14$\times$14 \\
 & 3$\times$3 max pool, stride=2 & 7$\times$7 \\ \hline
\multirow{2}{*}{\begin{tabular}[c]{@{}c@{}}DRF block\\ estage 5A\end{tabular}} & {[}3$\times$3, conv, 256{]} $\times$ 5 & 7$\times$7 \\
 & concatenate \& {[}1$\times$1 conv, 1024{]} & 7$\times$7 \\ \hline
\multirow{2}{*}{\begin{tabular}[c]{@{}c@{}}DRF block\\ stage 5B\end{tabular}} & {[}3$\times$3, conv, 288{]} $\times$ 5 & 7$\times$7 \\
 & concatenate \& {[}1$\times$1 conv, 1024{]} & 7$\times$7 \\
 \bottomrule
\end{tabular}
}
\caption{ Overall architecture of VoVNet. VoVNet is compose of 39 convolution layers. Note that each "conv" layer has the sequence Conv-BN-ReLU.}
\label{tb:VoVNet}
\vspace{-0.35cm}
\end{table}


text:
Q: How can I make a component render onClick in a React functional component? I'm a bit surprised I'm having trouble finding this online, but I can't seem to find an example of how to do this in a React functional component. I have a React component that I would like to render when I click a button. Right now the function fires and I can see my console.log firing, however the component isn't rendering. My first guess was that it won't render because React doesn't know to update the view, however I added boolean via useState and it still won't render. What am I doing wrong?
Below is the relevant code. How can I get the component in addSection to render?
const FormGroup = ({index}) => {
  const [additionalSection, setAdditionalSection] = useState(false);

  const addSection = form => {
    setAdditionalSection(true);
    console.log('form', form);

    return additionalSection && (

This should render

        <AdditiveSection
          form={form}
          register={register}
          errors={errors}
        />

    );
  };
  ...
 return (
...
 <FormAdd>
   <LinkButton
      type="button"
      onClick={() => addSection(form)}
   >
     span className="button--small">{form.button}
   </LinkButton>
 </FormAdd>
);

A: You should change your state (or a prop in your useEffect dependency array in case you had one) in order to force a rerender. In this case:
setAdditionalSection(prevState=>!prevState);

A: A state change like the one you are calling, will trigger a re-render.
But all html to be rendered must be included in the functional components return statement.
The elements you want to render can be conditionally rendered like this:
    const FormGroup = ({index}) => {
      const [additionalSection, setAdditionalSection] = useState(false);

      const addSection = form => {
        setAdditionalSection(true);
        console.log('form', form);
      };
      ...
     return (
    ...
     <FormAdd>
       <LinkButton
          type="button"
          onClick={() => addSection(form)}
       >
         {form.button}
       </LinkButton>
       {additionalSection &&

This should render

            <AdditiveSection
              form={form}
              register={register}
              errors={errors}
            />

       }
     </FormAdd>
    );


text:
Q: C3.JS : show only one line on load by default for line chart I am using C3.js for multiple line graph.
I have around 2 line at the start but out of those two, i want to show only one and hide another one.
I have used   chart.show('data1')
but without any luck.
Please help.
Another question is , can we have drilling charts in C3.js ?
Thanks.
The code :

 <link href="./c3.css" rel="stylesheet" type="text/css">

A: By default all the lines will be visible. so hide all the lines first and then show the line you want to see
chart.hide(['data1', 'data245']);
chart.show('data1');

If you have only 2 lines and want hide one then
chart.hide('data245');

check the show and hide api
I created a fiddle implementing the above.


text:
Q: Django-CMS text editing not working on Apache When serving my django-cms application on apache with mod_wsgi I can't get the text-plugin to work.
The difference is that when serving on apache the textedito tries to get an url that does not exist.
On Apache:
/admin/js/iframe/default/wymiframe.html
With manage.py runserver
/static/cms/wymeditor/iframe/default/wymiframe.html
the wymiframe.html file is present in my static folder and is accessible but not via the wrong URL that I get when running the app through apache.
What do I do to get the text-plugin requesting the right URL?

A: What have you set STATIC_URL to in your settings file? That in part is what controls paths when links are created.
https://docs.djangoproject.com/en/1.4/howto/deployment/wsgi/modwsgi/#serving-the-admin-files

A: My problem was that I served static content on a subdomain and I had problems with Access Control.
My solution was to set
Header set Access-Control-Allow-Origin *

in my apache config file


text:
Q: Exercise: The measure of the boundary of a level set of a Holder continuous function is positive
Let $M$ be a compact manifold in $R^3$ and consider a non negative
function $f\in C^{1,\alpha}(M)$ for some $0<\alpha<1$. I am interested
in showing that $|\partial \{f>0\} |>0$, where $|\cdot|$ stands for
the Hausdorff measure and $\partial A$ denotes
the boundary of $A$.

My Attempt:
By definition, $x^* \in M$ is a boundary point of $\{f>0\}$, if for every $r>0$ it holds that $B_r(x^*) \cap \{f>0\} \neq \emptyset$ and $B_r(x^*) \cap \{f=0\} \neq \emptyset$. In other words, if for every ball with center at $x^*$, I can find not only points of $\{f>0\}$ but also of its complement. Now, it is also true that $M=\{f>0\}\cup \{f=0\} $. Hence, if I could find/construct a dense subset of $\{f>0\}\cup \{f=0\}$, let's say $D$, I could obtain that $B_r(x^*) \cap D \neq \emptyset$ by density. This in particular would yield that $B_r(x^*) \cap (\{f>0\}\cup \{f=0\})=(B_r(x^*) \cap \{f>0\})\cup (B_r(x^*) \cap\{f=0\}) \neq \emptyset$. At this point, two issues arise:

*

*The latter does not imply that both intersections must be non empty, but only at least one between them.

*I am not sure if such a dense set exists.

DISCLAIMER: I have seen some similar question here in which the answer is given by a Cantor set. However, since I am not that familiar with topology, I would prefer to prove this (if possible) using the "slightest" tools.
I feel that density is a key part here but I am not able to tackle this problem properly. Any help or hint will be much appreciated!
Thanks in advance.

A: I do not understand why the dense set would help you in this situation as nonempty sets can still have zero Hausdorff measure. In this answer I will denote the $2$-dimensional Hausdorff measure by $\mathcal{H}^2$ (using the absolute value seems very misleading to me). In the comments I gave some heuristics. Let me back this up by something a bit more rigorous.
As I pointed out in the comments it depends on the desired notion of boundary (either withing the manifold with the subspace topology or in $\mathbb{R}^3$). As you are using $\{ f> 0 \}^c = \{ f=0 \}$, you seem to take the boundary within the manifold. In this case, your claim is not true. Consider
$$\mathbb{T}^2 = \{ (x,y,z) \in \mathbb{R}^3 \ : \ (x^2+y^2-2)^2+z^2 =1 \}$$
(some 2-dimensional torus) embedded in $\mathbb{R}^3$. This is a compact, smooth manifold. Now consider the map $f: \mathbb{T}^2 \rightarrow \mathbb{R}, f(x,y,z)=z^2$. Then $f$ is a smooth, nonnegative map. However, the boundary of the zero locus is equal to two circles (1-dimensional manifolds) and thus, the $2$-dimensional Hausdorff measure will vanish.
If you were to pick the boundary in the topology of $\mathbb{R}^3$, (meaning, the balls should intersect $\{ f>0 \}$ and $\{ f>0 \}^c$), then you get $\{f>0 \} \subseteq \partial \{ f>0 \}$ (that is because any ball in $\mathbb{R}^3$ intersects $M^c$). However, $\{ f>0 \}$ is an open subset of a $2$-dimensional, $C^{1,\alpha}$ manifold and thus is a $2$-dimensional $C^{1,\alpha}$ manifold itself. However, nonempty $2$-dimensional $C^{1,\alpha}$ manifolds have positive $2$-dimensional Hausdorff measure. As $M$ is embedded, for every point $p\in M$ there exists a diffeomorphism $\varphi: B_1(0) \rightarrow \mathbb{R}^3$ such that $$\varphi((-1,1)^3) \cap \{ f>0\} = \{ \varphi(x,y,0) \ : \ (x,y,0)\in (-1,1)^3 \}$$
and such that $\varphi(0)=p$. By the monotonicity of measures, we get
$$ \mathcal{H}^2( \varphi([-0.5, 0.5] \times [-0.5,0.5] \times \{0\})) \vert \leq \mathcal{H}^2( \{ f>0 \} ) \leq \mathcal{H}^2( \partial \{ f>0 \} ). $$
However, as $\varphi$ is $C^1$, we have that its restriction to $[-0.5,0.5]^3$ is bilipschitz (lets say with the inverse having lipschitz constant equal to $L$). By Measure of image of Lipschitz function is bounded? (the $C^{1,\alpha}$ regularity actually would allow you for a simpler proof of this fact, in fact we do not really need $M$ to be more than a topological manifold, see the next paragraph) we have
$$ 0<1 = \mathcal{H}^2([-0.5,0.5] \times [-0.5,0.5]\times \{0\})=\mathcal{H}^2(\varphi^{-1} \varphi([-0.5, 0.5] \times [-0.5,0.5] \times \{0\}))
\leq L^2 \mathcal{H}^2(\varphi([-0.5, 0.5] \times [-0.5,0.5] \times \{0\})). $$
Hence, we get
$$ 0< 1/L^2 \leq \mathcal{H}^2(\partial \{ f>0\}). $$
Added: The $C^{1, \alpha}$ assumption is not really need. Everything works in the topological setting if your manifold is locally given as a graph. Then we can use the projection map. I.e. we have
$$ \mathcal{H}^2((-1,1)^2)=\mathcal{H}^2(P(\{ (x,y, g(x,y)) \in \mathbb{R}^3 \ : \ (x,y)\in (-1,1)^2 \})) \leq \mathcal{H}^2(\{ (x,y, g(x,y)) \in \mathbb{R}^3 \ : \ (x,y)\in (-1,1)^2 \})  $$
where $g$ is any map (we need no regularity, only the fact that we can write it as a graph) and $P: \mathbb{R}^3\rightarrow \mathbb{R}^2, (x,y,z)=(x,y)$ is the projection. So you only need the estimate for the projection which is much easier to show (also because it has all the regularity one can hope for).

A: I think I figured out the missing keys so I will post the whole argument here as an answer. In case, there are still mistakes, please correct me.
We know that $f \in C^{1,\alpha}(M)$ for some $0<\alpha<1$. Hence, $f \in C^{1,\beta}(M)$ for some $0<\beta<\alpha<1$. We can find a sequence of smooth functions $g_n$ converging to $f$ such that $g_n(x)>0$ for all $x\in B_{\delta_n}(x)$ and $g_n(x)=0$ otherwise (here $\delta_n$ is chosen arbitrarily small). Moreover, since $M$ is a compact manifold, there exists a countable dense subset $\{ x_n, n \in \mathbb N\}$ in $M$. Passing to a subsequence $\hat x_n$ we obtain by density that $\hat x_n \to x^* \in M$.
We can write $M=M \setminus \big (\bigcup_{n=1}^{\infty} B_{\delta_n}(x_n) \big) \cup \big (\bigcup_{n=1}^{\infty} B_{\delta_n}(x_n) \big)$. We recall that $\big (\bigcup_{n=1}^{\infty} B_{\delta_n}(x_n) \big) \neq \emptyset$ since $\{x_n\}$ is dense. At this point, we distinguish cases. If $x^*\in M \setminus \big (\bigcup_{n=1}^{\infty} B_{\delta_n}(x_n) \big) $ then $f(x^*)=0$. If $x^* \in \big (\bigcup_{n=1}^{\infty} B_{\delta_n}(x_n) \big)$ then due to $g_n$ and by passing to a subsequence, we obtain that $f(x^*)>0$. This completes the argument.


text:
Q: Trying to assign an extern __shared__ memory pointer leads to "expression must be a modifiable lvalue" error I have something like the code below:
__device__ unsigned char* device_func(unsigned char* var_sh, unsigned char param){
    if (var_sh[0] == param)
        return var_sh + param;
    else return 0;
}

__global__ void global_func(uchar parameters){
    extern __shared__ unsigned char var_sh[];
    //just copying things from global to shared memory:
    for(int i = blockIndex; i < size; i += blockDim.x * gridDim.x){
        var_sh[i] = rla->initial[i];
    }
    var_sh = device_func(var_sh, parameters);
}

This global function is called in this way:
global_func<<< blocks,threads,shared_size >>>(parameters);

But when I try to compile, the compiler returns the following error on the line "var_sh = device_func(var_sh, parameters);":
"error: expression must be a modifiable lvalue"
I don't know why, can someone explain?

A: This error means that the expression on the left of '=' can't be modified. In this case, var_sh has been defined, it is an unsigned char array, but in your code, you assign another pointer to var_sh: 'var_sh = device_func(var_sh, parameters)', it may point to another address, but not the shared memory.

A: When we declare __shared__ memory as extern, we need to assign this variable to a pointer before using it. In my problem i was using var_sh and trying to modify it, but first i need to assign it to a pointer and then use it like i want.
I've fixed my problem doing:
extern __shared__ uchar array[];
uchar* var_sh = (uchar*) array;

This way var_sh is a modifiable lvalue and i can use and modify it.


text:
Q: How do I improve my performance with this singly linked list struct within my program? Hey guys, I have a program that does operations of sets of strings. I have to implement functions such as addition and subtraction of two sets of strings. I need to get it down to the point where performance if of O(N+M), where N,M are sets of strings. Right now, I believe my performance is at O(N*M), since I for each element of N, I go through every element of M. I'm particularly focused on getting the subtraction to the proper performance, as if I can get that down to proper performance, I believe I can carry that knowledge over to the rest of things I have to implement.
The '-' operator is suppose to work like this, for example.
Declare set1 to be an empty set.
Declare set2 to be a set with { a b c } elements
Declare set3 to be a set with ( b c d } elements
set1 = set2 - set3
And now set1 is suppose to equal { a }. So basically, just remove any element from set3, that is also in set2.
For the addition implementation (overloaded '+' operator), I also do the sorting of the strings (since we have to).
All the functions work right now btw.
So I was wondering if anyone could
a) Confirm that currently I'm doing O(N*M) performance
b) Give me some ideas/implementations on how to improve the performance to O(N+M)
Note: I cannot add any member variables or functions to the class strSet or to the node structure.
The implementation of the main program isn't very important, but I will post the code for my class definition and the implementation of the member functions:
strSet2.h (Implementation of my class and struct)
// Class to implement sets of strings

// Implements operators for union, intersection, subtraction,
//  etc. for sets of strings

// V1.1 15 Feb 2011 Added guard (#ifndef), deleted using namespace RCH

#ifndef _STRSET_
#define _STRSET_

#include <iostream>
#include <vector>
#include <string>
// Deleted: using namespace std;  15 Feb 2011 RCH

struct node {
    std::string s1;
    node * next;
};

class strSet {

private:
    node * first;

public:
    strSet ();  // Create empty set
    strSet (std::string s); // Create singleton set
    strSet (const strSet &copy); // Copy constructor
    ~strSet (); // Destructor

    int SIZE() const;

    bool isMember (std::string s) const;

    strSet  operator +  (const strSet& rtSide);  // Union
    strSet  operator -  (const strSet& rtSide);  // Set subtraction
    strSet& operator =  (const strSet& rtSide);  // Assignment

};  // End of strSet class

#endif  // _STRSET_

strSet2.cpp (implementation of member functions)
#include <iostream>
#include <vector>
#include <string>
#include "strset2.h"

using namespace std;

strSet::strSet() {
    first = NULL;
}

strSet::strSet(string s) {
    node *temp;
    temp = new node;
    temp->s1 = s;
    temp->next = NULL;
    first = temp;
}

strSet::strSet(const strSet& copy) {
    if(copy.first == NULL) {
        first = NULL;
    }
    else {
        node *n = copy.first;
        node *prev = NULL;
        while (n) {
            node *newNode = new node;
            newNode->s1 = n->s1;
            newNode->next = NULL;
            if (prev) {
                prev->next = newNode;
            }
            else {
                first = newNode;
            }
            prev = newNode;
            n = n->next;
        }
    }
}

strSet::~strSet() {
    if(first != NULL) {
        while(first->next != NULL) {
            node *nextNode = first->next;
            first->next = nextNode->next;
            delete nextNode;
        }
    }
}

int strSet::SIZE() const {
    int size = 0;
    node *temp = first;
    while(temp!=NULL) {
        size++;
        temp=temp->next;
    }
    return size;
}

bool strSet::isMember(string s) const {
    node *temp = first;
    while(temp != NULL) {
        if(temp->s1 == s) {
            return true;
        }
        temp = temp->next;
    }
    return false;
}

strSet strSet::operator +  (const strSet& rtSide) {
    strSet newSet;
    newSet = *this;
    node *temp = rtSide.first;
    while(temp != NULL) {
        string newEle = temp->s1;
        if(!isMember(newEle)) {
            if(newSet.first==NULL) {
                node *newNode;
                newNode = new node;
                newNode->s1 = newEle;
                newNode->next = NULL;
                newSet.first = newNode;
            }
            else if(newSet.SIZE() == 1) {
                if(newEle < newSet.first->s1) {
                    node *tempNext = newSet.first;
                    node *newNode;
                    newNode = new node;
                    newNode->s1 = newEle;
                    newNode->next = tempNext;
                    newSet.first = newNode;
                }
                else {
                    node *newNode;
                    newNode = new node;
                    newNode->s1 = newEle;
                    newNode->next = NULL;
                    newSet.first->next = newNode;
                }
            }
            else {
                node *prev = NULL;
                node *curr = newSet.first;
                while(curr != NULL) {
                    if(newEle < curr->s1) {
                        if(prev == NULL) {
                            node *newNode;
                            newNode = new node;
                            newNode->s1 = newEle;
                            newNode->next = curr;
                            newSet.first = newNode;
                            break;
                        }
                        else {
                            node *newNode;
                            newNode = new node;
                            newNode->s1 = newEle;
                            newNode->next = curr;
                            prev->next = newNode;
                            break;
                        }
                    }
                    if(curr->next == NULL) {
                        node *newNode;
                        newNode = new node;
                        newNode->s1 = newEle;
                        newNode->next = NULL;
                        curr->next = newNode;
                        break;
                    }
                    prev = curr;
                    curr = curr->next;
                }
            }
        }
        temp = temp->next;
    }
    return newSet;
}

strSet strSet::operator - (const strSet& rtSide) {
    strSet newSet;
    newSet = *this;
    node *temp = rtSide.first;
    while(temp != NULL) {
        string element = temp->s1;
        node *prev = NULL;
        node *curr = newSet.first;
        while(curr != NULL) {
            if( element < curr->s1 ) break;
            if( curr->s1 == element ) {
                if( prev == NULL) {
                    node *duplicate = curr;
                    newSet.first = newSet.first->next;
                    delete duplicate;
                    break;
                }
                else {
                    node *duplicate = curr;
                    prev->next = curr->next;
                    delete duplicate;
                    break;
                }
            }
            prev = curr;
            curr = curr->next;
        }
        temp = temp->next;
    }
    return newSet;
}

strSet& strSet::operator =  (const strSet& rtSide) {
    if(this != &rtSide) {
        if(first != NULL) {
            while(first->next != NULL) {
                node *nextNode = first->next;
                first->next = nextNode->next;
                delete nextNode;
            }
        }
        if(rtSide.first == NULL) {
            first = NULL;
        }
        else {
            node *n = rtSide.first;
            node *prev = NULL;
            while (n) {
                node *newNode = new node;
                newNode->s1 = n->s1;
                newNode->next = NULL;
                if (prev) {
                    prev->next = newNode;
                }
                else {
                    first = newNode;
                }
                prev = newNode;
                n = n->next;
            }
        }
    }
    return *this;
}

A: Yes, I believe your current operator- is O(N*M).
Since this is homework, I don't want to give you too much information, but ...
If your linked list were ordered, then you could write subtraction in O(N+M). This leaves two questions for you: how to keep the list ordered? and how to write an O(N+M) subtraction algorithm, given ordered lists.


text:
Q: Nesting Data Frames I have a function wrapping RODBC::sqlQuery that takes a start & end date and returns 5 columns with and roughly 1 million rows per call. I need to iterate through a list of about 60 dates storing the function's resulting data frames in a list.
What I want to know is:

*

*How to pass both start and end date arguments to the function in an
apply-style fashion

*How to store the resulting data frames neatly (like a table of |date|data.frame.pointer|)

Here's some of the code:
get.data <- function(date.start, date.end) { ... }
date.range <- seq(as.Date("2009-01-01"), Sys.Date(), by="1 month")

And sample output:
get.data(date.start="2009-01-01", date.end='2009-02-01')
               date    country    oId    eId       pId
    1    2009-01-01  Australia  12345  12345     12345
    2           ...        ...    ...    ...       ...

Thank you for your help. I've been trying to figure out how to do this for hours to no avail.

A: For what you want, mapply will do the trick:
n <- length(date.range)
mapply(get.data, date.range[-n], date.range[-1])

This returns a list whose elements are the individual returned values from get.data. So in this case, you would get a list of data frames. That may well be the most appropriate way of storing the output, but it would depend on what you want to do with it.


text:
Q: Angular 7 - Set variable click event with *ngFor property I would like to set different methods to be called at the (click) event. I created an array of dictionaries in the ts-File:
headerElements = [
{
  descriptor: "Name",
  icon: "/assets/imgs/name-32.png",
  cursor: "default",
  event: "null"
},
{
  descriptor: "Price",
  icon: "/assets/imgs/description-32.png",
  cursor: "pointer",
  event: "orderByPrice()"
},
{
  descriptor: "Link",
  icon: "/assets/imgs/timer-32.png",
  cursor: "default",
  event: "null"
},
{
  descriptor: "Datum",
  icon: "/assets/imgs/timer-32.png",
  cursor: "pointer",
  event: "null"
}
];

The orderByPrice-Method looks like this:
  orderByPrice() {
    this.isSortedAsc = !this.isSortedAsc;
    const direction = this.isSortedAsc ? "desc" : "asc";
    this.gearPieces = this.gearService.getGearComponentsOrderByPrice(direction);
  }

I call it like this in the html-File:

        {{header.descriptor}}

Unfortunately, setting a specific method to be called on (click) gives me this error:

Template parse errors: Parser Error: Got interpolation ({{}}) where
  expression was expected at column 0 in [{{header.event}}]

Is it even possible, to accomplish this?

A: One of the easy solution will be (If headerElements variable data is not retrieved from server and is locally defined):
Change headerElements.event as follows:
headerElements = [
{
  descriptor: "Name",
  icon: "/assets/imgs/name-32.png",
  cursor: "default",
  event: () => {return this.test1();}
},
{
  descriptor: "Price",
  icon: "/assets/imgs/description-32.png",
  cursor: "pointer",
  event: () => {return null;}
},
{
  descriptor: "Link",
  icon: "/assets/imgs/timer-32.png",
  cursor: "default",
  event: () => {return null;}
},
{
  descriptor: "Datum",
  icon: "/assets/imgs/timer-32.png",
  cursor: "pointer",
  event: () => {return this.test2('It works!');}
}
];

Also, modify HTML click event as follows:
(click)='value.event()'

A: Update
Instead of function names, you can directly attach the function references to the event prop in your object. So if you have a method:
orderByPrice() {
    console.log("order by price called");
}

attach the references like:
headerElements = [
  {
    descriptor: "Price",
    icon: "/assets/imgs/description-32.png",
    cursor: "pointer",
    event: this.orderByPrice //<---- assign the actual reference of the function
   },
   .
   .
]

Old answer (I don't know what was I thinking)
You can create reference for the methods in your class. Something like:
orderByPrice = () => {
    console.log("order by price called");
}

Use the function references for assigning to event to header elements instead of their names
The create your object like:
headerElements = [
  {
    descriptor: "Name",
    icon: "/assets/imgs/name-32.png",
    cursor: "default",
    event: null
  },
  {
    descriptor: "Price",
    icon: "/assets/imgs/description-32.png",
    cursor: "pointer",
    event: this.orderByPrice //<---- assign the actual reference of the function
  },
  {
    descriptor: "Link",
    icon: "/assets/imgs/timer-32.png",
    cursor: "default",
    event: null // <-- as described in comments have it falsy, actual null
  },
  {
    descriptor: "Datum",
    icon: "/assets/imgs/timer-32.png",
    cursor: "pointer",
    event: null
  }
];

Have your HTML like:

    {{header.descriptor}}

Edit
(Based on the comments)
This part contains checks and explanations if it is correct to have a variable in an angular class referencing a function.
I checked the component instance when we add a variable as a function reference rather than adding a named function in the class.
So, When a named function is added it appears in the prototype of the component instance. But if I have a variable reference to the function then the variable(so the function) appears directly in the component instance(this means code duplication).
To avoid this, we can add the function to the prototype of the class.
  AppComponent.prototype['orderByPrice'] = (): void => {
    console.log("order by price called");
  }

I couldn't find any other differences. I am open to suggestions, counter questions and correcting my mistake if this is not correct.
Thanks!


text:
Q: Searching for text then selecting the parent element? (ruby) I'd like to search for text within the html then select the parent of the element so I can use that to store a reference ID as a string.  (I'm using watir to do this as the purpose for it is automated testing)
so here's an example:

                     ref4040

                 example

Is there a way I can use ruby to search for the text "example" then select the parent so I can store the reference ID within the span as a string?
(I know you can do it the simple way in this example of selecting the div then the span, but on the project I am actually working on, this is not possible.  The only possible way of doing it is via search for the text then selecting the reference.)

A: You can get the parent element by doing .parent.
So you could do something like:
browser.div(:text, 'example').parent.span(:class, 'story').text


text:
Q: Hidden UserForm apprears when hovering over Excel app I'm developing a tool for my company using Excel VBA. In this tool I need UserForms. I noticed that when i hide them (usually when the user clicks "Ok", the code processes the info I need and there's a line somewhere saying Me.Hide), they still appear when I hover the mouse on the Excel app in the taskbar, when another app is on top.
The userform does disappear when I click on Excel.
I also noticed that the data the user entered is still there when I open the userform again. I don't know if these issues are related.
(The question is of course how to have the userform not appear and how to reset the fields)

A: I used Unload Me instead of Me.Hide and it worked perfectly


text:
Q: Texture partially off screen - performance difference On the picture is an example of two situations, where a textured polygon is being rendered. All done by Opengl ES2.

A) the polygon is partially off the viewport
B) the polygon is completely inside it
My question:
Is situation 'A)' going to consume less system/gpu resources*, because the texture is partially off screen, or will it perform just the same as if i rendered it inside of the viewport and why?
*"Resources" - meaning speed, not memory.
I know that opengl does calculate  vertices first, before rendering texture and if the vertices are off screen/viewport, it skips any further calculations, but is that the same case with textured object that is partially off screen? Will it omit the part of the texture that is not visible?

A: Situation A should be faster. Vertex processing will be the same. After that, clipping to the view volume is applied. In situation A, part of the polygon will be clipped, while the whole polygon goes through in situation B. After that, the polygon is rasterized, and the resulting fragments go into fragment processing. Since there are fewer fragments in situation A, there's less work to do in this stage. The fragment shader does the texture sampling, so only the visible parts of the texture will be sampled in this case.
Clipping can also happen after the fragments are generated, but I would always expect it to be done before the fragment shader.
While there will always be less work in situation A, this doesn't necessarily mean that you'll see a speed difference in the rendering. You could have bottlenecks in other parts of the pipeline, or in your app code.


text:
Q: Automated transcripts of conference calls What's the best way to get an automated transcript of a FaceTime/Skype or simple audio conference call?

A: A simple answer is NO.
There are lots of Dictation software but they really only work for Dictation (one person talking in a quiet room.
Even than you have to train the software to your specific voice and how you pronounce stuff to get accurate text output
You can try to use them for transcription a conference call, but you will end up editing a lot.

A: As Buscar notes, even the best dictation software isn't really going to work for transcribing a conversation. However, you might want to read this blog post by Andy Baio on how he uses Amazon's Mechanical Turk to get transcriptions done cheaply.
The gist is, take your recording and chop it up into small chunks (he uses 5 minutes), and create Mechanical Turk jobs to transcribe each one. It's not free, but it looks like it's substantially cheaper than other paid transcription services, and the work of getting the recording onto the site could be automated relatively simply.


text:
Q: libtool failed with exit code 1 in Xcode 4.2 I compile my project, it shows this error:

Libtool /Users/trinstanchen/Library/Developer/Xcode/DerivedData/iOSSocial-dedmezxegpbuqnfkhmbfrvtphyas/Build/Products/Debug-iphonesimulator/libiOSSocial.a normal i386
      cd "/Users/trinstanchen/Downloads/iOSSocial-develop copy/iOSSocial"
      setenv IPHONEOS_DEPLOYMENT_TARGET 5.0
      setenv PATH "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
      /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool -static -arch_only i386 -syslibroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator6.0.sdk -L/Users/trinstanchen/Library/Developer/Xcode/DerivedData/iOSSocial-dedmezxegpbuqnfkhmbfrvtphyas/Build/Products/Debug-iphonesimulator -filelist /Users/trinstanchen/Library/Developer/Xcode/DerivedData/iOSSocial-dedmezxegpbuqnfkhmbfrvtphyas/Build/Intermediates/iOSSocial.build/Debug-iphonesimulator/iOSSocial.build/Objects-normal/i386/iOSSocial.LinkFileList -ObjC -fno-objc-arc -framework CoreGraphics -framework SenTestingKit -framework UIKit -framework Foundation -o /Users/trinstanchen/Library/Developer/Xcode/DerivedData/iOSSocial-dedmezxegpbuqnfkhmbfrvtphyas/Build/Products/Debug-iphonesimulator/libiOSSocial.a
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool: unknown option character `f' in: -fno-objc-arc
  Usage: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool -static [-] file [...] [-filelist listfile[,dirname]] [-arch_only arch] [-sacLT]
  Usage: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool -dynamic [-] file [...] [-filelist listfile[,dirname]] [-arch_only arch] [-o output] [-install_name name] [-compatibility_version #] [-current_version #] [-seg1addr 0x#] [-segs_read_only_addr 0x#] [-segs_read_write_addr 0x#] [-seg_addr_table ] [-seg_addr_table_filename ] [-all_load] [-noall_load]
  Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool failed with exit code 1

can anyone give me help?


text:
Q: Fragment crash: IndexOutOfBoundsException: Invalid index x, size is x after updating my database Im making an app where i download the data from an api. The data is downloaded every X minutes. When the data has been downloaded, it is stored in my DB. However, the problem i have is that whenever i update the db, the generateData() method in FragmentTrend crashes when i switch to another tab and comeback again. I get the the index out of bound exception as seen below. It crashes at line:
int y = Integer.parseInt(listDatastream.get(i).getCurrent_value());

Ive tried to test out that whenever the count != getNumberOfElementsInDatabase() then just return the value to see whether or not it would help, however, i end up with another error which is similar to this thread: DB error code 14
Any help would be appreciated! Ive been stuck with this problem for more than 3 days now! Thank you!
Additional information: I have 4 tabs and use FragmentStatePagerAdapter to navigate. Ive noticed one thing while navigating. Whenever i navigate to the neighboring tab (such as tab1 to tab2), the previous tab is not terminated. It is still on the run. I found this out by printing an endless forloop with text. The for loop stops only when im 2 tabs away (such as from tab1 to tab3 / tab4 or tab 2 to tab4 etc). So the app crashes only when i select tab3 or tab4 then reselect tab1 or tab2 respectively.
Error:
10-29 19:37:09.693 2618-2618/? E/AndroidRuntime: FATAL EXCEPTION: main
10-29 19:37:09.693 2618-2618/? E/AndroidRuntime: Process: com.thesis.dell.MaterialTest2, PID: 2618
10-29 19:37:09.693 2618-2618/? E/AndroidRuntime: java.lang.IndexOutOfBoundsException: Invalid index 166, size is 166
10-29 19:37:09.693 2618-2618/? E/AndroidRuntime:     at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
10-29 19:37:09.693 2618-2618/? E/AndroidRuntime:     at java.util.ArrayList.get(ArrayList.java:308)
10-29 19:37:09.693 2618-2618/? E/AndroidRuntime:     at com.thesis.dell.MaterialTest2.fragments.FragmentTrend.generateData(FragmentTrend.java:166)
10-29 19:37:09.693 2618-2618/? E/AndroidRuntime:     at com.thesis.dell.MaterialTest2.fragments.FragmentTrend.drawGraphVolt(FragmentTrend.java:112)
10-29 19:37:09.693 2618-2618/? E/AndroidRuntime:     at com.thesis.dell.MaterialTest2.fragments.FragmentTrend.onCreateView(FragmentTrend.java:86)
10-29 19:37:09.693 2618-2618/? E/AndroidRuntime:     at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)
10-29 19:37:09.693 2618-2618/? E/AndroidRuntime:     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
10-29 19:37:09.693 2618-2618/? E/AndroidRuntime:     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1126)

FragmentTrend.java
package com.thesis.dell.MaterialTest2.fragments;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.LegendRenderer;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
import com.thesis.dell.MaterialTest2.MyApplication;
import com.thesis.dell.MaterialTest2.R;
import com.thesis.dell.MaterialTest2.log.L;
import com.thesis.dell.MaterialTest2.pojo.Datastream;

import java.util.ArrayList;

public class FragmentTrend extends Fragment {

private static final String STATE_DATASTREAM2 = "state_datastream2";
private ArrayList<Datastream> listDatastream = new ArrayList<>();
//private SwipeRefreshLayout mSwipeRefreshLayout;
private View view;
private LineGraphSeries<DataPoint> mVolt;
private int count;

public FragmentTrend() {
    // Required empty public constructor
}

public static FragmentTrend newInstance(String param1, String param2) {
    FragmentTrend fragment = new FragmentTrend();
    Bundle args = new Bundle();
    //put any extra arguments that you may want to supply to this fragment
    fragment.setArguments(args);
    return fragment;
}

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.tab_trend,container,false);

    count = getNumberOfElementsInDatabase();
    //setupSwipe();
    //printAllValuesInDatastream();

    if (savedInstanceState != null) {
        //if this fragment starts after a rotation or configuration change,
        // load the existing data from a parcelable
        L.t(getActivity(), "savedInstanceState not null");
        listDatastream = savedInstanceState.getParcelableArrayList(STATE_DATASTREAM2);
    }
    else {
        //if this fragment starts for the first time, load the list of data from a database
        //get a reference to our DB running on our main thread
        L.t(getActivity(), "savedInstanceState is null");
        listDatastream = MyApplication.getWritableDatabase().readDatastreams();
    }
    if (listDatastream != null && !listDatastream.isEmpty()) {
        drawGraphVolt();
    }

    return view;
}

public void drawGraphVolt () {
    // Setting up and drawing volt graph
    GraphView graph = (GraphView) view.findViewById(R.id.graph);

    mVolt = new LineGraphSeries<>(generateData());
    graph.addSeries(mVolt);

    // styling grid/labels
    graph.getGridLabelRenderer().setGridColor(getResources().getColor(R.color.colorGraphGrid));
    graph.getGridLabelRenderer().setHorizontalLabelsColor(getResources().getColor(R.color.colorGraphText));
    graph.getGridLabelRenderer().setVerticalLabelsColor(getResources().getColor(R.color.colorGraphText));
    graph.getGridLabelRenderer().setTextSize(45);
    graph.getGridLabelRenderer().reloadStyles();

    // styling series
    mVolt.setColor(getResources().getColor(R.color.colorAccent));
    mVolt.setThickness(4);
    //series.setDrawBackground(true);
    //series.setBackgroundColor(getResources().getColor(R.color.gridGraphColor));

    graph.getViewport().setYAxisBoundsManual(true);
    graph.getViewport().setMinY(graph.getViewport().getMinY(false));
    graph.getViewport().setMaxY(graph.getViewport().getMaxY(false));

    graph.getViewport().setXAxisBoundsManual(true);
    graph.getViewport().setMinX(graph.getViewport().getMinX(true));
    graph.getViewport().setMaxX(graph.getViewport().getMaxX(true));

    mVolt.setTitle("Volt");
    graph.getLegendRenderer().setVisible(true);
    graph.getLegendRenderer().setAlign(LegendRenderer.LegendAlign.TOP);
    graph.getLegendRenderer().setTextSize(45);
    graph.getLegendRenderer().setBackgroundColor(getResources().getColor(R.color.colorPrimary));
    graph.getLegendRenderer().setTextColor(getResources().getColor(R.color.colorPrimaryText));
    graph.getLegendRenderer().setPadding(15);
    graph.getLegendRenderer().setMargin(0);

    graph.getViewport().setScrollable(true);
}

private DataPoint[] generateData() {

    DataPoint[] values = new DataPoint[count];
    for (int i = 0; i < count; i++) {
//            if (count != getNumberOfElementsInDatabase()) {
//
//                return values;
//            }

        int x = i;
        int y = Integer.parseInt(listDatastream.get(i).getCurrent_value());
        DataPoint v = new DataPoint(x, y);
        values[i] = v
    }
    return values;
}

@Override
public void onPause() {
    super.onPause();
}

@Override
public void onResume() {
    super.onResume();
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putParcelableArrayList(STATE_DATASTREAM2, listDatastream);
}

public int getNumberOfElementsInDatabase() {
    int countListDatastream = MyApplication.getWritableDatabase().getTotalNumberOfElements();
    return countListDatastream;
}

}
My Database:
package com.thesis.dell.MaterialTest2.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;

import com.thesis.dell.MaterialTest2.pojo.Datastream;
import com.thesis.dell.MaterialTest2.log.L;

import java.util.ArrayList;
import java.util.Date;

public class MyDatabase {

private MyHelper mHelper;
private SQLiteDatabase mDatabase;

public MyDatabase(Context context) {
    mHelper = new MyHelper(context);
    mDatabase = mHelper.getWritableDatabase();
    //mDatabase.close();
}

public void insertValues(ArrayList<Datastream> listValues, boolean clearPrevious) {
    if (clearPrevious) {
        deleteData();
    }
    //beginTransaction(null /* transactionStatusCallback */, true); allowed to comment like this?
    //create a sql prepared statement
    String sql = "INSERT INTO " + MyHelper.TABLE_NAME + " VALUES (?,?,?);";
    //compile the statement and start a transaction
    SQLiteStatement statement = mDatabase.compileStatement(sql);
    mDatabase.beginTransaction();
    for (int i = 0; i < listValues.size(); i++) {
        Datastream currentData = listValues.get(i);
        statement.clearBindings();
        //for a given column index, simply bind the data to be put inside that index
        statement.bindString(2, currentData.getCurrent_value());
        statement.bindLong(3, currentData.getCurrent_valueAt() == null ? -1 : currentData.getCurrent_valueAt().getTime());
        L.m("Inserting entry " +i);
        statement.execute();
    }
    //set the transaction as successful and end the transaction
    mDatabase.setTransactionSuccessful();
    mDatabase.endTransaction();
}

public int getTotalNumberOfElements() {

    int numberOfElements = -1;
    //get a list of columns to be retrieved, we need all of them
    String[] columns = {MyHelper.COLUMN_VALUE, MyHelper.COLUMN_DATE_AT};
    //make a simple query with dbname, columns and all other params as null
    Cursor cursor = mDatabase.query(MyHelper.TABLE_NAME, columns, null, null, null, null, null);
    if (cursor != null && cursor.moveToFirst()) {
        numberOfElements = cursor.getCount();
        return numberOfElements;
    }
    return numberOfElements;
}
public ArrayList<Datastream> readDatastreams()
{
    //init an empty array list
    ArrayList<Datastream> listDatastream = new ArrayList<>();

    //get a list of columns to be retrieved, we need all of them
    String[] columns = {MyHelper.COLUMN_VALUE, MyHelper.COLUMN_DATE_AT};
    //make a simple query with dbname, columns and all other params as null
    Cursor cursor = mDatabase.query(MyHelper.TABLE_NAME, columns, null, null, null, null, null);
    if (cursor != null && cursor.moveToFirst()) {
        do {
            //create a new Datastream object and retrieve the data from the cursor to be stored in this Datastream object
            Datastream datastream = new Datastream();
            //each step is a 2 part process, find the index of the column first, find the data of that column using
            //that index and finally set our blank Datastream object to contain our data
            datastream.setCurrent_value(cursor.getString(cursor.getColumnIndex(MyHelper.COLUMN_VALUE)));
            long valueAtMilliseconds = cursor.getLong(cursor.getColumnIndex(MyHelper.COLUMN_DATE_AT));
            datastream.setCurrent_valueAt(valueAtMilliseconds != -1 ? new Date(valueAtMilliseconds) : null);
            //add the datastream to the list of datastream objects which we plan to return
            listDatastream.add(datastream);
        }
        while (cursor.moveToNext());
    }
    return listDatastream;
}

//delete all rows from our table
public void deleteData() {
    mDatabase.delete(MyHelper.TABLE_NAME, null, null);
}

public long insertData(String value, String valueDate) {
    SQLiteDatabase db = mHelper.getWritableDatabase();
    ContentValues cv = new ContentValues();
    cv.put(MyHelper.COLUMN_VALUE, value);
    cv.put(MyHelper.COLUMN_DATE_AT, valueDate);
    //ID indicates the row id that was inserted if successfull
    long id = db.insert(MyHelper.TABLE_NAME, null, cv);
    return id;
}

public String getColumnValueLast() {
    SQLiteDatabase db = mHelper.getWritableDatabase();
    String[] columns = {MyHelper.COLUMN_VALUE};
    Cursor cursor = db.query(MyHelper.TABLE_NAME, columns, null, null, null, null, null );

    String lastValue = "-1";
    if (cursor.moveToLast()) {
        int index1 = cursor.getColumnIndex(MyHelper.COLUMN_VALUE);
        String value = cursor.getString(index1);
        lastValue = value;
    }
    return lastValue;
}

static class MyHelper extends SQLiteOpenHelper {

    private static final String DB_NAME = "MyDB";
    private static final String TABLE_NAME = "TableValue";
    private static final int DB_VERSION = 2;
    private static final String COLUMN_UID = "_id";
    private static final String COLUMN_VALUE = "current_value";
    private static final String COLUMN_DATE_AT = "at";
    private static final String CREATE_TABLE = "CREATE TABLE "
            + TABLE_NAME
            + " ("
            + COLUMN_UID
            + " INTEGER PRIMARY KEY AUTOINCREMENT, "
            + COLUMN_VALUE
            + " VARCHAR(100), "
            + COLUMN_DATE_AT
            + " VARCHAR(100));";
    private static final String DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;
    private Context context; //mContext;

    public MyHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
        // or mContext = context
        this.context = context;
        L.t(context, "constructor called");
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        try {
            db.execSQL(CREATE_TABLE);
            L.t(context, "onCreate called");
        } catch (SQLException e) {
            L.t(context, "" + e);
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        try {
            L.t(context, "onUpgrade called");
            db.execSQL(DROP_TABLE);
            onCreate(db);
        } catch (SQLException e) {
            L.t(context, "" + e);
        }
    }
}

}


text:
Q: Local Apache Server - Refusing to connect after trying to install PHP5.6 through bash script My local apache server was working fine on PHP 7.1, however I was trying to install PHP 5.6 due to a current projecting using deprecated functions.
I ran the following command to try install PHP 5.6

curl -s https://php-osx.liip.ch/install.sh | bash -s 5.6

After extracting the PHP files, the following ran:
Executing post-install script /tmp/5.6-10.10-frontenddev-post-install
Create symlink /usr/local/php5/entropy-php.conf
/etc/apache2/other/+php-osx.conf
Restarting Apache
AH00112: Warning: DocumentRoot [/usr/docs/dummy-host.example.com] does
not exist
AH00112: Warning: DocumentRoot [/usr/docs/dummy-host2.example.com]
does not exist
AH00558: httpd: Could not reliably determine the server's fully
qualified domain name, using 192.168.1.126. Set the 'ServerName'
directive globally to suppress this message
Syntax OK
Finished.

Not really to sure whats going on, but my local vhosts are all refusing to connect after running the command.
Apache Error Log
AH00112: Warning: DocumentRoot [/usr/docs/dummy-host.example.com] does
not exist
AH00112: Warning: DocumentRoot [/usr/docs/dummy-host2.example.com] does
not exist
AH00558: httpd: Could not reliably determine the server's fully
qualified
domain name, using 192.168.1.126. Set the 'ServerName' directive
globally
to suppress this message
[Fri Feb 22 11:49:47.580441 2019] [mpm_prefork:notice] [pid 12019]
AH00163: Apache/2.4.33 (Unix) PHP/7.1.16 configured -- resuming normal
operations
[Fri Feb 22 11:49:47.580524 2019] [core:notice] [pid 12019] AH00094:
Command line: '/usr/sbin/httpd -D FOREGROUND'
[Fri Feb 22 12:00:14.719520 2019] [mpm_prefork:notice] [pid 12019]
AH00169: caught SIGTERM, shutting down

Can anyone please help me get my apache local server up and running again. I ideally need it so I can switch between PHP5.6 + PHP7.
Thanks
UPDATE:

/etc/apache2.other/+php-osx.conf

#
# Additional PHP Apache directives,
# part of the entropy.ch PHP package for Mac OS X
#
# For more information, go to http://www.entropy.ch/software/macosx/php/
#

LoadModule php5_module        /usr/local/php5/libphp5.so

<IfModule mod_php5.c>

    AddType application/x-httpd-php .php
    AddType application/x-httpd-php-source .phps

    <IfModule mod_dir.c>
        DirectoryIndex index.html index.php
    </IfModule>

</IfModule>

Commenting out the line to loadmodule brings my apache back :) Guess it was because it was loading PHP7 from httpd.conf. Although commenting out PHP 7 in httpd.conf and enabling PHP 5 still runs PHP7?


text:
Q: Consider the solution set S of the linear equation $x_1 + 2x_2 + x_3 = 1$ in $\Bbb R^3$ . Calculate the distance of the point (1, 1, 1) from S. Question: Consider the solution set $S$ of the linear equation $x_1 + 2x_2 + x_3 = 1$ in $\Bbb R^3$. Calculate the distance of the point $(1, 1, 1)$ from $S$.
I thought at first that you can make a matrix of the linear equation of set $S$ and then calculate the outcomes of $x_1, x_2$ and $x_3$. When this is done you can calculate the distance between the two points with the square root of the sum of the squares of the differences between corresponding coordinates.

A: It's just how to calculate the distance from a point to an hyperplane: https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_plane
In your case: let $\underline{x}=(x,y,z)=(1, 1, 1)$ and $S: ax_1+bx_2+cx_3=d$. Now $$d(x,S)=\frac{|ax+by+cz-d|}{\sqrt{a^2+b^2+c^2}}=\frac{|1*1+2*1+1*1-1|}{\sqrt{1^2+2^2+1^2}}=\frac{3}{\sqrt{6}}=\frac{\sqrt{6}}{2}$$

A: Here is an easy way to obtain the general formula for the distance of a point $M_0=(x_0,y_0,z_0)$ to the plane $\Pi$ with equation $\;ax+by+cz=d$:
Remember the vector $\vec n=(a,b,c)$ is normal to the plane $\Pi$. If $H$ is the orthogonal projection of $M_0$ onto $\Pi$, we'll use the parametric  equation of the perpendicular line  to $\Pi$, $(M_0H)$: it is (in vector notation):
$$M=M_0+t\,\vec n.$$
The value of $t$ for $H$ is characterised  by the fact that $H$ satisfies the vector equation of $\Pi$:
$$\vec n\cdot \overrightarrow{OH}=\vec n\cdot \overrightarrow{OM}_0+ t \,\vec n\cdot\vec n=ax_0+by_0+cz_0+t\|\vec n\|^2=d,$$
so that $\;t=\dfrac{d-ax_0-by_0-cz_0}{\|\vec n\|^2}.$
Now the sought distance is $\;\|\overrightarrow{M_0H}\|=\|t\,\vec n\|=|t|\|n\|$, and eventually
$$d(M_0,\Pi)=\frac{|d-ax_0-by_0-cz_0|}{\|\vec n\|^2}\,\|\vec n\|=\frac{|ax_0+by_0+cz_0-d|}{\|\vec n\|}. $$


text: Q: How to determine which drive Windows booted from? Is there an easy way of programmatically determining which drive the currently running Windows instance booted from? I am using Delphi, but any answer in just about any language/programming environment would be helpful.


text:
Q: Receiving "SQLSTATE[HY000] [2002] Connection refused error" in Laravel Project I am working on my Mac and i am trying to connect to database as shown in the env file i have mention the db name but i still getting this error on my laravel project. i have tried it on core php project it work but i get this error while connecting laravel project to database.

SQLSTATE[HY000] [2002] Connection refused (SQL: select * from information_schema.tables where table_schema = cart and table_name = migrations and table_type = 'BASE TABLE') at vendor/laravel/framework/src/Illuminate/Database/Connection.php:671

667|         // If an exception occurs when attempting to run a query, we'll format the error
668|         // message to include the bindings with SQL, which will make this exception a
669|         // lot more helpful to the developer instead of just the database's errors.
670|         catch (Exception $e) {
671|             throw new QueryException(
672|                 $query, $this->prepareBindings($bindings), $e
673|             );
674|         }
675|

A: try this
php artisan config:clear

and then
php artisan migrate

that if you are sure the database already exists


text:
Q: why are single quotes not visible I am making a array from values from databse in PHP then storing it into javascript array. When I alert the array the single quotes are not visible, although when PHP is seen it shows the quotes around values. What's wrong in my code? It should be ['1','2','3','4'] but it shows [1,2,3,4].
<script>
    var values = [
        <?php
            $conn = mysql_connect("localhost","root","") or die ("we couldn't connect!");
            mysql_select_db("test_value");
            $rs = mysql_query("SELECT * FROM test") or die(mysql_error());
            while($row = mysql_fetch_array($rs))
            {
                echo "'".$row['var1']."',";
            }
        ?>
    ];
    window.alert(values);
</script>

A:

<script>
    var values=[
    <?php
    $conn =mysql_connect("localhost","root","") or die ("we couldn't connect!");
    mysql_select_db("test_value");
    $rs = mysql_query("SELECT * FROM test") or die(mysql_error());
    while($row = mysql_fetch_array($rs)){
            echo "\'".$row['var1']."\',";
    }?>
   ];
    window.alert(values);
    </script>

Use this , this may help you


text:
Q: Replace bracket (][) by ',' in Node JS I'm using Node JS and a library replace-in-file
I'm using some functions into a file (functions.js)
And using another file for call function (index.js)
When I launch the script first time it works but then I relaunch the script and the '][' is not replace by ','
Function.js
var priority = "";
var expectedValue = "";
var score1 = "";
var score2 = "";

/* some function*/

function generateJSON(key){
    var table = []

    table.push({"executionDate":date,
    "issueID":key,
    "priority":{
        "jira": priority,
        "computed":score1
    },
    "expectedValue":{
        "jira": expected,
        "computed":score2
    }
})

var json = JSON.stringify(table,null, 2);

fs.appendFile('templateLog1.json', json, 'utf8', function (err) {
    if (err) console.error(err)

});

}

function replaceCaracter(){
    const options = {
        files: 'templateLog1.json',
        from: '][',
        to: ',',
    };

    replace(options, (error, results) => {
        if (error) {
        return console.error('Error occurred:', error);
        }
        console.log('Replacement results:', results);
    });
}

Index.js
setTimeout(function() {
    functions.getAllIssueForSCII().then(function(json){
        for (let i=0; i<json.issues.length;i++){
            functions.generateJSON(json.issues[i].key);
            functions.replaceCaracter()
        }

    });
}, 1000)

Actual result :
[
{
    "executionDate": 1556197884153,
    "issueID": "SCII-10",
    "priority": {
    "jira": "Lowest",
    "computed": -25
    },
    "expectedValue": {
    "jira": "Low",
    "computed": -10
    }
}
,
{
    "executionDate": 1556197884153,
    "issueID": "SCII-7",
    "priority": {
    "jira": "Low",
    "computed": -10
    },
    "expectedValue": {
    "jira": "Low",
    "computed": -10
    }
}
][
{
    "executionDate": 1556197896877,
    "issueID": "SCII-10",
    "priority": {
    "jira": "Lowest",
    "computed": -25
    },
    "expectedValue": {
    "jira": "Low",
    "computed": -10
    }
}
][
{
    "executionDate": 1556197896877,
    "issueID": "SCII-7",
    "priority": {
    "jira": "Low",
    "computed": -10
    },
    "expectedValue": {
    "jira": "Low",
    "computed": -10
    }
}
]

Expected result:
[
{
    "executionDate": 1556197884153,
    "issueID": "SCII-10",
    "priority": {
    "jira": "Lowest",
    "computed": -25
    },
    "expectedValue": {
    "jira": "Low",
    "computed": -10
    }
}
,
{
    "executionDate": 1556197884153,
    "issueID": "SCII-7",
    "priority": {
    "jira": "Low",
    "computed": -10
    },
    "expectedValue": {
    "jira": "Low",
    "computed": -10
    }
}
,
{
    "executionDate": 1556197896877,
    "issueID": "SCII-10",
    "priority": {
    "jira": "Lowest",
    "computed": -25
    },
    "expectedValue": {
    "jira": "Low",
    "computed": -10
    }
}
,
{
    "executionDate": 1556197896877,
    "issueID": "SCII-7",
    "priority": {
    "jira": "Low",
    "computed": -10
    },
    "expectedValue": {
    "jira": "Low",
    "computed": -10
    }
}
]

A: This is a common mistake. As you can see, the first occurence of ][ has indeed been replaced.
This usually happens when you use the String.replace() methos with a simple string as the first parameter (the string to replace).
What you need to do is use a regex with the global flag. Try changing '][' to /]\[/g in the options object.
More details on the String.replace method : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace


text:
Q: Remove part of url, but keep extension All of my websites are generated in the following pattern:
http://www.example.com/category/xyz/article---12345.html

I want to use mod_rewrite to remove the part "---12345", where the three minuses are always there, but the amount of numbers varies from 3 to 7.
The html shoul stay there so that the urls look like that:
http://www.example.com/category/xyz/article.html

How can I achieve that?

A: The following rule assumes that the html file you are requesting doesn't exist and will redirect them to the new html file name. It will do this for any .html file and not just those called "article".
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} \.html$
RewriteCond %{REQUEST_URI} ---
RewriteRule ^(.*)---(.*)$ "/$1.html" [R=301]

Things to note:
If the original .html file exists remove the first two RewriteCond rules.
If you don't want the address bar to change then replace [R=301] with [L]

A: File: .htaccess
RewriteEngine On
RewriteRule ^xyz/article---([0-9]{3,7}).html /xyz/article.html

Problem: you have to have one .htaccess in every folder where the article---xxxxxx.html is


text:
Q: unable to pair my 2014 Muse headband to my 2015 macbook pro On macOS 10.13.6, when I select to bluetooth pair my Muse 2014 headband, I see this ...

Notice that the device is showing up but the "connect" button does not appear next to it. I am uncertain what this means.

A: This means that your Mac has remembered you connecting to it before but it is currently not in range. Try restarting the device or bringing it closer.
The Bluetooth is working as connect appears on the other device.

A: The solution offered by @Allan works.
I simply click on the X that appears beside the device when I hover the pointer over it.
Then when I hold the button in on the headband to put it into search mode, I am able to make a bluetooth connection on the mac.
Be aware, however, that with the 2014 Muse headband the bluetooth connection will disconnect after a few seconds unless you are actively pulling data from the device with a tool like muse-io. This is, apparently, the intended behavior.
It is my understanding that 2016 Muse headband behaves differently. It uses bluetooth low energy and muse-io does not work with it.


text:
Q: Changing a variable inside a function the next time I call it? I am making a chess game. I reached a point where I need to change 4 variables inside a function so the next time I run the function, the variables will be different. Below I have the code necessary to look at:
The function piecesRotation will rotate the position of all the pieces upside down so the other player will play.
Javascript:
function piecesRotation(){
    //rotate the pieces
}

function check(el){

    //there variables indicate which user turn is it
    var FirstCurrentPlayersPiece = "B";
    var CurrentPlayersPieceColor = "black";
    var FirstOpponentsPieceLetter = "W";
    var OpponentsPieceColor = "white";
    //If player played then run the function below to change the position of the pieces and change the 4 variables so the other player will play
    piecesRotation();
    FirstCurrentPlayersPiece = "W";
    CurrentPlayersPieceColor = "white";
    FirstOpponentsPieceLetter = "B";
    OpponentsPieceColor = "black";
}

On HTML I call the function check(el) where el is the elepemt which the player clicked on.
To illustrate, I need somehow to change these variables:
var FirstCurrentPlayersPiece = "B";
var CurrentPlayersPieceColor = "black";
var FirstOpponentsPieceLetter = "W";
var OpponentsPieceColor = "white";

To this:
var FirstCurrentPlayersPiece = "W";
var CurrentPlayersPieceColor = "white";
var FirstOpponentsPieceLetter = "B";
var OpponentsPieceColor = "black";

And the change of these variables will happen each time the player plays. Is there a way to do it?
IMPORTANT
English isn't my first language, that's why I am bad at it.
NOTE1
The reason I am not providing the whole code is because it's HUGE and Stack overflow doesn't let me paste it.
NOTE2
I am stupid. I had to use global variables (as I think that they are bad practice, it's the only solution.

A: Just place the variables in an object and pass them to the function
var boardState = {
        FirstCurrentPlayersPiece : "B",
        CurrentPlayersPieceColor : "black",
        FirstOpponentsPieceLetter: "W",
        OpponentsPieceColor: "white"
}

function piecesRotation(){
    boardState =  {
            FirstCurrentPlayersPiece : boardState.FirstOpponentsPieceLetter,
            CurrentPlayersPieceColor : boardState.OpponentsPieceColor,
            FirstOpponentsPieceLetter: boardState.FirstCurrentPlayersPiece,
            OpponentsPieceColor: boardState.CurrentPlayersPieceColor
    }
}

function check(el){
    piecesRotation();
}


text:
Q: antd column chart: label value is displayed outside of chart I have a fairly simple ant column chart, this is it:
import React from "react";
import ReactDOM from "react-dom";
import { Column } from "@ant-design/plots";

const DemoColumn = () => {
const data = [
{
  type: "Value 1",
  value: 315801
},
{
  type: "Value 2",
  value: 222095
},
{
  type: "Value 3",
  value: 10800
}
];

const config = {
data,
loading: data.length === 0,
xField: "type",
yField: "value",
seriesField: "type",
  yAxis: {
    label: {
      formatter: (v) => v
    }
  },
  xAxis: false,
  height: 200,
  autoFit: false,
  legend: {
    position: "bottom",
    flipPage: false
  },
  interactions: [
    {
      type: "element-active"
    }
  ],
  label: {
     position: "top",
     offsetY: 8,
     formatter: ({ value }) => value
   }
 };
 return <Column {...config} />;
};

ReactDOM.render(<DemoColumn />, document.getElementById("container"));

The problem is, that the number of Value 1 is hanging off the chart. I tried setting the padding but this did not help, it acutally screwed the whole chart up?!?

Here is also a fiddle: https://codesandbox.io/s/cool-microservice-gbrbm9?file=/index.js:0-929

A: Fixed it myself by adding
appendPadding: 10

A: There is an Open Bug in AntD GitHub [BUG] Label of column charts are being cut out if label position is set to 'top' officials for this issue. Some member of ant design team has given an answer as set limitInPlot: true in config. I tried that but didn't work.
I tried with adjusting height prop and offsetY in lable prop inside config. This is just tricky option for you to achieve what you want.
Option 1 -
label: {
  position: "top",
  offsetY: 15, // change offset to this then value will not crop as before but just overlap with chart.
  formatter: ({ value }) => value
}

Option 2 -
xAxis: false,
height: 750, // increase the chart height and it will show the value with a gap. But this will create a scroll.
autoFit: false,

Option 3 -
You can use mix of above two options with adjusting right values. This will get what you want without a scroll. below values got this result.
xAxis: false,
height: 500, // adjust height
autoFit: false,
legend: {
  position: "bottom",
  flipPage: false
},
interactions: [
  {
    type: "element-active"
  }
],
label: {
  position: "top",
  offsetY: 12, // adjust offset
  formatter: ({ value }) => value
}

This is the sandboxcode.
Hope this will help to overcome your issue.


text:
Q: How to implement ' Call me ' function in Firebase Phone Authentication? I'm using Firebase Phone number authentication for authenticate my users. (Android)
Everything is fine, but I don't know how to call the User's phone for the verification Code instead of sending a SMS message. Sometimes SMS never reaches the device.  So 'Call Me' button helps there.
So how to implement that feature in Firebase?

A: As far as I know it works only with text messages.

A: Right now Firebase Auth doesn't have the call me feature. Maybe you can try
CheckMobi, which has the feature you are asking for.
https://www.checkmobi.com/#/SmsProduct


text:
Q: Improvments for this scipt to restart each running systemd service? I have Centos 7+ systems, and they all use systemd. Sometimes the best way to proceed after an important system change is to restart each currently running service. If I restart each service one-at-a-time, then the system generally stays online, and it is very easy to see service problems as they appear.
So I hacked out this little bash script, which restarts each running systemd service, EXCEPT certain named services which I think are core to keeping the box online.
#!/bin/bash
set -e
set -u
running=$(systemctl list-units --type service | grep running \
    | grep -iv audit \
    | grep -iv disk \
    | grep -iv drive \
    | grep -iv getty \
    | grep -iv irq \
    | grep -iv libstoragemgt \
    | grep -iv lvm \
    | grep -iv multipath \
    | grep -iv polkit \
    | grep -iv storage \
    | cut -d' ' -f1)

for service in $running ; do
    echo "$service"
    systemctl restart "$service"
done

There are several things I wish were better:

*

*Grepping for "running" is a crude way to filter for running tasks, and the multiple pipes are pretty expensive.

*Using cut is really brittle, and breaks when the output format
of systemd changes.

*systemctl restart does not set a return code on start failure, so the script keeps going even if a service fails to stop or start.

What may be some better ways to to this?

A:
What may be some better ways to do this?

Reboot the server :)
Restarting all services is rarely a good idea. Either you are updating the whole system and then you want to make sure you that everything uses the latest patched libraries. Or you are updating / reconfiguring just one service and then a simple systemctl reload whatever.service should be enough, no need to restart all running services.
Besides it's a good idea to reboot the server from time to time to ensure that it actually is rebootable. I have seen servers with years of uptime that no one dares to reboot because no one knows if they will actually come back up, what changes have been made and not saved, etc.
If it is a critical system it is surely in some High-Availability cluster and rebooting one node won't matter. If it is not a critical system you can reboot it, even if after business hours or over the weekend.
So to answer your question - reboot the server

A: To improve your code you can do the following:

*

*use systemctl's --state running instead of grep running to filter the services you nees.

*use grep -v -f exclude-services.list instead of a chain of grep's

*use systemctl try-restart s1 s2 s3 ... all at once instead of looping through the list.

First list the services to be excluded in exclude-services.list:
potom@vm /tmp $ cat exclude-services.list
audit.service
disk.service
drive.service
getty.service
irq.service
libstoragemgt.service
lvm.service
multipath.service
polkit.service
storage.service

Then this script should work:
potom@vm /tmp $ cat restart-all.sh
RESTART_SERVICES=$(systemctl list-units --type service --state running | \
    awk '$1 ~ /\.service/{print $1}' | \
    grep -v -f exclude-services.list )

systemctl try-restart ${RESTART_SERVICES}

That may be a little more robust than your script. Let me know how it goes.


text:
Q: Why might weird characters ($p) appear at beginning of every file in vim? Every file I open in vim lately, even new empty files, as a ($p) at the beginning. This does not appear to be real - inserting text overwrites it, and once it's overwritten it does not return.
I have no idea what might be doing this, or how to fix it.

A: Fixed: I resolved this issue on OSX 10.13.4 by updating to iTerm2 3.1.5
vim github issue #2008 reveals it's your terminal emulator not supporting certain DCS (Device Control Strings)
https://github.com/vim/vim/issues/2008
Works for me with version combination:
VIM version 8.0.1283
iTerm2 3.1.15
OSX 10.13.4


text:
Q: need to query work items related to release in TFS We have recently started using TFS for deploying release tickets, i was trying to check to see the number of workitems related to each release# but there is no easy way of finding it, any suggestions?

A: Assuming you are using the vNext build, you can use the REST API to get the number of workitems related to each release.
GET http://SERVER:8080/tfs/DefaultCollection/{project}/_apis/release/releases/{releaseId}/workitems

You can use below PowerShell script to achieve that:

#Get the work items associated to Release

$collectionurl = "http://server:8080/tfs/Collection"
$project = "ProjectName"

$ErrorActionPreference = 'SilentlyContinue'

#Get releases
$baseReleasesUrl = "$collectionurl/$project/_apis/release/releases"
$Releases = Invoke-RestMethod -Uri $baseReleasesUrl -Method Get -UseDefaultCredential

#Get the associated work items.
foreach ($release in $Releases.value)
{
$releaseID = $release.id
$baseUrl = "$collectionurl/$project/_apis/release/releases/$releaseID/workitems"
$response = Invoke-RestMethod -Uri $baseUrl -Method Get -UseDefaultCredential
$wits = $response.value

Write-Host "Release name:" $release.name
Write-Host "Release ID  :" $release.id
Write-Host "Count of Asssociated Work items:"$response.count

      foreach ($wit in $wits)
    {
      Write-Host "Work item ID:" $wit.id
    }
    write-host

}


text:
Q: Filter already output mysql data in HTML table I have my MySQL data output into a HTML table successfully and exactly how I want it. Now I'd like to filter this data based on multiple dropdown values and a submit button. I've looked around in tutorials and other questions but can't find what I'm looking for. Here's how I output:
$fetchResult = "SELECT a.MembershipID, a.FirstName, a.Surname, t.RaceID, r.RaceName, t.Time, r.RaceID, r.ClubYear
                            FROM Athlete AS a
                            INNER JOIN Time AS t
                                ON a.MembershipID=t.MembershipID
                            INNER JOIN Race AS r
                                ON t.RaceID=r.RaceID
                            ORDER BY a.Surname";
            $result = $mysqli->query($fetchResult);

            //Start table
            echo "
";
            echo "

                    First Name
                    Surname
                    Race
                    Time
                    Club Year	";

            // Loop through database
            while ($row = mysqli_fetch_array($result)) {
                echo '
';
                echo '' . $row['FirstName'] . '	';
                echo '' . $row['Surname'] . '	';
                echo '' . $row['RaceName'] . '	';
                echo '' . $row['Time'] . '	';
                echo '' . $row['ClubYear'] . '	';
            }

            echo "

";

Now I have 4 dropdowns also populated by data from the database. What I'd like to happen is, the user picks an option between 1 and 4 dropdowns and the data in the HTML gets filtered but I can't get this to work. Here is what I have so far:
if (!empty($clubYear)) {
    $fetchResult = "SELECT a.MembershipID, a.FirstName, a.Surname, t.RaceID, r.RaceName, t.Time, r.RaceID, r.ClubYear
                            FROM Athlete AS a
                            INNER JOIN Time AS t
                                ON a.MembershipID=t.MembershipID
                            INNER JOIN Race AS r
                                ON t.RaceID=r.RaceID
                            WHERE r.ClubYear='$clubYear'
                            ORDER BY a.Surname";
    }
    $result = $mysqli->query($fetchResult);

So I check to see if the dropdown is empty, if not, apply a query with a WHERE filter. This just makes the page refresh and go to a "no data received" page. Where am I going wrong? The filter should be applied based on what's been selected in the dropdown but without explicitly stating what that dropdown equals i.e= if $clubYear == "whatever", then WHERE r.ClubYear="whatever" - I'd like to just filter through passing the variable.
Thanks.


text:
Q: How to automate CentOS7 minimal kickstart installation using OEMDRV volume? I'm trying to automate the installation process of CentOS7 minimal in VirtualBox. Kickstart file is the solution. I find putting ks.cfg file into OEMDRV.vhdm disk and mounting it to VM memory the easiest way to give the VM access to the configuration file.
Anaconda reads ks.cfg file, as it pointed out mistake in spelling, but once the file is properly written the VM runs an error, same happens if the ks.cfg file is empty:
The I/O cache encountered an error while updating data in medium "ahci-
0-1" (rc=VERR_ACCESS_DENIED). Make sure there is enough free space on the
disk and that the disk is working properly. Operation can be resumed
afterwards.

The host is Windows 10, below is my ks.cfg file. The file is taken of already existing centOS7 minimal VM.
#version=DEVEL
# System authorization information
auth --enableshadow --passalgo=sha512
# Use CDROM installation media
cdrom
# Use cmdline/text/graphical install
graphical
# Run the Setup Agent on first boot
firstboot --enable
ignoredisk --only-use=sda
# Keyboard layouts
keyboard --vckeymap=us --xlayouts='us'
# System language
lang en_US.UTF-8

# Network information
network  --bootproto=dhcp --device=enp0s3 --ipv6=auto --activate
network  --hostname=localhost.localdomain

# Root password #working on --isctrypted rootpw
rootpw --iscrypted $6$6eqrvzKwp2ST4PMi$VUqUy8G/AsbaZK9XbtqlQcSIZjZ7QQk5yFqe5h/91YwM3GI3PjxEASc062EFPgGjvsmMxcLuKvx8d69KLplYJ1
# System services
services --disabled="chronyd"
# System timezone
timezone Europe/Warsaw --isUtc --nontp
# User
user --groups=wheel --name=secutest --password=$6$Ct923BcyZG.13TR2$jEUcu5tlvncoejaWa9eof.5GL1oU3wLVe0zEWLDrpKY6oXJhGeV4CRvoiYfFeC1IpkPeaXc1z912E3HdvOS/t/ --iscrypted --gecos="secutest"
# System bootloader configuration
bootloader --append=" crashkernel=auto" --location=mbr --boot-drive=sda

%packages
@^minimal
@core
kexec-tools

%end

%addon com_redhat_kdump --enable --reserve-mb='auto'

%end

%anaconda
pwpolicy root --minlen=6 --minquality=1 --notstrict --nochanges --notempty
pwpolicy user --minlen=6 --minquality=1 --notstrict --nochanges --emptyok
pwpolicy luks --minlen=6 --minquality=1 --notstrict --nochanges --notempty
%end

reboot

A: The solution is to use OEMDRV.iso, ISO disk type. Next OEMDRV disk has to be mounted to VM's SATA controller.
This command creates OEMDV.iso file with volume labeled 'OEMDRV' out of folder, which is exactly what we need.
$ mkisofs -V OEMDRV -o OEMDRV.iso path/to/directory


text:
Q: Return frequency of words in a column along with Row it is associated with I have a dataset with a text column containing sentences and an ID column. I was able to count the frequency of how many times each word is repeated in the text column using data.text.str.split(expand=True).stack().value_counts().
But my goal is to pull out word frequency, along with the id column to which this word is associated with.
INPUT :

Text
ID

He best work move happy
1

unemployed bad season
1

best way margin
2

frustated unemployed
3

Desired OUTPUT :

Word
frequency
ID

best
2
1

best
2
2

frustrated
1
1

unemployed
2
1

unemployed
2
3

bad
1
1

A: Are you sure you want to duplicate the total frequency in the output? Either way, one of the tables wordids, freqs_df, or output should do be able to help you:
g = df['text'].str.split(expand=True)
g['id'] = df['id']
wordids = g.melt(id_vars=['id']).dropna()[['id', 'value']]
freqs = wordids['value'].value_counts()
freqs_df = pd.DataFrame({'value': freqs.index, 'freq': freqs.values})
output = pd.merge(wordids, freqs_df, on='value')
print(output)

Input:
df = pd.DataFrame({
    'id': [1, 1, 2, 3],
    'text': ['He best work move happy', 'unemployed bad season',
             'best way margin', 'frustated unemployed']
})

Output:
    id       value  freq
0    1          He     1
1    1  unemployed     2
2    3  unemployed     2
3    2        best     2
4    1        best     2
5    3   frustated     1
6    1         bad     1
7    2         way     1
8    1        work     1
9    1      season     1
10   2      margin     1
11   1        move     1
12   1       happy     1


text:
Q: How to print a text next to a line in xaml I have a Line and Textblock in my xaml as follow:
 <Line X1="{Binding StartPoint.X}" Y1="{Binding StartPoint.Y}" X2="{Binding EndPoint.X}"
          Y2="{Binding EndPoint.Y}" Stroke="{Binding Color}" StrokeThickness="{Binding Thickness}" />
 <TextBlock Text="{Binding Title}" />

The TextBlock shows the title of line (for example "Line 1").
The above XAML draw the lines on a canvas and work correctly, but it doesn't show the TextBlock next to line and in parallel to it.
How can I change this XAML code so the text be in the centre of line and parallel to it.

A: I would do that by using a TextBlock and nest inside of it the Line and the TextBlock you want to use. For example:
        <TextBlock Canvas.Left="147" Canvas.Top="132" Height="45">
                <Line X1="10" Y1="20" X2="100" Y2="0" Stroke="Black" StrokeThickness="4"/>
                <TextBlock Text="Line1" VerticalAlignment="Center" HorizontalAlignment="Center"/>
        </TextBlock>

The result of the above will be:

A: I attempted to solve your problem with a different approach
example below will render the line for given coordinates and will place a label next to it
I start by writing a class for LineData
class LineData : DependencyObject
{
    public Point P1
    {
        get { return (Point)GetValue(P1Property); }
        set { SetValue(P1Property, value); }
    }

    // Using a DependencyProperty as the backing store for P1.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty P1Property =
        DependencyProperty.Register("P1", typeof(Point), typeof(LineData), new PropertyMetadata(new Point(), (d, e) => (d as LineData).Update()));

    public Point P2
    {
        get { return (Point)GetValue(P2Property); }
        set { SetValue(P2Property, value); }
    }

    // Using a DependencyProperty as the backing store for P1.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty P2Property =
        DependencyProperty.Register("P2", typeof(Point), typeof(LineData), new PropertyMetadata(new Point(), (d, e) => (d as LineData).Update()));

    public string Label
    {
        get { return (string)GetValue(LabelProperty); }
        set { SetValue(LabelProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Label.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty LabelProperty =
        DependencyProperty.Register("Label", typeof(string), typeof(LineData), new PropertyMetadata(string.Empty));

    public double Length
    {
        get { return (double)GetValue(LengthProperty); }
        set { SetValue(LengthProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Length.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty LengthProperty =
        DependencyProperty.Register("Length", typeof(double), typeof(LineData), new PropertyMetadata(0.0));

    public double TransformAngle
    {
        get { return (double)GetValue(TransformAngleProperty); }
        set { SetValue(TransformAngleProperty, value); }
    }

    // Using a DependencyProperty as the backing store for TransformAngle.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty TransformAngleProperty =
        DependencyProperty.Register("TransformAngle", typeof(double), typeof(LineData), new PropertyMetadata(0.0));

    public void Update()
    {
        //calculate angle
        double dy = P2.Y - P1.Y;
        double dx = P2.X - P1.X;
        double theta = Math.Atan2(dy, dx);
        theta *= 180 / Math.PI;
        TransformAngle = theta - 90;

        //calculate length
        double aSq = Math.Pow(P1.X - P2.X, 2);
        double bSq = Math.Pow(P1.Y - P2.Y, 2);
        Length = Math.Sqrt(aSq + bSq);
    }
}

in this class i wrote logic to convert given point into angle and length which will be used in data template to render accordingly, Update method is called when any point is changed
here comes the xaml, here l: is namespace to the line data class
    <ItemsControl>
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <Canvas/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemContainerStyle>
            <Style TargetType="ContentPresenter">
                <Setter Property="Canvas.Left" Value="{Binding Path=P1.X}" />
                <Setter Property="Canvas.Top" Value="{Binding Path=P1.Y}" />
            </Style>
        </ItemsControl.ItemContainerStyle>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.RenderTransform>
                        <RotateTransform Angle="{Binding TransformAngle}"/>
                    </Grid.RenderTransform>
                    <TextBlock Text="{Binding Label}" VerticalAlignment="Center" Margin="5,0,0,0"/>
                    <Line Y2="{Binding Length}" StrokeThickness="1" Stroke="Black"/>
                </Grid>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
        <l:LineData Label="Line 1" P1="100,100" P2="135,150"/>
        <l:LineData Label="Line 2" P1="150,150" P2="235,50"/>
    </ItemsControl>

*

*i used the canvas as panel of the items control

*placed the item at the correct place by binding canvas.left and canvas.top to point one of the line data in style of ContentPresenter

*created a data template with a grid, label and line

*set the y2 of line as length of line data leaving all other points to be 0

*set the label in textbox

*rotated the grid based on the angle

it's done, result of the sample

since I was not sure what is actually meant by parallel to you I assumed a label which is horizontal when line is vertical (so perpendicular to line)
if you want both horizontally parallel then apply a render transform to your textblock too
        <TextBlock Text="{Binding Label}" VerticalAlignment="Center" Margin="16,0,0,10">
            <TextBlock.RenderTransform>
                <RotateTransform Angle="90"/>
            </TextBlock.RenderTransform>
        </TextBlock>

you may also bind the items control to a observable collection of line data and binding will do the rest.
Alternative horizontally parallel approach
    public void Update()
    {
        double dy = P2.Y - P1.Y;
        double dx = P2.X - P1.X;
        double theta = Math.Atan2(dy, dx);
        theta *= 180 / Math.PI;
        TransformAngle = theta; //remove the 90 degree vertial adjustment

        double aSq = Math.Pow(P1.X - P2.X, 2);
        double bSq = Math.Pow(P1.Y - P2.Y, 2);
        Length = Math.Sqrt(aSq + bSq);
    }

<DataTemplate>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="auto"/>
        </Grid.RowDefinitions>
        <Grid.RenderTransform>
            <RotateTransform Angle="{Binding TransformAngle}"/>
        </Grid.RenderTransform>
        <TextBlock Text="{Binding Label}" HorizontalAlignment="Center" ></TextBlock>
        <Line X2="{Binding Length}" Grid.Row="1" StrokeThickness="1" Stroke="Black"/>
    </Grid>
</DataTemplate>

*

*removed vertical adjustment in calculation

*using Length property for line's X2

*removed margin adjustments from textblock

result is bit cleaner approach without adjustments


text:
Q: How to do searching in NSTableView with NSSearchField? I have implemented a application in which I use NSTableview with the help of its data source and delegates I have not used NSArrayController nor I want to use it. My question is how can I bind NSSearchField with my NSTableView in this situation? I had seen a lot of answer using NSArrayController.
I do not want to convert implementation to NSArrayController as things are working good with NSMutableArray.

A: TableView is a display control and is not for filtering.
You should add 2 NSArray properties;
1) @property(nonatomic, strong) NSArray *allItems;
2) @property(nonatomic, strong) NSArray *filteredItems;
#import "ViewController.h"

@interface ViewController()<NSSearchFieldDelegate, NSTableViewDelegate, NSTableViewDataSource>

// Your NSSearchField
@property (weak) IBOutlet NSSearchField *searchField;

// Your NSTableView
@property (weak) IBOutlet NSTableView *tableView;

// In this array you will store all items
@property(nonatomic, strong) NSArray *allItems;

// In this array you will store only filtered items
@property(nonatomic, strong) NSArray *filteredItems;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.searchField.delegate = self;// You can set delegate from XIB/Storyboard
    self.tableView.delegate = self;// You can set delegate from XIB/Storyboard
    self.tableView.dataSource = self;// You can set dataSource from XIB/Storyboard

    self.allItems = @[@"Test1", @"Demo filter", @"Test 2", @"Abracadabra"];
    [self applyFilterWithString:@""];
}

- (void)controlTextDidChange:(NSNotification *)obj{

    if (obj.object == self.searchField) {
        [self applyFilterWithString:self.searchField.stringValue];
    }
}

-(void)applyFilterWithString:(NSString*)filter {

    if (filter.length>0) {
        NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:@"self CONTAINS[cd] %@", filter];
        self.filteredItems = [self.allItems filteredArrayUsingPredicate:filterPredicate];
    }
    else {
        self.filteredItems = self.allItems.copy;
    }
    [self.tableView reloadData];
}

#pragma mark - ***** NSTableViewDataSource, NSTableViewDelegate *****

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
    return self.filteredItems.count;
}

// for the "Cell Based" TableView
- (nullable id)tableView:(NSTableView *)tableView objectValueForTableColumn:(nullable NSTableColumn *)tableColumn row:(NSInteger)row {

    NSString *item = self.filteredItems[row];
    return item;
}

@end


text:
Q: How to flatten a column containing a list of dates as strings into just date? I have a dataframe containing a column that has a list of dates stored as strings:
# sample dataframe
data = [[1, ["2019-08-02 08:30:56"]], [2, ["2020-08-02 08:30:56"]]]

df = pd.DataFrame(data, columns=["items", "dates"])
df["dates"] = df["dates"].astype(str)
df

  items                  dates
0   1   ['2019-08-02 08:30:56']
1   2   ['2020-08-02 08:30:56']

I would like to do several things:

*

*Convert from a list to a string.

*Convert the string to a date.

*Eliminate the time stamp.

So that the final dataset would look like this:
    items       dates
0   1      2019-08-02
1   2      2020-08-02

I am able to remove the list brackets by doing this:
df["dates_2"] = df["dates"].apply(lambda x: x[1:-1])

But I am wondering if there is a better way to do all of these things in one step?

A: Another solution is to apply ast.literal_eval to convert the column to list. Then .explode() it, convert to datetime and get a date part:
from ast import literal_eval

df["dates"] = df["dates"].apply(literal_eval)
df = df.explode("dates")
df["dates"] = pd.to_datetime(df["dates"]).dt.date

print(df)

Prints:
   items       dates
0      1  2019-08-02
1      2  2020-08-02

A: Example
data = [[1, ["2019-08-02 08:30:56"]], [2, ["2020-08-02 08:30:56"]]]
df = pd.DataFrame(data, columns=["items", "dates"])
df["dates"] = df["dates"].astype(str)

Code
pd.to_datetime(df['dates'].str[2:-2]).dt.normalize()

output
0   2019-08-02
1   2020-08-02
Name: dates, dtype: datetime64[ns] <-- chk dtype

if you want dtype is object not datetime, use following code:
df['dates'].str[2:12]

0    2019-08-02
1    2020-08-02
Name: dates, dtype: object <-- chk dtype

A: This is how I would do it:
df.dates = pd.to_datetime(df.dates.str.slice(1,-1)).dt.date

Output:
   items       dates
0      1  2019-08-02
1      2  2020-08-02

It's important to note that dates contains values of type str, each of which looks like a list when displayed but is not a list (each is a str) after running the following code as shown in the original question:
# sample dataframe
data = [[1, ["2019-08-02 08:30:56"]], [2, ["2020-08-02 08:30:56"]]]

df = pd.DataFrame(data, columns=["items", "dates"])
df["dates"] = df["dates"].astype(str)

Therefore, all we need to do is:

*

*remove the [ and ] characters using df.dates.str.slice(1,-1) to get the substring of type str that looks like a datetime

*use pd.to_datetime() to convert the Series to Timestamps

*use .dt to get at the datetime-like properties of the values in the Series

*use the .date accessor to convert to a numpy array of objects of type datetime.date


text:
Q: How to identify Hyper-V guest IP addresses? Is there a way to find out, using Win2008 R2 Hyper-V manager or a command-line tool, the externally-accessible IP Address(es) of Windows XP Hyper-V guests?
I'd like to be able to connect to my guests by IP address via Remote Desktop (for cases where name resolution is not working properly) but without combing through the DHCP server it's been challenging to know which IP address corresponds to which host.
Any ideas?
Assigning static IPs to each guest is possible but is something I'd like to avoid.

A: look at this link it will do what you want
http://blogs.technet.com/b/m2/archive/2010/07/29/how-to-get-the-ip-address-of-a-virtual-machine-from-hyper-v.aspx

A: Why not just use the Hyper-V Manager to open the VM's Console? It works remotely if you have Remote Management enabled in the Firewall Settings, and you don't have to do any look-ups in the DHCP Server. Otherwise, no, Hyper-V does not track it's VMs IPs, just their MAC addresses.

A: You could use a script to get the information from WMI (from technet):
...determine the IP address of a computer?
Use the Win32_NetworkAdapterConfiguration class and check the value of the IPAddress property. This is returned as an array, so use a For-Each loop to get the value.
strComputer = "."

Set objWMIService = GetObject( _
    "winmgmts:\\" & strComputer & "\root\cimv2")
Set IPConfigSet = objWMIService.ExecQuery _
    ("Select IPAddress from Win32_NetworkAdapterConfiguration ")

For Each IPConfig in IPConfigSet
    If Not IsNull(IPConfig.IPAddress) Then
        For i=LBound(IPConfig.IPAddress) _
            to UBound(IPConfig.IPAddress)
                WScript.Echo IPConfig.IPAddress(i)
        Next
    End If
Next
Sadly that's code for the local machine, and you'd need to tweak it according to this article to connect to the remote WMI.
It might just be easier to have each machine write its IP address to a text file on a network share when it starts up.
Or you could query the DHCP server directly for the information (if it's MS, Can I query DHCP server for getting mapping of MAC to IP address (I have admin rights)? should work)


text:
Q: Keyboard not responding on the BIOS/Windows 7 installation I have been trying to install Windows 7 on my new PC but, at first try, the keyboard wouldnt respond during the installation process. The keyboard and mouse did respond on the BIOS, though.
Following this advice, I first tried unplugging and replugging the keyboard during the install, and failing to improve the situation, I disabled the legacy USB on the BIOS to try it again, but not only did this not solve the problem on the install screen of windows 7, the keyboard and mouse now won't respond on the BIOS either, making it impossible to switch it back.
I have tried every USB port I could but none of them give any different result.
The motherboard is a Gigabyte Z390 Aorus Elite, keyboard is a Rii RK100, mouse is some wireless HP mouse.
Edit : managed to get the keyboard working again by resetting the BIOS, so hopefully this should be easier by now