text:
Q: Using R, how to trace a function based on library::method? I was reviewing the function install_github which I thought belonged to the library devtools.
It does, sort of.  It belongs to a library remotes.
When an error triggers in RStudio, you have a way to trace the stack to troubleshoot.  Can I apply that logic proactively?
Is there a function traceFunction() or something that can see return a list of sequential library::method calls?
If the function doesn't exist, could it?
traceFunction("install_github");

Update
To clarify, I did git clone on the referenced packages.  devtools has the following:
#' @importFrom remotes install_github
#' @rdname remote-reexports
#' @export
install_github <- with_pkgbuild_build_tools(with_ellipsis(remotes::install_github))

Where remotes has the following:
#' # To install from a private repo, use auth_token with a token
#' # from https://github.com/settings/tokens. You only need the
#' # repo scope. Best practice is to save your PAT in env var called
#' # GITHUB_PAT.
#' install_github("hadley/private", auth_token = "abc")
#'
#' # To pass option arguments to `R CDM INSTALL` use `INSTALL_opts`. e.g. to
#' install a package with source references and tests
#' install_github("rstudio/shiny", INSTALL_opts = c("--with-keep.source", "--install-tests"))
#' }
install_github <- function(repo,
                           ref = "HEAD",
                           subdir = NULL,
                           auth_token = github_pat(quiet),
                           host = "api.github.com",
                           dependencies = NA,
                           upgrade = c("default", "ask", "always", "never"),
                           force = FALSE,
                           quiet = FALSE,
                           build = TRUE, build_opts = c("--no-resave-data", "--no-manual", "--no-build-vignettes"),
                           build_manual = FALSE, build_vignettes = FALSE,
                           repos = getOption("repos"),
                           type = getOption("pkgType"),
                           ...) {

  remotes <- lapply(repo, github_remote, ref = ref,
    subdir = subdir, auth_token = auth_token, host = host)

  install_remotes(remotes, auth_token = auth_token, host = host,
    dependencies = dependencies,
    upgrade = upgrade,
    force = force,
    quiet = quiet,
    build = build,
    build_opts = build_opts,
    build_manual = build_manual,
    build_vignettes = build_vignettes,
    repos = repos,
    type = type,
    ...)
}

which calls install_remotes which I don't readily find by searching all ".R" files in the repository remotes.

A: Short answer, no. R is dynamically typed and has a number of different typing systems (S3, S4, R6, etc.). In short, we see the effect of the dynamic typing in calls to e.g. print or plot. You might have noticed that print behaves differently for matrices, simple vectors, lists, data.frames etc. plot is even more diverse and can handle the former mentioned types, as well as almost any custom object thrown to it from other packages (correlation matrices, heatmaps, etc.) - and produces widely different results.
This is due to R's method dispatching (and similar ideas for the different typing system), which basically looks at the class of the object passed as the first argument(s) to the function. It then tries to call plot.<class> for each class in the class-attribute of the object, until something works. If nothing works, it falls back to plot.default.
This is why many packages can use the plot-function. They implement a plot-function, say plot.foobaz that works for their foobaz-classed objects.
Then there are methods that, based on the input, concatenate function names and then tries to call them.
On top of that, we can throw different packages into the environment (with e.g. library) which might alter the path of execution, when a package's methods mask a previously loaded package.
So to proactively figure out the call tree of method, it would be restricted to be based on the actual objects passed. There is a package that does this, https://rdrr.io/cran/lobstr/man/cst.html.


text:
Q: Show that given a set of positive n integers, there exists a non-empty subset whose sum is divisible by n This is the question I've run into: Show that given a set of  positive n integers, there exists a non-empty subset whose sum is divisible by  n
I'm having trouble understanding how they came to the conclusion

the part that I'm having trouble understanding is how subtracting the two subsets results in a sum that's divisible by n given that the two subsets have the same remainder

A: Let $p<q$, if $S_p = \sum_{i=1}^p s_i \equiv r \pmod{n}$
and $S_q = \sum_{i=1}^q s_i \equiv r \pmod{n}$
then we have $S_q-S_p=\sum_{i=p+1}^q s_i \equiv r-r \equiv  0 \pmod{n}$
where we have use the property that if $a \equiv b \pmod{n}$ and $c \equiv d \pmod{n}$, then we have $a-c \equiv b-d \pmod{n}$
If you are not familiar with modulo arithmetic, view it as if $a = nk+r$ and $c = nt+r$, then $a-c = n(k-t)$.

