text:
Q: The meaning of Differentials in Integration This is further to the questions discussed in a previous post
Here is an example of what I mean: Suppose that $C$ is a closed path in the plane and consider the line integral of $xy\,dx+x^2\,dy$ over $C$. Note that this can be written as $$\oint_C x\,d(xy)$$
Question: If we let $A$ denote the starting and ending point of the path, is it valid to use "Integration by Parts" to write $$\oint_C x\,d(xy)=x\cdot xy\bigg|_A^A -\oint_C xy\cdot dx=-\oint_C xy\cdot dx$$ Note that the claim is valid, as the sum of the two integrands is $2xy\,dx+x^2\,dy$ which is conservative, being the gradient of $f(x,y)=x^2y$. Therefore the sum of the two integrals in the last equation is zero, hence they are negatives of each other. (And obviously, the second integral will usually be more desirable to compute than the first.)
But what does this mean, and why is it true?
More generally, I think it would insightful to have a discussion about differentials in the context of integration and how/why the Leibniz notation can or cannot be used to intuitively understand calculations such as the above.
And how can we interpret differentials of general quantities which may involve several variables, as opposed to just single ones? Does the expression $d(xy)$ only make sense in the context of a path $C$, where we can view it as the change in $g(x,y)=xy$ over small segments of that curve, or does it admit a broader interpretation?

A: There is a satisfactory modern account of this in terms of differential forms, though it is not the only possible account.  Here $d(xy)$ is a differential 1-form. It is shown in general theory that it safisfies the suitable version of the Leibniz rule. Therefore these manipulations are easily accounted for in that framework. In general, the viewpoint is that what one integrates when path integrals are concerned are not functions but differential 1-forms. One can then interpret the results in terms of functions, but the interpretation is less elegant and sometimes you run into problems, as the problem with the notorious change of sign when you switch $dx$ and $dy$ in multiple integrals.
See Writing Integrals using Differential Forms for a related discussion.


text:
Q: Closed subgroups of $\mathrm{SO}(4)$ My question is quite simple : we know all closed subgroups of $\mathrm{SO}(3)$; is it also known what are the closed subgroups of $\mathrm{SO}(4)$?

A: There is an epimorphism $\mathrm{SU}(2) \times \mathrm{SU}(2) \to \mathrm{SO}(4)$ with the kernel $\langle(−I, −I)\rangle$.  Since $\mathrm{SU}(2)$ is isomorphic to the unit quaternions, the epimorphism is given by $(u,v)\mapsto R_{u,v}$ where $R_{u,v}$ is the rotation of $\mathbb{R}^4$ given by $R_{u,v}(q)=v^{-1}qu$ for any quaternion $q$.
And $\mathrm{SU}(2)$ maps onto $\mathrm{SO}(3)$ with kernel $\langle -I\rangle$; again use quaternions.
As you say, you know the closed subgroups of $\mathrm{SO}(3)$, and so this gives the closed subgroups of $\mathrm{SU}(2)$ and so those of $\mathrm{SU}(2)\times \mathrm{SU}(2)$ (via Goursat's Lemma) and finally those of $\mathrm{SO}(4)$.
More generally, as it relates to semisimple subgroups, all simple subgroups of real Lie groups are known, as described here:
Karpelevič, F. I. The simple subalgebras of the real Lie algebras. Trudy Moskov. Mat. Obšč. 4 (1955), 3–112.
Karpelevič, F. I. Classification of the simple subalgebras of the real forms of classical algebras. Doklady Akad. Nauk SSSR (N.S.) 93, (1953). 613–616.
Karpelevič, F. I. Classification of the simple subgroups of the real forms of the group of complex unimodular matrices. Doklady Akad. Nauk SSSR (N.S.) 85, (1952). 1205–1208.

A: There is a complete list in the paper Mendes, Roberto de Maria Nunes. "Symmetries of spherical harmonics." Transactions of the American Mathematical Society 204 (1975): 161-178. As in the above answer this paper uses the 2 to 1 homomorphism  $\phi:S^3 \times S^3 \rightarrow SO(4)$ . To summarize the construction in the paper for $G$ as subgroup of $SO(4)$ let L and R be the projections of $\phi^{-1}G$ on to the two components, these are closed subgroups of $S^3$  , and $L_K$ and $R_K$ are the normal subgroups $ (L,1) $ and $(1,R)$ of $L$ and $R$. We can then define an isomorphism $\Phi: L/L_K \rightarrow R/R_K$ by $\Phi(l L_K)= rR_k$ where $(l,r) \in \phi^{-1}G$.
Given $L,R, L_K,R_K,\Phi$ we can define $G$ by its action on a quaternion $q$ as
$$
G = \{ g \in SO(4): g(q) = l q r^{-1} , l \in L, r \in R, \Phi(l L_K)= r R_K \}
$$
All the  closed subgroups of $SO(4)$ are enumerated as pairs $(L/L_K; R/R_K)$ a table in the paper.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Convince Apache of the original client protocol So I have a relatively straight forward server stack utilizing a SSL offloading and an HTTP load balancer. The setup looks something like this:
(client) -> (SSL offload - stud) -> (balancer - haproxy) -> (http server - apache)

My question isn't about plugging all this up. It works great, and I'm honestly blown away at how straight forward it has been to set this up. I'll also add that HTTP clients connect directly to haproxy, thereby bypassing the SSL offloaded. And for the record, there are redundant partners for each of the above pieces.
The problem is somewhat abstract. I'll start with a demonstration. The client makes a request through the setup to https://myserver.tld/scp (some headers removed to keep things clear)
GET /scp HTTP/1.1
Host: myserver.tld
(headers added by haproxy)
X-Forwarded-For: [original::client:ip]
X-Forwarded-Proto: https

And the server responds with
HTTP/1.1 301 Moved Permanently
Date: Wed, 03 Jul 2013 03:16:25 GMT
Server: Apache/2.2.15 (CentOS)
Location: http://myserver.tld/scp/
Content-Length: 344
Content-Type: text/html; charset=iso-8859-1

So Apache mod_dir is sending a redirect to the same URL with a trailing slash. It's proper to do so. That isn't the issue. The issue is that the HTTPS protocol was lost. Again, I think Apache is correct to redirect to an HTTP URL, after all, the connection it received from the aforementioned stack is a regular HTTP connection.
So from the perspective of Apache, the client requested a regular HTTP connection. The HTTPS flag is off, along with all other SSL information, because the SSL part of the session is handled by stud.
Although (inside Apache) I have a valid X-Forwarded-Proto header, I cannot find a way to tell Apache that the original client connection was HTTPS and that the directory slash redirect by mod_dir should use the https:// protocol. What am I missing?
The only thing I've come up with is to rewrite the Location header inside haproxy for the HTTPS forwarded connections to replace http:// with https://, but I really don't think that approach is very elegant. I would prefer for Apache (and (don't hurt me) PHP further down the chain) to be informed and treat the connection like a normal HTTPS connection.
Please help!
PS - I've heard it said before if you have to ask, then you're doing it wrong. Perhaps that's the root issue here, but this seems like such a simple dilemma and I feel like the only one ever to have arrived here.

A: *

*The directory slash redirect: What you want is mod_rewrite.
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} =https
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.+[^/])$          https://www.example.com/$1/  [R=301,L,QSA]

If the header is set to https and the requested filename is a directory (-d), then rewrite that (replace example.com with your own domain).

*As for making PHP treat the connection like a normal HTTPS connection, set the environment variable HTTPS to on:
SetEnvIf X-Forwarded-Proto https HTTPS=on

A: You can do this by including the protocol in the ServerName directive:
ServerName https://my-server-name

According to the Apache docs:

Sometimes, the server runs behind a device that processes SSL, such as a reverse proxy, load balancer or SSL offload appliance. When this is the case, specify the https:// scheme and the port number to which the clients connect in the ServerName directive to make sure that the server generates the correct self-referential URLs.


text:
Q: How to compute time complexity of an infinite loop which is sure to end at a point? So I have the following code, for which first I was using a while(true) with breaking it using an if statement with the same condition which is now in my do-while loop.
The code now looks like this:
do {
        for (int i = 0; i < arrayToUse.length; i++) {
            int diff = arrayToUse[i] - number;

            if (diff >= 5) {
                arrayToUse[i] -= 5;
                count++;
                break;
            }

            if (diff >= 2) {
                arrayToUse[i] -= 2;
                count++;
                break;
            }

            if (diff == 1) {
                arrayToUse[i] -= 1;
                count++;
                break;
            }
        }

        if(preCount == count)
            break;

        preCount = count;

    } while (!allElementsEqual(arrayToUse, number));

Here arrayToUse is the array I receive as the input. And the code for allElementsEqual() looks like this:
static boolean allElementsEqual(int[] arr, int num){

    for(int i=0;i<arr.length;i++){
        if(arr[i] != num)
            return false;
    }

    return true;
}

I have timeouts in the code I am using this for, and I am not able to find how can I compute the time complexity of an algorithm that has not really well defined time of end. I am talking about time complexity in Big Oh Notation.
I would appreciate any help.

A: Current Complexity:
Let´s call m the maximum number of the array. Your first loop will run at most N times to find a number that is still greater than num. When it does, it brings it closer to num in at most 5 units. The 2 and 1 unit is not important for the complexity, but the important part is that it will always bring it closer to num.
So when you have changed an element, you break the loop to find the number and then won´t break the do while because the precount will be different than count. Then the allElementsEqual function runs and that is also O(n). So for each run of the do while, you do twice O(n) operations. What remains is how many times can this do while loop run.
It can only stop when all elements are equal, and we said that in each step we bring 1 number closer to num by at most 5. This will mean that for each number in our array, it will run about ((originalNumber[i] - num) / 5) times, and the worst case is on the maximum which was m. So it will take about (m - num) / 5 loops to bring only that number equal to num. If all numbers were the maximum, this would mean that for each number we will do (m - num) / 5 steps to equal it to num.
This gives us (m - num) / 5 steps for each number, there are N numbers and each step costs O(n), all in all giving a complexity of O((m - num) / 5 * N * N). We can remove the /5 and just leave it as O((m - num) * N * N).
As a side note, using while(true) instead of allElementsEqual is the same, because your precount == count if is already taking care of checking that.
Can we do better?
Assuming we remove the allElementsEqual for true, that changes the operation to O(1) instead of O(n) but we still have the loop to find the number not equal to num that is O(n). If we change the i to be initialized at 0 outside the do while so that it does not start at 0 on every step, it will change the operation to O(1) and still work, because the breaks will prevent i from updating until the difference is 0 and when the difference is 0 we don´t care anymore about that number so we can increase i. This changes the algorithm to O((m - n) * N)
Can we do even better?
Instead of bringing the number closer to num with at most 5 units, why don´t we do it all at once? We can count the number of times we will need to reduce it by 5, the times we will reduce by 2 (0, 1 or 2 times) and the times by 1 (0 or 1 time).
int diff = arrayToUse[i] - number;

count += floor(diff / 5) + floor((diff % 5) / 2) + (diff % 5) % 2
arrayToUse[i] = number;

With this, we can do it in O(N) and can´t be done better as we need to read each number. So this is optimal

A: I'd say O(n² + n*m), where n is the length of arrayToUse and m the maximum value contained in the array.
In the worse case you'll have to run the main loop n times to change each element and make it equal to num, as each run seems to be able to update one single element at the time. So we have an external n multiplication factor.
Then we have the cost of each loop, that seems to be O(n + m), as O(n) is the cost of the test and O(m) is the cost of updating each element to descrease it down to num.
So O(n² + n*m).


text:
Q: What does 'shaping touch' mean in this sentence? I found this sentence:

Don't despite training. Even you would be worthless without the shaping  touch of drills and studies.

What does 'shaping touch' mean?

A:
Don't despise training. Even you would be worthless without the shaping touch of drills and studies.

I assume you mean despise (to hold in contempt).

"Shaping" refers to the intention of training. Training shapes the student, in that it aims to provide them with the necessary skills and make them better (at whatever the topic of training is).
"Touch" refers to the input that provides. (In the context of your example, "drills and studies" are considered to be the teaching element, rather than referring to a literal teacher)
This is a figurative usage of the common definitions of "touch":

*

*Come into or be in contact with.

*Handle in order to interfere with, alter, or otherwise affect.

*Affect or concern.

It is similar to "touching on a subject", which is an apt description of what a training intends to do in the first place: get you acquainted with the subject matter.

"Shaping touch" is similar to "guiding hand", in this context.


text:
Q: Keycloak 15.0.2: Getting started: WildFly error "Required mechanism 'KEYCLOAK' is not available in mechanisms [..] HttpAuthenticationFactory I'm trying to follow the 'Getting Started' procedure of the latest (15.0.2) Keycloak.
Using the WildFly 25.0.0.Final,
updated with keycloak-oidc-wildfly-adapter-15.0.2
The WildFly error happens when installing the app-profile-jee-vanilla quickstart sample, while running the command
'mvn clean wildfly:deploy':
19:58:05,514 ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 80) MSC000001: Failed to start service jboss.deployment.unit."vanilla.war".undertow-deployment: org.jboss.msc.service.StartException in service jboss.deployment.unit."vanilla.war".undertow-deployment: java.lang.RuntimeException: java.lang.IllegalStateException: The required mechanism 'KEYCLOAK' is not available in mechanisms [BASIC, CLIENT_CERT, DIGEST, FORM] from the HttpAuthenticationFactory.
at org.wildfly.extension.undertow@25.0.0.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:90)
...

