text:
Q: Dynamic cast unexpectedly returns null for a type, but only sometimes and not for other types I have this dynamic cast, which I would expect to always work:
BaseClass *b = new DerivedClass();
DerivedClass *d = dynamic_cast<DerivedClass *>(b);

Well, of course I'm posting this question because it doesn't always work. Here's the situation:

*

*BaseClass and DerivedClass are both defined in the same framework.

*This framework is used in two different applications.

*For the first application, the dynamic cast works fine (returns b).

*For the second application, the dynamic cast doesn't work (returns null).

*For the second application, RTTI seems to be enabled because dynamic casts for other types work.

So what could be causing the dynamic cast for this one type to fail in one application?

A: Another thing that can happen with GCC is if some of your code is static-linked and some is dynamic-linked. Or if the same class is defined in two different dynamic libraries.
For example, a type SomeClass in the static linked code will produce a SomeClass typeinfo. And the SomeClass in the dynamic linked code will also produce a SomeClass typeinfo.
What I have seen is that most of the code will point to the dynamic SomeClass typeinfo while all of the code in the static-linked block will point to its internal copy of SomeClass typeinfo.
Since GCC determines types for RTTI and exception handling via typeinfo pointers, this means that as far as it is concerned SomeClass and SomeClass are not the same type.
Now, Microsoft with Windows, probably because they deal with a lot more static linked code and old binary libraries that can't be recompiled, decided to do strcmp name comparisons of types which means that their RTTI and exception handling is a lot slower but works in almost all cases.

A: Had this happen to me once.
The problem boiled down to the visibility of C++ symbols in the framework.
Specifically, the symbols were hidden for some reason.
Now, dynamic_cast requires, in the derived class, to point to some type information for the base class, which can't happen if the symbol is not visible.
Bottom line, setting the visibility for the affected classes like that :
class __attribute__((visibility("default"))) SomeClass
{
    /* ... */
};

solved the issue for us


text:
Q: Java: Defining a generic method inside an anonymous class The following java code works fine.
public static void main(String[] arg){
    JPanel p = (new JPanel());
    p.add( new Object(){
        JButton f(JButton x){
            x.setEnabled(false);
            return x;
        }}.f(new JButton("B")) );
    JFrame w = new JFrame("W");
    w.add(p);
    w.pack();
    w.setVisible(true);
}

If the method is changed to its generic form the program fails.
public static void main(String[] arg){
    JPanel p = (new JPanel());
    p.add( new Object(){
        <T> T f(T x){
            x.setEnabled(false);
            return x;
        }}.f(new JButton("B")) );
    JFrame w = new JFrame("W");
    w.add(p);
    w.pack();
    w.setVisible(true);
}

Why does it fail? How can you define generic methods within an anonymous class?
This question is for learning purposes.

A: T's erasure is Object, which does not have setEnabled. It works if you give it a bound of JComponent, which definessetEnabled:
public static void main(String[] arg) {
    JPanel p = (new JPanel());
    p.add( new Object(){
        <T extends JComponent> T f(T x){
            x.setEnabled(false);
            return x;
        }}.f(new JButton("B")) );
    JFrame w = new JFrame("W");
    w.add(p);
    w.pack();
    w.setVisible(true);
}

