text:
Q: Find all records where first_name column does NOT start with A-Z I need to extract a subset of results where the value for the first_name column starts with anything other than standard English alphabet letters (i.e. A-Z), for example È. I am banging my head against a brick wall with this - for example, this is how I've been able to get all the records starting with the letter A:
@results = User.where("first_name LIKE ?", "A%").order("first_name ASC")

Any help would be wonderful.
EDIT: I am using a PostgreSQL database.

A: You can use ~ operator to match regular expression. ~ is used to match case sensitive data. So in your case first_name ~ '^[^A-Z]' will give users whose first_name doesn't start with A-Z. To match case insensitive you need to use ~*.
  @results = User.where("first_name ~ ?", "^[^A-Z]").order("first_name ASC")

or
You can also use !~ which gives the unmatched results (i.e.) first_name !~ ^[A-Z] equivalent to first_name ~ ^[^A-Z]. To match case insensitive use !~*.
  @results = User.where("first_name !~ ?", "^[A-Z]").order("first_name ASC")

For more information see documentation

A: This should work in Postgresql
@results = User.where("first_name SIMILAR TO ?", "[A-Z]%")
More info here.


text:
Q: Multivariate normal conditioned on sum of squares
Suppose that $X_i$ are i.i.d. N(0,1) random variables, and set $S =
 \sum_{i=1}^n X_i^2$. Then $S \sim \chi^2_{(n)}$, the $\chi^2$
  distribution with $n$ degrees of freedom. Compute the induced
  probability measure on $\mathbb{R}^n$: $$\mu^s_n(A) := P((X_1, \dots,
 X_n) \in A | S = s),$$ where $A \subset \mathbb{R}^n$ is
  Borel-measurable.

First, a proposed solution. Let $X = (X_1, ..., X_n)$. Then $S = \|X\|^2$. Moreover, for any rotation matrix $O$, $OX$ has the same distribution as $X$. Thus, for any rotation matrix $O$,
$$\mu^s(OA) = P(X \in OA | S = s) = P(O^{-1}X \in A | S = s) = \mu^s(A),$$
so $\mu$ is rotation invariant. Moreover, given that $S = s$, $X$ must lie on the sphere of radius $\sqrt{s}$, and $\mu^s(\mathbb{S}_{\sqrt{s}}^{n-1}) = 1$, where $\mathbb{S}_{\sqrt{s}}^{n-1}$ denotes the $n-1$-sphere in $\mathbb{R}^n$ of radius $\sqrt{s}$. Thus $\mu$ is a rotation-invariant probability measure which takes full mass on the $n-1$-sphere; by uniqueness of such measures, $\mu$ must be the uniform distribution on the $n-1$-sphere.
The problem I have is computing this explicitly. This measure is singular with respect to $\mathbb{R}^n$-Lebesgue measure, though theorems on regular conditional probabilities tell me this is a well-defined measure for each $s$.
Problem
Take $n = 2$, let $R^2 = X_1^2 + X_2^2$, $\theta = \arctan(X_2/X_1)$. We have
$$\left|\begin{pmatrix} \frac{\partial R}{\partial X_1} & \frac{\partial R}{\partial X_2} \\ \frac{\partial \theta}{\partial X_1} & \frac{\partial \theta}{\partial X_2}\end{pmatrix}\right| = \left|\begin{pmatrix} \frac{X_1}{\sqrt{X_1^2+X_2^2}} & \frac{X_2^2}{\sqrt{X_1^2+X_2^2}} \\ \frac{-X_2}{X_1^2+X_2^2} & \frac{X_1}{X_1^2+X_2^2}\end{pmatrix}\right| = \frac{1}{R}.$$
Hence, using independence of $X_1$ and $X_2$ and the density for a standard normal,
$$f(R,\theta) = f_{X_1,X_2}(X_1, X_2)\left|\frac{\partial (R,\theta)}{\partial (X_1,X_2)}\right|^{-1} = \frac{1}{2\pi}e^{-R^2}R.$$
From this we see further that $R$ and $\theta$ are actually independent, with $\theta$ being uniform on $(0,2\pi)$ (I know this is not the case in higher dimensions). Thus, the desired density should be
$$f(R,\theta | S = s) = \frac{f(s,\theta)}{f(s)} = \frac{1}{2\pi},$$
but this doesn't take into account the radius of the sphere.
I suspect the problem is with having a density on an $n-1$ dimensional submanifold and not taking into account the volume form correctly, but I'm not sure how to fix this. I'd also like some rigorous explanation of why (or if!) I am allowed to just apply the rules for conditional density like I did. Any help appreciated.

A: Actually, when $n=2$, the density of $(R,\Theta)$ is the function $f_{R,\Theta}$ defined by
$$f_{R,\Theta}(r,\theta)=r\mathrm e^{-r^2/2}\mathbf 1_{r\gt0}\,\frac1{2\pi}\mathbf 1_{0\leqslant\theta\lt2\pi}.
$$
Thus, for every $r\gt0$, the conditional density of $\Theta$ conditionally on $R=r$ is the function $g_{\Theta\mid R=r}$ defined by
$$
g_{\Theta\mid R=r}(\theta)=\frac1{2\pi}\mathbf 1_{0\leqslant\theta\lt2\pi}.
$$
Since $g_{\Theta\mid R=r}$ does not depend on $r$, one sees that $R$ and $\Theta$ are independent.
Likewise, in every dimension $n\geqslant2$, the spherical coordinates read
$$
(X_1,\ldots,X_n)=R\cdot Z,
$$
where $R$ is in $[0,\infty)$ and $Z$ in $S^{d-1}$. Then, $R$ and $Z$ are independent and $Z$ is uniformly distributed on $S^{d-1}$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Threading in node.js How single threaded architecture makes node js more efficient than a multi threaded architecture?

A Node.js app runs in a single process, without creating a new thread for every request. Node.js provides a set of asynchronous I/O primitives in its standard library that prevent JavaScript code from blocking and generally, libraries in Node.js are written using non-blocking paradigms, making blocking behavior the exception rather than the norm.

reference for above sentence(node js documentation)

A: It doesn't.
Using a single thread eliminate some classes of bugs (race conditions). Using evented IO improves performance for some workloads (mostly IO-bound with many simultaneous connections)


text:
Q: Is antisymmetry equivalent to alternativity? Reading my class's lecture notes, the definition of the determinant is given as follows:
A function $det: (F^n)^n \rightarrow F$ such that it satisfies the following:

*