As far as I see the KEYCLOAK mechanism is present in the http-authentication-factory section of standalone.xml config file.
Any idea, why it's not available ?

A: According with this article, to Wildfly 25 it not necessary install any adapder, but the in web.xml the name must be OIDC instead KEYCLOAK.
<login-config>
   <auth-method>OIDC</auth-method>
</login-config>


text:
Q: Detect system hibernate(S4) from .NET Windows Service? I am writing a windows service application in .NET/C#.
My service has to be notified when the system enters in hibernation(S4). How to do this in code?
Looks like ServiceBase.OnPowerEvent() method does not notify about the hibernation(S4) event.


text:
Q: Issue with Cassandra lightweight transaction I am seeing some interesting behavior with Cassandra lightweight transactions in a standalone Cassandra instance. I am using DataStax Enterprize 5.0.2 for my testing. The issue is, a table being updated using lightweight transaction is returning true, which means it is updated. But a subsequent query on the same table shows that the row is NOT updated. Please note that I tried the same in a clustered environment and it worked absolutely fine! So I am just trying to understand what's going wrong in my environment.
Here is a simple example of what I am doing.
I create a simple table as provided below:
CREATE TABLE smart.TOPICSCONSUMERASSNSTATUS (
    TOPNM text,
    PARTID int,
    STATUS text,
    PRIMARY KEY (TOPNM,PARTID)
);

I I put the following set of preload data for testing purpose:
insert into smart.topicsconsumerassnstatus (topnm, partid, status) values ('ESP', 0, 'UNASSIGNED');
insert into smart.topicsconsumerassnstatus (topnm, partid, status) values ('ESP', 1, 'UNASSIGNED');
insert into smart.topicsconsumerassnstatus (topnm, partid, status) values  ('ESP', 2, 'UNASSIGNED');
insert into smart.topicsconsumerassnstatus (topnm, partid, status) values ('ESP', 3, 'UNASSIGNED');
insert into smart.topicsconsumerassnstatus (topnm, partid, status) values ('ESP', 4, 'UNASSIGNED');

Now, I put the first select statement to get the details from the table:
select * from smart.topicsconsumerassnstatus where topnm='ESP';

It lists all partids with status UNASSIGNED. To assign partid 0, I then fire the following update statement:
update smart.topicsconsumerassnstatus set status='ASSIGNED' where topnm='ESP' and partid=0 if status='UNASSIGNED';

It returns true. And now, when I fire the above select query again, it lists all 5 rows with status UNASSIGNED. Interestingly, repeated execution of the update statement keeps returning true all the time - this clearly mean that actual data is not getting updated in the table.
I have seen the query trace as well and the update seems to be working fine as CAS is returned successful.
Also note that this behavior is seen explicitly when a query is used with "allow filtering" at least once, and from then on...
Can anyone please put some lights on what could be the issue? Is it something to do with "allow filtering" clause?


text:
Q: How to side load an image from a service I am currently working on a WordPress plugin that creates dummy content.  I'd like to also have the plugin create random images using a service like http://lorempixel.com.  The problem however is that when accessing the service that an actual file name isn't generated.  You generate a random image like this:
http://lorempixel.com/1200/700/
How can I use the media_handle_sideload() function to accomplish this?

A: Short answer, you don't.  Functions like sideload are for importing images into WordPress itself and using all the normal media library stuff. For images on an external service, use normal img tags.
If you want to copy an image from a URL, you sideload it. Not otherwise.

A: Okay... I've solved this...
@otto - looks like all I had to do was use a bit of curl magic to do this...
code below as part of an advanced wordpress dummy page / post / image / text creator
function render_page() {
    if ($_POST['delete']) {
        $num_posts_deleted = 0;
        $num_images_deleted = 0;
        global $wpdb;

        $SQL = "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wpl_dummy'";
        $rows = $wpdb->get_results($SQL);

        foreach ($rows as $row) {
            $num_posts_deleted++;
            wp_delete_post( $row->post_id, true );
        }

        $SQL = "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wpl_dummy_image'";
        $rows = $wpdb->get_results($SQL);

        foreach ($rows as $row) {
            $num_images_deleted++;
            wp_delete_attachment( $row->post_id, true );
        }

    }
    if ($_POST['create']) {
        $num_posts_created = 0;
        // Build the options array
        $options = array();

        if ($_POST['number_of_paragraphs'])
            $options[] = $_POST['number_of_paragraphs'];

        if ($_POST['paragraph_length'])
            $options[] = $_POST['paragraph_length'];

        if ($_POST['decorate'])
            $options[] = 'decorate';

        if ($_POST['links'])
            $options[] = 'links';

        if ($_POST['ul'])
            $options[] = 'ul';

        if ($_POST['ol'])
            $options[] = 'ol';

        if ($_POST['dl'])
            $options[] = 'dl';

        if ($_POST['bq'])
            $options[] = 'bq';

        if ($_POST['code'])
            $options[] = 'code';

        if ($_POST['headers'])
            $options[] = 'headers';

        if ($_POST['ac'])
            $options[] = 'allcaps';

        if ($_POST['pr'])
            $options[] = 'prude';

        if ($_POST['fi'])
            $featured_image = 1;

        if ($_POST['fi_width'])
            $featured_image_width = $_POST['fi_width'];

        if ($_POST['fi_height'])
            $featured_image_height = $_POST['fi_height'];

        $options = implode('/', $options);

        // Match up
        $args = array(
            'public'=>true
        );
        $post_types = get_post_types( $args, 'objects', 'and' );

        if ( $featured_image )
            require_once( ABSPATH . 'wp-admin/includes/image.php' );

        foreach ( $post_types as $post_type ) {
            if ( $post_type->name != 'attachment') {
                if ( $_POST[$post_type->name]) {
                    for ($i=1; $i <= $_POST['number_of_posts_to_create']; $i++) {
                        // Get the random text
                        $curl = curl_init();
                        curl_setopt_array($curl, array(
                            CURLOPT_RETURNTRANSFER => 1,
                            CURLOPT_URL => 'http://loripsum.net/api/' . $options
                        ));
                        $resp = curl_exec($curl);
                        curl_close($curl);

                        // Massage our data
                        preg_match("/<h1 ?.*>(.*)<\/h1>/", $resp, $matches);
                        $title = $matches[1];
                        $body = str_replace($matches[0], '', $resp);

                        // Create the post
                        $post = array(
                            'post_content'  => $body,
                            'post_title'    => $title,
                            'post_type'     => $post_type->name,
                            'post_status'   => 'publish'
                        );
                        $post_id = wp_insert_post( $post, $wp_error );
                        update_post_meta($post_id, '_wpl_dummy', '1');

                        // Add and attach a featured image if necessary
                        if ( $featured_image ) {
                            $curl = curl_init();
                            curl_setopt_array($curl, array(
                                CURLOPT_RETURNTRANSFER => 1,
                                CURLOPT_URL => 'http://lorempixel.com/' . $featured_image_width . '/' . $featured_image_height . '/'
                            ));
                            $img_raw = curl_exec($curl);
                            curl_close($curl);

                            $upload_dir = wp_upload_dir();

                            // place our file on the server in the appropriate directory
                            $file = $upload_dir['path'] . '/wpl_' . time() . '_dummy.jpg';
                            file_put_contents ( $file , $img_raw );

                            // Check the type of tile. We'll use this as the 'post_mime_type'.
                            $filetype = wp_check_filetype( basename( $file ), null );;

                            // Prepare an array of post data for the attachment.
                            $attachment = array(
                                'guid'           => $upload_dir['url'] . '/' . basename( $file ),
                                'post_mime_type' => $filetype['type'],
                                'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $file ) ),
                                'post_content'   => '',
                                'post_status'    => 'inherit'
                            );

                            // Insert the attachment.
                            $attach_id = wp_insert_attachment( $attachment, $file, $post_id );

                            // Generate the metadata for the attachment, and update the database record.
                            $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
                            wp_update_attachment_metadata( $attach_id, $attach_data );

                            // Update the featured image
                            update_post_meta($post_id, '_thumbnail_id', $attach_id);
                            update_post_meta($attach_id, '_wpl_dummy_image', '1');
                        }

                        $num_posts_created++;
                    }
                }
            }
        }

    }

}
        ?>
