text:
Q: Why can we detect single photons, but not single gravitons? Everybody can buy a single photon counter. Why are there no single graviton counters?
Obviously, graviton sources are rare. But why are graviton detectors so hard to make? Is it just because the typical gravitons (say, from black hole mergers) have such low frequency, and thus very low energy?
In other words, is it a noise issue, in the sense that any graviton detector has intrinsic difficulties to distinguish a signal from noise, because the signal has such a low level?
Or is there still another reason?

A: The best reference on this topic that I'm aware of is Rothman and Boughn, "Can Gravitons Be Detected?," http://arxiv.org/abs/gr-qc/0601043 . They argue that the cross-section for a graviton to interact with pretty much any target is on the order of the square of the Planck length. This is not obvious, and they refer to a lot of previous authors who came up with other estimates, and claim that with hindsight those estimates were wrong. So basically we can't detect single gravitons because the Planck length is very small.

A: Look at the difference in coupling constants between electromagnetism and gravity:

The coupling constants are what define the ballpark of the probability calculations in quantum mechanics. Supposing that gravitons exist ( it is an effective, not decisive, quantization of gravity that is used) the probability of their interacting with the atoms and molecules of a detector is smaller than for photons at least by $10^{35}$ times.
Since Avogadro's number( molecules in a mole of matter) is of order $10^{23}$ you can imagine how big a detector would have to be in order for a graviton to interact with one of its molecules. Then there is the probability of the interaction being non trivial in energy so some photons are produced in order to see that an interaction happened.

A: Photons interact readily with individual charged particles and have a relatively high energy compared with the energy required to trigger a chain of events that leads to a count in a detector.
Gravitons don't interact with individual particles directly, they have the effect of warping spacetime. The effect an individual graviton is expected to have is incredibly tiny compared with the impact of a photon on an atom, so a vastly more-sensitive detector would be required.

A: It is very important to differentiate between virtual gravitons (in QFT calculations of interactions) and real gravitons (GW quanta). Now there is no consensus on this site whether gravitons are the quanta of GWs or not.
https://physics.stackexchange.com/a/215180/132371
There are two ways we can detect gravitons, either build detectors as you suggest, or create them at the LHC.
Now detecting single gravitons is very unlikely, because gravitons interact with matter very very weakly.
$$\alpha_\mathrm{G} = \frac{G m_\mathrm{e}^2}{\hbar c} = \left( \frac{m_\mathrm{e}}{m_\mathrm{P}} \right)^2 \approx 1.7518 \times 10^{-45} $$
The gravitational coupling constant characterizes the gravitatonal attraction between elementary particles.
$$\alpha_\mathrm{G}$$ is 42 orders of magnitude smaller then $$\alpha$$
Now if you use the energies at LHC, you will see that it is similarly orders of magnitude less likely to produce a single graviton at the LHC then a single photon.
https://en.wikipedia.org/wiki/Gravitational_coupling_constant
Thus, the correct answer to your question is that in the foreseeable future we will not be able to build detectors that can detect single gravitons nor will we be able to produce them at the LHC.
You are correct, it is the cross section.
Gravitons have a much lower cross section then photons to interact with matter.
https://arxiv.org/pdf/gr-qc/0607045.pdf


text:
Q: Adding onto a linked list I have a .c and a .h file. All the linked list methods are supplied by my professor. I wanted to test the linked list out by creating a main function and trying to add to the linked list and then displaying the linked list. How would I do that in the main function? Here is what I have:
int main() {
    linkedList* test = createLinkedList();
    addToLinkedList(test, value);
    displayLinkedList(test);
}

I also tried this code:
int main() {
    linkedList* hello = createLinkedList();
    struct tnode* test = "hello";
    addToLinkedList(hello, test);
    return (0);
}

However, what I have doesn't work.
Here is the code the prof gave us:
TESTlinkedlist.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "TESTlinkedList.h"

/* Creates a linked list */
linkedList* createLinkedList() {
    return NULL;
}

/* Displays the linked list */
void displayLinkedList(linkedList* ll) {
    linkedList* p = ll;

    printf("[");
    while (p != NULL) {
        printf(" % d " , p -> node -> c);
        p = p -> next;
    }
    printf("]\n");
}

/* Adds a tree node to the linked list */
void addToLinkedList(linkedList** ll, tnode* val) {
    linkedList* nn = (linkedList*)malloc(sizeof(linkedList));
    nn -> node = val;
    nn -> next = NULL;

    linkedList* p = *ll;
    if (p == NULL) {
        p = nn;
    } else {
        while (p -> next != NULL) {
            p = p -> next;
        }
        p -> next = nn;
    }
}

TESTlinkedlist.h:
/* Include Guards to prevent double inclusion with include directive */
#ifndef TESTLINKEDLIST_H
#define TESTLINKEDLIST_H

/* Typedef Structures */

typedef struct tnode {
    double weight;
    int c;
    struct tNode* right;
    struct tNode* left;
    struct tNode* parent;
} tnode;

typedef struct ll {
    tnode* node;
    struct ll* next;
} linkedList;

/* Methods */

linkedList* createLinkedList();
void displayLinkedList(linkedList* ll);
void addToLinkedList(linkedList** ll, tnode* val);
void addInOrder(linkedList **ll, tnode* nn);

#endif /* LINKEDLIST_H */

Any clue how I can make a new linked list, create a t node and add it to that linked list, and then display it, given the methods that my prof put down?

A: The code your professor gave you is broken, for example struct tnode* test = "hello"; causes an error during compilation.
Take it back to him and fail him. While you're there, tell him return is not a function and he shouldn't cast malloc.
On another professor-malloc-related note, he should be checking the return value. For example:
linkedList* nn = malloc(sizeof *nn);
if (!nn) {
    return;
}
nn -> node = val;
nn -> next = NULL;

There is another error that you're probably both at fault for; there are two main entry points and your compiler might get confused between them. Remove one of them.
In both of those entry points, addToLinkedList is used incorrectly; the first argument is intended to be a linkedList ** where-as what is being given is a linkedList *. Perhaps (in your first main entry point) you meant to write addToLinkedList(&test, value);. Note the additional ampersand.

A: the functions addToLinkedList and displayLinkedList need to get a pointer to a pointer as their fist parameter.
So, the main should look like this:
int main() {
    linkedList* test = createLinkedList();
    addToLinkedList(&test, value);
    displayLinkedList(&test);
}

Hope this helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why doesn't this remove all of the items from the  element? I have a function that is supposed to remove all child elements from a <select> on the onfocus event. (this is soon to be followed by filling the <select> with values from an AJAX call) For some reason, it only removes one of the elements the first time it is called , and then proceeds to do nothing all subsequent calls. Does anyone have any clue as to why this might be happening?
JS Code:
function handle(e) {
  for(var i = 0; i < e.children.length - 1; i++) {
    e.removeChild(e.children[i]);
  }
}

A: i'm guessing handle() is your onfocus event handler. in which case e is your event object and doesn't have any children property
why not just use select.innerHTML  = ""