*Multilinearity: $det(\dots, v_j+v_j',\dots)=det(\dots, v_j,\dots) +
    det(\dots, v_j',\dots)$ and $det(\dots, c*v_j,\dots)=c*det(\dots,
    v_j,\dots)$ for $c \in F$

*Antisymmetry: $det(\dots, v_j, \dots, v_i, \dots)=-det(\dots, v_i,
    \dots, v_j, \dots)$

*Normalization: $det(e_1, \dots, e_n)=1$
Then there is a claim that alternatively, we can take Alternativity instead of Antisymmetry because they are equivalent.

Alternativity: $det(\dots, v_j, v_j, \dots)=0$

I can see that Antisymmetry implies Alternativity: $det(\dots, v_j, v_j, \dots)=-det(\dots, v_j, v_j, \dots)$, implying that $det(\dots, v_j, v_j, \dots)=0$.
And going from Alternativity to Antisymmetry, my guess was to use Multilinearity: $det(\dots, v_i, v_j, \dots)+det(\dots, v_j, v_i, \dots)=det(\dots, v_i+v_j, v_j+v_i, \dots) = 0$.
My question is, is there a way to go from Alternativity to Antisymmetry without relying on Multilinearity?

A: The properties of alternativity and antisymetry are defined only for multilinear applications (or at least, this is what we are dealing with right now).
Be careful that, in general (and for multilinear applications), the alternativity is a stronger property than antisymetry, and these two properties are equivalent if the base field has characteristic different than 2.
As you can see with your proof, if $f$ is a multilinear antisymmetric application, you end up with an equality that looks like :
\begin{equation}
f(x,x,x_3,..., x_n) = -f(x,x,x_n,...,x_n)
\end{equation}
So what you actually get is
\begin{equation}
2f(x,x,x_3,...,x_n) = 0
\end{equation}
If you want to deduce that $f(x,x,x_3,..,x_n) = 0$, you need to know that the base field has characteristic $\neq 2$.

A: $f$ defined by $f(x,y) = 0$ if $x = y$ and $f(x,y) = 1$ if $x \neq y$ respects alternativity. Not Antisymmetry.
I think there is no way to not use multilinearity.


text:
Q: Redshift Python encrypt/decrypt UDF Error - String contains invalid or unsupported UTF8 codepoints I want to create the below encrypt and decrypt UDF's in Redshift.
Library:
create library pyaes
language plpythonu
from 's3://aws_python/library/pyaes/pyaes.zip'
credentials 'aws-role'
region as 'aws-region';

Encrypt:
CREATE OR REPLACE FUNCTION test.aes_encrypt(input varchar(max))
RETURNS varchar(max) AS
'    if input is None:
        return None
    import pyaes
    key = ''abcdefghijklopoo''
    aes = pyaes.AESModeOfOperationCTR(key)
    encrypted_msg = aes.encrypt(input)
    return encrypted_msg
'
LANGUAGE plpythonu STABLE;

Tried with below options as well:
encrypted_msg = aes.encrypt(input.encode("utf8"))
 key = key.encode('utf-8')

Decrypt:
CREATE OR REPLACE FUNCTION test.aes_decrypt(encrypted_msg varchar(max))
RETURNS varchar(max) AS
'
    if encrypted_msg is None or len(str(encrypted_msg)) == 0:
       return None
    import pyaes
    key = ''abcdefghijklopoo''
    aes = pyaes.AESModeOfOperationCTR (key)
    decrypted_msg = aes.decrypt(encrypted_msg).decode("utf8")
    return decrypted_msg
'
LANGUAGE plpythonu STABLE;

select aes_encrypt('Testing');
select aes_decrypt('');
But it's throwing below error:
Error: Invalid operation: String contains invalid or unsupported UTF8 codepoints. Bad UTF8 hex sequence: d5 fc (error 4);
Please advise. Thanks in advance.

A: I worked this through in a notebook where I could view the outputs.  Basically an error occurs while the AES function is happening that you can't see the output of, and it passes a bad type back to Redshift because aes returns as a byte.
PLEASE NOTE: THIS IS MEANT FOR ENCRYPTED OBFUSCATION OF COLUMNS OF DATA and is not server side encryption.  If security is critical please go encrypt your whole database.  If you're going to use this to protect your customers data, please don't, please encrypt salt and hash everything etc etc.  THIS IS your DISCLAIMER.
This needs to be converted to something redshift can deal with like hex, so use
'binascii.hexlify(cipher_txt)' to get the value back in a printable manner.
CREATE OR REPLACE FUNCTION aes_encrypt(input VARCHAR(20000))
RETURNS VARCHAR STABLE AS $$
  import pyaes
  import binascii
  if input is None:
    return None
  key = 'abcdefghijklnosp'
  aes=pyaes.AESModeOfOperationCTR(key)
  cipher_txt=aes.encrypt(input)
  cipher_txt2=binascii.hexlify(cipher_txt)

  return str(cipher_txt2.decode('utf-8'))

$$ LANGUAGE plpythonu ;

Note the decode on return is redundant, and the cipher texts are split into lines to illustrate.  I'm sure you can put them back into one line.  like
    cipher_txt=binascii.hexlify(aes.encrypt(input))
To unencrypt:
CREATE OR REPLACE FUNCTION aes_decrypt(encrypted_msg varchar(max))
RETURNS VARCHAR STABLE AS $$
  import pyaes
  import binascii
  if encrypted_msg is None or len(str(encrypted_msg)) == 0:
       return None
  key = 'abcdefghijklnosp'
  aes = pyaes.AESModeOfOperationCTR(key)
  encrypted_msg2=binascii.unhexlify(encrypted_msg)
  decrypted_msg2 = aes.decrypt(encrypted_msg2)
  return str(decrypted_msg2.decode('utf-8'))
$$ LANGUAGE plpythonu ;

Also - side note - you don't need to specify length of the return varchar unless you need to for some other reason (unions or some-such) - because making everything max is a waste of space.


text:
Q: How to write this SQL against Oracle? I have 5 tables:
TABLE_A:
    A_ID

TABLE_B:
    A_ID
    B_ID
TABLE_C:
    B_ID
    C_ID
    C_SOME_NUMBER

TABLE_D:
    A_ID
    D_ID
TABLE_E:
    D_ID
    E_ID
    E_SOME_NUMBER

As you can see, the mapping relationships are:
1 A --> n B
1 B --> n C
1 A --> n D
1 D --> n E

I want to write a SQL to calculate: the count of A_ID that:
sum(C_SOME_NUMBER) != sum(E_SOME_NUMBER)

But I don't know how to write this sql. My DB is Oracle

A: select
    count(Q1.ID) as 'whoopsie'
from
    (
        select
            a.ID,
            sum(c.some_number) as someNum
        from
            TA a,
            TB b,
            TC c
        where
            a.ID=b.IB
            and b.ID=c.ID
        group by
            a.ID
    ) Q1,
    (
        select
            a.ID,
            sum(e.some_number) as someNum
        from
            TA a,
            TD d,
            TE e
        where
            a.ID=d.IB
            and d.ID=e.ID
        group by
            a.ID
    ) Q2
where
    Q1.ID=Q2.ID
    and Q1.someNum != Q2.someNum


text:
Q: Improve Alexa rating with requests I have a site and android app of it and many users are using my site's app.
In my app i use HttpPost, HttpGet and HttpClient for sending request to my server.

My question is how can i tell Alexa in every request that a user visited my site and uses its services.


text:
Q: Undo adding disks to a RAID-Z Configuration I've started running out of space on one of my data pool and decided to expand it by adding some extra disks. Below is what it looked like before extending:
        NAME                       STATE     READ WRITE CKSUM
    data                       ONLINE       0     0     0
      raidz1-0                 ONLINE       0     0     0
        c0t5000C50041BF93A7d0  ONLINE       0     0     0
        c0t5000C50041FEBCFFd0  ONLINE       0     0     0
        c0t5000C50041FEBE1Bd0  ONLINE       0     0     0
        c0t5000C50041FEC223d0  ONLINE       0     0     0
        c0t5000C50041FECC0Bd0  ONLINE       0     0     0
        c0t5000C500422BAF33d0  ONLINE       0     0     0

Now after extending the pool I've got first set of drives in raidz1 and the second set using raidz2
        NAME                       STATE     READ WRITE CKSUM
    data                       ONLINE       0     0     0
      raidz1-0                 ONLINE       0     0     0
        c0t5000C50041BF93A7d0  ONLINE       0     0     0
        c0t5000C50041FEBCFFd0  ONLINE       0     0     0
        c0t5000C50041FEBE1Bd0  ONLINE       0     0     0
        c0t5000C50041FEC223d0  ONLINE       0     0     0
        c0t5000C50041FECC0Bd0  ONLINE       0     0     0
        c0t5000C500422BAF33d0  ONLINE       0     0     0
      raidz2-1                 ONLINE       0     0     0
        c0t5000C50034245B57d0  ONLINE       0     0     0
        c0t5000C500350A3847d0  ONLINE       0     0     0
        c0t5000C50042033AA7d0  ONLINE       0     0     0
        c0t5000C500421FBD03d0  ONLINE       0     0     0
        c0t5000C500422B9737d0  ONLINE       0     0     0
        c0t5000C5005678B8BFd0  ONLINE       0     0     0

This is my mistake, no excuse. My question is how do I undo this operation so I can setup the drives again to have raidz1-0 and raidz1-1? Data is being written to the data pool only during the night as this is a backup pool.

A: You've messed up... Sorry.
I'd love to see the output of zpool history data. But my guess is that you wanted to add more disk space, but instead, you added a group of 6 disks in a RAIDZ2 and set it to stripe with your RAIDZ1 set.
You should know that RAIDZ vdevs aren't expandable... the only way to "grow" the pool is by adding another vdev. You were trying to create something like RAID 5+0 and possibly mistyped?
Either way, there's no option to unstripe these two vdevs. Do you have the ability to send the data somewhere else, reformat and try again?


text:
Q: Calculate differences between pairs of consecutive variables, AND retain all original rows and columns using dplyr in R I would like to calculate differences between pairs of consecutive variables in a rowwise manner, AND retain all rows using dplyr in R.
The first part of calculating differences works well on condition that the starting dataframe (df2) has no row with ALL NAs in the pairs (var1-var9) used in the calculations.
However I would like to tweak this solution, so such that besides calculating the required differences, it also retains the rows where the pairs (var1-var9) used in the calculations all have NAs in them, as well as all the columns that were present originally.
Below is the code I am working with and dataset:
library(tidyverse)

df2 %>%
    bind_cols(df2 %>%
                  rowid_to_column() %>%
                  gather(col, val, var1:var9) %>%
                  group_by(id) %>%
                  mutate(val = val - lag(val)) %>%
                  filter(!is.na(val)) %>%
                  mutate(col = paste0("diff_", col)) %>%
                  spread(col, val)  %>%
                  select(contains("diff"))
    )

Dataset:
df2 <- structure(list(var1 = c(17, 16, 14, 16, 16, 11, 13, 16, 16, 16,
16, 14, 16, 12, 16, 16, 16, 17, 14, 15, 13, 13, 16, 0, 13, 15,
12, 10, 13, 16, 16, 15, 12, 15, 12, 11, 11, 16, 15, 14, 16, 0,
15, 16, 16, 16, 16, 16, 15, 16, 11, 16, 11, 16, 16, 14, 14, 0,
12, 16, 16, 1, 11, 14, 16, 12, 11, 12, 16, 2, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA), var2 = c(17, 16, 15, 17, 17, 16, 13,
16, 16, 16, 16, 15, 16, 12, 16, 16, 16, 17, 14, 15, 13, 13, 16,
0, 13, 15, 13, 10, 13, 16, 16, 15, 12, 16, 12, 11, 12, 16, 15,
15, 17, 0, 15, 16, 16, 16, 16, 16, 15, 16, 11, 16, 11, 16, 16,
15, 14, 0, 13, 16, 16, 2, 11, 14, 16, 12, 16, 12, 16, 11, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA), var3 = c(17, 16, 15, 17,
17, 16, 13, 17, 16, 16, 17, 15, 17, 13, 16, 17, 17, 18, 15, 16,
13, 14, 17, 0, 13, 16, 13, 11, 14, 17, 16, 16, 12, 16, 13, 12,
13, 16, 16, 16, 17, 1, 16, 16, 17, 17, 17, 16, 15, 17, 11, 16,
11, 16, 17, 17, 15, 0, 14, 17, 17, 11, 11, 16, 16, 12, 17, 12,
16, 7, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), var4 = c(NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, 14, NA, NA, NA, NA, NA, NA, NA, NA, 16, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, 7, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), var5 = c(NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, 14, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, 14, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA),
    var6 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 16, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA), var7 = c(NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, 19, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA), var8 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 25, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA), var9 = c(NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, 27, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA), wt = c(17, 16, 15, 17, 17, 16, 13, 17, 16, 16, 17,
    15, 17, 13, 16, 17, 17, 18, 15, 16, 13, 14, 17, 0, 13, 16,
    13, 11, 14, 17, 16, 16, 12, 16, 13, 12, 13, 16, 16, 16, 17,
    1, 16, 16, 17, 17, 17, 16, 15, 17, 11, 16, 11, 16, 17, 17,
    15, 0, 14, 17, 17, 11, 11, 16, 16, 12, 17, 12, 16, 7, 2,
    5, 12, 9, 15, 19, 21, 3, 14, 47), plt = c(17, 16, 14, 16,
    16, 11, 13, 16, 16, 16, 16, 14, 16, 12, 16, 16, 16, 17, 14,
    15, 13, 13, 16, 0, 13, 15, 12, 10, 13, 16, 16, 15, 12, 15,
    12, 11, 11, 16, 15, 14, 16, 0, 15, 16, 16, 16, 16, 16, 15,
    16, 11, 16, 11, 16, 16, 14, 14, 0, 12, 16, 16, 1, 11, 14,
    16, 12, 11, 12, 16, 2, 2, 5, 12, 9, 15, 19, 21, 3, 14, 47
    ), dir = c(17, 16, 15, 17, 17, 16, 13, 16, 16, 16, 16, 15,
    16, 12, 16, 16, 16, 17, 14, 15, 13, 13, 16, 0, 13, 15, 13,
    10, 13, 16, 16, 15, 12, 16, 12, 11, 12, 16, 15, 15, 17, 0,
    15, 16, 16, 16, 16, 16, 15, 16, 11, 16, 11, 16, 16, 15, 14,
    0, 13, 16, 16, 2, 11, 14, 16, 12, 16, 12, 16, 11, 2, 5, 12,
    9, 15, 19, 21, 3, 14, 47), conv = c(NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, 25, 2, 5, 12, 9, 15, 19, 21, 3, 14, 47), conv2 = c(17,
    16, 14, 16, 16, 11, 13, 16, 16, 16, 16, 14, 16, 12, 16, 16,
    16, 17, 14, 15, 13, 13, 16, 0, 13, 15, 12, 10, 13, 16, 16,
    15, 12, 15, 12, 11, 11, 16, 15, 14, 16, 0, 15, 16, 16, 16,
    16, 16, 15, 16, 11, 16, 11, 16, 16, 14, 14, 0, 12, 16, 16,
    1, 11, 14, 16, 12, 11, 12, 16, 2, 2, 5, 12, 9, 15, 19, 21,
    3, 14, 47), id = 1:80), row.names = c(NA, -80L), class = c("tbl_df",
"tbl", "data.frame"))


