text:
Q: Understanding an algorithm for computing a matrix polynomial I'm trying to understand this algorithm by Charles Van Loan for evaluating a matrix polynomial $p(\mathbf A)=\sum\limits_{k=0}^q b_k \mathbf A^k=b_0\mathbf I+b_1\mathbf A+\cdots$ (where $\mathbf A$ is $n\times n$):

$\displaystyle s=\lfloor q\rfloor, \quad r=\lfloor q/s\rfloor$
  $\displaystyle \mathbf Y=\mathbf A^s$
  $\displaystyle \text{for}\quad j=1,\dots,n$
  $\displaystyle\quad\quad \mathbf y_0^{(j)}=\mathbf e_j$ ($\mathbf e_j$ is the $j$th column of the identity matrix)
  $\displaystyle\quad\quad \text{for}\quad k=1,\dots,s-1$
  $\displaystyle\quad\quad\quad \mathbf y_k^{(j)}=\mathbf A\mathbf y_{k-1}^{(j)}$
  $\displaystyle\quad\quad \mathbf f_0^{(j)}=\sum_{k=q}^{rs}b_k\mathbf y_{k-rs}^{(j)}$
  $\displaystyle\quad\quad \text{for}\quad k=1,\dots,r$
  $\displaystyle\quad\quad\quad \mathbf f_k^{(j)}=\mathbf Y\mathbf p_{k-1}^{(j)}+\sum_{i=0}^{s-1}b_{s(r-k)+i}\mathbf y_{i}^{(j)}$

I've tried going through it a number of times, but it seems that the quantity (vector?) $\mathbf p_{k-1}^{(j)}$ was never defined anywhere in the paper. What might it be? Also, the paper claims (or more probably it's how I (mis)understood the paper) that only three matrices need to be stored for the evaluation: $\mathbf A$, $\mathbf Y$, and the final $p(\mathbf A)$. However, I can't see how to properly organize things so that an extra array for storing the $\mathbf y_k^{(j)}$ is not needed (otherwise, four matrices are now needed instead of the three claimed in the paper).
Could anyone enlighten me on how to implement this algorithm properly? Better yet, is there any code available anywhere that implements this algorithm (I'm language-agnostic, so whatever code you post, I can likely translate into the language I'm currently using).
Thanks for any help!

A: The storage required for the $y^{(j)}_k$ is less than a "full" matrix in proportion as $s \ll n$.  That is, $s$ such vectors are required for each step $j$, and the storage for one step may be reused in the next step.
The Question states $s$ to be the floor of $q$, the degree of the polynomial, but this is mistaken.  Per the discussion of the paper preceding Algorithm I, $s$ can be any integer strictly between 1 and $q$.  While this does not guarantee $s \ll n$, it allows for it.  See the discussion of applying Algorithm II to the Taylor polynomial for $e^A$, where $s=4$ and $q=16$ were chosen.  [Note also the discussion of minimizing "work count" in Algorithm II by choosing $s$ around $\sqrt{q/2}$.]
That leaves still the mysterious $p^{(j)}_k$.  My guess is it is a typo, that $f^{(j)}_k$ is being computed by adjusting $Yf^{(j)}_{k-1}$, after initializing $f^{(j)}_0$, but I need to do a bit of scribbling to confirm that works out.
Added:  My guess above is correct, that we should read $f^{(j)}_{k-1}$ instead of $p^{(j)}_{k-1}$ at one point in Algorithm II where the latter appears.
The algorithm may be understood as combining two ideas.  One is that the matrix polynomial $p(A)$ will be evaluated column by column, i.e. by applying it successively to unit vectors $e_j$, $j=1,..,n$.
The other idea is simple though a bit cumbersome to spell out.   Recall that $1 \lt s \lt q$ where $q$ is the degree of $p$.  Let the polynomial:
$$ p(x) = \sum^q_{i=0} b_i x^i$$
be grouped according to the largest power of $x^s$ that divides each term and rewrite $p(x)$ in an expansion involving powers of $x^s$ and "coefficients" that are polynomials of degree at most $s-1$.  Taking $r = \lfloor q/s \rfloor$, and assuming any indicated coefficients $b_m$ where $m \gt q$ are zero:
$$ p(x) = \sum^r_{k=0} x^{sk} \beta_k(x)$$
where $\beta_k(x) = \sum^{s-1}_{i=0} b_{sk+i} x^i$ are the polynomial "coefficients" as above.
Assume that $Y = A^s$ has already been computed, e.g. by binary exponentiation or other scheme.
The outermost loop of Algorithm II is then iteratively applying $p(A)$ to $n$ unit vectors $v = e_j$ as explained above.  For simplicity we just describe computing $p(A)v$ for an arbitrary vector $v$ of compatible dimension, a column of length $n$ where $A$ is $n \times n$.  In effect we thus omit superscript $(j)$ from the remainder of the discussion.
First is a loop to initialize $y_0 = v$ and $y_i = A y_{i-1}$ for $i = 1,..,s-1$.
Second is a loop that essentially applies Horner's method to get $p(A)v$ using the expansion in powers of $A^s$ and "coefficients" $\beta_k(A)v$.  Note that the latter are column vectors, and for $k = 0,..,r$ we evaluate $\beta_k(A)v$ by taking the appropriate linear combination of previously initialized $y_i$.  That is:
$$ f_0 = \beta_r(A) v $$
$$ f_k = Y f_{k-1} + \beta_{r-k}(A) v $$
for $k = 1,..,r$.  This shows us that the term $p^{(j)}_{k-1}$ is a misprint for $f^{(j)}_{k-1}$ in Algorithm II.

A: Here is some octave code that implements "Algorithm II" quite faithfully. The arrays named with "_shifted" are indexed using $i+1$ in the last component wherever the paper uses $i,$ because arrays in matlab are indexed from 1 instead of 0. All the arithmetic is done mod 29 to make it easy to check against a simpler reference implementation. I haven't tried to make it particularly fast; it's really just meant to demonstrate that the algorithm works.
q=20;
s=floor(sqrt(2*q));
r=floor(q/s);
n=100;
modulo=29;
A=randi(modulo,n,n);
b_shifted=randi(modulo,q+1,1);

pA_van_loan = zeros(n,n);

# Compute A^s
As=eye(n);
for k = 1:s
  As=A*As;
  As=mod(As, modulo);
end

# Van Loan algorithm II
for j = 1:n
  y_shifted = zeros(n,s);
  y_shifted(j,1) = 1;
  for k = 1:s-1
    y_shifted(:,k+1) = A*y_shifted(:,k-1+1);
    y_shifted(:,k+1) = mod(y_shifted(:,k+1), modulo);
  end

  f = zeros(n,1);
  for m = 0:(q-s*r)
    f = f + b_shifted(s*r+m+1) * y_shifted(:,m+1);
  end
  f = mod(f, modulo);
  for k = 1:r
    f = As * f;
    for m = 0:s-1
      f = f + b_shifted(s*(r-k)+m+1) * y_shifted(:,m+1);
    end
    f = mod(f, modulo);
  end

  pA_van_loan(:,j) = f;
end

# Compute polynomial naively for reference
pA_reference = zeros(n,n);
Aj = eye(n);
for j = 0:q
  pA_reference = pA_reference + b_shifted(j+1)*Aj;
  Aj=A*Aj;
  Aj=mod(Aj,modulo);
end
pA_reference=mod(pA_reference,modulo);

assert(pA_van_loan == pA_reference);

A: Here is some python code that implements Algorithm II from Van Loan. It is not optimized for speed. Instead, I tried to follow the steps of the pseudo code in the paper as much as possible. The code above can be optimized and I showed in comments two possibilities (but I am sure there are more possibilities).
import numpy as np

def van_loan(A: np.array, b: np.array) -> np.array:
    ''' Compute sum_{j=0}^q b[q] * A**q using Van Loan's algorithm II

    A needs to be a square matrix (there is no check in this function).
    b is a vector containing q+1 coefficients.
    '''
    n = A.shape[0]
    q = len(b)-1
    s = np.floor(np.sqrt(2*q)).astype(np.int)
    r = q // s
    Y = np.linalg.matrix_power(A, s)
    p_van_loan = np.zeros((n, n))
    y = np.zeros((n, s))
    for j in range(n):
        # Initialize y as being the j-th column of the n-by-n identity matrix
        y[:, 0] = 0
        y[j, 0] = 1

        # Compute the remaining y according to y_k = A*y_{k-1}
        for k in range(1, s):
            y[:, k] = np.dot(A, y[:, k-1])

        # Compute f_0
        f = np.zeros(n)
        for l in range(0, q-s*r+1):
            f += b[l+s*r]*y[:, l]
        # Compute f_0 alternative:
        # f = np.einsum("i,ni->n", b[s*r:q+1], y[:, :q-s*r+1])

        # Compute the remaining f iteratively
        for k in range(1, r+1):
            f = np.dot(Y, f)
            for l in range(0, s):
                f += b[s*(r-k)+l]*y[:, l]
            # This for loop can be replaced by the following (faster)
            # line of code:
            # f += np.einsum("s,ns->n", b[s*(r-k):s*(r-k+1)], y[:, :s])

        # Set the j-th column to the computed f
        p_van_loan[:, j] = f

    return p_van_loan

To demonstrate that this produces the same result as when implementing the original equation of $p(\textbf{A})$, the following code can be used:
def van_loan_reference(A, b):
    n = A.shape[0]
    Ap = np.eye(n)
    p = b[0]*Ap
    for j in range(1, len(b)):
        Ap = np.dot(Ap, A)
        p += b[j]*Ap
    return p

n = 3
q = 8
np.random.seed(0)
A = np.random.rand(n, n)
b = np.random.randn(q+1)
print(van_loan(A, b))
print(van_loan_reference(A, b))

This produces:
[[26.07842457 33.42897135 37.28842938]
 [22.01005978 31.30224965 33.21369951]
 [31.17386387 42.02787474 48.15436486]]
[[26.07842457 33.42897135 37.28842938]
 [22.01005978 31.30224965 33.21369951]
 [31.17386387 42.02787474 48.15436486]]


text:
Q: How to add a UISplitViewController to a window-based app If I create a new project in Xcode 3 - a "Universal" window based project, I can't seem to instantiate the UISplitViewController outlet I am adding to the iPad's XIB.
Starting with a brand new "window-based" project, I select "Universal" from the drop down (iPhone, iPad, Universal). I then create an IBOutlet property in AppDelegate_iPad.h, synthesize the variable in the .m file and release it in the appropriate dealloc.
I open MainWindow_iPad.xib file and add a UISplitViewController object to it. I then connect the "splitViewController" outlet from AppDelegate_iPad to the UISplitViewController I just dragged onto the XIB.
Unfortunately, when I run this, splitViewController is never instantiated. Consequently, I can't add it to the window's view or set it as the window's root controller. I check this by putting a break point in
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

to view the splitViewController ivar - but unfortunately, it is always 0x0. Is there some special step I am missing? I've compared my code to the split view controller template in Xcode and I can't see any differences.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Graph the set of all complex numbers $z_n=\frac{2n+1}{n-i},n\in\mathbb R$ I'm a bit rusty on my complex numbers, how would you solve the following problem on paper?