A: The T generic doesn't derive explicitly from a class or an interface. So it derives from  Objectand Object has no setEnabled() method.
If you want to use generic, you could specify a java.swing base type that has this method. For example : javax.swing.AbstractButton.
public static void main(String[] arg){
    JPanel p = (new JPanel());
    p.add( new Object(){
        <T extends AbstractButton> T f(T x){
            x.setEnabled(false);
            return x;
        }}.f(new JButton("B")) );
    JFrame w = new JFrame("W");
    w.add(p);
    w.pack();
    w.setVisible(true);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Invariant subspaces under the set of all unitary linear transformations Given a finite dimensional vector space $V$ over a field $k$ and a set $S$ of endomorphisms of $V$ (=linear transformations from $V$ to $V$) we say that $V$ is $S$-simple if the only $S$-invariant subspaces of $V$ are $V$ and $\{0\}$.
We know that if $S=End(V)$ is the set of all endomorphisms of $V$, then $V$ is $S$-simple.
My question is if $U\subset End(V)$ is the set of all unitary ($B^*B=BB^*=I$) endomorphisms of $V$, is it true that $V$ is $U$-simple?
What we know about unitary endomorphisms $B\in U$ is that if $W$ is invariant under $B$ then so is $W^\perp$.

A: Since we are talking about linear transformations, it suffices to show what the elements of $U$ do on a basis of $V$.
In particular, pick an orthonormal basis $\{v_1,\dots,v_n\}$. (I suppose we have an inner/Hermitian product, since we are talking about unitary transformations). Now:

Any permutation of $\{v_1,\dots,v_n\}$ extends linearly to a unitary transformation. (Can you see why?)

The crucial word here is "any". This means that if we have a $U$-invariant subspace $W\ne\{0\}$, we can take an orthonormal basis $\{w_1,\dots,w_k\}$ of $W$, and complete it to an orthonormal basis $\{w_1,\dots,w_k,v_{k+1},\dots,v_n\}$ of $V$.
Now permute, for example, $w_1$ and $v_{k+1}$. There will be then a $B\in U$ such that $Bw_1=v_{k+1}$, and so necessarily $v_{k+1}\in W$. We can do this with all the possible combinations, and we conclude that:

$W=V$. (again, can you see why?)

Try yourself following these steps!


text:
Q: R: Vector to matrix - convert one-dimensional vector index to two-dimensional matrix index? Let's say I have a vector:
myVector <- c(1,2,3,4,1,2,3,4,1,2,3,4)

And for some reason index, say, 9 in that vector (having value 1) is important to me:
> myVector[9]
[1] 1

For some another reason, I want to make this vector a matrix with dimensions 6x2 (six rows, two columns).
> myMatrix <- matrix(myVector, nrow = 6, ncol = 2)  # Only either nrow or ncol argument is actually required.
> myMatrix
     [,1] [,2]
[1,]    1    3
[2,]    2    4
[3,]    3    1
[4,]    4    2
[5,]    1    3
[6,]    2    4

Now I would like to know where my vector index 9 is located at in this new matrix. How do I get that information?
Of course, I can see in this case that it is row number 3 and column number 2, but how do I know in general where do the parameters of the transformation (number of rows and columns in the matrix) take my original index?

A: You can use arrayInd():
arrayInd(9, .dim = dim(myMatrix))

     [,1] [,2]
[1,]    3    2

A: The matrix you are creating still incorporates the vector it was build on, so indexing should still work.
myVector <-seq(10,120,10)
myMatrix <- matrix(myVector, nrow = 6, ncol = 2)
# check
myMatrix[3,2]
myVector[9]

# check all positions:
all(myMatrix==myVector)

Addition:
To convert the singular array index to a pair of indices i,j  I  wrote this function,
[maybe there is a more elegant solution to this problem.]
Take the singular index v_i and apply a modulo operation with first dimension i of the matrix M , the edge-case would be that the result is 0, than we use i instead the modulo result.
[This is implemented with the ifelse statement.]
For the second index j , v_i is simply divided by i and round op to the next integer.
# This small functions converts the singular array index to
# a matrix index i,j based on the dimensions of the input matrix
M_ind <- function(v_i,M) {
  i = dim(M)[1]
  i_m = ifelse(v_i%%i,v_i%%i,i)
  return(c(i_m,ceiling(v_i/i)))
}

## test
test<-M_ind(7,myMatrix)
test
myMatrix[test[1],test[2]]

## Another matrix
myVec<-LETTERS[1:24]
myMat<-matrix(myVec,4,6)

myVec[16] # "P"
test<-M_ind(16,myMat)
test
myMat[test[1],test[2]] #"P"

A: After giving myself some time to think this, I figured out that this can be solved with some algebra:
originalIndex <- 9 # this is the index in the original vector
nrows <- 6 # number of rows in the matrix to be created

rowIndex = originalIndex - (ceiling(originalIndex / nrows) - 1) * nrows
columnIndex = ceiling(originalIndex / nrows)

And the print out is as it should:
> rowIndex
[1] 3
> columnIndex
[1] 2


text:
Q: I try to write a cycle instead of recursive function I try to find clusters in array. For example, I have such array:
0 0 0 0 0
0 2 3 0 1
0 8 5 0 7
7 0 0 0 4

After I launched the program, it will print such rezults:
Cluster 1: <2,3,8,5,7>

Cluster 2: <1,7,4>

I've made recursive function to resolve this problem:
void DFS(int x, int y)
{
  printf("%d ", g[x][y]);
  g[x][y] = 0;
  // iterate over neighbours
  for(dx=-1; dx<=1; dx++)
    for(dy=-1; dy<=1; dy++)
      if (g[x+dx][y+dy]) DFS(x+dx, y+dy);
}

for(i=0; i<n; i++)
  for(j=0; j<n; j++)
    if (g[i][j])
    {
      DFS(i, j);
      printf("\n");
    }

But there is the problem: I need to process extra large arrays, so when recursive function calls itself more than ~1000 times, the program finished with an error "Stack overflow".
So I need to remake this code without usage of recursive functions.
I tried to use lists, cicles and so on, but it doesn't work properly.
Can you tell me, how can I do this?
TRY TO EXPLAIN AGAIN:
// random_number_gererator.cpp: определяет точку входа для консольного приложения.
//

#include "stdafx.h"
#include <ctime>
#include <iostream>
#include <fstream>

//Задаем максимально возможный размер стека
#pragma comment(linker, "/STACK:100000000000")

using namespace std;

const int k = 2;                                        //размерность массива
const int N = k * k * k;                                //количество элементов, которые необходимо сгенерировать
int number0 = 0, number1 = 0;

int generation(float probability);                      //прототип функции генерации псевдослучайных чисел
int create_array();                                     //прототип функции создания трехмерного массива

int ***ptrarray = new int **[k];                        //указатель на трехмерный массив

ofstream fout("clusters.txt");

int find_and_write_clusters(int X, int Y, int Z);       //прототип функции поиска кластеров

int main()
{

    setlocale(LC_ALL, "rus");                           //установка русской кодировки
    int err = create_array();                           //вызов функции создания трехмерного массива
                                                        //cout << err<<endl;
    generation(0.3);                                    //функция генерации и заполнения массива
                                                        //После генерации данные заполнились в массив ptrarray[][][]

    for (int X = 0; X < k; X++) {
        for (int Y = 0; Y < k; Y++) {
            for (int Z = 0; Z < k; Z++) {
                if (ptrarray[X][Y][Z] == 1) {
                    find_and_write_clusters(X, Y, Z);   //вызываем рекурсивную функцию поиска и записи кластеров
                    fout << endl;
                    fout << endl;
                }
            }
        }
    }
    fout.close();
    system("pause");
    return 0;
}

int generation(float probability) {
    int prob_persent = ceil(probability * 10000);       //введенная пользователем вероятность, в процентах до 10 000 (для большей точности)
    int T;
    if (probability > 1 || probability < 0) return 1;

    for (int X = 0; X < k; X++) {
        for (int Y = 0; Y < k; Y++) {
            for (int Z = 0; Z < k; Z++) {
                T = 0 + rand() % 10001;
                if (T <= prob_persent) {
                    ptrarray[X][Y][Z] = 1;
                }
                else {
                    ptrarray[X][Y][Z] = 0;
                }
            }
        }
    }
    for (int X = 0; X < k; X++) {
        for (int Y = 0; Y < k; Y++) {
            for (int Z = 0; Z < k; Z++) {
                cout << ptrarray[X][Y][Z];
            }
            cout << endl;
        }
        cout << endl;
    }

    return 0;
}
int create_array() {
    for (int X = 0; X < k; X++) {
        ptrarray[X] = new int *[k];
        for (int Y = 0; Y < k; Y++) {
            ptrarray[X][Y] = new int[k];
        }
    }
    return 0;
}

int find_and_write_clusters(int X, int Y, int Z) {
    if (ptrarray[X][Y][Z] == 1) {
        //Здесь проверить, есть ли такой элемент в файле
        fout << X << ";" << Y << ";" << Z << " ";
        //Заменяем текущий элемент на 0, чтобы он больше не обрабатывался
        ptrarray[X][Y][Z] = 0;
        if (X + 1 < k) find_and_write_clusters(X + 1, Y, Z);
        if (Y + 1 < k) find_and_write_clusters(X, Y + 1, Z);
        if (Z + 1 < k) find_and_write_clusters(X, Y, Z + 1);

        if (X - 1 >= 0) find_and_write_clusters(X - 1, Y, Z);
        if (Y - 1 >= 0) find_and_write_clusters(X, Y - 1, Z);
        if (Z - 1 >= 0) find_and_write_clusters(X, Y, Z - 1);
    }
    return 0;
}

This is full code. In this one, our program generates 3D-array and fill it with "0" and "1" numbers.
After that, program find clustert with usage such algorithm (for example, we made 2*2*2 array:
10
01

11
00

Here we have 2 layers, 8 elements (2*2*2) in total.
How to find clusters:
We scan our array and call the function find_and_write_clusters. If element equal to "1", we call this function in neighbour elements. And so on.
Now, if yoy compile and run this code, you will get file "clusters.txt" with 2 rows. I'll try to paint it for you

A: Well your description So I need to remake this code without usage of recursive functions. I tried to use lists, cicles and so on, but it doesn't work properly. is very vague.
It would be a lot better if you just started the question by having a reduced example (i.e just a fixed array, the random generation really wasn't relevant to the question) of the recursive code and then also included your doesn't work properly try. Then it would be easier for us to help you learn.
Anyway here's a version of the function that's a straight translation of the recursive version to something that stores the data on the heap. You can use another data structure if vector doesn't suite your use-case but I think it might be serviceable until really large.
int find_and_write_clusters(int X, int Y, int Z) {
    struct IState {
        int X, Y, Z, step;
    };
    std::vector<IState> remaining;
    auto insertIfOne = [&remaining](int X, int Y, int Z) {
        if (ptrarray[X][Y][Z] == 1) {
            fout << X << ";" << Y << ";" << Z << " ";
            ptrarray[X][Y][Z] = 0;
            remaining.emplace_back(IState{ X, Y, Z, 0 });
        }
    };
    insertIfOne(X, Y, Z);
    while (!remaining.empty())
    {
        auto& c = remaining.back();//current
        switch (c.step++)
        {
        case 0:
            if (c.X + 1 < k) insertIfOne(c.X + 1, c.Y, c.Z);
            break;
        case 1:
            if (c.Y + 1 < k) insertIfOne(c.X, c.Y + 1, c.Z);
            break;
        case 2:
            if (c.Z + 1 < k) insertIfOne(c.X, c.Y, c.Z + 1);
            break;
        case 3:
            if (c.X - 1 >= 0) insertIfOne(c.X - 1, c.Y, c.Z);
            break;
        case 4:
            if (c.Y - 1 >= 0) insertIfOne(c.X, c.Y - 1, c.Z);
            break;
        case 5:
            if (c.Z - 1 >= 0) insertIfOne(c.X, c.Y, c.Z - 1);
            break;
        default:
            remaining.pop_back();
        }
    }
    return 0;
}

But your approach is very inefficient to start with. You can save a lot of complexity by using a Two-pass approach (although I guess for 3D you'd need to merge connected 2d labels across layers, still cheaper than all the branching and cache missing you're doing now) instead of iterating over the data irregularly for each label like you're doing now.
edit: if the lambda is confusing, the code is equivalent to this version without the lambda
struct IState {
    int X, Y, Z, step;
};

void insertIfOne(std::vector<IState>& stack, int X, int Y, int Z)
{
    if (ptrarray[X][Y][Z] == 1) {
        fout << X << ";" << Y << ";" << Z << " ";
        ptrarray[X][Y][Z] = 0;
        stack.emplace_back(IState{ X, Y, Z, 0 });
    }
}

int find_and_write_clusters(int X, int Y, int Z) {
    std::vector<IState> remaining;
    insertIfOne(remaining, X, Y, Z);
    while (!remaining.empty())
    {
        auto& c = remaining.back();//current
        switch (c.step++)
        {
        case 0:
            if (c.X + 1 < k) insertIfOne(remaining, c.X + 1, c.Y, c.Z);
            break;
        case 1:
            if (c.Y + 1 < k) insertIfOne(remaining, c.X, c.Y + 1, c.Z);
            break;
        case 2:
            if (c.Z + 1 < k) insertIfOne(remaining, c.X, c.Y, c.Z + 1);
            break;
        case 3:
            if (c.X - 1 >= 0) insertIfOne(remaining, c.X - 1, c.Y, c.Z);
            break;
        case 4:
            if (c.Y - 1 >= 0) insertIfOne(remaining, c.X, c.Y - 1, c.Z);
            break;
        case 5:
            if (c.Z - 1 >= 0) insertIfOne(remaining, c.X, c.Y, c.Z - 1);
            break;
        default:
            remaining.pop_back();
        }
    }
    return 0;
}

A: Every recursive construction can be replaced with a stack construction and vice versa. Try replacing your recursive logic with a stack datatype.
This is C#, but this concept applies to all languages: https://haacked.com/archive/2007/03/04/Replacing_Recursion_With_a_Stack.aspx/


text:
Q: Size of Boolean and Number types in Lua? How big these two types of data in Lua 5.3?
As I understand, the size varies depending on the implementation of the language and how configured compliant, and on what system is running.
Would it be faster and less costly to use true and false values for object state on, off instead of 1 and 0?


text:
Q: Prove that the product over a sum is the sum over the cartesian products of the products. Prove this generalization of the distributive law,
$$ \prod_{a \in A} \sum_{b \in B_a} t_{a,b} = \sum_{c \in \prod_{a \in A} B_a}  \prod_{a \in A}t_{a,c_a} $$
where the product of sets $\prod_{a \in A} B_a$ is taken to be a cartesian product.
For example,
$$ A = \{ 1, 2 \} \wedge B_1 = \{ 1, 2 \} \wedge B_2 = \{ 1, 2 \} $$
$$ \prod_{a \in A} \sum_{b \in B_a} t_{a,b} $$
$$ = (t_{1,1}+t_{1,2}) (t_{2,1}+t_{2,2}) $$
$$ = \sum_{c \in \prod_{a \in A} B_a}  \prod_{a \in A}t_{a,c_a} $$
$$ = \sum_{c \in \{(m, n) | m \in B_1 \wedge n \in B_2\}}   t_{1,c_1}t_{2,c_2} $$
$$ = \sum_{c \in \{(1,1),(1,2),(2,1),(2,2)\}} t_{1,c_1}t_{2,c_2} $$
$$ = t_{1,1}t_{2,1}+t_{1,1}t_{2,2}+t_{1,2}t_{2,1}+t_{1,2}t_{2,2} $$

These definitions of the cartesian product are trivial, but useful.
Firstly, N-tuples are concatenated.
$$ (c_1, c_2)+(c_3, c_4) = (c_1, c_2, c_3, c_4) $$
R is a 1 dimensional cartesian product, in,
$$ R = \{(s)|s \in S\}$$
Use $\times$ for the cartesian product. If V and W are cartesian products,
$$ V\times W = \{v+w|v \in V  \wedge w \in W\}$$
If V and W are cartesian products,
$$ V\times W = \{v+w|v \in V  \wedge w \in W\}$$
If R, P, and Q are cartesian products,
$$  R\times P \cup R\times Q = R \times  (P \cup Q)$$

A: For finite sums and products the statement is trivial. So I assume you meant generalizing to infinite sums and products.

You need absolute convergence. In the case of the Euler product for the Riemann zeta function, for $\sigma >1$, since $$\prod_p \frac{1}{1-p^{-\sigma}}=\prod_p (\sum_{k \ge 0} p^{-\sigma k})$$ is a product of series of non-negative terms, you are right it is enough to show that $0 < -\log(1-p^{-\sigma}) < p^{-\sigma}$ to obtain that $-\sum_p \log(1-p^{-\sigma})$ converges absolutely so that $\prod_p \frac{1}{1-p^{-\sigma}}$ converges absolutely, obtaining
$$\prod_p \frac{1}{1-p^{-\sigma}} = \prod_{i \ge 1} (\sum_{k \ge 0} p_i^{-\sigma k}) = \sum_{a \in \mathbb{N}^{\mathbb{N}_{\ge 1}}} \prod_{i\ge 1} p_i^{-\sigma a_i} = \sum_{n =1}^\infty n^{-\sigma}$$
where $\mathbb{N}^{\mathbb{N}_{\ge 1}}$ is the set of sequence of integers.

Now to prove rigorously such statements, it suffices to write infinite products and sums as what they are : limit of finite products and sums. Obtaining
 $$\prod_p \frac{1}{1-p^{-s}} \overset{def}= \lim_{m \to \infty} \prod_{i =1}^m \frac{1}{1-p_i^{-\sigma}}=\lim_{m \to \infty} \prod_{i =1}^m (\sum_{k \ge 0} p_i^{-sk}) \overset{(1)}=\lim_{m \to \infty} \sum_{a\in \mathbb{N}^m}\prod_{i=1}^m p_i^{-\sigma a_i}\\ = \lim_{m \to \infty} \sum_{\text{Lpf}(n) \le p_m} n^{-\sigma} \overset{(2)}= \lim_{N \to \infty}\sum_{n=1}^N n^{-\sigma}$$
where $(1)$ is justified because it is a finite product of series, and $\text{Lpf}(n) $ is the largest prime factor, and changing the order of summation in $(2)$ is justified by absolute convergence.

Obviously the argument is the same in general, but the notations would be cumbersome, so I won't detail it.

A: For simplicity, let $A = \{1 .. n \}$. This reduces the complexity without loss of generality, as if we wanted to use an arbitrary set we could store the actual elements in an n-tuple and index them. So we can think of $1..n$ as representing the actual elements.
Use induction on $n$
For n = 1.
$$ \sum_{b \in B_1} t_{1,b} = \sum_{c \in B_1}  t_{1, c} $$
Which is true, proving the case.
Assume the formula is true for n, prove it for n+1.
$$ (\prod_{a \in \{1..n\}} \sum_{b \in B_a} t_{a,b})(\sum_{b \in B_{n+1}} t_{n+1,b}) = (\sum_{c \in \prod_{a \in \{1..n\}} B_a}  \prod_{a \in \{1..n\}}t_{a,c_a}) (\sum_{b \in B_{n+1}} t_{n+1,b}) $$
We need this result which we will prove below,
$$ (\sum_{c \in \prod_{a \in \{1..n\}} B_a}  \prod_{a \in \{1..n\}}t_{a,c_a}) \sum_{b \in X_{n+1}} t_{n+1,b} = \sum_{c \in (\prod_{a \in \{1..n\}} B_a) \times X_{n+1}}  \prod_{a \in \{1..n+1\}}t_{a,c_a}$$
Which gives,
$$ (\prod_{a \in \{1..n\}} \sum_{b \in B_a} t_{a,b})(\sum_{b \in B_{n+1}} t_{n+1,b}) = \sum_{c \in (\prod_{a \in \{1..n\}} B_a) \times B_{n+1}}  \prod_{a \in \{1..n+1\}}t_{a,c_a}$$
$$  = \sum_{c \in \prod_{a \in \{1..n+1\}} B_a}  \prod_{a \in \{1..n+1\}}t_{a,c_a}$$
Which completes the induction case on $n$, but assuming,
$$ (\sum_{c \in \prod_{a \in \{1..n\}} B_a}  \prod_{a \in \{1..n\}}t_{a,c_a}) \sum_{b \in X_{n+1}} t_{n+1,b} = \sum_{c \in (\prod_{a \in \{1..n\}} B_a) \times X_{n+1}}  \prod_{a \in \{1..n+1\}}t_{a,c_a}$$
To prove this, use induction on the size $X_{n+1}$.
If $X_{n+1}$ has a single element.
$$ (\sum_{c \in \prod_{a \in \{1..n\}} B_a}  \prod_{a \in \{1..n\}}t_{a,c_a}) t_{n+1,k} = \sum_{c \in (\prod_{a \in \{1..n\}} B_a) \times \{k\}}  \prod_{a \in \{1..n+1\}}t_{a,c_a}$$
Which is true, proving the case for size 1.
Now assume it is true for $X_{n+1}$ and $Y_{n+1}$ we will prove it for $Z_{n+1}$. This corresponds to the induction step if the size of $Y_{n+1}$ is 1. So all we are doing is proving a more general case. We do this because $X_{n+1}$ and $Y_{n+1}$  are then symmetrical, and so the proof is easier to understand.
$$ Z_{n+1} = X_{n+1} \cup Y_{n+1} $$
Then
$$ \sum_{b \in Z_{n+1}} t_{n+1,b} = (\sum_{b \in X_{n+1}} t_{n+1,b} + \sum_{b \in Y_{n+1}} t_{n+1,b}) $$
Starting with the left hand side of the assumption,
$$ (\sum_{c \in \prod_{a \in \{1..n\}} B_a}  \prod_{a \in \{1..n\}}t_{a,c_a}) \sum_{b \in Z_{n+1}} t_{n+1,b} $$
Substituting for $Z_{n+1}$
$$ = (\sum_{c \in \prod_{a \in \{1..n\}} B_a}  \prod_{a \in \{1..n\}}t_{a,c_a}) (\sum_{b \in X_{n+1}} t_{n+1,b} + \sum_{b \in Y_{n+1}} t_{n+1,b}) $$
$$ = (\sum_{c \in \prod_{a \in \{1..n\}} B_a}  \prod_{a \in \{1..n\}}t_{a,c_a}) \sum_{b \in X_{n+1}} t_{n+1,b} + (\sum_{c \in \prod_{a \in \{1..n\}} B_a}  \prod_{a \in \{1..n\}}t_{a,c_a}) \sum_{b \in Y_{n+1}} t_{n+1,b}$$
Use the assumption for X and Y
$$= \sum_{c \in (\prod_{a \in \{1..n\}} B_a) \times X_{n+1}}  \prod_{a \in \{1..n+1\}}t_{a,c_a} + \sum_{c \in (\prod_{a \in \{1..n\}} B_a) \times Y_{n+1}}  \prod_{a \in \{1..n+1\}}t_{a,c_a}$$
Merging the sums,
$$= \sum_{c \in ((\prod_{a \in \{1..n\}} B_a) \times X_{n+1} \cup (\prod_{a \in \{1..n\}} B_a)\times Y_{n+1})}  \prod_{a \in \{1..n+1\}}t_{a,c_a}$$
The cartesian product is,
$$(\prod_{a \in \{1..n\}} B_a)\times X_{n+1} \cup (\prod_{a \in \{1..n\}} B_a)\times Y_{n+1}$$
Use $  R\times P \cup R\times Q = R \times  (P \cup Q)$
$$ = (\prod_{a \in \{1..n\}} B_a)\times (X_{n+1} \cup Y_{n+1})$$
Use $ X_{n+1} \cup Y_{n+1} = Z_{n+1} $
$$ = (\prod_{a \in \{1..n\}} B_a)\times Z_{n+1}$$
Substituting back in,
$$\sum_{c \in ((\prod_{a \in \{1..n\}} B_a)\times X_{n+1} \cup (\prod_{a \in \{1..n\}} B_a)\times Y_{n+1})}  \prod_{a \in \{1..n+1\}}t_{a,c_a} = \sum_{c \in (\prod_{a \in \{1..n\}} B_a)\times Z_{n+1}}  \prod_{a \in \{1..n+1\}}t_{a,c_a}$$
Which is the right hand side of the assumption. This completes the induction on size and completes the proof.


text:
Q: Look Thru all my spreadsheets for a sheet with a specific name app script Hi.
I am trying to create a script that will look thru all my Spreadsheets in drive and search for a sheet with a specific name and return the sheets URL / ID and the Spreadsheet Name
This is what I got so far but its really slow and not efficient
As I have about 190 Google Sheets In drive and Each sheet name I'm Looking for has a sheet in about 20 of the 190
I thought that if there is a way to do this by searching drive for the sheet name so it narrows down
from all my google sheets to only the google sheets containing the sheet name value it might make it faster but I'm not sure how to do this and I don't think it will be fast enough for me
Thanks so much for trying to help me out with your professionalism

function getSheetNames(text = "Sheet Name To Search for") {
  var arraywithfoundsheets = [];
  var sp = SpreadsheetApp;
  // Get all Sheets in drive
  var allsheets = DriveApp.getFilesByType(MimeType.GOOGLE_SHEETS);
  //loop thru all spredsheets
  while (allsheets.hasNext()) {
    var spreadsheet = sp
      .open(allsheets.next());

    // return an array with all the sheet names from the spreadsheet
    var allsheetsinspreadsheet = spreadsheet.getSheets()
      .map(su => su.getName())

    // if this spredsheet contains a sheet with the specified name
    if (allsheetsinspreadsheet.indexOf(text) > -1) {

      // add the sheet with the specified name to the array
      arraywithfoundsheets.push([spreadsheet.getUrl()
                                 + '#gid='
                                 + spreadsheet.
      getSheetByName(allsheetsinspreadsheet[allsheetsinspreadsheet.indexOf(text)])
                                    .getSheetId(),spreadsheet.getName()]);
    }
  }
Logger.log(arraywithfoundsheets);
return arraywithfoundsheets;
}

A: Probably this will be a little bit faster (if it will work at all, I haven't tried):
function getSheetNames(text = "Sheet Name To Search for") {
  var arraywithfoundsheets = [];
  var sp = SpreadsheetApp;

  // Get all Sheets in drive
  var allsheets = DriveApp.getFilesByType(MimeType.GOOGLE_SHEETS);

  //loop thru all spredsheets
  while (allsheets.hasNext()) {
    var spreadsheet = sp.open(allsheets.next());
    var sheet = spreadsheet.getByName(text);   // no need to find for the sheet if you have its name
    if (!sheet) continue;                      // skip if there is no sheet with such name

    arraywithfoundsheets.push([
      spreadsheet.getUrl() + '#gid=' + sheet.getSheetId(), // if you have the sheet already you can get its ID directly
      spreadsheet.getName()
    ]);

  }

  Logger.log(arraywithfoundsheets);
  return arraywithfoundsheets;
}

It makes less calls to the server. But actually I see no way to make the script noticeable faster.

A: This does run but it takes a long time to open up each spreadsheet:
function getSheetUrlId(name = 'Sheet4') {
  const ss = SpreadsheetApp.getActive()
  const fit = DriveApp.getFilesByType(MimeType.GOOGLE_SHEETS);
  let shts = [];
  while (fit.hasNext()) {
    let ss = SpreadsheetApp.openById(fit.next().getId());
    if (ss) {
      let sh = ss.getSheetByName(name);
      if (sh) {
        let ssurl = ss.getUrl();
        let shid = sh.getSheetId();
        let url = `${ssurl}#gid=${shid}`
        shts.push({ url: url, id: sh.getSheetId(), name: sh.getName() });
      }
    }
  }
  Logger.log(JSON.stringify(shts));
}

I suspect a solution using the Sheets API may render a quicker solution.  Bit I'm not that interested in finding out for myself.


text:
Q: Flutter: fill a textfield with a string on shared preferences I'm trying to fill a textfield with a string stored on shared preferences, but I don't understand how to do it.
The case is:
1 - I log in on the first screen.
2 - The username is saved on shared preferences.
3 - Then the second screen is called with some text fields.
4 - The username field should be filled with the user that was saved.
Here is how i store the username on the first screen:
 final prefs = await SharedPreferences.getInstance();
                      final key = 'user';
                      final value = loggedUser;
                      prefs.setString(key, value);
                      print('saved $value');

And here is the function that I use on the second screen to retrieve the username:
 static _read() async {
    final prefs = await SharedPreferences.getInstance();
    final key = 'user';
    final value = prefs.getString(key);
    print('saved $value');
    String usu = value;
  }

I can load the username on the second screen but I can't put it on a textfield, how can I do that?
I have tried a little modification on the function (below) and them passing the function on the text controller but doesn't worked, I guess its not the right way.
  static _read() async {
    final prefs = await SharedPreferences.getInstance();
    final key = 'usuario';
    final value = prefs.getString(key);
    print('saved $value');
    String usu = value;
    return usu; //the modification
  }

The controller:
final _pecasController = TextEditingController(text: _read());

A: I finally did it.
Thanks for the guys who commented here and helped me, it wasnt working so i made a search and finally managed to make it work.
Here's the codes
The function:
 static _read() async {
    final prefs = await SharedPreferences.getInstance();
    final key = 'usuario';
    final value = prefs.getString(key);
    print('saved tester $value');
    String usu = value;
    return usu;

  }

The initstate:
  @override
  void initState() {
    super.initState();
    _read();

    WidgetsBinding.instance.addPostFrameCallback((_) async {
      _usuarioController.text = await _read();
    });

I don't know if this is the best way to make it, but it worked and thats all i need for now.

A: As I was in the same boat, even though this answer is old, I felt like i wanted to give an answer. I would have posted this in the comments but am unable to do so atm.
@override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      await _read();
    });
  }

The inital code can be smaller, there is no need to load the _read() before the WidgetsBinding. All it does is call it twice.. For readability I would also suggest making the _read() call shorter, and make it a normal Future so you will be sure the return type is String. Also privatised the values.
Future<void> _read() async {
    final _prefs = await SharedPreferences.getInstance();
    final _value = _prefs.getString('usuario');
    print('saved tester $_value');
    setState(() {
      _usuarioController.text = value;
    });

  }

I know the previous answer was correct and it worked, but this is better.

A: Does this work for you?
class TheState extends State<TheWidget> {

  TextEditingController _pecasController = TextEditingController();

  @override
  void initState() async {
    _pecasController.text = await _read();
  }

A: use setState() method  and update the textController of textfield with updated string.
final TextEditingController _mobile = TextEditingController(text: '');

String mobileString = '1238892922';

setState((){
_mobile.text = mobileString;
}
)

And the textfield text will be this 1238892922


text:
Q: y.tab.h and y.tab.c files are not generated by bison on Win32 I run the following command on Windows Server 2012 with latest Bison and Flex.
bison --yacc -dv test.y

But only a y.output file is generated.
I need y.tab.c and y.tab.h. Why are they not generated?
The error message that I didn't notice before:
m4: cannot open `Files': No such file or directory
m4: cannot open `(x86)\GnuWin32\Bison/share/bison': No such file or directory
m4: cannot open `D:\Program': No such file or directory
m4: cannot open `Files': No such file or directory
m4: cannot open `(x86)\GnuWin32\Bison/share/bison/m4sugar/m4sugar.m4': No such file or directory

A: Yes, it works now. Bison cannot handle space in path string. Never expected such an issue. Thanks EJP for the reminding.


text:
Q: OS X 10.9 - Home Directory for Share Only Account? I created a new Share Only user account but I am not able to find the home directory for this account in Finder, or under /Users.
I know for sure that the account was created correctly, because when I try to recreate the same Share Only Account, the system tells me that an account of this type already exists.
Where can I find the home directory for this specific account?
My other accounts (Standard User Account, Administrative User Account and Parental Control User Account) appear in the /Users directory.

A: Sharing Only accounts do not have home folders. Home folders are really only used during a local login session, and Sharing Only users cannot log in locally, there's no real point to having one.
If you want a Sharing Only account to have a their own private file storage location, create a folder (where doesn't really matter), use System Preferences -> Sharing pane -> File Sharing service to add it to the shared folder list, then set the owner to the Sharing account (and optionally limit access for other users).


text:
Q: Weighted Least Squares - Categorical Data vs. Numerical Data Over on Stackoverflow, I am trying calculate the Weighted Least Squares (WLS) of a data set in a python library called Numpy as compared to using a library called Statsmodels. However, I noticed something very mysterious.
I have discovered that computing the WLS on numerical data vs. categorical data yields a completely different line of best fit. I understand that in the categorical example of male vs. female, with the values zero (0) and one (1) being assigned respectively, it is wrong to compare the dummy variables of the male and female category groups (e.g. male < female because 0 < 1) as we could have chosen any numbers for these groups, but...
How does the math change? Why do you get a different line of best fit when just treating everything as numerical data than when having categorical data?
As reported here on slide 2, the WLS estimates for the parameters of the line of best fit are found by minimizing the weighted Residual Sum of Squares (RSS):
$$\sum_{i=1}^{n} w_i(y_i-[\beta_0+\beta_1*x_i])^2 \\ parameters=\beta_0,\beta_1 \\ weights=\vec{w} \\ input=\vec{x} \\ output=\vec{y}$$
How does this change with categorical data? I am extremely confused about the math behind including categorical data in the calculations. Does anyone have any thoughts on this?


text:
Q: problem passing values via XCom in my Airflow DAG I'm trying to pass a value  from one  Task to another in my DAG.
I have this piece  of  code in my DockerOperator task:
'''ti = kwargs['ti']'''

'''command=ti.xcom_pull(key='return_value', task_ids=['run_this']),'''

Yet  I am get error 'invalid syntax' from this  line with 'ti.xcom_pull'  above.
This  DAG has  two  tasks,  the first  one is Task ID run_this which calls a Python Callable Function called run_this_now that has this as its  return statement:
return payload
I am looking at the UI under  Admin-->XComs and see the key 'return_value' with its value as shown to be returned by task ID 'run_this'.
So I know I have  an XCom  with a return value and  yet the  syntax  is still giving  me this   error.
I am running Airflow 2.0.2

A: The fix was  to use double  {{'s under  the DockerOperator
I didn't need  to reference  the variable as the run_this  function  only returned one value via 'return' statement
    command="{{ti.xcom_pull(task_ids = 'run_this')}}",


text:
Q: BIRT - using multiple webservices to get the data I am trying to generate a report using Eclipse BIRT report designer.
The scenario is this:
There are 2 web service data sources. There are 2 datasets for webservices 'WS1' and 'WS2' respectively.
The output element 'COUNTRYID' of one webservice 'WS1' would go as input for another webservice 'WS2'.
What I did:

*

*Created a parameter COUNTRYID.

*Created a dummy Computed Column in the dataset of the web service 'WS1' with the expression:
    params["COUNTRYID"].value=row["COUNTRYID"]

*Now the input parameters for the 'WS2' dataset is related to the global paramter 'COUNTRYID'.

*When I run the report, I see that the global parameter contains the value from the 'WS1' output.
But the report does not display the values from the response of the web service 'WS2'
My questions:

*

*How can I see, if the webservice got fired or not?

*How can I see, if the webservice got fired with correct values ?

A: WS1 is not fired unless it is explicitely bound to a report element. Typically, to achieve this we apply following steps:

*

*insert a data element at the beginning of the report body

*turn the property visibility of this new element to false (or let it visible during testing)

*bind it to the first dataset WS1

It will force a silent execution of WS1, and therefore this will populate your parameter COUNTRYID before WS2 runs.
However this approach would not work if:

*

*WS2 dataset has to be used to populate selection items of a report parameter (which does not seem to be the case here)

*If COUNTRYID parameter is used at render time. This point is much more annoying, if you need this parameter in chart expressions for example. If so, i would recommend to store WS1 in a report variable instead of (or why not in addition to) a report parameter. See this topic to see how to create a report variable.

You can initialize it at the same place you did for the report parameter with:
vars["COUNTRYID"]=row["COUNTRYID"];

and use it anywhere with
vars["COUNTRYID"];

Report variables are available from the palette of expressions editor :


text:
Q: (Angular custom validation) Input field always has the previous value instead of the updated one I have the following directive which is responsible for a custom validation:
@Directive({
  selector: '[acUniqueName]',
  providers: [{provide: NG_VALIDATORS, useExisting: UniqueNameDirective, multi: true}]
})

export class UniqueNameDirective implements Validator {
  @Input('acRole') role: Role;

  validate(control: AbstractControl): { [key: string]: any } | null {
    console.log(control.value);
    console.log(this.role.name);
    // logic here
  }
}

I bind to it in an input field:
<input type="text" class="form-control" name="test" id="test" [(ngModel)]="customerRole.name" acUniqueName [acRole]="customerRole">

customerRole is an object of class Role.
The problem is that whenever i type something in the input field this.role.name always shows the previous value. So for example if i have a text Hello in the input field and i add another letter in Hello1, then control.value will correctly be assigned to the correct new value Hello1, but this.role.name will still be assigned to the previous value Hello. If i then type in Hello12, this.role.name will be assigned to Hello1.
What might cause the input value to be one step behind all the time?
PS: The original problem is that i wanted to use an array of roles as an input and check whether that array contains a name equal to control.value. But that didnt work because the roles inside that array always had the previous name value stored instead of the current one like in this simplified example.


text:
Q: Super Street Fighter 4 for PC runs very slowly I recently installed SSFIV on my new PC. It runs extremely slowly. What can I do to fix this? I don't believe that its a hardware problem as my PC is brand new and can play more resource-intensive games than this.
I am playing offline on a dual-core, 3.2 GHz, 32-bit PC. I have turned off v-sync and I'm playing at maximum screen resolution.

A: Your video card does not meet the minimum system requirements for the game.
Because everything in SSF4 is tied to frames and framerate, if you can't push the framerate, then the entire game slows down to match.
Looking at the benchmarks for your videocard it can't even handle most games at low settings.  This isn't suprising since its an integrated card and the GMA4500 is one of the low end ones in that area.


text:
Q: How to and is good practice to create generic Host class extension methods in ASPNETCORE 3? In typical aspnet core application.
As a example of Program.cs
var host = new HostBuilder()
      .Build();

   await host.RunAsync();

How we must declare if we wish to extend HostBuilder capablites with extension methods as when using "CreateDefaultBuilder()" with IWebHost in netcore <2.2.

A: To create IHostBuilder extension method.
Begins creating a static class with static methods (public)
Import to the client that is going to use the method.
Declaration is as follows:
public static class MyHostHostBuilderExtension
    {
        public static IHostBuilder CreateMyBuilder(this IHostBuilder hostBuilder)
[...]

In the Program.cs use a HostBuilder() instance.
var host = new HostBuilder().CreateMyBuilder().Build();

Notice if you using Host static class. It can't be extended.


text:
Q: Maxtor 6B250S0 from iMac mount on Windows 10 USB I'm trying to plug a Maxtor disk drive pulled out of what I assume is a G5 iMac. I'm plugging it into an "Aukey" USB adapter caddy and trying to access on Windows 10.
I get a "Device not migrated" error in Device Manager:

The "Maxtor MaxBlast" recognises the disk but labels it as unallocated / no partitions:

I've tried "HFSExplorer" to see whether it's a partition format (HFS+ ?) that Windows doesn't recognise. It doesn't auto-detect any matching partitions.
The disk doesn't sound too healthy in the caddy (a bit of high pitched noise and whirring on startup) but not as bad as some other working drives I've had before!
I'm just trying to read from the drive and pull a few photos off before reformatting; no need to write to the drive.

A: Most likely, the partition table on the drive is a legacy APT (Apple partition table), which neither Windows itself nor the modern day tools recognize.
The easiest way out is to boot into Linux (use a Ubuntu "Live" USB Stick it won't Install or otherwise ruin you Windows Installation), as most Distros natively support APT.


text:
Q: LibGDX game dies with PVRSRVAllocDeviceMem error in Android I made a really simple game using the latest stable LibGDX. It's just a few Actors (5 max at any given time) and some background textures.
The game runs fine and after a few times that I die and have to start over I get the following message in the console
02-24 08:19:10.478: E/IMGSRV(26860): :0: PVRSRVAllocDeviceMem: Error 1 returned

The game continues running fine for a few seconds or minutes, then it just dies with no other error message in the console. The only other messages I see are GC ones.
Any ideas?
Thanks!
Update:
Here's a screenshot of the heap right after I get the error message, but hasn't crashed yet:


text:
Q: gtkmm3.0 and Css :active state selector for GtkButton state not applying changes So I'm new with GUI development and I'm just implementing a user interface with C++ on a Raspbian OS using Gtkmm3.0 (GTK wrapper for c++).
I'm trying to apply custom design to a button with CSS through a Gtk::CssProvider which works perfectly.
css = Gtk::CssProvider::create();
css->load_from_path("css/theme.css");
auto ctx_mnew_session = mnew_session.get_style_context();
ctx_mnew_session->add_provider(css,GTK_STYLE_PROVIDER_PRIORITY_USER );
ctx_mnew_session->add_class("th-button");
ctx_mlast_session->context_save();

my th-button is a css defined class like this:
.th-button
{
    background-color:#000000;
    color:#ffffff;
    border:solid 2px #ffffff;
    border-radius: 7px;
}
.th-button:active
{
    background-color:#ffffff;
    color:#000000;
}

The design applies perfectly but does not take in consideration the active state. It doesn't matter if I press on the button or not, the design does not change although it is said in the Gtk+ reference that the :active selector is handled.

Another use of pseudo-classes is to match widgets depending on their state. The available pseudo-classes for widget states are :active, :hover :disabled, :selected, :focus, :indeterminate, :checked and :backdrop. In addition, the following pseudo-classes don't have a direct equivalent as a widget state: :dir(ltr) and :dir(rtl) (for text direction), :link and :visited (for links) and :drop(active) (for highlighting drop targets). Widget state pseudo-classes may only apply to the last element in a selector.

Does this make any sense to you?
Config: Raspbian OS on raspberry pi 4 / GTKmm 3.24.0
My widget architecture

*

*MainWindow::Window

*
*

*MainFrame::Box

*
*

*
*

*mnew_session::Button

*
*

*
*

*css::CssProvider


text:
Q: What does the ALSO keyword mean in MLISP? I've been looking over the source code for the early AI project Parry recently. It's tricky because the bulk of the code is written in MLISP, for which no working implementation still exists (that I know of). Instead, I've been using the language specification (MLISP Users' Manual and the earlier MLISP Technical Report).
One curiosity that I haven't been able to explain is the IF-THEN-ELSE-ALSO construct, e.g.:
IF !LAMBDANAME(B) THEN ERROR("NONLAMBDA INTO REACT2",B) ALSO RETURN NIL;

The documentation I have been able to find does not mention an ALSO clause for the IF statement, and I'm scratching my head a bit to understand what it's for.
One plausible suggestion I've seen is that it's used the way the finally clause is used for exception handling in Java, i.e. to run cleanup code no matter how the IF is terminated.  On the other hand, that doesn't explain statements that appear never to raise exceptions, like:
IF REACTTO='QUIT THEN REACTTO:=NIL ALSO TRACE_MEM:='NOSPECIALANAPH;

Any ideas?

A: IF e1 THEN a ALSO b ALSO c ELSE d ALSO e ALSO f

Is just
(COND (e1 a b c) (T d e f))

See MLISP from David Canfield Smith, 1970.


text:
Q: OutOfMemoryException when trying to draw tile map I'm trying to draw a tile map in C# and the problem I'm having is strange in my opinion.
I have this int array that is suposed to hold the x coordinate and y coordinate to draw the tiles on the screen. (The arrow with not only 0's in it is X and other one is Y)
int[,] level1 = { { 0, 32, 64, 96 }, { 0, 0, 0, 0 } };

Here is how I use for loops to render a part of the tile into the screen and it's here I'm getting an "OutOfMemoryException" on a line that I will comment out:
public void DrawTest(SpriteBatch spriteBatch)
    {
        for (int x = 0;; x++)
        {
            for (int y = 0;; y++)
            {
                x = level1[x, 0];
                y = level1[0, y];

                //This line bellow is where it says OutOfMemoryException
                spriteBatch.Draw(tileSheet, new Rectangle(x, y, 32, 32), new Rectangle(0, 0, 32, 32), Color.White);

                if (x >= 5 | y >= 5)
                {
                    x = 0;
                    y = 0;
                }
            }
        }
    }

When i want to call this render method i do it in the main class Render method
levelLoader.DrawTest(this.spriteBatch);

It worked perfectly before i used this DrawTest method to try drawing the tiles. But I have completely no idea why this isn't working correctly.
UPDATE:
public void DrawTest(SpriteBatch spriteBatch)
        {
            for (int x = 0; x < 5 ; x++)
            {
                for (int y = 0; y < 5 ; y++)
                {
                    x = level1[x, 0];
                    y = level1[0, y];
                    spriteBatch.Draw(tileSheet, new Rectangle(x, y, 32, 32), new Rectangle(0, 0, 32, 32), Color.White);
                }
            }
        }

UPDATE2:
        public void DrawTest(SpriteBatch spriteBatch)
    {
        for (int x = 0; x < 5 ; x++)
        {
            for (int y = 0; y < 5 ; y++)
            {
                int tileXCord = level1[x, 0];
                int tileYCord = level1[0, y];
                spriteBatch.Draw(tileSheet, new Rectangle(tileXCord, tileYCord, 32, 32), new Rectangle(0, 0, 32, 32), Color.White);
            }
        }
    }

A: I see several problems in your code:

*

*You have an infinite loop here in your code. What is the termination condition for your nested loops?

*(important!) The spriteBatch.Draw() method doesn't draw anything, it just schedules the drawing of your sprites. This method invocation should be preceded by spriteBatch.Begin() (to start scheduling he drawing) and eventually you must call spriteBatch.End() to flush the scheduled spites to your device. You infinite loops cause the infinite scheduling of your sprite drawing until the memory is full and you are facing the out of memory exception.

*(note!) In you condition (x >= 5 | y >= 5) you are using a bitwise OR comparison, you shouldn't do it (unless on purpose, which I don't see here and rather use boolean OR: (x >= 5 || y >= 5)

*It is a very bad habit to modify loop counters within the loop itself. Not it is only errors prone, it is also difficult to understand and support your code written this way.

I would re-write your code this way
    spriteBatch.Begin();
    for (int x = 0; x < 5; x++)
    {
        for (int y = 0; y < 5; y++)
        {
            x = level1[x, 0];
            y = level1[0, y];

            //This line bellow is where it says OutOfMemoryException
            spriteBatch.Draw(tileSheet, new Rectangle(x, y, 32, 32), new Rectangle(0, 0, 32, 32), Color.White);
        }
    }
    spriteBatch.End();

It will re-draw all your tiles on every Draw() event of the main gameloop (provided you are still calling this method from your Draw() method of your Game class. XNA varies the FPS rate depending upon the performance of you PC and the amount of calculation it has to be done on every frame.

A: I think you are stuck in an infinite loop. You need to exit somehow to avoid the out of memory exception.


text:
Q: Can I have ogr ExportToJson export with NO z coordinate? I have code exporting a polygon to a json file, I would like to do this without the z coordinate since I don't need it and editing the database that was created from geodjango migrates looks painful.
So some way to tell this:
poly.ExportToJson()  to not include a z coordinate?
snippet that exports the json from a read in geotiff file:
for gcp in gcps:
    ring.AddPoint(gcp.GCPX, gcp.GCPY)

ring.AddPoint(gcps[0].GCPX, gcps[0].GCPY) #close off the polygon
    # Create polygon
poly = ogr.Geometry(ogr.wkbPolygon)
poly.AddGeometry(ring)
md = nitfData.GetMetadata()
print(filename)
dic = {"sensor" : md['NITF_ISORCE'], "corner_coords" : md['NITF_IGEOLO'], "target_name" : md['NITF_TGTID'], "collection_dt" : md['NITF_IDATIM'], "f_size":os.path.getsize(path), "polarization" : md['NITF_FTITLE'], "mpoly" : poly.ExportToJson() }

jsonPaths.append(json.dumps(dic) + ',')

A: You can remove z coordinate like follow:
poly.FlattenTo2D()


text:
Q: hetzner vswitch и пул ip /27 Подскажите пожалуйста куда копать.
Настроил vswitch на хецнере, 3 ноды proxmox видят друг друга.
Хецнер выдал пул белых ip /27 для id 4000. 167.233.xxx.xxx
Как его подключить к нодам?

A: #Для начала
sysctl -w net.ipv4.ip_forward=1

echo "1 vswitch" >> /etc/iproute2/rt_tables

#И сам конфиг
auto lo
iface lo inet loopback

iface lo inet6 loopback

#начальный сетевой конфиг
auto eno1
iface eno1 inet static
        address 95.xxx.84.169/26
        gateway 95.xxx.84.129
        up route add -net 95.xxx.84.128 netmask 255.255.255.192 gw 95.xxx.84.129 dev eno1

#vSwitch для кластера (те айпишники которые будут мигрировать с контейнерами между нодами)
auto eno1.4000
iface eno1.4000 inet static
        address 10.0.0.3/24
        mtu 1400
        up ip addr add 167.xxx.4.226/27 dev eno1.4000
        up ip rule add from 167.xxx.4.226 lookup vswitch
        up ip rule add to 167.xxx.4.226 lookup vswitch
        up ip route add default via 167.xxx.4.225 dev eno1.4000 table vswitch
        down ip addr del 167.xxx.4.226/27 dev eno1.4000
        down ip route del default via 167.xxx.4.225 dev eno1.4000 table vswitch
        down ip rule del to 167.xxx.4.226 lookup vswitch
        down ip rule del from 167.xxx.4.226 lookup vswitch

#CIDR для одной из нод
auto vmbr0
iface vmbr0 inet static
        address 167.xxx.4.226/27
        bridge-ports eno1.4000
        bridge-stp off
        bridge-fd 0
        bridge-vlan-aware yes
        bridge-vids 2-4094
        mtu 1400

Дальше добавить остальные ноды в сеть vswitch и вбить похожий конфиг, cidr брать из свободных айпи.


text:
Q: Creating virtual device
*

*Is it possible to create virtual device "on the fly" ? (The guy click on a button "new virtual device", write the device name and the windows popup appear as if he a just plugged a new device).

*Do i have to create a custom device driver or can i use a generic one ?

*Where should i start (documentation link) ?

My goal is to emulate one or more virtual gamepads, visible in games (with their custom names), and mapped to one or multiple physical devices, like keyboard and mouse.
Thank you !

A: Yes, it's possible. The Windows driver architecture needs such support to allow USB drivers to load on the fly. You will need a custom device driver. There are existing "virtual" device drivers, e.g. for NUL, but those aren't what you want.
However, device driver writing isn't for the faint of heart. You really can't expect to read a single article and start hacking.


text:
Q: Library is using wrong R file I package a library project as aar-file and include it in a different project via gradle.
Now it seems like the library project is using a wrong R file which leads to NullPointerExceptions.
Library Project (packaged as aar):

*

*SomeFragment
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
   View v = new View(getActivity());
   v = inflater.inflate(R.layout.fragment_some, container, false);
}

My Project

*

*MyFragment extends SomeFragment
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
L.d("ExtendedFragment - onCreateView");

return super.onCreateView(inflater, container, savedInstanceState);
}

R values:

*

*build/generated/source/r/debug/com.example.myapp/R.java - fragment_some=0x7f030005;

*build/generated/source/r/test/debug/com/example/mylibrary/R.java - fragment_some=0x7f030005;

*build/intermediates/exploded-aar/com.example/mylibrary/version/R.txt - fragment_some 0x7f030000
While debugging I realized that in the Library the Id of the R.txt file is handed to the Inflater. The problem is that the Inflater uses the R.java, mentioned above, to resolve the ressource, gets the wrong ressource and inflates therefore a wrong layout which in the following leads to Exceptions.
What could be the reason for this behaviour?

*

*Is the R.txt file incorrectly generated? What purpose has the R.txt file?

*Do I have to set the Context or the R file somewhere in Code?

*Or could it be in the buildscript of the project, that it might not include the lib corretly?

Update 20.10.2014
I could not find a solution yet but I included the libraryproject directly as module into my project and everythings works fine. So it seems like it is a problem how gradle resolves the aar file.

A: Steps

*

*Clean your project and build it again

*Check whether the R.java file is generated or not
If the R.java is not generated there is possibility that there is a error in your project most probably in xml file

*Find out from the imports which R.java is imported whether it is import android.R or import android.projectName.R. So the correct one is import android.projectName.R. Android automatically does this but sometimes you have to do this manually

A: Resources need to be uniquely named/identified. This is actually a convenience if you want to override a previously defined resource. For example, you want to change a layout that exists in a library, and customize it when you implement it in your app. Like if you create a library for "search" then you want to use that library across several projects and change the look by using custom icons or changing background colors. You can create icons with the same name and those will be used when the project is built.
In order to avoid this you need to uniquely name the resource in the current project.
As an aside, this also means that if you ever build a library for general distribution you should be sure to create resource names that are unlikely to conflict with the developer's selection of resource names.
In particular, you have a resource named fragment_some that is assigned the same reference value 0x7f030005 - this creates a collision that is resolved by referencing the most recently created R file.

A: Check the import you must have by mistake imported the android.R instead of com.yourproject.R


text:
Q: how show 'no results" in jquery autocomplete, properly? I want to accomplish to implement a message when user search a query that it is not in the list to show No Search Found. I tried using
$('#searchTextField').html(" NO SEARCH FOUND");

but it is not working. Does anyone know how to solve this with my code below? Thanks for the help.
Here is my code:
$(function () {
  var myData = [];
   myData.push("NO SEARCH FOUND");
  $.get("http://localhost:8080/myApp/JobSearchItem.xhtml", function (data) {
    $("#searchTextField").autocomplete({
      minLength: 2,
      source: myData,
    }).val('NO SEARCH FOUND').data('autocomplete')._trigger('select');

    $.each(data, function (k, v) {
      myData.push({
        id: v.id,
        label: v.label,
        value: v.id
      });
    });
  });
});

html
     <form id="searchForm" >

          <input type="text" name="searchValue" id="searchTextField" class="form-control"
                           placeholder="search"/>

      <button type="submit"   class="btn btn-primary" >Search</button>

            </form>

A: Hi I think you are looking for if no match found it should be shown in dropdown. so you need to update your code something like this.
$(function() {
    $("#userInput").autocomplete({
        source: function(request, response) {
            $.ajax({
                url: "http://api.stackexchange.com/2.1/users", // update with your url
                data: {
                    site: 'stackoverflow',
                    inname: request.term
                },
                dataType: 'jsonp'
            }).done(function(data) {
                if (data.items) {
                    response($.map(data.items, function(item) {
                        console.log(item);
                        return item.display_name + " " + item.location; // return your value which is coming from ajax response
                    }));
                }
            });
        },
        minLength: 1,
        response: function(event, ui) {
            if (!ui.content.length) {
                var message = { value:"",label:"No results found" };
                ui.content.push(message);
            }
        }
    });
});

<label for="userInput">Search StackOverflow user:</label>
<input id="userInput" type="text" />

Please check with working fiddle


text:
Q: Include Jquery Parameter in Echo PHP with Row hello ive been trying to figure this out for days now.
What i want to do is echo a test and then create a button that copies the echoed text to the clipboard.
So what i want is that i have an SQL list, in that List there is an ID row i can pass to my echo in the paragraph, but when i try to do the same with the parameter the # seems to an issue.
while($row = mysqli_fetch_array($result)) {
   echo "
";
   echo "
" . $row['Message'] . "
";
   echo '<button onclick="copyToClipboard('. $row['Title'] . ')">Copy TEXT 2</button>';
   echo "
";
}

Also it somehow generates the parameter but there is a blank space between
(" #om2")".

*

*my SQL

*ID = OM2

*Title = "#OM2"

*Message = some3ohruihrgfijbfgbrfghrgjikbnhjergbnergbg

any help is greatly appreciated
Edit.
Script

with echo '<button onclick=\"copyToClipboard(' . $row['Title'] . ')>Copy TEXT 2</button>';
Image!!!

A: You are trying to pass #OM2 as agument of the copyToClipboard() function...
There are some quotes missing to make it a string. Actually, #OM2 isn't.
Try to add some \':
echo '<button onclick="copyToClipboard(\''. $row['Title'] . '\')">Copy TEXT 2</button>';

That should work... But I would suggest a better alternative...
Use a class handle the click event, instead of an inline onclick.
while($row = mysqli_fetch_array($result)) {
   echo "
";
   echo "
" . $row['Message'] . "
";
   echo '<button class="copy">Copy TEXT 2</button>';
   echo "
";
}

Then your clipboard copy script would simply be:
$(".copy").on("click",function(){
  var text = $(this).prev("p").html().replace(/
/g, "\n");
  navigator.clipboard.writeText(text);
});

Here is a snippet ;)

$(".copy").on("click",function(){
  var text = $(this).prev("p").html().replace(/
/g, "\n");
  navigator.clipboard.writeText(text);
});

some3ohruihrgfijbfgbrfghrgjikbnhjergbnergbg

  <button class="copy">Copy TEXT 2</button>


text:
Q: GtkLabel is not wrapping after updating its content here is the code i am using :
    messageCrypte= gtk_label_new("");
    gtk_widget_set_size_request(messageCrypte, 400, 100);
    gtk_label_set_line_wrap(GTK_LABEL(messageCrypte), TRUE);
    gtk_grid_attach(GTK_GRID(cryptTab), messageCrypte, 0, ++i, 2, 1);

when i initialize the label manually by passing a string to the gtk_label_new , the text is wrapped ,
but when updating the GtkLabel , it increment the window size to the infinite without wrapping,
from the docs :

Note that setting line wrapping to TRUE does not make the label wrap
  at its parent container's width, because GTK+ widgets conceptually
  can't make their requisition depend on the parent container's size.
  For a label that wraps at a specific position, set the label's width
  using gtk_widget_set_size_request().

i did what it is said but no results !

A: the problem was in the wrap mode ,
the wrapd mode is '...WORD' by default that's mean it will wrap when :
(the limit is exceeded AND there is a new word)
but i was entering a string example that dont contains space so it will consider it a one word ,
but when setting the wrao mode to '...CHAR' it will wrap when :
(the limit is exceeded AND there is a new char) the 2nd condition is always verified ofcourse ,


text:
Q: What is the most optimal way of solving this problem? I saw this coding question on an online coding competition but I couldn't find the most optimal solution.
Here is the question:
"You are given an array A of N integers and Q queries.Each query is of the following type :
1 pos val: Update the element at index pos to val
2 pos : Find the smallest index i less than or equal to pos such that all elements between i and pos are same."
I somehow believe that we can use segment tree but I could not figure out what each index of the segment tree will represent.

A: Here`s O(N +  Q log^2 N) approach:

*

*Build a segment tree for given array

*In each segment tree node store minimum number of interval and maximum number in interval

*Now queries of type 1 can be done by simple update on segmenent tree

*For queries of type 2 we can use binary search to find smallest i such that minimum value in range[i, pos] is equal to maximum value in same range


text:
Q: SQL - how to let sql auto set the next id how can I let sql/mysql set the next id, that I have no problems with posts at the same time?

A: CREATE TABLE Persons
(
ID int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255)
)

Auto_Increment can be used as ID as there wont any duplicate value.
When insert value for the table :
INSERT INTO Persons (FirstName,LastName)
VALUES ('Hello','World')

The table will look like this.
ID | FirstName | LastName
1  |   Hello   |  World


text:
Q: How can I make git commit messages divide into multiple lines? When I use git log to check out my commit explanatory note I want it to look like this:
1. what I changed
2. blank line
3. why I changed it

...being in 3 lines not 1 like this:
1. what i changed  2. blank line 3. why i changed

However, git log shows it in one line. So, how do I get this to happen using git commit -m?

A: Rather than use a temp file when trying to do this programmatically you can use stdin
git commit -F-
then write the message to stdin

A: Use two --message/-m options, first one for the subject and second one for the body.
Excerpt from documentation:

-m <msg>

--message=<msg>

Use the given  as the commit message. If multiple -m options are given, their values are concatenated as separate paragraphs.

In your case it does exactly what you want, inserts a blank line between first and second lines.
git commit -m "Subject: what I changed" -m "Body: why I changed it"

This is useful if you want to amend previously added comment.

A: I needed to have a bash script do multi-line git commits for me, so here are two options I came up with:

*

*Write to a temporary file then commit with the contents of the file as the message:
 printf "first line\nsecond line\nthird line" > "file.txt"
 git commit -F "file.txt"

*(My preferred approach): Write to a temporary variable then commit with the contents of the variable as the message. Note that the quotes around $MSG when doing any command to recall the contents of the variable are required! Without them, you'll lose your newlines.
 MSG="$(printf "first line\nsecond line\nthird line")"
 git commit -m "$MSG"

As an extension of this 2nd approach, in case you need to script building the message in multiple pieces or steps, that is possible too. WATCH OUT though! Notice where I place my newline (\n) characters. I do NOT place them at the end of any printf string. That's because if I do they will get gobbled up, because bash automatically removes any trailing newline characters, since it's dumb like that. So, do it like this instead, which works just fine:
    MSG="$(printf "first line")"
    MSG="$(printf "${MSG}\nsecond line")"
    MSG="$(printf "${MSG}\nthird line")"
    git commit -m "$MSG"

Sample git log output from any of the above git commits:
commit e1983659c6ae2e9d2eb4332657329837582fc32b (HEAD -> master)
Author: Gabriel Staples <email@gmail.com>
Date:   Tue Mar 24 00:55:31 2020 -0700

    first line
    second line
    third line

References:

*

*Unix & Linux: "Why does shell Command Substitution gobble up a trailing newline char?"

*VERY USEFUL! ==> How can I have a newline in a string in sh? <==

A: The multiple-line format you describe is the recommended one with Git (See DISCUSSION in the documentation of git commit). The simplest way to do it is to use git commit without -m, and write your message in your text editor.

A: I find it much easier to save the commit message to a file, and then use the -F option.
Example:
$ cat > /tmp/commit_msg.txt
DE123 bug fix: incorrect fetching of instance details
- fixed this and that
- also did such and such
$ git commit -F /tmp/commit_msg.txt

You could also use an editor to edit the message file before the commit.

A: You just use the following command:
$ git commit -m "1. what i changed
> 2. blank line
> 3. why i changed"

In your terminal, just hit 'enter' for a new line. The commit message won't end until you add the closing quote. The git log will look like:
$ git log
commit abcde2f660c707br2d20411581c4183170c3p0c2
Author: Alex Pan <alexpan@stackoverflow.com>
Date:   Tue Apr 28 20:52:44 2015 -0700

    1. what i changed
    2. blank line
    3. why i changed

A: When writing a commit message just hit Shift + Enter when you want to go to the next line. It looks like this:
git commit -m "multiline
dquote> commit
dquote>
dquote> 1"

And the result will be:
multiline
commit

1


text:
Q: Yii2 GridView show multiple pages I have a GridView with 52 rows and two columns.
What I want is instead of a 52-row long list, to have four lists, one next to the other, each with 13 rows, so like pagination with pageSize=13 but have all pages visible one next to the other.
Can anyone point me to the right direction?

A: Could be use different dataProvider with different page values
$dataProvider0 = new ActiveDataProvider([
  ...
  'pagination' => [
    'pageSize' => 13,
    'page' = 0,
  ],
]);

$dataProvider1 = new ActiveDataProvider([
  ...
  'pagination' => [
    'pageSize' => 13,
    'page' = 1,
  ],
]);

$dataProvider2 = new ActiveDataProvider([
  ...
  'pagination' => [
    'pageSize' => 13,
    'page' = 2,
  ],
]);

$dataProvider3 = new ActiveDataProvider([
  ...
  'pagination' => [
    'pageSize' => 13,
    'page' = 3,
  ],
]);

And assigning the provider to 4 different gridview

A: There are several possible solutions.

*

*You can use GridView properties $beforeRow and $afterRow to visually split one GridView to several blocks.

*You can use one instance of the DataProvider to split it to several ones. For example, you can use an ActiveDataProvider and make $provider->getModels() to get all model objects. Then create four instances of ArrayDataProvider and just use them in four GridViews.


text:
Q: TextInput Update and state modification slow I have made a React page. It initially gets data from my API, and stores it in state. The parent component makes a TextInput in a component for each row of data.
The TextInput value is from a prop. The onChange calls a method on the parent (through a prop given to the TextInput), which finds the appropriate index to update, updates it, then setState. It also sends a PUT to my API to update the data.
However it is pretty sluggish when typing. I can type fast and you can see it having a delay sometimes.
Any ideas?
update_sound(sound_transcript, sound_id) {
  var index = this.state.board.sounds.findIndex(sound => {
    return sound.id === sound_id;
  });

  this.state.board.sounds[index].sound_transcript = sound_transcript;
  this.setState({
    board: this.state.board
  });

  axios
    .put("/api/v1/sounds/" + sound_id, {
      sound_transcript: sound_transcript
    })
    .then(response => {
      //Handle success
      console.log("Update success");
    })
    .catch(error => {
      //Handle error
      console.log("Update error: " + error);
    })
    .then(() => {
      //Always executed
    });
}

<textarea
  className="soundPlayer_text_input"
  value={this.props.sound.sound_transcript}
  onChange={this.soundOnChange}
/>;

soundOnChange(event) {
  console.log("soundOnChange");
  this.props.update_sound(event.target.value, this.props.sound.id);
}

Thanks


text:
Q: Highlight the weekday cells as day goes by automatically, Monday Thru Sunday. Today is Tuesday I want Tuesday to be highlighted, see image attached Please see image below, I want the library hours to be highlighted automatically everyday.
https://i.stack.imgur.com/LvqhR.png

A: You could use JavaScript for that.
var date = new Date();
var day = date.getDay(); //Returns 0-6 (sunday-saturday)

You can now add a highlighter class to the current day div depending on the day variable.


text:
Q: Metrics from new job absent in Prometheus I installed new node_exporter.
Mertics aviable on
server01:9100/metrics
for example
...
node_filesystem_device_error{device="/dev/sda1",fstype="ext4",mountpoint="/boot"} 0
node_filesystem_device_error{device="/dev/sdb1",fstype="xfs",mountpoint="/data"} 0

wrote in config prometheus.yml new job and target
- job_name: node_exporter_metrics
    metrics_path: /metrics
    static_configs:
      - targets: ['server01:9100']

After restarted Prometheus.
Checked avialability new job and target by API, returned:
{"discoveredLabels":{"__address__":"server01:9100","__metrics_path__":"/metrics","__scheme__":"http","job":"node_exporter_metrics"},"labels":{"instance":"server01:9100","job":"node_exporter_metrics"},"scrapeUrl":"http://server01:9100/metrics","lastError":"","lastScrape":"2017-12-14T17:32:02.835779115+03:00","health":"up"}

tried to get values by new job
http://server01:9090/api/v1/query_range?query=node_exporter_metrics&start=1513255115&end=1513258715&step=60

result
{"status":"success","data":{"resultType":"matrix","result":[]}}

How solve this problem?

A:
http://server01:9090/api/v1/query_range?query=node_exporter_metrics&start=1513255115&end=1513258715&step=60

The name of the metric is not node_exporter_metrics, it's node_filesystem_device_error. node_exporter_metrics is the job label.


text:
Q: how to iterrate the tool variable in jenkins groovy In an example pilepline I saw a variable named tool and is used like this:
echo "${tool 'vs2017'}"
// Outputs C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin

My question is, what kind of variable is this? and how can I see what includes in this variable. I tried to print it like this but it fails:
tool.each { k, v -> echo 'k'}

groovy.lang.MissingPropertyException: No such property: tool for class: groovy.lang.Binding
  at groovy.lang.Binding.getVariable(Binding.java:63)
  at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:271)
  at org.kohsuke.groovy.sandbox.impl.Checker$7.call(Checker.java:353)


text:
Q: How to make SSL/HTTPS certificates on Gitlab Auto DevOps with GKE and kube-lego The instructions say to install it, but doesn't suggest which method will work, in what order or with which load balancer. I keep getting useless test certificates installed on my deployments.

A: It sounds like you are getting the default chart from helm, which is slightly different than the instructions you will find on the kube-lego Github. The helm chart uses Let's Encrypt's staging server by default. Also if you are not familiar with helm it can be quite tricky to undo the remnants that the kube-lego helm chart leaves behind, specially as tiller likes to keep the old installation history.
Here's a brief overview of setting up Gitlab Auto Devops with Google Kubernetes Engine. I should mention that you can skip up to step 13 if you use the Gitlab GKE wizard introduced in 10.1, but it won't really tell you what's happening or how to debug when things go wrong, also the wizard is a one way process.

*

*In Gitlab under integrations you'll find a Kubernetes integration button

*

*You can also find this under CI/ CD -> cluster

*The API URL is the endpoint ip prefixed by https://

*The "CA Certificate" it asks for is service account CA, not the same as the cluster CA

*To connect to gitlab you'll need to create a k8s service account and get the CA and token for it. Do so by using gcloud to authenticate kubectl. GCE makes it easy by doing this for you through the "connect" button in k8s engine

*

*https://kubernetes.io/docs/admin/authentication/#service-account-tokens

*All commands must be run with a custom namespace, it will not work with default

*kubectl create namespace (NS)

*kubectl create serviceaccount (NAME)  --namespace=(NS)

*

*This will create two tokens in your configs/secrets, a default one and you service account one

*kubectl get -o json serviceaccounts (NAME)  --namespace=(NS)

*kubectl get -o json secret (secrets-name-on-prev-result) --namespace=(NS)

*To decode the base64 values echo them to base64 -d, for example

*

*Echo mybase64stringasdfasdf= | base64 -d

*To install helm, use the installation script method

*

*https://docs.helm.sh/using_helm/#from-script

*Init helm and update it's repo

*

*helm init

*helm repo update

*Install nginx-ingress, its ingress with nginx. You could use the Google load balancer as well, but it's not as portable.

*

*helm install stable/nginx-ingress

*Make a wild card subdomain with an A record pointing to the IP address set up by ingress

*In Gitlab, Make auto devops use your newly setup wildcard subdomain, if its "*.x" on "me.com" you should enter "x.me.com" in the auto devops settings.

*Now install kube lego

*

*helm install --name lego-main \
--set config.LEGO_EMAIL=CHANGEMENOW@example.com \
--set config.LEGO_URL=https://acme-v01.api.letsencrypt.org/directory \
stable/kube-lego

*

*Helm installations are called charts, equal to a k8s container installation

*If you wish to delete a release, you must purge it, otherwise tiller will keep a history, with:

*

*helm delete --purge my-release-name

*You can find the release names and their associated chart in

*

*helm list

Troubleshooting

*

*Order doesn't seem to matter too much. attaching to a pod can be a useful way of debugging problems, such as a bad email address. The Ideal order however is probably, nginx-ingress, then kube-lego, then gitlab. I did make it work with gitlab first, then nginx-ingress, then kube-lego.

I heard from Sid that they are working to make this easier... let's hope so.


text:
Q: Export dataframe to csv date type I want to convert the dataframe (below) to csv file only with year from Tarih and value from Veri:
        Tarih  Veri
0  1960-01-01     0
1  1961-01-01     0
2  1962-01-01     0
3  1963-01-01     0
4  1964-01-01     0
5  1965-01-01     0
6  1966-01-01     0
7  1967-01-01     0
8  1968-01-01     0
9  1969-01-01     0
10 1970-01-01     0

I use this function:
df= pandas.read_excel(path)
df.to_csv(newPath, header=True, index=False, decimal=",", date_format="%Y")

But it exports like that in newPath.csv file(without Veri column):
Tarih,Veri
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970

If I use date_format="%Y,%m" or date_format="%Y,%m,%d" it gives right result. Even I use date_format like that: date_format="%Y,"(it gives 1960,,0 but gives Veri) or date_format="%Y "(leaving a space after Y; it gives 1960 ,0 but gives Veri).
How can I get this csv file by using this function:
Tarih,Veri
1960,0
1961,0
1962,0
1963,0
1964,0
1965,0
1966,0
1967,0
1968,0
1969,0
1970,0

Where am I wrong?

A: It works for me, a workaround that might work for you:
df = df.set_index('Tarih')

df.to_csv(newPath, header=True, index=True, decimal=",", date_format="%Y")

This will set the index to the 'Tarih' column and outputs it in the csv file.


text:
Q: Regex split with quotes and colon I've seen a thousand posts about regex and matching quoted terms, etc. but none of them seem to give me what I need and despite my best efforts I'm honestly pretty terrible with regex, especially when you get into looking forward/backward and such, which is what I think I need here.
I have a single text box for users to enter a search.  It may be a single word, or it may have some hints for which field to search (colon for text fields, or a > or < for date/numeric fields).  In this example, I'm searching anything containing the word blue or dark blue, written by John Smith, with the word Foo in the title, and published after 1/1/2020.  Some of this is similar syntax to Google's search.
blue "dark blue" author:"john smith" title:foo published>20200101
There are a few factors to consider.  First, I have to keep dark and blue together, john and smith together as a single search term.  Then I have to split things out (the : < or >) and decide which field to search.
As a step one, I'd like to just get an array that looks like this:
blue
"dark blue"
author:"john smith"
title:foo
published>20200101

Then step two would be to figure out if each term has an operator like author, title, etc.
If that can be rolled into one expression that would be great, but I'm certainly not counting on it.
Can anyone help me with this regex pattern?  Thanks so much!  For whatever it's worth I'm using C#/.NET for any kind of nuance.

A: You may try doing a regex split on the following pattern:
[ ](?="|\w+:|\w+>)

Demo
The regex used here says to split on a space [ ], according to this logic:
[ ]       split on space, which is followed by
(?=
    "     a double quote
    |     OR
    \w+:  a word term followed by colon :
    | OR
    \w+>  a word term followed by >
)

Note that the (?=...) term is a lookaround, and asserts, but does not actually consume any text.  The only thing consumed during the split is the single space.


text:
Q: How to match a negated word in a regex for better or worse I need to do the following using a regex:
match everything between an opening and closing textarea html tag:
Other HTML
<textarea id = foo class = 'bar'>

some text which can include brackets> like that

<thi is an opening bracket > that was a closing one

</textarea>
Other HTML

The regex I've got so far is the following except it doesn't go all the way to the ending textarea
<textarea id = foo[^>]+>[^>]+>

We're using a proprietary system and we don't have any alternatives. Thanks in advance for your help.

A: Here's the simplest pattern I can come up with:
<textarea[^>]*>(.*?)<\/textarea>

Demo. Use with the s option or add (?s) in the front of the pattern if your tool allows it. If it doesn't, replace . with [\s\S] as a workaround.
This makes use of a nongreedy quantifier.
The contents of the tag are captured in the first (and only) group.

A: With perl :
perl -0777ne 'print $& if /<textarea .*?textarea>/s' file.txt

Output:
<textarea id = foo class = 'bar'>

some text which can include brackets> like that

<thi is an opening bracket > that was a closing one

</textarea>

A: Instead of using a RegExp, I would do it with some simple vanilla JavaScript.  Like this:

function getText(){

var text1 = document.getElementById('text1').value;

document.getElementById('output').innerHTML = text1;

}
<textarea id="text1">Here is text with some <'s and some >s.</textarea>

    <button onclick="getText()">Get the text above, store it in variable "text1", and then display it below.</button>

I know that this isn't what you asked for, but I find it easier, and it's just a suggestion.  I hope it helps!


text:
Q: how to forward to jsp from servlet? ViewServlet.java:
            List<User> list=EmpDao.getAllEmployees();

            out.print("<table border='1' width='100%'");
            out.print("
ID	USERNAME	PASSWORD	FIRSTNAME	LASTNAME	CITY	ADDRESS	COUNTRY	");

              out.print("
");
            out.close();

*

*My objective is to write html code in 'ViewServlet.java' into pure html code in 'result.jsp'.

*What i am expecting is if i write pure html code in jsp then all the records will be retrieved from "MYSQL" will be displayed in ViewServlet.java.If i want to edit,delete then will happen in 'ViewServlet.java'

*I tried request.getAttribute for ID, USERNAME, PASSWORD, FIRSTNAME, LASTNAME, CITY, ADDRESS, COUNTRY[parameters].
Well my brother guided me to write following -

request.getRequestDispatcher(request.getContextPath()+"/result.jsp")
                                          .forward(request, response);
I am new to JSP,SERVlETS please provide a solution.Thank you.
result.jsp
 <%{
        ArrayList list = (ArrayList)request.getAttribute("alist");
        for(int i = 0; i<list.size(); i++) {
            User user = (User)list.get(i); %>

        <%=user.getID()%>
        <%=user.getUSERNAME()%>
        <%=user.getPASSWORD()%>
        <%=user.getFIRSTNAME()%>
        <%=user.getLASTNAME()%>
        <%=user.getCITY()%>
        <%=user.getADDRESS()%>
        <%=user.getCOUNTRY()%>

        <%
        ArrayList<User> list = (ArrayList<User>)request.getAttribute("/ViewServlet.java");
        for(User e:list){
            out.println(e.getID());
            out.println(e.getUSERNAME());
            out.println(e.getPASSWORD());
            out.println(e.getFIRSTNAME());
            out.println(e.getLASTNAME());
            out.println(e.getCITY());
            out.println(e.getADDRESS());
            out.println(e.getCOUNTRY());

        }%>

*

*Here after 8 parameters add two hyperlinks such has EDIT,DELETE ,My objective here is to add two hyperlinks Edit,delete servlets(EDITSERVLET,DELETESERVLET) so that i can edit,delete records in the table.

*Here i am getting error has "UNABLE TO COMPILE CLASS OF JSP".

*I dont know why i am getting error at "line 33" i mentioned it above.
Kindly help me.Thank you..

A: request.getRequestDispatcher(request.getContextPath()+"/youjsppage.jsp")
                                      .forward(request, response);


text:
Q: Kill all non-essential processes I'm looking for a utility that will allow me to kill all processes that aren't essential to maintaining system stability in an efficient manner. I'm guessing the easiest way to do this would be to find out which processes are owned by Apple Inc. and exclude them from a kill list, if possible.
Disabling login items is not an option as certain processes are needed at startup, such as a few different cloud services which synchronise files. Killing them on demand would be ideal.
Below is an example of what should be killed.

A: The processes you mention would all be killed by one command:
kill -9 -1

That would also log you out and kill all the programs you run so it's not ideal, but it would free and allow the OS to dedicate all further memory and resources to the system.
Practically, you would need to use launchctl to list all user tasks and quit them one by one. The tasks you mention all get started when you log in, so killing them might not do anything but cause them to exit, and re-start.
I would recommend instead of killing - doing the work to really measure the aspect of the system that's causing you constraint. RAM, CPU, Network, disk IO and focus on apps that impact that. The CPU times of the tasks you mentioned are so trivially small, it's hard to see them as any sort of problem, but perhaps you have data and measurements showing otherwise.
OS X can run thousands of small processes and juggle memory, and it's a rare instance where one program has a large enough memory leak or doesn't idle when it's not in use that it's unlikely you have a problem that doing all the work to script a kill tool would ever make you back the time you spent on it. I'd say, work on that script if you need it to learn how things work and not to make any difference going forward. In this instance, don't solve the general problem is my advice...


text:
Q: Kotlin suspend fun I have Kotlin interface
interface FileSystem {
    suspend fun getName(path: Path): List<String>
}

How I can call it from Java? What is
Continuation <? super List<String>>

A: Kotlin implements coroutines using a mix of the regular stack-based calling convention and the continuation-passing style (CPS). To achieve that, it performs a CPS transformation on all suspend funs by adding an implicit parameter, an object you can use to continue the program from the place where the function was called. That's how Kotlin manages to pull off the trick to suspend the execution within your function's body: it extracts the continuation object, saves it somewhere, and then makes your function return (without yet having produced its value). Later on it can achieve the effect of jumping into the middle of your function body by invoking the continuation object.
The continuation is basically a callback object, just like those familiar from async Java APIs. Instead of returning its result, the suspendable function passes its result to the continuation. To call a suspend fun from java, you'll have to create such a callback. Here's an example:
Continuation<List<String>> myCont = new Continuation<List<String>>() {
    @Override public void resume(List<String> result) {
        System.out.println("Result of getName is " + result);
    }
    @Override public void resumeWithException(Throwable throwable) {
        throwable.printStackTrace();
    }
    @NotNull @Override public CoroutineContext getContext() {
        return Unconfined.INSTANCE;
    }
};

NOTE: The above works only with experimental coroutines. In the final API there's just one resumption method: resumeWith(result: Result<T>) where Result is a discriminated union of the result type and the internal class Failure, which makes it inaccessible from Java.

Let's also create a mock implementation of the FileSystem interface:
class MockFs : FileSystem {
    override suspend fun getName(path: Path): List<String> {
        suspendCoroutine<Unit> {
            println("getName suspended")
        }
        println("getName resumed")
        return listOf("usr", "opt")
    }
}

Now we're ready to call it from Java:
Object result = new MockFs().getName(Paths.get(""), myCont);
System.out.println("getName returned " + result);

It prints
getName suspended
getName returned
kotlin.coroutines.experimental.intrinsics.CoroutineSuspendedMarker@6ce253f1

getName() returned a special marker object that signals the function got suspended. The function will pass its actual result to our callback, once it resumes.
Let us now improve MockFs so we can get access to the continuation:
class MockFs : FileSystem {
    var continuation : Continuation<Unit>? = null

    override suspend fun getName(path: Path): List<String> {
        suspendCoroutine<Unit> {
            continuation = it
            println("getName suspended")
        }
        println("getName resumed")
        return listOf("usr", "opt")
    }
}

Now we'll be able to manually resume the continuation. We can use this code:
MockFs mockFs = new MockFs();
mockFs.getName(Paths.get(""), myCont);
mockFs.getContinuation().resume(Unit.INSTANCE);

This will print
getName suspended
getName resumed
Result of getName is [usr, opt]

In real life a suspendable function will use some mechanism to get itself resumed when the result becomes available. For example, if it's a wrapper around some async API call, it will register a callback. When the async API invokes the callback, it will in turn invoke our continuation. You shouldn't need to manually resume it like we did in our mock code.
A suspend fun also has the option to just return its result directly. For example, with this MockFs code
class MockFs : FileSystem {
    override suspend fun getName(path: Path) = listOf("usr", "opt")
}

in Java we can just say
System.out.println(new MockFs().getName(Paths.get(""), myCont));

and it will print [usr, opt]. We could even have passed in an empty implementation of Continuation.
The most demanding case happens when you don't know in advance whether the function will suspend itself or not. In such a case a good approach is to write the following at the call site:
Object retVal = mockFs.getName(Paths.get(""), myCont);
if (retVal != IntrinsicsKt.getCOROUTINE_SUSPENDED()) {
    myCont.resume((List<String>) retVal);
}

Otherwise you'll have to duplicate the code that handles the function's result.


text:
Q: Select columns and group by columns in function arguments I am trying to write a function so that I can input any columns to be described both at the overall level and by a grouping variable.
However, I am having trouble with getting output for grouped results.
My data:
df <- data.frame(gender=c("m", "f", "m","m"), age=c("18-22","23-32","23-32","50-60"), income=c("low", "low", "medium", "high"), group=c("A", "A", "B", "B"))
> df
  gender   age income group
1      m 18-22    low     A
2      f 23-32    low     A
3      m 23-32 medium     B
4      m 50-60   high     B

Function:
library(dplyr)
make_sum <- function(data=df, cols, group_var) {
data %>% dplyr::select(cols)  %>%
  # print tables with frequency and proportions
  apply(2, function(x) {
    n <-  table(x, useNA = "no")
    prop=round(n/length(x[!is.na(x)])*100,2)
    print(cbind(n, prop))
  })
  # print tables by group
data %>% dplyr::select(cols, vars(group_var))  %>%
  apply(2, function(x) {
    n <-  table(x, vars(group_var),useNA = "no")
   print(n)
  })
}

cols <- df %>% dplyr::select(gender,age, income) %>% names()

make_sum(data=df, cols=cols, group_var="group")

I get the proper output for the overall tables but not the grouped, with this error showing:
Error: `vars(group_var)` must evaluate to column positions or names, not a list

Desired output (example) for grouped gender variable:
    A B
  f 1 0
  m 1 2

A: Instead of using the apply with MARGIN = 2, summarise_all can be called here.  Also, the vars wrapped is applied along with a tidyverse function.  Here, inorder to get the  frequency, an option is to subset the column with [[ which is more direct.  Also, as summarise returns only a single row (for each group - if there is grouping variable), we can wrap the output in a list
make_sum <- function(data=df, cols, group_var) {
data %>%
  dplyr::select(cols)  %>%
   summarise_all(~ {

    n <-  table(.,  data[[group_var]], useNA = "no")
    #list(round(n/length(.[!is.na(.)])*100,2))
    list(n)

  })
  }

cols <- df %>%
            dplyr::select(gender,age, income) %>%
            names()

out <- make_sum(data=df, cols=cols, group_var="group")
out$gender
#[[1]]

#.   A B
#  f 1 0
#  m 1 2


text:
Q: How to get data from such blob:http:// url in golang? I have an api written in go, which takes the input in form of blob file, actually a blob url from frontend , When the file gets uploaded to s3 it makes an empty image.
My Go S3 Code looks like
bucket := os.Getenv(infrastructure.FilesBucketName)
if err := s3.PutS3Object(
    bucket,
    "testimage_12344589.jpeg",
    []byte("blob:http://localhost:3001/65e1e5ae-419e-44db-b651-a37c388a0ccb"),
    aws.String("image/jpeg")); err != nil {
    return nil, err
}

What is the best way to fix this issue ?
I have also tried approaches like converting url to string etc, but nothing worked.


text:
Q: Can I use JS BigInt in a BigQuery UDF? Chrome V8 - the JavaScript engine - recently added support for BigInt - arbitrary precision large integers:

*

*https://developers.google.com/web/updates/2018/05/bigint
Can I use these BigInt in BigQuery?

A: Yes! BigQuery runs one of the latest versions of V8, so it already supports BigInts.
To use them:
CREATE TEMP FUNCTION testBigInt()
RETURNS ARRAY<STRING>
LANGUAGE js AS """

return [
  Number.MAX_SAFE_INTEGER
  , Number.MAX_SAFE_INTEGER+2
  , Number.MAX_SAFE_INTEGER+1
  , Number.MAX_SAFE_INTEGER+100
  , BigInt(Number.MAX_SAFE_INTEGER) + 2n];

""";

SELECT testBigInt()

9007199254740991
9007199254740992
9007199254740992
9007199254741092
9007199254740993

From the results, note that JavaScript silently produces the wrong answer when not using BigInt - hence the need for BigInts.
To keep the BigInts compatible with BigQuery, you'll need to treat them as String. Stay tuned, as we've requested improvements for this.
With the wrong types you might get these errors:

*

*Error: Failed to coerce output value 9007199254740993 to type NUMERIC

*Error: Failed to coerce output value 9007199254740992 to type INT64


text:
Q: Angular 2 App Testing, how to access and operate on html elements? I have an Angular 2 Frontend to be tested, I found on a Site ( https://kendaleiv.com/angular-2-component-testing-template-using-testbed/ ) a guy using ng-test (angular core testing) TestBed, this is a really basic example it does not explain how to do operations with the Elements.
My App has an Input Form element, once the input signal has been sent through the Form Element it show a results set on an InfoBox element.
So what I would like to do is to retrieve the element Form from the TestBed provide a String to search with it and get the response from the Input box. (Test 3)
1)  How do I retrieve the elements (form and InfoBox)?
2)  How do I get the signal to be processed from the InfoBox?
3)  How can I retrieve the result set from the InfoBox Element once the signal has been processed?
Here is the code sample that I'm using, when I run it with the command 'ng test' it starts Chrome and the first two tests are working.
describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AgsResultsComponent,
        AppComponent,
        FormularComponent,
        FormularAutocompleteComponent,
        InfoBoxComponent,
        InfoBoxAgencyDetailsComponent,
        InfoBoxAgencyItemComponent
      ],
      providers: [ConfigurationService],
      schemas: [NO_ERRORS_SCHEMA]
    }).compileComponents();
  }));

  // Test 1
  it('should create the app', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    console.log(app);
    expect(app).toBeTruthy();
  }));

  // Test 2
  it('should render agsheading in a h1 tag', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('h1').textContent).toContain('Agentursuche');
  }));

  // Test 3
  it('should execute a search using Form', async(() => {
    const formular = TestBed.createComponent(FormularComponent);
    const infoBox = TestBed.createComponent(InfoBoxComponent);
    formular.detectChanges();
    infoBox.detectChanges();
    const formularCompiled = formular.debugElement.nativeElement;
    const infoBoxCompiled = infoBox.debugElement.nativeElement;
    formularCompiled.sendInput('Just a Test');
    expect(infoBoxCompiled).toContain(something);
  }));

});

A: You should use another beforeEach method to create the components and store them in a local variable, so you avoid writing the same thing in each test.
In order to fetch html elements from the component one can use the query method on the debug element:
const inputDebugElement = formular.debugElement.query(By.css('input'));
const inputHtmlElement = inputDebugElement.nativeElement as HTMLInputElement;

Once you have that, you can set values on it and dispatch events:
inputHtmlElement.value = 'foo';
inputHtmlElement.dispatchEvent(new Event('input'));

Remember that in order to trigger the change detection you need to call detectChanges() on the fixture and after that wait for it to be stable with whenStable() call or call tick() inside a fakeAsync test.
Would recommend to read the official testing guidelines to get a better insight on how to test Angular applications.