obviously more to it but this handles what I was aiming to accomplish.  Thanks for the nudge in the proper direction.


text:
Q: How to calculate CBO and LCOM for a class using Python and SciTools Understand API In Python, how can I calculate LCOM (lack of cohesion) for C++ files (or any other file types) using SciTools Understand API?
For an assignment, we're asked to calculate LCOM ourselves instead of using SciTools's Understand.
To calculate LCOM4, I need the following metrics,

*

*number of functions/methods in a class (given by Understand as "CountDeclFunction")

*number of method pairs in class with at least one instance variable that they commonly use or define in their body.

*number of method pairs in class that have at least one instance method that they commonly call in their body.
Any suggestion is much appreciated.

A: From the metrics listed on https://scitools.com/support/metrics-reports/, I believe you have to develop your own metrics to complement what Understand provides.


text:
Q: Building navbar and I get this error Element type is invalid: expected a string (for built-in components) or a class/function for composite components I'm building a navbar for a project and the above message is telling me to check the render method in my header component. I've tried everything I can think of, including looking through answers on here. Specifically, I tried moving the Header component between my App component and the index.js file Not sure if I need a break or something but in any case, here's my header:
import React from "react";
import Nav from "react-bootstrap/Nav";
import Navbar from "react-bootstrap/Navbar";
import "bootstrap/dist/css/bootstrap.min.css";
import LinkContainer from "react-router-bootstrap";

const header = () => {
  return (
    <Navbar collapseOnSelect expand="lg">
      <LinkContainer to="/App">
      <Navbar.Brand href="/App">
        <img
          src="/PPLogoEdit.jpg"
          width="110"
          height="50"
          className="d-inline-block align-top"
          alt="pikelogo"
        />
      </Navbar.Brand>
      </LinkContainer>
      <Navbar.Toggle aria-controls="responsive-navbar-nav" />
      <Navbar.Collapse id="responsive-navbar-nav">
        <Nav className="mr-auto">
         <LinkContainer to="/App">
          <Nav.Link style={{ color: "yellow" }} href="/App">
            Home
          </Nav.Link>
          </LinkContainer>
          <LinkContainer to="/About">
          <Nav.Link style={{ color: "orange" }} href="/About">
            About
          </Nav.Link>
          </LinkContainer>
          <LinkContainer to="/Gallery">
          <Nav.Link style={{ color: "green" }} href="/Gallery">
            Gallery
          </Nav.Link>
          </LinkContainer>
          <LinkContainer to="/Shop">
          <Nav.Link style={{ color: "blue" }} href="/Shop">
            Shop
          </Nav.Link>
          </LinkContainer>
          <LinkContainer to="Contact">
          <Nav.Link style={{ color: "purple" }} href="/Contact">
            Contact
          </Nav.Link>
        </LinkContainer>
        </Nav>
      </Navbar.Collapse>
    </Navbar>
  );
}

export default header

and the index.js file:
import React from "react";
import ReactDOM from "react-dom";
import 'bootstrap/dist/css/bootstrap.min.css'
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import Header from './components/Header';
import App from "./components/App";
import About from "./components/About";
import Gallery from "./components/Gallery";
import Shop from "./components/Shop";
import Contact from "./components/Contact";

ReactDOM.render(<React.StrictMode>
  <Router>

 <Switch>
   <Route exact path="/" component={App} />
   <Route path="/about" component={About} />
   <Route path="/gallery" component={Gallery} />
   <Route path="/shop" component={Shop} />
   <Route path="/contact" component={Contact} />
 </Switch>
</Router>
</React.StrictMode>, document.getElementById("root"));

Any help is appreciated, thank you!

A: Look at the error messages:

Warning: React.createElement: type is invalid -- expected a
string (for built-in components) or a class/function (for composite
components) but got: undefined. You likely forgot to export your
component from the file it's defined in, or you might have mixed up
default and named imports.

Check your code at Header.jsx:24.
    in Header (at src/index.js:15)
    in Router (created by BrowserRouter)
    in BrowserRouter (at src/index.js:14)
    in StrictMode (at src/index.js:13)

Repeats "Check your code at Header.jsx:XX" for all lines where LinkContainer is used.
It's flagging the LinkContainer you try to import from react-router-bootstrap. You default import it but it should be a named import.
import { LinkContainer } from "react-router-bootstrap";


text:
Q: C# ASP.NET Open a new windows and redirecting in button click event How can i redirect to another page and open a new window in one button click?
protected void ASPxButton_save_Click(object sender, EventArgs e)
{
     try
     {
         //do other stuff

         if (oSoins.DEVENIR_ECVAC_PAR != 0)
         {
             string AdrUrl = "Print_DosSoin.aspx?SoinId=" + Soin_Id;
             ClientScript.RegisterStartupScript(this.GetType(), "newWindow", String.Format("<script>window.open('{0}');</script>", AdrUrl));
          }

          Response.Redirect("DossierSoin_Liste.aspx");
       }
       catch (ThreadAbortException) {/* do nothing, it might be a response.Redirect exception */}
       catch (Exception excThrown)
       {
          lbl_err.Text = excThrown.Message;
          if (excThrown.InnerException != null) lbl_err.Text += "-->" + excThrown.InnerException.Message;
          string TempMsg = "DosSoin Fiche " + Appel_ID + "-- ASPxButton_save_Click -->" + lbl_err.Text;
          Outils.SendingEmail(TempMsg);
        }

With the script above it's redirecting but does not open a new window.
Thank you in advance.

A: You should modify your javascript to the following:
string script = default(string)

if (oSoins.DEVENIR_ECVAC_PAR != 0)
{
    string AdrUrl = "Print_DosSoin.aspx?SoinId=" + Soin_Id;
    script = string.Format("window.open('{0}'); ", AdrUrl);
}

script += " window.location.href = 'DossierSoin_Liste.aspx';";

ClientScript.RegisterStartupScript(this.GetType(), "newWindow", script, true);

This will create a new window then redirect on the client.


text:
Q: DynamoDB JSON or Standard JSON? My old project has data in Standard JSON format in MySQL.
For my completely new project in JS (Node.js) and DynamoDB, about the data in Standard JSON format:

*

*Is it advisable to convert it to DynamoDB JSON?

*What advantages does DynamoDB JSON have over Standard JSON?

*Will it be easier to parse the data?

*Or does it integrate more with other AWS services like AppSync with GraphQL?

*Or is it enough to handle it as a string?

*Is there something I didn't consider?

Standard JSON
{ updated_at: 146548180, uuid: 'foo', status: 'new' }

DynamoDB JSON
{"updated_at":{"N":"146548180"},"uuid":{"S":"foo"},"status":{"S":"new"}}

A: The main benefit of the DynamoDB JSON is that you explicitly set the datatype, which is useful for the internal representation DynamoDB uses, aside from that I don't see any of them. I'm also not aware of any other AWS service that uses the same DynamoDB-JSON flavor.
In my experience, DynamoDB-JSON is just more annoying to work with, because of the additional data conversions it requires.
I prefer to use regular JSON in combination with a JSON-schema in order to enforce data types and format.

*

*Or is it enough to handle it as a string?

That may be advantageous in some use cases, but if you use the DynamoDB-JSON structures, you're able to set additional indexes on the fields and even create attribute-level permissions if you require that.


text:
Q: Why did Sankofa struggle with the leopard? In the novella Remote Control, by Nnedi Okorafor, the protagonist has the ability to emit a green radiation that is lethal to living creatures. Her power is considerable: she can kill everyone within miles, and at close range, outright incinerate several individuals.
However, at one point in the story, she is menaced by a leopard, which is able to resist her power, even approaching to within mere meters of her before falling down dead. The narration even notes that the leopard should have been turned to ash long before it could approach so close to her.
So why did she struggle so much to kill the leopard? Or alternately, why was the leopard able to resist her power for so long?

A: Movenpick her fox companion while wary, was also not affected by her power. This is part of the mystery that brings beauty to Nnedi's story. And what allows us to escape. (what else is the purpose for reading sci-fi?)
In a University of California television interview with her, she explained how her writing process changed over the years and that she is very selective about what is placed on the page. These are not her words, but what I took from part of the interview. Link to the Writer's Symposium by the Sea interview:

possible Spoiler alert below? (although I don't think it's possible to spoil the story, the prose is too enjoyable)
Also, Sankofa'a power is of the alien seed that was gifted or simply came to her from the stars above. It then drew her to find it when it was taken away. Nnedi does not reveal the underlying power of the seed, but allows the reader to take the journey with Fatima.


text:
Q: LEFT OUTER JOIN with no duplicates on left table I've got two tables (let's say "left" and "right" tables). The right table's got from none to several rows matching each row on the left table.
I need to perform a query where I can join the two tables the same way a LEFT OUTER JOIN works, but getting only one row for each existing one in the left table. That row should be the one corresponding to the highest id on the right table.
A NATURAL JOIN would work, but I won't be getting the rows from the left table that don't match any row on the right one.

A: Try this:
 Select L.[ValuesfromLeftTable], ...
        R.[ValuesfromRightTable], ...
 From LeftTable as L
   Left Join RightTable as R
     On R.Id = (Select Max(id)
                From RightTable
                Where FK = L.Id)