Determine and sketch (graph) the set of all complex numbers of form:
  $$z_n=\frac{2n+1}{n-i},n\in\mathbb R$$

Rationalizing yields $$S=\left\{z_n\in\mathbb C : z_n=\frac{n + 2 n^2}{1 + n^2}+\frac{1 + 2 n}{1 + n^2}i\right\}$$
How do I proceed to sketch (graph) this now on paper? (Wolframalpha yields a circle)
I assume I need to find the center and the radius of that circle which would be enough to sketch the graph, but I can't quite proceed from this point on.

A: Say $$w= {2n+1\over n-i}\Longrightarrow n ={wi+1\over w-2}$$
Since $\overline{n}=n$ we have:
$$ (\overline{w}-2)(wi+1)=   (-i\overline{w}+1)(w-2)$$
so
$$ |w|^2i-2wi+\overline{w}-2  = -i|w|^2+2i\overline{w}+w-2$$
so
$$ |w|^2 = (\overline{w}+w)+{w-\overline{w}\over 2i}$$
Now, since $w=x+yi$ we have
$$ x^2+y^2 = 2x+y$$
So this is circle $$(x-1)^2+(y-{1\over 2})^2 ={5\over 4}$$

A: I'll use $x$ instead of $n$.
Note that$$\frac{2x^2+x}{x^2+1}=1+\frac{x^2+x-1}{x^2+1}=1+\frac{2x^2+2x-2}{2(x^2+1)}$$and that$$\frac{2x+1}{x^2+1}=\frac12+\frac{-x^2+4x+1}{2(x^2+1)}.$$So$$\frac{2x+1}{x-i}=1+\frac i2+\frac{2x^2+2x-2}{2(x^2+1)}+\frac{-x^2+4x+1}{2(x^2+1)}i.$$Now, observe that$$\left(\frac{2x^2+2x-2}{2(x^2+1)}\right)^2+\left(\frac{-x^2+4x+1}{2(x^2+1)}\right)^2=\frac54.$$Therefore, your set is contained in the circle with center $1+\frac i2$ and radius $\frac{\sqrt5}2$.

A: $\dfrac{1}{\overline{z_n}} = \dfrac{n+i}{2n+1} = \dfrac{n}{2n+1}+\dfrac{i}{2n+1}$
Evidently $\dfrac{1}{\overline{z_n}}$ lies on the line $L: 2x+y=1$
$z_n$ hence lies on the curve obtained by inverting $L$ in the circle $|z|=1$. The result is a circle passing through origin $O$. The radius and centre of this circle are found using properties of inversion as below:
Since $L$ is at a distance of $\dfrac{1}{\sqrt 5}$ from origin, the foot of the perpendicular $P$ from $O$ transforms to a point $P'$ at a distance of $\sqrt 5$ along the line $x-2y=0$ i.e. to $P'(2,1)$. Also $P'$ becomes the other end of the diameter from $O$. Hence the radius of the circle is $\dfrac{\sqrt 5}{2}$ and center is $\left(1, \dfrac{1}{2} \right)$
Hence $z_n$ lies on $\left(x-1\right)^2+\left(y-\dfrac{1}{2}\right)^2 = \dfrac{5}{4}$


text:
Q: Check device is locked? I've a multitasking application and I'm using all the app delegate events for backgrounding but when the device locked or idle timer expires none of the delegate events get fired. So I need to check device lock status.
Is there way to do this with SDK(non private api solution)?

A: Maybe you can watch after an item in the Keychain :
kSecAttrAccessibleWhenUnlocked
The data in the keychain item can be accessed only while the device is unlocked by the user. This is recommended for items that need to be accesible only while the application is in the foreground. Items with this attribute migrate to a new device when using encrypted backups.
Available in iOS 4.0 and later.
Declared in SecItem.h.
From : http://developer.apple.com/library/ios/#documentation/Security/Reference/keychainservices/Reference/reference.html

A: From the discussion it sounds like you could use applicationProtectedDataWillBecomeUnavailable:

On a device that uses content protection, protected files are stored in an encrypted form and made available only while the device is unlocked. This notification lets your application know that the device is about to be locked and that any protected files it is currently accessing will be unavailable shortly.
If your application is currently accessing a protected file, you can use this method to release any references to that file. Although it is not an error to access the file while the device is locked, any attempts to do so will fail. Therefore, if your application depends on the file, you might want to take steps to avoid using that file while the device is locked.

I assume this will get called regardless of whether or not you are using protected files. I have not tested it yet though.


text:
Q: Condition in aggregation mongodb I'm new in Mongodb and I try to learn aggregation.
My database look like this:
{
  _id : 1,
  a: 5,
  b: 6,
  c : {
    ca: 3
    cb: 5
}
},
{
  _id : 1,
  a: 3,
  b: 4,
  c : {
    ca: 3
    cb: 7
}
}

Is there anyway to :
- First: find max in c
- Second: create a new object like this:
{
   a : [ 5, 3],
   b : [6, 4],
   c : [5, 7]
}

My apologies if this is a repeated question but I wasn't able to find a similar one.

A: Try this,
db.collection.aggregate([
  {
    $addFields: {
      c: {
        $objectToArray: "$c"
      }
    }
  },
  {
    $group: {
      _id: null,
      a: {
        $push: "$a"
      },
      b: {
        $push: "$b"
      },
      c: {
        $push: {
          $max: "$c.v"
        }
      }
    }
  }
])

Mongo Playground


text:
Q: D3: Lag update on force layout links when dataset changes The "data 15000" button changes the dataset to another one that has the same nodes, but more linkages between nodes. However, the user has to click twice in order to fully display the updated force layout.
Why is this line of code 1-click late?
link.enter().append("line")
    .attr("stroke-width", function (d) { return scale(d.value); });

How do I solve this problem? Thank you!
JSFiddle here
The problem, basically:

A: Please add selection to tick function:
function ticked() {
    var link = linkg.selectAll("line")
    var fnode = fnodeg.selectAll("circle")
    ... update attributes for link(line) and fnode(circle).

working code here


text:
Q: I receive method options and return undefined I'm writing my login form which provides for a put request to the server.
The communication protocol is JSON
I have to send username and password hashes, using CryptoJS with SHA-256 hash algorithm.
Authentication data must be stored encrypted in the browser as a cookie, and each request is sent to the server as the basis for authentication, when you close the browser window, the data must be deleted.
example put request:
PUT my api adress

{"loginRequest": {
"username": "admin",
"hash": "8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918"

}}
Response OK
Code: 200
{"loginResponse": {
"username": "admin",
"name": "Example Admin",
"roles": [
    "USER", "ADMIN"
],
"lastLogin": "2014-02-17+01:00",
"backendVersion": "katconnect-backend-0.0.1-SNAPSHOT"

}}
Response Data Validation Error (URI username <> JSON username)
Code: 400
{"error": {
"code": "400",
"message": "the message of the error"

}}
Response Authentication Error (username or hash is null, user not found, wrong hash value)
Code: 401
{"error": {
"code": "401",
"message": "Username or password false"

}}
Here is my code:
angular.module('validationApp')

.controller('loginCtrl',function ($scope,$http,Base64,$cookieStore) {

$scope.login = function () {
        var user = {
            username: $scope.username,
            hash: CryptoJS.SHA256($scope.password)
        };
        var loginRequest = JSON.stringify(user);
        var credentials = Base64.encode($scope.username + ':' + $scope.password);

     $http({
            method: 'PUT',
            url: url+'/users/'+ $scope.username +'/login',
            data: loginRequest,
            headers:{'Content-Type': 'application/json'}
            })

                .success(function (){
                    $http.defaults.headers.common['Authorization'] = 'Basic ' + credentials;
                    $cookieStore.put( authCookieKey ,credentials);
                })
                .error(function(code){
                if (401 === code) {
                    $scope.invalidUsernamePassword = true;
                    }
                })

    };

})

A: You are doing a cross domain request to the API server. The browser first sends a options request to see if the HTTP method is allowed. Have you setup up CORS middleware from your server? If yes check if the method PUT is in whitlist.
http://better-inter.net/enabling-cors-in-angular-js/


text:
Q: Term or phrase like "pangram" for more general cases I am looking for a word or phrase like "pangram" that signifies an example of something that contains all the allowable contents of that class of object:

*

*"1,234.567809" contains all the generally-allowed symbols for a (US) number

*"1 + 2 × (3 / 4)" contains all the basic arithmetic operations

*Or an example sentence without the concrete example: "this program is a Python 'pangram': it contains usages of every allowable syntax of the language."

It seems to me that "pangram" itself might fit the bill, but this usage would stretch the definitions a bit:
pangram, n. (OED)

A sentence containing every letter of the alphabet.

pangram, n. (M-W)

a short sentence containing all 26 letters of the English alphabet

EDIT: although I was hoping there was a more general form of "pangram" for any case that is a "complete example" or something similar, the original impetus for this request was to describe a Markdown document that contained all examples of Markdown syntax to use as a complete test case for a set of CSS styles. Perhaps there is a name for this in the particular domain of programming/markup languages?

A: Catch-all examples, or all-inclusive examples:
One could use terms, a catch all example, or an all-inclusive example to describe such an example.  Pangram sounds a little too heavy term needing an explanation for itself, when the intention is clearly to illustrate an example that is peculiar about full coverage of concepts to be illustrated. An adjective to word "example" would make it clear that it's something about the nature of the example, and that something is readily highlighted by the meaning of the adjective.

A: Exhaustive
You might consider using exhaustive.

Merriam-Webster:
Including all possibilities; thorough.
'conducted an exhaustive search'
Oxford Living:
Including or considering all elements or aspects; fully comprehensive.
'The guide outlines every bus route in exhaustive detail.'
'The list is by no means exhaustive but it does capture some of the main elements.'
'After exhaustive testing they found that a long track in the circuit board had functioned as the antenna.'

Although this is probably not what is meant in the last example above (where I would take exhaustive to simply mean 'thorough'), exhaustive testing is in use as a technical term, and it is one where the meaning should be apparent even to a reader encountering the term for the first time without any explanation:

Technopedia:
Exhaustive testing is a testing or quality assurance approach in which
  all possible combinations of scenarios and use/test cases are used for
  testing.
In testing software, it is all the possible combinations of
  every type of input as well as every permutation and variation of how
  the input is carried out to ensure that everything works as expected.
  This goes the same for hardware testing—pressing any and all
  combinations of buttons and switches to determine which ones expose a
  bug so that it can be fixed.

Exhaustive testing refers to a process or procedure, of course, but you are asking for a class exemplar (a person or thing serving as a typical example or appropriate model: another word you might consider!)
Something like an exhaustive test case or an exhaustive use case should do the job, depending on your exact circumstances.


text:
Q: Measurability of multifunction Let $f:[a,b]\times \mathbb{R}^{n} \times \mathbb{R}^{m} \rightarrow \mathbb{R}^{n}$. Suppose $ f (.,x, u) $ is Lebesgue measurable for each $(x,u)$. Suppose also that $ f $ is continuous at $ (x, u) $ for each fixed $t$.
Let $ g: [a, b] \rightarrow [a, b] $ be a Lebesgue measurable function and $ U: [a, b] \rightrightarrows \mathbb {R}^{m} $ be a Lebesgue measurable multifunction. Then the multifunction
$$
F(t,x) = f(g(t),x,U(t))
$$
é  $\mathcal{L}\times \mathcal{B}^{n}$-measurable (Lebesgue-Borel)? Or should require continuity in $ t $ in the function $ f $?
Obs: Let $H: \Omega \rightrightarrows \mathbb {R}^{n} $ and  $(\Omega,\mathcal{F})$ be a measurable space. $H$ is $\mathcal{F}$-measurable if for each compact set $K \subset \mathbb {R}^{n}$,
$$
\{x \in \Omega: H(x) \cap K \not= \emptyset\} \in \mathcal{F}.
$$


text:
Q: gcc - undefined reference to `libusb_init' I'm trying to compile a piece of code which uses libusb:
#include <stdio.h>
#include <libusb-1.0/libusb.h>
#include <assert.h>

int main(void) {
    libusb_context *context = NULL;
    int rc = 0;

    rc = libusb_init(&context);
    assert(rc == 0);

    libusb_exit(context);
    return 0;
}

Upon compiling with gcc -lusb -lusb-1.0 sample.c -o sample the following errors emerge:
/tmp/ccr65JBT.o: In function `main':
sample.c:(.text+0x2e): undefined reference to `libusb_init'
sample.c:(.text+0x62): undefined reference to `libusb_exit'
collect2: error: ld returned 1 exit status

To make sure libusb is availible on my system:
raven@enforcer:~/sample$ pkg-config --libs libusb-1.0
-lusb-1.0
raven@enforcer:~/sample$ pkg-config --libs libusb
-lusb

I'm running Ubuntu 18.04 with gcc 7.3.0-16ubuntu3, how to fix?

A: Got it working by appending the flags after the .c: gcc sample.c -o sample -lusb -lusb-1.0
Autotools: sample_LDADD instead of sample_LDFLAGS
Thanks to Felix Palmen.


text:
Q: SQL select records with current month I have a field name textbook date field name NewMonth
The data like this
TextBook     NewMonth
ABC          2020-01-01
HDS          2020-01-30
ZXY          2020-02-15
FGD          2020-02-01
YTS          2020-04-02
HFH          2020-04-05
EDD          2020-03-25

My goal to select the records with current month (2020-04-XX)
TextBook     NewMonth
YTS          2020-04-02
HFH          2020-04-05

My query and not working. Can some one correct my query. Thank you
SELECT TextBook, NewMonth
   from  Store
   where NewMOnth >= Dateadd(Month, Datediff(Month, 0, DATEADD(m, -1, current_timestamp)), 0)

I think -1 for current month, -2 for last 2 months , -3 for last 3 months andso on

A:
My goal to select the records with current month (2020-04-XX)

Here is one option:
where NewMonth >= datefromparts(year(getdate()), month(getdate()), 1)

If you need an upper bound too:
where
    NewMonth >= datefromparts(year(getdate()), month(getdate()), 1)
    and NewMonth < dateadd(month, 1, datefromparts(year(getdate()), month(getdate()), 1))

If you want the previous month:
where
    NewMonth >= dateadd(month, -1, datefromparts(year(getdate()), month(getdate()), 1))
    and NewMonth < datefromparts(year(getdate()), month(getdate()), 1)

Or two months ago:
where
    NewMonth >= dateadd(month, -2, datefromparts(year(getdate()), month(getdate()), 1))
    and NewMonth < dateadd(month, -1, datefromparts(year(getdate()), month(getdate()), 1))

A: For 2020-04 you can use this :
WHERE CONCAT(YEAR(NewMonth),MONTH(NewMonth)) = CONCAT('2020','04')

To select records with current month  :
WHERE CONCAT(YEAR(NewMonth),MONTH(NewMonth)) = CONCAT(now(),now())


text:
Q: GOPATH и смешанные проекты Только начал осваивать Go. Согласно мануалу, GOPATH должен ссылаться на workspace, где в папке src будет храниться исходных код пакетов (и своих и чужих). У меня же основной язык PHP/C++ и я уже давно привык к структуре одна папка - один проект. Без разделения на языки: /Projects/CompanyX/ProjectNameX. Go же предлагает создать еще одну папку со своей структурой. К тому же, основной проект будет находится в одном месте, а только Go - в другом. Это просто удар по моему перфекционизуму :)
Мне удобно было бы, допустим: /Projects/freelance/site1/services/GoModule.
Вопрос. Является ли правильным при работе с Go проектом в IDE переключать GOPATH на этот конкретный workspace? Мне больше по душе один проект – один workspace.