text:
Q: Get the display name dynamically inside Django view? I have a model called person like this
class person(models.Model):
    choice1 = ("a","DisplayNameA", "b", "DisplayNameB")
    choice1_field = models.CharField(max_length=1, choices=choice1)
    choice2 = ("c","DisplayNameC", "d", "DisplayNameD")
    choice2_field = models.CharField(max_length=1, choices=choice2)
    # and so on, there are many fields like these

After this, I am trying to generate a CSV file in my views
I can loop through all the fields I need and then access the values dynamically like this
getattr(person_object, field_name)

However this returns "a", "b" and so on.
I know I can access the display name using get_FOO_display(), where foo is the field's name. However, as the retrieval of the field is happening dynamically, is there a way to access the display name of a field dynamically? Without having to bind functions?

A: You can pass get_fieldname_display to the getattr function:
getattr(person_object, 'get_{}_display'.format(field_name))()
or you can make use of the methodcaller of the operator package:
from operator import methodcaller

mygetter = methodcaller('get_{}_display'.format(field_name))

result = mygetter(person_object)


text:
Q: How to block a cross domain script? The action in a controller of domain1:
def show
  respond_to do |format|
    format.html
    format.js { render js: 'alert("Foo")' }
  end
end

When I call get this js format in my domain2 view, the alert works.
<script type="text/javascript" src="http://domain1/action.js"></script>

However, I was expecting it to not work since the js script is provided by the domain1.
I believe it is a Cross-Domain request. I am wrong?
How can I block it in Rails (using cors - I´m not considering authentication)?
request headers:
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Cookie:language=en; JSESSIONID=548BBE8340E2BCF88CC79FD406D87201; _session_id=36e9c1d96dd60d139edc669e4eb5311a
Host:domain1
If-None-Match:"4160518da6c411ed4f844684e3bd82e8"
Referer:https://domain2/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36

response headers:
Cache-Control:max-age=0, private, must-revalidate
Content-Length:13
Content-Security-Policy:default-src * 'unsafe-inline' 'unsafe-eval'; connect-src * 'unsafe-inline' 'unsafe-eval'; font-src * 'unsafe-inline' 'unsafe-eval'; frame-src * 'unsafe-inline' 'unsafe-eval'; img-src * 'unsafe-inline' 'unsafe-eval' data:; media-src * 'unsafe-inline' 'unsafe-eval'; object-src * 'unsafe-inline' 'unsafe-eval'; script-src * 'unsafe-inline' 'unsafe-eval'; style-src * 'unsafe-inline' 'unsafe-eval';
Content-Type:text/javascript; charset=utf-8
Date:Thu, 02 Jul 2015 14:36:17 GMT
Etag:"68a0bef3fb4d7408f31dfd3d2958cb4d"
Server:WEBrick/1.3.1 (Ruby/1.9.3/2013-11-22)
Strict-Transport-Security:max-age=631138519
X-Content-Type-Options:nosniff
X-Frame-Options:SAMEORIGIN
X-Request-Id:136ef12c007055e756e4ac1b7de83046
X-Runtime:0.264848
X-Ua-Compatible:IE=Edge
X-Xss-Protection:1

A: You can include code from any domain, this is how libraries like google maps work.
What you can't do in JavaScript is make (XMLHTTP)requests to other domains unless those domains have an origin policy that allows your domain.
Including is a script is not considered a cross domain request (this is also how JSONP gets around the origin restrictions). Outputting a CORS policy is not going to stop the request.
As to how you can block the request. It depends on your situation. If you're offering the scripts as part of an API suite your best bet is to use authentication tokens.


text:
Q: Javascript won't run inside partial view when partial view is loaded Using chartJS I'm trying to load a bar chart in a partial view. It works on my layout page. But I want it to work in a partial view. But, when I click on a link to render a partial view with the chart inside it doesn't work. What could I be doing wrong?

    <meta name="viewport" content="width=device-width" />

    <title>Index</title>

Here is the Layout page for a bit more detailed information of my code.
<!DOCTYPE html>

        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>@ViewBag.Title MM-3</title>
        <link href="@Url.Content("~/Content/bootstrap.css")" rel="stylesheet" type="text/css" />

        @Scripts.Render("~/bundles/modernizr")
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/unobtrusive")
        @model IEnumerable<RoboticUI.Models.ResultantRead>

        <link rel="stylesheet" type="text/css" href="~/Content/MainRobotFrontier.css?version=1" />

Robot Gallery

                @Ajax.ActionLink("Robot", "Robot", "Chart", new AjaxOptions() { UpdateTargetId = "navResult" })
                @Ajax.ActionLink("Data", "Data", "Home", new AjaxOptions() { UpdateTargetId = "navResult" })
                @Ajax.ActionLink("Client", "Client", "Home", new AjaxOptions() { UpdateTargetId = "navResult" })

Lorum Ipsum

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

        Copyright &copy MMM

    @RenderBody()

With help from Jesse, I turned my problem into a solution. But, now the my div element doesn't expand according to the chart's height and width.enter image description here

A: Thanks for working with me there.  I think I know what's going on.
Since "test" isn't appearing in your dev console after adding a console log, we can be pretty sure that the function is not being called..
I'm not too familiar with the @Ajax.ActionLink, but I'm betting that it doesn't do a page refresh and uses Ajax to load the new view onto the page.
You might want to try to do what they did here:
Running scripts in an ajax-loaded page fragment
Actually according to this post, it's not even a good practice to do this:
ASP.NET MVC Loading scripts in partial views
I also think that the function that you're expecting to be called will not be called after the ajax takes place as the "window" has already been loaded.  when you had the script in the layout, it was present when the window was loading, but in your current scenario the script isn't on your page until AFTER your window is done loading, so it will never fire.
(that's why i was thinking the first link would help with an "ajax on load" callback vs the "window on load" callback)
Beyond that I was afraid of mvc razor's @ not being handled correctly if it's loaded through ajax, but that may not end up being an issue if you can figure out the rest.
I think the best practice here might be a success callback after the Ajax.ActionLink is done doing its thing.
If you look here (and i'm sure elsewhere) you can see an example of people using a success callback for your Ajax.ActionLink:
 How to tell Ajax.ActionLink OnSuccess callback which element initiated the ajax
I think what you're going to want to is remove your script from the partial view and put it somewhere that it is always present, like back in your layout.  However, you're just going to encase it in a regular javascript function, and it's just going to be hanging out on the page.
function myfunction() {}

instead of your
window.onload = {}

Now to tie it all together you'll just call this myfunction() as your ActionLink's success callback.
The idea here is after your ActionLink loads the new elements onto the page, the success callback will call the myfunction and run your custom code.  It should give you the same effect as if the script had just been loaded through the Ajax.ActionLink


text:
Q: Graduate Level Degree for Simulation/Statistics/Prediction? I am wondering if anyone has any insight into this. I am thinking of going to grad school to get some computer science related degree. I have always been intrigued by people who are working on problems using statistical packages or simulation to solve problems. What would I study to get a good breadth of knowledge of these things? Do they fall into machine learning?
Thanks

A: My girlfriend is getting a degree in mathematics with an emphasis in Statistics and   Operations Research.
She does a lot of work with SAS and other statistical software to maximize certain functions and predict the likelihood of future events.  It may be more mathematics then you like, but you might try looking for masters of CS programs with an emphasis in Operations Research or Statistics.

A: There's a wide range of possible opportunities here.  Let me add the following choices:

*

*Physics with a focus on complex networks.  This has applications in biology, epidemiology, sociology, finance, and computer science.

*A good machine learning program, with statistics, data mining, text analysis, and computational learning theory.

*Industrial engineering/operations research, with simulation, reliability, and process control.

I'd be happy to talk further about this, please put questions in comments.

A: I would assume that your school would offer some actual Statistics courses, probably in the Math department, which you could take to learn all about this.

A: Study a lot of mathematics, especially probability and statistics. I have a graduate simulation course right now, and I wish I knew more probs/stats stuff.

A: In Biostatics (at the U of Minnesota), we did a lot of simulation, in areas like Bayesian statistics, genetics, and others.   Any strongly analytical program is a good candidate for teaching the skills you want, including:  econ, econometrics, agronomics, statistical genetics... etc., etc., :)
While you're waiting, pick up R, Matlab (Octave is the free implementation), or your Turing-Complete language of choice, dig into Wikipedia, and get to work :)

A: I'd like to second Gregg Lind's recommendation of thinking about statistics in the biological sciences. It's well-funded, there's a lot of interesting work going on (both theoretical and applied!), and you can sound really cool at parties because somehow, someway you can always make some sort of connection from your work back to curing cancer. :)
Seriously though, a lot of great statistical work was done in the early 20th century by people like Haldane, Fiscer and Wright. More recent interesting work has been done on analysis or large data sets, multiple hypothesis testing, and applied machine learning. It's super exciting. Come join us!


text:
Q: Using Zabbix with Active Agent, How to determine the correct key. (LLD) I'm trying to do a discovery to get info from antivirus software.
In zabbix_agentd.conf i put this:
UserParameter=custom.discovery, cscript c:\soft\zabbix\av.vbs //NOLOGO

With this result:
{"data":[
{"{#DISPLAYNAME}": "ESET Endpoint Security 6.4.2014.2",
"{#PRODUCTSTATE}": "266240",
"{#TIMESTAMP}": "Tue, 18 Jul 2017 21:24:26 GMT"},
{"{#DISPLAYNAME}": "Windows Defender",
"{#PRODUCTSTATE}": "393472",
"{#TIMESTAMP}": "Thu, 10 Nov 2016 12:20:52 GMT"}
]}