A: So the answer is simply to remove them in inverse order, as to avoid the effects of a indexing system quite similar to the VB.NET List Class. (That is that it reorganizes itself every time a change is made.


text:
Q: php-How can i put this IF condition inside switch? Please help me for correcting this code,i want put if inside switch:
switch ($urlcomecatid) {

 if ($urlcomeparentid == 1 || $urlcomeparentid == 2 || $urlcomeparentid == 3)
  break;

case "50":
case "51":
case "52":
case "109":
case "110":
    //do nothing and exit from switch
    break;
default:
    header ("Location:http://www.example.com/tech/tech.php"); exit();
    break;

}

A: The correct code should be something like
switch ($urlcomecatid) {
    case "50":
    case "51":
    case "52":
    case "109":
    case "110":
        //do nothing and exit from switch
        break;
    default:
        if ($urlcomeparentid == 1 || $urlcomeparentid == 2 || $urlcomeparentid == 3)
            break;
        header ("Location:http://www.example.com/tech/tech.php"); exit();
        break;
 }

A: Use an if instead of the switch.
<?php
if(!in_array($urlcomeparentid, array(1, 2, 3) && !in_array($urlcomecatid, array('50', '51', '52', '109', '110')){
    header ("Location:http://www.example.com/tech/tech.php");
    exit();
}

You should avoid exit() as it kills the rest of your script which is a potential source of problems when you debug.


text:
Q: derivative with respect to scalar variable What is the result of the following expression:
$\frac{\partial}{\partial a} (\mathbf{x} - a \mathbf{1})^T \Sigma (\mathbf{x} -  a \mathbf{1})$,
where $a$ is a scalar, $\mathbf{x}$ is a $K \times 1$ column vector, and $\Sigma$ is a $K\times K$ matrix. I can compute the derivative if $a$ is also a vector, which is given as:
$-2\Sigma(\mathbf{x}-\mathbf{a})$,
but could not find the solution when $a$ is scalar.

A: I think your notation could still be improved, since your $\mathbf{1} $ symbol is more often used to denote the identity matrix, which cannot be the case. Let me restate the formula in terms of the symbol $\mathbf{y}$, which represents the same array of ones but is less confusing:
$$
\frac{\partial}{\partial a} (\mathbf{x} - a \mathbf{y})^T \Sigma (\mathbf{x} -  a \mathbf{y})
$$
Which, in terms of components reads (summation implied for repeated indices):
$$
\frac{\partial}{\partial a} \left( (x_i - a y_i) \Sigma_{ij} (x_j - a y_j) \right ) = y_i \Sigma_{ij} (a y_j - x_j) + (a y_i - x_i) \Sigma_{ij} y_j
$$
Or, in the initial notation,
$$
\frac{\partial}{\partial a} (\mathbf{x} - a \mathbf{y})^T \Sigma (\mathbf{x} -  a \mathbf{y}) = \mathbf{y}^T \Sigma (a \mathbf{y} - \mathbf{x}) +  (a \mathbf{y} - \mathbf{x})^T \Sigma \mathbf{y}
$$


text:
Q: why use postfix /prefix expression instead of infix? I understand how to convert infix to postfix/prefix but I do not understand why postfix or prefix expression are used in computer system?
What is the advantage of postfix prefix over infix expression?

A: Notice that LISP languages (e.g. Common Lisp, Scheme, Clojure and many specific dialects inspired by them like AutoLISP, Emacs-LISP, MELT, etc...) are all using a prefix-syntax: every expression starts with a left parenthesis, then the operator, then the operands, then the right parenthesis. These expressions are called S-expressions. For example 1+2*3 is typed as (+ 1 (* 2 3)) and there is no need for operator precedence.
The advantages of such a simple syntax (probably the simplest possible one for ASTs, outside of stack languages à la Forth) include:

*

*easy to remember syntax rule for human developers

*easy and quick to parse for language implementations

*easy to emit when generating code in s-expressions (from some AST representation)

*ability to easily make homoiconic languages above them

*ability to handle many operands (e.g. have variadic operators or functions, or functions with many formal arguments)

*simple to read, once you can match a left parenthesis with its right one

The disadvantage of such syntax is a pun on the language: Lots of Insipid Stupid Parenthesis. However (believe it or not) any Lisp coder don't see the parenthesis as agressive, and uses the ability (provided by any good editor) to match parenthesis when reading code on the screen.
BTW, what is important is not to convert textual representation from e.g. infix to prefix, but to parse expressions into AST (abstract syntax trees).  Very often, an AST is a tree-like structure in memory, keeping more information that the simple syntactical shape (e.g. the source location, as a file name, line number, column number, or some type information, etc...).

A: Both pre- and postfix have basically the same advantages over infix notation. The most important of these are:

*

*much easier to translate to a format that is suitable for direct execution. Either format can trivially be turned into a tree for further processing, and postfix can be directly translated to code if you use a stack-based processor or virtual machine

*entirely unambiguous. Infix notation requires precedence and associativity rules to disambiguate it, or addition of extra parentheses that are not usually considered part of the notation. As long as the number of arguments to each operator are known in advance, both prefix and postfix notation are entirely unambiguous: "* + 5 6 3" is (5+6)*3, and cannot be interpreted as 5+(6*3), whereas parenthesis is required to achieve with infix.

*supports operators with different numbers of arguments without variation of syntax. "unary-op 5" and "ternary-op 1 2 3" both work fine, but need special syntax to make them work in infix.


text:
Q: Are there equivalent classes or functions to DataInputStream in Java for the iPhone to read binary information Java provides classes DataInputStream and DataOutputStream to read/write binary data (as bytes) in a structured way like DataInputStream.readInt()/readLong()/read(byte[]) from a byte stream; likewise for the DataOutputStream.
Are there equivalent classes or functions to the same in iPhone?

A: NSData will do what you looking for I think:Core Data Class Reference

A: Ram,
I feel your pain. Coming from Java land lots of things will feel backward or missing. NSData is your starting point but it works more like ByteArray stream classes as it holds the materialized data. Also beware that there are no formatting functions for serializing/deserializing data written/read to/from the source. In other words you won't find readInt(), readShort() in here. Do this: Cmd+Shift+? from XCode to call up help, type NSData to bring up the docs for it then click the link for the binary programming guide. Having dealt with an issue that may be exactly what you're about to hit, I'll warn you about the endian-ness of reading data on the iPhone from a stream that was written by Java. You'll have to swap byte orders from low to high. In other words if you use a DataOutputStream.writeInt() on one end (in something like a servlet) then try to map an int over the data read into an NSData object then swap byte orders.


text:
Q: Using dompdf library in codeigniter can anybody help me, i'm trying to use dompdf library with codeigniter. When i do it on localhost its work. But it's not work properly when my website has been uploaded. Here's the library code
    <?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * CodeIgniter PDF Library
 *
 * Generate PDF's in your CodeIgniter applications.
 *
 * @package         CodeIgniter
 * @subpackage      Libraries
 * @category        Libraries
 * @author          Chris Harvey
 * @license         MIT License
 * @link            https://github.com/chrisnharvey/CodeIgniter-PDF-Generator-Library
 */
require_once(dirname(__FILE__) . '/dompdf-0.6.2/dompdf_config.inc.php');
class Pdf extends DOMPDF
{
    /**
     * Get an instance of CodeIgniter
     *
     * @access  protected
     * @return  void
     */
    protected function ci()
    {
        return get_instance();
    }
    /**
     * Load a CodeIgniter view into domPDF
     *
     * @access  public
     * @param   string  $view The view to load
     * @param   array   $data The view data
     * @return  void
     */
    public function load_view($view, $data = array())
    {
        $html = $this->ci()->load->view($view, $data, TRUE);
        $this->load_html($html);
    }
}

this code to call create the pdf, i try to call the view only and it's work but when its called the "pdf" function, the screen is blank.
    $this->load->library('pdf');
    $this->pdf->load_view('mydocument', $data);
    $this->pdf->render();
    $this->pdf->stream("mydocument.pdf");

and this is structure of my files
enter image description here

A: As noted in the comments @jagad89 is right about including the autoload file from DOMPDF.
Instead of using it with a library wrapper, try installing with Composer
composer require dompdf/dompdf

And then setup the $config['composer_autoload'] = '/path/to/vendor/autoload.php'; in the config.php of your application and you should be good to use DOMPDF like this:
$dompdf = new Dompdf\Dompdf();
$dompdf->loadHtml('hello world');

// Render the HTML as PDF
$dompdf->render();
$dompdf->stream();

A: Use the following code in controller instead, It shoud be work for you.
$this->load->library('pdf');
$this->pdf->load_view('mydocument', $data);
$this->pdf->setPaper('A4', 'portrait');
$this->pdf->render();
$this->pdf->stream("mydocument", array("Attachment" => 0));

A: Download an archive of dompdf and extract it into the directory where dompdf will reside

*

*You can download stable copies of dompdf from https://github.com/dompdf/dompdf/releases

*Or download a nightly (the latest, unreleased code) from http://eclecticgeek.com/dompdf

Libraries/Pdf Class:

require_once APPPATH.'libraries/dompdf/autoload.inc.php';
use Dompdf\Dompdf;
class Pdf {
    $dompdf = new Dompdf();
    $dompdf->loadHtml('
Hello Word
');
    $dompdf->setPaper('A4', 'portrait');
    $dompdf->render();
    $dompdf->stream('mydocument.pdf');
}


text:
Q: Does $f_n=x^n$ on $\{1, 1/2, 1/3, 1/4, ...\}$ have a subsequence converges uniformly? I know we can show $f_n=x^n$ on $[0, 1]$ does not have a subsequence converges uniformly by contradiction. But what if I define $f_n$ on $[1, 1/2, 1/3, ...].$ Does the conclusion still hold? If so, what should I do? Thanks!

A: As @AnginaSeng suggests, $(f_n)_n$ converges uniformly to the function $f : \left\{1, \frac12, \frac13, \ldots\right\} \to \Bbb{R}$ given by
$$f(x) = \begin{cases} 1, &\text{ if } x = 1\\ 0, &\text{otherwise}.\end{cases}$$
Indeed, we have
$$\|f_n - f\|_\infty = \sup_{k\in\Bbb{N}} \left|f_n\left(\frac1k\right) - f\left(\frac1k\right)\right| = \sup_{k\ge 2} \frac1{k^n} = \frac1{2^n} \xrightarrow{n\to\infty} 0$$
so $f_n \to f$ uniformly on $\left\{\frac1k : k \in \Bbb{N}\right\}$.


text:
Q: Signing a certificate with my CA On running:
openssl ca -in ${ALIAS}.csr -out user-cert.pem -keyfile cacert-private.pem -cert cacert.pem -passin pass:$PASSWD -config ${CONFIG}

I get:

The stateOrProvinceName field needed to be the same in the
  CA certificate (Gloucestershire) and the request (Gloucestershire)

I've read the error a few times and I'm fairly sure the field is the same value in each case. I have found references to similar problems being caused by different encodings but I don't know how I should be specifying that and where.
This is the ${ALIAS}.csr:
-----BEGIN NEW CERTIFICATE REQUEST-----
MIICxzCCAa8CAQAwgYExCzAJBgNVBAYTAkdCMRgwFgYDVQQIEw9HbG91Y2VzdGVyc2hpcmUxEzAR
BgNVBAcTCkNoZWx0ZW5oYW0xHzAdBgNVBAoTFldhbnNkeWtlIEhvdXNlIExpbWl0ZWQxDjAMBgNV
BAsTBUZpemlvMRIwEAYDVQQDEwlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK
AoIBAQDWvivt1JHiuaNeadOQJtxynQ4sSAR/peWgKd8g9UQgNM+H9QW4NlRE81+g63BdRqZT5YMm
J4K3upovQNlDRklevslgEYoTdQM4yBKV676Q4XDbM7Vk+rt04sqL5IgdsAUXODfMJvu81t3tOjFc
OGO7S+B+LEJ1+8qshLbuK2gBigfgcZtlbNgW6fCGik8ZsrKWl8W+NFbw1seS01INAipwCBasxaaj
/lINwWQVbQIG09+vEdwuHmmq5VIKlJqFcYNUTFBVojoJLfzyStZR2PfFUxp7R+t2YmVj6a48B7NA
lODnIlQDkAprECNMpCZoSP1QjrZgW1BgaVbT5OaWlVsPAgMBAAGgADANBgkqhkiG9w0BAQUFAAOC
AQEAvalFyJOgzmd1jcFlS5YoqiNgX1bm9nZ0/cFgj6cGL7R0Gqc9wu5QPakWRxa9c2UcI0m7p1lp
cygDvQTY23LEBhVcruymIGQG5DhDpXHeaBCbV3OWO6xowAjh+riQjvTNeVSXtP3jUNs5DaId0z+A
GXeb7dR96jhyj+soNYENoQseQLqLdAW4p0jdK1BraMJTc0ber0FBx1nOUXOEoTIJL9kL9cUWaCp3
7uYkonIPtVCCfS8KcgXxUsNMC41q/SkKDVB23PeCjnWgcyXxnSpx8n+AK7fwMgh+4TcZ5usmVujR
MNqk84hZpw8h1FIcmqRaWtaPWyv3EX8JH5LTnDe3eQ==
-----END NEW CERTIFICATE REQUEST-----

And cacert.pem:
-----BEGIN CERTIFICATE-----
MIIDQDCCAqmgAwIBAgIJAPj9mvMDl1K/MA0GCSqGSIb3DQEBBQUAMIG4MQswCQYD
VQQGEwJHQjEYMBYGA1UECAwPR2xvdWNlc3RlcnNoaXJlMRMwEQYDVQQHDApDaGVs
dGVuaGFtMR8wHQYDVQQKDBZXYW5zZHlrZSBIb3VzZSBMaW1pdGVkMQ4wDAYDVQQL
DAVGaXppbzESMBAGA1UEAwwJbG9jYWxob3N0MTUwMwYJKoZIhvcNAQkBFiZyaWNo
YXJkLm1pZHdpbnRlckB3YW5zZHlrZS1ob3VzZS5jby51azAeFw0xMTA4MDcyMTU4
NDBaFw0yMTA4MDQyMTU4NDBaMIG4MQswCQYDVQQGEwJHQjEYMBYGA1UECAwPR2xv
dWNlc3RlcnNoaXJlMRMwEQYDVQQHDApDaGVsdGVuaGFtMR8wHQYDVQQKDBZXYW5z
ZHlrZSBIb3VzZSBMaW1pdGVkMQ4wDAYDVQQLDAVGaXppbzESMBAGA1UEAwwJbG9j
YWxob3N0MTUwMwYJKoZIhvcNAQkBFiZyaWNoYXJkLm1pZHdpbnRlckB3YW5zZHlr
ZS1ob3VzZS5jby51azCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA03Y4hYdd
at3e3AB98s+E5wlxrvRL8RhJtRac0Jt0gXQy12ZYziFm3gryx0IG02srXluM+V3/
BPRRCLsnEnltfoi/fE0wM9MT0V1Ao9EXQ5t1E2rOzdoXUUdvovd6qvwG2L/DHCdL
kKjhokVR9TkFW/AWctBdWkb9qfFFTpDY4i0CAwEAAaNQME4wHQYDVR0OBBYEFHbG
d3+Lzax90slk65y1BYDgZ897MB8GA1UdIwQYMBaAFHbGd3+Lzax90slk65y1BYDg
Z897MAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADgYEArZ2yfTGJK3R+jRwP
FjaonDy1NVOt9tgjHfyh9YNQfyFSC7R987wFPcyydEqh8xg/Lb3WGwseDuzCBusw
jmVIqiUYBClHzkF3jG1766ltdlVVTOavVQgQMRBGMvpHVxcMH2RUNUyWH0XW+DH2
/uuRRpu4vX5sfEW75uEfORB9Mrg=
-----END CERTIFICATE-----

Any ideas? Thanks in advance.

A: As shown by :
openssl asn1parse -in req.csr

the request DN strings are encoded as PRINTABLESTRING.
openssl asn1parse -in cacert.pem

shows the CA DN strings are encoded as UTF8STRING.
For a quick'n dirty hack, I suggest you change the encoding of strings in your request by replacing the encoding type for PRINTABLESTRING (0x13) by the type for UTF8STRING (0x0c), using your favorite hex editor.
You will have to convert your request in DER before poking it.
The offset of bytes to change can be found with :
openssl asn1parse -in csr |grep PRINTABLESTRING |awk -F":" '{print $1}'

Then try to sign again.

A: I just ran into this problem. The root cause is a mismatch between the values of string_mask in the client's and the CA's openssl.cnf. The easy fix is to modify the client's value to match what the CA expects, then regenerate the CSR. The hard fix is to edit the CA's value and start a fresh CA.

A: Promoting mbrownnyc's comment to an answer, as it was useful to me and deserves more attention.
I believe /usr/ssl/openssl.cnf contains a policy called policy_anything that contains the above setup. You can use it by utilizing the policy argument as follows:
openssl ca -policy policy_anything -days 365 -out /root/ca/certs/out.pem -in certreq.csr

A: You can also set the attributes as optional:
# For the CA policy

[policy_match]
countryName= optional
stateOrProvinceName= optional
organizationName= optional
organizationalUnitName= optional
commonName= supplied
emailAddress= optional

A: I have also run into this problem.  Thanks to the replies above (mainly Francois), I discovered the source of the problem.
openssl is encoding using UTF8STRING and keytool (Java 6) is encoding with PRINTABLESTRING.
Worked around it by changing the openssl configuration so it matches keytool.  In /usr/ssl/openssl.cnf change the "string_mask" setting to "pkix".

A: The previous posters already answered the question, but to make it easier, here is an example how to specify the encoding. Use the string_mask:
[ req ]
default_bits            = 2048
default_md              = rsa
prompt                  = no
string_mask             = utf8only  # <--------------
distinguished_name      = req_distinguished_name

[ req_distinguished_name ]
countryName             = GB
stateOrProvinceName     = Gloucestershire
localityName            = Cheltenham
organizationName        = Wansdyke House Limited
organizationalUnitName  = Fizio
commonName              = localhost


text:
Q: Uploading file with c# ftp methods results in webexception. Problem disappears after program restart I have following problem:
I'm using C# ftp methods to automate sending files to FTP servers. The program is constantly running, checking predefined directories. If it finds files in a directory, it is supposed to upload them to a defined ftp server. There are about 80 directories and most of the time the program has something to do. Everything works fine, except from the following scenario:

*

*The file is being uploaded.

*An error occurs while uploading: the remote host is down, the quota is exceeded or something similar.

*An attempt is made to upload the file once again and the error occurs once again.

*An attempt is made to upload file for the third, fourth, ... time and then this line of code:
Stream requestStream = ftpRequest.GetRequestStream();
throws WebException with status: Undefined, and description: the time limit for this operation has been reached (or something similar - I had to translate this from polish). While this WebException is being thrown, ftp request to other servers (files from different directories) succeed, so it looks like there is only problem with connection to this one ftp server.
It all results in no further attempt to upload file being successful. Uploading this file through other ftp client is, however, possible. When I restart the program, everything runs smoothly. Should I somehow manually release ftp resource? I'm using KeepAlive property of FtpWebRequest set to true..
I would very appreciate if someone could shed some light on this problem.
Edited:
I followed David's hint and found the place where I didn't call Close() method on the requestStream, I fixed it, but the problem reoccurred.
I will paste some code then. Here is part of the method, that uploads the file to the server. If it fails, another attempt is being made, something like:
while (retryCounter++ < retryNumber)
{
  //upload file,
  //if succeeded, break
}

inside while-block there is:
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(remoteFileName);
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.Credentials = new NetworkCredential(UserName, Password);
ftpRequest.ReadWriteTimeout = SendTimeout;
ftpRequest.Timeout = ConnectTimeout;
ftpRequest.KeepAlive = true;
ftpRequest.Proxy = null;
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;

Stream requestStream = null;

try
{

  using (MemoryStream fileStream = new MemoryStream(localFile))
  {
    byte[] buffer = new byte[BufferSize];

    int readCount = fileStream.Read(buffer, 0, BufferSize);
    int bytesSentCounter = 0;

     while (readCount > 0)
     {
         requestStream.Write(buffer, 0, readCount);
         bytesSentCounter += readCount;

         readCount = fileStream.Read(buffer, 0, BufferSize);
         System.Threading.Thread.Sleep(100);

     }
}

requestStream.Close();
requestStream = null;

FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();
FtpStatusCode code = response.StatusCode;
string description = response.StatusDescription;
response.Close();

_logger.Information("Upload file result : status code {0}, status description {1}", code, description);

if (code == FtpStatusCode.ClosingData)
{
    _logger.Information("File {0} uploaded successfully", localFileName);
}
else
{
    _logger.Error("Uploading file {0} did not succeed. Status code is {1}, description  {2}", localFileName, code, description);
}

}
catch (WebException ex)
{

    if (requestStream != null)
        requestStream.Close();

    ftpRequest.Abort();

    FtpStatusCode code = ((FtpWebResponse)ex.Response).StatusCode;
    string description = ((FtpWebResponse)ex.Response).StatusDescription;

   _logger.Error("A connection to the ftp server could not be established. Status code: {0}, description: {1} Exception: {2}. Retrying...", code, description, ex.ToString());

}
So, again the scenario is following:
1. The file is being uploaded and System.Net.Sockets.SocketException occurrs.
2. Another attempt is being made and System.Net.Sockets.SocketException reoccurs.
3. Always before I call the uploadfile method, I check whether the remote server is up and everything is ok by trying to list the remote directory. And from now, by calling
ftpRequest.GetResponse() (where ftpRequest.Method is WebRequestMethods.Ftp.ListDirectory) I get WebException with status: Undefined, and description: the time limit for this operation has been reached. When I restart the application, the problem disappears.
I can find no other place where the streams are not released properly, and have no idea what to do next..

A: Are you sure you're closing the stream correctly and thus release all underlying resources properly?
If not, this might be the cause of your problem, when you hit a limit (e.g. open sockets) after repeated failures.

A: You need to ensure you put the Stream.Close(), Request.Close() and Response.Close() in a finally block otherwise they will be skipped whenever there is an error. Keep in mind when dealing with external resources such as over a network, you need to program to expect errors since they will certainly crop up at some point.

try
{
    processing here...
}
finally
{
     requestStream.Close();
     requestStream = null;
}

A: One possible source of error that I've run into is creating a new "NetworkCredential" over and over again. Then you'll get an exception after awhile.


text:
Q: TCP optimisation I've written a code using SOL_SOCKET protocol but getting error as 10043 (error in socket).
The code is as follows:
#include <QCoreApplication>
#include<QDebug>
//#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>

/****************************************/
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")
/****************************************/

#define DEFAULT_BUFLEN 512

int recvbuflen = DEFAULT_BUFLEN;
char recvbuf[DEFAULT_BUFLEN];

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    WSADATA wsaData;
    int iResult;
    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed with error: %d\n", iResult);
        return 1;
    }

    struct addrinfo *result = NULL,
                    *ptr = NULL,
                    hints;
    ZeroMemory( &hints, sizeof(hints) );
    //hints.ai_family = AF_UNSPEC;
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = SOL_SOCKET;
    //hints.ai_protocol = IPPROTO_TCP;

#define DEFAULT_PORT "10990"

// Resolve the server address and port
iResult = getaddrinfo(argv[1], DEFAULT_PORT, &hints, &result);
if (iResult != 0) {
    printf("getaddrinfo failed: %d\n", iResult);
    WSACleanup();
    return 1;
}

SOCKET ConnectSocket = INVALID_SOCKET;

// Attempt to connect to the first address returned by
// the call to getaddrinfo
ptr=result;

// Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
    ptr->ai_protocol);

if (ConnectSocket == INVALID_SOCKET) {
    printf("Error at socket(): %ld\n", WSAGetLastError());
    freeaddrinfo(result);
    WSACleanup();
    return 1;
}

    int rcvbuf = 8192;  /* recv buffer size */
    int z = setsockopt(ConnectSocket,SOL_SOCKET,SO_RCVBUF,
    (char*)&rcvbuf,sizeof(rcvbuf));

    do {
            iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
            if (iResult > 0)
            printf("Bytes received: %d\n", iResult);
            else if (iResult == 0)
            printf("Connection closed\n");
            else
            printf("recv failed: %d\n", WSAGetLastError());
       } while (iResult > 0);

    return a.exec();
}

When I run it shows::
Error in socket:10043

I googled it and found that the error is because of wrong protocol for the socket type,I tried to find the correct protocol and socket type match but couldn't find.I tried every possible socket option and protocol match.
Any body facing the same problem?

A: You're putting the wrong value in the ai_protocol field. It needs to be one of the IPPROTO_ constants (like e.g. IPPROTO_TCP or IPPROTO_ICMP).
SOL_SOCKET is used to set socket options (like you do later in the code).
You should normally not set that member, except to zero.


text:
Q: Encode ' to be XML safe I have a string that contains a right single quotation mark:
$str = "David's Spade";

I am sending the string via XML and need to encode it. I have read that I should encode string using htmlspecialchars, but I have found that XML request still fails whereas htmlentities works.
When I error_log $str:
$str; // David\xe2\x80\x99s Spade
htmlspecialchars($str); // David\xe2\x80\x99s Spade
htmlspecialchars($str, ENT_QUOTES, 'UTF-8'); // David\xe2\x80\x99s Spade
htmlentities($str); // David's Spade

Would it be better to str_replace ' and then use htmlentities? Are there any other chars htmlentities may miss?

A:
I am sending the string via XML and need to encode it.

No, you don't. If the XML is UTF-8 encoded (it is by default) and as your $str is UTF-8 encoded (as you show by the binary sequences in your question), you do not need to encode it.
This is by the book. So given on the technical information of the data you collaborate with, this is clear and fine.
You then write that some things work and others won't. Whatever you do there, there problem lies within the things you've hidden from your question.
To make this more explicit:
$str = "David's Spade"; // "David\xE2\x80\x99s Spade"

is a perfectly valid string, for example to use it with an XML library like Simplexml to add it to an XML document:
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><doc/>');
$xml->element = $str;
$xml->asXML('php://output');

Output:
<?xml version="1.0" encoding="UTF-8"?>
<doc><element>David's Spade</element></doc>

As you can see, the XML has been encoded by not changing the byte-sequence of the string here because it's UTF-8.
Let's take some ASCII:
$xml = new SimpleXMLElement('<doc/>');
$xml->element = $str;
$xml->asXML('php://output');

Output:
<?xml version="1.0"?>
<doc><element>David’s Spade</element></doc>

As this example shows, it depends on the document encoding then. This second example is a fall-back of Simplexml to make the output more robust, but actually this wouldn't be necessary as UTF-8 would be the default encoding.
In any case you should not be too concerned about the encoding yourself by using a library that has specialized on creating XML documents. PHP has some few for exactly that. Take one of them.


text:
Q: `git pull` locks up on one repository I have a remote git server that has been working great for months.  Earlier today a couple of my teammates said they were having trouble with git pull for one of our projects.
I am testing it now and I cannot preform a git pull either.  I was able to run git fetch once, but now that isn't working.  When I look at the server processes for the git user (the one that connects to the remote repo) I see 3 processes that are just sitting there: sshd, php, and git-upload-pack.
All of the other repositories that are also on this remote server are working fine.  The repository is fairly large and just had a new branch added to it.
Any ideas on how to fix this?
Thanks.

A: git-fsck and git-gc

A: It ended up being an issue with remote repositories over ssh for that one project.  To fix it I rebuilt the remote repository by following these steps on the remote server.
1.In a temp location rungit clone /full/path/to/local/repo/project.git temp_repo, then cd temp_repo
2.Make sure you create, checkout, and pull every branch (I had 3).
3.Now you have a complete fresh copy of the repository, just overwrite the original with the new one with mv /path/to/new/temp_repo /full/path/to/local/repo


text:
Q: Strategy for securing paid Data as a Service API When creating a webservice/api that is intended to be used by javascript/flash/mobile clients, what is a good method for making sure that a paying client's credentials are not stolen and reused.
To clarify further, lets say I want to charge $1 for every 10,000 requests against my API. If someone wants to farm my data for free, they would just need to find another client app that already uses my API and construct requests using the credentials of the paying customer.
I don't see any way that I can "hide" what is going on the client, someone will always be able to easily reverse engineer the "auth" scheme. So what are good ways to mitigate abuse?
EDIT
More in depth example of the scenario...
Lets say my data service is bus schedules. The purpose of the services is for developers to write apps consuming the data. There's nothing personal about the data, it is the same for everyone. The intention is for the developer to write javascript/flash/mobile apps directly against the api (I'm aware of cross domain restrictions). But the developer has to pay when users of his app make requests against the bus schedule api. How do I keep another developer going to the original developer's site and just lifting the credentials that are used by his browser to talk to the bus schedule api, and writing his own app using those credentials?