A: Это не является "идеологически правильным и рекомендуемым" сценарием для go-проектов в целом.
Однако если вам так удобно, а GO из коробки эту функциональность поддерживает - я не вижу причин ей не следовать.
Размещение всего проекта в одном репозитории имеет свои плюсы. Например при откате версий или изучении истории вам не нужно будет по 5 репозиториям бегать и искать что где менялось.
Либо есть еще один вариант, которым я иногда пользуюсь: физически у меня go-код лежит вместе с остальным проектом, а в GOPATH я просто из логически понятного места делаю симлинк на папку с моим кодом. Тогда и код удобно лежит и IDE, команды go работают как ожидается, без доп. обёрток/настроек.

A: Все устанавливаемые пакеты скидываются как правило в
/home/'username'/go/src/github.com
где компилятор используя GOPATH ищет их при импортах в твоих проектах. Твои проекты размещаются тут же, /home/'username'/go/src/'your_project_name' где и происходит работа с ними. Фактически ты имеешь одно дерево для всех проектов + все пакетные зависимости в одном месте. Это крайне удобно и продуманно.
И ответ на вопрос - ты можешь переключать workspace, но будть готов к постоянному дублированию зависимых пакетов, которые импортируешь в собственную разработку, короче это путь = создание себе лишних головняков. Оно тебе надо? Риторический вопрос :)
А что один проект - один workspace= дело привычки. Поработай на Go месяцок именно с одним деревом, ты реально поймешь насколько этот концепт продуман. Ребята с Google не зря лаптем щи хлебают :))))

A: кто то юзает docker что бы добиться изолированности workspace, лично я юзаю maven + mvn-golang плагин что бы изолированно билдить проекты (так как тоже люблю один проект в однйо папке) и не зависеть от окружения и прописанных в окружении путей. понятие workspace как то имхо неочень удобно и неочень привычно после той же java


text:
Q: How to write a bash script to execute a different command with additional arguments? When called as my_cmd -a -b ... c,
the script will finally call program a with addition parameters:
a -additional -a -b ... c

How can I write such a bash script?

A: a -additional "$@" [pad to 30 characters]

A: Given that the additional arguments come immediately after the command, it is trivial:
exec a -additional "$@"

The exec is optional.

A: If the command's name "a" has to be also taken from the my_cmd's parameters:
"${1:1}" -additional "$@"


text:
Q: Why does xterm alt-backspace produce the Unicode character U+00FF? In xterm, when I press alt-backspace, xterm produces the Unicode character 'LATIN SMALL LETTER Y WITH DIAERESIS' (U+00FF) as described here. It shows up on-screen as a 'y' character with two dots above it.
What component, code or configuration causes this particular Unicode sequence to be emitted when alt-backspace is typed? terminfo? Is it hard-coded in xterm? Xkb? Something else?
I'd appreciation any pointers to configuration files, man pages, source code, and so forth. Thanks.

A: You wanted a man page?
man xterm
   eightBitInput (class EightBitInput)
           If  "true",  Meta  characters (a single-byte character combined
           with the Meta modifier key) input from the  keyboard  are  pre‐
           sented  as a single character, modified according to the eight‐
           BitMeta resource.  If "false", Meta  characters  are  converted
           into  a  two-character  sequence with the character itself pre‐
           ceded by ESC.  The default is "true".

No applause or thank you necessary: Just click the sad little grey check-mark till it turns green.  For any future questions: just click here.  ;-)

A: put arrow in middle of term then keep pushed Ctrl+left mouse button and in menu check option "Meta send escape"
edit file  /etc/X11/app-defaults/XTerm
add this line at the end
*metaSendsEscape: True


text:
Q: troubles in a simple weather webapp using openweathermaps API Initially I had 3 separates .js files, one for each city to test the api, and it worked perfectly.
Now i'm trying to insert all the 3 request in a single .js file, to make all the request at the same time and call a single js from the html, but i am unable to do it.
    var APPID = "b4d7400359e1dd91c7dee5cf238c9681";``
var temp1;
var loc1;
var icon1;
var temp2;
var loc2;
var icon2;
var temp3;
var loc3;
var icon3;

function updateById1(){
    var url = "http://api.openweathermap.org/data/2.5/weather?id=2525689&APPID=" + APPID;
    sendRequest(url);
}

function updateById2(){
    var url = "http://api.openweathermap.org/data/2.5/weather?id=2525473&APPID=" + APPID;
    sendRequest(url);
}

function updateById3(){
    var url = "http://api.openweathermap.org/data/2.5/weather?id=3173435&APPID=" + APPID;
    sendRequest(url);
}
function sendRequest (url){
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange =  function() {
                console.log(xmlhttp.status);
            if (xmlhttp.readyState ===
                        XMLHttpRequest.DONE && xmlhttp.status === 200){
            var data = JSON.parse(xmlhttp.responseText);
            var weather = {};
            weather.icon = data.weather[0].id;
            weather.loc = data.name;
            weather.temp = K2C(data.main.temp);
            update(weather);
        }
    };
    xmlhttp.open("GET", url, true);
    xmlhttp.send();

}

function K2C (k) {
    return Math.round(k-273.15);
}

function update(weather){
    loc.innerHTML = weather.loc;
    temp.innerHTML = weather.temp;
    icon.src = "imgs/codes/" + weather.icon + ".png";
    //console.log(icon.src);
}

window.onload = function () {
    temp1 = document.getElementById.innerHTML= "temperature1";
    loc1 = document.getElementById("location1");
    icon1 = document.getElementById("icon1");
    temp2 = document.getElementById("temperature2");
    loc2= document.getElementById("location2");
    icon2 = document.getElementById("icon2");
        temp3 = document.getElementById("temperature3");
    loc3 = document.getElementById("location3");
    icon3 = document.getElementById("icon3");

        updateById1();
    updateById2();
    updateById3();
}

Here the html

    <meta charset="utf-8"/>
    <title>Weather App</title>
    <link rel="stylesheet" type="text/css" href="styles.css" />

0°

Unknown

0°

Unknown

0°

Unknown