A: This is what I would do:
select *
  from `left` as l
    LEFT JOIN `right` as r
       on (l.id = r.left_id)
group by l.id
order by r.id

A: You can use GROUP BY clause to show only distinct records

A: SELECT Left.Field1, Left.Field2, ... Right.Field1, Right.Field2, ...
FROM tblLeft AS Left
LEFT JOIN (SELECT CommonID, Max([ID]) AS MaxID
    FROM tblRight
    GROUP BY CommonID) AS RightMax ON Left.CommonID = RightMax.CommonID
LEFT JOIN tblRight AS Right ON RightMax.MaxID = Right.[ID] AND Left.CommonID = Right.CommonID


text:
Q: Connecting MySQL in a php file and using it in another php file I have a config.php file such as
<?php
/**
 * Database config variables
 */
define("DB_HOST", "blabla");
define("DB_USER", "blabla");
define("DB_PASSWORD", "blabla");
define("DB_DATABASE", "blabla");

?>

And I have a connect.php file such as
<?php

class DB_Connect {

    // constructor
    function __construct() {

    }

    // destructor
    function __destruct() {
        // $this->close();
    }

    // Connecting to database
    public function connect() {
        require_once 'config.php';
        // connecting to mysql
        $con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
        // selecting database
        mysql_select_db(DB_DATABASE);

        // return database handler
        return $con;
    }

    // Closing database connection
    public function close() {
        mysql_close();
    }

}
?>

And I have a functions.php file such as
      <?php

    class DB_Functions {

        private $db;
    //put your code here
    // constructor
        function __construct() {
            include_once 'connect.php';
        // connecting to database
            $this->db = new DB_Connect();
            $this->db->connect();
        }

    // destructor
        function __destruct() {

        }

    /**
     * Storing new user
     * returns user details
     */
    public function insertRecord($name, $email, $gcm_regid, $password) {

        // insert user into database
        $response = array();
        $query0 = "SELECT * FROM gcm_users WHERE name='$name'";
        $result0 = mysql_query($query0);

        if(mysql_fetch_array($result0) == NULL){

    //insert...
            // insert user into database
  $query = "INSERT INTO `gcm_users`(`id`, `gcm_regid`, `name`, `email`) VALUES (NULL,'$gcm_regid','$name','$email');";

  $result= mysql_query( $query);
        // check for successful store
        if ($result) {
            // get user details
      //      $result2 = mysql_query("SELECT * FROM gcm_users WHERE name = '$name'") or die(mysql_error());
            // return user details
      //      if (mysql_num_rows($result2) > 0) {
                $response["success"] = 1;
        $response["message"] = "record added";
    // echo no users JSON
        return $response;

    }else{
        $response["success"] = 0;
        $response["message"] = "No records added";
    // echo no users JSON
        return $response;
    }

}else{
        $response["success"] = 0;
        $response["message"] = "Record already exists";
    // echo no users JSON
        return $response;
    }

}
?>

And I have a simple function that inserts a record but it doesn't work.I think the multiple file connection system has an error transfering the connection but I couldn't find why .Please help me thanks.
By the way I call this method from another file
which includes and calls this method as
 include_once 'functions.php';
 $db = new DB_Functions();
 $res = $db->insertRecord($name, $email, $gcm_regid, $password);
        echo json_encode($res);

Sorry for misleading but I use this connection through an android application and the program is always entering the else part rather than if($result) part.However when I connect without using another config.php and connect.php and just writing everything in the same file as
       <?php

    class DB_Functions {

        private $db;
    //put your code here
    // constructor
        function __construct() {
            include_once 'connect.php';
        // connecting to database
            $this->db = new DB_Connect();
            $this->db->connect();
        }

    // destructor
        function __destruct() {

        }

    /**
     * Storing new user
     * returns user details
     */
    public function insertRecord($name, $email, $gcm_regid, $password) {
       $con = mysql_connect("blabla","blabla","blabla");
  mysql_select_db('blabla');

        // insert user into database
        $response = array();
        $query0 = "SELECT * FROM gcm_users WHERE name='$name'";
  $result0= mysql_query( $query0 , $con);

        if(mysql_fetch_array($result0) == NULL){

    //insert...
            // insert user into database
  $query = "INSERT INTO `gcm_users`(`id`, `gcm_regid`, `name`, `email`) VALUES (NULL,'$gcm_regid','$name','$email');";

  $result= mysql_query( $query , $con);
        // check for successful store
        if ($result) {
            // get user details
      //      $result2 = mysql_query("SELECT * FROM gcm_users WHERE name = '$name'") or die(mysql_error());
            // return user details
      //      if (mysql_num_rows($result2) > 0) {
  mysql_close($con);

                $response["success"] = 1;
        $response["message"] = "products found";
    // echo no users JSON
        return $response;

    }else{
  mysql_close($con);

        $response["success"] = 0;
        $response["message"] = "No products added";
    // echo no users JSON
        return $response;
    }

}else{
  mysql_close($con);

        $response["success"] = 0;
        $response["message"] = "Product already exists";
    // echo no users JSON
        return $response;
    }

}
?>

the $result is returning true and the record is added.In fact there is not error , the situation that the $result variable doesn't turn to be true when I use object oriented connection pattern.

A: I can't comment... anyway...
According to here, "This extension is deprecated as of PHP 5.5.0, and will be removed in the future." Consider using PDO: http://php.net/manual/en/book.pdo.php.
Also, consider checking the connection and database selection with something like this:
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);

if(!$con)
{
  die("Connection issue: " . mysql_error());
}

$db_selection=mysql_select_db(DB_DATABASE);
if(!$db_selection)
{
  die("Database selection issue: " . mysql_error());
}

*mysql_select_db will use the last connection opened with mysql_connect() if you don't pass in the connection you want to use as a second parameter. http://php.net/manual/en/function.mysql-select-db.php
After changing your DB information to suit my test environment, it worked fine so I don't think $this->db->connect(); is the issue. I'd double check that the right DB and table information is being used. Hope this helped a bit... new here.
Also your functions.php file you posted is missing a: }?>. Do you have error reporting turned on? Might want to check that the DB_Functions instance is even being made.


text:
Q: Failed to access MongoDB in container through Flask application So guys n gals, hope you can help me.
So i'm diving into docker containers right now and i try to port my application (flask+mongodb) into two seperate containers. MongoDB container is set up and works great, running a mongoexpress container with a link gives me the access to the database i wished. Now i ported my Flask application and the login page loads fine (so the docker port itself works) but even though i run the container with a link to my database container, i get a server error when i try to load content from the database.
The logs give me the following traceback:
File "/usr/local/lib/python3.7/site-packages/mongoengine/queryset/manager.py", line 37, in __get__
    queryset = queryset_class(owner, owner._get_collection())
File "/usr/local/lib/python3.7/site-packages/mongoengine/document.py", line 190, in _get_collection
    db = cls._get_db()
File "/usr/local/lib/python3.7/site-packages/mongoengine/document.py", line 179, in _get_db
    return get_db(cls._meta.get('db_alias', DEFAULT_CONNECTION_NAME))
File "/usr/local/lib/python3.7/site-packages/mongoengine/connection.py", line 241, in get_db
    db = conn[conn_settings['name']]
File "/usr/local/lib/python3.7/site-packages/pymongo/mongo_client.py", line 1323, in __getitem__
    return database.Database(self, name)
File "/usr/local/lib/python3.7/site-packages/pymongo/database.py", line 107, in __init__
    "of %s" % (string_type.__name__,))
TypeError: name must be an instance of str

So my Flask-MongoEngine is set up like:
app = Flask(__name__)
app.config["MONGODB_DB"] = 'database-name'
db = MongoEngine(app)

Basically my database should be available on localhost at the standard port 27017. Is there anything i have to consider when connecting with Flask to the container or should the link not already expose the ports as expected?mongoexpress works and has access, so it has to be a problem with my setup.

A: At least put this in your settings:
app.config['MONGODB_HOST'] = 'mongo'

The raison why your mongoexpress works is it looks for mongo on host named mongo by default, so when you do docker run -it --rm -p 8081:8081 --link YOUR_MONGODB_CONTAINER:mongo mongo-express it can find the linked mongo instance. However in flask-mongoengine, the host is default to localhost.

A: In the end things were simpler than i thought. As i migrated my code from Apache2 to Nginx, the flow of my code changed without me noticing it. So my configuration lines for Flask were simply not called.


text:
Q: How can I turn ClusterRouterPool from C# to HOCON configuration? I'm learning akka.net and potentially will use it to replace part of our traditional message driven app.
Basically I'm trying to have X number of nodes joined to a cluster. It's peer to peer type, and I might run X number of actors (same actor) on a node.
If I have 10 jobs (say SendEmailActor), ideally, I would like each of the 10 jobs be executed on different nodes (spread the load evenly).
I have an extremely simple console app to demonstrate.
using System;
using System.Configuration;
using Akka;
using Akka.Actor;
using Akka.Cluster;
using Akka.Cluster.Routing;
using Akka.Configuration;
using Akka.Configuration.Hocon;
using Akka.Routing;

namespace Console1
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            Console.Write("Is this the seed node? (Y/n): ");

            var port = Console.ReadLine().ToLowerInvariant() == "y" ? 9999 : 0;

            var section = (AkkaConfigurationSection)ConfigurationManager.GetSection("akka");

            var config =
                ConfigurationFactory.ParseString("akka.remote.helios.tcp.port=" + port)
                    .WithFallback(section.AkkaConfig);

            var cluster = ActorSystem.Create("MyCluster", config);

            var worker = cluster.ActorOf(Props.Create<Worker>().WithRouter(
                                 new ClusterRouterPool(
                                     new RoundRobinPool(10),
                                     new ClusterRouterPoolSettings(30, true, 5))), "worker");

            while (true)
            {
                Console.Read();
                var i = DateTime.Now.Millisecond;
                Console.WriteLine("Announce: {0}", i);
                worker.Tell(i);

            }
        }
    }

    public class Worker : UntypedActor
    {
        protected override void OnReceive(object message)
        {
            System.Threading.Thread.Sleep(new Random().Next(1000, 2000));
            Console.WriteLine("WORKER ({0}) [{1}:{2}]", message, Context.Self.Path, Cluster.Get(Context.System).SelfUniqueAddress.Address.Port);
        }
    }
}