My Discovery rule is this:
Name: Antivirus
Type: Zabbix Agent (Active)
key: custom.discovery

And i create this item prototype:
Name: Antivirus {#DISPLAYNAME}
Type: Zabbix Agent (Active)
Key: custom.discovery[ {#DISPLAYNAME}, PRODUCTSTATE]

My problem is when the item trying to get the "Productstate", the items are discovered correctly, but without value.
At the Configuration/Host/Item, i see the error "Item does not allow parameters" in each item created from the discovery.
Somebody can help me? Thx!

A: You should have separate userparameter to get item values, and that key should be used in the item prototypes. Your LLD rule key should not return item values.


text: Q: Pipeline deploy to android APK to app store I currently use bitbucket as my repo for my react native android projects, bitbucket has pipelines which allow me to build an apk. However, I cannot find or figure out how it then automatically deploy this to the play store via the playstores api. Could anyone one point me in the right direction? Thanks.


text:
Q: React redux not updating data I am fetching data from api with axios.When action completed and data not changed.
components/HomeContainter:

    class HomeContainer extends Component {

    static propTypes = {
        posts: PropTypes.object.isRequired
    };

    componentDidMount()
    {
        this.props.fetchPosts();
    }

    render() {
        return (

Ana Sayfa

                    <PostList posts={this.props.posts}></PostList>

        );
    }
}

const mapStateToProps = ({ posts }) => {
    return {
        posts
    }
};

const mapDispatchToProps = {
    fetchPosts
}

export default connect(mapStateToProps, mapDispatchToProps)(HomeContainer);

actions/Posts.js:
        export const FETCH_POSTS_PENDING = 'FETCH_POSTS_PENDING';
        export const FETCH_POSTS_FULLFILLED = 'FETCH_POSTS_FULLFILLED';
        export const FETCH_POSTS_ERROR = 'FETCH_POSTS_ERROR';

       export function fetchPosts()
       {
           return dispatch => {
               dispatch({
                   type: 'FETCH_POSTS',
                   payload: axios.get(API_BASE + '/posts/get/1')
                    .then(result => result.data)
            })
        }
    }

reducers/posts.js:
    const initialState = {
        fetching: false,
        posts: [],
        error: {}
    };

    export default (state = initialState, action) => {
        switch (action.type) {
            case FETCH_POSTS_PENDING:
                return {
                    ...state,
                    fetching: true,
                };
            case FETCH_POSTS_FULLFILLED:
                console.log(state)
                return {
                    ...state,
                    fetching: false,
                    posts: action.payload,
                };
            case FETCH_POSTS_ERROR:
                return {
                    ...state,
                    posts: action.payload,
                    fetching: false,
                };

            default:
                return state;
        }
    }

component/postlist.js:
    const PostList = ({ posts }) => {

        const emptyMessage = (

Görüntülenecek gönderi yok!

        );

        console.log(posts)
        const postList = (

                {
                    posts.posts.map(post => post.id)
                }

        );

        return (

                <SyncLoader color={'#E8B723'} loading={posts.fetching} />
                { posts.length === 0 ? emptyMessage : postList }

        );
    }

    PostList.propTypes = {
        posts: PropTypes.shape({
            posts: PropTypes.array.isRequired
        }).isRequired
    };

    export default PostList;

And results:
stuck loader
log

A: Your logic runs asynchronously which means there's no guarantee that a piece of code finishes running before another starts.
In the case for:
   export function fetchPosts()
   {
       return dispatch => {
           dispatch({
               type: 'FETCH_POSTS',
               payload: axios.get(API_BASE + '/posts/get/1')
                .then(result => result.data)
        })
    }

What's likely happening is that the action is dispatched before the axios request actually finishes. The order of operations is wrong. You're not actually using result.data, you're not assigning it to payload either.
Since you're using some sort of Redux-middleware (probably thunk), you can rework your code like this:
   export function fetchPosts(){
       return (dispatch) => {
           axios.get(API_BASE + '/posts/get/1')
                .then((res) => {
                      dispatch({
                          type: 'FETCH_POSTS',
                          payload: res.data
                      })
                 })
       }
    }

Thus the Promise is completed before dispatching the action.


text:
Q: Custom field history tracking on partial update? I would like to track more than 20 fields on my custom objects, so built a logic almost same as What is the best workaround for the 20 field history tracking cap?. This works most of the time if you are using update commands. But if you are using update commands on Database class like Database.update(sObjects, false) which allows partial updates, how can we know which objects are successfully updated and which objects are not? Is there any way to retrieve the addError that was added on a sObject in trigger?

A: Your question is a bit of an X-Y problem, but basically, you can't determine from within the trigger context if errors have been added to a record or not. You can only determine the errors from the calling context (e.g. the API or upper-level context that called Database.update(records, false)). However, it doesn't matter. The history records you create during your trigger will automatically be rolled back in the case of a failed update (the system creates a save point, then rolls back if any errors occur before trying again).


text:
Q: How to wait for the result in a single function for all callbacks in node.js? May be question title not appropriate but I can explain what I want to do in my code
// One  Callback Function
  connection_db.query(get_measure_query,function(err,user_data1){
        if(err){
          // throw err;
          let response_data = status_codes.db_error_0001;
          console.log(response_data);
          res.end('error');
        }else {

    }

    });

// 2nd  Callback Function
  connection_db.query(get_measure_query,function(err,user_data2){
        if(err){
          // throw err;
          let response_data = status_codes.db_error_0001;
          console.log(response_data);
          res.end(enc);
        }else {
      res.end('error');
    }
    });

// 3rd Callback Function
 connection_db.query(get_measure_query,function(err,user_data3){
        if(err){
          // throw err;
          let response_data = status_codes.db_error_0001;
          console.log(response_data);
          res.end('error');
        }else {

    }
    });

Now I need all the data user_data1, user_data2 and user_data3. How can I get this in a single function
function allData(){
// This should wait for all the callbacks and then execute

}

I hope I am able to understands my question. Please let me know if som eone not understands it well
In advance, thanks for the help guys !

A:

// 1. use Promise  Promise.all()
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

// 2. or gruff
function handleAll(data) {
  if(!handleAll.all) {
    handleAll.all = []
  }
  handleAll.all.push(data)
  if(handleAll.all.length >= 3) {
    //do something with handleAll.all [data1, data2, data3 ..]

    handleAll.all = null
  }
}
// invoke it in all the callback function
connection_db.query(get_measure_query,function(err,user_data1){
  if(err){
    // throw err;
    let response_data = status_codes.db_error_0001;
    console.log(response_data);
    res.end('error');
  }else {
    handleAll(user_data1)
  }
});

A: I did it roughly but you can use callback to get all the data in allData function. I think the below should work for you without adapting to newer version of code.

 function runALL(allData) {
     connection_db.query(get_measure_query, function(err, user_data1) {
         if (err) {
             // throw err;
             let response_data = status_codes.db_error_0001;
             console.log(response_data);
             res.end('error');
         }
         else {
             connection_db.query(get_measure_query, function(err, user_data2) {
                 if (err) {
                     // throw err;
                     let response_data = status_codes.db_error_0001;
                     console.log(response_data);
                     res.end(enc);
                 }
                 else {
                     connection_db.query(get_measure_query, function(err, user_data3) {
                         if (err) {
                             // throw err;
                             let response_data = status_codes.db_error_0001;
                             console.log(response_data);
                             res.end('error');
                         }
                         else {
                             allData(user_data1, user_data2, user_data3)
                         }
                     });
                 }
             });
         }

     });
 }

 function allData((user_data1, user_data2, user_data3) {
     // use user_data1, user_data2, user_data3
 })

 runAll(allData)


text:
Q: Getting this error in ffmpeg pipeline: Non-monotonous DTS in output stream 0:0; previous: 4951970, current: 4951659; changing to 4951971 Error: Non-monotonous DTS in output stream 0:0; previous: 4951970, current: 4951659; changing to 4951971. This may result in incorrect timestamps in the output file.
I am using AWS Chime streaming then passing there data stream to FFMPEG and then going live with that data stream using AWS IVS(Interactive video service).
I am using ffmpeg for changing aspects of video on live streaming and brightness and contrast.
But when we turn off camera and after some time reopen it we facing the above mention error.
I have read about concat but we don't have input file actually we are passing data stream is ffmpeg that's why its not working.
Here is my ffmpeg command
ffmpeg=ffmpeg.spawn('ffmpeg', [
            '-i', '-' ,
            // '-f', 'concat',
            // '-segment_time_metadata','1',
            // '-use_wallclock_as_timestamps', '1',
            '-c:v', 'libx264',
            '-b:v', '2567k',
            '-maxrate', '6000K',
            '-preset', 'ultrafast',
            '-profile:v', 'baseline',
            '-level', '3.0',
            // '-aspect', '9:16',
            '-force_key_frames', 'expr:gte(t,n_forced*2)',
            '-movflags', 'faststart',
            '-fflags', 'nobuffer',
            '-tune', 'zerolatency',
            '-acodec', 'aac',
            '-ab', '160k',
            '-ar', '44100',
            '-f', 'flv',
            'rtmps-url/secret-key-replaced'
        ])

I have tried this command -use_wallclock_as_timestamps', '1' but it does nothing to error.


text:
Q: Can I take different components from two different rotation axis-angle vectors and form a new rotation axis-angle vector? It is weird question, but from what I read in one software documentation it states:
"With respect to rotations, the constraint is different along different local directions. Along the z-axis (twist direction), the constraint is identical to the one enforced via the continuum coupling method (see Distributing coupling constraints). By contrast, the rotational constraint in the plane perpendicular to the z-axis relates the in-plane reference node rotations to the in-plane rotations of the coupling nodes in the immediate vicinity of the reference node. This choice provides a more realistic (compliant) response when the constrained surface is small and deforms primarily in a bending mode."
By rotation vector, I meant rotation axis-angle vector, pseduo-vector. My understanding of how rotation pseudo-vector being updated is that I have two rotation pseudo-vectors $\textbf{v}(v_1,v_2,v_3)$ and $\textbf{u}(u_1,u_2,u_3)$, and by the rule it states, the rotation pseudo-vector by adding them is $\textbf{w}=(u_1,u_2,v_3)$, is it correct rotation updates?


text:
Q: SharePoint List - Power Automate - Post updated item in a teams chat I'm facing an issue with the below flow, when I try to post a message in a chat.
The current flow reads the whole table but I would like to send only the last updated item.

Thank you in advance,
Andriana


text:
Q: Change SQL statement to EXISTS clause Given the following SQL statenent:
select
    OBJECT_ID
FROM HPSFWY.RVERSIONING_1703 A
WHERE A.STAMP_ID >1
    AND A.OBJECT_REV NOT IN (
select MAX(OBJECT_REV)
from HPSFWY.RVERSIONING_1709763 B
where B.COMMITID <= 6066
    and B.OBJECT_ID = A.OBJECT_ID
    )

In this query the where clause AND OBJECT_REV NOT IN must be changeed from NOT IN to an equivalent EXISTS statement.
We try this
select
OBJECT_ID
FROM HPSFWY.RVERSIONING_1703 A
WHERE A.STAMP_ID >1
AND exists (
select *
from HPSFWY.RVERSIONING_1709763 B
where B.COMMITID <= 6066
and B.OBJECT_ID = A.OBJECT_ID
and B.OBJECT_REV > A.OBJECT_REV) ;

It gives us close results, but not same

A: You can do it with NOT EXISTS like this:
SELECT A.OBJECT_ID
FROM HPSFWY.RVERSIONING_1703 A
WHERE
  A.STAMP_ID > 1
  AND
  NOT EXISTS (
    SELECT 1 FROM (
      SELECT MAX(B.OBJECT_REV) MAXOBJECT_REV
      FROM HPSFWY.RVERSIONING_1709763 B
      WHERE B.COMMITID <= 6066 AND B.OBJECT_ID = A.OBJECT_ID
    ) t
    WHERE t.MAXOBJECT_REV = A.OBJECT_REV
  )

Note: the subquery of NOT IN:
select MAX(OBJECT_REV)
from HPSFWY.RVERSIONING_1709763 B
where B.COMMITID <= 6066 and B.OBJECT_ID = A.OBJECT_ID

returns only 1 row with 1 column.
So instead of NOT IN you could use <> like this:
SELECT A.OBJECT_ID
FROM HPSFWY.RVERSIONING_1703 A
WHERE
  A.STAMP_ID > 1
  AND
  A.OBJECT_REV <> (
    SELECT MAX(OBJECT_REV)
    FROM HPSFWY.RVERSIONING_1709763 B
    WHERE B.COMMITID <= 6066 AND B.OBJECT_ID = A.OBJECT_ID
  )


text: Q: How can I change registry in yarn.lock I was developing a project with a default registry. And now I need to pull up packages from the local register, how can I change the register without dancing, for example, use any command?


text:
Q: windows 2016 high availability cluster - file share not reachable from other hosts I am setting up some Windows 2016 HighAvailability Cluster with FileServer Role.
I am working on virtualized hardware inside an Openstack.
Started creating an iSCSi target and an Active Directory on the first instance, i have 2 Cluster Nodes configured in Failover Cluster Manager.
Cause all images were booted from the same source image, I needed to execute sysprep to have an unique SID.
Everything went fine while the configuration of the Storage, the nodes and the Share. I only have one big problem, I can only access the IP of the clustered FileServer from the active instance.
That means if Node1 is at the moment the active instance I can only access the share from Node1 (but with virtual Cluster IP). If I switch the active node to be Node2, it's not accessible anymore from Node1 (but therefore on Node2).
I don't see any errors in the event monitor.
I know that this is not that much information, but maybe somebody knows this kind of problem.
Is this maybe a restriction of not activated Windows? Cause the systems are not activated by now (But afaik there is no such limitation).
I configured my HA Cluster like it's described here:
https://www.1e.com/blogs/2014/08/25/creating-a-windows-cluster-part-3-creating-a-windows-failover-cluster/
So summed up, everything is working fine (also the real switching of the node if a node falls out), besides accessing the share from another host than the active node.
On ServerManager I see all Servers listed, also the Virtual Ones.
Thanks in advance,
Marco

A: Just if somebody else faces this problem. It's corresponding to the Openstack Server. Openstack by default does not except new IPs, which are not created from the OS network itself and blocks all traffic to this machines.
-> Only Accessible from the active node.
So i think that is really specific kind of problem and not corresponding to the windows cluster itself.


text:
Q: Making the user active when tapping a button in html, and using a DetailView (Django) I'm trying to make a user active when I tap a button, and I'm using a DetailView.
views.py
from .models import Model
from django.contrib.auth.models import User
from django.shortcuts import redirect

class UserInspectView(DetailView):
    model = Model
    template_name = 'user-inspect.html'

# Make the user is_active = True
def accept (request, pk):
    user = User.objects.get(id=pk)
    user.is_active
    return redirect('home')

...

urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('inspect/<slug:slug>/', views.UserInspectView.as_view(), name='user-inspect'),
    path('inspect/<int:pk>/accept/', views.accept, name="user-accept"),
    ...
]

user-inspect.html
{% extends 'base.html' %}

{% block title %} <title>User Inspection</title> {% endblock %}

{% block content %}

User: {{model.user}}

Name: {{model.name}}

            <form method="post" action="{% url 'user-accept' model.user.pk %}">
                {% csrf_token %}
                <button type="submit" class="btn btn-primary">Accept</button>
            </form>

            Back

{% endblock %}

models.py
from django.db import models
from django.contrib.auth.models import User

    class Model(models.Model):
        name = models.CharField(max_length=100)
        user = models.ForeignKey(User, on_delete=models.CASCADE)
        slug = models.SlugField(unique=True, blank=False, null=False)

Before my accept view looked like this
def accept (request, pk):
    user = User.objects.get(id=pk)
    user.is_active()
    user.save()
    return redirect('home')

but I changed it, because I got this error

TypeError at inspect/30/accept/
'bool' object is not callable

When I tap the Accept button, it takes me to the redirect that I have in the accept view, but the user is still inactive.

A: user.is_active is a boolean not a function.
def accept (request, pk):
    user = User.objects.get(id=pk)
    user.is_active = True
    user.save()
    return redirect('home')


text:
Q: I need to print the values from the web service from one screen to another screen in android I am trying to display the values from the web service from one screen to another screen,but i am unable to print those values on the next screen.
Actually my emulator is getting run,but showing only the empty screen
Here is my source for reference,please find it and let me know the solution.
Main_WB.java
public class Main_WB extends Activity
{
EditText edt1,edt2;
  //    TextView txt_1;

Button btn;

 @Override
 public void onCreate(Bundle savedInstanceState)
 {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    edt1 = (EditText)findViewById(R.id.editText1);
    edt2 = (EditText)findViewById(R.id.editText2);
    btn = (Button)findViewById(R.id.button1);

    btn.setOnClickListener(new View.OnClickListener()
    {
    public void onClick(View v)
    {
        getTMSChart(edt1.getText().toString(),edt2.getText().toString());
        Intent myint = new Intent(Main_WB.this,ResultActivity.class);
        startActivity(myint);
    }
    });
  }

 private void getTMSChart(String FromDate,String ToDate)
 {
 //txt_1 = (TextView)findViewById(R.id.textView1);

 System.setProperty("http.keepAlive", "false");
 SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

 envelope.dotNet = true;

 String NAMESPACE = "http://tempuri.org/";
 String URL = "http://54.251.60.177/TMSOrdersService/TMSDetails.asmx";
 String METHOD = "GetTMSChart";

 SoapObject request = new SoapObject(NAMESPACE, METHOD);
 request.addProperty("FromDate", FromDate);
 request.addProperty("ToDate", ToDate);

 envelope.setOutputSoapObject(request);
 HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

 try
 {
    androidHttpTransport.call(NAMESPACE + METHOD, envelope);
    SoapObject result = (SoapObject) envelope.bodyIn;
    SoapObject root =  (SoapObject) ((SoapObject)(result).getProperty(0)).getProperty("NewDataSet");
    int tablesCount = root.getPropertyCount();

    for (int i = 0; i < tablesCount; i++)
    {
       SoapObject table = (SoapObject) root.getProperty(i);
       int propertyCount = table.getPropertyCount();

       int[] ord = new int[propertyCount];
       int[] fre = new int[propertyCount];
       int[] margin = new int[propertyCount];

    for (int j = 0; j < propertyCount; j++)
    {
        String x,y;

        int orderNo = Integer.parseInt(table.getPropertyAsString("Order_No"));
        int freightRate = Integer.parseInt(table.getPropertyAsString("Freight_Rate"));
        int marginPercent = Integer.parseInt(table.getPropertyAsString("Margin_Percent"));

    //  String orderNo =  table.getPropertyAsString("Order_No");

        ord[j] = orderNo;
        fre[j] = freightRate;
        margin[j]= marginPercent;

        x = ord.toString();
        y = fre.toString();

        Intent myIntent = new Intent(Main_WB.this, ResultActivity.class);
        myIntent.putExtra("gotonextpage", x);
        startActivity(myIntent);

        // whatever you do with these values
          }
       }
    }
    catch (Exception e)
    {
    }
    }      }

ResultActivity.java
 public class ResultActivity extends Activity
 {
String str;
TextView txtv;

 @Override
 public void onCreate(Bundle savedInstanceState)
 {
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);

Bundle extras = getIntent().getExtras();
if(extras != null)
{
 str = extras.getString("goto_next_page");
 }
else
{
}

txtv = (TextView)findViewById(R.id.txtVw);
txtv.setText(str);
}}

A: I would use AsynkTask.
And on onPostExecute I would start the activity.
That networking mixed with UI it to mess for me, does it run in Android 4 at all? - you should get an exception there with no network on UI thread or something like that, forgot the exception name. Anyway, try to separate the network and UI layers.
Also calling an asmx, I needed to se somewhere - forgot where - a param to true: isDotNet or similar the prope name.

A: use
getIntent().getStringExtra("gotonextpage", "default");

instead of
getIntent().getExtras();

in the resultActivity. Note that you have to use the same key you used to put data, to retrieve it.

A: First, you're calling your web service on the UI thread. That's a big no-no.
Second, your names don't match. You're setting the extra as "gotonextpage", but then trying to retrieve it in the second activity as "goto_next_page".


text:
Q: OnItemClickListner is not working in json parser android I am using listview in android with JSON Parser the listview sucessful working, here is my problem, onitemclicklistner is not working in listview?
Here this my code
Main Activity  code
 public class MainActivity extends Activity {

    private static final String TAG_NAME = "name";
    private static final String TAG_EMAIL = "email";
    private static final String TAG_PHONE_MOBILE = "mobile";
    ListView mListView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // URL to the JSON data
        String strUrl = "http://192.168.0.200/android/count.php";

        // Creating a new non-ui thread task to download json data
        DownloadTask downloadTask = new DownloadTask();

        // Starting the download process
        downloadTask.execute(strUrl);

        // Getting a reference to ListView of activity_main
        mListView = (ListView) findViewById(R.id.lv_countries);

    }

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

            // Creating an http connection to communicate with url
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            // 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 downloading url", e.toString());
        }finally{
            iStream.close();
        }

        return data;
    }

    /** AsyncTask to download json data */
    private class DownloadTask extends AsyncTask<String, Integer, String>{
        String data = null;
        @Override
        protected String doInBackground(String... url) {
            try{
                data = downloadUrl(url[0]);
            }catch(Exception e){
                Log.d("Background Task",e.toString());
            }
            return data;
        }

        @Override
        protected void onPostExecute(String result) {

            // The parsing of the xml data is done in a non-ui thread
            ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();

            // Start parsing xml data
            listViewLoaderTask.execute(result);

        }
    }

    /** AsyncTask to parse json data and load ListView */
    private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{

        JSONObject jObject;
        // Doing the parsing of xml data in a non-ui thread
        @Override
        protected SimpleAdapter doInBackground(String... strJson) {
            try{
                jObject = new JSONObject(strJson[0]);
                CountryJSONParser countryJsonParser = new CountryJSONParser();
                countryJsonParser.parse(jObject);
            }catch(Exception e){
                Log.d("JSON Exception1",e.toString());
            }

            // Instantiating json parser class
            CountryJSONParser countryJsonParser = new CountryJSONParser();

            // A list object to store the parsed countries list
            List<HashMap<String, Object>> countries = null;

            try{
                // Getting the parsed data as a List construct
                countries = countryJsonParser.parse(jObject);
            }catch(Exception e){
                Log.d("Exception",e.toString());
            }

            // Keys used in Hashmap
            String[] from = { "flag","details"};

            // Ids of views in listview_layout
            int[] to = { R.id.iv_flag,R.id.tv_country_details};

            // Instantiating an adapter to store each items
            // R.layout.listview_layout defines the layout of each item
            SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), countries, R.layout.lv_layout, from, to);

            return adapter;
        }

        /** Invoked by the Android on "doInBackground" is executed */
        @Override
        protected void onPostExecute(SimpleAdapter adapter) {

            // Setting adapter for the listview
            mListView.setAdapter(adapter);

            for(int i=0;i<adapter.getCount();i++){
                HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
                String imgUrl = (String) hm.get("flag_path");
                ImageLoaderTask imageLoaderTask = new ImageLoaderTask();

                HashMap<String, Object> hmDownload = new HashMap<String, Object>();
                hm.put("flag_path",imgUrl);
                hm.put("position", i);

                // Starting ImageLoaderTask to download and populate image in the listview
                imageLoaderTask.execute(hm);
            }

        }

    }

    /** AsyncTask to download and load an image in ListView */
    private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{

        @Override
        protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) {

            InputStream iStream=null;
            String im,gUrl;
            gUrl = (String) hm[0].get("flag_path");
            int position = (Integer) hm[0].get("position");

            URL url;
            try {
                url = new URL(gUrl);

                // Creating an http connection to communicate with url
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                // Connecting to url
                urlConnection.connect();

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

                // Getting Caching directory
                File cacheDirectory = getBaseContext().getCacheDir();

                // Temporary file to store the downloaded image
                File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+position+".png");

                // The FileOutputStream to the temporary file
                FileOutputStream fOutStream = new FileOutputStream(tmpFile);

                // Creating a bitmap from the downloaded inputstream
                Bitmap b = BitmapFactory.decodeStream(iStream);

                // Writing the bitmap to the temporary file as png file
                b.compress(Bitmap.CompressFormat.PNG,100, fOutStream);

                // Flush the FileOutputStream
                fOutStream.flush();

               //Close the FileOutputStream
               fOutStream.close();

                // Create a hashmap object to store image path and its position in the listview
                HashMap<String, Object> hmBitmap = new HashMap<String, Object>();

                // Storing the path to the temporary image file
                hmBitmap.put("flag",tmpFile.getPath());

                // Storing the position of the image in the listview
                hmBitmap.put("position",position);

                // Returning the HashMap object containing the image path and position
                return hmBitmap;

            }catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(HashMap<String, Object> result) {
            // Getting the path to the downloaded image
            String path = (String) result.get("flag");

            // Getting the position of the downloaded image
            int position = (Integer) result.get("position");

            // Getting adapter of the listview
            SimpleAdapter adapter = (SimpleAdapter ) mListView.getAdapter();

            // Getting the hashmap object at the specified position of the listview
            HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position);

            // Overwriting the existing path in the adapter
            hm.put("flag",path);

            // Noticing listview about the dataset changes
            adapter.notifyDataSetChanged();
            mListView.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                        int arg2, long arg3) {
                    Activity view = null;
                    // TODO Auto-generated method stub
                    // getting values from selected ListItem
                    String type = ((TextView) view.findViewById(R.id.tv_country_details)).getText().toString();

                    // Starting new intent
              Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
                in.putExtra(type, type);
                startActivity(in);

            }

               });
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    }

