text:
Q: Selecting a matching ID from a list of objects Okay so i have a list filled with objects which have the following properties:
category_id and category_title
In the code it looks like this:
class CategoryModel
{
    public int category_id { get; private set; }
    public string category_title { get; private set; }

    //Constructor
    public CategoryModel(int id, string title)
    {
        category_id = id;
        category_title = title;
    }

I have multiple objects of this class stored in a list
    static List<CategoryModel> CategoryList = new List<CategoryModel>();

From this list i am trying to select the category_title where it matches a certain category_id
    public static string GetCategoryName(int categoryNumber)
    {
        IEnumerable<string> title = from c in CategoryList
                    where c.category_id.Equals(categoryNumber)
                    select c.category_title;
        return title.ToString();
    }

So let's say GetCategoryName(4), it's now supposed to select from the list where category_id equals 4 and return category_title
However it seems that i'm not getting the name back but a syntax of the query instead!
Output: system.linq.enumerable.whereselectlistiterator'2[project.CategoryModel,System.string]

A: Just use Linq to do it:
return CategoryList.Single(c => c.category_id == categoryNumber).category_title;

Single will throw an exception if the category list does not have any matching ID.

A: Your query returns list not a single category.
Please try this
public static string GetCategoryName(int categoryNumber)
{
    IEnumerable<string> title = from c in CategoryList
                where c.category_id.Equals(categoryNumber)
                select c.category_title;
    return title.FirstOrDefault();
}

A: The IEnumerable class does not implement some sort of fancy format of its elements in the ToString function. I think the simplest way to approach this would be to use the String.Join function if there are supposed to be multiple results:
return String.Join(",", title);

A: You should use Linq to select first or default value :
public static string GetCategoryName(int categoryNumber) {
    return CategoryList.FirstOrDefault( category => category.category_id == categoryNumber).category_title;
}

But this can throw exception when there's no such category id because of .category_title so the best solution would be :
public static string GetCategoryName(int categoryNumber) {
    CategoryModel category = CategoryList.FirstOrDefault( category => category.category_id == categoryNumber);
    return category == null ? string.Empty : category.category_title;
}

Which will return empty string when no such category was found.
About the error you're getting back. It is because your query returns "many" objects of CategoryModel ie. IEnumerable<string> which then you try to convert to string.
Doing ToString() on any kind of table ( array, list, etc. ) will return something like system.string[] or in other words same result as you would do call IEnumerable<string> .ToString().

A: public static string GetCategoryName(int categoryNumber)
{
    CategoryModel result = CategoryList.Where(x => x.category_id == categoryNumber).FirstOrDefault();
    if (result != null)
        return result.category_name;
    else
        //no matches, do something else
}

This will take the item from CategoryList where the category_id matches the number you passed in, and return category_name if there was a match.

A: You're ToString'ing the Enumerable, which hasn't been evaluated, which is why you're getting the query implementation object.
Assuming you're after the only item that matches, do:
title.SingleOrDefault()?.ToString()

NOTE: the ? operator will only work on C# 6; you can just do a normal assignment and if x == null type check for below


text:
Q: Is there a strictly increasing family $\{ f_\alpha:\alpha<\aleph_1 \} \subseteq \omega^\omega$ of size $<\aleph_1$ Is there a strictly increasing family $\{  f_\alpha:\alpha<\aleph_1 \} \subseteq \omega^\omega$   of size $<\aleph_1$ such that

*

*$f_\alpha\leq^* f_\beta$ if $\alpha\leq\beta<\aleph_1$

*$\lim_{n\to \infty}(f_\alpha(n)-f_{\alpha}(n-1))=\infty$

*$f_\alpha(n)\leq f_{\alpha+1}(n-1)$ for all except finitely many $n$ ?

How I can build this family?  Any suggestions.

A: Let's look first of all at your condition (1) by itself. We can easily construct such a family, via the following fact:

$(*)\quad$ If $\mathcal{C}$ is a countable collection of functions $\omega\rightarrow\omega$, then there is an $f$ which is $\ge^*$ every element of $\mathcal{C}$.

Proof. List $\mathcal{C}$ as $g_0, g_1, g_2, g_3, . . .$, and let $f(n)=1+\sum_{k\le n}g_k(n)$.  $\quad\Box$
This lets us construct a $\le^*$-increasing $\omega_1$-sequence of functions, via transfinite induction. (Of course we need a small amount of AC here.)
Specifically, the proof of $(*)$ gives us a template for producing such sequences, as long as we have a mechanism for picking bijections between countable ordinals and $\omega$: fix some "initial" $\omega$-sequence $f_0, f_1, f_2, . . .$ with the appropriate properties, and then - for $\alpha\ge\omega$ a countable ordinal, and $b_\alpha:\alpha\rightarrow\omega$ the picked bijection between $\alpha$ and $\omega$ - let $f_\alpha$ be the function produced via $(*)$ applied to the collection $\{g_{\alpha,i}: i\in\omega\}$, where $g_{\alpha, i}=f_{b_\alpha^{-1}(i)}$.
Now, what if you want your sequence to have other properties - such as your (2) and (3)? Well, just alter the template $(*)$ appropriately! Rather than the specific choice of $f$ used in the proof of $(*)$ given above, pick a different expression for $f$ which grows "fast enough" (in the relevant ways) to satisfy your requirements.
For instance, we can get condition (2) to hold by replacing the definition of $f$ in $(*)$ with $$f(n)=n^2+\sum_{k\le n}g_k(n).$$
Similarly, for condition (3) we want $f(n)>g_i(n+1)$ for all but finitely many $n$s. We can achieve this by just adding more terms to the sum in the definition of $f$; e.g. $$f(n)=n^2+\sum_{k\le n}\left(\sum_{j\le n+2}g_k(j)\right)$$ folds in both (2) and (3) simultaneously. (Actually, a statement stronger than (3) is satisfied here.)

Note that this general method cannot be modified to work for sequences of length $>\omega_1$, since to form the $\omega_1$st term of such a sequence we would need to "meet $\omega_1$-many requirements" simultaneously, and we really only know how to meet countably many requirements at once. The existence of such sequences, in fact, is independent of ZFC; Martin's axiom (plus the negation of the Continuum Hypothesis) tends to be the right additional axiom needed to construct them.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Algorithm to pass through all the connected points once for each collection of connected points I'm trying to go through each "special" point in a 2D array once, I made a recursive function but it passes through several points multiple times, thus making the collection of special points much bigger than it should be.
void foo(int x, int y) {
    if( Board(x,y) == '*' ) {
        Point newpoint(x, y, '*');
        dq.push_back(newpoint);
        foo(x, ++y);//down
        //foo(x, --y);//up, disabled up to avoid infinite loops
        foo(++x, y);//right
        foo(--x, y);//left
    }
}

For example this could be the board, foo will receive the top left asterisk's location.
   asdf
      ****
       *****
    ****   ***
  4578       *   76767

Is this a known problem? Does it have a name that I could search for it?
PS: I know I can linearly go through each row, adding to the collection if the condition is true, but my end goal is to make several collections of connected asterisks and it's unknown how many collections there should be.

A: Use dynamic programming: store the board coordinates that were already passed through as a bool 2D array (non-local to foo() or static in foo()), then mark each one as passed whenever you pass through it. Then invoke the recursion only if passed[i][j] is false.
Here is a brief tutorial to get you started with dynamic programming, that uses the typical example of recursive Fibonacci (which of course scales super badly if you don't use caching, i.e. dynamic programming):
http://functionspace.com/articles/32/Fibonacci-series-and-Dynamic-programming

A: It looks like you could use a series of breadth-first searches to find the regions of connected asterisks.  You could modify the original array or a copy of that array as you go to mark which coordinates have already been visited, or if the proportion of asterisks is small relative to the overall board then it might be more efficient to store the visited coordinate pairs in a hash table.


text:
Q: Machine Learning Experiment Design with Small Positive Sample Set in Sci-kit Learn I am interested in any tips on how to train a set with a very limited positive set and a large negative set.
I have about 40 positive examples (quite lengthy articles about a particular topic), and about 19,000 negative samples (most drawn from the sci-kit learn newsgroups dataset). I also have about 1,000,000 tweets that I could work with.. negative about the topic I am trying to train on. Is the size of the negative set versus the positive going to negatively influence training a classifier?
I would like to use cross-validation in sci-kit learn. Do I need to break this into train / test-dev / test sets? Is know there are some pre-built libraries in sci-kit. Any implementation examples that you recommend or have used previously would be helpful.
Thanks!

A: The answer to your first question is yes, the amount by which it will affect your results depends on the algorithm. My advive would be to keep an eye on the class-based statistics such as recall and precision (found in classification_report).

*

*For RandomForest() you can look at this thread which discusses
the sample weight parameter. In general sample_weight is what
you're looking for in scikit-learn.

*For SVM's have a look at either this example or this
example.

*For NB classifiers, this should be handled implicitly by Bayes
rule, however in practice you may see some poor performances.
For you second question it's up for discussion, personally I break my data into a training and test split, perform cross validation on the training set for parameter estimation, retrain on all the training data and then test on my test set. However the amount of data you have may influence the way you split your data (more data means more options).

A: You could probably use Random Forest for your classification problem. There are basically 3 parameters to deal with data imbalance. Class Weight, Samplesize and Cutoff.
Class Weight-The higher the weight a class is given, the more its error rate is decreased.
Samplesize- Oversample the minority class to improve class imbalance while sampling the defects for each tree[not sure if Sci-kit supports this, used to be param in R)
Cutoff- If >x% trees vote for the minority class, classify it as minority class. By default x is 1/2 in Random forest for 2-class problem. You can set it to a lower value for the minority class.
Check out balancing predict error at https://www.stat.berkeley.edu/~breiman/RandomForests/cc_home.htm
For the 2nd question if you are using Random Forest, you do not need to keep separate train/validation/test set. Random Forest does not choose any parameters based on a validation set, so validation set is un-necessary.
Also during the training of Random Forest, the data for training each individual tree is obtained by sampling by replacement from the training data, thus each training sample is not used for roughly 1/3 of the trees. We can use the votes of these 1/3 trees to predict the out of box probability of the Random forest classification. Thus with OOB accuracy you just need a training set, and not validation or test data to predict performance on unseen data. Check Out of Bag error at https://www.stat.berkeley.edu/~breiman/RandomForests/cc_home.htm for further study.


text:
Q: Data in a variable address doesn't update when I change the value I try to send some data over the network. Two long value in addition to a character. I convert data to the byte form using the memcpy function in the results variable and send them over the network using a UDP connection:
#define SERVER "127.0.0.1"
#define PORT 9090

void die(char *s)
{
    perror(s);
    exit(1);
}

using namespace std ;

int main() {

    char* results = new char[17];
    nanoseconds ns = duration_cast<nanoseconds>(high_resolution_clock::now().time_since_epoch());
    long a = ns.count() ;
    long b = 1l ;
    char end = '\n';
    memcpy(results, &a, 8);
    memcpy(results + 8, &b, 8);
    memcpy(results + 16, &end, 1);

    struct sockaddr_in si_other;
    int sock ,slen=sizeof(si_other);
    if ( (sock=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
    {
        die("socket");
    }

    memset((char *) &si_other, 0, sizeof(si_other));
    si_other.sin_family = AF_INET;
    si_other.sin_port = htons(PORT);

    if (inet_aton(SERVER , &si_other.sin_addr) == 0)
    {
        fprintf(stderr, "inet_aton() failed\n");
        exit(1);
    }

    cout << "Sending data over the network ..." << endl;
    while (true) {
        ns = duration_cast<nanoseconds>(high_resolution_clock::now().time_since_epoch());
        a = ns.count() ;
        b += 1 ;
        // cout << a << endl ;
        memcpy(results, &a, 8);
        memcpy(results + 8, &b, 8);
        // cout << *((unsigned long*)results) << endl ;
        // memcpy(results + 16, &end, 1);

        if (sendto(sock, results, 17 , 0 , (struct sockaddr *) &si_other, slen)==-1)
            {
               die("sendto()");
            }
    }
}

I checked data in the destination and it's all the same with the value that has been set to variables before the while loop. The data in the results variable is updating, too, but what is sending over the network is all constant!
I guess it's because of the sendto function behavior. Can anyone help?


text:
Q: finding the mean in normal distribution I am struggling on this question where I need to find the mean given the standard deviation.
The question is the following:
A certain brand of flood lamps has a length of life that is normally distributed,
with a standard deviation of 392 hours.
If 8 % of the lamps last more than 5600 hours, what is the mean length of life?

This is what I've tried so far
let $X$ = length of light
$X\sim\mathcal{N}(\text{mean = unknown }(u), SD = 392)$
$P(X > 5600) = 0.8$
$1 - P(X < 5600) = 0.8$ (stuck after this part)
$1 - P(5600-u/392 < 5600) = 0.8$ ( incorrect)
I am having troubles working backwards to the find the mean.
Could someone point me in the right direction.

A: $$\mathbb{P}[X>5600]=8\%=0.08$$
$$\mathbb{P}[X\leq 5600]=92\%=0.92$$
that is
$$\Phi\Bigg[\frac{5600-\mu}{392}\Bigg]=0.92$$
Now using Z-table you get
$$\frac{5600-\mu}{392}=1.4051$$
that is
$$\mu=5049$$

How to read a Z-table

I used a calculator. With Paper -table you get that the quantile corresponding to the probability of $0.92$ is between $1.40$ and $1.41$, more or less exactly in the middle...

A: \begin{align}
X &\sim \mathcal{N}(\mu, 392^2) \\
P(X \le 5600) &= 0.92 \\
P \left( Z \le \frac{5600 - \mu}{392} \right) &= 0.92 \tag{normalize} \\
\mu \approx 5600 - 392 (1.41) &= 5047.28 \tag{check standard normal table}
\end{align}
P.S. My answer used $\approx$ instead of $=$ as the value is only an approximation.


text:
Q: Finding subarray with target bitwise AND value Given an array A of size N and an integer P, find the subarray B = A[i...j] such that i <= j, compute the bitwise value of subarray elements say K = B[i] & B[i + 1] & ... & B[j].
Output the minimum value of |K-P| among all possible values of K.

A: Here is a a quasilinear approach, assuming the elements of the array have a constant number of bits.
The rows of the matrix K[i,j] = A[i] & A[i + 1] & ... & A[j] are monotonically decreasing (ignore the lower triangle of the matrix). That means the absolute value of the difference between K[i,:] and the search parameter P is unimodal and a minimum (not necessarily the minimum as the same minimum may occur several times, but then they will do so in a row) can be found in O(log n) time with ternary search (assuming access to elements of K can be arranged in constant time). Repeat this for every row and output the position of the lowest minimum, bringing it up to O(n log n).
Performing the row-minimum search in a time less than the size of row requires implicit access to the elements of the matrix K, which could be accomplished by creating b prefix-sum arrays, one for each bit of the elements of A. A range-AND can then be found by calculating all b single-bit range-sums and comparing them with the length of the range, each comparison giving a single bit of the range-AND. This takes O(nb) preprocessing and gives O(b) (so constant, by the assumption I made at the beginning) access to arbitrary elements of K.
I had hoped that the matrix of absolute differences would be a Monge matrix allowing the SMAWK algorithm to be used, but that does not seem to be the case and I could not find a way to push to towards that property.

A: Are you familiar with the Find subarray with given sum problem? The solution I'm proposing uses the same method as in the efficient solution in the link. It is highly recommended to read it before continuing.
First let's notice that the longer a subarray its K will be it will be smaller, since the & operator between two numbers can create only a smaller number.
So if I have a subarray from i to j and I want want to make its K smaller I'll add more elements (now the subarray is from i to j + 1), if I want to make K larger I'll remove elements (i + 1 to j).
If we review the solution to Find subarray with given sum we see that we can easily transform it to our problem - the given sum is K and summing is like using the & operator, but more elements is smaller K so we can flip the comparison of the sums.
This problem tells you if the solution exist but if you simply maintain the minimal difference you found so far you can solve your problem as well.
Edit
This solution is true if all the numbers are positive, as mentioned in the comments, if not all the numbers are positive the solution is slightly different.
Notice that if not all of the numbers are negative, the K will be positive, so in order to find a negative P we can consider only the negatives in the algorithm, than use the algorithm as shown above.

A: Here an other quasi-linear algorithm, mixing the yonlif Find subarray with given sum problem solution with Harold idea to compute K[i,j]; therefore I don't use pre-processing which if memory-hungry. I use a counter to keep trace of bits and compute at most 2N values of K, each costing at most O(log N).  since log N is generally smaller than the word size (B), it's faster than a linear O(NB) algorithm.
Counts of bits of N numbers can be done with only ~log N words :

So you can compute  A[i]&A[i+1]& ... &A[I+N-1] with only log N operations.
Here the way to manage the counter: if

*

*counter is C0,C1, ...Cp, and

*Ck is Ck0,Ck1, ...Ckm,

Then   Cpq ... C1q,C0q is the binary representation of the number of bits equal to 1 among the q-th bit of {A[i],A[i+1], ... ,A[j-1]}.
The bit-level implementation (in python); all bits are managed in parallel.
def add(counter,x):
    k = 0
    while x :
        x, counter[k] = x & counter[k], x ^ counter[k]
        k += 1

def sub(counter,x):
    k = 0
    while x :
        x, counter[k] = x & ~counter[k], x ^ counter[k]
        k += 1

def val(counter,count):  # return A[i] & .... & A[j-1] if count = j-i.
    k = 0
    res = -1
    while count:
       if count %2 > 0 : res &= counter[k]
       else: res &= ~counter[k]
       count //= 2
       k += 1
    return res

And the algorithm :
def solve(A,P):
    counter = np.zeros(32, np.int64) # up to 4Go
    n = A.size
    i = j = 0
    K=P # trig fill buffer
    mini = np.int64(2**63-1)

    while i<n :

        if  K<P or j == n :     # dump buffer
            sub(counter,A[i])
            i += 1
        else:                   # fill buffer
            add(counter,A[j])
            j += 1

        if j>i:
            K = val(counter, count)
            X = np.abs(K - P)
            if mini > X: mini = X
        else : K = P            # reset K

    return mini

val,sub and add are O(ln N) so the whole process is  O(N ln N)
Test :
n = 10**5
A = np.random.randint(0, 10**8, n, dtype=np.int64)
P = np.random.randint(0, 10**8, dtype=np.int64)

%time solve(A,P)
Wall time: 0.8 s
Out: 452613036735

A numba compiled version (decorate the 4 functions by @numba.jit) is 200x faster (5 ms).

A: Yonlif answer is wrong.
In the Find subaray with  given sum solution we have a loop where we do substruction.
while (curr_sum > sum && start < i-1)
    curr_sum = curr_sum - arr[start++];

Since there is no inverse operator of a logical AND, we cannot rewrite this line and we cannot use this solution directly.
One would say that we can recalculate the sum every time when we increase the lower bound of a sliding window (which would lead us to O(n^2) time complexity), but this solution would not work (I'll provide the code and counter example in the end).
Here is brute force solution that works in O(n^3)
unsigned int getSum(const vector<int>& vec, int from, int to) {
    unsigned int sum = -1;
    for (auto k = from; k <= to; k++)
        sum &= (unsigned int)vec[k];
    return sum;
}

void updateMin(unsigned int& minDiff, int sum, int target) {
    minDiff = std::min(minDiff, (unsigned int)std::abs((int)sum - target));
}

// Brute force solution: O(n^3)
int maxSubArray(const std::vector<int>& vec, int target) {
    auto minDiff = UINT_MAX;
    for (auto i = 0; i < vec.size(); i++)
        for (auto j = i; j < vec.size(); j++)
            updateMin(minDiff, getSum(vec, i, j), target);
    return minDiff;
}

Here is O(n^2) solution in C++ (thanks to B.M answer) The idea is to update current sum instead calling getSum for every two indices. You should also look at B.M answer as it contains conditions for early braak. Here is C++ version:
int maxSubArray(const std::vector<int>& vec, int target) {
    auto minDiff = UINT_MAX;
    for (auto i = 0; i < vec.size(); i++) {
        unsigned int sum = -1;
        for (auto j = i; j < vec.size(); j++) {
            sum &= (unsigned int)vec[j];
            updateMin(minDiff, sum, target);
        }
    }
    return minDiff;
}

Here is NOT working solution with a sliding window: This is the idea from Yonlif answer with the precomputation of the sum in O(n^2)
int maxSubArray(const std::vector<int>& vec, int target) {
    auto minDiff = UINT_MAX;
    unsigned int sum = -1;
    auto left = 0, right = 0;

    while (right < vec.size()) {
        if (sum > target)
            sum &= (unsigned int)vec[right++];
        else
            sum = getSum(vec, ++left, right);
        updateMin(minDiff, sum, target);
    }
    right--;
    while (left < vec.size()) {
        sum = getSum(vec, left++, right);
        updateMin(minDiff, sum, target);
    }
    return minDiff;
}

The problem with this solution is that we skip some sequences which can actually be the best ones.
Input: vector = [26,77,21,6], target = 5.
Ouput should be zero as 77&21=5, but sliding window approach is not capable of finding that one as it will first consider window [0..3] and than increase lower bound, without possibility to consider window [1..2].
If someone have a linear or log-linear solution which works it would be nice to post.

A: Here is a solution that i wrote and that takes time complexity of the order O(n^2).
The below code snippet is written in Java .
class Solution{
    public int solve(int[] arr,int p){
        int maxk = Integer.MIN_VALUE;
        int mink = Integer.MAX_VALUE;
        int size = arr.length;

        for(int i =0;i<size;i++){
            int temp = arr[i];
            for(int j = i;j<size;j++){
                temp &=arr[j];
                if(temp<=p){
                    if(temp>maxk)
                        maxk = temp;
                }
                else{
                    if(temp < mink)
                        mink = temp;
                }
            }
        }
        int min1 = Math.abs(mink -p);
        int min2 = Math.abs(maxk -p);
        return ( min1 < min2 ) ? min1 : min2;
    }
}

It is simple brute force approach where 2 numbers let us say x and y , such that x <= k and y >=k are found where x and y are some different K = arr[i]&arr[i+1]&...arr[j] where i<=j for different i and j for x,y .
Answer will be just the minimum of |x-p| and |y-p| .

A: This is a Python implementation of the O(n) solution based on the broad idea from Yonlif's answer. There were doubts about whether this solution could work since no implementation was provided, so here's an explicit writeup.
Some caveats:

*

*The code technically runs in O(n*B), where n is  the number of integers and B is the number of unique bit positions set in any of the integers. With constant-width integers that's linear, but otherwise it's not generally linear in actual input size. You can get a true linear solution for exponentially large inputs with more bookkeeping.

*Negative numbers in the array aren't handled, since their bit representation isn't specified in the question. See the comments on Yonlif's answer for hints on how to handle fixed-width two's complement signed integers.

The contentious part of the sliding window solution seems to be how to 'undo' bitwise &. The trick is to store the counts of set-bits in each bit-position of elements in your sliding window, not just the bitwise &. This means adding or removing an element from the window turns into adding or removing 1 from the bit-counters for each set-bit in the element.
On top of testing this code for correctness, it isn't too hard to prove that a sliding window approach can solve this problem. The bitwise & function on subarrays is weakly-monotonic with respect to subarray inclusion. Therefore the basic approach of increasing the right pointer when the &-value is too large, and increasing the left pointer when the &-value is too small, will cause our sliding window to equal an optimal sliding window at some point.
Here's a small example run on Dejan's testcase from another answer:
A = [26, 77, 21, 6], Target = 5

Active sliding window surrounded by []

[26], 77, 21, 6
left = 0, right = 0, AND = 26

----------------------------------------
[26, 77], 21, 6
left = 0, right = 1, AND = 8

----------------------------------------
[26, 77, 21], 6
left = 0, right = 2, AND = 0

----------------------------------------
26, [77, 21], 6
left = 1, right = 2, AND = 5

----------------------------------------
26, 77, [21], 6
left = 2, right = 2, AND = 21

----------------------------------------
26, 77, [21, 6]
left = 2, right = 3, AND = 4

----------------------------------------
26, 77, 21, [6]
left = 3, right = 3, AND = 6

So the code will correctly output 0, as the value of 5 was found for [77, 21]
Python code:
def find_bitwise_and(nums: List[int], target: int) -> int:
    """Find smallest difference between a subarray-& and target.
    Given a list on nonnegative integers, and nonnegative target
    returns the minimum value of abs(target - BITWISE_AND(B))
    over all nonempty subarrays B

    Runs in linear time on fixed-width integers.
    """

    def get_set_bits(x: int) -> List[int]:
        """Return indices of set bits in x"""
        return [i for i, x in enumerate(reversed(bin(x)[2:]))
                if x == '1']

    def counts_to_bitwise_and(window_length: int,
                              bit_counts: Dict[int, int]) -> int:
        """Given bit counts for a window of an array, return
        bitwise AND of the window's elements."""

        return sum((1 << key) for key, count in bit_counts.items()
                   if count == window_length)

    current_AND_value = nums[0]
    best_diff = abs(current_AND_value - target)

    window_bit_counts = Counter(get_set_bits(nums[0]))

    left_idx = right_idx = 0
    while right_idx < len(nums):

        # Expand the window to decrease & value
        if current_AND_value > target or left_idx > right_idx:
            right_idx += 1
            if right_idx >= len(nums):
                break
            window_bit_counts += Counter(get_set_bits(nums[right_idx]))

        # Shrink the window to increase & value
        else:
            window_bit_counts -= Counter(get_set_bits(nums[left_idx]))
            left_idx += 1

        current_AND_value = counts_to_bitwise_and(right_idx - left_idx + 1,
                                                  window_bit_counts)

        # No nonempty arrays allowed
        if left_idx <= right_idx:
            best_diff = min(best_diff, abs(current_AND_value - target))

    return best_diff


text:
Q: HTML background fade color once I need to highlight a div with a text value to show users when a value in a cell has changed. I need the background to change color from red to white. I need it to do this once for values that have changed on page load and then remain white. What's the simplest way to accomplish this?

A: As far as I understood you have a div whose color should be changed after page has been totally loaded.

*

*So first thing to do it, you can set initial color to that div, so that when your page is loaded it will have red color

*Next using JQuery code
//This will change color of your div when everything has been totally loaded (text,images, etc.)

window.onload = function(){ $('YOUR DIV').css('color',white);}

Hope it will help you

A: One way to do that

$('input[type=button]').click( function() {
 $('#newContent').addClass('backgroundAnimated');
});
@-webkit-keyframes fadeIt {
  0%   { background-color: #FFFFFF; }
  50%  { background-color: #AD301B; }
  100% { background-color: #FFFFFF; }
}
@-moz-keyframes fadeIt {
  0%   { background-color: #FFFFFF; }
  50%  { background-color: #AD301B; }
  100% { background-color: #FFFFFF; }
}
@-o-keyframes fadeIt {
  0%   { background-color: #FFFFFF; }
  50%  { background-color: #AD301B; }
  100% { background-color: #FFFFFF; }
}
@keyframes fadeIt {
  0%   { background-color: #FFFFFF; }
  50%  { background-color: #AD301B; }
  100% { background-color: #FFFFFF; }
}

.backgroundAnimated{
    background-image:none !important;
    -webkit-animation: fadeIt 5s ease-in-out;
       -moz-animation: fadeIt 5s ease-in-out;
         -o-animation: fadeIt 5s ease-in-out;
            animation: fadeIt 5s ease-in-out;
}

old value

New value

<input type="button" value="test" />


text:
Q: Decay Feynman diagram $$D^0 \to K^+ +\pi^- + \pi^0 + \pi^0$$ cannot occur by first order weak interactions. Could anybody help me confirm this? What I currently have is that the initial charm goes to anti-strange and the anti-up goes to anti-down, both through the $W$ boson.

A: Is there something wrong with this process? (it will admittedly be suppressed by $|V_{su}|^2\approx \frac{1}{20}$, i.e. "doubly cabbibo suppressed")

or maybe even replace the Z boson with gluons.


text:
Q: Proving an example doesn't violate the Dominated Convergence Theorem I just worked through the following example from Shreve's Stochastic Calculus for Finance.

For each positive integer $n$, define $f_n$ to be the normal density
with mean $0$ and variance $n$, i.e.,
$$f_n(x)=\frac{1}{\sqrt{2n\pi}}e^{-\frac{x^2}{2n}}\text{.}$$

He defines $f(x) = \lim_{n \to \infty} f_n(x)$. Then he poses the problem

(iii) Note that
$$ \lim_{n \to \infty} \int _{-\infty} ^{\infty} f_n(x)\, dx \neq \int_{-\infty}^{\infty}f(x)\,dx\text{.}$$
Explain why this does not violate the Monotone Convergence Theorem,
Theorem 1.4.5.

It's easy to see that these functions aren't monotonically decreasing, so the assumptions for the Monotone Convergence Theorem aren't satisfied. I now want to understand why this example does not violate the Dominated Convergence Theorem. I believe that it suffices to show that
$$\int_{-\infty}^{\infty} \sup_{n \in \mathbb{N}} f_n(x) \, dx \nless \infty \text{.}$$
I have two questions about this.

*

*Can you confirm, yes or no, that the above (essentially) proves the $f_n$ do not satisfy the assumption of the Dominated Convergence Theorem?

*Do you have an explanation for why the above display is true? A proof is preferable, the details aren't important.

A: Hint: Let $x>1$. $\sup_n f_n(x)\geq f_{[x^{2}]}(x)$ where $[,]$ is the greatest integer function. $f_{[x^{2}]}(x) \geq \frac  1 {(2\pi)^{1/2} |x|}e^{-x^{2}/2[x^{2}]}$. Note that  $x^{2}/[x^{2}] \to 1$ as $x \to \infty$. Conclude that $\int_0^{\infty} \sup_n f_n(x)dx=\infty$.


text:
Q: XSLT | SAXON | Creating legitimate extension namespace I searched google I looked at books and I'm still puzzeled. How do I create real working extension for XSLT2.0 that can be served online. Some guidance is much appreciated.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"

    xmlns:my="http://my.working.url.which.serves.the.extension"

    exclude-result-prefixes="xs"
    version="2.0">
</xsl:stylesheet>

Solutions with pseudo namespace inside the current scope are not welcome. I'm looking for information about creating legitimate extension such as exslt was for XSLT 1.0

A: Neither with XSLT 1.0 nor with 2.0 nor with EXSLT the namespace URL used loads any code from the domain given in the URL, rather the implementation of the XSLT processor implements the extension. With some extension you can implement them in XSLT itself and then you can xsl:import or xsl:include to module with the extension. In some cases it is also possible to implement an extension function using a processor specific implementation in a different language (Java, Javascript, C#, VB, PHP) but the code is then also included in an XSLT module or in an additional library to the XSLT processor, it is not served from a URL.


text:
Q: What is the Semantics of this Notation: admin.auth.UserInfo? I am struggling with the docs for Firebase, Google Cloud etc. I notice I often get stuck on this notation. There must be something I do not know about it or have forgotten.
For example this page admin.auth.UserInfo tells me I can get info about the user (email etc). But after reading the page I still don't know how. What am I missing?
PS: I believe I know that admin comes from this but it does not help me:
const admin = require("firebase-admin");

A: When using the Admin SDK, to get information about a user, call admin.auth().getUser(uid).  An example is provided in the documentation.
getUser() returns a UserRecord.  It contains an number of properties, including providerData, which is an array of UserInfo.
Each client SDK provides methods to obtain the UID of an authorized user.  For example, on Android it's FirebaseAuth.getInstance().getCurrentUser().getUid() (example here).
The UID of each user for a project is available in the Authorization panel of the Firebase Console.

A: In your example you are reading the documentation of an interface. It defines what UserInfo has.
If you want to access to a method, for example for reading userInfo, first you have to access to auth service using admin.auth().<method>.
If you want more info about how to use it, see https://firebase.google.com/docs/reference/admin/node/admin.auth.Auth


text:
Q: Immediate Function Definition inside a Module In mathematica, it is possible to perform immediate definition of a function where the dependent variable is not explicitly mentioned on the RHS. For example:
f1[xval_] := yval xval;
f2[xval_, yval_] = f1[xval] (*Immediate definition since cant use delayed due to yval*);
f2[10, 20]

One obtains the desired output of 200. However, if I try to do the same in Module, the behavior is quite different:
ff[x1_, y1_] := Module[{x = x1, y = y1, f1, f2, yval},
 f1[xval_] := yval xval;
 f2[xval_, yval_] = f1[xval];
 f2[x1, y1]];
ff[10, 20]

When I try to run this, the output of ff[10,20] is 10 yval$166783 instead of 200. I was wondering if there a way to get the same behavior that one gets without a module in this case? Of course, one solution is to use yval as the dependent variable of f1 i.e. f1[xval,yval] instead of just f1[xval]. However, I have several lines of code before the definition of f2 and adding yval as the dependent variable for each such line will involve too much effort.


text:
Q: how to stop ajax modal popup from closing in an update panel that is running a timer I have an asp update panel that contains a repeater with items bound to a dataset showing the names of tables on which a particular sql query is about to run. For each item in the repeater I also show the status of the query (Waiting/Running/Completed), when the query started, and when the query finished.
When the user presses a run button, each table is queried in turn, and the status/start time/end time are all updated to give the user feedback as to where the queries are up to. This is all achieved using asp:timer and asp:AsyncPostBackTrigger. As each query finishes a "data preview" button is also unhidden that opens an ajax modal popup box to show the data extracted.
My issue is that if a user presses the data preview button whilst the timer is still running, the popup opens and then immediately closes. Once all queries have finished and the timer is closed, all is fine - but I would like the user to be able to able to preview the results of each query at the point they finish.
I have found on other forums the suggestion to move the modal popup box out of the update panel, but then I can't find a way to link the repeater buttons to the popup controls.
Any ideas?
ASPX page extract:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

<asp:Timer runat="server" ID="Timer1" Interval="1000" Enabled="false" ontick="Timer1_Tick" />

<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always">
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
    </Triggers>
    <ContentTemplate>
        <asp:ImageButton ID="Export" ImageUrl='/Stock/Some.png' runat="server" Enabled="False" Visible="False" />

        <asp:Repeater ID="rptTbl" runat="server">

            <HeaderTemplate>

Querying Tables:

                            Table Name

                            Status

                            Query Start

                            Query End

                            Preview Data

            </HeaderTemplate>

            <ItemTemplate>

                        <asp:Label ID="TblData" runat="server" Text='<%# Eval("table_name") %>'></asp:Label>

                        <asp:Image ID="LoadingImg" runat="server" ImageUrl="~/Stock/Spinner.gif" Visible="False" Height="20px" /><asp:Label ID="LoadingLabel" runat="server" Text='Please Wait...'></asp:Label>

                        <asp:Label ID="lblQuerySart" runat="server" Text=''></asp:Label>

                        <asp:Label ID="lblQueryEnd" runat="server" Text=''></asp:Label>

                        <asp:ImageButton ID="BtnViewData" runat="server" AlternateText="Preview Data..." OnCommand="BtnViewData_Click" CommandArgument='<%# Eval("table_name") %>' CausesValidation="False" BorderStyle="Solid" BorderWidth="1px" ImageAlign="AbsMiddle" Height="20px" ImageUrl="~/Stock/Some.png" Visible="False" Enabled="False" />

                        <ajaxToolkit:modalpopupextender
                        id="MPE_ShowData" runat="server"
                        cancelcontrolid="ButtonDeleteCancel" okcontrolid="ButtonDeleleOkay"
                        targetcontrolid="BtnViewData" popupcontrolid="DivShowData"
                        backgroundcssclass="ModalPopupBG">
                        </ajaxToolkit:modalpopupextender>

                        <ajaxToolkit:confirmbuttonextender id="CBE_ShowData"
                        runat="server" targetcontrolid="BtnViewData" enabled="True"
                        displaymodalpopupid="MPE_ShowData">
                        </ajaxToolkit:confirmbuttonextender>

            </ItemTemplate>
            <FooterTemplate>

            </FooterTemplate>
        </asp:Repeater>

    </ContentTemplate>
</asp:UpdatePanel>

<asp:panel class="popupConfirmation" id="DivShowData"
    style="display: none" runat="server" ScrollBars="Auto" Height="70%" Width="70%" BackColor="Gray">

                Show The Data

                This is where the data appears!

            <input id="ButtonDeleleOkay" type="button" value="Okay" />
            <input id="ButtonDeleteCancel" type="button" value="Cancel" />

</asp:panel>


text:
Q: WebActivator is not working with Orchard I have current version of Orchard CMS 1.6.1 and WebActivator 2.0.1.
Default installation of Orchard. WebActivator PreApplicationStartMethod is not fired.
In the same solution I have sample MVC application and the same WebActivator code works fine.
What is wrong with Orchard app. Is it breaks standard ASP.NET pipeline?
Sample code (I've used both Pre and PostApplicationStartMethod):
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(Go2See.Web.App_Start.LocalizationServiceStarter), "PreStart")]
namespace Go2See.Web.App_Start
{
    public static class LocalizationServiceStarter
    {
        public static void PreStart()
        {
            throw new ApplicationException("x");
        }
    }
}


text:
Q: Prove by induction that $2^{4^n}+5$ is divisible by 21 . After I did the first two steps in the induction , I am stuck in the last step ; to prove for $n+1$ that $2^{4^n}+5$ is divisible by $21$ , so
I know that $2^{4^n}+5$ is divisible by $21$ is true .
I want to prove for $n+1$ ( $n$ is natural ):
$$2^{4^{n+1}}+5=$$ $$=2^{4^{n}\cdot 4}+5=$$ $$=2^{4^{n}\cdot 4}+5=$$ $$=2^{{4}^{{4}^{n}}}+5=$$ $$=16^{{4}^{n}}+5.$$
this is the last step I reached , I would be happy to get some recommendation on how to continue from here .

A: Hint:
The statement is equivalent to $2^{4^n} = -5 + 21k$ for some $k\in\mathbb Z$. Then raise both sides to the $4$'th power. (Looks cleaner with modular arithmetic if you know it).

A: We have that $2^{4^n}+5\equiv 0 \mod 21 \implies 2^{4^n}\equiv -5 \mod 21$ then for the induction step use that
$$2^{4^{n+1}}+5\equiv(2^{4^{n}})^4+5 \equiv(-5)^4+5\equiv (25)^2+5 \equiv 16+5\equiv0 \mod 21$$

A: $2^{4^n}+5$ is divisible by $21$ iff $2^{4^n} \equiv -5 \equiv 16 = 2^4 \bmod 21$.
Let $a_n = 2^{4^n}$. Then $a_{n+1} = a_n^4$.
Thus, to make the induction work, it is enough to prove the $(2^4)^4 \equiv 2^4 \bmod 21$, which is immediate.

A: In $\mod (25)$
$$2^{4^n}\equiv -5 \implies 2^{4^{n+1}}\equiv (-5)^4= 625 $$
$$625+5 = 630 = 21(30)$$


text:
Q: How can i add another authentication parameter to Spring Security authentication login_security_check? I am working with Spring security authentication but I cannot seem to find where the credentials are being authenticated. I need to add the functionality to authenticate using username + password + isEnabled parameter. Where does the login_security_check take place? and how can I edit this?

A: Database-backed UserDetailsService for authentication with Spring Security has a method named loadUserByUsername().
This method can be overridden to customize the process of finding the user at the time on login.
You can add the code to check if the user is enabled or not in this method.
For learning more about this check the link.
https://www.baeldung.com/spring-security-authentication-with-a-database


text:
Q: Installing openssl 3.0.5 in windows 10 using CMake externalproject failing due to config.com file I was trying to install openssl in external project using CMake in ubuntu , android and Windows. Its working fine in ubuntu . but in windows , Its failing with the following line
  Performing configure step for 'openssl_external'
  This version of D:\17-6-2022\main\src\external\openssl\config.com is not compatible with the version of Windows you're running. Check your computer's system information and then contact the software publisher.

Looks like the issue is with the config.com file is not supported in windows 10. Not sure how to fix it since the above error might come with architecture change . my system is windows 64 and this openssl 3.0.5 is creating lib64 folders in my ubuntu.
I have added the CMake command for configure and install below:
set(OPENSSL_INSTALL_DIR ${CMAKE_BINARY_DIR}/install)
set(OPENSSL_INCLUDE_DIR ${OPENSSL_INSTALL_DIR}/include)
set(OPENSSL_LIB_DIR ${OPENSSL_INSTALL_DIR}/lib)
set(OPENSSL_DATA_DIR ${OPENSSL_INCLUDE_DIR}/openssl-data)
set(OPENSSL_CONFIGURE_COMMAND ${CMAKE_CURRENT_LIST_DIR}/config)

 ExternalProject_Add(
      openssl_external
      PREFIX openssl
      SOURCE_DIR "${CMAKE_CURRENT_LIST_DIR}"
      CONFIGURE_COMMAND ${OPENSSL_CONFIGURE_COMMAND}
      --prefix=${OPENSSL_INSTALL_DIR}
      --openssldir=${OPENSSL_DATA_DIR}
      --libdir=${OPENSSL_LIB_DIR}
      no-shared
      BUILD_COMMAND make
      TEST_COMMAND ""
      INSTALL_COMMAND make install
      INSTALL_DIR ${OPENSSL_INSTALL_DIR}
      BUILD_IN_SOURCE 0)

A: I have used config as configure command in the above example. but ./config script is a legacy script by Openssl team which is used on 1.x versions. This only supports Unix based OS. because of that its not working well with windows OS for mycase.
(IDK why Openssl team is still keeping it.)
For latest versions its recommended to use Configure script . this works fine in both windows(perl Configure) and unix(./Configure)


text:
Q: Adobe flash player 32 game performance is strange So I don't know if this question belongs here, but I will ask it anyway.
So this flash game is a .exe file and can only be played in Adobe flash player 32. This game is locked at 30 fps. (There is a .swf file.)
In idle on 1080p with low-quality settings, the game uses about 22% of my CPU The game gives me a steady 30fps.
In actual gameplay with the same settings. I still get a steady 30 fps. about 30% CPU
changing the quality settings to medium gives me this:
In idle, CPU 29%, I get 30 fps with dips to 25 fps.
gameplay, CPU 40%, I get around 15 fps.
Why is this happening? My CPU is a i7-7700HQ. What can I do to get a better framerate?


text:
Q: error C2065: 'MF_BITMAP' : undeclared identifier - Windows CE 6.0 I have added a bitmap in to menu in the following way,
HBITMAP bmSeparator = LoadBitmap(g_hInstance, MAKEINTRESOURCE(IDB_LINE));
fOK = AppendMenu(hmenu, MF_BITMAP,IDM_LINE,(LPCTSTR)bmSeparator);

While compiling the code, I got the below error,
error C2065: 'MF_BITMAP' : undeclared identifier

is "MF_BITMAP" not available for Win CE?

A: Indeed, MF_BITMAP is not supported for WinCE.  See the documentation for AppendMenu.


text:
Q: Force Page Break with Syncfusion Essentials HTML to PDF Conversion I have been converting HTML to PDF using the Syncfusion.HtmlConverter.HtmlToPdfConverter class, which produces great results as long as you use the Webkit rendering engine, but I have not been able to get it to properly honor page breaks.  Syncfusion documents an older class, HtmlConverter, and suggests utilizing
 which requires you to set the AutoDetectPageBreak property to true.
The problem is that the newer class does not contain this property.  Does anyone know the proper way to enforce page breaks using HtmlToPdfConverter?

A: As it turns out, the documentation is almost correct.  If you pass
 as they suggest it will page break, but add a huge space after the break.  However if you use:

It honors the break properly (and automatically) without the need for setting any properties on the conversion object.  This is as of version 14.2450.


text:
Q: UITableViewCell Delete button animation I've noticed that in iOS8 default insertion/deletion control has a specific animation from top-left corner:

However in iOS9 that animation is gone.
Do you know anything about it? Has it changed between iOS versions indeed? Any way of customizing it?
Thanks.

A: It is still there.
Check the attachment right side left swipe


text:
Q: Windows 8 turns program sound volume down randomly I recently upgraded to Windows 8 from Win 7 64 bit and have started to encounter a strange issue.
When I have any program running which plays sound, such as a game or spotify, after a random interval (usually around 5-10 minutes) the program sound will set itself really low.
If I Alt-Tab to the desktop and check the Mixer I can see that the Application volume has automatically set itself really low - the other volume levels (i.e. the Device speakers) stay the same.  I'm able to just set the application volume back to a reasonable level and it stays that way for another 5 - 10 minutes then goes quiet again.
My sound is Realtek High Definition Audio and my machine is an Acer Aspire 5738G if that helps in any way.
Any help much appreciated!

A: This is often caused by Windows thinking (often incorrectly) you are running an application that uses a microphone/telephony, and lowers other sounds for you.
Try the following to disable this behavior:

*

*In the Start menu, search in the Settings category (Win+W)for "Change Sound Card Settings".

*In the Communications tab, change "When Windows detects communications activity" to Do nothing.

A: Similar to mtone and danijar, I had this issue with a something that was modifying the volume in an attempt to keep it constant. It was a program called "Dolby Digital Plus" which has an option called "Volume Leveler". I opted to turn the whole program off tho - problem solved!
I did notice lots of my music had very different volumes, but I go through them and change their volume as I come across them.


text:
Q: rsync - copy files to another server I have more than 500 Mp4 files in my server 1
so i want half of them to send to server 2 and half of them to server 3
but i dont know how to make this
Is there a way to select files by alphabet or maybe date or something else
example videos that start with
 a,c,e*.mp4

will send to server 2  and videos that start with
 b,d,f*.mp4

will send to server 3
or is there any other way you think is better
rsync -avzP /home/user/public_html/domain.com/ ip:/home/user2/public_html/domain.com/

A: 1) use find to make a list of all the files
find /opt/mymp3folder -print > /tmp/foo

2) find the count of lines and split the list in two
cd /tmp
wc -l /tmp/foo
387
split -l 200 /tmp/foo

3) split by default makes a set of files called xaa xab xac etc.  So use xaa to copy to one server and xab to copy to the other
rsync -av --files-from=/tmp/xaa . server1:/opt/newmp3folder/
rsync -av --files-from=/tmp/xab . server2:/opt/newmp3folder/

'.' in the above is the "source" path and allows the use of relative paths in the "files-from" You either need to be in the same path that the find command is run from and use . or set it to an absolute value
Obviously if you wanted to do this on a regular basis probably want to script it properly

A: 1) use find to make a list of all the files
find /opt/mymp3folder -print > /tmp/foo

2) find the count of lines and split the list in two
wc -l /tmp/foo

387
    split -l 200 /tmp/foo
mv xaa xaa.txt

and then rsync like this
 rsync -avzP -e ssh `cat xaa.txt` root@0.0.0.0:/var/www/

A: I think that is better to split files by size than for numbers (I assume that you have several file sizes in your mp4).
#!/bin/bash
FOLDER=$1
TMP_FILE=$(mktemp)

find  $FOLDER -type f -exec stat -c "%s;%n" {} \; | sort -t ';' -k 2 | awk 'BEGIN{ sum=0; FS=";"} { sum += $1; print sum";"$1";"$2 }' > $TMP_FILE
TOTAL_SIZE=$(tail -n 1 $TMP_FILE | cut -f 1 -d ';')
HALF_SIZE=$(echo $TOTAL_SIZE / 2 | bc)
echo $TOTAL_SIZE $HALF_SIZE

# split part
IFS=';'
while read A B C ; do
    [ $A -lt $HALF_SIZE ] && echo "$C" >> lst_files_1.txt || echo "$C" >> lst_files_2.txt
done  < $TMP_FILE
rsync -avzP
rm $TMP_FILE

After execution you have list_files_1.txt and list_files_2.txt that contains half of files depending of size.
You can send this files to each server using rsync:
rsync -avzP $(cat list_files_1.txt) ip:/home/user2/public_html/domain.com/


text:
Q: module 'tsfresh.feature_extraction.feature_calculators' has no attribute I'm new using tsfresh, when I use the following lines, I get the extracted feature as desired
import numpy as np
import pandas as pd
from tsfresh.feature_extraction import ComprehensiveFCParameters
from tsfresh import extract_features

df = pd.DataFrame(np.array([[1, 2, 3, 4],[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]),
                       columns=['Context ID','Time Elapsed', 'time_serie A', 'time_serie B'])

settings = ComprehensiveFCParameters()
kind_to_fc_parameters = {
        "time_serie A": {},
        "time_serie B": {"mean": None}
    }

extract_features = extract_features(df,  kind_to_fc_parameters =kind_to_fc_parameters,
                     column_id='Context ID', column_sort="Time Elapsed")

extract_features

However, when I change {"mean": None} by {"absolute_maximum": None} or "count_above": [{"t": 0.05}] it'won't work anymore:

module 'tsfresh.feature_extraction.feature_calculators' has no
attribute 'absolute_maximum'

What do I miss ?

A: I just had a similar issue with another calculation I chose and found it's just not in the feature_calculators.py (you can open it from yourdirectory\Python\Python37\Lib\site-packages\tsfresh\feature_extraction), so I did pip install tsfresh -U in terminal to get the latest tsfresh, checked feature_calculators.py again, my desired function is there and code runs fine then.


text:
Q: Помогите правильно организовать запрос SQL Помогите правильно организовать запрос SQL
 $sqlstr = "INSERT INTO `manufacturer` SET
              `manufacturer_id` ='$val[vendorID]',
              `name`='$val[name]'";
        db_query($sqlstr);

в значениях массива $val[name] попадаются названия которые содержат знак '   вот пример  Daddy's Big Top
что нужно сделать что бы такой запрос обработался когда в слове попадается такой символ?

A: в итоге это получилось сделать так
$test = addcslashes($val['name'] , "'" );
$sqlstr = "INSERT INTO `manufacturer` SET `manufacturer_id` ='$val[vendorID]',`name`='$test'";


text:
Q: How to write __init__ method inheriting two classes? I have 3 class in my program. Base, Sub_1 and Sub2. Sub_1 inherits from Base and Sub_2 inherits from QThread and Base.
Base class has some pyQtSignal properties which I want other two classes to have. Now I have problem instantiating class Sub_2. When I run this code I get the following error:
QObject::connect: No such signal Sub_2::signal_1()
Traceback (most recent call last):
  File "main.py", line 31, in <module>
    win = MainWindow()
  File "main.py", line 25, in __init__
    self.worker.signal_1.connect(lambda: print('ok 1'))
TypeError: connect() failed between Base.signal_1[] and unislot()

main.py:
from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5.QtCore import QObject, pyqtSignal, QThread

class Base(QObject):
    signal_1 = pyqtSignal()
    signal_2 = pyqtSignal()

    def __init__(self):
        super(QObject, self).__init__()

class Sub_1(Base):
    def __init__(self):
        super().__init__()

class Sub_2(QThread, Base):
    def __init__(self):
        super().__init__()

class MainWindow(QMainWindow):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.worker = Sub_2()
        self.worker.signal_1.connect(lambda: print('ok 1'))
        self.worker.signal_2.connect(lambda: print('ok 2'))

import sys
app = QApplication(sys.argv)
win = MainWindow()
win.show()
sys.exit(app.exec_())

A: There is no guarantee that QThread.__init__ properly supports multiple inheritance. The call to super().__init__() in Sub2 may therefore not initialize Base as you expect. You can fix this by changing your MRO.
To change the MRO:
class Sub_2(Base, QThread):

You might want to change Base to be more explicit in its support of multiple inheritance. Instead of super(QObject, self).__init__(), write
super().__init__()


text:
Q: How can we prevent a specific element from inheriting CSS rules with * sign? I have defined this CSS rule:
*,
*::before,
*::after {
    box-sizing: border-box
}

What if we want to exclude only a specific element with this class .testim?

A: Its very simple; If I correct undertood then;
.testim,
.testim::before,
.testim::after{
  box-sizing: unset;
}

The unset CSS keyword resets a property to its inherited value if the property naturally inherits from its parent, and to its initial value if not.
More info for CSS unset value.

A: :not() is like *. It selects every element apart from the element in its brackets. (https://developer.mozilla.org/en-US/docs/Web/CSS/:not).

:not(.testim), *::before, *::after {
  box-sizing: border-box;
}

div {
  width: 200px;
  border: 20px solid black;
}

.testim {
  width: 200px;
  border: 20px solid black;
}

I am div with width: 200px and border: 20px.

I am of the class testim with width: 200px and border: 20px.


text:
Q: Duplicate symbol while invoking headers from mainwindow.h Building the following cmake project from the trivial Qt6 project below gives me the following linker error when I #include "utils.hpp" from mainwindow.h:
duplicate symbol 'get_test_map()' in:
    CMakeFiles/qt_minimal.dir/qt_minimal_autogen/mocs_compilation.cpp.o
    CMakeFiles/qt_minimal.dir/src/gui/main.cpp.o
duplicate symbol 'get_test_map()' in:
    CMakeFiles/qt_minimal.dir/qt_minimal_autogen/mocs_compilation.cpp.o
    CMakeFiles/qt_minimal.dir/src/gui/mainwindow.cpp.o
ld: 2 duplicate symbols for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

According to an answer to a similar question, having the #include "utils.hpp" in mainwindow.cpp instead solves the linker error. However, I would like the class MainWindow to call functions from external headers which requires having the include in MainWindow.h itself.
How do I fix this issue?
CMakeLists.txt
cmake_minimum_required(VERSION 3.24)
project(qt_minimal)

set(CMAKE_CXX_STANDARD 20)

find_package(Qt6 COMPONENTS Widgets REQUIRED)
set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake)
include(QtCommon)

set(GUI_SOURCE_FILES
        main.cpp
        mainwindow.cpp
        )

add_executable(${PROJECT_NAME} ${OS_BUNDLE} # Expands to WIN32 or MACOS_BUNDLE depending on OS
        ${GUI_SOURCE_FILES} ${META_FILES_TO_INCLUDE} ${RESOURCE_FILES}
        )

target_precompile_headers(${PROJECT_NAME} INTERFACE QtWidgets.h)

target_link_libraries(${PROJECT_NAME} Qt6::Widgets)

main.cpp
#include <QApplication>
#include "mainwindow.h"

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    MainWindow mainWindow;
    mainWindow.show();
    return app.exec();
}

utils.hpp
#ifndef QT_PROJECT_GUI_UTILS_HPP
#define QT_PROJECT_GUI_UTILS_HPP

#include <unordered_map>
using Map = std::unordered_map<std::string, std::string>;

Map get_test_map() {
    Map m;
    m["accountID"] = "LKH7876";
    m["BankBalance"] = "1,00,000";
    m["LoanAmt"] = "10,00,000";
    return m;
}

#endif

mainwindow.h
#ifndef mainwindow_h
#define mainwindow_h

#include <QMainWindow>
#include "utils.hpp" // <-- Offending include

namespace Ui
{
    class MainWindow;
}

class MainWindow : public QMainWindow {
    Q_OBJECT

public:
    MainWindow(QWidget *parent = 0);
    virtual ~MainWindow();

private:
    QScopedPointer<Ui::MainWindow> ui;
};

#endif

mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
        : QMainWindow(parent),
          ui(new Ui::MainWindow) {
    ui->setupUi(this);
    // do something with get_test_map()
}

MainWindow::~MainWindow() = default;

QTCommon.cmake
macro(fix_project_version)
if (NOT PROJECT_VERSION_PATCH)
    set(PROJECT_VERSION_PATCH 0)
endif()

if (NOT PROJECT_VERSION_TWEAK)
    set(PROJECT_VERSION_TWEAK 0)
endif()
endmacro()

macro(add_project_meta FILES_TO_INCLUDE)
if (NOT RESOURCE_FOLDER)
    set(RESOURCE_FOLDER src/gui/res)
endif()

if (NOT ICON_NAME)
    set(ICON_NAME AppIcon)
endif()

if (APPLE)
    set(ICON_FILE ${RESOURCE_FOLDER}/${ICON_NAME}.icns)
elseif (WIN32)
    set(ICON_FILE ${RESOURCE_FOLDER}/${ICON_NAME}.ico)
endif()

if (WIN32)
    configure_file("${PROJECT_SOURCE_DIR}/cmake/windows_metafile.rc.in"
      "windows_metafile.rc"
    )
    set(RES_FILES "windows_metafile.rc")
    set(CMAKE_RC_COMPILER_INIT windres)
    ENABLE_LANGUAGE(RC)
    SET(CMAKE_RC_COMPILE_OBJECT "<CMAKE_RC_COMPILER> <FLAGS> -O coff <DEFINES> -i <SOURCE> -o <OBJECT>")
endif()

if (APPLE)
    set_source_files_properties(${ICON_FILE} PROPERTIES MACOSX_PACKAGE_LOCATION Resources)

    # Identify MacOS bundle
    set(MACOSX_BUNDLE_BUNDLE_NAME ${PROJECT_NAME})
    set(MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION})
    set(MACOSX_BUNDLE_LONG_VERSION_STRING ${PROJECT_VERSION})
    set(MACOSX_BUNDLE_SHORT_VERSION_STRING "${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}")
    set(MACOSX_BUNDLE_COPYRIGHT ${COPYRIGHT})
    set(MACOSX_BUNDLE_GUI_IDENTIFIER ${IDENTIFIER})
    set(MACOSX_BUNDLE_ICON_FILE ${ICON_NAME})
endif()

if (APPLE)
    set(${FILES_TO_INCLUDE} ${ICON_FILE})
elseif (WIN32)
    set(${FILES_TO_INCLUDE} ${RES_FILES})
endif()
endmacro()

macro(init_os_bundle)
if (APPLE)
    set(OS_BUNDLE MACOSX_BUNDLE)
elseif (WIN32)
    set(OS_BUNDLE WIN32)
endif()
endmacro()

macro(fix_win_compiler)
if (MSVC)
    set_target_properties(${PROJECT_NAME} PROPERTIES
        WIN32_EXECUTABLE YES
        LINK_FLAGS "/ENTRY:mainCRTStartup"
    )
endif()
endmacro()

macro(init_qt)
# Let's do the CMake job for us
set(CMAKE_AUTOMOC ON) # For meta object compiler
set(CMAKE_AUTORCC ON) # Resource files
set(CMAKE_AUTOUIC ON) # UI files
endmacro()

init_os_bundle()
init_qt()
fix_win_compiler()


text:
Q: Add to Array-Form of Integer - how to show the full result? Add to Array-Form of Integer : say I have A=[1,2,3], K = 50000, I want to add those two and get A=[5,0,1,2,3],
after I add them and convert the carry to list, but somehow I can not get the full array printed :
def addToArrayForm(A, K):
    A[-1] += K
    for i in range(len(A) - 1, -1, -1):
        carry, A[i] = divmod(A[i], 10)
        if i: A[i-1] += carry
    if carry:
        B=list(str(carry))
        A=B+A

    return A

A=[1,2,3]
addToArrayForm(A, 5000)
for i in range(len(A) ):
    print (A[i])

the result shows: 1,2,3 :
but I was expecting 5,0,1,2,3, where is the problem ?

A: def add(a, k):
    return [int(j) for j in str(k + int(''.join(str(i) for i in a)))]

Example
>>> add([1,2,3], 50000)
[5, 0, 1, 2, 3]

A: The problem with your original code is that the command A = B+A doesn't do what you apparently expect.  I'm not sure, because your function returns a given value (the new, updated A), but your main program assumes that the list is changed in place.
The value you return is the one you expect.  However, it is no longer the original object A.  The expression B+A builds a new list; your local variable A is changed to point to that and returned ... where your main program ignores it.
Make a simple change:
A=[1,2,3]
A = addToArrayForm(A, 50000)    # I corrected this to 50000; you were short a 0

Output:
5
0
1
2
3

MORE PROBLEMS
Note that this is not sustainable -- you can't do additional math on this list, because you've left the elements of B as string, rather than integer.  You'll want to convert those, I think.

ANOTHER WAY ...
If you do want to alter A in place, then try pushing those digits to the start of the list, in place:
...
    if carry:
        B = list(str(carry))
        for dig in B:
            A.insert(0, int(dig))

A=[1,2,3]
addToArrayForm(A, 50000)
...

A: You could do it by converting A to an integer, adding that to K, and then replacing A in-place with the sum, this should work regardless of the number of digits in K (or A).
def addToArrayForm(A, K):
    a = 0
    for d in A:
        a = a*10 + d
    A[:] = [int(d) for d in str(a + K)]
    return A

A = [1, 2, 3]

addToArrayForm(A, 50000)

for i in range(len(A)):
    print(A[i])

Output:
5
0
1
2
3

A: class Solution:
    def addToArrayForm(self, nums: List[int], k: int) -> List[int]:
        # convert the array form into a string
        string=""
        for num in nums:
            string+=str(num)
        # add the values
        res=int(string)+k
        # res is an int but we cannot iterate over int. So we convert it to str
        return[int(x) for x in str(res)]


text:
Q: Dynamically invoke the getter of property I'm trying to get dynamically the get value of a property, however, I got an exception:
System.Reflection.TargetParameterCountException: 'Parameter count mismatch.'
object result = null;

....

MethodInfo getMethod;
if ((getMethod = p.GetGetMethod(true)) != null)
{
    var openGetterType = typeof(Func<,>);
    var concreteGetterType = openGetterType.MakeGenericType(typeResult, p.PropertyType);
    var getterInvocation = Delegate.CreateDelegate(concreteGetterType, null, getMethod);

    var value = getterInvocation.DynamicInvoke(); //exception thrown here
    if (value != null)
    {
        p.SetValue(result, value, null);
    }
}

Remarks:

*

*I'm trying to avoid using the p.GetValue() because is slow.

*As I'm trying to invoke a getter I thought that it's not necessary to pass any value to getterInvocation.DynamicInvoke()

A: I solve the problem.
I need to pass the source object to the DynamicInvoke.
var value = getterInvocation.DynamicInvoke(source)


text:
Q: Eclipse complains "No symbol table is loaded" while elf file contains debug info I am working on an STM32 processor.
Using readelf -w, tons of debug information could be extracted from my elf file. A short piece of the output is shown below:
 <1><3faf>: Abbrev Number: 30 (DW_TAG_variable)
    <3fb0>   DW_AT_name        : (indirect string, offset: 0x24e): ITM_RxBuffer
    <3fb4>   DW_AT_decl_file   : 19
    <3fb5>   DW_AT_decl_line   : 1742
    <3fb7>   DW_AT_type        : <0x3f48>
    <3fbb>   DW_AT_external    : 1
    <3fbc>   DW_AT_declaration : 1

dwarfdump also confirms debug info is available in elf file.
I am using the following software packages:
Eclipse Juno
arm-2011.03/bin/arm-none-eabi-gdb
OpenOCD and JTAG key
After producing elf file, burn it into STM32 processor, and start the debug session in Eclipse.
JTAG could be started and stopped, so I guess OpenOCD deamon is fine. Breakpoint cannot be set due to the fact "No symbol table is loaded". One thing I noticed is among the "variable/breakponts/register/modules" window, the modules tab showing the elf file loaded contains followiing details:
Type: executable
symbols: not loaded
symbol file: BuildResult.elf
In debug configuration->Startup tab, check/uncheck "Load image/Load symbols" make no difference. I am wondering how eclipse loads elf file contained symbol info into the debug process?
Any suggestions, hints, are greatly appreciated.


text:
Q: Sympy: How can I store an equation in order to solve it later numerically? Hello wonderful people,
I am building a physics model for some project. I have found a nice equation for my interest variable, but I would like to be able to solve the problem repeatedly with different parameters. What I would like to do is to save my equation as an object in a file (using pickle for example), then loading it at runtime and feed it the parameters it needs.
How would you achieve this?
With a simple example, the whole process would look like this:
(in a jupyter notebook)
import sympy as sp
import pickle

a, b, c = symbols("a b c")
eqn = sp.Eq(b + c, a) #for a real equation I would simplify it before using sympy
with open("eqn.txt") as f:
    pickle.dump(eqn, f)

and then later in the app's code:
...
with open("eqn.txt") as f:
    eqn = pickle.load(f)
b = 1
c = 2
#magic line to put b and c into the equation
a = sp.solve(eqn, a)
print(a) # 3

Implementing the whole equation directly in a function is probably not an option although I am considering how to implement it manually. It just looks really, really hard to do and if I could do it in two lines using simpy, that'd be great.
Thanks for your time!

A: with open("eqn.txt") as f:
    eqn = pickle.load(f)
b, c = 1, 2  # b,c are python symbols here
reps = dict(zip(symbols('b c'), (b, c)))  # keys are SymPy Symbols, values are 1,2
eqn = eqn.xreplace(reps) #magic line to put b and c into the equation
a = sp.solve(eqn, a)
print(a) # 3

It is important to keep in mind the distinction between b = 1 and b = Symbol('b'). The left hand side of the expressions are Python variables and on the right, an int or a SymPy Symbol, respectively. In a SymPy expression you might reference a Python variable and its value will be included in the equation:
>>> from sympy import *
>>> b = 1
>>> b + 1
2
>>> b = Symbol('b')
>>> b + 1
b + 1
>>> eq = _
>>> eq.subs(b,1)
2
>>> b=2  # assigning a new value to b does not change the object in eq
>>> eq
b + 1
>>> eq.subs(b, 2)  # i.e., eq.subs(2,2) doesn't work -- no 2 in eq
b + 1
>>> eq.subs(Symbol('b'), 2)  # replace the Symbol with value of 2 works
3

So in reps above, zipping the symbols to their corresponding values creates a mapping that can be used to do the replacement.
There is more discussion of such issues in the documentation gotchas file, but this should help with your current issue.


text:
Q: Xamarin.Forms implement Lazy Loading in CollectionView This is my CollectionView xaml file:
    <ContentPage.Content>
        <Grid>
            <StackLayout>
                <RefreshView IsRefreshing="{Binding IsRefreshing, Mode=OneWay}"
             Command="{Binding LoadRefreshCommand}">
                    <CollectionView ItemsSource="{Binding Photos}" SelectedItem="{Binding SelectedPhoto}" RemainingItemsThreshold="10" RemainingItemsThresholdReachedCommand="{Binding LoadNewPhotosCommand}" >
                        <CollectionView.ItemTemplate>
                            <DataTemplate>
                                <Frame BorderColor="#3498DB">
                                    <Grid  RowSpacing="0" ColumnSpacing="0" Padding="0">
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="*"/>
                                            <ColumnDefinition Width="3*"/>

                                        </Grid.ColumnDefinitions>
                                        <Grid.GestureRecognizers>
                                            <TapGestureRecognizer  Command="{Binding Source={x:Reference CurrentPage}, Path=BindingContext.LoadPhotosCommand}" />
                                        </Grid.GestureRecognizers>
                                        <Image Aspect="AspectFit" HeightRequest="50" Source="{Binding Url}"  Grid.Column="0"></Image>
                                        <Frame HasShadow="False" VerticalOptions="Center"  Grid.Column="1">
                                            <Label Text="{Binding Title}"></Label>
                                        </Frame>
                                    </Grid>
                                </Frame>
                            </DataTemplate>
                        </CollectionView.ItemTemplate>
                    </CollectionView>
                </RefreshView>
            </StackLayout>
            <StackLayout HorizontalOptions="CenterAndExpand" VerticalOptions="Center">
                <Frame IsVisible="{Binding IsBusy}" BorderColor="#3498DB" HasShadow="False" BackgroundColor="#eeeeee">
                    <StackLayout>
                        <ActivityIndicator IsVisible="{Binding IsBusy}" IsRunning="{Binding IsBusy}" HorizontalOptions="Center" VerticalOptions="Center"></ActivityIndicator>
                        <Label TextColor="#3498DB" Text="Loading Data, Please Wait..." HorizontalTextAlignment="Center" VerticalTextAlignment="Center" HorizontalOptions="Center" VerticalOptions="Center" IsVisible="{Binding IsBusy}"/>
                    </StackLayout>
                </Frame>
            </StackLayout>
        </Grid>
    </ContentPage.Content>

This is the constructor in the ViewModel:
        public MainPageViewModel()
        {
            LoadPhotosCommand = new Command(execute: async () => await ExecuteGetAllPhotos());
            LoadRefreshCommand = new Command(execute: async () => await ExecuteRefreshGetAllPhotos());
            LoadRefreshCommand = new Command(execute: async () => await ExecuteGetNewPhotos());
            Photos = new ObservableCollection<Photo>();
            PhotosModel = new PhotosModel();
            SelectedPhoto = new Photo();
        }

This is the code in the ViewModel how i get the data:
        async Task ExecuteGetAllPhotos()
        {
            if (IsBusy)
                return;
            try
            {
                IsBusy = true;
                Photos.Clear();
                PhotosModel = await InstagramCloneDataStore.GetAllPhotos();
               if(PhotosModel!=null)
                {
                    foreach (var photo in PhotosModel.Photos)
                    {
                       Photos.Add(photo);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                var msg = ex.Message;
            }
            finally
            {
                IsBusy = false;
            }
        }

This code work perfectly fine when a read 100,200,500 data entries.But when i read 5000 data entries the app got freezed and want to make a force stop. It wait about 2-3minutes to show the data. So i want to implement some logic for Lazy loading or Infinity scrolling.
This is the command functionfor RemainingItemsThresholdReachedCommand and logic should be writen for scrolling data:
        async Task ExecuteGetNewPhotos()
        {
            if (IsBusy)
                return;
            try
            {
//some logic here---------->
                IsBusy = true;
                Photos.Clear();
                PhotosModel = await InstagramCloneDataStore.GetAllPhotos();
                if (PhotosModel != null)
                {
                    foreach (var photo in PhotosModel.Photos)
                    {
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                var msg = ex.Message;
            }
            finally
            {
                IsBusy = false;
            }
        }

I don't understand how lazy loading or scrolling working. Can someone help?

A: When your page loads, you should call your service to load the first X rows of data.  Let's say that X=50 - it can be whatever value you want.
When the user scrolls to the bottom of the list, CollectionView will fire RemainingItemsThresholdReachedCommand.  When this fires, you should fetch the next X number of items from your service and add them to your ItemsSource.
For this to work, your service needs to be capable of incrementally loading data.


text:
Q: Looking for a way to get HTTP Digest Authentication headers from incoming http requests I've been working on a REST implementation with my existing Cake install, and it's looking great except that I want to use HTTP Digest Authentication for all requests (Basic Auth won't cut it).  So great, I'll generate a header in the client app (which is not cake) and send it to my cake install.  Only problem is, I can't find a method for extracting that Digest from the request...
I've looked through the Cake API for something that I can use to get the Digest Header.  You'd think that Request Handler would be able to grab it, but I can't find anything resembling that.
There must be another method of getting the digest that I am overlooking?
In the meantime I'm writing my own regex to parse it out of the Request...  once I'm done I'll post it here so no one has to waste as much time as I did hunting for it.

A: Figured it out.  It's already accessible via PHP as $_SERVER['PHP_AUTH_DIGEST']
So then you pass to parseDigestAuthData($_SERVER['PHP_AUTH_DIGEST']);
<bangs head against wall>


text:
Q: JavaScript - Moment and Date.toLocaleDateString keeps returning my time when using a different locale I started off using the Moment library to try to get the time for Germany using the following code:
import moment from 'moment'
import 'moment/locale/de'

moment.locale('de');
console.log(moment().format('LTS'));

However, it kept returning my time, British summer time (BST)
I figured maybe it was an issue with the library, so I rewrote it without using the library like so:
const options = { hour: 'numeric', minute: 'numeric', second: 'numeric' }
const test = new Date();
console.log(test.toLocaleDateString('de-DE', options));

Yet this also returns my time... (with the added date, month and year as expected)
Am I doing something wrong? Or maybe it's something to do with how Chrome outputs to the console?

A: Moment locale refers to language not timezone.
You'll need moment timezone for that:
moment().tz('CET').format('LTS')

EDIT
As suggested by RobG, could also be achieved without moment:
new Date().toLocaleString('de-DE', { timeZone: 'Europe/Berlin' });

document.getElementById('date').innerHTML = new Date().toLocaleString('de-DE', { timeZone: 'Europe/Berlin' });
<div id="date"/>

A: With toLocaleString you can use the timeZone option, however it may not be supported everywhere you need it to be:

var options = {hour: 'numeric', minute: 'numeric', second: 'numeric', timeZone: 'Europe/Berlin'};
var test = new Date();
console.log(test.toLocaleDateString('de-DE', options));

A: Here's how you can do it using moment -

function toTimeZone(time, zone) {
    var format = 'YYYY/MM/DD HH:mm:ss ZZ';
    return moment(time, format).tz(zone).format(format);
}

console.log(toTimeZone(new Date(), "UTC"));
<script src="http://momentjs.com/downloads/moment.min.js"></script>


text:
Q: How to fix CSS with placing multiple buttons on one side of a row in Bootstrap? I am trying to make a simple example where I have a row and inside that row is columns. One column is for the name of the left-hand side and on the right-hand side is the three buttons that exist. However, I am having issues placing the buttons properly on the right side as well as spacing them at an appropriate distance. I tried using the max-width in my CSS but I just ended up screwing up the project even more. Below is my HTML/CSS file:

#submitGPBtn {
  margin-right: 30px;
}

 Group Pattern Test

    <button class="btn btn-primary">Save</button>

    <button class="btn btn-primary">Close</button>

    <button class="btn btn-primary" id="submitGPBtn">Submit</button>

A: You would want to use a btn-toolbar to group your buttons in-line.

#submitGPBtn {
  margin-right: 30px;
}

    Group Pattern Test

    <button class="btn btn-primary">Save</button>

    <button class="btn btn-primary">Close</button>

    <button class="btn btn-primary" id="submitGPBtn">Submit</button>

A: This question has been answered well here. But here's an example below, add float-right class to your button bar, you can put a breakpoint in the class like float-sm-right but float-right works on any viewport width.

#submitGPBtn {
  margin-right: 30px;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>

    Group Pattern Test

    <button class="btn btn-primary">Save</button>

    <button class="btn btn-primary">Close</button>

    <button class="btn btn-primary" id="submitGPBtn">Submit</button>

A: In bootstrap ml-auto is fine to align buttons to the right, but you should apply it only to the first item after the "offset".
I added ml-1 to space the other buttons and a lightyellow background just to show where the container ends.
My personal suggestion when you use bootstrap is to code inside a container, you can't set its size to what you want but it prevents stretching in wide monitors.

.container {
  background-color: lightyellow;
}
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>

 Group Pattern Test

        <button class="btn btn-success ml-auto">Save</button>
        <button class="btn btn-success ml-1">Close</button>
        <button class="btn btn-success ml-1" id="submitGPBtn">Submit</button>


text:
Q: How To Remove List From Another List In C# Here I have two list var userListFromFriendTable = mainService.GetUserFromFriend(ChattingUserName); and var getAllUserFromMessageUserTable = mainService.GetalluserfromMessageUser(); whose implementation are
given below.
Now what is want is to remove all the Friend table FriendRequestReceiverName column data of userListFromFriendTable  list from MessageUser table MessageUserName column of getAllUserFromMessageUserTable list.
Any help will be grate
    public List<Friend> GetUserFromFriend(string chattingUserName)
    {
        var checkUser = uow.Repository<Friend>().FindBy(x => x.FriendRequestSenderName.ToLower() == chattingUserName.ToLower()).ToList();
        return checkUser;
    }
    public List<MessageUser> GetalluserfromMessageUser()
    {
        var checkUser = uow.Repository<MessageUser>().GetAll().ToList();
        return checkUser;
    }

public class Friend
{
    public int FriendId { get; set; }
    public string FriendRequestSenderName { get; set; }
    public string FriendRequestReceiverName { get; set; }
    public int IsConfirmed { get; set; }
}
public class MessageUser
{
    public int Id { get; set; }
    public string MessageUserName { get; set; }
    public int IsFriend { get; set; }
}

A: try this:
var names=userListFromFriendTable.Select(i=> i.FriendRequestReceiverName)
  .OfType<string>()
 .ToArray();

getAllUserFromMessageUserTable.RemoveAll(r => names.Contains( r.MessageUserName );


text:
Q: Display only specific attachments I'm trying to list the attachments of a list item depending on it's name. But I have no idea how to get the name attribute into the if condition:
<xsl:if test="????????">
  <xsl:element name="SharePoint:AttachmentsField">
      <xsl:attribute name="runat">server</xsl:attribute>
      <xsl:attribute name="FieldName">Attachments</xsl:attribute>
      <xsl:attribute name="ControlMode">Display</xsl:attribute>
      <xsl:attribute name="Visible">true</xsl:attribute>
      <xsl:attribute name="ItemId">
         <xsl:value-of select="@ID"/>
      </xsl:attribute>
  </xsl:element>
</xsl:if>

Who can help me?


text:
Q: Calculate the homology of the mapping cone of $\Delta.$
Let $\Delta : S^n \longrightarrow S^n \times S^ n$ be the diagonal map given by $\Delta (x) = (x,x),$ $x \in S^n.$ Calculate  $H_{*} (C(\Delta)),$ the homology of the mapping cone of $\Delta.$

I have tried to use Mayer-Vietoris sequence to solve the problem but couldn't quite able to do it. Is there any specific way to approach such problems? Any help will be greatly appreciated.
Thanks!

A: If you cover the cone $X := C(\Delta)$ as in the picture, you will have $X = int(A) \cup int(B).$ Note that $A$ contracts to a point, $A \cap B$ is homotopically equivalent to $S^n,$ and $B$ deformation-retracts on $S^n \times S^n.$
Thus, for $k \not= 0,n$ we have $H_k(A \cap B) = 0$ and the Mayer-Vietoris sequence looks as follows:
$$\ldots \to 0 \to H_{n+1}(S^n \times S^n)  \to H_{n+1}(X) \xrightarrow{\partial} H_n(S^n) \xrightarrow{\Delta_*} H_n(S^n \times S^n) \to H_n(X) \to 0 \to H_{n-1}(S^n \times S^n) \to H_{n-1}(X) \to 0 \to \ldots$$
Since $\Delta_*$ is injective, $\partial$ is also zero, and thus $H_k(X) \simeq H_k(S^n \times S^n) $ for $k \not= n,$ wheareas $H_n(X)$ is the cokernel of $\Delta_*$.
[Intuitively, you get rid of one of the $n$-holes of $S^n \times S^n$ by glueing a cell along a cycle. It is possible to picture on a torus though I'm not sure how helpful that would be for you. This intuition can of course be made into another formal proof.]


text:
Q: Change font in Remote jupyter notebook I am accessing a jupyter notebook via ssh tunnel as explained here:
http://danielhnyk.cz/running-ipython-notebook-different-computer/
Unfortunately both chrome and firefox use the default font for the code cells of the remote notebook when I access it via http://localhost:8881/notebook.ipynb like in the attached screenshot

This is bad, since I want the code cells to be displayed in a fixed-width font.
I tried fixing it using the Font Changer extension for chrome, but this changes the font of the whole notebook to fixed-width, including the markdown cells, and it messes up the symbols in the Toolbar.
Any help would be greatly appreciated.
Note: When I run a notebook on my computer with the command  jupyter notebook the fonts look fine.

A: The code font which I used on the notebook server was not installed on my home computer. I simply adapted the custom.css file under
.jupyter/custom/custom.css

to use a font installed on both machines, i.e. DejaVu Sans Mono:
.CodeMirror pre {
    font-family: DejaVu Sans Mono;
    font-size: 10pt;
}


text:
Q: validate MOQ unit test method return value I have the below class and test class written using Moq:
public class Mytest : testin
{
    public int getId(int id)
    {
      int s = 2;
      return s;
    }

}

test class:
private Mock<testin> _mock;

[TestInitialize]
public void Setup()
{
    _mock = new Mock<testin>();

}

[TestMethod]
public void returngetId()
{

    // Build up our mock object

    _mock.Setup(x => x.getId(It.IsAny<int>())).Returns(1)

}

I'm returning 2 from the function and in unit test cases checking for the value 1. As per my understanding the test cases should fail. But im getting success message. How i can validate the return value is exactly what im expecting? I want to fail the test if it returning other than 1.

A: Your current setup will skip the method's execution, and instead "blindly" return 1. You should not mock the method if you wish it to be executed. If you remove the setup line, your test cases will indeed fail. In general, you should only mock a method if you need it to NOT be executed.

To clarify:
The line _mock.Setup(x => x.getId(It.IsAny<int>())).Returns(1) configures your mock object so that whenever you call the getId method, instead of executing it, the value 1 will always be returned. So, the following test would pass:
[TestMethod]
public void returngetId_Always1()
{
    // ... Build up our mock object
    _mock.Setup(x => x.getId(It.IsAny<int>())).Returns(1);
    Assert.AreEqual(1, _mock.Object.getId("foo"));
    Assert.AreEqual(1, _mock.Object.getId("bar"));
}

In order to get the actual implementation of the method to be invoked from within the mock, you have to mock the class, not the interface, with the following configuration:
[TestMethod]
public void returngetId_CallBase()
{
    var mock = new Mock<MyTest>() { CallBase = true };
    // add other method setups here. DO NOT setup the getId() method.
    Assert.AreEqual(2, _mock.Object.getId("foo"));
    Assert.AreEqual(2, _mock.Object.getId("bar"));
}

This will allow the mock to defer to the base implementation for any methods for which a mocking setup has not been provided.


text:
Q: Advice for PhD in Algebra I hope that this question is okay to post here.
I'm in my final year of my master's degree in Sweden, and I'm starting to feel that some doors are closing in regards to applying for a postgraduate degree. Some Universities in America have their application deadlines by the 15th of December, which is in five days, and some universities in the UK by the beginning of January.
I've asked but haven't really learned much from my department about what Universities would be good to do a PhD in within my area of interest. It's not that I wouldn't want to stay where I am, but I would like to work/study abroad.
So are there any good Universities for Algebra/Representation theory/etc that currently have general applications, or any specific application/position that would be good to apply for now or in the near future?


text:
Q: Create new StateCode in CRM 4.0 I have a situation where i have to add a new State to the stateCodes list. I would like to add "Fired" to Active and InActive state, How can i do such a thing ?
Note: i know about the StatusCode and how to use it but i want to use the statecode.
Thanks so much.

A: You can't. State codes are very tightly controlled. In the UI, there are only going to be options for activating and deactivating a record, so CRM doesn't allow you to add any new ones. Your best option is probably just to add it to the possible statuscode values for your entity.

A: Well, i couldn't find anyway to do what i want except the dirty way, which is to open the CRM database and add a new StateCode which is not recommended from Microsoft by the way.
This Query may help you to find the suitable attributes.
http://blogs.inetium.com/blogs/azimmer/archive/2010/02/08/status-codes-when-deactivating-records-in-crm-4-0.aspx
Thank you Matt.
Have a nice day :)


text:
Q: How to automatically resize the vagrant disk image size for linux guests? There are numerous steps online for manually increasing the vagrant disk size, for example: link
It would be great if the resize could be done automatically in the Vagrantfile, something like this:
  config.vm.provider :virtualbox do |vb|
    if first_up      # only run on the first 'up' command
      disk_uuid = ?  # how to get the disk_uuid?
      vb.customize ["modifyhd", disk_uuid, "--resize", "15360"]
      config.vm.provision "shell", path: "resize2fs -p -F /dev/sda"
    end
  end

Question: How can I find out the disk uuid in a cross platform way?
Question: Is this all that is required to resize the guest's disk?

A: I have found the following options to be useful:
1) Add another disk to the Vagrant box.
See my answer to a similar question on AskUbuntu here.
2) Use Opscode Vagrant boxes which tend to have 40Gb disks
See the opscode page for more information.
3) Use packer to create your own box.
After reading the packer tutorials, you can start by copying the packer definitions from somewhere else (e.g. opscode) and tweak the disk size.

Some more information:
An issue was raised on Vagrant's issue tracker about extending vagrant disks.

A: There is a vagrant-disksize plugin.
You can install it by executing:
vagrant plugin install vagrant-disksize
Then you can include it in the Vagrantfile like this:
Vagrant.configure('2') do |config|
  config.vm.box = 'ubuntu/xenial64'
  config.disksize.size = '50GB'
end

Its limited at the moment only to the first disk.


text:
Q: Separating transaction log files from database files in two different physical drives I am very new to this as it is my first time installing the product,
I have installed SQL Server 2014 enterprise edition on Windows Server 2012 R2 standard edition using the default installation, which means everything in one physical drive (C drive).
Now SQL server is installed and running, but I did not move my database there yet.
My question is, how can I change the settings to make both transaction logs and the database in two different physical drives?
I have C drive for the OS (Windows Server 2012 R2)
So far everything on C drive, but I want to put the transaction logs on D drive and the databases on E drive.
In a simple word, can I change into the below structure before moving my data?

*

*C: OS and SQL installation files

*D: SQL Server Transaction Log Files

*E: SQL Server Database
Files

A: Try to follow the below process it may helps you

 --> Right click on the name of the database
    --> Select Properties
    --> Go to the Files tab
    --> Make a note of the Path and FileName of MDF and LDF files. This step is important in case you don't want to end up searching for missing files...
    --> Right click on the database name
    --> Select Tasks -> Detach
    --> Move the files where you want
    --> Right click on the Databases node of your server
    --> Select Attach
    --> Click on the Add button
    --> Point to the new location
    --> Click OK


text:
Q: Get value from Pyramid by finding a contruction pattern with Python Can someone help me with this problem.

Here is my code but it is far away to the solution
def get_value_from_pyramid(l):
    for i in range(0,l):
        num=1
        for j in range(0,i+1):
            if i == j:
                num=1
            print(num, end=" ")
            num+=1
        print("\r")

A: All you need is some basic math :)
If you are using python >= 3.8:
from math import comb

def get_value_from_pyramid(n, r):
    return comb(n, r)

If you're using an older version of python:
import operator as op
from functools import reduce

def get_value_from_pyramid(n, r):
    r = min(r, n-r)
    numer = reduce(op.mul, range(n, n-r, -1), 1)
    denom = reduce(op.mul, range(1, r+1), 1)
    return numer // denom

More info can be found here


text:
Q: Recursion-schemes generalization of `tails` I've got a recursion-schemes style structure and I'd like to obtain a list of all substructures including the full structure - i.e. the equivalent of what the tails function does on a List. I think it would be possible to implement this by calling para, mapping back to the original structure at each step, and then sticking the original structure on the front separately, but that seems very cumbersome: (untested, apologies if the Haskell is incorrect; written in terms of Mu as I haven't really understood the Base construct yet)
gtails :: Functor f => Mu f -> [Mu f]
gtails = para (\a -> (fmap fst a) : (foldMap snd a))

(i.e. in the case f=Prim this is tails, for other f it's a generalization)
Is there a nicer way? I realise this isn't so bad, but the fmap fst a to recover the "original" structure at that step feels quite cumbersome, and the foldMap snd a is something I find myself repeating a lot when using para (likewise fold a when using cata which again feels like it should be unnecessary).

A: I don't see any issue with para. Just cons back the head and the tail at each Cons step:
import Data.Functor.Foldable

tails :: [a] -> [[a]]
tails = para (\case Nil -> [[]]; Cons a (as, res) -> (a : as) : res)

For clarity, specialized to lists and without recursion-schemes:
para :: (a -> [a] -> b -> b) -> b -> [a] -> b
para f z []     = z
para f z (a:as) = f a as (para f z as)

tails :: [a] -> [[a]]
tails = para (\a as res -> (a : as) : res) [[]]

However, if you'd like to be more general, the less nice para formulation comes handy:
import qualified Data.Functor.Foldable as Rec (Foldable)

tails :: (Rec.Foldable t, Base t ~ Prim [a]) => t -> [t]
tails as = as : para (\case Nil -> []; Cons a (as, res) -> as : res) as

This works for lists as usual, but you can also give type instance Base t = Prim [a] for other t-s, along with the Foldable instance, and use them as well.
Alternatively, we can keep the first tails definition at the cost of introducing an Unfoldable constraint:
tails' :: (Unfoldable t, Rec.Foldable t, Base t ~ Prim [a]) => t -> [t]
tails' = para (\case Nil -> [embed Nil]; Cons a (as, res) -> embed (Cons a as) : res)

This isn't too bad, since for each project there should be an inverse embed for fixpoints of functors anyway, so the Foldable and Unfoldable instances naturally come in pairs.

A: para is indeed the right function to use here. I have put everything in a self-contained gist augmented with examples if you want to play with it.
We start with the definition of the fixpoint Mu and the usual fold and para.
module Tails where

import Data.Function

newtype Mu f = In { out :: f (Mu f) }

fold :: Functor f => (f a -> a) -> Mu f -> a
fold alg = alg . fmap (fold alg) . out

para :: Functor f => (f (a, Mu f) -> a) -> Mu f -> a
para alg = alg . fmap (\m -> (para alg m, m)). out

We can then implement tails using para and an additional Foldable constraint allowing us to use foldMap to collect the intermediate result in the list monoid:
tails :: (Functor f, Foldable f) => Mu f -> [Mu f]
tails m = m : para (foldMap $ uncurry $ flip (:)) m


text:
Q: Double-Double Curly Braces in docker-compose.yml for kafka I'm looking at wurstmeister/kafka-docker, and found this pull suggesting using the IP address.  Basically, it uses the docker info formatting:
HOSTNAME_COMMAND: "docker info -f '{{`{{.Swarm.NodeAddr}}`}}'"

I get the idea that it uses the formatting to get the address, but I don't understand what's going on with the extra {{...}}  and the backticks (which would normally be an eval).  docker-compose allows for ${variables}, but there's no dollar sign ($) here, so no need to escape.  Why isn't this just:
HOSTNAME_COMMAND: "docker info -f '{{.Swarm.NodeAddr}}'"

I've seen this elsewhere, so I assume there's a reason.

A: This is basically a duplicate of this post.  However, you might not find that one if you aren't aware that docker-compose files use Go templates (I didn't find any mention of it in the compose file reference).  So basically, in go,  the backquotes indicate a literal string, so the outer set of {{ }} is a template allowing for the backquotes to take everything between literally.


text:
Q: Android Menu Group Checkable I currently am programming for API 10 and above. I created a menu and was looking to implement the method Menu.setGroupCheckable(id, checkable, exclusive). Below is my code. From the documentation I was expecting a check mark over the selected item out of the group and the other ones to be disabled. However, this is not the case.
 @Override
public boolean onCreateOptionsMenu(Menu menu) {
     super.onCreateOptionsMenu(menu);
     menu.add(0, 1, 0, "I1").setIcon(R.drawable.ic_launcher);
     menu.add(0, 2, 1, "I2");
     menu.add(0,3,2,"I3");

     menu.add(1, 4, 3, "I4");
     menu.add(1, 5, 4, "I5");
     menu.add(1,6,5,"I6");

    menu.setGroupCheckable(1, true, true);

     return true;
}

Android documentation link: http://developer.android.com/reference/android/view/Menu.html

A: Android Menu: Two single-checkable groups in the same menu
http://www.brighthub.com/mobile/google-android/articles/28673.aspx
http://www.mysamplecode.com/2011/07/android-options-menu-submenu-group.html
http://www.itcsolutions.eu/2011/09/26/android-tutorial-how-to-add-a-menu-programmatic-vs-declarative-solution/
These links may help you!!!

A: use Updated lib
compile 'com.android.support:appcompat-v7:23.1.0'
    compile 'com.android.support:design:23.1.0'


text:
Q: How Angular JS works when I defined ng-app in html tag? Html parse from top to bottom.
But when I define ng-app into html tag and call it's library from script tag which is inside html tag.
So how AngularJS know that I have defined ng-app into html tag?
See below code for reference

<html ng-app="myFirstApp">
 <head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
 </head>
</html>

A:
Angular initializes automatically upon DOMContentLoaded event or when
  the angular.js script is evaluated if at that time document.readyState
  is set to 'complete'. At this point Angular looks for the ngApp
  directive which designates your application root. If the ngApp
  directive is found then Angular will:

*

*load the module associated with the directive.

*create the application injector

*compile the DOM treating the ngApp directive as the root of
  the compilation. This allows you to tell it to treat only a portion of
  the DOM as an Angular application.

There are a lot of useful info in the official developer guide docs, like this article about bootstrapping. Also you can walk through tutorial