A: Via modular arithmetic this is very easy, and something you can check (if you're familiar with this). Otherwise, one can show the following result via the division algorithm (i.e. just straight division with quotient and remainder):

If $a$ and $b$ have the same remainder when divided by $n$, then $a-b$ is divisible by $n$.

The proof is as follows. Let $r$ be the common remainder of $a$ and $b$ when divided by $n$. The division algorithm gives integers $q,p$ such that $a=qn+r$ and $b=pn+r$. Thus, we get $$a-b=(qn+r)-(pn+r)=(qn-pn)+(r-r)=(q-p)n$$
so $n$ divides $a-b$.
Note that the above result is more general, and can be applied to your situation by having $a=S_j$ and $b=S_i$. It doesn't really matter that the $S_i$ and $S_j$ are sums of integers when applying the statement I just proved; as far as we care they are just some integers $a$ and $b$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Certificates of connectivity of basic semi-algebraic sets Given real polynomials $p_1, \ldots, p_n \in {\mathbb R}[x_1, \ldots, x_d]$, consider the closed basic semi-algebraic set $S \subseteq {\mathbb R}^d$ given by $$S := \{x \in {\mathbb R}^d : p_i(x) \geq 0 \text{ for every $i$}\}$$
I am curious as to whether there any computationally efficient certificates concerning the connectedness of $S$.
Here, I have to be somewhat vague about what it means to be computationally efficient: essentially, I mean a numerical algorithm having polynomial-time complexity which produces either (up to numerical roundoff error):

*

*a certificate that $S$ is connected; or

*a certificate that $S$ has multiple connected components; or

*an inconclusive answer
with the hope that the third outcome is sufficiently rare, or can be made more and more rare by increasing the degree of the working polynomials, similar to the Lasserre hierarchy in polynomial optimisation.
With this definition of efficiency, an algorithm based on cylindrical algebraic decomposition is not sufficiently fast (though it is deterministic in exact arithmetic).
In the more restrictive case of deciding convexity (rather than connectedness) of basic semi-algebraic sets, there is indeed a fast approach. In 2009, Lasserre developed certificate methods examining the convexity of $S$, see doi:10.1016/j.aml.2010.04.009. In essence, his algorithm checks whether the double-variable polynomial $(x,y) \mapsto p_j ( (x+y)/2 )$ is non-negative on $S \times S$ via semidefinite programming (for each $j = 1, \ldots, n$). The approach works in polynomial time and satisfies the above speed requirements.
I like the elegance of this approach to compute certificates of the (non-)convexity of $S$, using the speed of semidefinite programming. I suspect the same cannot be done to derive certificates of connectedness of $S$, though I am not sure. Does anyone here have some thoughts on this? My question is similar to a previous one, but a little more directed in the sense that I am permitting the algorithm to return an answer of "I'm uncertain whether $S$ is connected or not", similar to Lasserre's certificate methods for convexity.


text:
Q: JS PDF Blob empty page I'm using external Rest API to get spedition label for package. In response I have:
%PDF-1.4\n%����\n6 0 obj\n<</ColorSpace[/Indexed/DeviceRGB 255(\0\0\0 [...]

Now I need to display PDF in browser
var xhr = new XMLHttpRequest();
    xhr.open('POST', '/Order/CreateShipmentInpost', true);
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhr.responseType = 'arraybuffer';
    xhr.onload = function (e) {
        if (this.status == 200) {
            var blob = new Blob([this.response], { type: "application/pdf" });
            var link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = "Report.pdf";
            link.click();
        }
    };
    xhr.send($.param(data));

In generated PDF file is only blank page. I don't know why content is not showing.

I'm using responseType = 'arraybuffer'. Controller returns:
 return File(Encoding.UTF8.GetBytes(data, MediaTypeNames.Application.Pdf);

I also tried to return json or string, but PDF was always empty.


text:
Q: How to wait for each process to terminate in the following example? The program terminates after taking 4 or 5 values from scanf.
But I want it to accept 8 values (totaling 8 processes) and then terminate.
void main() {
    fork();
    fork();
    fork();

    scanf("%d",&j);
    printf("The values are %d\n",j);

    wait(0);
}

A: Well, the first question you have to answer to yourself is how many processes you think you have there?  As you don't use the returned value from the fork(2) system call, you don't know even if you are the parent or you are the child after execution of each fork.
You'll have one process at the beginning of the tale, which does a fork(2) system call and converts in two processes, that then execute (both, parent and child) a second fork(2) call, converting (each) in two processes (two more, so four in total) when the second call returns.  Then comes the third, which duplicates again the number of processes, so you'll get at the end of the story eight running processes at all in a binary tree execution history hierarchy fully populated up to height three.
but the processes relationships are not the same
The processes can each wait(2) for each of their own children, but there are processes that, since their inceptions have made three, two, one, or no fork() at all. The root node is the only that makes three fork()s, so it can do up to three wait(2)s without error (for each of its children), the first of its children, makes only two, the second makes only one... like this:
proc[0]---fork()-----fork()---fork()----exit();
          |          |        |
          |          |        proc[3]---exit();
          |          |
          |          proc[2]--fork()----exit();
          |                   |
          |                   proc[4]---exit();
          |
          proc[1]----fork()---fork()----exit();
                     |        |
                     |        proc[5]---exit();
                     |
                     proc[6]--fork()----exit();
                              |
                              proc[7]---exit();

so

*

*proc[0] can wait(2) to proc[1], proc[2] and proc[3];

*proc[1] can wait(2) to proc[5] and proc[6];

*proc[2] can wait(2) to proc[4] only

*proc[3] cannot wait(2) (it will result in error if wait(2) is called);

*proc[4] cannot wait(2);

*proc[5] cannot wait(2);

*proc[6] can wait(2) only to proc[7] and

*proc[7] cannot wait(2).

As wait(2) can only wait for one of such children (children must be created with fork, or the call will result in error) you have to issue as many wait(2) calls as fork(2)s you have issued, to wait for them all, so you must control the number of children you have (as you see, this number is different for each process).  You can, for example, increment a counter in the parent (the process that receives a 0 result from fork(2) so you know the number of fork(2)s you have issued up to now.
int main()
{
    int forks_made = 0;
    if (fork() > 0) forks_made++;
    if (fork() > 0) forks_made++;
    if (fork() > 0) forks_made++;
    for (i = 0; i < forks_made; i++) wait(NULL);
    exit(0);
}

or simply, you can wait(2) until the system call results in an error (you don't have more children)
int main()
{
    fork();
    fork();
    fork();
    while(wait(NULL) == 0)
        continue;
    exit(0);
}

Be careful as the process hierarchy is a different tree from the binary history tree.  The process hierarchy is like this:
proc[0]
|
+--proc[1]
|  |
|  +--proc[5]
|  |
|  `--proc[6]
|     |
|     `--proc[7]
|
+--proc[2]
|  |
|  `--proc[4]
|
`--proc[3]

Suppose I write the following code:
int main()
{
    fork(); fork(); fork();
    wait(0); wait(0); wait(0);
    exit(0);
}

The result is:
                                ok             ok         ok
p[0]-f()-f()-f()----------------w()------------w()--------w()-exit();
     |   |   |                  ^              ^          ^
     |   |   |      err err err |              |          |
     |   |   +-p[3]-w()-w()-w()-exit();        |          |
     |   |                                     |          |
     |   |                         ok  err err |          |
     |   +-p[2]-f()----------------w()-w()-w()-exit();    |
     |          |                  ^                      |
     |          |                  |                      |
     |          |      err err err |                      |
     |          +-p[4]-w()-w()-w()-exit();                |
     |                             ok             ok  err |
     +-p[1]-f()-f()----------------w()------------w()-w()-exit();
            |   |                  ^              ^
            |   |      err err err |              |
            |   +-p[5]-w()-w()-w()-exit();        |
            |                         ok  err err |
            +-p[6]-f()----------------w()-w()-w()-exit();
                   |                  ^
                   |      err err err |
                   +-p[7]-w()-w()-w()-exit();

NOTE
Even if the children die before the parent does a wait(2) the kernel maintains them in the process table (but without any resource allocated) as zombie processes just to wait for the parent to do the proper wait(2) system call.  This is why the kernel knows that you can do a wait(2) or not (you can only wait if you have made a fork(2)).
NOTE 2
Why the process only read(2)s part of the results and finishes? Well, I have been reading some documentation and making some tests, and the behaviours are different on the three operating systems I have tested on:

*

*MacOS X.  I have tested and when the process group leader exit(2)s, all of its children are awaken from the read(2) call and given a ETIMEDOUT error (surprisingly)

*FreeBSD. On FreeBSD, the result is similar but with a different error (EIO).

*Linux. On Linux, the terminal driver gives each process only one input character (even if there are more) in raw mode (they output each caracter as it is read) This is by far the most weird behaviour.

As normal job control makes the shell to reacquire the control terminal and the process group ceases to be the control group of the terminal device, the terminal should awake all the processes trying to read(2) from it with an error code, so perhaps FreeBSD is the most coherent result we should have.
The code used to test this case follows:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>

void hndlr(int sig)
{
    printf("%d(prnt=%d,pgrp=%d): signal %d received\n",
            getpid(), getppid(), getpgrp(), sig);
}

int main()
{
    int i;
    char line[1024];

    for (i = 1; i < 64; i++)
        signal(i, hndlr);
    printf("pid=%d, pgrp=%d\n", getpid(), getpgrp());
    fork();
    fork();
    fork();
    i = read(0, line, sizeof line);
    switch(i) {
    case -1:
        printf("pid=%d, prnt=%d, pgrp=%d: read: %s(errno=%d)\n",
                getpid(), getppid(), getpgrp(), strerror(errno), errno);
        break;
    case 0:
        printf("pid=%d, prnt=%d, pgrp=%d: read: EOF\n",
                getpid(), getppid(), getpgrp());
        break;
    default:
        printf("pid=%d, prnt=%d, pgrp=%d: read: [%*.*s]\n",
                getpid(), getppid(), getpgrp(), i, i, line);
        break;
    }
#if 0
    wait(NULL);
    wait(NULL);
    wait(NULL);
#endif
} /* main */

A: The problem here is that wait(0) only waits for the first child. The main process will exit once it has successfully raced to get its own input, and a direct child has done the same.
The easiest kludge is to just wait until there are no more children to wait for:
void main() {
    int j;
    fork();
    fork();
    fork();

    scanf("%d", &j);
    printf("The values are %d\n",j);

    while (wait(0) != -1);
}

This reads 8 values from the interactive terminal as expected.
You should never do this in a real program though. The main thread should instead read all 8 values and create the children as needed to process them. Failing to do so causes race conditions and buffering issues.
Here's an example of this, using one less fork() for brevity:
$ for i in {1..4}; do echo "$i"; done  | ./foo
The values are 1
The values are 0
The values are 0
The values are 0

$ for i in {1..4}; do echo "$i"; sleep 0.1; done  | ./foo
The values are 1
The values are 2
The values are 3
The values are 4

In the former case, multiple writes to the pipe become a single read, which is picked up by an arbitrary process. The others get nothing.
In the second case, a short sleep is added to allow more time between each read, and now they get the values as expected.

A: You need to wait for all your children and your children need to wait for their children, etc. Currently your wait(0) call only waits for one child to change state.
// wait(0);
while (1) {
   int status;
   pid_t done = wait( &status );
   if ( done == -1 )
      break; // no more children
}


text:
Q: java.lang.Error: javax.crypto.BadPaddingException I have implemented AES Algorithm to encrypt and Decrypt the access token, below is my Code.
    @RequiresApi(Build.VERSION_CODES.M)
    fun createKey(): SecretKey {
        try {
            var keyGenerator =
                KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
            keyGenerator.init(
                KeyGenParameterSpec.Builder(
                    "SCI",
                    KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
                )
                    .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                    .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
                    .build()
            )
            return keyGenerator.generateKey()
        } catch (e: NoSuchAlgorithmException) {
            throw RuntimeException("Failed to create a Symmetric Key", e)
        } catch (e: NoSuchProviderException) {
            throw RuntimeException("Failed to create a Symmetric Key", e)
        } catch (e: InvalidAlgorithmParameterException) {
            throw RuntimeException("Failed to create a Symmetric Key", e)
        }
    }

    fun storeData(data: String, key: String, context: Context) {
        val pref = PreferenceProvider(context)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val secretKey = createKey()
            val chiper =
                Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7)
            chiper.init(Cipher.ENCRYPT_MODE, secretKey)
            val encryptionIV = chiper.iv
            val passwordBytes = data.toByteArray()
            val encrptedPasswordBytes = chiper.doFinal(passwordBytes)
            val encrptedValue = android.util.Base64.encodeToString(
                encrptedPasswordBytes,
                android.util.Base64.DEFAULT
            )
            pref.saveString(key, encrptedValue)
            pref.saveString(
                "encryptionIV", android.util.Base64.encodeToString(
                    encryptionIV,
                    android.util.Base64.DEFAULT
                )
            )
        } else {
            pref.saveString(key, data)
        }
    }

    fun retraiveData(key: String, context: Context): String {
        val pref = PreferenceProvider(context)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val base64EncryptedPassword = pref.getString(key)
            val base64EncryptedIV = pref.getString("encryptionIV")
            val encryptedPassword = Base64.decode(base64EncryptedPassword, Base64.DEFAULT)
            val encryptedIV = Base64.decode(base64EncryptedIV, Base64.DEFAULT)
            var keyStore = KeyStore.getInstance("AndroidKeyStore")
            keyStore.load(null)
            val secretKey = keyStore?.getKey("SCI", null) as SecretKey
            val chiper =
                Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7)
            chiper.init(Cipher.DECRYPT_MODE, secretKey, IvParameterSpec(encryptedIV))
            val passwordBytes = String(chiper.doFinal(encryptedPassword), charset("UTF-8"))
            //  val passwordBytes = chiper.doFinal(encryptedPassword)
            val password = passwordBytes
            return password
        } else {
            return pref.getString(key)
        }
    }

getting below error
java.lang.Error: javax.crypto.BadPaddingException
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1173)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:923)
     Caused by: javax.crypto.BadPaddingException
        at android.security.keystore.AndroidKeyStoreCipherSpiBase.engineDoFinal(AndroidKeyStoreCipherSpiBase.java:515)
        at javax.crypto.Cipher.doFinal(Cipher.java:2055)
        at s4.c.a(Unknown Source:30)
        at e6.g.c(RealInterceptorChain.kt:14)
        at d6.e.g(RealCall.kt:23)
        at d6.e$a.run(RealCall.kt:12)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:923)
     Caused by: android.security.KeyStoreException: Invalid argument
        at android.security.KeyStore.getKeyStoreException(KeyStore.java:1461)
        at android.security.keystore.KeyStoreCryptoOperationChunkedStreamer.doFinal(KeyStoreCryptoOperationChunkedStreamer.java:186)
        at android.security.keystore.AndroidKeyStoreCipherSpiBase.engineDoFinal(AndroidKeyStoreCipherSpiBase.java:506)
        at javax.crypto.Cipher.doFinal(Cipher.java:2055)
        at s4.c.a(Unknown Source:30)
        at e6.g.c(RealInterceptorChain.kt:14)
        at d6.e.g(RealCall.kt:23)
        at d6.e$a.run(RealCall.kt:12)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:923)


text:
Q: Understanding the Selection Rules of a Spin-Forbidden, Magnetic Dipole Transition in Molecular Oxygen I am studying the transition from the second excited electronic state of molecular oxygen, $b^1\Sigma_g^+$ , to the ground state, $X^3\Sigma_g^-$. I know that the ground state has total angular momentum $J=1$, total spin $S=1$, and three spin sublevels $(m_s=-1,0,+1)$. The upper state has $J=0$, $S=0$, and one sublevel with $m_s=0$. I am specifically interested in the transition from the upper state to the ground state $m=\pm1$ level and I will refer to it as the $b-X,1$ transition.
I would like to understand the the selection rules that govern this transition and the language that is used to describe this transition.
Here is what I know so far about this transition.

*

*Brecha, Pedrotti, Krause, "Magnetic rotation spectroscopy of molecular oxygen with a diode laser" JOSA 1998: They describe this transition as "doubly weak" and I quote, "First, it is a magnetic dipole transition and thus is roughly 5 orders of magnitude weaker than a normal electric dipole transition. Second, the transition is a singlet-triplet intercombination band, making it 3 orders of magnitude weaker still."

*Minaev, Agren, 1997: They describe this transition as "magnetic dipolar" and "spin-forbidden." They also say that it is spin-orbit coupling that accounts for this "doubly weak" transition being as large as it is.

*Wikipedia-Selection Rules: Provides the rules for Magnetic Dipole (M1) transitions and discusses Spin-Obrit (LS) Coupling but I do not understand where this came from.

*Sannigrahi, "Derivation of Selection Rules for Magnetic Dipole Transitions,"  1982: This is pretty clear but just seems to say that $\Delta m_s=\pm1$. This is true for the $b-X,1$ transition but how do I tie in $L$ and $J$ into the selection rules?
Most of what I have found on the internet and in textbooks relating to selection rules is directed to electric dipole transitions. Where I have found something discussing magnetic dipole transitions, it is either a summary of the rules or I do not have the required background to understand it.

*

*What does it mean for a transition to be spin-forbidden?

*What is a singlet-triplet intercombination band? Does this change the selection rules? How is this related to being spin-forbidden?