A: Your update function had loc and temp which were undefined. I have updated and tested the code. Let me know if you need help in understanding anything in particular.
Always look at console (right click -> inspect element -> console) for errors.
   var APPID = "b4d7400359e1dd91c7dee5cf238c9681";
   var temp1;
   var loc1;
   var icon1;
   var temp2;
   var loc2;
   var icon2;
   var temp3;
   var loc3;
   var icon3;

   function updateById1() {
       var url = "http://api.openweathermap.org/data/2.5/weather?id=2525689&APPID=" + APPID;
       sendRequest(url, 1);
   }

   function updateById2() {
       var url = "http://api.openweathermap.org/data/2.5/weather?id=2525473&APPID=" + APPID;
       sendRequest(url, 2);
   }

   function updateById3() {
       var url = "http://api.openweathermap.org/data/2.5/weather?id=3173435&APPID=" + APPID;
       sendRequest(url, 3);
   }

   function sendRequest(url, id) {
       var xmlhttp = new XMLHttpRequest();
       xmlhttp.onreadystatechange = function() {
           console.log(xmlhttp.status);
           if (xmlhttp.readyState ===
               XMLHttpRequest.DONE && xmlhttp.status === 200) {
               var data = JSON.parse(xmlhttp.responseText);
               var weather = {};
               weather.icon = data.weather[0].id;
               weather.loc = data.name;
               weather.temp = K2C(data.main.temp);
               update(weather, id);
           }
       };
       xmlhttp.open("GET", url, true);
       xmlhttp.send();

   }

   function K2C(k) {
       return Math.round(k - 273.15);
   }

   function update(weather, id) {
       switch (id) {
           case 1:
               loc1.innerHTML = weather.loc;
               temp1.innerHTML = weather.temp;
               icon1.src = "imgs/codes/" + weather.icon + ".png";
               break;
           case 2:
               loc2.innerHTML = weather.loc;
               temp2.innerHTML = weather.temp;
               icon2.src = "imgs/codes/" + weather.icon + ".png";
               break;
           case 3:
               loc3.innerHTML = weather.loc;
               temp3.innerHTML = weather.temp;
               icon3.src = "imgs/codes/" + weather.icon + ".png";
               break;
           default:
               console.log("incorrect id")
       }
   }

   window.onload = function() {
       temp1 = document.getElementById("temperature1");
       loc1 = document.getElementById("location1");
       icon1 = document.getElementById("icon1");
       temp2 = document.getElementById("temperature2");
       loc2 = document.getElementById("location2");
       icon2 = document.getElementById("icon2");
       temp3 = document.getElementById("temperature3");
       loc3 = document.getElementById("location3");
       icon3 = document.getElementById("icon3");

       updateById1();
       updateById2();
       updateById3();
   }


text:
Q: Youtube api video auto playing when page scroll How to play youtube video automatically when user scrolls page with several youtube videos (like on twitter and Facebook). When scrolling to video - autoplay youtube video.

A: Here is what you have to do.
To make an embedded video autoplay, add "&autoplay=1" to the video's embed code, right after the video ID (the series of letters that follows "v/").
Here's an example:
<object height="350" width="425"><param name="movie" value="http://www.youtube.com/v/OdT9z-JjtJk&autoplay=1" /><embed height="350" src="http://www.youtube.com/v/OdT9z-JjtJk&autoplay=1" type="application/x-shockwave-flash" width="425"></embed></object>

If you want to have more functionalities with the embedded video you can visit this page.

A: https://github.com/olssonandreas/youtubeautoplay
Simple javascript project that shows how you can autoplay multiple videos on the same page. The autoplay starts when the video is in the viewport.