SingleMenuItemActivity code
public class SingleMenuItemActivity  extends Activity {

    // JSON node keys

    private static final String TAG_details = "details";
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.single_list_item);

            // getting intent data
            Intent in = getIntent();

            // Get JSON values from previous intent
            String cost = in.getStringExtra(TAG_details);

            // Displaying all values on the screen
            TextView lblCost = (TextView) findViewById(R.id.tv_country_details);

            lblCost.setText(cost);

        }
    }

Json Parser Code
public class CountryJSONParser {

// Receives a JSONObject and returns a list
public List<HashMap<String,Object>> parse(JSONObject jObject){

    JSONArray jCountries = null;
    try {
        // Retrieves all the elements in the 'countries' array
        jCountries = jObject.getJSONArray("countries");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    // Invoking getCountries with the array of json object
    // where each json object represent a country
    return getCountries(jCountries);
}

private List<HashMap<String, Object>> getCountries(JSONArray jCountries){
    int countryCount = jCountries.length();
    List<HashMap<String, Object>> countryList = new ArrayList<HashMap<String,Object>>();
    HashMap<String, Object> country = null;

    // Taking each country, parses and adds to list object
    for(int i=0; i<countryCount;i++){
        try {
            // Call getCountry with country JSON object to parse the country
            country = getCountry((JSONObject)jCountries.get(i));
            countryList.add(country);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    return countryList;
}

// Parsing the Country JSON object
private HashMap<String, Object> getCountry(JSONObject jCountry){

    HashMap<String, Object> country = new HashMap<String, Object>();

    String flag="";
    String currencyName = "";

    try {

        flag = jCountry.getString("flag");
        currencyName = jCountry.getJSONObject("currency").getString("currencyname");

        String details = currencyName ;

        country.put("flag", R.drawable.blank);
        country.put("flag_path", flag);
        country.put("details", details);

    } catch (JSONException e) {
        e.printStackTrace();
    }
    return country;
}

public static Object optJSONObject(int arg2) {
    // TODO Auto-generated method stub
    return null;
}

public static boolean isNull(int arg2) {
    // TODO Auto-generated method stub
    return false;
}

}

A: Add these code into your dewnloadurl method.
    String jsonString = null;

    HttpURLConnection linkConnection = null;
    try{
        URL linkur1 = new URL(url);
        linkConnection = (HttpURLConnection) linkur1.openConnection();
        int responseCode = linkConnection.getResponseCode();
        if(responseCode == HttpURLConnection.HTTP_OK){
            InputStream linkingStream = linkConnection.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int j = 0;
            while ((j = linkingStream.read()) != -1) {
                baos.write(j);
            }
            byte[] data = baos.toByteArray();

            jsonString = new String(data);
        }
    }catch(Exception e){
        e.printStackTrace();
    }finally{
        if(linkConnection != null){
            linkConnection.disconnect();
        }
    }

    return jsonString;

Than Use it to get single item
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
        long id) {
          View item = arg0.getChildAt(position);
}


text:
Q: student-advisor interaction I am obviously not using my real name or identity for evident reasons. I haven't contacted my advisor for the last couple of months and communication was silent. Now we barely talk and any sort of interaction with him makes it seem like our previous collaboration was a failed attempt.
This can be a dumb question, but I do not know how else to express this and I feel pressured to ask this. If a advisor-advisee relationship fails, should I look for a different advisor? Has anyone been in a similar situation. I am still interested in the subject/area that advisor works in and, of course, there are some things which I need to change- I have to be more committed in the sense that I follow through with every project I start (Usually I started to recognize a pattern where these sorts of collaborations end sourly for me...). I'm still an undergraduate, so I hope I have some time.

A: *

*Not seeing the advisor for a period of time doesn't necessarily mean that the collaboration or the advisor-advisee relationship is a failure. My dissertation advisor took a sabbatical the entirety of my second year in PhD; he also has a style that emphasizes independence in research so we didn't sit down for a serious math discussion until I had something new to show him.

*Before you decide that the relationship is a failure, you should talk to somebody about it in detail. It may be that your perception of how things are going is quite different from the point of view of a faculty member. If you still have okay personal relationship with said advisor, you should initiate a discussion voicing your worries. Sometimes just talking it over will solve a lot of things. If you don't think you can face your advisor, seek help through the University. Most universities have some sort of counselling service, who can mediate this kind of discussions. For example, at MIT there is the Student Support Services. Another option is that a lot of universities (especially more liberal-arts oriented ones) have general Academic Advisors for before you declared a major, and a Director of Undergraduate Studies for after you declared the major. Talking to them will also help.

*If you are really convinced that the relationship is irreparable, then the sooner you find a different advisor and move on the better for your own academic and mental well-being. Sorting out this "break-up" can be emotionally taxing, and I would suggest you make use of the counselling or advising services from your university whenever available.


text:
Q: How to avoid hash sign in URL, using react-router-dom and react-router-bootstrap? I'm using <Route /> from react-router-dom for routing and Nav + LinkContainer from react-bootstrap + react-router-bootstrap for navigation:
//...
  <Route path="/shop/" component={Shop} />
//...
  <NavItem caption="Home" path="/" />
  <NavItem caption="Shop" path="/shop" />
//...

// with a helper component:
const NavItem = (props) => {
  return (
    <LinkContainer to={props.path} >
      <Nav.Link> {props.caption} </Nav.Link>
    </LinkContainer>
  )
}

This creates an URL with a hash sign in it, e.g.:
http://localhost:3000/#/shop

Where does this come from, what is it good for? Everything is working fine anyway, but this hash sign isn't smart, I think. Can I avoid it?

A: You can use

BrowserRouter

Instead of

HashRouter

which prevents the showing # on URL.
import {
  BrowserRouter as Router,
  ...
}

instead of

import {
  HashRouter as Router,
  ...
}


text:
Q: Show real object hierarchy in gdb/Eclipse CDT debug watch by pointer MSVS has a nice feature, when watching a pointer to an interface, it shows the real object. E.g.
struct IIntf1 {}
struct IIntf2 {}
class CIntf1: public IIntf1 {}
class CIntf2: public IIntf2, public CIntf1 {}
IIntf1 *p = new CIntf2();

MSVS will show that p is really CIntf2, which is IIntf1 and all its members, it will even show multiple and nested classes there (that p is C/IIntf1 and so on).
Is there something like this for gdb and/or Eclipse CDT under Linux?

A: Try set print object on in gdb.  (You might also try set print pretty if you want the printed objects to have more structure.)


text:
Q: Minimal polynomial and cyclic subspace. I'm lost with minimal polynomials. I have to prove that the degree of the minimal polynomial $m_{x_0}(x)$ such that cancels a vector $x_0 \in V$ is equal to the dimension of the cyclic subspace spanned by $x_0$. In addition, $m_{x_0}(x)$ divides other polynomial that cancels $x_0$. I think that is straightforward from definition but I don't know how.

A: Demo
Given an operator $\mathcal T$, the cyclic space generated by $v\in V$ is
$$
C_v=\mathrm {span}\{v, \mathcal Tv, \dots, \mathcal T^k v, \dots\}.
$$
Assume $V$ is finite dimensional, then there is some $p\in \mathbb N^*$ s.t. $(\mathcal T^j v)_0^{p-1}$ is a linearly independent set, but $(\mathcal T^j v)_0^{p}$ is not. So there exists a set of scalars $(a_j)_0^{p-1}$ s.t.
$$
\mathcal T^p v  = \sum_0^{p-1} a_j \mathcal T^j v.
$$
Hence the polynomial $g(x ) = x^p - \sum_0^{p-1}a_j x^j$ satisfies that $g(\mathcal T)v = 0$, thus $g(x)$ annihilates $\mathcal T|_{C_v}$. Let $m(x)$ be the desired minimal polynomial, then since $g(\mathcal T)v =0$, $m|g$. On the other hand, if some monic polynomial $r(x)  $ with degree $q <p$ satisfying $r(\mathcal T)v =0$, then $(\mathcal T^j v)_0^q$ is linear dependent, contradicting the definition of $p$. So $\deg m \geqslant \deg g$ where $m$ is an annihilating polynomial for $v$. Since $m, g$ are monic by definition, $m = g$, hence $\deg m = \deg g$. By the definition of $p$, we could conclude that $\dim(C_v)=p$, hence the desired conclusion.
UPDATE
Suppose $g(x)$ annihilates $v$, and $m(x)$ is the minimal one. Then perform the division with remainder, we could get polynomials $q(x), r(x)$ s.t. $g =mq + r$ where $\deg r < \deg m$. If $r \neq 0$, then since $m$ is the minimal one, $m$ annihilates $v$. Then
$$
0=g(\mathcal T)v = m(\mathcal T)q(\mathcal T)v + r(\mathcal T) = 0 + r(\mathcal T)v.
$$
If $r \neq 0$, then $r$ is a polynomial annihilating $v$ with $\deg r <\deg m$, contradicting the minimality of $m$. Hence $g=mq $, equivalently $m | g$.
TEXTS I HAVE READ

*

*Peter Petersen Linear Algebra
A second course for LA. I think the choice of proofs are special.

*Sheldon Axler Linear Algebra Done Right
A second course with theory developed without introducing determinants. It is pretty geometric.

*Kenneth Hoffman, Ray Kunze Linear Algebra
A classic with deeply developed theories. Should be revisited after the 1st or 2nd exposure to the subject.
The crucial part is to use the polynomials to study the structure of linear spaces, which is covered by these books.


text:
Q: This Activity already has an action bar supplied by the window I have a problem with my Navigation Drawer.
my project First run by splash page and Then show Navigation Drawer.
When I compile my application the following error messages :
AndroidRuntime: FATAL EXCEPTION: main
 Process: ir.mosayebtorabi.sapp, PID: 4793
 java.lang.RuntimeException: Unable to start activity ComponentInfo{ir.mosayebtorabi.sapp/com.loridic.ir.loridic.MainActivity}: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
     at android.app.ActivityThread.access$800(ActivityThread.java:153)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1305)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:135)
     at android.app.ActivityThread.main(ActivityThread.java:5293)
     at java.lang.reflect.Method.invoke(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:372)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
  Caused by: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
     at android.support.v7.app.AppCompatDelegateImplV9.setSupportActionBar(AppCompatDelegateImplV9.java:201)
     at android.support.v7.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:129)
     at com.loridic.ir.loridic.MainActivity.onCreate(MainActivity.java:25)
     at android.app.Activity.performCreate(Activity.java:5990)
     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2280)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
     at android.app.ActivityThread.access$800(ActivityThread.java:153)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1305)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:135)
  at android.app.ActivityThread.main(ActivityThread.java:5293)
     at java.lang.reflect.Method.invoke(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:372)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