And my app.config looks like
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
        <section name="akka" type="Akka.Configuration.Hocon.AkkaConfigurationSection, Akka" />
    </configSections>
    <akka>
    <hocon>
        <![CDATA[
            akka {
                actor {
                    provider = "Akka.Cluster.ClusterActorRefProvider, Akka.Cluster"
                }

                remote {
                    helios.tcp {
                        hostname = "127.0.0.1"
                        port = 0
                    }
                }

                cluster {
                    seed-nodes = ["akka.tcp://MyCluster@127.0.0.1:9999"]
                }
            }
        ]]>
    </hocon>
    </akka>
</configuration>

I want to use HOCON and setup akka.actor.deployment, and I couldn't get it to work. I don't quite understand the routees.paths, and its relationship with the the actor.deployment/worker and how will routees.paths map to the actors created in C#.
actor {
    provider = "Akka.Cluster.ClusterActorRefProvider, Akka.Cluster"
    deployment {
        /worker {
            router = roundrobin-pool
            routees.paths = ["/worker"] # what's this?
            cluster {
                    enabled = on
                    max-nr-of-instances-per-node = 1
                    allow-local-routees = on
            }
        }
    }
}

Another question: with aka.net.cluster is it possible to "mirror" the nodes to provide redundancy? Or GuaranteedDeliveryActor (I think it's renamed to AtLeastOnceDelivery) is the way to go?

A: Thanks to @RogerAlsing.
The C# line looks like this
var worker = cluster.ActorOf(Props.Create(() => new Worker()).WithRouter(FromConfig.Instance), "worker");
and the config looks like
akka {
        actor {
            provider = "Akka.Cluster.ClusterActorRefProvider, Akka.Cluster"
            deployment {
                /worker {
                    router = round-robin-pool #broadcast-pool also works
                    nr-of-instances = 10
                    cluster {
                            enabled = on
                            max-nr-of-instances-per-node = 2
                            allow-local-routees = on
                    }
                }
            }
        }

        remote {
            helios.tcp {
                hostname = "127.0.0.1"
                port = 0
            }
        }

        cluster {
            seed-nodes = ["akka.tcp://MyCluster@127.0.0.1:9999"]
        }
    }


text:
Q: Compare 2 values and only return the index Let's say we have 2 Elements:
x = (123, 'aab', 1)
y = (456, 'cca', 2) or y = None

where x[0]=Key, x[1]=Value, x[2]=Index and y[0]=Key, y[1]=Value, y[2]=Index, where y can be potentially be None
Is there an elegant way in Python to compare the Value of both Elements with the min function and return the corresponding Index? Considering the case, that y can be potentially be None. For example
x = (123, 'aab', 1)
y = (456, 'cca', 2)

would return 1 since min(123,456) = 123  so x has the smaller value.
or
x = (123, 'aab', 1)
y = None

would also return 1

A: It's not pretty:
min((x,) + ((y,) if y else ()))[2]

The conditional expression will return a tuple containing y if it's not None, otherwise an empty tuple.
This gets appended to the tuple containing x.
Then we pass this tuple to min(), which compares the two tuples. There's no need to compare [0] explicitly, since tuples are compared lexicographically.
Then we extract [2] of the result to get the corresponding index.
Somewhat less cryptic is:
(x if y is None else min(x, y))[2]

A: you can store in a numpy array of type object

import numpy as np
x = (123, 'aab', 1)
y = (456, 'cca', 2)
arr = np.array([x,y, None], dtype=object)

## Filter None Elements
arr = arr[arr!=None]

minimal = np.min(arr,axis=0)

print(minimal[2])


text:
Q: How do you prove uniqueness of solution of homogeneous linear recurrences? I was following the MIT 6.042 course on OCW (that don't cover generating function on the lectures, sorry if the answer is easier by doing that method).
Recall a linear homogeneous recurrences is of the form:
$$T(n) = \sum^{n}_{i=1} a_i T(n-i)$$
It is shown that the solution can be obtained from the roots of the characteristic equation:
$$x^n = \sum^{n}_{i=1}a_i x^{n-i}$$
and the combining them linearly to form the homogenous solutions.
It is clear to me that indeed, that the roots and their linear combinations are a valid solution. However, what is not clear to me is the uniqueness of the solution (its also not clear that it did not "miss" out any other potential function that solves the recurrence that should have been included linearly in the solution to the homogeneous recurrence).
How does one go about proving that we did not miss some function that could have been part of the solution?
Said differently, say that the homogeneous solution to the linear recurrence is:
$$f(n) = \sum^{n}_{i=1}r_i(x,n)$$
where $r_i(x,n)$ is one of the roots of the characteristic polynomial (or a function of it in the case where there are repeated roots). How do you prove that this are all of terms that solves the recurrence? How are you able to rule out "crazy" functions such as $f(n) = e^{e^{e^{n^3 + log{n}}}}$ or any other infinite set of creative functions I could think? How do you show they ALL could NEVER solve the recurrence?
I am well aware that there a extremely similar question to this one here. Here is the link to it:
Uniqueness of solutions to linear recurrence relations
However I am unable to fully understand its solution and how its able to rule out this infinite set of alternative potential functions that could solve the recurrence.
For easy of reference I will post the solution given to that question and address the parts that don't make sense to me (also, look at the end of my question to understand the notation used in the following answer):

Yes, you can see it by observing that the set of all solutions is a vector space of dimension d; this holds because if you choose q1,…qd, the rest is clearly determined. The solutions {rni} are linearly independent (which can be shown by Vandermond determinant, for example), so they generate the whole space.

The first thing is, how do you justify or prove that the solutions is a vector space of dimension d? How does that rule out the possibility of the function $\log{\log \log \log {n^{2.777}}}$ to be a solutions? I know I could just try to plug them into the recurrence, but there is an infinite set of these, isn't there an easier way to reason about them and really get that the roots are the only solutions?

Reference of the notation used on the other question:
Recurrence:
$$q_n = q_{n-1} + c_2 q_{n-2} + \cdots + c_d q_{n-d}$$
Its characteristic polynomial
$$p(t) = t^d - c_1 t^{d-1} - \cdots - c_{d-1} t - c_d$$
and if the roots are $r_1, \ldots, r_d$ (say distinct, for simplicity) then the solution is:
$$q_n = k_1 r_1^n + \cdots k_d r_d^n$$
for any choice of coefficients $k_i$.

A: You can write the recurrence system as $X_{n+1} = M X_n$ where $X_0 \in\mathbf{R}^n$ is given, and then you see that the set of solutions is given by all $X_0$ possible, which is a  vector space of dimension $d$ over $\mathbf{R}$. If you need more details on $M$ or the $X_n$'s tell me.
EDIT More "elaborate answer" as the OP politely asked for it :
1) First of all, you made a big mistake in the very definition of a sequence defined by a linear homogeneous recurrence. Indeed, at each step $n$, the $n$-th term of your sequence will depend on all $n-1$ previous terms. This is not the definition of a sequence defined by a linear homogeneous recurrence. The real and only definition (justifying the use of a polynomial after, use that would be useless and inappropriate in the case of your definition) is the following : $u_n = a_1 u_{n-1} + \ldots + a_d u_{n-d}$ for all $n$, with $u_0,\ldots,u_{d-1}$ given for a start. You'll tell if this is what you mean, but I think it is.
2) Now with this correct definition, consider the polynomial $P = T^d - a_1 T^{d-1} - \ldots - a_d$. Assuming that the roots of $P$ are $\alpha_1,\ldots,\alpha_e$ with $\alpha_i$ being a root with multiplicity $m_i$. (We then have $\alpha_1 + \ldots + \alpha_e = d$.) Then, the following sequences (and all linear combination thereof) verify our linear homogenous recurrence (I note the sequences in a map fashion) : $n\mapsto \alpha_1^n, \ldots, n\mapsto n^{\alpha_1 - 1} \alpha_1^n, \ldots, n\mapsto \alpha_e^n, \ldots, n\mapsto n^{\alpha_e - 1} \alpha_e^n$. (Exercise : check it.)
3) If you count the number of elements of the previous list of sequences, you'll count $\alpha_1 + \ldots + \alpha_e = d$ sequences, all linearly independant. The dimension of the solution space is therefore at least $d$. Now the point is to show that it is exactly $d$. (This is what interests you.) Everything is based of the following observation : you can rewrite your linear homoegenous recurrence $u_n = a_1 u_{n-1} + \ldots + a_d u_{n-d}$ as :
$\underbrace{\begin{bmatrix}u_n\\u_{n-1}\\ u_{n-2} \\ \vdots \\ u_{n-d+1} \end{bmatrix}}_{:= X_n \in \mathbf{R}^{d}} = \underbrace{\begin{bmatrix}a_{1} & a_{2} & \cdots & a_{d-1} & a_{d} \\ 1 & 0 & \cdots &0 & 0\\ 0 & 1 & \cdots & 0 & 0\\ \vdots & \vdots & \ddots & \vdots & \vdots\\ 0 & 0 & \cdots & 1 & 0\end{bmatrix}}_{:=M \in \mathbf{M}_d (\mathbf{R})} \underbrace{\begin{bmatrix}u_{n-1} \\u_{n-2} \\ u_{n-3} \\ \vdots \\ u_{n-d} \end{bmatrix}}_{= X_{n-1}}$ where the first line defines the linear homegenous recurrence relations, and all other $d-1$ lines are dummy equations $u_{n-1} = u_{n-1}, u_{n-2} = u_{n-2}, \ldots u_{n-d+1} = u_{n-d+1}$. This is the matrix recurrence I was writing about above : $X_n = M X_{n-1}$.
Solutions of our linear homogenous equation and solution of this matrix linear recurrence are isomorphic. Indeed, note $S_1$ the space of solutions of our initial linear homogeneous equation and $S_2$ the space of solutions of $X_n = M X_{n-1}$.
All solution of this linear recurrence are $X_n = M^n X_0$ with $X_0 \in \mathbf{R}^d$. (Same as geometric sequences in $\mathbf{R}$...) Now define a linear map from $S_2$ to $S_1$ by associating to a sequence $(X_n)_n$ veryfing $X_n = M X_{n-1}$ the real sequence $(u_n)_n$ verifying $u_n = a_1 u_{n-1} + \ldots + a_d u_{n-d}$ with $u_0 = x_1, \ldots, u_{d-1} = x_d$ where $X_0 = \begin{bmatrix} x_1 \\ \vdots \\ x_d \end{bmatrix}$ is the initial vector giving rise to the sequence $(X_n)_n$. Define a linear map from $S_1$ to $S_2$ by associating to a sequence $(u_n)_n$ verifying $u_n = a_1 u_{n-1} + \ldots + a_d u_{n-d}$ the vector sequence $(X_n)_n$ verifying $X_n = M^n X_0$ where $X_0 = \begin{bmatrix} x_1 \\ \vdots \\ x_d \end{bmatrix}$ with $x_1 = u_1, \ldots, x_d = u_{d-1}$. It is clear that the maps are inverse one to the other, showing that $S_1$ and $S_2$ are isomorphic vector spaces. We saw that $S_2$ is of dimension $d$ (because $X_0$ determines all the sequence, and you can choose it in whole $\mathbf{R}^d$). Therefore $S_1$ is also of dimension $d$, which shows that in (2) we indeed found all solutions.
Now if you're happy, don't hesitate to upvote ! ;-)