A: First of all, just because someone has the code doesn't mean they can bypass your authentication by merely reverse-engineering your code. If you have a private/public encryption in place, having the code doesn't help an attacker much.
On the actual question: The common thing to do seems to be handing out API keys, each of which identifies a paying customer. All requests done through one customer's API key get charged to their account; this way, you hand the responsibility for keeping the API key secret and avoid abuse to the client.
Of course, to avoid eavesdropping and man-in-the-middle attacks, you should serve API requests over HTTPS.


text: Q: Is there a way to figure out if a form has already been validated? I have some WTForms being used in a flask app. Within templates, I'd like to be able to add Bootstrap's was-validated class to the form when a form has already been validated. Is there an object variable that I can look at in the form object?


text:
Q: PL/SQL split one to many rows I have a table like this.

|PARAMKEY  | PARAMVALUE
  ----------+------------
  KEY       |[["PAR_A",2,"SCH_A"],["PAR_B",4,"SCH_B"],["PAR_C",3,"SCH_C"]]

I need to split the values into three columns and I use REGEXP_SUBSTR. Here is my code.
SELECT REGEXP_SUBSTR(paramvalue, '[^],["]+', 1,1 ) PARAMETER
       ,REGEXP_SUBSTR(paramvalue, '[^],[",]+', 1, 2) VERSION
       ,REGEXP_SUBSTR(paramvalue, '[^],["]+', 1, 3) SCHEMA
       FROM   tmp_param_table