activity_splash_screen.xml Contains:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimaryDark"
tools:context="com.loridic.ir.loridic.SplashScreen">
<ImageView
    android:id="@+id/image"
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:src="@drawable/lorvajeh"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.4"
    android:contentDescription="@string/lorem_ipsum" />

<TextView
    android:id="@+id/welcomeText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/welcome_screen"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@id/image"
    app:layout_constraintVertical_bias="0.2"
    android:textSize="22sp"
    android:textColor="@color/colorWhite"
    android:textStyle="bold"/>

activity_splash_screen class Contains:
package com.loridic.ir.loridic;
import android.app.Activity;`
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
public class SplashScreen extends AppCompatActivity {
Handler handler;
public static Activity fa;
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash_screen);
    fa = this;
    ImageView iv = findViewById(R.id.image);
    TextView tv = findViewById(R.id.welcomeText);

    Animation animation = AnimationUtils.loadAnimation(this, R.anim.splashtransition);
    iv.startAnimation(animation);
    tv.startAnimation(animation);
    Splashregister();

}

public void Splashregister() {
    handler = new Handler();
    {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                fa.finish();
                startActivity(new Intent(SplashScreen.this, MainActivity.class));
            }
        }, 4000);

    }
}
}

styles.xml Contains:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
</resources>

MainActivity class Contains:
package com.loridic.ir.loridic;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.FrameLayout;

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {
FrameLayout frameLayout;
FragmentManager fragmentManager=getSupportFragmentManager();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    frameLayout=(FrameLayout)findViewById(R.id.frmlayoutview);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.SentWord) {
        FragmentTransaction ft=fragmentManager.beginTransaction();
        ft.replace(R.id.frmlayoutview,new FragmentClassAddWord());
        ft.commit();
    } else if (id == R.id.Target) {
        FragmentTransaction ft=fragmentManager.beginTransaction();
        ft.replace(R.id.frmlayoutview,new FragmentClassAbout());
        ft.commit();
    } else if (id == R.id.PersonalInformation) {
        FragmentTransaction ft=fragmentManager.beginTransaction();
        ft.replace(R.id.frmlayoutview,new FragmentClassRegistername());
        ft.commit();
    } else if (id == R.id.Share) {
        FragmentTransaction ft=fragmentManager.beginTransaction();
        ft.replace(R.id.frmlayoutview,new FragmentClassShare());
        ft.commit();
    } else if (id == R.id.About) {
        FragmentTransaction ft=fragmentManager.beginTransaction();
        ft.replace(R.id.frmlayoutview,new FragmentClassMaker());
        ft.commit();
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}
}

MainActivity xml Contains:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">

<include
    layout="@layout/app_bar_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_main"
    app:menu="@menu/activity_main_drawer" />

</android.support.v4.widget.DrawerLayout>

AndroidManifest.xml Contains:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.loridic.ir.loridic">

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".SplashScreen"
        android:label="LoreVajeh"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".Activityaddword" />
    <activity android:name=".Activityregistername" />
    <activity android:name=".Activityabout" />
    <activity android:name=".Activitymaker" />
    <activity android:name=".Activityshareapp" />
    <activity android:name=".MainActivity"></activity>
</application>

</manifest>

A: As you are supplying a toolbar in your MainActivity you need to turn the default one off in the AndroidManifest.xml file
e.g.
<activity
            android:name=".MainActivity"
            android:theme="@style/AppTheme.NoActionBar" />


text:
Q: Filtering QSqlRelation in QSqlRelationalTableModel I have two tables like:
Person (Id, Name, JobID, Age)
Jobs (Id, Company, Salary)
I'm using a SqlRelationalTableModel and it's working with the following QSqlRelation:
   model-> setTable("Person")
   model-> setRelation(2,QSqlRelation("Jobs", "Id", "Company"))

My problem is that now I want to show only the jobs with salaries over 50000 and I don't know how to filter Jobs table to do it since setFilter only affects Person table.

A: You can use QSqlQueryModel
QSqlQueryModel* model = new QSqlQueryModel();
model->setQuery("select * from Person left join Jobs on Person.JobID=Jobs.Id where Salary>50000");


text:
Q: AWS - Creating resources in a multi-account environment I just created a new AWS account using Terraform aws_organizations_account module. What I am now trying to do is to create ressources into that new account. I guess I would need the account_id of the new AWS account to do that so I stored it into a new output variable but after that I have no idea how can I create a aws_s3_bucket for example
provider.tf
provider "aws" {
  region = "us-east-1"
}

main.tf
resource "aws_organizations_account" "account" {
  name      = "tmp"
  email     = "first.last+tmp@company.com"
  role_name = "myOrganizationRole"
  parent_id = "xxxxx"
}

## what I am trying to create inside that tmp account
resource "aws_s3_bucket" "bucket" {}

outputs.tf
output "account_id" {
  value       = aws_organizations_account.account.id
  sensitive   = true
}

A: You can't do this the way you want. You need entire, account creation pipeline for that. Roughly in the pipeline you would have two main stages:

*

*Create your AWS Org and member accounts.

*Assume role from the member accounts, and run your TF code for these accounts to create resources.

There are many ways of doing this, and also there are many resources on this topic. Some of them are:

*

*How to Build an AWS Multi-Account Strategy with Centralized Identity Management

*Setting up an AWS organization from scratch with Terraform

*Terraform on AWS: Multi-Account Setup and Other Advanced Tips
Apart from those, there is also AWS Control Tower, which can be helpful in setting up initial multi-account infrastructure.


text:
Q: Problema en programación C, lista simple sin cabecera Buenas tardes, estoy haciendo un programa (práctica universidad), donde añadir,mostrar,borrar, etc 'estructuras clientes para una agencia de viajes'.
Estoy utilizando listas simples sin cabecera.
Cuando lo ejecuto, elijo en el menú añadir cliente nuevo, lo añade pero cuando pasa a la siguiente función para poner NULL en el ultimo elemento de la lista.El programa se detiene.
Alguien me podría ayudar? muchas gracias de antemano!
El error me sale en la linea while de esta fución:
struct NodoCliente *ListaUltima(struct NodoCliente *l){

    struct NodoCliente *aux;    /*El ultimo elemento de la lista es NULL.*/
    aux = l;

    while ( aux->siguiente != NULL ){
        aux = aux->siguiente;
    }
    return (aux);
}

Aqui dejo el código completo:
struct Viaje {
    char identificador[DNI_MAX + 3]; //Identificador compuesto por      DNI_identificaror unico (Ej: 75499435J_02)
    char ciudad_destino[CIUDAD_DESTINO_MAX];
    char hotel[HOTEL_MAX];
    int num_noches;
    char transporte[TRANSPORTE_MAX];
    float precio_aloj;
    float precio_desp;
};

struct Cliente {
    char dni[DNI_MAX];
    char nombre[NOMBRE_MAX];
    char apellidos[APELLIDOS_MAX];
    char direccion[DIRECCION_MAX];
    int num_viajes;
    struct Viaje viaje[VIAJES_MAX];
    struct Cliente *ptrcliente;
};

struct NodoCliente {
    char dni[DNI_MAX];
    char nombre[NOMBRE_MAX];
    char apellidos[APELLIDOS_MAX];
    char direccion[DIRECCION_MAX];
    struct NodoCliente *siguiente;
};

typedef struct NodoCliente *ListaClientes;
typedef struct NodoCliente *Posicion;

struct NodoCliente* crearListaClientes(void)
    {
        return (NULL);
    }

struct NodoCliente* posicionPrimero(struct NodoCliente *l)
    {
        return (l);
    }

struct NodoCliente* insertarCliente(struct NodoCliente *l, struct NodoCliente      *pindice){

FILE *fc; //Declaramos un putero a File

char nombre_fichero[NOMBRE_FICHERO_MAX];
char dni[DNI_MAX];
char nombre[NOMBRE_MAX];
char apellidos[APELLIDOS_MAX];
char direccion[DIRECCION_MAX];

struct NodoCliente *aux;

aux = (struct NodoCliente *) malloc(sizeof(struct NodoCliente));

printf("Introduzca el nombre del fichero del cliente a crear: ");
fflush(stdin);
scanf("%s",nombre_fichero);
printf("Extrayendo informacion del archivo %s\n", nombre_fichero);
fc = fopen(nombre_fichero,"r");

if (fc == NULL) {
    printf("Archivo no encontrado.\n");
}

else {

    fscanf(fc,"%[^\n] %[^\n] %[^\n] %[^\n]", dni, nombre, apellidos, direccion);

    //fclose(fc);

    printf("Creando cliente con datos: \n%s\n%s\n%s\n%s\n", dni, nombre, apellidos, direccion);

    if (aux != NULL) {

        strcpy(aux->dni, dni);
        strcpy(aux->nombre, nombre);
        strcpy(aux->apellidos, apellidos);
        strcpy(aux->direccion, direccion);

        if (l == NULL) {

            aux->siguiente = NULL;
            l = aux;

        }else {

            aux->siguiente = pindice->siguiente;
            pindice->siguiente = aux;

        }
    }
}

return(l);
}

struct NodoCliente *ListaUltima(struct NodoCliente *l){

struct NodoCliente *aux;    /*El ultimo elemento de la lista es NULL.*/
aux = l;

while ( aux->siguiente != NULL ){
    aux = aux->siguiente;
}
return (aux);
}

void mostrar_lista(struct NodoCliente *l) {

struct NodoCliente *aux; /* lo usamos para recorrer la lista */
int i;
i=0;
aux = l;

printf("\nMostrando la lista completa:\n");

while (aux!=NULL) {
    printf( "DNI: %s, Nombre: %s\n", aux->dni,aux->nombre);
    aux = aux->siguiente;
    i++;
}
if (i==0) printf( "\nLa lista está vacía!!\n" );
}

int main(){
int opcion;
ListaClientes listaclientes = crearListaClientes();
Posicion p1 = posicionPrimero(listaclientes);

do {
    printf ("Bienvenido, eliga una opción. ,\n\n");
    printf ("1- Dar de alta un nuevo cliente. \n");
    printf ("2- Dar de baja un cliente existente. \n");
    printf ("3- Dar de alta un nuevo viaje. \n");
    printf ("4- Eliminar un viaje. \n");
    printf ("5- Listar datos de la agencia. \n");
    printf ("6- Escribir en un fichero los datos de la agencia. \n");
    printf ("7- Deshacer acción. \n");
    printf ("8- Rehacer acción. \n");
    printf ("9- Salir. \n\n");
    fflush(stdin);
    scanf ("%d", &opcion);
    printf ("\n");

    switch (opcion) {
        case 1:
            insertarCliente(listaclientes, p1);
            p1 = ListaUltima(listaclientes);

            break;


text:
Q: Sessão não inicia em php via htaccess Estou tentando iniciar uma sessão no .htaccess usando php_value session.auto_start 1 para evitar duplicações de linhas nos códigos php.
Porém isto está a não funcionar, informa que está sempre off?

A:
Nota: no caso o autor está experimentando a versão gratuita do hostinger, que provavelmente é limitada e não tem suporte completo (não posso afirmar, é uma suposição) e este parece ser o motivo do problema

Acredito que o comando seja php_flag e não php_value, exemplo:
php_flag session.auto_start 1

Para testar crie um arquivo vazio chamado teste.php na mesma pasta que se encontra .htaccess com este conteudo:
<?php
var_dump(session_id(), $_SESSION);

Deve retornar algo como:
string(26) "jgg7lol8o97733q3vgs46tm7p5" array(0) { }

Isto significa que está funcionando.
Solução alternativa
Se acaso isto não funcionar você pode fazer o seguinte, crie um arquivo chamado global.php, nele adicione o seguinte conteúdo:
<?php
if (session_id() === '') {
    session_start();
}

E inclua este arquivo em todos arquivos necessários, por exemplo o arquivo index.php
<?php
require_once 'global.php';
?><!DOCTYPE html>
<html>
<head>
Resto do html...


text:
Q: Getting different files when installing making a new Jekyll project I've just recently started a course on Jekyll and I've followed every instruction the guy did, but when he gets to creating a new project through a terminal I follow everything he does and yet I get different files in my project folder than he does.

These are the files he gets.

And these are the files I get.
Why am I not getting the same files as he?
How can I fix it?

A: Since jekyll 3.2, every layout, include and assets are hidden somewhere on you file system, thank to the new gem based themes.
You can find them with : bundle show minima if you're using the default theme.
Good luck with this.


text:
Q: Can't module 'reflect-metadata' on Docker container in Production Server I get an error
module.js:550
     throw err;
     ^

 Error: Cannot find module 'reflect-metadata'
     at Function.Module._resolveFilename (module.js:548:15)
     at Function.Module._load (module.js:475:25)
     at Module.require (module.js:597:17)
     at require (internal/module.js:11:18)
     at Object.<anonymous> (/usr/src/app/dist/App.js:11:1)
     at Module._compile (module.js:653:30)
     at Object.Module._extensions..js (module.js:664:10)
     at Module.load (module.js:566:32)
     at tryModuleLoad (module.js:506:12)
     at Function.Module._load (module.js:498:3)

when running docker-compose on the production server. Although I have successfully run it on a local machine, I really find it difficult to understand why this error occurred in the production server?
My package.json:
{
...
  "dependencies": {
    "@types/mocha": "2.2.41",
    "@types/node": "7.0.22",
    "@types/express": "^4.16.0",
    ...
    "nodemon": "latest",
    "puppeteer": "latest",
    "reflect-metadata": "latest",
    "typeorm": "0.2.16",
    "typescript": "latest"
  },
...
}
My Dockerfile:
FROM node:8.15.0
MAINTAINER Nguyen Tien-Linh <nguyentienlinh2611@gmail.com>

RUN mkdir -p /usr/src/app

WORKDIR /usr/src/app

COPY package.json /usr/src/app/
RUN yarn install

COPY . /usr/src/app

COPY wait-for-it.sh /

EXPOSE 3000

CMD /wait-for-it.sh database:3306 -- yarn run prod

My docker-compose.yml:
...
   web:
      container_name: vnuonline_web
      privileged: true
      build: .
      ports:
         - "3000:3000"
      volumes:
         - data:/usr/src/app/data
         - .:/usr/src/app
         - /var/run/docker.sock:/var/run/docker.sock
      restart: on-failure
      links:
         - openface
         - database
      depends_on:
         - openface
         - database
...

A: Based on your dependency list my guess is that reflect-metadata is listed as a 'devDependencies' and not a regular dependency. Make sure it is listed in the correct section in package.json. Anything you need for running in production, you need in the dependencies section.

A: I had the same issue yesterday, and found a solution :
You have to explicitly define a volume for your node_modules :
...
   web:
      container_name: vnuonline_web
      privileged: true
      build: .
      ports:
         - "3000:3000"
      volumes:
         - data:/usr/src/app/data
         - .:/usr/src/app
         - /var/run/docker.sock:/var/run/docker.sock
         - /usr/src/app/node_modules    # new line here
      restart: on-failure
      links:
         - openface
         - database
      depends_on:
         - openface
         - database
...

To make sure my app on server was clean before trying, I also removed the Docker images and rebuilt everything