text:
Q: padx on Tkinter Frame in python produces different spacing on different machines Are there any factors that would cause the padx option of a Tkinter Frame to result in different sizes on different screens/OS? I am developing on Linux and I have a set of icons lined up using the padx option. When another user on a Windows machine tried it, the icons are out of place.
Please let me know if there is any other relevant information I can provide.

A: There is no magic with padx -- it specifies an absolute number of pixels for padding. A value of one means one pixel on every window manager on every OS. There must be more to your problem than simply padding.
On different window managers or OS's, however, the default borderwidth on widgets may be different, and there are other defaults that may be different from platform to platform.


text:
Q: How to solve this inequality with absolute value: $ \frac{\left|x-3\right|}{\left|x+2\right|}\le 3 $ Good morning to everyone. I have an inequality that I don't know how to solve: $$ \frac{\left|x-3\right|}{\left|x+2\right|}\le 3 $$ I tried to solve it in this way: $$ \frac{\left|x-3\right|}{\left|x+2\right|}\le 3 \rightarrow \frac{\left|x-3\right|}{\left|x+2\right|} - 3 \le 0 \rightarrow \frac{\left|x-3\right|-3\left|x+2\right|}{\left|x+2\right|}\le 0 \rightarrow $$
Case 1:
$$ \left|x+2\right| > 0 \wedge \left|x-3\right|-3\left|x+2\right| \le 0 $$
Case 1 a) $$ x+2 >0 \rightarrow x>-2$$
Case 1 b) $$ -x-2 <0 \rightarrow x>-2$$
Case 1 c) $$ \left|x-3\right|-3\left|x+2\right| \le 0 \rightarrow \left|x-3\right| \le 3\left|x+2\right| \rightarrow x-3 \le x+2 \rightarrow $$
The solution are all real numbers
Case 1 d)$$ -x+3 < x+2 \rightarrow x>\frac{1}{2} $$
Case 1 e) $$ x-3 \le -x-2 \rightarrow x \le \frac {1}{2} $$
Case 1 f) $$ x-3 < x+2  $$
The solution: all real numbers
Case 2: $$ \left|x+2\right| \le 0 \wedge \left|x-3\right|-3\left|x+2\right| > 0 $$
It'll have the same solutions because are the same inequalities. Therefore $x$ belongs to $(\frac{1}{2}, \infty)$ But my answer sheet shows that it belongs to $(-\infty, -\frac{9}{4}) \wedge (-\frac{3}{4},\infty)$

A: hint: $x \neq -2$, and $|x-3| \leq 3|x+2|$, and square both sides.

A: If $|y|\le a$ for real $y, a\ge0,$
we need $-a\le y\le a$
So, $-3\le\dfrac{x-3}{x+2}\le3$
Now $\dfrac{x-3}{x+2}\le3\iff\dfrac{x-3}{x+2}-3\le0\iff\dfrac{2x+9}{x+3}\ge0$
$\iff x\le-\dfrac92$ or $x>-3$
can you take it from here?

A: Simply write the homographic function in canonical form:
$$\biggl\lvert\frac{x-3}{x+2}\biggr\rvert=\biggl\lvert\frac{(x+2)-5}{x+2}\biggr\rvert=\biggl\lvert1-\frac{5}{x+2}\biggr\rvert.$$
The inequation means the distance between $1$ and $\dfrac{5}{x+2}$ is at most $3$, so it's equivalent to
$$1-3=-2\le \frac{5}{x+2}\le 1+3=4.$$
As $\dfrac{5}{x+2}$ can't be $0$, we have two cases

*

*$-2\le \dfrac{5}{x+2}<0\iff x+2\le-\dfrac52\iff x\le-\dfrac92$,

*$0<\dfrac{5}{x+2}\le 4\iff x+2\ge\dfrac54\iff x\ge-\dfrac34$.

A: Hint:
For $x \ne -2$ the inequality is equivalent to:
$$
|x-3| \le 3|x+2|
$$
so since the arguments of the absolute values change sign at $x=-2$ and $x=3$ the inequality is equivalent to the systems:
$$
\begin{cases}
x<-2\\
3-x\le 3(-x-2)
\end{cases}
\quad \lor \quad
\begin{cases}
-2<x\le3\\
3-x\le 3(x+2)
\end{cases}
\quad \lor \quad
\begin{cases}
x\ge 3\\
x-3\le 3(-x-2)
\end{cases}
$$


text:
Q: Knockout - Function in foreach loop with multiple models I have my HTML here, when the user clicks on the list I want it to execute a function loadLayerSource.

                Name
                Description

To achieve this I have the following:
//This is data that would be returned from a web service
var jsonData = [{
        "SubCategory": "Report",
        "CategorySources": [{
            "Source": "cvr01",
            "Category_ID": "cvr01",
            "ReadableName": "Climate Viewer Reports",
            "Type": "kml",
            "URL": "/layers/kml/cv-reports/cv-reports-0415.kml",
            "Description": "Content disclaimer etc"
    }]
}, {
        "SubCategory": "Earthquake",
        "CategorySources": [{
            "Source": "usgs-all-hour",
            "Category_ID": "",
            "ReadableName": "USGS - All Earthquakes (Last Hour)",
            "Type": "geojson",
            "URL": "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.geojson",
            "Description": "Content disclaimer etc"
            }, {
            "Source": "kml-emsc",
            "Category_ID": "",
            "ReadableName": "Euro-Med Earthquakes - CSEM/EMSC",
            "Type": "kml",
            "URL": "http://www.emsc-csem.org/Earthquake/Map/earth/kml.php",
            "Description": "Content disclaimer etc"
    }]
}];

//This is our ProductType model
var typeModel = function (source, name, type, url, description) {
    var self = this;
    self.Source = ko.observable(source);
    self.ReadableName = ko.observable(name);
    self.Type = ko.observable(type);
    self.URL = ko.observable(url);
    self.Description = ko.observable(description);
};

var typeReturn = function (source, name, type, url, description) {
    alert(source + name);
};

//This is the model that contains the header (Category) and an array of typeModels (Products)
var gridModel = function (subcategory, categorySources) {
    var self = this;
    self.SubCategory = subcategory;
    self.CategorySources = ko.observableArray(categorySources);
};

//This is the viewmodel that contains an array of gridModels
var settingsViewModel = function () {
    this.layerSources = ko.observableArray();
    var me = this;
    //This is where you would normally make an ajax call to get your data
    //TODO figure out a way to reduce the amount of loops
    $.each(jsonData, function (key, value) {
        $.each(value, function (k, v) {
            if (k == 'CategorySources') {
                var categorySources = [];
                $.each(v, function (a, b) {
                    categorySources.push(new typeModel(b.Source, b.ReadableName, b.Type, b.URL, b.Description));
                });
                me.layerSources.push(new gridModel(value.SubCategory, categorySources));
            }
        });
    });
};
ko.applyBindings(new settingsViewModel());

No matter where I put the below code, I get an undefined error.
self.loadLayerSource = function() {
    alert(layerType);
};

jsFiddle Link

A: See the updated fiddle: http://jsfiddle.net/ucz8yzxy/2/
You need to properly scope the call to loadLayerSource with $root, because you're 2 levels deep in foreach loops. Also, loadLayerSource, if in the viewModel, should be attached to this instead of self since self isn't defined in there.
And since the fields are observable, make sure you evaluate them (parens).


text:
Q: Can multiple ngrams be used in the same classifier? I'm new to NLP and have a very simple question I expected to be asked a lot, but honestly couldn't find anywhere: can multiple types of ngrams be used within the same classifier (e.g. unigrams + bigrams)?
I have tried doing so, and, for Naive Bayes, at least, it gives me a higher accuracy than bigrams only (though lower than unigrams), but I am not sure whether it is a legitimate practice at all. One concern that I have is that there is potential for multicollinearity, if that's even an applicable term, i.e. both 'luck' and 'good luck' are near the top of the most informative features list.

A: The short answer is "yes". The longer answer is, you can use anything you want as training features. But I suspect you are using the raw unigrams and bigrams as your features. If bigrams by themselves are less useful than unigrams, you clearly do not have enough training data for your application to make useful inferences from them. Add some higher-level features (e.g., a bigram of the POS tags) that have fewer possibilities and are therefore easier to generalize.


text:
Q: Rails: Capistrano change database.yml to database.yml.example causes error When I deploy a new app to nginx using Capistrano.
I follow tutorial to do git mv database.yml database.yml.example and git mv secrets.yml secrets.yml.example , then created a new database.yml file on remote server. But now when I want to run app on my local mechine, it shows me an error

No such file - ["config/database.yml"]

Because there is no database.yml on my local repo.
Can I create an new and empty database.yml to fix this?

A: The guide just tells you that storing database credentials in a repository is bad practice and you shouldn't do it, but it doesn't mean you don't need to have this files at all.You application still needs it, so you definitely need to create it, just don't store it in main repo with code, this security critical information is better to store it elsewhere you decide to keep your authentification data like separate repository for credentials, key-pass storage or whatever place you want for such critical information.
PS Of course, if you just learning since it's not a big deal, you COULD keep your "root-123" credits in repository, but it's better to develop right habit from the beginning or at least get the idea why it should be separated.