where paramkey = 'KEY'
       UNION ALL
SELECT REGEXP_SUBSTR(paramvalue, '[^],["]+', 1, 4 ) PARAMETER
       ,REGEXP_SUBSTR(paramvalue, '[^],[",]+', 1, 5) VERSION
       ,REGEXP_SUBSTR(paramvalue, '[^],["]+', 1, 6) SCHEMA
       FROM   tmp_param_table
where paramkey = 'KEY'
       UNION ALL
SELECT REGEXP_SUBSTR(paramvalue, '[^],["]+', 1, 7 ) PARAMETER
       ,REGEXP_SUBSTR(paramvalue, '[^],[",]+', 1, 8) VERSION
       ,REGEXP_SUBSTR(paramvalue, '[^],["]+', 1, 9) SCHEMA
       FROM   tmp_param_table
where paramkey = 'KEY';

and this is the result that i need.

PARAMETER | VERSION | SCHEMA
  ---------+---------+-------
  PAR_A    |2        |SCH_A
  PAR_B    |4        |SCH_B
  PAR_C    |3        |SCH_C

But the value is too long and I hope there is another way to make it simplier by using loop or anything.
Thanks

A: Try something like this:
with tmp_param_table as
(
select 'KEY' as PARAMKEY  ,  '[["PAR_A",2,"SCH_A"],["PAR_B",4,"SCH_B"],["PAR_C",3,"SCH_C"]],["PAR_D",4,"SCH_D"]]' as PARAMVALUE from dual
),
levels as        (select level as lv   from dual connect by level <= 156),
steps as (select lv-2  as step from levels  where MOD(lv,3)=0)
select step, (SELECT REGEXP_SUBSTR(paramvalue, '[^],["]+',1, step ) PARAMETER  FROM   tmp_param_table where paramkey = 'KEY')  parameter,
             (SELECT REGEXP_SUBSTR(paramvalue, '[^],["]+',1, step+1 ) PARAMETER  FROM   tmp_param_table where paramkey = 'KEY') version,
             (SELECT REGEXP_SUBSTR(paramvalue, '[^],["]+',1, step+2 ) PARAMETER  FROM   tmp_param_table where paramkey = 'KEY') schema
               from  steps

Here
levels - returns numbers form 1 till 156 (52*3) (or whatever you need)
steps - are the numbers 1, 4, 7 etc with step 3
Results:
1   PAR_A   2   SCH_A
4   PAR_B   4   SCH_B
7   PAR_C   3   SCH_C
10  PAR_D   4   SCH_D
13
etc..

A: I have tried using regular expression
and part paramvalue column value into common separated value
SELECT
REGEXP_SUBSTR(COL, '[^],["]+', 1, 1) PARAMETER,
REGEXP_SUBSTR(COL, '[^],[",]+', 1, 2) VERSION,
REGEXP_SUBSTR(COL, '[^],["]+', 1, 3) SCHEMA
FROM
(
SELECT paramkey,REGEXP_SUBSTR(to_char(paramvalue),'[^][^]+',1,level ) COL
 from tmp_param_table
connect by regexp_substr(to_char(paramvalue),'[^][^]+',1, level) is not null
)
WHERE COL <>','

I hope this may help.


text:
Q: Gatsby doesn't render MDX, instead gives plain text I'm building a blog with Gatsby, I've made some progress but when I try to render mdx in my blog template, it doesn't render to anything.

I use createPages api, and everything works accordingly except this. When I wanted to use  it gives an error 'Element type is invalid'. From my research, it is because its outdated with mdx v2?
This is the bit where I create pages and pass nodes
exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions

  const result = await graphql(
    `
    query AllQueries {
      site {
        siteMetadata {
          title
        }
      }
      allMdx(sort: {fields: [frontmatter___date], order: DESC}) {
        nodes {
          fields {
            slug
          }
          excerpt
          frontmatter {
            date(formatString: "Do MMMM YYYY ")
            title
            description
          }
          body
        }
      }
    }
  `
  )

  const blogPostTemplate = path.resolve(`./src/templates/blog-post.js`)
  const articles = result.data.allMdx.nodes
  result.data.allMdx.nodes.forEach((node, index) => {
    console.log('node', node)
    createPage({
      path: `/blog${node.fields.slug}`,
      component: blogPostTemplate,
      context: {
                post: node,
                prev: index == 0 ? null : articles[index -1],
                next: articles.length -1 ? articles[index + 1] : null
      },
    })
  })

I can get frontmatter, title, date etc. without any problems.
node [Object: null prototype] {
  fields: [Object: null prototype] { slug: '/eighth-post' },
  excerpt: 'Heading Level Two Some text\n\nHeading Level Three\n\nSome more text',
  frontmatter: [Object: null prototype] {
    date: '5th October 2022 ',
    title: 'Eighth Post',
    description: 'This article is the truth'
  },
  body: '\n' +
    '\n' +
    '\n' +
    '## Heading Level Two\n' +
    '\n' +
    'Some text\n' +
    '\n' +
    '### Heading Level Three\n' +
    '\n' +
    'Some more text'
}

This is the example of a node that I'm getting. Thank you.
This is the template I'm using to render posts.
import React from "react";
import { Link } from "gatsby";
import  Layout from "../components/layout";

function BlogPost({ pageContext }) {

  const { post } = pageContext
  const prev = pageContext.prev
  ? {
    url : `${pageContext.prev.fields.slug}`,
    title : pageContext.prev.frontmatter.title
  } : null

  const next = pageContext.next
  ? {
    url : pageContext.next.fields.slug,
    title : pageContext.next.frontmatter.title
  } : null

  return (

   <Layout>

         <Link className="card-link" to={`.${post.fields.slug}`}>

{post.frontmatter.title}

         </Link>

{post.frontmatter.date}

{post.frontmatter.description}

{post.body}

         {next &&
         <Link to={`..${next.url}`} className="previous">
            < {next.title}
         </Link>
         }
         {prev &&
            <Link to={`..${prev.url}`} className="next">
               {prev.title} >
            </Link>
         }

   </Layout>
  )
}

export default BlogPost

This is the gatsby-config file
module.exports = {
  siteMetadata: {
    title: `My Online Portfolio`,
    description: `my home on the web`,
    siteUrl: `https://evilsaint.cloud`,
    social: {
      twitter: `https://twitter.com/_EvilSaint_`
    },
  },
  plugins: [
  `gatsby-plugin-image`,
  `gatsby-plugin-sitemap`,
  `gatsby-plugin-mdx`,
  `gatsby-plugin-sharp`,
  `gatsby-transformer-sharp`,
  {
    resolve: 'gatsby-plugin-mdx',
    options: {
      extensions: [`.mdx`, `md`],
      gatsbyRemarkPlugins: [
        {
          resolve: `gatsby-remark-highlight-code`,
          options: {
            terminal: "ubuntu",
          },
        },
      ],
    },
  },
  {
    resolve: 'gatsby-source-filesystem',
    options: {
      "name": "images",
      "path": "./src/images/"
    },
    __key: "images"
  },
  {
    resolve: 'gatsby-source-filesystem',
    options: {
      "name": "pages",
      "path": "./src/pages/"
    },
    __key: "pages"
  },
  {
    resolve: `gatsby-transformer-remark`,
    options: {
      footnotes: true,
      gfm: true,
      plugins: [],
    },
  },
  {
    resolve: 'gatsby-source-filesystem',
    options: {
      "name": `blogs`,
      "path": `${__dirname}/src/blog/`,
    },
    __key: "blogs"
  },
  'gatsby-transformer-remark',

]
};

A: The problem is that you are just rendering the body as is, as a plain text:

{post.body}

If you want to render the content as MDX you have two options:

*

*Using the built-in plugin by Gatsby (see docs):

*

*Install gatsby-transformer-remark

*Add it to your gatsby-config.js:

module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `markdown-pages`,
        path: `${__dirname}/src/markdown-pages`,
      },
    },
 `gatsby-transformer-remark`,
  ],
}

Important: add it below gatsby-source-filesystem instance

*Use React's dangerouslySetInnerHTML to display the internal content. Change your current
 to:

Caveats: using dangerouslySetInnerHTML you are potentially exposing your site as XSS (Cross-Site Scripting)

*Use another library like markdown-to-jsx (or similar)
import Markdown from 'markdown-to-jsx';

...

<Markdown options={{ wrapper: 'p' }}>{post.body}</Markdown>


text:
Q: AngularJs : how to use multiple condition inside ng-switch? I have a div based on switch but in one particular case even when switch case will be true I need to display another link based on different condition. Can some one suggest me any ideas ?

    <a ng-switch-when="true && row.id.indexOf(:) < 0" href="{{url + row.id}}">
    {{getName(row)}}

      {{getName(row)}}

A: You may need other tags such as ng-show and ng-if

A: ngswitch only allows you to compare a single condition.
if you want to test multiple conditions you can use ng-if
If you still need to use multiple conditions, look at the answer with a directive.
AngularJS: ng-switch-when with an OR


text:
Q: How do I open the Windows Task Manager during a Remote Desktop session? When I press Ctrl-Alt-Delete I can only open the Task Manager for the local PC.
Is there some simple way to open the Task Manager on the remote PC while running Remote Desktop from one Windows XP machine to another?