A: Even though this is an old thread, I found a solution and thought I'd post it in-case it's useful for anyone.
Using the code below, it will play the embedded YouTube video when the user scrolls to your element. Just fill in "#YourElement" with the element that will play the video when they scroll to it. Finally, give your iFrame and ID attribute and change "#YourIFrame" to whatever you called the ID of your iFrame.
$(window).scroll(function() {

//will trigger when your element comes into viewport
    var hT = $('#YourElement').offset().top,
    hH = $('#YourElement').outerHeight(),
    wH = $(window).height(),
    wS = $(this).scrollTop();

if (wS > (hT+hH-wH)){
    //appends &autoplay=1 to iFrame src, making it autoplay
    var videoUrl = $('#YourIFrame').attr('src');
    $('#YourIFrame').attr('src', videoUrl + "&autoplay=1");
}


text:
Q: WPF XAML Animation How do i stop it when bound boolean becomes false? I want the animation to stop when the boolean CanAnimate becomes false.  It starts on true, so how do i tell it to stop when CanAnimate is false?  (The CanAnimate bool is set inside a SelectedItem setter)
<Border BorderBrush="Black" BorderThickness="2" Margin="1" Name="ReviewNote">
    <Border.Style>
        <Style TargetType="Border">
           <Style.Triggers>
               <DataTrigger Binding="{Binding CanAnimate}" Value="True">
                   <DataTrigger.EnterActions>
                       <BeginStoryboard>
                           <Storyboard>
                              <DoubleAnimation
                                    Storyboard.TargetProperty="(Border.Opacity)"
                                    From="1.0" To="0.0" AutoReverse="True"
                                    RepeatBehavior="Forever" />
                            </Storyboard>
                       </BeginStoryboard>
                   </DataTrigger.EnterActions>
               </DataTrigger>
            </Style.Triggers>
         </Style>
    </Border.Style>
   <TextBlock/>
</Border>

A: You can try using the ExitActions on the DataTrigger to stop the animation, by overriding with another animation. For instance:
<DataTrigger Binding="{Binding CanAnimate}" Value="True">
   <DataTrigger.EnterActions>
       <BeginStoryboard>
           <Storyboard>
              <DoubleAnimation
                    Storyboard.TargetProperty="(Border.Opacity)"
                    From="1.0" To="0.0" AutoReverse="True"
                    RepeatBehavior="Forever" />
            </Storyboard>
       </BeginStoryboard>
   </DataTrigger.EnterActions>
   <DataTrigger.ExitActions>
        <BeginStoryboard>
           <Storyboard>
              <DoubleAnimation
                    Storyboard.TargetProperty="(Border.Opacity)"
                    From="0.0" To="0.0" Duration="0:0:0.0" FillBehavior="HoldEnd" />
            </Storyboard>
       </BeginStoryboard>
   </DataTrigger.ExitActions>
</DataTrigger>

Alternatively, there is a way to stop storyboards in XAML by name, again you could use ExitActions for this. This previous question shows the way.
Hope this helps!


text:
Q: How can I debug the bash prompt? I've been editing .bashrc files and other init files, and it seems that I've left behind a few code snippets or two that are causing a few errors at the prompt (e.g. file missing), but I can't find them.
How do I debug the prompt to find out what init scripts I've carelessly hacked?

A: The easiest way to get a clean initial state is to SSH into your current host, but instead of letting SSH launch your shell with default settings, you provide an explicit command which prevents .bashrc from being read.
ssh -tt localhost /bin/bash --norc

The -tt forces SSH to allocate a TTY, which is what would normally happen when you open a shell connection, but is not default when running an explicit command.
The --norc prevents bash from reading your settings file (since we want to do that ourselves).
You should now be at a bash prompt, in a clean environment. This is useful for examining what variable are set to before your .bashrc runs etc. Enable tracing and source your .bashrc:
set -x   # Enable tracing
source .bashrc

A: Most of the shells have debug flags that show the commands being executed. Bash may even have one that shows a command before expansion of variables and after. Have you tried checking (I believe) -c -x or -X flags and see if they show the information you are looking for.
You can set them as first thing in the rc files (most global one) or just pass it down into bash command by invoking it from another shell.
In fact, if you invoke bash from another shell, you can also use script command to record everything you see and do into the file, which makes postmortem analysis so much easier.

A: Try invoking bash with the -x flag, then sourcing your .bashrc or .bash_profile or whatever you're using. That ought to be prolix enough to find your problem
ie:
bash -x
source .bashrc

A: Try to see where you've defined prompt - probably it in some dot file in your home directory:
grep PS1 ~/.*

You can see current value of prompt by just printing it:
echo $PS1

HTH

A: Check the  .bash_history file in your home directory to find out what commands you have been running. If you used commands like vi filename to open the init scripts, it will find them in the command history.


text:
Q: How can I get embed resource without defining serializer in Django REST Framework? As I know, if I want to get an embed resource, need to define it in the proper serializer. Then it will be always embed no matter I need it or not.
If I want two different embedding propurse, I need two urls for each.
So I wonder if I could implement an ?embedded= request like Eve do:
GET (/emails/<id>/?embedded={"author":1}, embedded resource is READ ONLY by default.

A: Assuming that you want to have different objects as embedded, you can implement such think with something like following:
You can pass your kwargs to a serializer as context
serializer = YourSerializer(data=initial_first_shop_data,
                            context={"author": 1})

And then override .to_representation() method
def to_representation(self, instance):
    representation = super(DynamicFieldsModelSerializer, self).to_representation(instance)

    if 'author' in self.context:
        author = AuthorSerializer(Author.objects.get(pk=self.context['author']))
        representation['author'] = author.data

    return representation

If you will always have author as embedded object, it's simpler to add it to your serializer and take it our in case if it's not in the context.


text:
Q: Remote access problem - PostgreSQL I'm don't know much about database management, so to enable the remote access to my postgresql db I followed some tutorials. I've updated pg_hba_conf and postgresql_conf files.
In pg_hba_conf I added the
"host   all   all   0.0.0.0/0   md5"
line  in the "# IPv4 local connections" slot.
I've been succeeded for some days, but since yesterday there's a problem happening. In the computer I'm remote accessing the server, after I input the password for postgres user, PgAdmin returns "timeout expired".

First I've checked the server properties, and discovered that the IP inserted was not correct (what seemed strange, but I've corrected anyway). For the day it did, but today the same "timeout expired" message appeared again. The remote access settings are fine in PgAdmin, but as I checked pg_hba_conf in the server computer, it came with this settings where I've updated in first time:
"# IPv4 local connections:
host    all             all             127.0.0.1/32            @authmethodhost@"
Seems that it automatically removed my updated line and also altered the authentication method (as I remember, the default was "md5" and not this @authmethodhost@). I'm really confused with that.
Below I'm copying a print from the pg_hba_conf file for you to check if there's another change that I wasn't able to perceive.


text:
Q: Add Individual Product Clicked to Cart. React Context I created a cart Array in my Context
 const [cart, setCart] = useState([]);

I want to implement an addToCart Button, on Each Button Click, Add the clicked product to cart, and change the button from Add to cart to Remove from cart on that particular Product, not all products.
const addProduct = (product) => {
    setCart([
      ...cart,
      {
        id: product.id,
        drinkName: product.drinkName,
        price: product.price,
        url: product.url,
      },
    ]);

};
Shop Page
const { products, storeQuery, addProduct } = useProduct();
// Products are coming from Firebase

  const addToCart = (product) => {
    const newProduct = {
      id: product.id,
      drinkName: product.drinkName,
      price: product.price,
      url: product.url,
    };
    product = newProduct;
    console.log("cart Added");
    addProduct(newProduct);
    console.log(newProduct.id, "Clicked");
  };

<SimpleGrid
              columns={{ base: 2, md: 4 }}
              spacing={{ base: 3, md: 4 }}
            >
              {products?.map((docsSnapshot) => {
                const product = docsSnapshot.data();
                return (
                  <ProductList
                    key={docsSnapshot.id}
                    docsSnapshot={docsSnapshot}
                    product={product}
                    addProductToCart={(product) => addToCart(product)}
                  />
                );
              })}
            </SimpleGrid>

ProductList page
<Button
              isFullWidth
              onClick={() => addProductToCart(product, docsSnapshot?.id)}
              colorScheme="success"
              size={"xs"}
            >
              Add to cart
            </Button>

id: undefined, Why is that happening?

I also want to check if a single product in the cart is another component.
Something like this
const inCart = Boolean(
    Map through the cart and check if that product is already in the cart
  );

So that I can display an incremental button if it exists and display addButton if it doesn't.
Lastly, to access the quantity from any component.
To be able to display a particular product quantity in the productDetails page.

A: I don't guarantee that each product document has an id field from Firestore.
Refactor code as :

{products?.map((docsSnapshot) => {
                const doc = docsSnapshot.data();
                const product = {...doc,id:docsSnapshot.id}
                return (
                  <ProductList
                    key={docsSnapshot.id}
                    docsSnapshot={docsSnapshot}
                    product={product}
                    addProductToCart={(product) => addToCart(product)}
                  />
                );
              })}

To change Add to cart to Remove to cart label try.

products?.map((docsSnapshot) => {
  const doc = docsSnapshot.data();
  const product = { ...doc, id: docsSnapshot.id };
  // Find product either added to cart.
  const inCart = Boolean(cart.find((el) => el.id === product.id));
  return (
    <ProductList
      key={docsSnapshot.id}
      docsSnapshot={docsSnapshot}
      product={product}
      addProductToCart={(product) => addToCart(product)}
      // Add extra props for to indicate if product added to cart
      isInCart={inCart}
    />
  );
});

Later inside Product page,
refactor as below:
<Button
  isFullWidth
  onClick={() => addProductToCart(product, docsSnapshot?.id)}
  colorScheme="success"
  size={"xs"}
>
  {props.isInCart ? "Remove" : "Add"} to cart
</Button>;

A: Calculate cart total.

const total = cart.map(product=>product.price* product?.quantity||1 ).reduce(previousValue, currentValue) => previousValue + currentValue,
  0)

console.log({total})


text:
Q: malloc: Incorrect checksum for freed object Below is function to do merge sort. but I meet error when I execute. The allocated memory(aux) has been freed every time in function merge, why it will be modified after freed?

a.out(65287,0x1112bedc0) malloc: Incorrect checksum for freed object
0x7ff9a4c05888: probably modified after being freed. Corrupt value:
0xb00000003 a.out(65287,0x1112bedc0) malloc: *** set a breakpoint in
malloc_error_break to debug Abort trap: 6

void merge(int arr[], int lo, int mid, int hi) {
    int i = lo;
    int j = mid + 1;
    int *aux = (int *)malloc((hi - lo + 1) * sizeof(int));
    for (int k = lo; k <= hi; k++) {
        aux[k] = arr[k];
    }
    for (int k = lo; k <= hi; k++) {
        if (i > mid)
            arr[k] = aux[j++];
        else if (j > hi)
            arr[k] = aux[i++];
        else if (aux[i] > aux[j])
            arr[k] = aux[j++];
        else
            arr[k] = aux[i++];
    }
    free(aux);
}

void mergesort1(int arr[], int lo, int hi) {
    if (lo >= hi)
        return;
    int mid = lo + (hi - lo) / 2;
    mergesort1(arr, lo, mid);
    mergesort1(arr, mid + 1, hi);
    merge(arr, lo, mid, hi);
}

call with:
mergesort1(arr, 0, 9);

A: malloc((hi - lo + 1) * sizeof(int)) allocates space for elements indexed from 0 to hi-lo, but for (int k = lo; k <= hi; k++) … aux[k] = … accesses the elements with indices from lo to hi, thus writing outside the allocated memory.

A: The aux array is not initialized properly: for (int k = lo; k <= hi; k++) { aux[k] = arr[k]; } should be:
    for (int k = lo; k <= hi; k++) {
        aux[k -lo] = arr[k];
    }

Your code writes beyond the end of the allocated array, potentially causing corruption of the data used by malloc() and free() to keep track of allocated memory.
Note that i and j should also be initialized differently and it is confusing to include the upper bound in the merge sort algorithm. If hi is excluded, the code is simpler as no +1/-1 adjustments are necessary:
void merge1(int arr[], int lo, int mid, int hi) {
    int i = 0;
    int j = mid -= lo;
    int n = hi - lo;
    int *aux = (int *)malloc(n * sizeof(int));
    for (int k = 0; k < n; k++) {
        aux[k] = arr[lo + k];
    }
    for (int k = lo; k < hi; k++) {
        if (i >= mid)
            arr[k] = aux[j++];
        else if (j >= n)
            arr[k] = aux[i++];
        else if (aux[i] > aux[j])
            arr[k] = aux[j++];
        else
            arr[k] = aux[i++];
    }
    free(aux);
}

void mergesort1(int arr[], int lo, int hi) {
    if (hi - lo < 2)
        return;
    int mid = lo + (hi - lo) / 2;
    mergesort1(arr, lo, mid);
    mergesort1(arr, mid, hi);
    merge1(arr, lo, mid, hi);
}

call with: mergesort1(arr, 0, 10);, which is simpler because 10 is the array length.
The code can be further simplified using pointer arithmetic:
void merge2(int arr[], int mid, int hi) {
    int *aux = malloc(n * sizeof(*aux));
    for (int i = 0; i < n; i++) {
        aux[i] = arr[i];
    }
    for (int i = 0, j = mid, k = 0; i < mid;) {
        if (j >= n || aux[i] <= aux[j])
            arr[k++] = aux[i++];
        else
            arr[k++] = aux[j++];
    }
    free(aux);
}

void mergesort2(int arr[], int n) {
    if (n < 2)
        return;
    int mid = n / 2;
    mergesort2(arr, mid);
    mergesort2(arr + mid, n - mid);
    merge2(arr, mid, n);
}

call with: mergesort2(arr, 10);, where 10 is the array length.


text:
Q: How to remotely access application Is there an application which can be used to remotely access and start application on a server without using RDP.
The main reason for this is security are security issue when user has a full access to server with RDP. I know it is possible to set restriction on user roles, but I would like to know if there is an application that can actually complete this? Would that be some sort of cloud?
Thanks for helping and clearing this out for me

A: If it's just an executable, there's always the option of setting up a network share and running it from there.
If you're needing platform independence or if this method won't work, your best bet may be to created a very restricted account on the RDP host and go that route.
What type of network is it, and what's the application?


text:
Q: How to get output information with official nvidia driver I want to parse the files in /sys/class/drm (edid, modes, status) to obtain some information about the connected monitors. Unfortuantely the nvidia driver does not support DRM. Is there any way to get reliable information about the outputs when using a nvidia driver?
xrandr is no option since it is not reliable since Ubuntu 13.10.

A: Try using the nvidia-smi utility.
You can also use: nvidia-xconfig --query-gpu-info to list GPU information and connected devices.


text:
Q: Unable to install Keras in my conda environment in Windows 10. Error message: call :GetWin10SdkDirHelper HKLM\SOFTWARE\Wow6432Node 1>nul 2>&1 OS: Windows-10
I'm trying to install data science packages in my Conda virtual environment. I've created and worked in such conda environments before and faced no issues at all, even while using Keras. But, this time, I am not even able to understand the cause of this issue.
This is how I created my Conda virtual environment:

*

*Open Anaconda Prompt

*cd path_to_my_project_folder

*conda create --prefix ./env numpy keras tensorflow  jupyter notebook flask

*conda activate path_to_my_project_folder/env
During and after installation of packages I don't see any error messages. But, as soon as I activate my conda environment I get the following error messages, and also, when I check the installed packages, I see all the packages except Keras. As soon as I activate my conda virtual environment I get the following error messages in my  Anaconda Prompt:

(base) C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>conda activate  C:/Users/Neerva/Documents/SU/SEM5/ibm_ice/tomato_leaf_disease_prediction/env

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>python C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction\env\etc\keras\load_config.py  1>temp.txt

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>set /p KERAS_BACKEND= 0<temp.txt

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>del temp.txt

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>python -c "import keras"  1>nul 2>&1

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>if errorlevel 1 (
ver  1>nul
 set "KERAS_BACKEND=theano"
 python -c "import keras"  1>nul 2>&1
)

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>SET DISTUTILS_USE_SDK=1

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>SET MSSdk=1

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>SET "VS_VERSION=15.0"

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>SET "VS_MAJOR=15"

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>SET "VS_YEAR=2017"

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>set "MSYS2_ARG_CONV_EXCL=/AI;/AL;/OUT;/out"

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>set "MSYS2_ENV_CONV_EXCL=CL"

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>set "PY_VCRUNTIME_REDIST=\bin\vcruntime140.dll"

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>set "CXX=cl.exe"

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>set "CC=cl.exe"

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>set "VSINSTALLDIR="

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>for /F "usebackq tokens=*" %i in (`vswhere.exe -nologo -products * -version [15.0,16.0) -property installationPath`) do (set "VSINSTALLDIR=%i\" )

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>if not exist "" (for /F "usebackq tokens=*" %i in (`vswhere.exe -nologo -products * -requires Microsoft.VisualStudio.Component.VC.v141.x86.x64 -property installationPath`) do (set "VSINSTALLDIR=%i\" ) )

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>if not exist "" (set "VSINSTALLDIR=C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\" )

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>if not exist "C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\" (set "VSINSTALLDIR=C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\" )

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>if not exist "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\" (set "VSINSTALLDIR=C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\" )

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>if not exist "C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\" (set "VSINSTALLDIR=C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\" )

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>IF NOT "" == "" (
set "INCLUDE=;"
 set "LIB=;"
 set "CMAKE_PREFIX_PATH=;"
)

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>call :GetWin10SdkDir

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>call :GetWin10SdkDirHelper HKLM\SOFTWARE\Wow6432Node  1>nul 2>&1

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>if errorlevel 1 call :GetWin10SdkDirHelper HKCU\SOFTWARE\Wow6432Node  1>nul 2>&1

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>if errorlevel 1 call :GetWin10SdkDirHelper HKLM\SOFTWARE  1>nul 2>&1

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>if errorlevel 1 call :GetWin10SdkDirHelper HKCU\SOFTWARE  1>nul 2>&1

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>if errorlevel 1 exit /B 1

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>exit /B 0

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>for /F %i in ('dir /ON /B "\include\10.*"') DO (SET WindowsSDKVer=%~i )
The system cannot find the file specified.

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>if errorlevel 1 (echo "Didn't find any windows 10 SDK. I'm not sure if things will work, but let's try..." )  else (echo Windows SDK version found as: "" )
Windows SDK version found as: ""

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>IF "win-64" == "win-64" (
set "CMAKE_GEN=Visual Studio 15 2017 Win64"
 set "BITS=64"
)  else (
set "CMAKE_GEN=Visual Studio 15 2017"
 set "BITS=32"
)

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>pushd C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\
The system cannot find the path specified.

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>CALL "VC\Auxiliary\Build\vcvars64.bat" -vcvars_ver=14.16
The system cannot find the path specified.

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>popd

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>IF "" == "" SET "CMAKE_GENERATOR=Visual Studio 15 2017 Win64"

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>call :GetWin10SdkDirHelper HKLM\SOFTWARE\Wow6432Node  1>nul 2>&1

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>if errorlevel 1 call :GetWin10SdkDirHelper HKCU\SOFTWARE\Wow6432Node  1>nul 2>&1

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>if errorlevel 1 call :GetWin10SdkDirHelper HKLM\SOFTWARE  1>nul 2>&1

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>if errorlevel 1 call :GetWin10SdkDirHelper HKCU\SOFTWARE  1>nul 2>&1

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>if errorlevel 1 exit /B 1

C:\Users\Neerva\Documents\SU\SEM5\ibm_ice\tomato_leaf_disease_prediction>exit /B 0

An issue which is similar to my own issue: https://github.com/keras-team/keras/issues/13209


text:
Q: cannot keep backslash in string in ruby code I have a string in my ruby code which ends with a backslash:
acc.secret_key = "ASJSJJDSJFJJFFJJFJF\"
acc.save

Above is the code snippet, when I try to save it using Active record I get an error, I tried adding another slash that is
acc.secret_key = "ASJSJJDSJFJJFFJJFJF\\"
acc.save

But now I have two slashes in the DB. What am I missing? THanks a lot.

A: Are you seeing this in the console?  If thats the case you're just seeing the escaping not two actual backslashes.
string = "1234\\"
# => "1234\\"
string.length
# => 5 (if there were two \\'s the length would be 6)
string
# => "1234\\"
puts string
# 1234\
# => nil

If you look up a record with an escaped backslash in your db console you should see one backslash.
tests_development=> select * from tests WHERE tests.id = 1;
 id |      name       |         created_at         |         updated_at         | public
----+-----------------+----------------------------+----------------------------+--------
  1 | this is a test\ | 2013-02-05 21:44:12.339854 | 2013-02-05 21:44:12.339854 | t
(1 row)

A: acc.secret_key = "ASJSJJDSJFJJFFJJFJF//".to_string
acc.save

this will push the string with the backshash into the database


text:
Q: Не могу решить проблему [i915]] *ERROR* Atomic update Linux Добрый день
NAME="Ubuntu"
VERSION="18.04.4 LTS (Bionic Beaver)"
ID=ubuntu

Эта проблема уже больше 2ох месяцев ......
(Ноут +syslog) много ошибок такого плана но работает нормально вроде как .
....
Product Name: Inspiron 15-3573

-
kernel: [ 5531.010580] [drm:intel_pipe_update_end [i915]] *ERROR* Atomic update failure on pipe A (start=332887 end=332888) time 2158 us, min 763, max 767, scanline start 713, end 16

-
[drm:intel_pipe_update_end [i915]] *ERROR* Atomic update failure on pipe A (start=106733 end=106734) time 1633 us, min 763, max 767, scanline start 728, end 6

-
 *-display
   описание: VGA compatible controller
   продукт: Intel Corporation
   производитель: Intel Corporation
   физический ID: 2
   сведения о шине: pci@0000:00:02.0
   версия: 03
   разрядность: 64 bits
   частота: 33MHz
   возможности: pciexpress msi pm vga_controller bus_master cap_list rom
   конфигурация: driver=i915 latency=0
   ресурсы: IRQ:126 память:81000000-81ffffff память:90000000-9fffffff ioport:f000(размер=64) память:c0000-dffff

*

*Побывал изменить параметр на 1 (Не помогло )
echo 1 > /sys/module/i915/parameters/enable_psr

Есть варианты ?

A: Обновить ядро ++++ -

5.4.0-53-generic


text:
Q: android failed to post data to server Hey i got this kind of error when i post data to server i don't know whats the error and how to handle it
this error come only when i use mobile data and do not occur on wifi or high speed internet
11-06 14:22:09.723: E/AndroidRuntime(18026): FATAL EXCEPTION: IntentService[Empty Constructor]
11-06 14:22:09.723: E/AndroidRuntime(18026): Process: com.androidhive.pushnotifications, PID: 18026
11-06 14:22:09.723: E/AndroidRuntime(18026): java.lang.NullPointerException
11-06 14:22:09.723: E/AndroidRuntime(18026):    at com.androidhive.pushnotifications.CapitalService.downloadUrl(CapitalService.java:123)
11-06 14:22:09.723: E/AndroidRuntime(18026):    at com.androidhive.pushnotifications.CapitalService.onHandleIntent(CapitalService.java:53)
11-06 14:22:09.723: E/AndroidRuntime(18026):    at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
11-06 14:22:09.723: E/AndroidRuntime(18026):    at android.os.Handler.dispatchMessage(Handler.java:102)
11-06 14:22:09.723: E/AndroidRuntime(18026):    at android.os.Looper.loop(Looper.java:136)
11-06 14:22:09.723: E/AndroidRuntime(18026):    at android.os.HandlerThread.run(HandlerThread.java:61)

my Intentservice code Below
 protected void onHandleIntent(Intent intent) {

    subject = intent.getStringExtra("subject");
    length = intent.getStringExtra("length");
    reciever = intent.getStringExtra("reciever");
    sender = intent.getStringExtra("sender");
    Allmex = intent.getStringExtra("Allmex");

    url = "http://";

    try {
        // Retreiving capital from the url
        capital = downloadUrl(url);

        // Creating an intent for broadcastreceiver
        Intent broadcastIntent = new Intent(Constants.BROADCAST_ACTION);

        // Attaching data to the intent
        broadcastIntent.putExtra(Constants.EXTRA_CAPITAL,Allmex);
        broadcastIntent.putExtra("subject", subject);
        broadcastIntent.putExtra("check_no1",length);
        // Sending the broadcast
        LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(broadcastIntent);

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

/** A method to download data from url */
private String downloadUrl(String strUrl) throws IOException{
    String data = "";
    InputStream iStream = null;
    HttpURLConnection urlConnection = null;
    try{
            URL url = new URL(strUrl);

            // Creating an http connection to communicate with url
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setReadTimeout(10000);
            urlConnection.setConnectTimeout(15000);
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("sender",sender));
            params.add(new BasicNameValuePair("reciever",reciever));
            params.add(new BasicNameValuePair("message",Allmex));
            params.add(new BasicNameValuePair("subject",subject));
            params.add(new BasicNameValuePair("id_no",Integer.parseInt(length)-1+""));
            OutputStream os = urlConnection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getQuery(params));
            writer.flush();
            writer.close();
            os.close();

            // Connecting to url
            urlConnection.connect();

            // Reading data from url
            iStream = urlConnection.getInputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

            StringBuffer sb  = new StringBuffer();

            String line = "";
            while( ( line = br.readLine())  != null){
                    sb.append(line);
            }

            data = sb.toString();

            br.close();

    }catch(Exception e){
            Log.d("Exception while fetching data", e.toString());
    }finally{
         iStream.close();
         urlConnection.disconnect();
    }
    return data;
}
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
    StringBuilder result = new StringBuilder();
    boolean first = true;

    for (NameValuePair pair : params)
    {
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
    }

    return result.toString();
}


text:
Q: How to make a command run after login and x start? I need to run xset led 3 after every login how can I do do this? I am on Manjaro using gnome.

A: If you are using a display manager (for example the Gnome-native GDM, take a look at ~/.xprofile, place your command in there to invoke it after the x server has started, but before any gnome is loaded. If you are using a bare-bones startx or xinit approach, take a look at ~/.xinitrc, place your command after the whole resource-merging section, but before the exec gnome-session.
If you want the command to run even in ungraphical logins (such as ssh or serial logins) you are out of luck, since xset needs a running x server.


text:
Q: How to collect the indices of an array X that has the same lengths between elements I am trying to make an array Z that  have indexes of the most frequent occurring difference between two elements in the array X. So if the most frequent occurring difference between two elements in X is 3 then I would get all the indexes in X that have that difference into array Z.
x = [ 0.2 0.4 0.6 0.4 0.1 0.2 0.2 0.3 0.4 0.3 0.6];
ct = 0;
difference_x = diff(x);
unique_x = unique(difference_x);
for i = 1:length(unique_x)
    for j = 1:length(x)
           space_between_elements = abs(x(i)-x(i+1));
           if space_between_elements  == difference_x
                ct = ct + 1;
                space_set(i,ct) = j;
           end
     end
end

I Don´t get the indexes of X containing the most frequent difference from this code.

A: It appears you want to find how many unique differences there are, with "difference" interpreted in an absoulte-value sense; and also find how many times each difference occurs.
You can do that as follows:
x = [ 0.2 0.4 0.6 0.4 0.1 0.2 0.2 0.3 0.4 0.3 0.6]; %// data
difference_x = abs(diff(x));
unique_x = unique(difference_x); %// all differences
counts = histc(difference_x, unique_x); %// count for each difference

However, comparing reals for uniqueness (or equality) is problematic because of finite precision. You should rather apply a tolerance to declare two values as "equal":
x = [ 0.2 0.4 0.6 0.4 0.1 0.2 0.2 0.3 0.4 0.3 0.6]; %// data
tol = 1e-6; %// tolerance
difference_x = abs(diff(x));
difference_x = round(difference_x/tol)*tol; %// apply tolerance
unique_x = unique(difference_x); %// all differences
counts = histc(difference_x, unique_x); %// count for each difference

With your example x, the second approach gives
>> unique_x
unique_x =
         0    0.1000    0.2000    0.3000
>> counts
counts =
     1     4     3     2


text:
Q: OCaml: reference cells, Some, None I am reading the book by Jason, and face the following code.
let x = ref None;;
let one_shot y =
    match !x with
        None ->
            x := Some y;
            y
      | Some z -> z;;

I do not understand the meaning of Some and None here.

A: None is something like is not set or null. if a value matches None, this value is not set.
Some is something like is set with something or not null. if a value matches Some z, this value has a value z.
here, the function one_shot looks !x (the variable in address x). if its None then sets with y and returns y and if is Some z then returns z

A: They are constructors of a built-in OCaml datatype, that you could have defined yourself as such:
type 'a option =
  | None
  | Some of 'a

This means that None if of type 'a option for any 'a, and, for example, Some 3 is an int option.

A: Those are constructors for the built-in option type, defined as follows:
type 'a option = None | Some of 'a

It's a generally useful sum type for representing an optional value, used as such in the example shown in your question.
Worth noting here, it's a built-in type (rather than provided in the Pervasives module) because it's used for inference of the types of functions with optional arguments.
For example, consider the following:
let f ?x () =
  match x with
  | Some x -> x
  | None -> 0

This function has the following type:
val f: ?x:int -> unit -> int


text:
Q: CMake copying Qt runtime libraries to executable output path This question is a duplicate. However, after sifting through other posts, I still can't fix the problem. My problem: When trying to package my application, so after I run cpack, the runtime dependencies Qt5Core.dll, Qt5Gui.dll, Qt5Network.dll, Qt5Svg.dll, Qt5Widgets.dll are placed in the root of the directory, while the executable and the remaining dependences are in the bin folder.
Like I know, I could just copy then contents of the bin folder outside to the root and it'll work but like nah.

My suspicions are not sure but I do believe this issue comes from using the include(GNUInstallDirs). If anyone can provide an explanation and solution. Thank you

Error message when trying to run executable.
This application failed to start because no Qt platform plugin could be initialized! Reinstalling the application may fix this problem.

CMakeLists.txt
cmake_minimum_required(VERSION 3.11.0)

project(Translation_Verification VERSION 1.0.0 LANGUAGES CXX)

set(CMAKE_INCLUDE_CURRENT_DIR ON)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)

find_package(Qt5 5.15 REQUIRED COMPONENTS Core Gui Network Widgets)

set(QONLINETRANSLATOR_VERSION 1.4.5)
include(FetchContent)
FetchContent_Declare(qonlinetranslator
    GIT_REPOSITORY https://github.com/crow-translate/QOnlineTranslator.git
    GIT_TAG ${QONLINETRANSLATOR_VERSION}
)

FetchContent_GetProperties(qonlinetranslator)
if(NOT qonlinetranslator_POPULATED)
    FetchContent_Populate(qonlinetranslator)
    add_subdirectory(${qonlinetranslator_SOURCE_DIR} ${qonlinetranslator_BINARY_DIR})
endif()

set(PROJECT_SOURCES
    src/main.cpp
    src/addlanguagedialog.cpp
    src/addlanguagedialog.ui
    src/verification.cpp
    src/widgetwindow.ui
    src/widgetwindow.cpp
)

include(GNUInstallDirs)
add_executable(Translation_Verification WIN32 ${PROJECT_SOURCES})
target_link_libraries(Translation_Verification QOnlineTranslator Qt5::Core Qt5::Gui Qt5::Network Qt5::Widgets)
install(TARGETS Translation_Verification RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})

target_include_directories(Translation_Verification PUBLIC
    "${qonlinetranslator_BINARY_DIR}/src"
    "${qonlinetranslator_SOURCE_DIR}/src")

##CPack
get_target_property(_qmake_executable Qt5::qmake IMPORTED_LOCATION)
get_filename_component(_qt_bin_dir "${_qmake_executable}" DIRECTORY)

set(CPACK_PACKAGE_NAME "Translation_Verification")
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Translation Verification Installation")
set(CPACK_PACKAGE_VERSION "1.0.0") # Version of installer

if(CMAKE_SYSTEM_NAME MATCHES "Linux")
    install(FILES ${CMAKE_SOURCE_DIR}/translationVerification.desktop DESTINATION share/applications/)
    set(CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION}-linux-${ARCHITECTURE}")
    set(CPACK_GENERATOR "TXZ")

elseif(CMAKE_SYSTEM_NAME MATCHES "Windows")

    set(CPACK_PACKAGE_INSTALL_DIRECTORY "Translation_Verification")
    set(CPACK_NSIS_DISPLAY_NAME ${CMAKE_PACKAGE_NAME})
    set(CPACK_NSIS_COMPRESSOR lzma)
    set(CPACK_NSIS_INSTALLED_ICON_NAME Translation_Verification.exe)
    set(CPACK_NSIS_MENU_LINKS "Translation_Verification.exe" "Translation Verification")
    set(CMAKE_INSTALL_SYSTEM_RUNTIME_DESTINATION ${CMAKE_INSTALL_BINDIR})
    set(CMAKE_INSTALL_UCRT_LIBRARIES TRUE)

    include(InstallRequiredSystemLibraries)
    find_program(WINDEPLOYQT_EXECUTABLE windeployqt HINTS "${_qt_bin_dir}")

    add_custom_command(TARGET Translation_Verification POST_BUILD
                       COMMAND ${CMAKE_COMMAND} -E remove_directory ${CMAKE_BINARY_DIR}/qtDeploy/
                       COMMAND ${WINDEPLOYQT_EXECUTABLE}
                               --release
                               --verbose 1
                               --no-compiler-runtime
                               --no-angle
                               --no-opengl
                               --no-opengl-sw
                               --no-webkit2
                               --no-quick-import
                               --no-translations
                               --dir ${CMAKE_BINARY_DIR}/qtDeploy $<TARGET_FILE:Translation_Verification>
    )
    install(
        DIRECTORY ${CMAKE_BINARY_DIR}/qtDeploy/
        DESTINATION .
        FILES_MATCHING PATTERN "*.*"
    )
    set(CPACK_GENERATOR "ZIP;NSIS")
endif()

set(CPACK_SOURCE_PACKAGE_FILE_NAME "${CPACK_PACKAGE_FILE_NAME}-src")
set(CPACK_SOURCE_GENERATOR "ZIP;TGZ")
include(CPack)

A: You explicitly ask for your result by using DESTINATION . in
    install(
        DIRECTORY ${CMAKE_BINARY_DIR}/qtDeploy/
        DESTINATION .
        FILES_MATCHING PATTERN "*.*"
    )

That could be DESTINATION ${CMAKE_INSTALL_BINDIR} to point to the same directory you use for other binaries.


text:
Q: External API issue in production - React.js I build an app rendering data from an external API. In development mode everything works fine but in production the API doesn't load. It does't return anything not error in console.
axios.get("https://api.github.com/repos/....")
  .then(response => ...)
  .catch(error => console.log(error))

axios.get("https://api.github.com/...")
  .then(response => {
      ....
  })
  .catch(error => console.log(error))

Can anyone tell me what the problem is?

A: You should check the network tab in the console and see which response code that request is returning. The catch block will only be hit if the response code of that request is one of these client errors listed on this website: https://httpstatuses.com/

A: Full code here
Note In development mode.
My signup form work fine, login work fine
But in production none of this work!
I have google during for one week but dont find answer.
import React, {useState, useEffect} from 'react';
import axios from 'axios';
import ShowCase from './utils/table.github.user';
import Validator from "../mm-admin/auth/auth.validator"
const Homepage = () => {

const [organisations, setOrgnisations] = useState([])

const [searchContributor, setSearchContributor] = useState('');
const [searchContributorResult, setSearchContributorResult] = useState([]);

const [isAdded, setAdded] = useState(false);

useEffect(() => {
    let cleanup = false;
    requestApi()
    return () => {
        cleanup = true;
    }

}, [searchContributor])

const requestApi = () =>{
    axios.get("https://api.github.com/repos/git/git/contributors", {
        params : {
            rejectUnauthorized: false,//add when working with https sites
            requestCert: false,//add when working with https sites
            agent: false,//add when working with https sites
        }
    })
    .then(response => {
        const all = response.data;
        const result = all.filter(contributor => {
            return contributor.login.toLowerCase().includes(searchContributor.toLowerCase())
        })
        setSearchContributorResult(result)
    })
    .catch(error => console.log(error))
    axios.get("https://api.github.com/organizations",  {
        params : {
            rejectUnauthorized: false,//add when working with https sites
            requestCert: false,//add when working with https sites
            agent: false,//add when working with https sites
        }
    })
    .then(response => {
        const all = response.data;
        const result = all.filter(contributor => {
            return contributor.login.toLowerCase().includes(searchContributor.toLowerCase())
        })
        setOrgnisations(result)
    })
    .catch(error => console.log(error))
}
const makeSearchContr = event => {
    event.preventDefault()
    setSearchContributor(event.target.value)
}
const addFavorite = (favorite, notes) => event => {
    event.preventDefault();
    if (Validator.isAuthenticated()) {
        const id = Validator.isAuthenticated().user._id;
        const favorites = {
            item : JSON.stringify(favorite),
            note : notes
        }
        axios.put("/user/action/" + id, favorites)
        .then(res => {
            setAdded(true)
            const timer = setTimeout(() => {
                setAdded(false)
            }, 4000)
           return () => clearTimeout(timer)
        })
        .catch(error => console.log(error))
    } else {
        console.log("Need to loged")
    }
}
const contributorGit = () => {
    return searchContributorResult.map((contributor, index) => {
        return <ShowCase key={index} item={contributor} status={isAdded} favorite={addFavorite}/>
    })
}
const organisationsGit = () => {
    return organisations.map((organisation, index) => {
        return <ShowCase key={index} item={organisation} favorite={addFavorite}/>
    })
}
return (

                    <form>

                            <input type="text" className="form-control" placeholder="Search" value={searchContributor} onChange={makeSearchContr}/>

                    </form>

List contributor :

                    {contributorGit()}

List organisation :

                    {organisationsGit()}

)
}
export default Homepage;


text:
Q: lldb python handle process crash or killed I want to do something when a process is crash or killed in a python script.
However I can't find anyway to know when a process is stop by lldb.
I've tried to catch a SIGKILL signal but no use.
import lldb
import signal
def debug(sig, frame):
    print "stop!\n"
def listen():
    signal.signal(signal.SIGKILL, debug)  # Register handler

I've find that we can use this to handle a breakpoint hit, but it can't deal with my situation.
def breakpoint_function_wrapper(frame, bp_loc, dict):

Anyone has some solutions?

A: There's a little sample program in the lldb python examples that shows how to handle process events using the lldb library:
http://llvm.org/svn/llvm-project/lldb/trunk/examples/python/process_events.py
That might help get you started.


text:
Q: Markup syntax and UML / Diagrams I want to use the markup syntax to describe my project. In this, I really like to draw diagrams to create better explanations.
Is there a good, maintainable way to do so? I do not like to draw the diagram somewhere else and then have to update it. A good way would be to draw the diagram directly in markup.
Any good ideas how to do this?
In case this is not possible - which open source UML tool do you prefer then?

A: Good evening!
The UML diagram tools are different.
That's why the tool will be depend on your diagram type.
The most common tool you can use is:

*

*Lucid Chart (as stated above)

*Gliffy https://www.gliffy.com/

*Microsoft Visio

I use StarUML for drawing UML class diagrams (https://staruml.io/).
You can use VisualParadigm or PowerDesigner or EnterpriseArchitect for that purpose, but it's like shooting birds with cannon (too costly).
If you want to draw diagrams from the text, you can use PlantUML. Just add this addon to your EDI, make a file with plantuml format, spend 10 minuts in the guide page (https://plantuml.com/ru/) and draw your sequence by text. You can easy draw UML sequence diagram without any addons. But if you need to make another types of UML diagrams you will have to use some extension for the plantUML.
Here you can find more information:
https://en.wikipedia.org/wiki/List_of_Unified_Modeling_Language_tools

A: You can use Lucid Chart  to draw the UML diagrams. link


text:
Q: Can't submit extended characters in Net::Twitter for search API I an trying to submit a search to the twitter 1.1 search API using Perl and Net::Twitter.  It all works fine when the search string has no extended characters, but if I use non-latin, I get a 401.
Calling url_encode_utf8 on the value leads to double-encoding.
Calling encode('utf8','...') on it gives me a 401.
Can anyone help?
Here's my test case:
#!/usr/bin/perl

use strict;
use warnings;

use Net::Twitter;
use Encode;

my $nt = Net::Twitter->new(
        traits => [qw/API::RESTv1_1/],
        consumer_key => '...',
        consumer_secret => '...',
        access_token => '...',
        access_token_secret => '...',

);

die "unauthorized" unless $nt->authorized;

my $q = 'ﺝﺎﻤﻋﺓ ﺎﻠﻤﻠﻛ ﺲﻋﻭﺩ';

eval{
        my $r = $nt->search({q => $q});
        use Data::Dumper;
        print Dumper $r;
};
if ($@)
{
        print STDERR $@, "\n";
}


text:
Q: Fitted values from a different model in R I was wondering whether it is possible to compute fitted values for a sample of observations which is different from the subsample that has been used to perform a linear regression. In particular, I have a full dataframe of 400 individuals. I want to perform two separate OLS regressions, subsampling the dataframe according to the value of a dummy.
ols1<-lm(log_consumption ~ log_wage + Age + Age2 + Education, data=df,  subset = type==1)
ols2<-lm(log_consumption ~ log_wage + Age + Age2 + Education, data=df, subset = type==0)

this code obviously returns me the two separate models and the corresponding fitted values. However I would like to get the fitted values of all my dataframe (i.e. the fitted values of all the 400 individuals) firstly according to model 1, then according to model 2. Basically I want to compare the fitted values for the entire dataframe exploiting the differences among the OLS coefficients that I get under the two different "regimes".
Is there a way to do this in R??
Thanks for your help,
Marco

A: It looks like you want to predict(). Try: predict(ols1, df) and predict(ols2, df). Here is an example using the iris data set.
## data
df <- iris
df$type <- rep(c(0, 1), 75) # 75 type 0 and 75 type 1

## models
ols1 <- lm(Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width,
           data = df, subset = type == 1)
ols2 <- lm(Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width,
           data = df, subset = type == 0)

## predicted values for all the 150 observations
# just for checking: fitted(ols1) and fitted(ols2) give the 75 fitted values
length(fitted(ols1))
length(fitted(ols2))
# here, we want predicted values instead of fitted values
# the the predict() function, we can obtained predicted values for all the 150 observations
predict(ols1, df)
predict(ols2, df)
# check: we have 150 observations
length(predict(ols1, df))
length(predict(ols2, df))


text:
Q: Use a set of routes to operate upon in app.all() function of node express I have a list of routes in my express application.
I need to perform a particular action on some of these routes.
For eg :
app.get('/xyz', file.xyz);

app.post('/xyz1', file.xyz1);

app.post('/xyz2', file.xyz2);

app.post('/xyz3', file.xyz3);

app.post('/xyz4', file.xyz4);

Now I want to perform similar action for '/xyz2' and '/xyz3' routes.
I came across through:
app.all('*', function (request, response, next) {
  //some action here
  next();
});

I would need to pass something like :
app.all(['/xyz2','/xyz3'], function (request, response, next) {
  //some action here
  next();
});

A: Express routes can be matched using regex.
Try this:
app.all(/\/xyz[23]/, function (request, response, next) {
  //some action here
  next();
});


text:
Q: What does $y = Ar^t$ mean? I keep coming up in this question and its variants in my math tests, but it has not been explained to me so I can't really answer it. As such, I am at risk of failing the year.
An example question is as below:

Bob bought a farm in 1980. In 2017 he sold it for $500,000 and calculated it rose exponentially at a rate of 4% over that time.
(i) Assuming that it increased in value according to the formula $y = Ar^t$, where $A$ is the purchase price and  $^t$  is the time in years, what was his profit?

As you can see, the values of $A$ and $^t$ are pretty clearly defined, and $y$ is implicitly defined, but nowhere is the value $r$ defined.
So what is $r$ supposed to be, and how would I go about answering this question?

A: The $r$ means rate of increase of the price, which is $1 + 4\% = 1.04$.
$$t = 2017 - 1980 = 37 \text{ years}$$
$$y = $500000$$
Now we calculate the value of $A$, which is the purchase price of the farm in 1980.
$$\begin{array}{rcll}
y &=& Ar^t\\
500000&=&A\left(1.04\right)^{37}\\
A&=&\dfrac{500000}{(1.04)^{37}} \\
&\approx&$117148.42
\end{array}$$
Now, the profit is $\text{Selling price} - \text{Purchase price}$:
$$\begin{array}{rcll}
\text{Profit} &=& $500000 - $117148.42\\
&\approx&$382851.58
\end{array}$$
To clarify, $y = Ar^t$ is an exponential equation. Usually $r$ denotes the rate of increase, or the rate of decrease as $r$ stands for "rate".

A: I am not sure what is mean by exponential rate, but assuming that it means continuous compounding, we have the formula
$y(t) = A e^{0.04 t}$, with $t$ in years.
Hence $y(2017) = y(1980) e^{0.04 (2017-1980)} = 500000$ from which can compute $y(1980)$. Then the profit is given by $y(2017)-y(1980) \approx 386181$.

A: The exponential function is:
$$f(x)=ab^x,b>0.$$
Now $b$ can take various values, in particular:
$$b=1+\frac{0.04}{m},m\ne 0$$
Note that when $m=1,2,4,12$, it is the annual, semi-annual, quarterly, monthly interest compounding, respectively. For example, for $x\in \mathbb N$:
$$f(x)=a(1+0.04)^x=a\underbrace{(1+0.04)(1+0.04)\cdots (1+0.04)}_{x}\\
f(x)=a\left(1+\frac{0.04}{2}\right)^{2x}=a\underbrace{\left(1+\frac{0.04}{2}\right)\left(1+\frac{0.04}{2}\right)\cdots \left(1+\frac{0.04}{2}\right)}_{2x}.$$
When $m\to \infty$, the formula of continuous interest compounding becomes:
$$f(x)=\lim_\limits{m\to \infty} a\left(1+\frac{0.04}{m}\right)^{mx}=ae^{0.04x}.$$
=========================================================================
The OP's problem suggests the exponential function $y=Ar^t$. However, it can be interpreted in two ways:
$$y(t)=Ar^t=A(1+0.04)^t=Ag(t)$$
or:
$$y(t)=Ar^t=A(e^{0.04})^t=Ag(t)$$
Note: The first is an ordinary exponential function, while the second is a natural exponential function.
Once it is clarified, the rest is a simple calculation with
$$\begin{align}y(0)&=A,\\
t&=2017-1980=37,\\
y(37)&=500,000\\
\text{Profit}&=\frac{y(37)}{A}=\frac{500,000}{A}=g(37) \ \ \text{(in percentage of the purchase price)}\\
\text{Profit}&=y(37)-A=\\
&=500,000-\frac{y(37)}{g(37)}=\\
&=500,000-\frac{500,000}{g(37)}\ \ \text{(in dollars)}\end{align}$$


text:
Q: One way slide transitions Is there a way to have a transitions only if coming from a particular ''direction'' in beamer?
I explain myself better. I'm doing a presentation and when I come to a particular slide from the linear workflow I want the transition to happen; I then have a reference in the appendix to the same slide and if I come from there I don't want the transition.
Here is the link to a the MWE, (currently) the same as the following:
\documentclass[10pt]{beamer}
\usepackage[utf8]{inputenc}
\usepackage{hyperref}

\mode<beamer>
{
\usetheme{PaloAlto}
}

\begin{document}

\begin{frame}{First slide}
some stuff
\end{frame}

\begin{frame}{I want transition}{\transwipe[direction=180, duration=0.6]}
\label{trans-slide}
I want a transition if I come from the first slide

I don't want it if I come from the appendix
\end{frame}

\appendix
\begin{frame}{Appendix}

\hyperlink{trans-slide}{\beamergotobutton{I don't want transition}}

\end{frame}

\end{document}

Thanks for your help


text:
Q: Postgresql insert trigger to set value Assume in Postgresql, I have a table T and one of its column is C1.
I want to trigger a function when a new record is adding to the table T. The function should check the value of column C1 in the new record and if it is null/empty then set its value to 'X'.
Is this possible?

A: You are correct that you need a trigger, because setting a default value for the column won't work for you - default values only work for null values and don't help you in preventing blank values.
In postgres there are a couple of steps to creating a trigger:
Step 1: Create a function that returns type trigger:
CREATE FUNCTION my_trigger_function()
RETURNS trigger AS $$
BEGIN
  IF NEW.C1 IS NULL OR NEW.C1 = '' THEN
    NEW.C1 := 'X';
  END IF;
  RETURN NEW;
END;
$$ LANGUAGE plpgsql

Step 2: Create a trigger that invokes the above function and fires BEFORE INSERT, which allows you to change the incoming values before they hit the table:
CREATE TRIGGER my_trigger
BEFORE INSERT ON T
FOR EACH ROW
EXECUTE PROCEDURE my_trigger_function()

And you're done.
See the above code executing on SQLFIddle.

You mention in a comment that the value 'X' is retrieved from a subquery. If so, change the relevant line so something like:
NEW.C1 := (select some_column from some_table where some_condition);

A: It is possible but you are likely to be better off setting a default constraint on the column instead. When creating the table that would look like:
create table mytable as (
    C1 thetype not null default X
);

This says that if you add a row to the table and don't specify the value for C1 then X will be used instead. The not null is not necessary, but prevents updates from nulling that column assuming that's what you want.
EDIT: This only works for constant X, from your comments it seems there are two possible solutions.
Using a trigger would look something like this:
create function update_row_trigger() returns trigger as $$
begin
    if new.C1 is NULL then
        new.C1 := X;
    end if;
    return new;
end
$$ language plpgsql;

create trigger mytrigger before insert on mytable for each row execute procedure update_row_trigger();

The new variable in a trigger function is special, representing the row being inserted. Specifying the trigger as a before insert trigger means you can modify the row before it is written to the table.
The second solution would be to use a computed column which Postgres defines in an unusual way:
create or replace function C1(row mytable) returns columntype immutable as $$
begin
    return X; -- where X is an expression using values from `row`
end
$$ language plpgsql;

This creates a function that takes a row of your table and returns a value, you can call it using . notation though, meaning you can do:
select
    *,
    t.C1
from
    mytable t;

The declaration of the function being immutable is optional, but it's needed if you want to index the "column". You would be able to index this column like this:
create index on mytable (C1(mytable));


text:
Q: RTS Style Game With Client-Side Prediction So, I am currently working on an RTS-like multiplayer game. Units are not controllable by players (they attack-move to a location automatically).
I decided not to go full lockstep but instead do a state-based / prediction hybrid. The game is fully simulated on the client with a state packet for every unit distributed only once per second (Position, health etc.). I've read that this is quite a common method of doing things these days but i'm having major issues with it. One clear problem is with health syncing. Damage is dealt locally on every client machine and corrected via the state packet. This results in issues similar to this:

*

*Projectile hits a unit on a client machine, taking him from 100 health down to 50.

*Client only then receives a state packet from the server saying he is on 100 health which spikes it back up.

Of course he will receive another corrective packet later on taking him back down to 50 but this causes really bad visual spikes. This issue gets even worse if you consider the impact of ability damage and such.
Have I completely misunderstood what is required to create a client-predicted game or do I just need to treat every variable on a case-by-case basis? (I.E. Put in silly hacks to make the health not look bad).

A: I would've posted this on Game Dev, as is is primarily a "what can I do?" kind of question but here's fine as there are some technical aspects.
As to your issue, what I'd do is:
Don't let the client predictive sim actually deal damage to units.
Or if you do, have the damage be 1/4 to 1/10th of what it actually is and visually display a value that is Math.min(Math.max(sim_hp, 5%), last_packet_hp), which prevents jumps up, but allows the server to correct downwards (and the client predictive damage acts as a visually pleasing "animation" between the last and current values). The client is also not allowed to reduce a unit's HP below 5% unless it actually dies on the server. Any discrepancies observable at this point can be easily ignored by players (as players are well acquainted with network lag and packet loss).