text:
Q: Working on project Web + Android + Raspberry Pi (with its GPS module) Im working on a project where I uses Raspberry Pi with the itead GPS (Add-on 2.0) which uploads the GPS location information to a database periodically. Website (with Google Maps API) will be used for configuration and can access the information from the database. The last module is the android app which also uses that database to exchange the information.
So the GPS location info goes to the database, web and android accesses the database.
What technology, framework and language should be used for website designing?
What database should I use?

A: Hey I have done a web based application with Google maps Api for web (JavaScript), JavaScript , php, MYSQL  and XML.
JavaScript was used for the logic part  , Google Maps Api to draw the map , add markers and such.php to send /receive data , XML as an interface to/from php and to/from JavaScript.


text:
Q: Cómo puedo hacer un llamado POST en Android con este tipo de json estoy haciendo una aplicación con retrofit en lenguaje JAVA,
estoy acostumbrado a hacer llamadas con un json simple,
cómo este

y el código que aplico es este
public class Cuerpo {

//parametros
@SerializedName("username")
@Expose
private String username;
@SerializedName("password")
@Expose
private String password;

public Cuerpo(String username, String password, String nroConteo, String item, String nroSerie, String cantidadFisica) {
    this.username = username;
    this.password = password;

mi interface
public interface Conexion {

@POST("/jderest/v3/orchestrator/MQ1201A_ORCH")
Call<Cuerpo> getDatos(@Body Cuerpo users );

}
y el main dónde hago el llamado
    Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(url)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

            Conexion conexion = retrofit.create(Conexion.class);

            Cuerpo logerse = new Cuerpo(usuario, contraseña);

ahora me tocó uno mas complejo,

mi consulta es, que tengo que aplicar en la interface para que pueda hacer el llamado total de todo esto:
{
"username" : "xxxx",
"password" : "xxxx",
"Deposito_Desde": "ADUANA",
"Deposito_Hasta": "JMINGE",
"GridIn_1_2": [
{
"Inicial__final": "F",
"Número_artículo": "SE36X361A0194  ",
"Cantidad": "1",
"Ubicación": ".",
"Número_lote_serie": "800004"
}
]
}
desde ya,
muchas gracias
edición
     Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://quantumconsulting.servehttp.com:925")
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    Conexion conexion = retrofit.create(Conexion.class);

    GridIn12 data = new GridIn12("F","SE36X361A0194","1",".","800004",
            "F","SE36X361A0194","1",".","800005",
            "T","1","SE36X361A0194","2","P2","T201C04");

    List<GridIn12> objList = new ArrayList<>();
    objList.add(data);

    Cuerpo logerse = new Cuerpo("xx", "xx","ADUANA","JMINGE",objList);

    Call<Cuerpo> call1 = conexion.getDatos( logerse);//acá es cuando se me pone en rojo
    call1.enqueue(new Callback<Cuerpo>() {

acá va el parseo
public class Cuerpo {
@SerializedName("username")
@Expose
private String username;
@SerializedName("password")
@Expose
private String password;
@SerializedName("Deposito_Desde")
@Expose
private String depositoDesde;
@SerializedName("Deposito_Hasta")
@Expose
private String depositoHasta;
@SerializedName("GridIn_1_2")
@Expose
private List<GridIn12> gridIn12 = null;

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public String getDepositoDesde() {
    return depositoDesde;
}

public void setDepositoDesde(String depositoDesde) {
    this.depositoDesde = depositoDesde;
}

public String getDepositoHasta() {
    return depositoHasta;
}

public void setDepositoHasta(String depositoHasta) {
    this.depositoHasta = depositoHasta;
}

public List<GridIn12> getGridIn12() {
    return gridIn12;
}

public void setGridIn12(List<GridIn12> gridIn12) {
    this.gridIn12 = gridIn12;
}

public Cuerpo(String username, String password, String depositoDesde, String depositoHasta, List<GridIn12> gridIn12) {
    this.username = username;
    this.password = password;
    this.depositoDesde = depositoDesde;
    this.depositoHasta = depositoHasta;
    this.gridIn12 = gridIn12;
}

parseo de lo que contiene gridIn12
public class GridIn12 {

@SerializedName("Inicial__final")
@Expose
private String inicialFinal;
@SerializedName("Número_artículo")
@Expose
private String nMeroArtCulo;
@SerializedName("Cantidad")
@Expose
private String cantidad;
@SerializedName("Ubicación")
@Expose
private String ubicaciN;
@SerializedName("Número_lote_serie")
@Expose
private String nMeroLoteSerie;

//segundo
@SerializedName("Inicial__final")
@Expose
private String inicialFinal2;
@SerializedName("Número_artículo")
@Expose
private String nMeroArtCulo2;
@SerializedName("Cantidad")
@Expose
private String cantidad2;
@SerializedName("Ubicación")
@Expose
private String ubicaciN2;
@SerializedName("Número_lote_serie")
@Expose
private String nMeroLoteSerie2;

//tercero
//segundo
@SerializedName("Inicial__final")
@Expose
private String inicialFinal3;
@SerializedName("Lineas_relacionadas")
@Expose
private String lineasRelacionadas;
@SerializedName("Número_artículo")
@Expose
private String nMeroArtCulo3;
@SerializedName("Cantidad")
@Expose
private String cantidad3;
@SerializedName("Ubicación")
@Expose
private String ubicaciN3;
@SerializedName("Numero_lote_serie")
@Expose
private String nMeroLoteSerie3;

public String getInicialFinal() {
    return inicialFinal;
}

public void setInicialFinal(String inicialFinal) {
    this.inicialFinal = inicialFinal;
}

public String getNMeroArtCulo() {
    return nMeroArtCulo;
}

public void setNMeroArtCulo(String nMeroArtCulo) {
    this.nMeroArtCulo = nMeroArtCulo;
}

public String getCantidad() {
    return cantidad;
}

public void setCantidad(String cantidad) {
    this.cantidad = cantidad;
}

public String getUbicaciN() {
    return ubicaciN;
}

public void setUbicaciN(String ubicaciN) {
    this.ubicaciN = ubicaciN;
}

public String getNMeroLoteSerie() {
    return nMeroLoteSerie;
}

public void setNMeroLoteSerie(String nMeroLoteSerie) {
    this.nMeroLoteSerie = nMeroLoteSerie;
}

public GridIn12(String inicialFinal, String nMeroArtCulo, String cantidad, String ubicaciN, String nMeroLoteSerie,
                String inicialFinal2, String nMeroArtCulo2, String cantidad2, String ubicaciN2, String nMeroLoteSerie2,
                String inicialFinal3, String lineasRelacionadas, String nMeroArtCulo3, String cantidad3, String ubicaciN3, String nMeroLoteSerie3) {

    this.inicialFinal = inicialFinal;
    this.nMeroArtCulo = nMeroArtCulo;
    this.cantidad = cantidad;
    this.ubicaciN = ubicaciN;
    this.nMeroLoteSerie = nMeroLoteSerie;
    this.inicialFinal2 = inicialFinal2;
    this.nMeroArtCulo2 = nMeroArtCulo2;
    this.cantidad2 = cantidad2;
    this.ubicaciN2 = ubicaciN2;
    this.nMeroLoteSerie2 = nMeroLoteSerie2;
    this.inicialFinal3 = inicialFinal3;
    this.lineasRelacionadas = lineasRelacionadas;
    this.nMeroArtCulo3 = nMeroArtCulo3;
    this.cantidad3 = cantidad3;
    this.ubicaciN3 = ubicaciN3;
    this.nMeroLoteSerie3 = nMeroLoteSerie3;
}

la interface
public interface Conexion {

@POST("//jderest/v3/orchestrator/MQ0801A_ORCH")
Call<Cuerpo> getDatos(@Body   final List<GridIn12>users );

}
y el llamado en el main
  Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://quantumconsulting.servehttp.com:925")
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    Conexion conexion = retrofit.create(Conexion.class);

    GridIn12 data = new GridIn12("F","SE36X361A0194","1",".","800004",
            "F","SE36X361A0194","1",".","800005",
            "T","1","SE36X361A0194","2","P2","T201C04");

    List<GridIn12> objList = new ArrayList<>();
    objList.add(data);

    Cuerpo logerse = new Cuerpo("xx", "xx","ADUANA","JMINGE",objList);

    Call<Cuerpo> call1 = conexion.getDatos( logerse);
    call1.enqueue(new Callback<Cuerpo>() {
        @Override
        public void onResponse(Cal

A: La respuesta es sumamente sencilla. En formato JSON los corchetes o parentesis cuadrados representan listas de objetos. Por lo tanto tu clase en JAVA debe implementar una lista del objeto en cuestion.
public class Cuerpo {

    //parametros
    @Expose @SerializedName("username")
    private String username;

    @Expose @SerializedName("password")
    private String password;

    @Expose @SerializedName("Deposito_Desde")
    private String despositoDesde;

    @Expose @SerializedName("Deposito_Hasta")
    private String depositoHasta;

    @Expose @SerializedName("GridIn_1_2")
    private List<Grid_1_2> codigosList;
}

class Grid_1_2{
    @Expose @SerializedName("Inicial__Final")
    private String inicialFinal;

    @Expose @SerializedName("Número_articulo")
    private String numeroArticulo;

    @Expose @SerializedName("Cantidad")
    private String cantidad;

    @Expose @SerializedName("Ubicación")
    private String ubicacion;

    @Expose @SerializedName("Número_lote_serie")
    private String numeroLoteSerie;

}

La lista que cree es codigosList, esta almacenará siempre una lista de objetos del mismo tipo. Prueba cambiar tambien el tipo de lista por ejemplo con ArrayList.  No inclui los set y get pero recuerda colocarlos.
Además en la interface conexion debes de actualizar los parametros
@POST("//jderest/v3/orchestrator/MQ0801A_ORCH")
Call<Cuerpo> getDatos(@Body   final List<GridIn12>users );

El codigo anterior te genera el error porque el BODY es una lista de GridIn12. Por lo que colocaste en postman deberia ser simplemente colocar el objeto Cuerpo.
En el Call<?> <<-- Aqui deberias de colocar el objeto que se devuelve en la consulta post.
EN palabras simples, el Body es el request del post y lo que colocas dentro del Call es la respuesta o result.
Cambia esto:
@POST("//jderest/v3/orchestrator/MQ0801A_ORCH")
Call<Cuerpo> getDatos(@Body   final List<Cuerpo>users );

Es posible que no te devuelva lo que necesites pero esto es porque según lo que colocaste en postman, el servicio post retorna un objeto diferente.


text:
Q: How and where to use Transformations.switchMap? In recent Android Architecture Components library released by Google, we have two static functions in the Transformations class. While the map function is straight forward and easily understandable, I am finding it hard to properly understand the switchMap function.
The official documentation of switchMap can be found here.
Can somebody explain how and where to use the switchMap function with a practical example?

A: The function passed to switchMap returns LiveData. Use it when your repository itself returns LiveData.

A: Adding my 2 cents to @DamiaFuentes answer.
MutableLiveData userIdLiveData = ...;
LiveData userLiveData = Transformations.switchMap(userIdLiveData, id ->
repository.getUserById(id)); // Returns LiveData

void setUserId(String userId) {
     this.userIdLiveData.setValue(userId);
}

Transformations.switchMap method will only be called when you have at least one observer for userLiveData

A: Another point to consider whether choosing between switchMap or map, you have to remember that map always wraps the returned value around LiveData e.g.
fun getUser(id: Int): User
...
val userId = MutableLiveData(1)
val user = userId.map { // LiveData<User>
   repository.getUser(it)
}

You might consider using map if repository.getUser(it) returns a plain simple User object instead of LiveData so the type of user becomes LiveData<User>.
If repository.getUser(it) returns a LiveData<User> then it's better to use switchMap
fun getUser(id: Int): LiveData<User>
...
val userId = MutableLiveData(1)
val user = userId.switchMap { // LiveData<User>
   repository.getUser(it)
}

The user type would be LiveData<User>

A: For those who want more explanation of @DamiaFuentes switchmap() function example given below:
 MutableLiveData userIdLiveData = ...;
 LiveData userLiveData = Transformations.switchMap(userIdLiveData, id ->
     repository.getUserById(id));

 void setUserId(String userId) {
      this.userIdLiveData.setValue(userId);
 }

In a scenario where the repository contains User(1, "Jane") and User(2, "John"), when the userIdLiveData value is set to "1", the switchMap will call getUser(1), that will return a LiveData containing the value User(1, "Jane"). So now, the userLiveData will emit User(1, "Jane"). When the user in the repository gets updated to User(1, "Sarah"), the userLiveData gets automatically notified and will emit User(1, "Sarah").
When the setUserId method is called with userId = "2", the value of the userIdLiveData changes and automatically triggers a request for getting the user with id "2" from the repository. So, the userLiveData emits User(2, "John"). The LiveData returned by repository.getUserById(1) is removed as a source.
From this example, we can understand that the userIdLiveData is the trigger and the LiveData returned by the repository.getUserById is the "backing" LiveData.
For more reference, check out: https://developer.android.com/reference/android/arch/lifecycle/Transformations

A: And yet another point for understanding.
One may think that as we always return new value (new reference) of LiveData inside switchMap() so how can we observe actual values with the observer having set just one time?
The point is the returned value of Transformations.switchMap is MediatorLiveData which adds new LiveData reference to as a new source (and deactivates the other sources).

A: In the map() function
LiveData userLiveData = ...;
LiveData userName = Transformations.map(userLiveData, user -> {
     return user.firstName + " " + user.lastName; // Returns String
});

everytime the value of userLiveData changes, userName will be updated too. Notice that we are returning a String.
In the switchMap() function:
MutableLiveData userIdLiveData = ...;
LiveData userLiveData = Transformations.switchMap(userIdLiveData, id ->
    repository.getUserById(id)); // Returns LiveData

void setUserId(String userId) {
     this.userIdLiveData.setValue(userId);
}

everytime the value of userIdLiveData changes, repository.getUserById(id) will be called, just like the map function. But repository.getUserById(id) returns a LiveData. So everytime that the value of the LiveData returned by repository.getUserById(id) changes, the value of userLiveData will change too. So the value of userLiveData will depend on changes of userIdLiveData and changes of the value of repository.getUserById(id).
Practical example of switchMap(): imagine you have a user profile with a follow button and a next profile button which sets another profile info. Next profile button will call setUserId() with another id so userLiveData will change and UI will change. Follow button will call the DAO to add one follower more to that user, so the user will have 301 followers instead of 300. userLiveData will have this update that comes from the repository, which comes from the DAO.


text:
Q: How to chain .where for firebase query My app allowed user to define backend fields (multiple), then using the 'rules' to chain them (by looping them) to return relevant docs inside a collection.
 let eeRef = this.afStore.collection<any>(`.../Collections/EmpSnapshot`).ref
 let eeDoc: any = null
 if (u.bAccessAll) {
     eeDoc = eeRef
 } else {
    for (let r of u.rules) {
        eeDoc = eeRef.where(r.field, r.condition, r.value)
    }
 }

await eeDoc.get()
.then(res => {
    for (let ee of res.docs) {
        emails.push(ee.id)
    }
}).catch(err => {
    console.log(`Error query-ing 'EmpSnapshot': `, err)
})

But in the actual fact, the eeDoc variable only can recognize the LAST criteria in the loop and not to chain all criteria up. Example if my rules are

*

*Fulltime (Staff)

*Finance (Department)

I am expecting it to return all Finance Staff who are Fulltimer, but my code will only return 'Finance' Staff
How to fix my code to chain the .where criteria?

A: You're overwriting the eeDoc in every iteration of the loop.
This should be closer to what you want:
 let eeDoc: any = eeRef

 if (u1.bAccessAll) {
    for (let r of u.rules) {
        eeDoc = eeDoc.where(r.field, r.condition, r.value)
    }
 }


text:
Q: Can I determine the statistical significance of conditional probabilities? I have the following table of conditional probabilities.
       | pre work | positive outcome based on pre work type
 group | done     | multi choice       | symbolic
-------|----------|--------------------|--------------------
 A     | YES      | 0.51               | 0.33
 B     | YES      | 0.42               | 0.56

Looking at the table above, is there any statistical test that I can use to confirm/reject that subjects in groups A who have done pre work did better preparing with symbolic vs multi choice work?
(it looks like the hypothesis is rejected, but the question holds anyway)

A: You should also know the size of each group to estimate the error of the estimates of your conditional probabilities. If in the A-YES-symbolic group only 1 of 3 people succeeded, the estimate 0.33 of the success rate is less reliable than if it's 1000 of 3000. If you don't have that information, I don't think any statistical test would apply.
Update: ok, you have the information, perfect. The rest is just Z-test for independent proportions. Fill the following table with your data:
       |               |  # of outcomes
 group | pre work type | positive | total
-------|---------------|----------|-------
 A     | multi choice  | k_1      | n_1
       | symbolic      | k_2      | n_2

Let $p_1$ be the probability of positive outcome in multi choice group, $p_2$ — in symbolic group. To test $H_0\colon p_1=p_2$, calculate $$Z = \frac{\hat{p}_1-\hat{p}_2}{\sqrt{P\left(1-P\right)\left(\frac1{n_1} + \frac1{n_2}\right)}}, $$
$$\hat{p}_1 = \frac{k_1}{n_1}, \;\hat{p}_2=\frac{k_2}{n_2}, \; P = \frac{\hat{p}_1n_1+\hat{p}_2n_2}{n_1+n_2}.$$
Under $H_0$ $Z$ would be distributed as $N\left(0,1\right)$, so, if you have $H_1\colon p_1\neq p_2$, then your p-value is $p=2\left(1-\Phi\left(\left|Z\right|\right)\right)$, where $\Phi$ is a standard normal cumulative distribution function.
It might be a good idea to calculate confidence interval for the difference between probabilities as well, so you would have an estimate of the effect size with explicitly specified uncertainty.


text:
Q: Create new signal or multiplex SIGALRM? I am trying to write a benchmark that receives a signal from the kernel telling it to adjust its parameters. I'm trying to study whether a proactive or reactive approach works best.
In the proactive approach, I use setitimer to set an alarm periodically and force the benchmark to look at its performance thus far and re-tune itself.
In the reactive approach, the kernel periodically monitors the process and signals it if it is performing poorly.
Since I've been using the setitimer functionality, and since setitimer causes SIGALRM, I have asked the kernel to throw a SIGALRM in the reactive approach. This has been working fine. However, now I need to use SIGALRM to run the benchmark for a specific duration of time.
Is there a way to multiplex SIGALRM to serve both purposes - to do a timed run and terminate and to re-tune. Is there a function/syscall similar to setitimer that allows the user to set an alarm but with a custom signal?

A: Yes.  You want to look at the timer_create / timer_settime etc., family of calls.
The 2nd parameter of timer_create is a struct sigevent.  The field within that, sigev_signo can be set to send a specific signal number on timer expiration.


text:
Q: React Google Analytics Is there a way to display the components in google analytics to my react dashboard
or fetch the data and use it on my site
Below are some components from google analytics i want to use on my dashboard.
This will help admins to see the activity of the site on the dashboard

A: You can use the Google analytics reporting api to request the data you are looking for, I recommend looking into using a service account as it will allow you to pre authorize the account to access your analytics data. This way you will not need to use Oauth2 and authorize a user.  You will however need to crate all the graphics yourself as the google analytics api only returns the data how it is displayed will be up to you.  You might want to look into the chartsapi
Another option will be the Google analytics embed api this is created in Javascript so it is client sided code as such it does not support service accounts, this means that any user you want to enable to use it will have to have been granted access to your google analytics account directly in the google analytics website.


text:
Q: Cross Deploying Java I have a java project which consists on 3 classes(Program,Proxy,Events) from which Program has the main function on it.
I have a Properties file in the same level as src folder.
I want to deploy this project so that i can run it in a cronjob on a ubuntu server but i have no idea how to do so.
1- How do i deploy it? i can only see 3 .class in the bin folder, i thought i would get only 1 output file of some sort.
2- Where do i put my settings file when deployed?
Using Eclipse BTW

A: From the directory, in a terminal, run java Program to run your application. You'll want your settings file in the same directory (depending on how you are loading it in your code, but if you are loading it as a classpath resource, that would be the spot to put it).
Alternatively, if you want to have a single file, in eclipse, you can export your code to a JAR file:

*

*File > Export > Java > Runnable Jar File

*Pick your project

*Choose a filename for the JAR (usually ending in the .jar extension)

*On the last page of the wizard, choose Program as your main class

To run it, enter java -jar XYZ.jar where XYZ.jar is what you named it.