A: Right-click the taskbar and click Task Manager.
CTRL+Shift+Esc will serve the purpose if its not allowing to click anywhere.

A: If Jonas may have been meaning he had a windowed remote desktop session, and he wondered what keyboard shortcut would open Task Manager on that remote, there is a shortcut for that (not mentioned yet in other answers here):
altshifthome
Since he mentioned using ctrlaltdel, it seems most focused on showing how to do THAT against in the remote (windowed or not), or how to open task manager other ways in the remote. Those are not wrong answers, but if Jonas (or other readers finding this post) wondered if there was such a keyboard shortcut for a windowed RDP session, hope this helps.
I have a blog post with still more such shortcuts for a "windowed" remote desktop: Helpful keyboard shortcuts for working with "windowed" Remote Desktop: switching windows, more

A: Press Ctrl+Alt+End, then press t

A: You can set the Windows key combinations to go to the remote computer and use Ctrl-Shift-Esc to launch the Task Manager.
In the remote desktop connection options for Local Resources you have the option of where to apply Windows key combinations (On the local computer, On the remote computer, or only in full screen mode).

A: Or click Start → Run, then type taskmgr.

A: If you just needed to enumerate processes on remote PC, you do not need to establish RDP session.
Take a look at Remote Process Manager http://admintoyssuite.com/l/remote-task-manager--view-and-kill-processes-and-applications-on-network-desktop-computers/
I found this way more flexible than to disturb currently logged on user with RDP connection prompt. Remote Process Manager connects on-the-fly and do not show any question boxes to remote users..

A: AltCtrlEsc will work on Remote Desktop.

A: Ctrl+Shift+Esc doesn't work in windowed (non-full screen) mode. Host Task Manager will be invoked.
Ctrl+Alt+End doesn't work in nested RDP session. Menu for outer RDP session will be displayed.
If you need to start Task Manager to rescue your server in nested session / windowed mode - just switch to full screen mode temporary with Ctrl+Alt+Break where you can use Ctrl+Shift+Esc. This key combination will be send to the most nested RDP session in full screen mode.
Other cool tips: https://blog.codinghorror.com/remote-desktop-tips-and-tricks/

A: You have to use CtrlF3.
The details are on my blog: How to Open the Task Manager on Remote Computer or Desktop

A: In nested remote desktop sessions the shortcut CTRL+ALT+Home brings up the taskmanager of the 1st remote Windows.
To invoke the taskmanager of the 2nd remote Windows I use the On-Screen Keyboard of the 1st remote Windows.


text:
Q: Finding inverse of a composite function Let $f (x) = x^{3}+x$ and $g (x) =x^{3} -x$ for all x.
I have to find derivative of $g\circ f^{-1}$ at $x=2$.
My textbook did this:
$(g \circ f^{-1})' (2) = \lim \limits_{h \to 0} \dfrac{g \circ f^{-1}(2 + h) - g \circ f^{-1}(2)}{h}$
$ = \lim \limits_{h \to 0} \dfrac{g(1 + \frac{h}{4}) - g(1)}{h}$
$= \lim \limits_{h \to 0} \dfrac{(1 + \frac{3h}{4}) - (1 + \frac{h}{4}) - 0}{h} $
$= \dfrac{1}{2}$
Can anyone please explain second step?

A: $f'(2)=4$, so $\bigl(f^{-1}\bigr)'\bigl(f^{-1}(2)\bigr)=\dfrac{1}{4}$. Btw, there's a typo at the beginning of the formula: it's $\bigl(g\circ f^{-1}\bigr)'(2)$ that is being computed.
More generally, you can prove that
$$\bigl(g\circ f^{-1}\bigr)'(x)=\dfrac{g'\bigl(f^{-1}(x)\bigr)}{f'\bigl(f^{-1}(x)\bigr)
}. $$
Indeed, the chain rule results in$$\Bigl(g\circ f^{-1}\Bigr)'(x)= g'\bigl(f^{-1}(x)\bigr)\cdot\bigl(f^{-1}\bigr)'(x)= g'\bigl(f^{-1}(x)\bigr)\cdot\frac{1}{f'\bigl(f^{-1}(x)\bigr)} $$
since $\bigl( f^{-1}\bigr)'(x)= \dfrac{1}{f'(y)}$, where $f(y)=x$.