*What does spin-orbit coupling have with this?
I look forward to any feedback on this topic.
Follow up Questions
Meaning of Spin-Forbidden
Does 'spin-forbidden' just mean that the transition from a $J=1$ to $J=0$ state is not allowed because the selection rules for magnetic dipole transitions say that $J$ cannot change? I expected 'spin-forbidden' to imply something about the change of the spin between the initial and final states.
For example, suppose I have a time-dependent perturbation like $V_{md}(t) = \frac{e}{m} \vec{S}\cdot \vec{B}(t)$ and I am interested in the transition rate between the initial state $\left| s m_s \right\rangle$ and the final state $\left| s' m_s' \right\rangle$ with the quantization axis in the z direction. As you pointed out, the transition rate will be proportional to $\left\langle s' m_s'\right| \vec{S} \cdot \vec{B}(t) \left| s m_s \right \rangle$. Now if $\vec{B}(t)$ is circularly polarized, the rules for an allowed transition will be $s'-s=0$ and $m_s'-m_s = \pm1$. For  $\vec{B}(t)$ polarized in the z direction,  $s'-s=0$ and $m_s'-m_s = 0$ so there is not a transition to other states. I would think that if $s'-s=0$ and $m_s'-m_s = \pm1$ are not true (like if $s'=1$ and $s=0$), then the magnetic dipole transition between $\left| s m_s \right\rangle$ and  $\left| s' m_s' \right\rangle$ would be called 'spin-forbidden.'
The same arguments could be made for $\vec{L}$ or $\vec{J}$ as I did with $\vec{S}$. Would you also call a magnetic dipole transition between $\left| L=0 \right\rangle$ and $\left| L=1 \right\rangle$ 'spin-forbidden?'
Spin-Orbit Coupling
Now the difference in the energies of the singlet $(b)$ and triplet, ground state $(X)$ is $1.63\text{ eV}$. That seems too large to be due to spin-orbit coupling breaking a degeneracy. If I was pretending this was a hydrogen atom, I would say this was like a transition where the principle quantum number $n$ changed. I am not sure how to talk about this in a molecule.
This isn't key to the rest of your explanation but I did want to clarify to make sure we were on the page.
Singlet-Triplet Intercombination Band
Do you know what the expression 'singlet-triplet intercombination band' is referring to? After your explanation, it seems to refer to the mixing of the singlet and triplet states due to spin-orbit coupling (SOC). Is this true?
Mixing of unperturbed states
How did you know that the perturbed upper state could be written as a combination of the unperturbed upper state and the $M_s=0$ ground state? It makes sense that the states would get mixed up by SOC but I don't know how. If this is a messy explanation, don't worry about it.
I would like to reiterate that your (George G's) explanation has been incredibly helpful. Thank you.

A: A magnetic dipole transition can be modelled as a time-dependent perturbation $V_{\text{md}}(t) = {e\over 2 m}(\vec{L} + 2\vec{S})\cdot \vec{B}e^{-i \omega t}$. Fermi's Golden Rule tells us that the transition rate for $b-X,1$ is proportional to the matrix element of the perturbation between the initial and final states,
$$W \propto \langle \psi_b|{e\over 2 m}(\vec{L} + 2\vec{S})\cdot \vec{B}|\psi_{X}\rangle,$$
where $|\psi_b\rangle$ is the excited state and $|\psi_{X}\rangle$ is the ground state (with three possible $M_S$ values.)
The effect of $\vec L$ and $\vec S$ will be to turn the final state into some combination of the triplet states, but it won't change $J$. Therefore we might expect the transition to be 'spin-forbidden':
$$W \propto \langle b^1\Sigma_g^+ |X^3\Sigma_{g,M_S=0,\pm1}^-\rangle = \langle J=0 | J=1 \rangle = 0.$$
This is where the spin-orbit coupling comes into play. Spin-orbit coupling is the reason why the singlet $(b)$ state has a higher energy than the triplet $(X)$ states. It is a perturbation of the form $V_\text{SO}={\mu\over\hbar}\vec{L}\cdot\vec{S}$, which can be rewritten as $V_\text{SO}={\mu \over 2\hbar}(J^2-L^2-S^2)$. In a spherically symmetric system like the helium atom, this perturbation commutes with the Hamiltonian, so all you get is a shift in the energy of the triplet (L=1) and singlet (L=0) states. However, in a linear molecule like $O_2$ you lose the spherical symmetry, so $[L^2,H]\neq0$ and in addition to an energy shift, you also get some mixing of the unperturbed eigenstates, so that the excited state is not exactly $|b^1\Sigma_g^+\rangle$, but rather $|\psi_b\rangle = c_1|b^1\Sigma_g^+\rangle + c_2|X^3\Sigma_{g,M_S=0}^-\rangle$. This mixing of J=0 and J=1 states is what allows $W$ to have a nonzero value. Since we can write $S_x = S_+ + S_-$, there will be a term in the transition rate like
$$W\propto c_2^*\langle X^3\Sigma_{g,M_S=0}^-|S_{\pm}|X^3\Sigma_{g,M_S=\mp1}^-\rangle+\cdots \neq 0.$$
Does this help? I know this is a bit hand-wavy so let me know if I can clarify anything.


text:
Q: Get file content from shared document in Sharepoint 2013 using JSOM I have excel file in shared document in sharepoint 2013. I want to store the content of that file in array variable and send it to server side for processing.
I am getting the client context loaded,but i want to get the records present inside in the file. I have excel file present inside SharedDocument/test folder
ExecuteOrDelayUntilScriptLoaded(viewfiles, "sp.js");
function viewfiles(){
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle('Documents');
var query = SP.CamlQuery.createAllItemsQuery();
query.set_folderServerRelativeUrl('http://win-mjphj36pn7d:55555/sites/Demo/Shared%20Documents/test');
allItems = list.getItems(query);
context.load(allItems, 'Include(Title, ContentType, File)');
context.executeQueryAsync(
Function.createDelegate(this, function (sender, args) {
                     var fileUrls = ""; var fileUrls = "";
                      var ListEnumerator = this.allItems.getEnumerator();
                       while(ListEnumerator.moveNext())
                       {
                        var currentItem = ListEnumerator.get_current();
                        var _contentType = currentItem.get_contentType();
                         if(_contentType.get_name() != "Folder")
                           {
                            var File = currentItem.get_file();
                            if(File != null)
                              {
                               fileUrls += File.get_serverRelativeUrl() + '\n';
                              }
                           }
                       }
                      alert(fileUrls);
                }),

Function.createDelegate(this, function (sender, args) {
          alert("failed. Message:" + args.get_message());
             })
            );

Please suggest how i get all data in the file in a array var or string

A: Apparently for some reason the openbinary method from  CSOM is not available in JSOM (or a least not documented).
So I'd suggest that you first try within the console in the browser's context to see if it's here. Otherwrise see the REST API documentation (second example) to retrieve the binary value.
Here is the jsom documentation and the CSOM documentation of this same aspect.


text:
Q: AWS DMS and Redshift I am using DMS to migrate data from MySQL to Redshift.
Inside DMS, I use the 'full-load-and-ongoing' option to load data to Redshift.
Assuming the full-load is complete and the on-going is in progress,I would like to know how I can resume the DMS task in case we restore Redshift using an old snapshot.
Thanks in advance.

A: You would need to

*

*Stop the DMS task

*Restore your target redshift

*RESTART your DMS task. (This will do the initial copy again and then reinstate the continuous replication)

If you have made any modifications to the target tables then change your task to truncate rather than drop and create.
If you cannot have any downtime on your Redshift table then you could do the following.

*

*Rename your existing Redshift table to be _inuse, e.g. if your table
is called orders then call it orders_inuse

*Create a new "late binding" view like this
CREATE VIEW orders as
SELECT * FROM orders_inuse
WITH NO SCHEMA BINDING;

*Set up DMS to replicate to orders_new table

*Drop orders_inuse

*recreate your view
CREATE or replace VIEW orders as
SELECT * FROM orders_new
WITH NO SCHEMA BINDING;


text:
Q: Assign all capturing groups of one regex to a hash Let's say you have a string that you know will match a regex at least once. That regex has two capturing groups and you want to assign each couple to a key-value pair in a hash.
I was thinking something like this, but I'm not sure if this is the Perl way to go - or if it would even work.
$string = 'f=banana&c=3;f=strawberry&c=1;f=coconut&c=6';
my %countedfruit;
($countedfruit{$1} = $2) = $string =~ /f=([a-z]+)&c=([0-9]+)/g;

for my $fruit (keys %countedfruit) {
    print "The count of '$fruit' is $countedfruit{$fruit}\n";
}

Expected result:
The count of 'banana' is 3
The count of strawberry is 1
The count of coconut is 6

Actual result:
The count of 'coconut' is

A: Just feed the hash with the list of pairs (matches)
%countedfruit = $string =~ /f=([a-z]+)&c=([0-9]+)/g;

This will issue a warning if there isn't an even-numbered list (with warnings enabled), otherwise key-value pairs in the hash are formed of pairs of consecutive matches in the list returned by m/.


text:
Q: Port forwarding with firewall-cmd I have several VMs running on top of a server (Virtual Machine Manager, VMM). I'd like to forward port 80 on the server to port 80 of one of my VMs. The host runs CentOS7, so firewalld is in charge. Apparently, firewalld is also used by VMM to handle the virtual connections, so I can't just throw it out of the window.
I basically reproduced all commands in this thread without success, which boils down to:
firewall-cmd --permanent --zone=public --add-forward-port=port=80:proto=tcp:toport=80:toaddr=192.168.122.224

or
firewall-cmd --permanent --zone=public --add-rich-rule 'rule family=ipv4 forward-port port=80 protocol=tcp to-port=80 to-addr=192.168.122.224'

The current status of firewalld is the following:
[root@my-machine ~]# firewall-cmd --list-all
public (active)
  target: default
  icmp-block-inversion: no
  interfaces: enp8s0
  sources:
  services: ssh dhcpv6-client samba smtp http
  ports: 25/tcp
  protocols:
  masquerade: yes
  forward-ports:
  source-ports:
  icmp-blocks:
  rich rules:
  rule family="ipv4" forward-port port="80" protocol="tcp" to-port="80" to-addr="192.168.xxx.xxx"

This is the output of
iptables -L -n -v

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target     prot opt in     out     source               destination
13917 8976K ACCEPT     all  --  *      virbr0  0.0.0.0/0               192.168.122.0/24     ctstate RELATED,ESTABLISHED
13539 2093K ACCEPT     all  --  virbr0 *       192.168.122.0/24     0.0.0.0/0
0     0 ACCEPT     all  --  virbr0 virbr0  0.0.0.0/0            0.0.0.0/0
4   240 REJECT     all  --  *      virbr0  0.0.0.0/0            0.0.0.0/0            reject-with icmp-port-unreachable <-----
1   133 REJECT     all  --  virbr0 *       0.0.0.0/0            0.0.0.0/0            reject-with icmp-port-unreachable
0     0 ACCEPT     all  --  virbr1 virbr1  0.0.0.0/0            0.0.0.0/0
0     0 REJECT     all  --  *      virbr1  0.0.0.0/0            0.0.0.0/0            reject-with icmp-port-unreachable
0     0 REJECT     all  --  virbr1 *       0.0.0.0/0            0.0.0.0/0            reject-with icmp-port-unreachable
0     0 ACCEPT     all  --  *      *       0.0.0.0/0            0.0.0.0/0            ctstate RELATED,ESTABLISHED
0     0 ACCEPT     all  --  lo     *       0.0.0.0/0            0.0.0.0/0
0     0 FORWARD_direct  all  --  *      *       0.0.0.0/0            0.0.0.0/0
0     0 FORWARD_IN_ZONES_SOURCE  all  --  *      *       0.0.0.0/0            0.0.0.0/0
0     0 FORWARD_IN_ZONES  all  --  *      *       0.0.0.0/0            0.0.0.0/0
0     0 FORWARD_OUT_ZONES_SOURCE  all  --  *      *       0.0.0.0/0            0.0.0.0/0
0     0 FORWARD_OUT_ZONES  all  --  *      *       0.0.0.0/0            0.0.0.0/0
0     0 DROP       all  --  *      *       0.0.0.0/0            0.0.0.0/0            ctstate INVALID
0     0 REJECT     all  --  *      *       0.0.0.0/0            0.0.0.0/0            reject-with icmp-host-prohibited

the problem is the 2nd rule, that seem to reject my packages (I can see the number increasing when trying to connect). Indeed, if I remove it with:
iptables -D FORWARD -o virbr0 -j REJECT --reject-with icmp-port-unreachable

my port forwarding works. What am I missing?

A: Mixing firewalld with libvirt can get you into this sort of situation.
By default with a "NAT" network, libvirt's networking will set up masquerade rules so that the VMs can access the legacy IPv4 Internet. But, libvirt blocks all incoming connections to "NAT" networks.
The solution is to change the network to a normal routed network, and then let firewalld handle any masquerading that you might require.
For instance, you would edit the network XML and change
  <forward mode='nat'/>

to
  <forward mode='route'/>

I recommend you change all libvirt NAT networks to routed, in this scenario, not just the one you want to forward ports to, if you want to allow the networks to communicate with each other.
Then you set masquerading on the firewalld zone corresponding to the interface connected to the rest of the Internet. For example:

firewall-cmd [--permanent] --zone=public --add-masquerade

(With firewalld 0.4.4.6 or later, you should not use this, but instead create a rich rule for IPv4 masquerade. These versions have a misfeature that causes an IPv6 masquerading rule to also be added when using --add-masquerade, which will break IPv6 connectivity.)
firewall-cmd [--permanent] --zone=public --add-rich-rule='rule family=ipv4 masquerade'


text:
Q: How to call a lambda function from above? I am trying to use my interest multiplier function from above and use that in the compound interest rate function but cannot figure out what I'm doing wrong here.
interest_multiplier = lambda r, n: (1 + (r/n))
print ("The interest multiplier is: ", interest_multiplier(.05,1))

compound_interest_rate = lambda interest_multiplier, n, t: interest_multiplier ** (n*t)
print ("The compund interest rate is: ", compound_interest_rate(interest_multiplier, n, 1))

A: interest_multiplier = lambda r, n: (1 + (r/n))
print ("The interest multiplier is: ", interest_multiplier(.05,1))

This is exactly correct. You call a lambda function just like any other function.
compound_interest_rate = lambda interest_multiplier, n, t: interest_multiplier ** (n*t)
print ("The compund interest rate is: ", compound_interest_rate(interest_multiplier, n, 1))

The problem here is that you are passing interest_multiplier to compound_interest_rate then using the ** operator with it. You cannot raise a function to a power in Python. I believe that you want to use the interest_multiplier function inside the compount_interest_rate function:
compound_interest_rate = lambda r, n, t: interest_multiplier(r, n) ** (n*t)

Note that I modified compount_interest_rate to have an argument named r. I also call interest_multiplier with the correct arguments.


text:
Q: How to create a multi-dimensional array from an indexed array in PHP?
*

*I have a 2D array that its first dimension is an index array and the second one is an associative array.

*In the array, there are some duplicates fields that I want to merge them, and for the other unduplicated fields, I want to make a third dimension array and push them there.

This is my code and array:
The entire code works correctly just the "datacontractor" field that is my third dimension does not work well.
        <?php
    $array=Array
    (
        "0" => Array
        (
                "sid" => 10,
                "contractorid" => 1,
                "fname" => "hi",
                "lname" => "fam",
                "sname" => "saba",
                "materialname" => "beton",
                "netweight" => 100,
            ),
        "1" => Array
        (
                "sid" => 16,
                "contractorid" => 2,
                "fname" => "a",
                "lname" => "a",
                "sname" => "khoram",
                "materialname" => "kk",
                "netweight" => 200,
            ),
        "2" => Array
        (
                "sid" => 16,
                "contractorid" => 7,
                "fname" => "a",
                "lname" => "a",
                "sname" => "khoram",
                "materialname" => "kk",
                "netweight" => 777,
            ),
        "3" => Array
        (
            "sid" => 10,
            "contractorid" => 5,
            "fname" => "hi",
            "lname" => "fam",
            "sname" => "saba",
            "materialname" => "beton",
            "netweight" => 200,
        ),
        "4" => Array
        (
            "sid" => 10,
            "contractorid" => 8,
            "fname" => "hi",
            "lname" => "fam",
            "sname" => "saba",
            "materialname" => "beton",
            "netweight" => 600,
        ),
        "5" => Array
        (
            "sid" => 15,
            "contractorid" => 9,
            "fname" => "hi",
            "lname" => "fam",
            "sname" => "saba",
            "materialname" => "beton",
            "netweight" => 400,
        ),

    );

    $finalarray[]= array();
    $sidlist= array();
    $arraycount=count($array);
    for($i=0;$i<$arraycount ;$i++) {
        array_push($sidlist,$array[$i]["sid"]);
    }
    $sidlist = array_unique($sidlist);
    $sidlistcount=count($sidlist);
    $sidlist1=array();
    foreach ($sidlist as $m){
        array_push($sidlist1,$m);
    }

    for ($i = 0;$i<$sidlistcount ; $i++){
        $id=$sidlist1[$i];
        $datacontractor[$id]= array();
        for ($j = 0;$j<$arraycount ; $j++){
            if ($id==$array[$j]["sid"]){
                $contractorid = $array[$j]["contractorid"];
                $netweight = $array[$j]["netweight"];
                $finalarray[$i]=array(
                    "sid" => $id,
                    "fname" => $array[$j]["fname"],
                    "lname" => $array[$j]["lname"],
                    "sname" => $array[$j]["sname"],
                    "materialname" => $array[$j]["materialname"],
                    "datacontractor" => $datacontractor[$id],

                );

                $datacontractor[$id]["$contractorid"]=$netweight;
                echo $id,"
";
            }

        }
    }

    echo '
';
    print_r($finalarray);
    echo '
';

This is my output of this code:
but it has wrong answer in "datacontractor" field.
Array ([0] => Array
    (
        [sid] => 10
        [fname] => hi
        [lname] => fam
        [sname] => saba
        [materialname] => beton
        [datacontractor] => Array
            (
                [1] => 100
                [5] => 200

            )

    )[1] => Array
    (
        [sid] => 16
        [fname] => a
        [lname] => a
        [sname] => khoram
        [materialname] => kk
        [datacontractor] => Array
            (
                [2] => 200

            )

    )[2] => Array
    (
        [sid] => 15
        [fname] => hi
        [lname] => fam
        [sname] => saba
        [materialname] => beton
        [datacontractor] => Array
            (

            )

    ))

And Finally My desired output is:
Please check and tell me what my fault is.
Array ([0] => Array
    (
        [sid] => 10
        [fname] => hi
        [lname] => fam
        [sname] => saba
        [materialname] => beton
        [datacontractor] => Array
            (
                [1] => 100
                [5] => 200
                [8] => 600
            )

    )[1] => Array
    (
        [sid] => 16
        [fname] => a
        [lname] => a
        [sname] => khoram
        [materialname] => kk
        [datacontractor] => Array
            (
                [2] => 200
                [7] => 777

            )

    )[2] => Array
    (
        [sid] => 15
        [fname] => hi
        [lname] => fam
        [sname] => saba
        [materialname] => beton
        [datacontractor] => Array
            (

                [9] => 400
            )

    ))

A: You set the "datacontractor" => $datacontractor[$id] to finalarray before finish insert all the data to the $datacontractor[$id] -> do that in separate loop.
You code is much more complicated then you actually need.
Consider the following short version:
$array = []; // this is just some of the fields - you can add all of then here
$array[] = array("id"=> 10, "contractorid" => 1,"netweight" => 100);
$array[] = array("id"=> 16, "contractorid" => 2,"netweight" => 200);
$array[] = array("id"=> 16, "contractorid" => 7,"netweight" => 777);
$array[] = array("id"=> 10, "contractorid" => 5,"netweight" => 200);
$array[] = array("id"=> 10, "contractorid" => 8,"netweight" => 600);
$array[] = array("id"=> 15, "contractorid" => 9,"netweight" => 400);

$ans = [];
foreach($array as $e) {
    if (!isset($ans[$e['id']])) { // if never set do first time
        $ans[$e['id']] = array("sid" => $e['id'], "datacontractor" => array($e["contractorid"] => $e["netweight"])); // here you can add all your other fields as fname, lname...
    } else {
        $ans[$e['id']]["datacontractor"][$e["contractorid"]] = $e["netweight"]; // just add the new field as already set
    }
}

Now, $ans will output your desire
Edit:
For having multi contractorid value change to this:
foreach($array as $e) {
    if (!isset($ans[$e['id']])) { // if never set do first time
        $ans[$e['id']] = array("sid" => $e['id'], "datacontractor" => array($e["contractorid"] => [$e["netweight"]])); // notice "contractorid" has array inside (extra "[]" around $e["netweight"])
    } else {
        $ans[$e['id']]["datacontractor"][$e["contractorid"]][] = $e["netweight"]; // append to the contractorid array
    }
}

For re-index $ans do this at the end: $ans = array_values($ans);

A: You can use array_reduce
$data = array_reduce($array, function ($old, $new) {
    if (isset($old[$new['sid']])) {
        $new['datacontractor'] = array_merge($old[$new['sid']]['datacontractor'], [$new['netweight']]);
        $old[$new['sid']] = $new;
    } else {
        $new['datacontractor'] = [$new['netweight']];
    }
    unset($new['netweight']);
    $old[$new['sid']] = $new;
    return $old;
}, []);

$data = array_values($data);
print '
';
print_r($data);
print '
';


text:
Q: GitHub Pages, deploy error 'User cannot be authenticated with the token provided' I was deploying my site via github pages. but today when I try to update the site, github gives an error and cannot deploy. I updated Workflow a few times, but when it didn't work, I deleted it and still nothing changed. The error I get is: 'error pulling image configuration: download failed after attempts=1: unauthorized: unauthenticated: User cannot be authenticated with the token provided.' How can I solve this problem?
My Repo: https://github.com/wraith4081/wafoen/
Error Log: https://github.com/wraith4081/wafoen/runs/7004088921?check_suite_focus=true


text:
Q: how to design an effecient database for multi client and each having thousands of records My Question related to DB design and efficiency. Probably this question have asked before but I cant find any detail info. Come to the point.
Requirement.
I have 500 Customers i.e Schools now some of the schools may have different branches say each school has 3 branches.
each branch has 8 to 10 thousands maximum students. now each student has attendance record almost about 3000 rows maximum.  500 X 3 X 8000 X 3000 = 36000000000 total records have to be searched. I need to design a database that can efficiently handle such a huge records. i mean If I query the DB to find attendance of a student for xyz branch of ABC school
What will be the ways to achive a
please guide me how to achieve this with keep in mind the following factors.
Best Db vendor that give best results.
What will be the design for this and how to make it efficient when concurrent calls will come to db from different schools i.e at same time different schools querying database. let say query is same as describe above.
what design guide line would use to achieve efficiency in terms of query optimization, db designing and optimizations for this type of db. Any Suggestions and links are welcome


text:
Q: How do I check for required scopes in a discord bot user using Python? I am making a discord API wrapper and I finally thought of embarking on commands. As most of you know, discord requires bots to have the application.commands scope for checking whether the bot user has permissions to receive application commands.
I wanted to check if the bot had the setting enabled using Python, but it never seems to work. I have tried many things and even have sifted through the documentation, but I am not able to find a solution. Can anyone help?
My Attempts:

*

*Tried to listen for any codes saying that the scope is not enabled

*Checked the docs for any status codes and handling scopes

Please help!
https://discord.com/developers/docs/interactions/application-commands#authorizing-your-application

A: This is only a workaround, but you could try to make a get request to the commands endpoint
GET /applications/{application.id}/guilds/{guild.id}/commands

If you get a 403 - Forbidden then the bot doesn't have the application.commands scope


text:
Q: Sequence divergence test Could I argue that $\left(1+\frac{1}{n}\right)^{n^2}$ = $e ^n$ therefore the sequence diverges?
I am wondering if it is a legal move

A: The idea is correct, but that's not a proof. On the other hand, you can say that $(\forall n\in\mathbb N):\left(1+\frac1n\right)^n\geqslant2$ and that therefore$$(\forall n\in\mathbb N):\left(1+\frac1n\right)^{n^2}=\left(\left(1+\frac1n\right)^n\right)^n\geqslant2^n.$$ That's enough to prove that your sequence diverges.

A: The equation you have written is not correct. $(1+\frac 1 n)^{n^{2}} =((1+\frac 1 n)^{n})^{n} > c^{n}$ for $n$ sufficiently large  if $1<c<e$ Since $c^{n} \to \infty$ the conclusion follows.

A: $\left(1+\frac{1}{n}\right)^{n^2} \lt e^n$ so that does not quite work
but $e^{n-1} \lt \left(1+\frac{1}{n}\right)^{n^2} \lt e^n$ for $n \gt 1$ and that would be enough if you could prove it

A: Option: Binomial expansion:
$(1+1/n)^{n^2} =$
$ 1+(n^2)(1/n)+....> n.$
Take the limit $n \rightarrow \infty$.

A: In this case, since no indetermination  is generated in the process, you can actually just say that
$$
\lim \left(1+\frac 1n\right)^{n^2} = \left(\lim \left(1+\frac 1n \right)^n\right)^{\lim n}=e^{+\infty} =+\infty.
$$


text:
Q: Asynchronous database search with AJAX, MVC, JQuery Sorry about the odd question wording. In all honesty I'm in right at the deep end here, having to learn a huge amount all at once.
I'm trying to figure out how to perform an asynchronous search on a database using AJAX, but it keeps coming up with a "500 internal server error". I've done some AJAX tutorials but none of them involve the MVC method of web development. I'm a bit lost with what information needs to be sent where, and how.
All I know is that a 500 Server Error means it's happening on the server side rather than the client side, so I presume there's a break in logic at the point where the controller starts to get involved. That's just a newbie guess though.
I'll paste all of what I believe to be the relevant code. For context, the database info is from an 'accounts' table in a mock bank database I've been working with for practice.
Thanks for any help.
Firstly, here's the error information I get when looking at debug info on Chrome

Now here's the code involved.
Javascript/JQuery:
 var $j = jQuery.noConflict();

    var key = 0;

    $j(function () {

        $j("#search_btn").click(function () {
            key = $j("#acc-id-search").val();
            searchAcc();
            return false;
        })
    });

    function searchAcc() {

        var callback = function (data) {

            $j("#account_data_table").empty();
            var htmlArray = [];
            if (data.total > 0) {
                $j.each(data.items, function (i, item) {
                    htmlArray.push("
");
                    htmlArray.push('' + item.account_id + '	');
                    htmlArray.push('' + item.product_id + '	');
                    htmlArray.push('' + item.cust_id + '	');
                    htmlArray.push('' + item.open_date + '	');
                    htmlArray.push('' + item.close_date + '	');
                    htmlArray.push('' + item.last_activity_date + '	');
                    htmlArray.push('' + item.status + '	');
                    htmlArray.push('' + item.open_branch_id + '	');
                    htmlArray.push('' + item.open_emp_id + '	');
                    htmlArray.push('' + item.avail_balance + '	');
                    htmlArray.push('' + item.pending_balance + '	');
                    htmlArray.push("
");
                });
            }
            else {
                htmlArray.push('
No results!
');
            }

            $j("#account_data_table").append(htmlArray.join(''));
            alert("Sucess?");

        };
        alert("Searching for '" + key + "'");
        postData('@Url.Content("~/Accounts/Index")', key, callback, '#account_data_table');
    }

    function postData(url, data, callback, lockObj, dataType, loadingMessage)
    {
        data = data || {};
        dataType = dataType || 'json';
        loadingMessage = loadingMessage || 'Loading...';;
        var isLock = !!lockObj;
        $.ajax({
            url: url,
            data: data,
            method: 'post',
            dataType: dataType,
            cache: false,
            beforeSend: function(){
                alert("About to send");
            },
            success: callback,
            error: function(){
                alert("Failed..!");
            },
            complete: function(){

            }
        });
    }

The controller that '@Url.Content("~/Accounts/Index")' points to:
[HttpPost]
    public NewtonJsonResult Index(int key)
    {
        var _service = new BankEntities();
        var searchCondition = new account() { account_id = key };
        var resultObj = new AjaxDataResult();
        var allitems = _service.All(searchCondition);
        var itemArray = new JArray();
        resultObj.total = allitems.Count();
        JObject temp;
        foreach(var item in allitems)
        {
            temp = new JObject();
            temp["account_id"] = item.account_id;
            temp["product_cd"] = item.product_cd;
            temp["cust_id"] = item.cust_id;
            temp["open_date"] = item.open_date;
            temp["close_date"] = item.close_date;
            temp["last_activity_date"] = item.last_activity_date;
            temp["status"] = item.status;
            temp["open_branch_id"] = item.open_branch_id;
            temp["open_emp_id"] = item.open_emp_id;
            temp["avail_balance"] = item.avail_balance;
            temp["pending_balance"] = item.pending_balance;
            itemArray.Add(temp);

        }
        resultObj.items = itemArray;
        return new NewtonJsonResult(resultObj);
    }

The 'All(searchcondition)' method which is used to find the required items in the table:
public List<account> All(account acc)
    {
        var data = accounts.Where(x => x.status == "ACTIVE");
        if(acc.account_id != 0)
        {
            data = data.Where(x => x.account_id == acc.account_id);
        }
        return data.OrderBy(x => x.account_id).ToList();
    }

A: Special thanks to @nnnnnn whose answer lies in the comments after the initial question:

The method might not be called because you're not setting the right
  request parameters, so no method exists for the request hence the 500
  error. Your current code is trying to include the key value without
  giving it a request parameter name. Try changing key =
  $j("#acc-id-search").val(); to key = { key: $j("#acc-id-search").val()
  };. (The actual request would then end up with a parameter
  key=thesearchvaluehere.)


text:
Q: Subversion: find last logfile entries over entire repo? I've been away for a few months and I'm trying to find out what a contractor has been doing on a project.
My old trunk checkout is up to date, but svn status -u shows that there are later versions. If I run find on the repo, I can see that various revprop files have been changed over the last few months, and they have new version numbers, so something has been going on. The last trunk version was, for the sake of argument, 1000, and the status and find commands show that there are new revs up to 1100. svn log -r shows nothing for any version above 1000.
There are about a dozen branches that he could have been working on, but svn ls and svn cat on the branch files are not showing anything obvious. So, how do I get a log file for the new revisions, without having to check out every branch?

A: If you run svn log on the working copy, you will only get entries relevant to the current subtree you are working on. As you need to look across "every branch", you should perform the query on the top of the repository tree.
Many svn commands allow you to perform the operation directly on the repository (rather than the working copy) by specifying its URL. The symbol ^ is a shortcut for this URL.
So, to view every log entry from 1000 onwards, across every branch, use:
svn log -r 1000:HEAD ^/


text:
Q: indent before theorem/assumption Please see below my try to add an indent before Assumption line.      Please see the packages in the preamble which I used in my actual document. I read that ragged2e kills indentation.
Eventhough I changed \usepackage{tabularx,ragged2e,booktabs,caption} to \usepackage{tabularx}, there is no indent added before Assumption.
\documentclass[letterpaper, 12 pt, conference,onecolumn,draftcls]{ieeeconf}  %%
\IEEEoverridecommandlockouts                              % This command is only
                                                          % needed if you want to
                                                          % use the \thanks command
\overrideIEEEmargins
\usepackage{color}
\usepackage[dvips]{graphicx}
%\usepackage{psfig,subfigure}
\usepackage{epsfig}
\usepackage{graphicx}
%comment below if any problem
%\usepackage[pdftex]{graphicx}
\usepackage{epstopdf}
\usepackage{here}
\usepackage{mathptmx} % assumes new font selection scheme installed
\usepackage{times} % assumes new font selection scheme installed
%\usepackage{lmodern}
\usepackage{bm}
%\usepackage{sansmath}
\usepackage{amssymb}
\usepackage{amsfonts}
%\usepackage{amsthm}
\usepackage{amsmath}
\usepackage{cite}
\usepackage[utf8]{inputenc}
\usepackage{multirow}
\usepackage[T1]{fontenc}
\usepackage{float}
%\usepackage{textcomp}
%\usepackage{txfonts}
\usepackage{subfigure}
\usepackage{setspace}
\usepackage{enumerate}
\usepackage{tabularx,ragged2e,booktabs,caption}
\usepackage[mathscr]{euscript}
\DeclareMathOperator*{\argmax}{arg\,max}
\usepackage{ntheorem}\theoremseparator{.}
\newtheorem{mydef}{Definition}\theoremseparator{.}
\newtheorem{myalgo}{Algorithm}\theoremseparator{.}
\newtheorem{myassum}{Assumption}\theoremseparator{.}
\newtheorem{myprop}{Proposition}\theoremseparator{.}
\newtheorem{mytheo}{Theorem}\theoremseparator{.}
\newtheorem{myproof}{Proof}\theoremseparator{.}
\DeclareMathOperator*{\argmin}{arg\,min}
\newcolumntype{C}[1]{>{\Centering}m{#1}}
\renewcommand\tabularxcolumn[1]{C{#1}}
\begin{document}

\indent\begin{myassum}\label{asum_contro} \rm{The value of $(A,B)$
are known.}
\end{myassum}

\par\begin{myassum}\label{asum_contro} \rm{The value of $(A,B)$ are
known.}
\end{myassum}

\parindent30pt\begin{myassum}\label{asum_contro} \rm{The value of
$(A,B)$ are known.}
\end{myassum}

Please help me add an indent just before Assumption 1. I mean the
assumptions should start as a paragraph.
\end{document}

A: The ntheorem package provides \theoremindent,which has to be used before \ntheorem with \theoremindent\parindent, i.e. without{}` pair.
Using theorem styles would be even better.
\documentclass[letterpaper, 12 pt, conference,onecolumn,draftcls]{IEEEconf}  %%
%\IEEEoverridecommandlockouts                              % This command is only
                                                          % needed if you want to
                                                          % use the \thanks command
%\overrideIEEEmargins
\usepackage{color}
\usepackage{graphicx}
%comment below if any problem
%\usepackage[pdftex]{graphicx}
\usepackage{here}
\usepackage{mathptmx} % assumes new font selection scheme installed
\usepackage{times} % assumes new font selection scheme installed
%\usepackage{lmodern}
\usepackage{bm}
%\usepackage{sansmath}
\usepackage{amssymb}
\usepackage{amsfonts}
%\usepackage{amsthm}
\usepackage{amsmath}
\usepackage{cite}
\usepackage[utf8]{inputenc}
\usepackage{multirow}
\usepackage[T1]{fontenc}
\usepackage{float}
%\usepackage{textcomp}
%\usepackage{txfonts}
\usepackage{subfigure}
\usepackage{setspace}
\usepackage{enumerate}
\usepackage{tabularx,ragged2e,booktabs,caption}
\usepackage[mathscr]{euscript}
\DeclareMathOperator*{\argmax}{arg\,max}
\usepackage{ntheorem}\theoremseparator{.}
\newtheorem{mydef}{Definition}\theoremseparator{.}
\newtheorem{myalgo}{Algorithm}\theoremseparator{.}
\theoremindent\parindent
\newtheorem{myassum}{Assumption}\theoremseparator{.}
\newtheorem{myprop}{Proposition}\theoremseparator{.}
\newtheorem{mytheo}{Theorem}\theoremseparator{.}
\newtheorem{myproof}{Proof}\theoremseparator{.}
\DeclareMathOperator*{\argmin}{arg\,min}
\newcolumntype{C}[1]{>{\Centering}m{#1}}
\renewcommand\tabularxcolumn[1]{C{#1}}
\begin{document}

\begin{myassum}\label{asum_contro} \textnormal{The value of $(A,B)$
are known.}
\end{myassum}

\begin{myassum}\label{asum_contro} \textnormal{The value of $(A,B)$ are
known.}
\end{myassum}

\begin{myassum}\label{asum_contro} \textnormal{The value of
$(A,B)$ are known.}
\end{myassum}

Please help me add an indent just before Assumption 1. I mean the
assumptions should start as a paragraph.
\end{document}


text:
Q: Django-ViewFlow: How to add CRUD views to flow I've recently come across the Viewflow library for Django which I appears to be a very powerful tool for creating complex workflows.
My app is a simple ticketing system were the workflow is started by creating a Ticket, then a user should be able to create zero or more WorkLog's associated with the ticket via a CRUD page(s), similar to the standard Django admin change_list/detail.
What should the template for the list view look like? I would like to have the UI integrated into the library's frontend.
The flow clearly utilises the following views:
1) CreateView for Ticket
2a) ListView of WorkLog's, template has controls 'back', 'add' (goes to step 2b), 'done' (goes to step 3).
2b) CreateView for WorkLog
3) End
Code:
models.py:
class TicketProcess(Process):
    title = models.CharField(max_length=100)
    category = models.CharField(max_length=150)
    description = models.TextField(max_length=150)
    planned = models.BooleanField()

    worklogs = models.ForeignKey('WorkLog', null=True)

class WorkLog(models.Model):
    ref = models.CharField(max_length=32)
    description = models.TextField(max_length=150)

views.py:
class WorkLogListView(FlowListMixin, ListView):

    model = WorkLog

class WorkLogCreateView(FlowMixin, CreateView):

    model = WorkLog
    fields = '__all__'

flows.py:
from .views import WorkLogCreateView
from .models import TicketProcess

@frontend.register
class TicketFlow(Flow):
    process_class = TicketProcess

    start = (
        flow.Start(
            CreateProcessView,
            fields = ['title', 'category', 'description', 'planned']
        ).Permission(
            auto_create=True
        ).Next(this.resolution)
    )

    add_worklog = (
        flow.View(
            WorkLogListView
        ).Permission(
            auto_create=True
        ).Next(this.end)
    )

    end = flow.End()

A: You can handle that in a different view, or in the same view, just don't call activation.done on a worklog adding request. You can do it by checking what button was pressed in the request.POST data.
@flow.flow_view
def worklog_view(request):
    request.activation.prepare(request.POST or None, user=request.user)
    if '_logitem' in request.POST:
         WorkLog.objects.create(...)
    elif request.POST:
        activation.done()
        request.activation.done()
        return redirect(get_next_task_url(request, request.activation.process))
    return render(request, 'sometemplate.html', {'activation': request.activation})


text:
Q: PowerShell: Почему не работает msg на несколько компов в условии? Подскажите, пожалуйста, в чем проблема?
Написал простейший скрипт на PS, который пингует сайт, в случае неполучения ответа перезагружает сетевой адаптер и отправляет на компы из списка с помощью msg сообщение. Но, почему-то отдельная функция, рассылающая сообщения, при вызове нормально работает, а при вызове в условии выдает ошибку:
Ошибка 1722 при получении имени сеанса
C:\Users\username\Desktop\PS\CheckInternet.ps1:22 знак:6
+      msg $Session /Server:$Recepient $Message
+      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (Ошибка 1722 при получении имени сеанса:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

Сам код:
$Site = "ya.ru"
$ListRecepients = Get-Content "C:\Scripts\recepients.txt"
$Session = "*"
$Message = "Доступ в интернет отсутствует. Начинаю перезагрузку сетевого адаптера"

function PingSite {
if ((Test-Connection -CN $Site -Count 1 -BufferSize 16 -Quiet) -match 'True')
    {
     write-host -ForegroundColor green Done
     }
else
    {
     write-host -ForegroundColor red Undone
     WTF
     Restart-NetAdapter -Name "Ethernet"
     }
}

function WTF {
ForEach ($Recepient in $ListRecepients)
    {
     msg $Session /Server:$Recepient $Message
     }
}

Причем, погуглив, даже поправил в реестре ключик AllowRPC, однако результат тот же.


text:
Q: Relação um para muitos entre entidades Tenho o seguinte esquema de base de dados:

Neste esquema pretende-se o seguinte:
1 user pode ter várias teams e uma team pode ter até dois utilizadores (assumi que é uma relação de muitos para muitos e depois valido se uma equipa tem ou não só dois utilizadores)
1 team pode ter vários jogos e um jogo apenas tem um home_team (team) e uma away_team (team) aqui assumi que terá então duas relações 1 para muitos (1 team tem vários jogos e um jogo apenas tem uma away_team e uma home_team).
A minha dúvida é como devo fazer as relações deles nos modelos, para, por exemplo, conseguir através de um utilizador obter todos os jogos dele, tanto away_team como home_team.

A: Você pode definir seus modelos assim:
<?php

// Model User
class User extends Authenticatable
{
    //  ....

    public function teams()
    {
        return $this->belongsToMany(Team::class, 'teams_users', 'user_uuid', 'team_uuid');
    }
}

// Model team
// php artisan make:model Team
class Team extends Model
{
    public function users()
    {
        return $this->belongsToMany(User::class, 'teams_users', 'team_uuid', 'user_uuid');
    }

    public function homeTeamGames()
    {
        return $this->hasMany(Game::class, 'games', 'home_team_uuid');
    }

    public function awayTeamGames()
    {
        return $this->hasMany(Game::class, 'games', 'away_team_uuid');
    }
}

// Model game
// php artisan make:model Game
class Game extends Model
{
    public function homeTeam()
    {
        return $this->belongsTo(Team::class, 'teams', 'uuid');
    }

    public function awayTeam()
    {
        return $this->belongsTo(Team::class, 'teams', 'uuid');
    }
}

Exemplo query capturando usuarios + times
$users = User::with(['teams'])->get();


text:
Q: Node.js is single threaded does this mean we cannot run multiple Node.js in different threads? I've read in an article that Node.js is single threaded. The question is what if we run multiple Node.js files in different ports? Do they have their own thread or all of them will be under the main Node.js thread?
Could someone shed someone light on the subject I'm now on the dark side.

A:
The question is what if we run multiple Node.js files in different ports? Do they have their own thread or all of them will be under the main Node.js thread?

From your question, it sounds to me like you are actually starting up multiple processes of Node.js.  In those cases, they will work like any other set of multiple processes on your system, and your OS will attempt to balance the load out between all the cores and/or CPUs.

I've read in an article that Node.js is single threaded.

This is a bit more complicated.  While the V8 JavaScript engine Node.js uses does run your JavaScript in a single thread, much of the Node.js libraries call out to native code which can use as many threads as it likes.  These internals of Node.js use a thread pool and multithreading for disk and network IO, among other tasks.
The applications Node.js really shines in are those that are typically IO bound.  In these cases, you get much of the benefit of multithreading without having to write any code for it.  For example, when you make multiple requests to disk Node.js will use multiple threads to handle the buffering and management of that data while not blocking your main JavaScript thread.
In many of my applications, I have found that I can fully utilize an 8-core box without writing any code to fire up child processes.  Node's internal multithreading does all the work for me.  Your mileage will vary from application to application.
I've written a different explanation on a past question you might find helpful:  https://stackoverflow.com/a/19324665/362536

A: http://nodejs.org/api/cluster.html
A single instance of Node runs in a single thread. To take advantage of multi-core systems the user will sometimes want to launch a cluster of Node processes to handle the load.
The cluster module allows you to easily create child processes that all share server ports.
var cluster = require('cluster');
var http = require('http');
var numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
  // Fork workers.
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', function(worker, code, signal) {
    console.log('worker ' + worker.process.pid + ' died');
  });
} else {
  // Workers can share any TCP connection
  // In this case its a HTTP server
  http.createServer(function(req, res) {
    res.writeHead(200);
    res.end("hello world\n");
  }).listen(8000);
}

Which means you have to architect yourself, so if you want to listen to different port in different threads, either use cluster or child_process.


text:
Q: Opening files in tabs in Macvim I am trying to learn MacVim with the Janus build. I've done the Vim tutorial and now I want to dive in and create some simple websites. My first project is a site that will convert roman numerals to arabic. But I can't seem to do the simplest thing - create new files in seperate tabs in one window for html, css, and js - using MacVim. I can create blank files from the terminal and then open the finder and drag these files to an open MacVim window and achieve my goal but it seems like a very convoluted approach. What I want to do is launch MacVim and create my blank html file in the open window and then create a blank css file in an adjacent tab and then create a blank js file in a third adjacent tab and then get to work on them. But when I use the command line in MacVim to create a new file (:!mvim roman.html), I get a new window. So I end up with a series of windows instead of a series of tabs. I googled around and it seems like others have had this problem. Their solution is to modify .bashrc or .bash_profie with an alias (MacVim Open File In Existing Window), but when I tried this and attempted to open a file in MacVim, I got a file filled with garbage, not an empty file. I'm also trying to make sense of NERDTRee. Maybe there is a simple solution there but I am just starting to explore it. Any guidance would be appreciated. Thanks.

A: You didn't ask for that much but here we go…

*

*Drop Janus as soon as you can. This piece of shit gives you a false sense of comfort while actively preventing you from learning how to use Vim and making it a lot harder than necessary to customize it to your liking.

*Vim's tabs are not like tabs in other editors: they are not and can't be 1-to-1 proxies for files. In Vim, a file is loaded in a "buffer" and that buffer may or may not be displayed in zero or more "windows", in zero or more "tabs". This particularity will probably bite you one of these days so you'd better get used to deal with buffers.

*In Vim, creating a new file works the same as in any editor: you edit a new empty file and, when you are done, you write it to disk.
:e[dit] file.html
(editing)
:w[rite]

Use :sp[lit] file.js to edit file.js in a new horizontally window.
Use :vs[plit] file.html to edit file.html in a new vertical window.
Use :tabe[dit] file.css to edit file.css in a new tab.
If you want to postpone the decision of the filename, :enew, :new, :vnew and :tabnew create empty buffers in place, in an horizontal window, in a vertical one and a tab.
You don't really need to create those files from outside of Vim.

*From the Finder, the simplest way to edit a file in MacVim is to right-click on it and choose "Edit in MacVim". Same for three files.
There is a drop menu, somewhere in MacVim's Preferences window, that lets you define the default behavior when MacVim is launched by other programs. Try it.
Since you seem to have installed the mvim script, editing a file in the MacVim GUI is done with $ mvim filename and editing the same file directly in your shell is done with $ mvim -v filename.
You can also open multiples files (even if they don't exist) in their own tabs from your shell:
$ mvim -p file1 file2 file3

*Your command, :!mvim filename, does exactly what it's supposed to do: it launches a new MacVim instance.

*Vim already comes with a file explorer that does a lot more than NERDTree called Netrw. See :help netrw.

*Did I tell you that you shouldn't use tabs if you don't have a solid understanding of what they are and what they do?

A: I think the command you want is :tabe something.html.  That creates a new tab in the current window with the file something.html in it, and will create a new file if that doesn't exist.  (Technically it won't create the new file until you save it).
If you like using tabs, it's probably worth your time to read :help tab-page-commands.

A: Command + T
Creates a new tab in MacVim.


text:
Q: Isotropy irreducible forms of a manifold Let $ M $ be a compact connected manifold. Suppose that
$$
M=G_1/K_1
$$
is isotropy irreducible
and
$$
M=G_2/K_2
$$
is also isotropy irreducible. Here $ G_1,G_2 $ are compact connected Lie groups and $ K_1,K_2 $ are subgroups. Must it be the case that $ G_1=G_2 $ or is it possible to have two different isotropy irreducible forms of a smooth manifold $ M $ in this sense?
For example, $ S^5=SO_6/SO_5 $ is isotropy irreducible, but $ S^5=SU_3/SU_2 $ is not isotropy irreducible. And I would imagine that the round $ S^5=SO_6/SO_5 $ is the only isotropy irreducible "form" of $ S^5 $ in this sense.

A: Yes it is possible to have different forms.
An example of this form is the natural metric on
$$
S^6 \cong G_2/SU_3
$$
versus the round metric on
$$
S^6 \cong SO_7/SO_6
$$
these are both isotropy irreducible. Note that compact $ G_2 $ is contained in $ SO_7 $ as the subgroup of automorphisms of an octonion algebra and moreover this is the minimal irrep of $ G_2 $. Also $ G_2\cap SO_6=SU_3 $ as subgroups of $ SO_7 $. Here we mean the natural $ SU_3 $ subgroup of $ SO_6(\mathbb{R}) $.


text:
Q: twitter bootstrap search box and buttons allignment "google like" I am trying to use twitter bootstrap for my new blog project, and I am trying to get the search box to work. To this end, I am using the following code:

        <form class="well form-search">
            <input type="text" class="input-xxlarge search-query">
            <button type="submit" class="btn btn-primary">Search</button>
        </form>

However, what this does is layout the "search button" next to the search box which is not what I'd like. I'd want it looking similar the google landing page, with 2 buttons on the bottom of the box and aligned "centre" to the box. I tried many different options (like a separate div), but I am not able to achieve this.
Secondly, as in the google landing page, I'd want to offset rows, to align it(the box and the two buttons) in the center of the page if possible. Again, I am struggling to figure out how to offset rows (but I am able to offset columns).
I'd appreciate any guidance on this. Thanks for your time.

A: Twitter Bootstrap only applies styling to your HTML via their classes. You can style your content using your own CSS too. I haven't tested the solution below, so don't expect it to work right out the box (although, if it does, do let me know). I have commented extensively to give you an idea of what I'm trying to achieve with every step.
div > div:only-child > form:only-child > button[type="submit"] {
  /* clear any floating implemented by the Twitter Bootstrap framework; you may
     want to use the legacy clearfix method to make this work on all browsers */
  clear: both;

  /* redeclare the button as a block element */
  display: block;

  /* set a width (less than the width of its container; in this case, form).
     this would help with centering the button */
  width: 45%;

  /* center the button. You can use a button group if you have more buttons */
  margin: 0 auto;

  /* center the text in the button, assuming it's not already centered by twitter */
  text-align: center;
}

p.s: apologies for the ridiculous selector. You didn't have explicit class names or id tags that weren't Twitter's.


text:
Q: Getting tf idf when documents are defined by two columns I'm doing text analysis using tidytext. I am trying to calculate the tf-idf for a corpus. The standard way to do this is:
book_words <- book_words %>%
   bind_tf_idf(word, book, n)

However, in my case, the 'document' is not defined by a single column (like book). Is it possible to call bind_tf_idf where the document is defined by two columns (for example, book and chapter)?

A: Why not concatenate both columns? E.g.
library(tidyverse)
library(tidytext)
library(janeaustenr)
book_words <- austen_books() %>%
  unnest_tokens(word, text) %>%
  count(book, word, sort = TRUE) %>%
  ungroup()
book_words$chapter <- sample(1:10, nrow(book_words), T)
book_words %>%
  unite("book_chapter", book, chapter) %>%
  bind_tf_idf(word, book_chapter, n) %>% print %>%
  separate(book_chapter, c("book", "chapter"), sep="_") %>%
  arrange(desc(tf_idf))


text:
Q: Remotely access a qsub compute node Using qsub, I have submitted a long running job that spawns two Java processes; one of which is listening for Java RMI calls on some port. Say qsub assigns that job to node "compute-0-37". How can I communicate with compute-0-37 remotely (on a node other than the head node) over an RPC call (Java RMI in this case)?
I have not been able to find this from reading existing docs (e.g. http://gridscheduler.sourceforge.net/htmlman/htmlman1/qsub.html, http://docs.adaptivecomputing.com/torque/4-0-2/Content/topics/commands/qsub.htm). As far as I can tell, the only way to access a compute node directly is from the head node, but it seems like that would be pretty restrictive for use cases like mine.

A: The reason you can't find any documentation in the resource management software documentation is because this isn't a resource management software question. Accessing worker nodes is simply that: a function of network access. Whether you're hoping to do RPC communication between the nodes themselves, or with some machine on a different subnet, you should be able to do so (provided that site policies and the system administator/s allow it).


text:
Q: php find dom element by containing text and adding an attribute i have following html code

      <? MPage::PlaceHolder("scipts") ?>

             <? MPage::PlaceHolder("menu") ?>

             <? MPage::PlaceHolder("content") ?>
             <? MPage::PlaceHolder("footer") ?>

what i wan't is to find all the element containing  MPage::PlaceHolder(...) and add an attribute called mpage-placeholder="..." in PHP, before outputting it
so:

   <? MPage::PlaceHolder("menu") ?>

becomes:

   <? MPage::PlaceHolder("menu") ?>

is this even possible??
cheers
c_bb

A: Using PHP, you should make it a DOMDocument and then use getElementsByTagName(). This returns a DOMNodeList, which is basically an array of DOMElement objects in this case. Now you can traverse the elements that contain that value. Using a wildcard ('*') in the getElements method returns a traversable DOMNodeList from which then the values of alle Nodes can be examined. Something like this should do the trick:
$input ='...'; // HTML contents in string

$dom = new DOMDocument();
$dom->loadHTML($input); // Convert HTML String into DOMDocument

$allNodes = $dom->getElementsByTagName('*'); // Get all DOMElements
foreach($allNodes as $node)
    {
    // If the node contains the value you want
    if (strpos($node->nodeValue, "MPage::PlaceHolder") !== false)
    {
        // Give the node an attribute
        $node->setAttribute("mpage-placeholder", "menu");
        // If need be you can give the node's parent the attribute:
        $node->parentNode->setAttribute("mpage-placeholder", "menu");
    }

}
$xmlDoc->formatOutput = true;
$xmlDoc = $xmlDoc->saveHTML(); // Write DOMDocument back into a String

A: You could start an output buffer (with ob_start) at the begining of the script in order to capture the outputted text.
When MPage::PlaceHolder() function is called you may obtain the outputted text (with ob_get_contents, for example) and then analyze the outputted HTML in order to find the changes you want to do.
If any changes have been made you may use ob_clean to clean the buffer (but not delete it) and then print the modified HTML.
I don't consider this very efficient, but it may work for you.
EDIT:
Another idea is to perform whatever operations (other than adding HTML attributes) the funciton does, plus adding some special tag: for example:

Thus at the end of the code you may search all these tags and perform the search for the parent node. This search you can become very simple if you put the PHP right after the tag is open.
EDIT 2
Just for fun, this regular expresion finds the last unclosed html tag:
preg_match("/.*<((?![\\/?])[^>]+[^\\/])>(?!.*<\\/\\1>).*?$/s", $html, ...)

It can be used with the first method I proposed.


text:
Q: Static classes and global variables I'm using FuelPHP 1.6.1 with a lot of static classes, this seems to work out quite nice. Now I have a Menu generator that loads some data
$menu = Menu::generate();

It loads some data and stores this in static::$data
How would I go for another class to load just that? I'm getting null results, probably because I'm doing something wrong, but I dont see what I'm doing wrong at the moment.
Also, yes, the Menu::$data  is declared public static $data
Any tips?
Using FuelPHP's Session::set() does the job, but only after a reload, I need the data straight away in other classes, and loading it again results into double queries (which I dont want)
PHP's $_SESSION is not used, nor will be used.

A: Turns out, in my way of showing views and menu, menu::generate() came after the other classes that needed it, put it at the start and using FuelPHP's Session::set() did the job


text:
Q: generate all possible subset from a character array in MATLAB I need to generate all possible subset from a character array in MATLAB with reduced execution time.
For example:
input='ABCA';
output ='A',
'B',
'C',
'AB',
'BC',
'CA',
'ABC',
'BCA',
'ABCA'

A: You can find all these subsets using straight-forward loops. I don't know if it is worth-while vectorizing these, as any vectorization will require large intermediate arrays.
With a random input of 500 characters, and maxLen at 20, I got 4207817 unique substrings. It took my computer (with MATLAB R2017a) 12 seconds to find these. Whether that is fast enough or not is up to you, but I would not bother further optimizing this.
input = 'ABCA';
maxLen = 4;

subsets = {};
for len = 1:maxLen
   subs = cell(1,numel(input)-len+1);
   for start = 1:numel(subs)
      subs{start} = input(start:start+len-1);
   end
   subs = unique(subs);
   subsets = [subsets,subs];
end
disp(subsets)

Output:
'A'    'B'    'C'    'AB'    'BC'    'CA'    'ABC'    'BCA'    'ABCA'

If it is important to preserve the order of the substrings, then add the 'stable' argument to the unique call:
   subs = unique(subs,'stable');

For example, for input = 'AFCB';, the output without 'stable' is:
'A'    'B'    'C'    'F'    'AF'    'CB'    'FC'    'AFC'    'FCB'    'AFCB'

and with 'stable' it is:
'A'    'F'    'C'    'B'    'AF'    'FC'    'CB'    'AFC'    'FCB'    'AFCB'


text:
Q: Compactness of two equivalent metric spaces Let $X$ be a non-empty set. Suppose that $d_1$ and $d_2$ are two possibly different metrics on $X$. Let $\tau_i$ denote the topology generated by the metric $d_i$ ($i\in\{1,2\}$).
The following are known:

*

*$\tau_1=\tau_2\equiv\tau$;

*$(X,d_1)$ is a totally bounded metric space;

*$(X,d_2)$ is a complete metric space.

Question: Is the topological space $(X,\tau)$ compact?
This is an extra twist added to the classical result that any totally bounded and complete metric space is compact. The twist is that one is given two different metric spaces, one being totally bounded and the other complete, even though they generate the same topology. I wonder whether this twist preserves the compactness of the common topology.

In other words:

*

*Any totally bounded and complete metric space is compact, but...

*...is any totally bounded and complete$\textit{ly metrizable}$ metric space compact?

A: It's not correct. Take $X_1 = (0,1)$ and $X_2 = \mathbb R$ (identified with $X_1$ via some homeomorphism). Then with the standard metric on both $X_i$, $X_1$ is totally bounded and $X_2$ is complete. Both are not compact.

A: Update: NOT true.
Counterexample: Consider $\mathbb N$ with the discrete topology, which is clearly not compact. Let $d_1$ be the discrete metric, which is complete, and $d_2(n,m)\equiv|1/n-1/m|$. Now, $d_2$ can be shown to be a totally bounded metric. It is also not difficult to check that both $d_1$ and $d_2$ generate the discrete topology on $\mathbb N$.


text:
Q: Is KVO on AVPlayerItem.loadedTimeRanges possible? Apples documentation alludes to it, but how do you set up key-value observation for the loadedTimeRanges property of AVPlayerItem? That property is an NSArray that doesn't change, so you can't just use playerItem addObserver:self forKeyPath:@"loadedTimeRanges ...
Or is there another way to get notifications or updates whenever this changes?

A: Actually, I'm using KVO for loadedTimeRanges without any trouble.  Maybe you're just not setting the right options?  The following is a very slight modification of some of the code in Apple's AVPlayerDemo, and it's working quite nicely for me.
//somewhere near the top of the file
NSString * const kLoadedTimeRangesKey   = @"loadedTimeRanges";
static void *AudioControllerBufferingObservationContext = &AudioControllerBufferingObservationContext;

- (void)someFunction
{
    // ...

    //somewhere after somePlayerItem has been initialized
    [somePlayerItem addObserver:self
                       forKeyPath:kLoadedTimeRangesKey
                          options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew
                          context:AudioControllerBufferingObservationContext];

    // ...
}

- (void)observeValueForKeyPath:(NSString*) path
                  ofObject:(id)object
                    change:(NSDictionary*)change
                   context:(void*)context
{
    if (context == AudioControllerBufferingObservationContext)
    {
        NSLog(@"Buffering status: %@", [object loadedTimeRanges]);
    }
}

A: Right. loadedTimeRanges doesn't change but the objects inside of it change. You could setup a timer to run every second (or so) and inspect the values inside of loadedTimeRanges. Then you'll see the changes you are looking for.
dispatch_queue_t queue = dispatch_queue_create("playerQueue", NULL);

[player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1)
                                          queue:queue
                                     usingBlock:^(CMTime time) {
                                         for (NSValue *time in player.currentItem.loadedTimeRanges) {
                                             CMTimeRange range;
                                             [time getValue:&range];
                                             NSLog(@"loadedTimeRanges: %f, %f", CMTimeGetSeconds(range.start), CMTimeGetSeconds(range.duration));
                                         }
                                     }];

A: Update to Swift 4.0 and later:
loadedTimeRangesObserver = player.observe(\AVPlayer.currentItem?.loadedTimeRanges, options: [.new, .initial]) { [unowned self] (player, change) in
    DispatchQueue.main.async {
        guard let ranges = change.newValue as? [CMTimeRange] else { return }
        // update UI
    }
}


text:
Q: A program in C to compare last digit of UPC code with a calculated value and check if its valid or not? So i made this code in c on visual studio, basically it takes as an input the UPC code of a product ( 12 integers) The last integer is like the check digit, which is related to the previous 11 digits by a formula. So the code basically checks if the UPC code is valid or not, by using the formula to calculate the check digit in the program itself and then compare it to the inputted value of the last digit :
Problem is, in visual studio the command prompt only takes the input and hangs,, as in it doesnt give any input and if i press enter the cursor blinks and just moves to a new line...
Edit :
The input I gave it is :
031564532525
Written exactly like that with no spaces

int main() {
    // initialize the 11 digits of the UPC individually //
    int d, i1, i2, i3, i4, i5, j1, j2, j3, j4, j5, first_sum, second_sum, total ;
    int end_dig;
    // take input from user of UPC digits //
    printf("Enter the UPC code:\n");
    scanf_s("%d%d%d%d%d%d%d%d%d%d%d%d", &d, &i1, &i2, &i3, &i4, &i5, &j1, &j2, &j3, &j4, &j5, &end_dig);

    // caclulate what the check digit SHOULD be according to the previous digits //
    int last_digit;
    first_sum = d + i2 + i4 + j1 + j3 + j5;
    second_sum = i1 + i3 + i5 + j2 + j4;
    total = (3 * first_sum) + second_sum;
    last_digit = 9 - ((total - 1) % 10);

    // compare calculated value of check digit with input value, to see wether its valid or not. //
    if (end_dig == last_digit) {
        printf("VALID\n");
    }
    else {
        printf("NOT VALID\n");
    }

    return 0;
    system("pause");

}

A: The %d format specifier reads not just a single number but a sequence of decimal digits.  So the number you enter is being consumed by the first instance of %d, resulting it the program waiting for more input to satisfy the remaining format specifiers.
You need to split the digits with spaces so you can read each individually:
0 3 1 5 6 4 5 3 2 5 2 5

If you don't want to do that, you need to instead read in a single string, then inspect each digit in the string.


text:
Q: Что означает typename = void? C++ Есть шаблон:
template<typename T, typename = void>

Что означает 2 параметр? Если typename U = void я могу понять, как тип U, который по умолчанию равен void, то как понять просто typename = void?


text:
Q: Getting the "videoId" from a YouTube video using YouTubeV3-API As the title suggests I am trying to get the "videoId" from a YouTube video.
Currently this is my code, it can be replicated.
import requests

channel_id = "UCfjTZZ3iqy24oSg-bmi2waw"
api_key = ""

api_url = f"https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={channel_id}&maxResults=1&order=date&type=video&key={api_key}"

request = requests.get(api_url).text

print(request)

When doing this method it returns me this:
result from requests.get(api_url).text
If I were to do this

print(request["videoId"])

It would return me this

TypeError: string indices must be integers, not 'str'

Am I just doing it wrong? Even if I try requesting a higher key it returns the same error message.

A: You need to parse the received JSON and to precise the path of the entry you are looking for, see the code below:
import requests, json

channel_id = "UCfjTZZ3iqy24oSg-bmi2waw"
api_key = ""

api_url = f"https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={channel_id}&maxResults=1&order=date&type=video&key={api_key}"

request = json.loads(requests.get(api_url).text)

print(request["items"][0]["id"]["videoId"])


text:
Q: Hide everything else and only show one div There are multiple items in a div. Each item has a button and info div. When clicking on title in any div, I want to slide up or fade out everything, want to display only the info of that div in kind of lightbox style.
Here's what I'm trying and it does not work. It slides up everything on click, but does not show the info.
HTML:

Info for box 1

Info for box 2

CSS:
.wrap{
    width: 500px;
    background: yellow;
    padding: 20px;
}

.box{
    margin-bottom: 20px;
}

.info{
    display: none;
}

.button{
    width: 20px;
    height: 20px;
    background: green;
}

jQuery:
$('.wrap').on('click','.button',function(){

    $('.inner').slideUp(400);
    $(this).closest('.info').slideDown(400);

});

Demo:
http://jsfiddle.net/a7wwz/

A: Or try this
$('.wrap').on('click','.button',function(){
    $('.inner>div>div').slideUp(400);
    $(this).next('.info').slideDown(400);
});

http://jsfiddle.net/a7wwz/4/
Your original version did not work because you use .slideup() on a container whose element you want to have visible afterwards. In my version I simply slideup only the divs of the lowest level inside the container .inner.
And, of course, closest() looks upwards for the closest parent. What you really meant was next().

A: Try
$('.wrap').on('click','.button',function(){

    var $info = $(this).next('.info').stop(true, true).slideDown(400);
    $('.info').not($info).stop(true, true).slideUp();

});

Demo: Fiddle

A: How about this:
$('.wrap').on('click', '.button', function () {
   $('.inner *').not($(this).parent()).slideUp(400);
   $(this).next().slideDown(400);
});

FIDDLE


text:
Q: how to properly align pipe in ul li elements with backgrounf image

/* I have the following CSS. */

.top-header-one {
  background: url('https://i.postimg.cc/cCBxMXSw/Journey-touch-off.png') no-repeat;
  height: 26px;
  width: 96px;
  display: inline-block;
}

.top-header-one:hover {
  background: url('https://i.postimg.cc/cCBxMXSw/Journey-touch-off.png') no-repeat;
}

.top-header-two {
  background: url('https://i.postimg.cc/cCBxMXSw/Journey-touch-off.png') no-repeat;
  height: 26px;
  width: 96px;
  display: inline-block;
}

.top-header-two:hover {
  background: url('https://i.postimg.cc/cCBxMXSw/Journey-touch-off.png') no-repeat;
}

.top-header-three {
  background: url('https://i.postimg.cc/cCBxMXSw/Journey-touch-off.png') no-repeat;
  height: 26px;
  width: 96px;
  display: inline-block;
}

.top-header-three:hover {
  background: url('https://i.postimg.cc/cCBxMXSw/Journey-touch-off.png') no-repeat;
}

.top-custom-link ul li {
  display: inline-block;
}

.top-custom-link ul li:not(:first-child):before {
  content: "|";
}

I am not able to align pipes with background images.
Here is the jsfiddle https://jsfiddle.net/L7ob2zfp/

A: I think you could try this:
add position: relative to the li, and then add 3 properties for pseudoclass
 position: absolute;
 top: 50%;
 transform: translateY(-50%);

Snippet:
. . .
. . .

.top-custom-link ul li {
  display: inline-block;
  position: relative;
}

.top-custom-link ul li:not(:first-child):before {
  content: "|";
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

Hope this helps :)

A: Adding vertical-align: middle; to .top-header-one, .top-header-two and .top-header-three will align the pipe with the background image. Besides, you may remove the unnecessary spaces in between the . See the code snippets comment for change details.

.top-header-one {
  background: url('https://i.postimg.cc/cCBxMXSw/Journey-touch-off.png') no-repeat;
  height: 26px;
  width: 96px;
  display: inline-block;
  vertical-align: middle; /* Add vertical-align */
}

.top-header-one:hover {
  background: url('https://i.postimg.cc/cCBxMXSw/Journey-touch-off.png') no-repeat;
}

.top-header-two {
  background: url('https://i.postimg.cc/cCBxMXSw/Journey-touch-off.png') no-repeat;
  height: 26px;
  width: 96px;
  display: inline-block;
  vertical-align: middle; /* Add vertical-align */
}

.top-header-two:hover {
  background: url('https://i.postimg.cc/cCBxMXSw/Journey-touch-off.png') no-repeat;
}

.top-header-three {
  background: url('https://i.postimg.cc/cCBxMXSw/Journey-touch-off.png') no-repeat;
  height: 26px;
  width: 96px;
  display: inline-block;
  vertical-align: middle;  /* Add vertical-align */
}

.top-header-three:hover {
  background: url('https://i.postimg.cc/cCBxMXSw/Journey-touch-off.png') no-repeat;
}

.top-custom-link ul li {
  display: inline-block;
}

.top-custom-link ul li:not(:first-child):before {
  content: "|";
}