A: Using $f^{-1}\circ f=\operatorname{id}$ and applying the chainrule we find:
$$g'\left(x\right)=\left(g\circ f^{-1}\circ f\right)'\left(x\right)=\left(g\circ f^{-1}\right)'\left(f\left(x\right)\right)f'\left(x\right)$$
Divide by $f'(x)$ to achieve: $$\left(g\circ f^{-1}\right)'\left(f\left(x\right)\right)=\frac{g'\left(x\right)}{f'\left(x\right)}$$
Substitute $f^{-1}(x)$ for $x$ to achieve on base of $f\circ f^{-1}=\operatorname{id}$: $$\left(g\circ f^{-1}\right)'\left(x\right)=\frac{g'\left(f^{-1}\left(x\right)\right)}{f'\left(f^{-1}\left(x\right)\right)}$$


text:
Q: Ошибка с DNS именем Встретился с ошибкой на новой RDS ферме. Создал новую RDS ферму HA на базе Windows Server 2016, все обновил. При попытке подключения по короткому имени terminal я получаю ошибку:
"The connection cannot be completed because the remote computer that was reached is not the one you specified. This could be caused by an outdated entry in the DNS cache. Try using the IP address of the computer instead of the name."
Ранее я уже сталкивался с данной ошибкой и решал ее одним из методов описанных в статье. Но ничего не помогло, подробнее опишу инфраструктуру и что делал.
Есть кластер Vmware ESXI 6.5 на физических серверах Dell R740. Вся RDS ферма состоит из виртуальных серверов.

*

*Я проверил, что виртуальные машины не берут время с железного сервера, в VMware Tools это отключено

*Я проверил, что время на контроллере домена полностью совпадает с временем на серверах

*Я пробовал чистить везде кэш DNS, как на самой DNS зоне, так и локальный кэш

*Проверял утилитой dig, что запрос идет правильно к DNS серверу

*PTR записи есть для данного имени входа на RDS

*Включал логирование на DNS сервере и видел по логам, что имя корректно разрешалось

*Пробовал Linux утилитами сделать трассировку DNS, запрос идет к нужному DNS кластеру

*На самом DNS сервере имя разрешается корректно, но короткое имя так же выдает туже ошибку

Если я пытаюсь зайти по FQDN имени terminal.domain.com, то меня спокойно пускает на RDS ферму, и по IP также. Еще интересный факт, что если я подключаю VPN соединение до локальной сети, и пытаюсь зайти по короткому имени, то все работает и ошибка только в рамках внутренней локальной сети, что еще можно проверить и диагностировать. Утилита nslookup разрешает корректно, как ip так и dns имя. Буду рад любой помощи.
Еще интересно, если я просто беру это короткое имя направляю в DNS на любой компьютер, то ошибка выскакивает та же самая, видимо где то есть какое-то старое значение.

A: В итоге разобрался, все дело было с SPN записью


text:
Q: How to custom output of powershell function I am writing a small function to get the file sizes in several pathes. And I have a problem about the function output. Here is my script:
function Get-FileSize {
    param (
        [Parameter(Mandatory,
                   ValueFromPipeline)]
        [string[]]$Path
    )
    PROCESS {
        foreach ($p in $Path) {
            Get-ChildItem -Path $p |
            ForEach-Object {
                $size = (Get-ChildItem -LiteralPath $PSItem -Recurse | Measure-Object -Sum Length).Sum + 0
                [PSCustomObject]@{
                    Name = $_.Name
                    Size = $size
                }
            }
        }
    }
}

This function will output several pscustomobjects. The size property is very hard to read, so I format the size property like this:
Size = "{0:N2} GB" -f $size

While this version is very easy to read, I can not be sort through the size property because the type of this property is string.
My problem is how can I custom the display style of pscustomobject's property?
For example, the command Get-Volume has a nice output.

A: After reading related topic about Format.ps1xml mentioned by @Olaf, I have solved the problem.
First, I create a customized Format.ps1xml:
<?xml version="1.0" encoding="utf-8"?>
<Configuration>
    <ViewDefinitions>
        <View>
            <Name>FileSizeView</Name>
            <ViewSelectedBy>
                <TypeName>MyType.FileSizeInfo</TypeName>
            </ViewSelectedBy>
            <GroupBy>
                <PropertyName>Path</PropertyName>
            </GroupBy>
            <TableControl>
                <TableHeaders>
                    <TableColumnHeader>
                        Name
                        <Width>50</Width>
                        <Alignment>left</Alignment>
                    </TableColumnHeader>
                    <TableColumnHeader>
                        Size
                        <Width>15</Width>
                        <Alignment>right</Alignment>
                    </TableColumnHeader>
                </TableHeaders>
                <TableRowEntries>
                    <TableRowEntry>
                        <TableColumnItems>
                            <TableColumnItem>
                                <PropertyName>Name</PropertyName>
                            </TableColumnItem>
                            <TableColumnItem>

                            </TableColumnItem>
                        </TableColumnItems>
                    </TableRowEntry>
                </TableRowEntries>
            </TableControl>
        </View>
    </ViewDefinitions>
</Configuration>

Second, add the new format file to the current session Update-FormatData \path\to\file\MyView.Format.ps1xml.
Third, before I return the pscustomobject in my function, I add the TypeName to it. The TypeName is defined in node <ViewSelectedBy>. Here is the function:
function Get-FileSize {
    param (
        [Parameter(Mandatory,
                   ValueFromPipeline)]
        [string[]]$Path
    )
    PROCESS {
        foreach ($p in $Path) {
            Get-ChildItem -Path $p |
            ForEach-Object {
                $size = (Get-ChildItem -LiteralPath $PSItem -Recurse -File | Measure-Object -Sum Length).Sum + 0
                $object = [PSCustomObject]@{
                    Name = $_.Name
                    Size = $size
                    Path = $p
                }
                $object | Add-Member -TypeName 'MyType.FileSizeInfo'
                return $object
            }
        }
    }
}


text:
Q: Word problem: a system of equations Can someone please help me. I'm having a hard time answering this question.

At a country fair, adults' tickets sold for £5.50, senior citizens' tickets sold for £4.00, and children's tickets sold for £1.50. On the opening night, the number of children's and seniors' tickets sold was 30 more than the number of adults' tickets sold. The number of senior citizens' tickets sold was 6 more than four times the number of children's tickets. Total receipts from the ticket sales were £14967. How many of each type of tickets were sold?

A: After putting the ticket prices in, and moving the terms around a bit, you have the equations
$$
\left\{
\begin{array}{ccclr}
-A + &S &+ C &= 30 & (1)\\
&S &- 4C &= 6 &(2)\\
5.50~A&+4.0~S&+1.50~C &= 14~967 & (3)
\end{array}
\right.
$$
Now we have to use elimination to solve for the three variables. We can multiply the row (2) by $-1$ and add it to (1) to get
$$\tag{4}
-A + 5C = 24
$$
Another way to get rid of the $S$ is to multiply row (1) by 4 and then subtract row (3) from it to get
$$ \tag{5}
9.5 A -2.5C = 14~847
$$
If you multiply Equation (4) by 9.5 and add that to equation (5), you get
$$
45 C = 15~075 \qquad \Rightarrow \qquad C = 335
$$
You can use this result in Equation (4) to solve for $A$. Can you continue from here?


text:
Q: CSS in a iFrame: it shows CSS code instead of loading and applying it I have an iFrame on a PHP page that in some cases and in just some browsers in some machines, instead of loading the CSS normally and aplying the style over the iFrame contents, it just shows the CSS code in a plain text mode.
Does anyone know why this could be possible?
Normal way should be, PHP page loading the iframe, this last one loading the content normally and everything appearing beautifully styled inside this iFrame. But as I said, in Chrome in a machine from a specific user (and just him) it doesn't work this way. Instead of this, we see the CSS code inside the iframe when PHP page finishes loading.

A: Check the headers that are being sent on the iframe's http request, specifically the "Content-Type" header. In some cases, a document that is served as text/plain will not render properly as HTML and CSS. Instead, you will just see the raw code.
This can also happen if your web server is not parsing the file as PHP, but just a plain text file. For example, try renaming a .php script to .myphp and then visit the URL in your browser. You will probably see the PHP source code and maybe even unprocessed HTML and CSS.


text:
Q: In Spring Boot, Can we add @Service Annotation for Interface? if that interface is not implemented by any class I created a interface which has not any implementations
@Service
public interface MyInterface{

    default void doSomething{
      System.out.print("print something");
    }
}

Can MyInterface be annotated by @Autowired?
@Autowired
MyInterface myInterFace;

following error displayed when it run
***************************
APPLICATION FAILED TO START
***************************

Description:

Field myInterFace in com.example.demo.controller.corejava.CoreJavaController required a bean of type 'com.example.demo.controller.corejava.MyInterface' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)

A: No you can't, because Spring tries to instantiate it to create a Bean (@Service), but it's an Interface, so thats not possible.


text:
Q: const leading to "formal parameter different from declaration" warning I have seen multiple questions (this one, for example) on this subject, but none explain the precise behavior I am seeing.
I have two functions, each declared and defined as such:
void PntCreate(Handle *cv);
void PntCreate(Handle * const cv)
{
    //...
}

ErrorCodes wim2Read(const char *fileName, cdCanvas *cv,
                    int onViewport);
ErrorCodes wim2Read(const char * const fileName, cdCanvas * const cv,
                   const int onViewport)
{
    //...
}

The declarations and definitions change only the const qualifiers. From the question linked above, I understand that can lead to warnings since they don't match perfectly. However, what I find curious is that the warning only appear for PntCreate, but not for wim2Read.
What is happening here? I thought it might be because the argument of PntCreate is a struct, but so is the second argument of wim2Read...

A: Your problem is that cv in the definition of wim2Read is a pointer to Canvas instead of a pointer to cdCanvas. The const in both PntCreate and wim2Read has no effect on the contract between the caller and the implementation since parameters are passed by value.


text:
Q: simplest possible way to prove chain rule for second derivative Given $\phi=\phi(u)$ and $u=u(x)$
What is the simplest possible way to prove
$$
\frac{d^2\phi}{dx^2}=\bigg(\frac{du}{dx}\bigg)^2.\frac{d^2\phi}{du^2}+\frac{d^2u}{dx^2}.\frac{d\phi}{du}
$$

A: Have you tried just iterating the chain rule for the first derivative? It's the first thing that comes to mind and a simple computation does the trick.
Hope that helps,

A: by repeated application of the chain rule:
$$
\frac{d^2\phi}{dx^2}=\frac{d}{dx}\big(\frac{d\phi}{dx}\big)=\frac{d}{dx}\big(\frac{d\phi}{du}\frac{du}{dx}\big)=\frac{d}{dx}\big(\frac{d\phi}{du}\big)\frac{du}{dx}+\frac{d\phi}{du}\frac{d^2u}{dx^2}=\frac{du}{dx}\frac{d}{du}\big(\frac{d\phi}{du}\big)\frac{du}{dx}+\frac{d\phi}{du}\frac{d^2u}{dx^2}=\frac{d^2\phi}{du^2}\big(\frac{du}{dx}\big)^2+\frac{d\phi}{du}\frac{d^2u}{dx^2}
$$
where $\frac{d}{dx}=\frac{du}{dx}\frac{d}{du}$


text:
Q: How to disconnect any clients still connected and close the server? I have to implement (in the server side) the quit command which disconnects any clients still connected and closes the server.
Here the server code.
public class Server {

    public static void main (String args []) {
        if (args.length < 1) {
            System.err.println("Usage: java Server <port>");
            return;
        }
        int port = Integer.parseInt(args[0]);

        try {
            ServerSocket listener = new ServerSocket(port);
            Files input = new Files();

            while (true) {
                System.out.println("Listening...");
                Socket s = listener.accept();
                System.out.println("Connected");

                Thread clientHandlerThread = new Thread(new ClientHandler(s,input));
                clientHandlerThread.start();
            }
        } catch (IOException e) {
            System.err.println("Error during I/O operation:");
            e.printStackTrace();
        }
    }
}

how can the server accept command line instructions while it is running?

A: First of all, you have to keep track of all the clients that you create by putting their instances in a list so that when you're going to shutdown everything, you could access them and tell them to finish their job.
And about how to tell the thread instances to do that, you should call their interrup() method to inform them that they should finish/stop whatever it's doing. Calling the interrupt() method on a thread leads an InterruptedException in the thread that you should handle and gracefully finish whatever you're doing.
For example if you have something like this in the run method of your ClientHandler:
while (true) {
    try {
        Thread.sleep(interval);
    } catch (InterruptedException e){
        Thread.currentThread().interrupt();
        System.out.println(
                "We've been asked to finish up the communication. Bye! ;)");
    }
    // do your business
}

This was of course a very simplified scenario to demonstrate the overall approach. You should be able to find tons of tutorials online about how to use the interrupt.


text:
Q: How to bring back auto scroll in Chrome? How to bring back auto scroll in Chrome ?
I'm really addicted to this feature and I feel like I'm missing a hand browsing without this feature.
Can I do this in Chrome ?
I'm using Ubuntu 13.10.

A: There is an Autoscroll extension:

After adding the extension, you might have to restart Chrome for the function to kick in.
Note that Chrome will, by default, continue running even if you have closed all open Chrome windows.
Make sure you have completely closed Chrome by checking that there is no Chrome icon in the top panel and/or that there are no Chrome processes in System Monitor.
Then, re-launch Chrome, and the extension will be working.


text:
Q: Redis start as service [unrecognized service error] I  install redis on Ubuntu 14.04.  I want to start redis as service. but I can't do that.
firstly , I cant start and stop redis server by using following commands:
sudo /etc/init.d/redis-server start
sudo /etc/init.d/redis-server stop

But I try  following command to start as service  , I get  "redis-service: unrecognized service"
sudo service redis-service start

I wait your helps, thanks

A: If you've used the defaults, your Redis service is actually named redis_6379 - try the following:
sudo service redis_6379 start

A: try: sudo service redis-server start

A: I think,to configure redis as service,you need to execute below line.
sudo update-rc.d redis-server defaults

A: in your shell, use this command:  redis-cli shutdown
or
into folder src use: ./redis-server


text:
Q: Statistic Book About Spearman Correlation Could you recommend me a book or scientific article that explains the interpretation of the results of a Spearman correlation analysis (SC)? For example, I need a reference in the literature that says:
SC = 0.5 is weak
SC < 0.7 is average
SC > 0.8 is strong
SC > 0.9 is very strong
I need it for a research paper, then to be something more "serious" than a web site.
[UPDATED after whuber´s help]: To be more specific, I'm using SC to evaluate an Information Retrieval System. I need to "correlate" the Rank result of my system against a rank calculated by some specialist.


text:
Q: .arrow class styling in bootstrap priority I have some form elements in my webpage, and I am displaying popovers when the user makes a custom error that the database won't recognise- such as small usernames and the kind. I tried removing the popover arrow using:

(Relevant HTML)

<label for = "username" class = "visible-xs">Username</label>
<input type = "text" id = "username" class = "form-control in-image hidden"
placeholder = "Username" autocomplete = "off" data-container = "#one"
data-toggle = "popover" data-placement = "auto bottom" data-content = "Username Too Short">

(Relevant CSS)

.popover-content {
color: red;
font-size: 15px;
padding-top: 2px;
padding-bottom: 2px;
background-color: #ff9;
}

.arrow {
display: none;
}

After I show the popover, the arrow is still displayed, and my arrow class has a lower priority than bootstrap classes. I have added the stylesheets properly, ie, my sheet after the bootstrap sheet, and yet this happens. (Hope the image is clear).

I found some answers on how to target the arrow class and it uses something like .popover > .arrow, but why doesn't this method work?


text:
Q: Model refresh if hasMany does not exist Information
So I have things setup like this
category
    posts: hasMany {async: true}

Now I have lots and lots of categories.
I request all the categories from the server. In the response I don't include the posts fields because I'd need to query the server for all the ids of the posts that are related to the category. To get my response into something like this:
categories: [{ other fields...., posts: [1,2,4,54,5]}, .... ]
Anyway, I have another route that is for a specific category. For that I query the posts and do include it in the response.
However, if I am coming from the route that lists all the categories. That specific category is already loaded into the store and so it doesn't query for it. Issue is that it doesn't have the posts data.
Question
How can I check if a field was present in a response or not, and subsequently do a model refresh to get the right data.

A: Since your hasMany relationship is async, Ember Data won't query /posts endpoint for related posts until you issue category.get('posts') or try to render category.
Always Include Posts IDs
This way Ember Data handles the rest.
Merge posts Field Whenever You Have to
Look at Store#update
Whenever you have posts ids
store.update('category', {id: categoryID, posts: [postIDs]})`

Check if Category has any Posts and if It doesn't Reload It
To check if posts association is empty
category.get('posts').then(function(posts){
  posts.get('length') > 0;
});

And to reload it
category.get('posts').then(function(posts){
  if(posts.get('length') > 0){
    store.find('category', category.get('id'));
  }
});


text:
Q: Proxy error: Could not proxy request /api/products from localhost:3000 to http://localhost:5000/ Многие сталкивались с этой проблемой и решением было "proxy": "http://localhost:5000/",

Но мне к сожалению не помогло и дальше выдаёт ошибку
Could not proxy request /api/products from localhost:3000 to http://localhost:5000/.


text:
Q: How to get tap location when using scaleEffect I have a ZStack with an Image and a small circle, and some gestures for panning and zooming in/out on the Image.  I want the small circle to change location based on where the user taps.  Everything is working fine until I start zooming in with scaleEffect.  How can I account for the current scale value when placing the circle? (See TODO: Fix tap point when scaled for where the issue is.)
struct PodMapTest: View {

    @State var circlePosition = CGPoint.zero
    @State var position = CGSize.zero

    @State var scale: CGFloat = 1.0
    @State var lastScaleValue: CGFloat = 1.0

    @State var tapPoint: CGPoint = CGPoint.zero
    @State var dragSize: CGSize = CGSize.zero
    @State var lastDrag: CGSize = CGSize.zero

    @GestureState private var dragOffset = CGSize.zero
    var body: some View {
        VStack {
            Spacer()
            ZStack {
                Image("floorPlan")
                    .resizable()
                self.circle
            }
            .scaledToFit()
            .animation(.linear)
            .scaleEffect(self.scale)
            .offset(self.dragSize)
            .gesture(MagnificationGesture().onChanged { val in
                let delta = val / self.lastScaleValue
                self.lastScaleValue = val
                self.scale = self.scale * delta

            }.onEnded { val in
                // without this the next gesture will be broken
                self.lastScaleValue = 1.0
                }

            )
                .simultaneousGesture(DragGesture(minimumDistance: 1, coordinateSpace: .local).onChanged({ val in
                    print("dragging map")
                    self.tapPoint = val.startLocation
                    self.dragSize = CGSize(width: val.translation.width + self.lastDrag.width, height: val.translation.height + self.lastDrag.height)
                })
                    .onEnded({ (val) in
                        self.dragSize = CGSize(width: val.translation.width + self.lastDrag.width, height: val.translation.height + self.lastDrag.height)
                        self.lastDrag = self.dragSize
                    }))
                .simultaneousGesture(DragGesture(minimumDistance: 0, coordinateSpace: .local).onChanged({ (val) in

                        // TODO: Fix tap point when scaled
                        let tapPoint = CGPoint(x: val.startLocation.x - self.dragSize.width, y: val.startLocation.y - self.dragSize.height)
                        self.circlePosition = tapPoint
                }))
            Spacer()
        }
    }

    var circle: some View {
        Circle()
            .frame(width: 20, height: 20, alignment: .center)
        .position(circlePosition)
    }
}


text:
Q: Basic data types not recognized in IDL v.8.7.2 My IDL installation (currently v.8.7.2, but the same problem occurred in v.8.5) does not recognize hash, list, dictionary and orderedhash. For example, typing
h = HASH('Id', 1234)

results in the error "Variable is undefined: HASH.". I am at my wits end. All kinds of other things are working with no problems, I don't seem to have issues with my path or with external libraries. What's going on??

A: My guess is that your path is not correct, that it is pointing at the IDL lib directory of an older (pre-hash, list, etc) IDL's lib directory. Could you print !path?


text:
Q: How to write a query to get all documents where field doesn't matches I am having some trouble writing a query where I want to get all documents where they don't have a single subdocument where its property IsCurrentRevision is true. In other words, only getting documents that don't have a single revision marked as current.
What I have so far is:
{StartTimeUtc: {$gte: new ISODate('12/14/2019')},
EndTimeUtc: {$lte: new ISODate('01/21/2020')},
IsDeleted: false, 'MyDocument.IsCurrentRevision': false,
"MyDocument.1.IsCurrentRevision" : {$exists: false}}

This gets me somewhere, but the issue is that I have to manually query the index. In this case, the above query returns all documents with only 1 revision (so only one element in the sub document array), that doesn't  have its revision marked as current. Thus if I wanted to get documents that have 2 revisions, with the second one marked as false as well I would need to update the query to be:
{StartTimeUtc: {$gte: new ISODate('12/14/2019')},
EndTimeUtc: {$lte: new ISODate('01/21/2020')},
IsDeleted: false, 'MyDocument.1.IsCurrentRevision': false,
"MyDocument.2.IsCurrentRevision" : {$exists: false}}

This is obviously tedious, is there a better way? If it helps, I am using Mongo Compass
Edit:
Here is how my document looks like
{
  _id: Guid,
  TemplateId: guid,
  StartTimeUtc: DateTime,
  EndTimeUtc: DateTime
  ..
  ..
  SoapNoteRevisions: Array {
      _id: Guid,
      IsCurrentRevision: boolean,
      ..
      ..
    }
}

I got rid of the unneeded bits as the document itself has a fair bit of fields within the revision as well (another sub array)

A: If you need documents where MyDocument elements/objects doesn't have IsCurrentRevision : true, try below query :
db.collection.find({'MyDocument.IsCurrentRevision': {$ne : true}})

If using aggregation :
db.collection.aggregate([{$match : {'MyDocument.IsCurrentRevision': {$ne : true}}}])

Collection Data :
/* 1 */
{
    "_id" : ObjectId("5e27282ad02e05b69498b814"),
    "MyDocument" : [
        {
            "IsCurrentRevision" : false
        },
        {
            "IsCurrentRevision" : false
        },
        {
            "IsCurrentRevision" : false
        }
    ]
}

/* 2 */
{
    "_id" : ObjectId("5e272839d02e05b69498b947"),
    "MyDocument" : [
        {
            "IsCurrentRevision" : true
        },
        {
            "IsCurrentRevision" : true
        },
        {
            "IsCurrentRevision" : true
        }
    ]
}

/* 3 */
{
    "_id" : ObjectId("5e272846d02e05b69498ba5c"),
    "MyDocument" : [
        {
            "IsCurrentRevision" : false
        },
        {
            "IsCurrentRevision" : true
        },
        {
            "IsCurrentRevision" : false
        }
    ]
}

Result :
/* 1 */
{
    "_id" : ObjectId("5e27282ad02e05b69498b814"),
    "MyDocument" : [
        {
            "IsCurrentRevision" : false
        },
        {
            "IsCurrentRevision" : false
        },
        {
            "IsCurrentRevision" : false
        }
    ]
}


text:
Q: Maximizing Log Function Involving Absolute Value
Let $1\leq a < \infty$ and $0<b<1$. Define
$$f(x) = \log(1+ax-|x|b) + \log(1-x-|x|b)$$ for $-1/(a+b) < x < 1/(1+b).$
I would like to find $x$ which maximizes $f(x)$.

Since the two terms, $1+ax - |x|$ and $1-x-|x|b$ are both concave and positive, taking log on both terms preserves concavity. Since the sum of two concave functions is still concave, we have $f(x)$ is concave. Hence, all I need is to find a local maximizer.
Then my naive approach to do so is to simply take the first derivative of $f(x)$:
$$
\frac{d f}{d x} =  \frac{a-b \frac{x}{|x|} }{  {1 + ax- |x|b  } } +  \frac{-1-b\frac{x}{|x|}}{  1-x - |x|b  }
$$
and then set the derivative above equals to zero to find the maximizer candidate. But then I got stuck on handling the absolute value $|x|$. I was thinking I have to separate into two cases for $x>0$ and $x<0$ but not quite sure this is the right thing to do. Any suggestion is appreciated.

A: The derivative of $|x|$ is equal to $\frac{|x|}{x}$ if $x\neq 0$, that is, to $+1$ if $x>0$ and to $-1$ if $x<0$. Using this, you can calculate the derivative for $x>0$ and for $x<0$ as follows:
$$f'(x)=\frac{-1-b}{1-x-bx}+\frac{a-b}{1+ax-bx}\quad x>0$$
$$f'(x)=\frac{-b-1}{1-x+bx}+\frac{a+b}{1+ax+bx}\quad x<0$$
and so for $x>0$, the derivative vanishes if and only if $x=\frac{a-1-2b}{2(a-b)(b+1)}$, whereas for $x<0$, the derivative vanishes if and only if $x=\frac{1-a-2b}{2(a+b)(b-1)}$.

A: You have two fractions. Add them together using $$\frac ab +\frac cd=\frac{ad+bc}{bd}$$ and then set the numerator to $0$ to see what $x$ satisfies the equation.


text:
Q: How do I replace Pulseaudio? Previous answers refer to previous versions of Ubuntu.
I'm having the same issues and dislikes with Pulseaudio in Natty as I had with previous versions of Ubuntu, so I want to replace it with something else.
I'm looking for references to step-by-step instructions by someone that succeeded in the replacement. ALSA or OSS are fine.
I don't care about the loss of integration, because it can be patched. I just want the (for me) ill-behaved pulseaudio out of my system.

A: I just went ahead and apt-get removed pulseaudio. Sound worked fine where it matters:

*

*System events

*Banshee

*Skype

To regain sound control from my keyboard, I installed AutoKey, and attached the following scripts to the corresponding keyboard keys:
#Volume Down
from subprocess import call
call('amixer set PCM 2dB-'.split())

and
#Volume Up
from subprocess import call
call('amixer set PCM 2dB+'.split())

and
#Mute-Unmute
from subprocess import call
call('amixer set PCM toggle'.split())

A: I've faced the same issue and have erased pulseaudio full package as well. Then i've installed AlsaMixer full package. you can look for it on synaptic.
When you erase pulseaudio on synaptic, other dependencies would be necessary to erase as well, like Ubuntu-desktop. That will erase sound icon on the tray.
To resolve this, you will have to install AlsaMixer, then put the AlsaMixer icon on the unity panel to control your sound board easily.
Removing Pulseaudio and installing Alsamixer
Hope this will help you.


text:
Q: MobaXterm - ssh to Linux server with gnome, set DISPLAY, "Connection refused" ubuntu@dsps-pi-k8s:~$ export DISPLAY=slapa:0.0
ubuntu@dsps-pi-k8s:~$ startx

/usr/lib/xorg/Xorg.wrap: Only console users are allowed to run the X server
xinit: giving up
xinit: unable to connect to X server: Connection refused
xinit: server error
Couldn't get a file descriptor referring to the console.

But I can see MobaXterm listening on port 6000, the usual X Display server port, and it's not a firewall problem, since: -
ubuntu@dsps-pi-k8s:~$ telnet slapa 6000
Trying 192.168.1.237...
Connected to slapa.
Escape character is '^]'.
^]
telnet> quit
Connection closed.

I'm sure this is what I used to do with HummingBird Exceed and other X servers before.

A: startx is the wrong tool here, as its purpose is to start X clients and an X server. You don't need that – the whole point of setting $DISPLAY was so that your programs would use an existing X display on another system, whereas "startx" always tries to launch a new one. (Usually it tries to start Xorg for rendering on the SSH server's monitor, which isn't going to work via SSH even if that were what you wanted.)
As you already have an X display server available (via $DISPLAY), you should be starting only the X client apps. For many programs this can be done without any special tools; you just run xterm & or firefox & through the SSH connection.
(To start an entire GNOME session you'd run dbus-run-session gnome-session &, although I don't expect GNOME to run all that well over networked X11 – you'll probably need to use Xvnc instead.)
To start the same X clients that startx would've started, you could manually run the ~/.xinitrc script, or /etc/X11/xinitrc if you don't have a custom one.


text:
Q: SQL nest tables Currently I have a table:

ItemCode  OldItem NewItem Usage
A                 B       3
B         A       C       1
C         B       D       5
D         C               1
E                         8

OutPut
ItemCode     Usage
D             10
E             8

Can you please help with SQL Query?  I have about 2000 Items that I need to add total usage based on the newItem link

A:
D= C Usage + B Usage + A Usage because they are linked based on old
  parts

I do not see how they "are linked" unless you are trying to indicate this is some form of hierarchy. I suspect you need to be more literal with how you decide to store old/new item values so that a hierarchy isn't involved. e.g.
ItemCode  OldItem NewItem Usage
A                 D       3
B         A       D       1
C         B       D       5
D         C       D       1
E                 E       8

In the meantime perhaps this will help:
SELECT
    CASE
        WHEN coalesce(OldItem,ItemCode) IN ('A', 'B', 'C','D') THEN 'D'
        ELSE ItemCode
    END AS ItemCode
    , SUM(Usage)
FROM yourtable t
GROUP BY
    CASE
        WHEN coalesce(OldItem,ItemCode) IN ('A', 'B', 'C','D') THEN 'D'
        ELSE ItemCode
    END


text:
Q: Getting DIVs to center based upon their parents DIVs? I'm developing a website. I'm creating drop-down lists as menus for the website. I've created hidden divs that appear when you hover over the link in the top menu. However, I can not figure out how to get them to center based upon their parents. I'm assuming it's because they're positioned "absolute," but I don't know how else I could create the hidden DIVs that overlay other stuff without them being absolute. I wouldn't really know what sections of my code to post, so if you want to know what I'm talking about, go to www.theguildwars2hq.com and hover over the links at the top. You'll notice they all start at the left border of the link above them. I'd like them to automatically center around the links, but at the top-offset they're coded. I want them to also automatically be the 100% width of their parents, but every time I try that, it 100%s to another div I'm not even certain of, but I think is "content."
Also, is there a way to make a div automatically create a second column once the div has reached a certain height?
I hope this made some sense, if very little. It's hard to explain my point without having something physical to present and point out.


text:
Q: HttpURLConnection в цикле слишком долго работает, как ускорить? Есть массив ссылок по которому я прохожусь в цикле, из этого массива ссылок мне нужно достать первую которая ответила статусом 200, вот что я для этого делаю:
String[] urls = {some urls...};
URL url;
HttpURLConnection http;
String goodResult = "";
for (String s : urls) {
            url = new URL(s);
            http = (HttpURLConnection) url.openConnection();
            if (http.getResponseCode() == HttpURLConnection.HTTP_OK) {
                goodResult = s;
                break;
            }
        }

Можно ли как то оптимизировать этот процесс и как то ускорить запросы?


text:
Q: What are the prerequisites to run IBM System i Navigator Version 6 on Windows? I'm running IBM System i Navigator Version 6 on Windows 7 with below configuration-:

RAM-: 6 GB
I want to run System i Navigator Version 6 on a 64-bit System. So I want to know whether its possible to run this application on a 64-bit Processor with 64-bit Windows OS?
If answer is no then how can I run System i Navigator Version 6 on a 64-bit System?

A: I can confirm that System i Navigator 6 works just fine on Windows 7 64 bit. There is a 64 bit specific installer that should be included on your install disk, or it can be downloaded from IBM if your maintenance contract is current.
System I Navigator 7 also works fine on Windows 8 and Windows 10, both 32 and 64 bit versions - we use it daily on over 100 machines with a mix of all 3 above OS's.
See here for required PTF level information: http://www-03.ibm.com/systems/power/software/i/access/windows/os.html


text:
Q: Find where a value would lie in a range I have a data frame as such
"X1"    "X2"    "X3"    "X4"    "X5"    "X6"    "X7"    "X8"    "X9"    "X10"   "X11"   "X12"   "X13"   "X14"   "X15"   "X16"   "X17"   "X18"   "X19"   "X20"   "X21"   "X22"   "X23"   "X24"
    13062   145 9   2   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
    586717  66068   18713   7105    3188    1506    750 460 251 141 81  41  39  14  12  6   1   0   1   0   0   0   0   0
    55893   1371    155 43  9   3   3   2   0   2   0   1   0   1   0   1   0   0   0   0   0   0   0   0
    63123   2573    266 35  10  6   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
    14258   63  4   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
    751302  43884   6109    1280    368 123 36  18  6   0   2   1   0   0   0   0   0   0   0   0   0   0   0   0
    45018   1017    89  10  6   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
    182932  6581    941 238 73  43  20  9   6   8   2   1   1   0   0   1   0   1   0   0   0   0   0   0
    23741   356 4   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
    4391    15  0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
    20201   546 75  17  1   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
    48193   943 50  9   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
    11284   89  1   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
    4819    48  2   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0

I am finding the mean for each row
df$mean=apply(df,1,mean)
"X1"    "X2"    "X3"    "X4"    "X5"    "X6"    "X7"    "X8"    "X9"    "X10"   "X11"   "X12"   "X13"   "X14"   "X15"   "X16"   "X17"   "X18"   "X19"   "X20"   "X21"   "X22"   "X23"   "X24"   "mean"
    13062   145 9   2   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   550.75
    586717  66068   18713   7105    3188    1506    750 460 251 141 81  41  39  14  12  6   1   0   1   0   0   0   0   0   28545.5833333333
    55893   1371    155 43  9   3   3   2   0   2   0   1   0   1   0   1   0   0   0   0   0   0   0   0   2395.16666666667
    63123   2573    266 35  10  6   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   2750.54166666667
    14258   63  4   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   596.875
    751302  43884   6109    1280    368 123 36  18  6   0   2   1   0   0   0   0   0   0   0   0   0   0   0   0   33463.7083333333
    45018   1017    89  10  6   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   1922.5
    182932  6581    941 238 73  43  20  9   6   8   2   1   1   0   0   1   0   1   0   0   0   0   0   0   7952.375
    23741   356 4   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   1004.20833333333
    4391    15  0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   183.583333333333
    20201   546 75  17  1   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   868.333333333333
    48193   943 50  9   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   2049.79166666667
    11284   89  1   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   473.916666666667
    4819    48  2   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   202.875

I want to figure out in the range of columns 1 to 24 where the mean would lie.
For example:
If I have x values as 1,2,3,4 and y as 10,20,30,40 . If I were to find value corresponding to 15 in x I would get 1.5 .Here I wish to find out where the mean would lie which could give me a floating point number specifying it lies at column e.g 1.5 .
Update :
Sample Data
X1  X2  X3  X4  X5  X6  X7  X8  X9  X10 mean
10  20  30  40  50  60  70  80  90  100 55

Here mean lies at 5.5 . How can I calculate something similar for the table above.
It can be assumed that the values in each row are sorted.

A: df<-read.table(text="X1    X2   X3    X4    X5  X6    X7    X8    X9    X10   X11   X12   X13   X14   X15   X16   X17   X18   X19   X20   X21   X22   X23   X24
        13062   145 9   2   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
       586717  66068   18713   7105    3188    1506    750 460 251 141 81  41  39  14  12  6   1   0   1   0   0   0   0   0
       55893   1371    155 43  9   3   3   2   0   2   0   1   0   1   0   1   0   0   0   0   0   0   0   0
       63123   2573    266 35  10  6   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
       14258   63  4   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
       751302  43884   6109    1280    368 123 36  18  6   0   2   1   0   0   0   0   0   0   0   0   0   0   0   0
       45018   1017    89  10  6   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
       182932  6581    941 238 73  43  20  9   6   8   2   1   1   0   0   1   0   1   0   0   0   0   0   0
       23741   356 4   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
       4391    15  0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
       20201   546 75  17  1   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
       48193   943 50  9   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
       11284   89  1   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
       4819    48  2   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0",header=T)

df$mean<-rowMeans(df)

n<-ncol(x)
apply(df,1,function(x) (max(which(x[n]<x[-n]))+min(which(x[n]>x[-n])))/2)

[1] 1.5 2.5 1.5 1.5 1.5 2.5 1.5 1.5 1.5 1.5 1.5 1.5 1.5 1.5


text:
Q: Switching theme only for checkout Is there a way to use a different theme completely for the checkout page for example? I know this can be done for products, categories and pages using the built-in scheduled design change mechanism in the admin, but what about other sections, like My Account, Cart and Checkout?
I'm thinking an observer could do it, but I have no idea which. Ideas?

A: For those, you can use event layout_load_before By using you can Swith theme at checkout.

<?php
namespace Devamitbera\ChangethemeAtCheckout\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Framework\App\ObjectManager;

class ObserverforChangeTheme implements ObserverInterface
{
     /**
     * Design package instance
     *
     * @var \Magento\Framework\View\DesignInterface
     */
    protected $_design;
    /**
     * Store manager
     *
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $_storeManager;
  protected $request;
  protected $logger;
    public function __construct(
        \Magento\Framework\View\DesignInterface $design,
      \Magento\Store\Model\StoreManagerInterface $storeManager,
      \Magento\Framework\App\Request\Http $request,
      \Psr\Log\LoggerInterface $logger
  ) {
        $this->_design = $design;
        $this->_storeManager = $storeManager;
       $this->request = $request;
        $this->logger = $logger;
      }

    /**
     *
     * @param \Magento\Framework\Event\Observer $observer
     * @return void
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
      $controller = $observer->getControllerAction();
      //$this->logger->info($this->request->getFullActionName());
      if($this->request->getFullActionName() =='checkout_index_index'){
          $this->_design->setDesignTheme(1); // Theme id
      }
  }

}

Note that code is not tested:
You can get theme id from  database table theme. Here i have set Magento  theme Magento Blank.

Full module at git https://github.com/devamitbera/Magento2-extension/tree/master/Change%20Theme%20at%20checkojt


text:
Q: How to get my company's proxy transparent? In my company there is a proxy that requires credentials.
I use Windows XP and I want to apply an indirection layer in my tcp/ip stack that makes this completely transparent.
For example it would be nice a software that I can configure with my company proxy and act as I don't have any proxy in my network.
With this software I don't have to configure software that don't consider my default proxy settings done with Internet Explorer.

A: This question is probably over, but in case the subject is still of interest, there are some possiblities with Fiddler, which are outline in the answers to this :
Configuring Fiddler to use company network's proxy? : essentially fiddler is configured to cache the credentials needed to access the internet, and your access from local box goes via fiddler proxy first.


text:
Q: SQL Server Hangs when creating view In SQL Server 2014 when creating a new view SQL Server management studio hangs for about 10 minutes then comes up with the error...

failed to retrieve data for this request. An exception occurred while
  executing a transact-SQL statement or batch. Lock request timeout
  exceeded

We can then create and save a new view as normal. Any ideas why this is happening and how to solve it ?

A: Try unlocking the database before creating your view:
First see if there are any exiting connections:
SELECT request_session_id
FROM   sys.dm_tran_locks
WHERE  resource_database_id = DB_ID('[dbname]')

If there are any open sessions, kill them using:
kill 52

Then use this to unlock the database:
USE [dbname];
ALTER DATABASE [dbname] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

Now you can create the view.
After that, don't forget to change the database to multi user mode:
ALTER DATABASE [dbname]
SET MULTI_USER


text:
Q: Prob. 41, Chap. 1, in Royden's REAL ANALYSIS 4th ed: $\lim\inf a_n \leq \lim \sup a_n$ Here is Prob. 41, Chap. 1, in the book Real Analysis by H.L. Royden and P.M. Fitzpatrick, 4th edition:

Show that $\lim\inf a_n \leq \lim\sup a_n$.

Here $\left( a_n \right)$ is of course a sequence of real numbers. Moreover,
$$
\lim\inf a_n := \lim_{n \to \infty} \inf \left\{ a_k \, | \,  k \in \mathbb{N}, k \geq n \right\} = \sup_{n \in \mathbb{N}} \inf_{k \in \mathbb{N}, k \geq n} a_k,
$$
and
$$
\lim\sup a_n := \lim_{n \to \infty} \sup \left\{ a_k \, |\, k \in \mathbb{N}, k \geq n \right\} = \inf_{n \in \mathbb{N}} \sup_{k\in \mathbb{N}, k \geq n} a_k,
$$
where the $\inf$ and the $\sup$ in each case is taken over the extended real number system.
My Attempt:

For any natural numbers $m$ and $n$ such that $m < n$, we find that
$$
\inf_{k \in \mathbb{N}, k \geq m} a_k \leq \inf_{k \in \mathbb{N}, k \geq n} a_k \leq \sup_{k \in \mathbb{N}, k \geq n} a_k,
$$
and aslo
$$
\inf_{k \in \mathbb{N}, k \geq n} a_k \leq \sup_{k \in \mathbb{N}, k \geq n} a_k \leq \sup_{k \in \mathbb{N}, k \geq m} a_k.
$$

Thus for any natural numbers $n$ and $m$, we have
$$
\inf_{k \in \mathbb{N}, k \geq m} a_k \leq \sup_{k \in \mathbb{N}, k \geq n} a_k.
$$
So for any natural number $m$, we have
$$
\inf_{k \in \mathbb{N}, k \geq m} a_k \leq \inf_{n \in \mathbb{N} }  \sup_{k \in \mathbb{N}, k \geq n}  a_k = \lim \sup a_n,
$$
which in turn implies that
$$
\lim \inf a_n = \sup_{m \in \mathbb{N} } \inf_{k \in \mathbb{N}, k \geq m} a_k \leq \lim \sup a_n,
$$
as required.

Is this proof correct and clear enough in each and every detail? Or, are there any issues with it?


text:
Q: JS setTimeout(alert('hi'), 2252124000); overflow! Генерирую скрипт под события, но когда временной интервал слишком велик, функция вызывается без задержки. Пример кода:
setTimeout(function(){alert('hi')}, 2252124000);

Сталкивался ли кто то с данной проблемой? Как можно ее обойти?

A: Думаю, дело в том, что максимальное значение Signed Integer 32bit равно 2 147 483 647, вы вышли за его пределы