What is the idiomatic way to transform an Option into an impl Iterator?

Question: I want to create a utility function which reads the contents of a directory, and returns an iterator to the file names contained within, excluding a specified filename.
So the signature should be like this:
fn dir_contents_excluding<'a>(dir: &Path, excluding: &str) -> impl Iterator<Item = &'a str>

and for instance if I have a directory like this:
/my_dir
  /foo.txt
  /bar.txt
  /baz.txt

And I call the function like so:
for file in dir_contents_excluding("./my_dir", "bar.txt") {
    println!(file);
}

The console output should be:
foo.txt
baz.txt

So far I have an implementation which looks like this:
use fs;
fn dir_contents_excluding<'a>(dir: &Path, excluding: &str) -> impl Iterator<Item = &'a str> {
    let read_dir = fs::read_dir(dir);

    match read_dir {
        // Here I transform the read_dir results
        // into filenames
        Ok(read_dir) => read_dir.filter_map(...),
        Err(_) => // ?? not sure what to do here
    }
}

So in the case that fs::read_dir returns an error, I would like to return an empty iterator, so that I don't have to handle the error case at the call site.
What would be the best way to achieve this?
Comment: But, to answer your actual question, you probably want: `opt.into_iter().flatten()`.
Comment: Nit: you cannot implement your function this way. You have to return owned `String` or `PathBuf`s.
Comment: Why not?  I mean what prevents this?
Comment: Because `std::fs::read_dir()` returns owned `PathBuf`s, and you cannot drop them.
Comment: Where would they be dropped?
Comment: Try to write it, even without error handling.
Comment: Put another way: given the `&str` in the iterator item is a refererence, what is it referring to, where is it held in memory and for how long?
Answer: The answer to your question is: using .into_iter().flatten(). Option itself is iterable, so into_iter() converts Option<impl Iterator> into impl Iterator<impl Iterator>. Then flatten() steps in to remove one level of nesting.
In your code, which currently looks like this:
match read_dir {
    Ok(read_dir) => read_dir.filter_map(...),
    Err(_) => // ?? not sure what to do here
}

...you'd change it to something like:
match read_dir {
    Ok(read_dir) => Some(read_dir.filter_map(...)),
    Err(_) => None,
}.into_iter().flatten()

But Result already has a method called ok() that converts Ok(x) to Some(x) and Err(_) to None, so you can use it. Combined with .map() you can elinimate the explicit match(), resulting in something like:
read_dir
    .ok()
    .map(|read_dir| read_dir.filter_map(...))
    .flatten()

While working on this you will encounter further borrow checking issues, as your iterator hands out &'a str, where the 'a namespace doesn't come from any input parameters (which is a hint that it won't compile). As others explained, you will need to hand out owned types such as PathBuf. Also, you'll need to convert excluding to something like OsStr to be able to compare paths provided by dir entries against it.
Here is an implementation that compiles:
fn dir_contents_excluding<'a>(
    dir: &Path,
    excluding: &'a str,
) -> impl Iterator<Item = PathBuf> + 'a {
    let read_dir = fs::read_dir(dir);
    let excluding = OsStr::new(excluding);
    read_dir
        .ok()
        .map(move |read_dir| {
            read_dir.filter_map(move |entry| {
                let p = entry.unwrap().path();
                if p != excluding {
                    Some(p)
                } else {
                    None
                }
            })
        })
        .into_iter()
        .flatten()
}

Playground
Answer: First; read_dir returns a Result<ReadDir>. For example, the directory may not exists. The idiomatic way of handling that error is by having dir_contents_excluding return a Result<..., io::Error> as well. Then you can invoke read_dir like so:
let read_dir = fs::read_dir(dir)?;

The question mark makes sure any error is immediately returned, yielding you the actual Ok(...) result only. This is a ReadDir struct. This struct is an iterator yielding io::Result<DirEntry>, where DirEntry represents a on of the items in the directory.
Secondly; the iterator has Item = Result<...> because iterating through a directory can fail due to IO errors (directory deleted for example). Depending on the type of application, it could be acceptable to panic on such an error so that you can make your function interface more simple. I would not recommend silently ignoring (by filtering) the errors. This yields:
    let iter = read_dir.filter_map(|maybe_entry| {
      match maybe_entry {
          Ok(entry) => Some(...),
          Err(err) => panic!("Error in dir_contents: {err}")
      }
    });

Lastly, you need to implement the filtering and decide on the return type. I would recommend getting rid of lifetime requirements by copying any references into local variables. Local variables can be moveed into the closure. Also, return PathBuf instead of &str. This becomes
use std::fs;
use std::path::{Path, PathBuf};
use std::io::Result;

fn dir_contents_excluding(dir: &Path, excluding: &str) -> Result<impl Iterator<Item = PathBuf>> {
    let read_dir = fs::read_dir(dir)?;
    let exclude = excluding.to_string();

    let iter = read_dir.filter_map(move |maybe_entry| {
      match maybe_entry {
          Ok(entry) => Some(entry.path()), // <-- replace with exclude logic
          Err(err) => panic!("Error in dir_contents: {err}")
      }
    });
    Ok(iter)
}

fn main() {
    let dir = Path::new("./my_dir");
    for file in dir_contents_excluding(dir, "bar.txt").unwrap() {
        println!("{:?}", file);
    }
}

The only thing left is to check the entry with exclude. Return None if it is excluded, Some(entry.path()) otherwise.


Como fazer projeto web com wildfly 16?

Question: Não consigo visualizar um HTML File, do WebContent, de teste de arquivo através do link (localhost:8080/Loucademia/teste.html), dá erro(404); o que significa que não to conseguindo acessar pelo navegador. Meu servidor de aplicações é o WildFly versão 16.0.0 e já está com datasource para o MySQL e com driver para o MySQL. Aparecem alguns erros no console que não consigo resolver, referentes a JBOSS e HIBERNATE. Estou usando JPA também, e JSF.
Criei essa classe no src:

<code>import javax.enterprise.context.ApplicationScoped;
import javax.faces.annotation.FacesConfig;
import javax.faces.annotation.FacesConfig.Version;

@FacesConfig( version = Version.JSF_2_3)
@ApplicationScoped
public class Config {

}
</code>

Erros no console quando reinicio o servidor:

Ajudem-me, galera.
Answer: Resolvi!
Criei um DataSource de forma errada. Ao invés de colocar o usuário e senha da conexão do MySQL, coloquei user and pass do WildFly. Putz!

Como fazer projeto web com wildfly 16?


Analysing incoming TCP packet discards on GNU/Linux

Question: I use Ubntu 12.04 Server as a gateway/router. The server has two NetXtreme BCM5721 Gigabit Ethernet PCI Express cards for LAN and WAN interfaces. Opennms monitoring software shows incoming packet discards on the  WAN (ISP) interface. The ISP provides direct Ethernet connectivity via SDH/SONET ring. However I don't see any packet discard on the LAN interface. Here is the WAN interface graph:

Are there any tools/commands to discover what is responsible for such packet discards. Is it possible to know if some misconfiguration at ISP's side is causing such an issue.
Ifconfig Output:
eth1      Link encap:Ethernet  HWaddr **:**:**:**:63:5d
          inet addr:***.***.4.130  Bcast:***.***.4.131  Mask:255.255.255.252
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:865089489 errors:0 dropped:596 overruns:0 frame:3
          TX packets:498072410 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:1092458492329 (1.0 TB)  TX bytes:48179244881 (48.1 GB)
          Interrupt:17

Comment: Can you post the output of `ifconfig` for that interface?
Comment: @Flup I have updated my question.
Answer: The ethtool command is used to query the driver for statistics that the NIC is reporting. ethtool -S ethX will show you the stats for a particular card, and you can see where the drops are.
Most commonly you'll be losing packets in the ring buffer (reported as a stat like "discard" "fifo" "bufs", it varies from card to card) and you resolve this by increasing the ring buffer with ethtool -g. See man ethtool for more.
The netstat command is used to query the kernel's networking stack. netstat -s will show you statistics and you can see if you're losing traffic in the backlog (after NIC but before socket buffer) or in socket buffers (too-small buffers or slow application) or elsewhere.


Making sure floats in binary file are represented as expected on different platforms?

Question: I have a large list of floating point numbers stored in a file as text in the following format
0.0010245  0.4624603  1.326266  -5.203623

The numbers are written out as plain text, then parsed to actual floating points as it's read into the program.
What I would like to do is cache the float representation of 4 bytes, store this as a seperate binary file, and then use it instead of the original plain text one on subsequent runs of the program.  However, I need to make sure the endianness and format of the platform didn't change between runs (if the user upgrades, moves files, or just changes computers).
So I have a test float written to the header of the cached file.  It has stored the 4 byte binary representation of -50.50505050 (just a random magic number).  If the value of the representation in the file matches (within a small error) what the program says it should be, it will use the cached file.  If it is not, it will use the original and regenerate another cached file.
My question is, is this test good enough to ensure the format and endianness of the cached file is correct always?
Answer: You can define the standard for your file. I.e. say that it's always little-endian and 32-bit IEEE float. If your target platform's native representation differs from that then perform the conversion upon read of the file to the native format.
Note that this is an issue only if you share the file between computers (or upgrades like you mentioned). If you always run it on the same configuration, you don't need to worry about the conversion and always just store the native format.
Comment: Since the value is multi-byte, you should put into your standard the Endianness that created it.
Answer: Your solution seems reasonable.  I cannot think of a pair of platforms where you'd get a false positive by moving such a file generated on one platform to the other.
I would avoid the "within a small error" bit, though.  Check that you got exactly the number you expected.  That means you should check for ==.  No arithmetic is occurring, so you will get exactly the number you serialised unless something weird happened, in which case you want to fail over.
Comment: "Check that you got exactly the number you expected" Since the goal is source-code portability though, testing with `==` may require extra care. Say that the C99-compliant compiler defines FLT_EVAL_METHOD to 1 or 2. Then `if (float_read_from_file == -50.50505050f)` will fail because the floating-point literal is stored with double (resp. long double) precision. Testing exact equality is more elegant but requires writing exactly the expected number (hexadecimal is one possibility, picking a value with a short exact decimal representation as sentinel is another).
Comment: Or casting: `if (float_read_from_file == (float)-50.50505050f)`.
Comment: How does this port to platforms that don't have the same endianness?  For example, if your computer is Big Endian and you write to the file and I read the file on my Little Endian platform, what will happen?
Comment: @ThomasMatthews: You get the wrong number and you read the text file, exactly as OP wanted.


Firebase has no response regarding volley request

Question: I am new to firebase. I tried to store user data in firebase database using volley. However, firebase has no response regarding my volley request and the database still is null. This is the tutorial I followed.
This is the volley request I used to connect firebase.
<code>public void executeFirebase(){
    StringRequest request = new StringRequest(Request.Method.GET, FIREBASE_REGISTER_URL, new Response.Listener<String>(){
        @Override
        public void onResponse(String s) {
            Firebase reference = new Firebase("https://tradeal-930ad.firebaseio.com/users");
            if(s.equals("null")) {
                reference.child(name).child("password").setValue(password);
                Toast.makeText(activity, "registration successful 1", Toast.LENGTH_LONG).show();
            }
            else {
                try {
                    JSONObject obj = new JSONObject(s);

                    if (!obj.has(name)) {
                        reference.child(name).child("password").setValue(password);
                        Toast.makeText(activity, "registration successful 2", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(activity, MainPageActivity.class);
                        activity.startActivity(intent);
                        activity.finish();
                        loginUserActivity.finish();
                    } else {
                        Toast.makeText(activity, "username already exists", Toast.LENGTH_LONG).show();
                    }

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

            loading.dismiss();
        }

    },new Response.ErrorListener(){
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            System.out.println("" + volleyError );
            loading.dismiss();
        }
    });

    RequestQueue rQueue = Volley.newRequestQueue(activity);
    rQueue.add(request);
}
</code>
Comment: what is the rules of your database?
Comment: @Shaifali Rajput ".read": "auth != null",
    ".write": "auth != null"
Comment: @Shaifali Rajput I thought I should still get response from volley request even the rule is not correct
Comment: you need to change the rules
Answer: change the rules of your database to public
<code>{
  "rules" :
           {
             ".read"  : true,
             ".write" : true
           }
}
</code>
otherwise
<code>{
  "error" : "Permission denied"
}
</code>
this will be your response
to know more about rules you can visit security rules


What is Boolean.valueOf in JavaScript

Question: Typeof of Boolean.valueOf is a function but what does it do? Why object versions of primitives have these methods like Array.valueOf? It's not the same as for example Boolean.prototype.valueOf...
Also what's the point of Boolean.toString() it just returns this: "function Boolean() { [native code] }". Also other objects like Array, Number have it...
Comment: * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean/valueOf
* Array inherits `valueOf` from Object.prototype.
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/valueOf

MDN: JavaScript calls the `valueOf` method to convert an object to a primitive value. You rarely need to invoke the `valueOf` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected.
Answer: Why it happens
Boolean is a function, just like String and Object, you can call it as a function to convert something to a boolean for example:
Boolean(3); // true

All functions in JavaScript are objects, and as objects they have a .valueOf property. Since Boolean is a function, its valueOf isn't very meaningful though. Since it's calling Object#valueOf via prototypical inheritance it just returns the same object

alert(Boolean.valueOf() === Boolean) // true

// for the same reason
var x = {};
alert(x.valueOf() === x); // true

The specification states:

22.214.171.124 Object.prototype.valueOf
Let O be the result of calling ToObject passing the this value as the argument.

Which in turn does:

9.9 ToObject
The result is the input argument (no conversion).

What it's for
The reason .valueOf exists is to provide an interface for explicit value obtaining. It is used extensively in the background of the language (as the other answer mentions, much like .toString). For example it can take a Number object and convert it into the primitive number data type.
Here is an example:

3 == {valueOf: function(){ return 3; }} // true
4 < {valueOf: function(){ return 2; }} // false
Math.max(3, {valueOf: function(){ return 5; }}) // 5, not the object

It's somewhat incomplete and in all honesty, we don't have a good solution in JavaScript for user defined values until ES7 kicks in with value types.
Comment: Very nice edit! The last example was really interesting
Answer: It seems that .valueOf is similar to .toString method according to output.

JavaScript calls the valueOf method to convert an object to a primitive value. You rarely need to invoke the valueOf method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected.
By default, the valueOf method is inherited by every object descended from Object. Every built-in core object overrides this method to return an appropriate value.

Source
Basically .valueOf is used to return primitive version of object, but you don't need to call it yourself. You could use it in your advantage in your library. For example, you have a request object instead of writing your own method, you could extend .valueOf and return status of request.

Also what's the point of Boolean.toString() it just returns this: "function Boolean() { [native code] }".

I don't sure about Boolean.toString(), but Boolean.prototype.toString() is quite helpful. With .toString method you can get string representation of any object, consider this example:
var bool = true;

console.log(bool.toString()); // "true"

In some cases it's could be helpful to get string representation of an object, but in most cases JS automatically convert object in string during string concatenation (+ operator).
More about .toString.
Comment: Well said. An interesting observation of `.valueOf` on `Boolean` is that `Boolean === Boolean.valueOf()` is true :)
Comment: Yeah, I noticed that too, in case of primitive JS objects (Array, Number, String, etc.), .valueOf is useless, but using for user defined objects is quite helpful, as the example with request. :)
Comment: Array, Number, String etc are all functions, I'm not sure what you mean by "primitive JS objects"
Comment: They are also constructors too, by primitive objects I meant the core objects of the language like primitives in most of the languages (int, char, long, double, etc.) If you didn't knew, everything is object in JS, even `Function`.
Comment: Oh, you mean primitive value types, those are string, number, boolean, null and undefined. Array is not a primitive value type, you can read more about how types work in the language [here](http://es5.github.io/#x8).
Comment: Yeah, maybe I'm confused array with data type, but others are primitives
Comment: As I learn JavaScript it was my main concern about what people meant writing for example "String", "string" or "_string_", not always mentioning if it's a function object or an instance of a primitive type. Finally I got the difference.

What is Boolean.valueOf in JavaScript


formula for the angle between a line and a plane in $R^4$

Question: Is there a formula for the angle between a line and a plane in $R^4$? More precisely, let $E_1$,$E_2$ and $E_3$ be three (non-colinear) vectors in $R^4$. We can always define the angle between two vectors by using "dot product". The angle between the vector $E_1$ and the plane spanned by $E_2$ and $E_3$ can be defined as the minimum angle between $E_1$ and a vector in $span(E_2, E_3)$. Can we explicitly write out this angle in terms of coordinates of $E_1$, $E_2$ and $E_3$?
PS: There is a formula for the angle between two planes in $R^4$. See
Angle between two planes in four dimensions
Comment: Think about the projection of $E_1$ onto the span of $E_2$ and $E_3$.
Comment: @Bye_World What is the definition of left contraction? Is there a formula for it? I just need the four dimensional case.
Comment: @Bye_World No, I don't. It seems quite complicated and not easy to understand for undergrad. It seems to be in a new subject called "Clifford Algebras"
Answer: There's a simple formula for the angle between $A$ (a $j$-blade representing some subspace of $\Bbb R^n$) and $B$ (a $k$-blade representing some other subspace of $\Bbb R^n$), where $j\le k$, given by
$$\cos(\theta) = \dfrac{\|A\ \raise .2em{\lrcorner}\ B\|}{\|A\|\|B\|}$$
where $\raise .2em{\lrcorner}$ is the left contraction product.

But because you're not familiar with geometric algebra, I'll try to give you just enough (non-rigorous) definitions so that you can calculate the angle between any two subspaces of $\Bbb R^n$.
Definitions:
Wedge Product: We define the wedge product, denoted $a\wedge b$, of two vectors $a, b\in \Bbb R^n$ as an object that is neither a vector nor a scalar and obeys all of the following:
$$\begin{align}a \wedge b &= -b \wedge a \\ a\wedge(b\wedge c) &= (a\wedge b)\wedge c \\ a\wedge a &= 0 \\ k(a\wedge b) &= (ka)\wedge b = a\wedge (kb) \tag{$k\in \Bbb R$}\\ a\wedge (b+c) &= a\wedge b + a\wedge c\end{align}$$
Blade: An object formed by the wedge product of $k$ vectors is called a $k$-blade.  We define scalars as $0$-blades, vectors as $1$-blades, objects that can be written as $a\wedge b$ as $2$-blades, objects that can be written as $a\wedge b\wedge c$ as $3$-blades, etc.
$k$-vector: A $k$-vector is a linear combination of $k$-blades.
Multivector: A multivector is a linear combination of $k$-vectors.
Grade: Objects in the algebra we're building have "grades".  All $k$-blades/ $k$-vectors have grade $k$.  But multivectors are in general multigraded objects.  For instance, $B = b_0 + b_1e_1 + b_2 e_2 + b_{12}e_1\wedge e_2$, where $b_i$ are scalars and $e_i$ are vectors, is a multigraded object.
Clifford product: The Clifford product is an associative product of multivectors satisfying:
$$ab = a\cdot b + a\wedge b \\ (AB)C = A(BC) \\ k(AB) = (kA)B = A(kB) \\ A(B+C) = AB+AC$$ for all vectors $a,b$, scalars $k$, and multivectors $A,B,C$.

A consequence of this is that if $\{e_1, \dots, e_n\}$ is an
orthonormal basis of $\Bbb R^n$ then $e_ie_i = e_i\cdot e_i = 1$ for
all $i$ and $e_ie_j = e_i \wedge e_j$ for $i\ne j$.

Grade projection: The grade projection operator, denoted $\langle A \rangle_i$, returns the grade $i$ parts of the multivector $A$.  For instance, $\langle ab\rangle_0 = \langle a\cdot b + a\wedge b\rangle_0 = a\cdot b$.
Norm: The norm of a multivector can be determined in the standard way after decomposing it into an orthonormal basis.  For instance, if $A = a_0 + a_1e_1 + a_2e_2 + a_{12}e_1 \wedge e_2$ then $$\|A\| = \sqrt{a_0^2 + a_1^2 + a_2^2 + a_{12}^2}$$
Left contraction: The left contraction product of a $j$-blade $A$ and a $k$-blade $B$ is defined as $$A\ \raise .2em{\lrcorner}\ B = \langle AB\rangle_{k-j}$$

Now for an example.  Consider the plane spanned by $a=2e_1 +3e_3$ and $b=e_2+e_3$ and the line spanned by $c=2e_1$.
Then the angle between that line and that plane is given by $$\cos(\theta) = \frac{\|c\ \raise .2em{\lrcorner}\ (a\wedge b)\|}{\|c\|\|a\wedge b\|}$$
So let's calculate it:
$$a\wedge b = (2e_1 +3e_3)\wedge (e_2+e_3) = 2e_1\wedge e_2 + 2e_1\wedge e_3 + 3e_3\wedge e_2 = 2e_1e_2 + 2e_1e_3 - 3e_2e_3 \\ \|a\wedge b\| = \sqrt{4+4+9} = \sqrt{17} \\ \|c\| = \sqrt{4} =2 \\ c\ \raise .2em{\lrcorner}\ (a\wedge b) = \langle (2e_1)(2e_1e_2 + 2e_1e_3 - 3e_2e_3)\rangle_1 = \langle 4e_2 + 4e_3 - 6e_1e_2e_3\rangle_1 = 4e_2 + 4e_3 \\ \|c\ \raise .2em{\lrcorner}\ (a\wedge b)\| = \sqrt{16+16} = \sqrt{32} \\ \implies \theta = \arccos\left(\frac{\sqrt{32}}{2\sqrt{17}}\right) \approx 46.7°$$
Answer: Let $\alpha$ be your plane. $X \in \alpha \Leftrightarrow \exists a, b \in \mathbb{R}$ such as $X = a Y_1 + b Y_2$, where $Y_1 = \frac{X_2 - X_1}{|X_2 - X_1|}$, $Y_2 = \frac{X_3 - X_1}{|X_3 - X_1|}$, and $X_1, X_2, X_3 \in \alpha$.
Let $L$ be your line. $X \in L \Leftrightarrow X = P + tD$, where $P \in L$ and $D$ is the normalized director vector ($|D| = 1$).
The distance between then is $d = \min_{a, b, t} |aY_1 + bY_2 - P - tD|$.
Let $f(a, b, t) = |aY_1 + bY_2 - P - tD|$. To find the minimum, we need to solve $\nabla f = 0$.
Doing the math, we need to solve the following linear system:
$$
\pmatrix{
1 & Y_1 \cdot Y_2 & -Y_1 \cdot D \\
Y_1 \cdot Y_2 & 1 & -Y_2 \cdot D \\
-Y_1 \cdot D & -Y_2 \cdot D & 1
}
\cdot
\pmatrix{a \\ b \\ t}
=
\pmatrix{P \cdot Y_1 \\ P \cdot Y_2 \\ -P \cdot D}
$$
Answer: Here's a straightforward approach:  find the unique (up to scalar multiples) non-zero vector $E = c_1 E_1 + c_2 E_2 + c_3 E_3$ that is normal to the plane spanned by $E_2$ and $E_3$.  (This comes down to solving a $2 \times 3$ system of equations of rank $2$.)  Then compute the angle $\theta$ between $E_1$ and $E$.  The angle you seek is $\pi/2 - \theta$.


Get USB port of plugged in device in node

Question: I'm using node-detection to be notify when a USB device was plugged in. However I can't seem to find out how to know to which port was it plugged in to, e.g. sdb1, sdc1, etc. Is there a simple way of doing it?
Comment: are you usig node-usb-detection? on npmjs?  Its based on usb (npmjs). It is hard to get the port. Also looking for it. I will post if I find a solution
Answer: You can use the drivelist module in addition to the node-detection module, made by the excellent folks at resin.io.
The drivelist module lists all connected devices including the mountpoint (path) information. This output is slightly different depending on your operating system. Check the drivelist documentation for more info.
Here's a quick example to find when a removable USB drive is inserted and mounted, and get the mount path.
From some testing, the usb-detection module fires nearly instantaneously when a device is plugged in, but it takes time for the device to mount. So I am using a setInterval to keep checking if a mountpoint exists. Once I find a mountpoint, I clear the interval.
// load modules
var usbDetect = require('usb-detection');
const drivelist = require('drivelist');
var checkUSBintervalID;

// This is the listener function for the 'add' event
function addUSBhandler() {
    console.log('added event listener for usb ADD');

    // Start interval to check if the USB is mounted
    checkUSBintervalID = setInterval(function() {
        drivelist.list(function(error, drives) {
            console.log('listening for USB mount...');
            if (error) { throw error; }

            // iterate through all drives
            for(var d = 0; d < drives.length; d++) {

                // if the drive is a removable usb
                if(drives[d].system == false) {

                    // if this drive is mounted
                    if(drives[d].mountpoints.length > 0) {
                        console.log('found removable USB');
                        // the drive is mounted
                        // do stuff here
                        // the path is at drives[d].mountpoints[0].path
                        clearInterval(checkUSBintervalID);
                    }
                }
            }
        });
    }, 1000);
}

// Add listener for when a USB is plugged in
usbDetect.on('add', addUSBhandler);

This answer does not take into account if the USB is inserted and removed before it is mounted. You probably need to add a timeout or something similar. Hoped this helped, and good luck.
Answer: I think it's not working with node-detection
Maybe not the best way, but this worked for me:
var shell = require('shelljs');
var watch = require('node-watch');
var tmpUsb;

Array.prototype.contains = function(needle){
  for (var i=0; i<this.length; i++)
    if (this[i] == needle) return true;

  return false;
}

Array.prototype.diff = function(compare) {
    return this.filter(function(elem) {return !compare.contains(elem);})
}

getUsb = function() {
      this.usbJson = JSON.parse(shell.exec('lsblk --json', {silent:true}).stdout);
      var dev = this.usbJson.blockdevices;
      var devices = [];
      dev.forEach(function(entry) {
          entry.children.forEach(function(e) {
              devices.push(e.mountpoint);
          });
      });
      return devices;
}

tmpUsb = getUsb();

watch('/dev/disk/by-id', { recursive: true }, function(evt, name) {
    var curr = getUsb();
    var add = curr.diff(tmpUsb);
    var rem = tmpUsb.diff(curr);
    if(add.length > 0) {
      console.log("ADD > " + add);
    }
    if(rem.length > 0) {
      console.log("REM > " + rem);
    }
    tmpUsb = curr;
});

Please add in your question what your output is. What code did you try....
Answer: I don't know about node.js bindings, but using external udevadm tool the info is exposed:
$ udevadm monitor
monitor will print the received events for:
UDEV - the event which udev sends out after rule processing
KERNEL - the kernel uevent

KERNEL[766928.886896] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1 (usb)
KERNEL[766928.888766] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0 (usb)
UDEV  [766929.091194] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1 (usb)
KERNEL[766930.777996] add      /module/usb_storage (module)
UDEV  [766930.780203] add      /module/usb_storage (module)
KERNEL[766930.781054] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4 (scsi)
KERNEL[766930.781241] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/scsi_host/host4 (scsi_host)
KERNEL[766930.781370] add      /bus/usb/drivers/usb-storage (drivers)
UDEV  [766930.782320] add      /bus/usb/drivers/usb-storage (drivers)
KERNEL[766931.092511] add      /module/uas (module)
UDEV  [766931.092584] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0 (usb)
KERNEL[766931.092608] add      /bus/usb/drivers/uas (drivers)
UDEV  [766931.093550] add      /module/uas (module)
UDEV  [766931.094000] add      /bus/usb/drivers/uas (drivers)
UDEV  [766931.094305] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4 (scsi)
UDEV  [766931.095737] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/scsi_host/host4 (scsi_host)
KERNEL[766931.807635] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0 (scsi)
KERNEL[766931.807770] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0 (scsi)
KERNEL[766931.807901] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/scsi_disk/4:0:0:0 (scsi_disk)
KERNEL[766931.807995] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/scsi_device/4:0:0:0 (scsi_device)
KERNEL[766931.809543] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/scsi_generic/sg2 (scsi_generic)
KERNEL[766931.809605] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/bsg/4:0:0:0 (bsg)
UDEV  [766931.811736] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0 (scsi)
KERNEL[766931.812771] add      /devices/virtual/bdi/8:16 (bdi)
UDEV  [766931.815246] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0 (scsi)
UDEV  [766931.815908] add      /devices/virtual/bdi/8:16 (bdi)
UDEV  [766931.818228] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/scsi_disk/4:0:0:0 (scsi_disk)
UDEV  [766931.819748] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/bsg/4:0:0:0 (bsg)
UDEV  [766931.821506] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/scsi_device/4:0:0:0 (scsi_device)
UDEV  [766931.821894] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/scsi_generic/sg2 (scsi_generic)
KERNEL[766931.895701] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/block/sdb (block)
KERNEL[766931.895807] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/block/sdb/sdb1 (block)
KERNEL[766931.895879] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/block/sdb/sdb2 (block)
UDEV  [766933.474661] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/block/sdb (block)
UDEV  [766933.566443] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/block/sdb/sdb2 (block)
UDEV  [766933.658413] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/block/sdb/sdb1 (block)

KERNEL[766942.802911] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/bsg/4:0:0:0 (bsg)
KERNEL[766942.804048] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/scsi_generic/sg2 (scsi_generic)
KERNEL[766942.804163] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/scsi_device/4:0:0:0 (scsi_device)
KERNEL[766942.804246] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/scsi_disk/4:0:0:0 (scsi_disk)
KERNEL[766942.804338] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/block/sdb/sdb2 (block)
KERNEL[766942.804426] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/block/sdb/sdb1 (block)
KERNEL[766942.804518] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/block/sdb (block)
KERNEL[766942.804590] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0 (scsi)
UDEV  [766942.806838] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/bsg/4:0:0:0 (bsg)
UDEV  [766942.807543] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/scsi_generic/sg2 (scsi_generic)
UDEV  [766942.809181] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/scsi_disk/4:0:0:0 (scsi_disk)
UDEV  [766942.809410] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/scsi_device/4:0:0:0 (scsi_device)
UDEV  [766942.812382] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/block/sdb/sdb1 (block)
UDEV  [766942.812545] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/block/sdb/sdb2 (block)
UDEV  [766942.814711] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/block/sdb (block)
UDEV  [766942.815300] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0 (scsi)
KERNEL[766942.816341] remove   /devices/virtual/bdi/8:16 (bdi)
KERNEL[766942.816384] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0 (scsi)
UDEV  [766942.817716] remove   /devices/virtual/bdi/8:16 (bdi)
UDEV  [766942.819175] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0 (scsi)
KERNEL[766942.864803] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/scsi_host/host4 (scsi_host)
KERNEL[766942.864891] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4 (scsi)
KERNEL[766942.865168] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0 (usb)
KERNEL[766942.866960] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1 (usb)
UDEV  [766942.867670] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/scsi_host/host4 (scsi_host)
UDEV  [766942.868469] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4 (scsi)
UDEV  [766942.869291] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0 (usb)
UDEV  [766942.870791] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1 (usb)

Some notes:

There can be more than one partition on a USB stick, or it may have a filesystem directly without partitions.
You probably don't need to monitor for USB devices specifically, just any block device perhaps?
This isn't doing any filtering, you'll get a lot of unrelated events yet.


Is this language $L$ context free?

Question: $L$ is a language combined with the symbols $\texttt{a}$, $\texttt{b}$ and $\texttt{c}$ given by:
$$ L = \{ v\texttt{c}w \mid v, w \in \{ \texttt{a, b} \}^*\text{ and } v \neq w \}.$$
I tried to prove that it is not context-free using the pumping lemma with strings $\texttt{a}^{n}\texttt{c}\texttt{b}^{n}$ or $\texttt{a}^{n}\texttt{bcb}\texttt{a}^{n}$ but it didn't work. My experience tells me that it should be context free since
$$L'=\{ vw \mid v \neq w \}$$
is context-free, but I still cannot find a context-free grammar to generate it. Can anyone kindly give some ideas please?
Comment: @UmbQbify-Key20-: $a,b$, and $c$ are simply the members of the alphabet over which $L$ is defined.
Comment: What is c here?
Comment: @Tawcher Bro I just noticed that you reposted this question. I'm not sure if it was closed because of the formatting. In any case, you can find a MathJax tutorial here: https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Comment: @Kevin López Aquino I am not sure why the first one was closed, maybe the title is too complicated? But thanks for your advice!
Comment: Consider using L' for the second grammar, since it is not equal.
Comment: @JCAA besides someone citing the paper which proves the OP's claim about $L'$, I don't see progress. Rain1's approach is not working IMO. If you have answer, please share it.
Comment: This is not a trivial question. I do not have an answer. The only suggestion I have is post the question to a comp. sci. site.
Answer: I think I've found a grammar $G_L$ that produces the $L$ from the problem (apologies to rain1, your approach does seem to lead to a solution):
S::=E|U
E::=AbM|BaM
A::=ZAZ|aMc
B::=ZBZ|bMc
U::=ZUZ|MZc|cZM
M::=epsilon|MZ
Z::=a|b

Note I'm not in expert in language theory, I may have made an error.
A global overview:
Note that any terminal word created by $G_L$ will contain exactly one $\texttt{c}$. That's because the expansion rules make sure that in U and after E is expanded, exactly one of $A$, $B$ and $U$ are in a word, and the expansion rules never increase that number, and finally each such non-terminal is consumed by an expansion that introduces exactly one $\texttt{c}$.
E and U stand for Equal and Unequal number of symbols left and right of $\texttt{c}$. While the words created from U will encompass exactly the words with one $\texttt{c}$ and an unequal number of symbols to the left and right of that $\texttt{c}$, words from E will encompass all words $\{ v\texttt{c}w \mid v, w \in \{ \texttt{a, b} \}^*\text{ and } v \neq w \text{ and }|v|=|w|\}$, and some more that are also generated from U.
Note that Z will evaluate to a exactly $1$ terminal symbol, so even during intermediate steps when we talk about number of symbols  that will not change further when considering Z's. Also M is just $\{ \texttt{a, b} \}^*$.
Lemma 1: The terminal words created from U ($L_U$) are exactly $\{ v\texttt{c}w \mid v, w \in \{ \texttt{a, b} \}^*\text{ and } |v|\neq|w|\}$.
Proof: As long as U is expanded as ZUZ, the number of symbols to the left and right of U remain equal. If U is then expanded as MZ$\texttt{c}$, there is now an additional Z on the left of $\texttt{c}$, and the number of symbols on the right of $\texttt{c}$ cannot increase further (only Z's or their terminal expansions there). So no matter how further expansions happen, there will always be more symbols on the left of $\texttt{c}$ than on the right of $\texttt{c}$.
Expanding U as $\texttt{c}$ZM works exactly the same, but now there will always be more symbols on the right of $\texttt{c}$ than on the left. Both cases together show that $L_U \subseteq \{ v\texttt{c}w \mid v, w \in \{ \texttt{a, b} \}^*\text{ and } |v|\neq|w|\}$.
Let now $v\texttt{c}w \in \{ v\texttt{c}w \mid v, w \in \{ \texttt{a, b} \}^*\text{ and } |v|\neq|w|\}$, let $l=|v|, r=|w|, m=\min(l,r)$.
Start with $U$ and expand it $m$ times as ZUZ ($m=0$ is no problem). If $m=l$, expand U as $\texttt{c}$ZM , if $m=r$, expand it as MZ$\texttt{c}$. The proof will be totally the same/symmetric for $m=r$, so I'll only show the case $m=l$. Up to now, the intermediate word looks like this:
$$\underbrace{Z\ldots Z}_{l \text{ times}}cZM\underbrace{Z\ldots Z}_{l \text{ times}}$$
Now exapand M $(r-l-1)$ times as MZ (possible, since $l$ is the minimum of $l$ and $r$, and $l\neq r$, so $r-l-1 \ge 0)$, then finally expand M as epsilon. The resultuing word is
$$\underbrace{Z\ldots Z}_{l \text{ times}}c\overbrace{Z\ldots Z}^{1 + (r-l-1) +l \text{ times}} = \underbrace{Z\ldots Z}_{l \text{ times}}c\underbrace{Z\ldots Z}_{r \text{ times}}$$
You can now expand each $Z$ to get exaclty $v$ to the left of $\texttt{c}$ and $w$ to the right of it. That shows $L_U \supseteq \{ v\texttt{c}w \mid v, w \in \{ \texttt{a, b} \}^*\text{ and } |v|\neq|w|\}$ and concludes the proof of Lemma 1.
Now let's look at the expansions of E.  Again there is a symmetry here. Expansion rules for M and Z remain the same if we exchange $\texttt{a}$ and  $\texttt{b}$. If we also exchange A and B, the expansions rules of $A$ and $B$ become the other one. Finally, those exchanges exchange one possible target of E with the other.
Lemma 2: For each terminal word generated from A$\texttt{b}$M, there exists a natural index $k \ge 1$ such that the $k$-th symbol from the beginning is $\texttt{a}$ and the $k$-th symbol after $\texttt{c}$ is $\texttt{b}$.
Proof: We'll prove that the mentioned $\texttt{b}$ in Lemma 2 can be the original $\texttt{b}$ from A$\texttt{b}$M. That means we don't care about the expansions of M. So the only thing to do is to expand A, we do that $t$ times as ZAZ ($t \ge 0$) and then once finally as $\texttt{a}$M$\texttt{c}$, resulting in the word
$$\underbrace{Z\ldots Z}_{t \text{ times}}aMc\underbrace{Z\ldots Z}_{t \text{ times}}b\ldots,$$
were 3 dots indicate whatever may have happened to the original M from A$\texttt{b}$M. As noted earlier, expanding any Z doesn't change the number of symbols.
In addition, in the above word, the only M (which can become none, one or many terminal symbols) is between $\texttt{a}$ and $\texttt{c}$ and possibly already expanded to the right of $\texttt{b}$.
But that means any further substitutions will still have the $\texttt{a}$ as the $(t+1)$-st symbol from the start and $\texttt{b}$ as the $(t+1)$-st symbol after $\texttt{c}$. That proves Lemma 2, with $k=t+1$.
By the symmetry mentioned before the proof of Lemma 2, the next Lemma follows immediately:
Lemma 3: For each terminal word generated from B$\texttt{a}$M, there exists a natural index $k \ge 1$ such that the $k$-th symbol from the beginning is $\texttt{b}$ and the $k$-th symbol after $\texttt{c}$ is $\texttt{a}$.
Now Lemmata 1,2 and 3 show one part of what we need to show, namely that
$$L(G_L) \subseteq \{ v\texttt{c}w \mid v, w \in \{ \texttt{a, b} \}^*\text{ and } v \neq w\} \tag1 \label{sub}.$$
Indeed, starting from S the expansions immediately lead to U, A$\texttt{b}$M or B$\texttt{a}$M. Lemma 1 shows that words derived from U can't even have the same number of symbols before and after $\texttt{c}$, so certainly $v \neq w$.
Lemma 2 and 3 show that any words derived from A$\texttt{b}$M and B$\texttt{a}$M, resp., can't have the same word before and after $\texttt{c}$ either, as there is some $k$ such that their $k$-th symbol is different.
What needs to be done is to prove the other direction of the inclusion! With that helps
Lemma 4: Any word in $\{ v\texttt{c}w \mid v, w \in \{ \texttt{a, b} \}^*\text{ and } v \neq w \text{ and }|v|=|w|\}$ can be derived from E.
Proof: Let
$$u\texttt{c}w \in \{ v\texttt{c}w \mid v, w \in \{ \texttt{a, b} \}^*\text{ and } v \neq w \text{ and }|v|=|w|\}.$$
$v$ and $w$ can't both be the empty word epsilon, as that would imply $v=w$. Since $v$ and $w$ have the same length, being unequal then means there must be a natural index $k$ with $1\le k \le |v|$ where $v$ and $w$ differ.
If the $k$-th symbol is $a$ in $v$ and $b$ in $w$, we'll show that $v\texttt{c}w$ can be derived from A$\texttt{b}$M. If it's the other way around, it can be derived from B$\texttt{a}$M in an exactly analogous way.
Expand the A in A$\texttt{b}$M $(k-1)$ times as ZAZ, then expand it as $\texttt{a}$M$\texttt{c}$, resulting in the word
$$\underbrace{Z\ldots Z}_{k-1 \text{ times}}aMc\underbrace{Z\ldots Z}_{k-1 \text{ times}}bM.$$
Setting $l=|v|=|w|$, expand the M between $\texttt{a}$ and $\texttt{c}$ $(l-k)$ times as MZ, then finally as epsilon, to get the word
$$\underbrace{Z\ldots Z}_{k-1 \text{ times}}a\overbrace{Z\ldots Z}^{l-k \text{ times}}c\underbrace{Z\ldots Z}_{k-1 \text{ times}}bM.$$
Since $k \le l$, this is possible. Do exactly the same for the M at the end after the $\texttt{b}$ and we have derived the word
$$\underbrace{Z\ldots Z}_{k-1 \text{ times}}a\overbrace{Z\ldots Z}^{l-k \text{ times}}c\underbrace{Z\ldots Z}_{k-1 \text{ times}}b\overbrace{Z\ldots Z}^{l-k \text{ times}}.$$
We now have exactly $l$ symbols before and after the $\texttt{c}$. We can substitute the Z's to arrive at $v$ and $w$ respectively. We know what their $k$-th symbol is, all other symbols can be chosen freely, when expanding Z. This concludes the proof of Lemma 4.
Now Lemmata 1 and 4 mean we have proved the other inclusion
$$L(G_L) \supseteq \{ v\texttt{c}w \mid v, w \in \{ \texttt{a, b} \}^*\text{ and } v \neq w\} \tag2 \label{sup}.$$
because
$$\{ v\texttt{c}w \mid v, w \in \{ \texttt{a, b} \}^*\text{ and } v \neq w\} = \{ v\texttt{c}w \mid v, w \in \{ \texttt{a, b} \}^*\text{ and } |v|\neq|w|\} \cup \{ v\texttt{c}w \mid v, w \in \{ \texttt{a, b} \}^*\text{ and } v \neq w \text{ and }|v|=|w|\},$$
and Lemma 1 proves the first subset is countained in $L(G_L)$ and the Lemma 4 proves it for the second subset.
\eqref{sub} and \eqref{sup} together prove what I stated at the beginning:
$L(G_L)=L.$
Comment: Amazing, I must say.
Answer: A grammar $L'$ is given in the paper [1]:
S ::= E|U|epsilon
E ::= AB|BA
A ::= ZAZ|a
B ::= ZBZ|b
U ::= ZUZ|Z
Z ::= a|b

Perhaps it could be modified for $L$ as follows:
E ::= AcB|BcA
U ::= ZUZ|Zc|cZ

Edit: Actually U is a bit harder to modify, it is the case where we have an odd length string. c needs to be able to appear anywhere in the string.
[1] https://pdfs.semanticscholar.org/a8dd/2ef009df7601cdbc90332765a56a24c7821c.pdf
Comment: But, how would this grammar generate strings like 'aacbb' or 'aaaacbbbb' ? It seems to ignore the case when both w and v are even length strings.
Comment: I think the problem is backwards. Your new rules doesn't seem to be able to create $aacab$, for example, mostly because $A$ and $B$ will always create an odd number of terminal symbols. That wasn't a problem in the original paper, as that meant the resulting string was even, and no $c$ symbol needed to be in the middle.
Generally, the "even/odd" distinction doesn't really work here, as $accb$ has an even length, but still needs to be rejected, as it contains 2 $c$'s.

Is this language $L$ context free?


Enviar mais de um registro para um mesmo cadastro no Banco de dados

Question: Possuo cadastro de dependentes com o form enviando corretamente para o BD.
Me deparei com o problema que não me atentei de que o trabalhador pode ter mais de uma dependente, gostaria de saber como posso adicionar mais de um dependente ao funcionário, crio mais campos para caso tenha outros dependentes mas como ficará e/ou enviará para meu BD e gravar junto com o funcionário?
Esse é meu código para adicionar dependente;

Tipo de Dependente:
  <select name="tpDep" id="tpDep">
    <option></option>
    <option value="01">Cônjuge;</option>
    <option value="02">Companheiro(a) com o(a) qual tenha filho ou viva há mais de 5 (cinco) anos ou possua Declaração de União Estável;</option>
    <option value="03">Filho(a) ou enteado(a);</option>
    <option value="04">Filho(a) ou enteado(a), universitário(a) ou cursando escola técnica de 2º grau;</option>
    <option value="06">Irmão(ã), neto(a) ou bisneto(a) sem arrimo dos pais, do(a) qual detenha a guarda judicial;</option>
    <option value="07">Irmão(ã), neto(a) ou bisneto(a) sem arrimo dos pais, universitário(a) ou cursando escola técnica de 2° grau, do(a) qual detenha a guarda judicial;</option>
    <option value="09">Pais, avós e bisavós;</option>
    <option value="10">Menor pobre do qual detenha a guarda judicial;</option>
    <option value="11">A pessoa absolutamente incapaz, da qual seja tutor ou curador;</option>
    <option value="12">Ex-cônjuge;</option>
    <option value="99">Agregado/Outros;</option>

  Nome:
  <input name="nmDep" type="text" id="nmDep" size="70" maxlength="70" />

  Data de Nascimento:
  <input name="dtNascto" type="text" placeholder="DD/MM/AAAA" id="dtNascto" size="10" maxlength="10" />

  CPF:
  <input name="cpfDep" type="text" id="cpfDep" size="15" maxlength="11" />

  Deduz IRRF?
  <input name="depIRRF" type="radio" value="S" />
    Sim
    <input name="depIRRF" type="radio" value="N" />
    Não

Salário Família?
  <input name="depSF" type="radio" value="S" />
    Sim
    <input name="depSF" type="radio" value="N" />
    Não

Defic. Fisica ou Mental?
  <input name="incTrab" type="radio" value="S" />
    Sim
    <input name="incTrab" type="radio" value="N" />
    Não

Answer: O ideal é ter uma tabela para o trabalhador e uma tabela separda só para os dependentes. Aí você utiliaza o id do trabalhador como chave estrangeira na tabela de dependentes.
Já na programação. Você permite a adição de um número de dependentes de forma fixa (3 por exemplo) ou dinâmica, com um botão "Adicionar Dependente" que através de javascript adiciona campos no próprio formulário de cadastro do trabalhador. Ou uma rota separada específica só para o cadastro de dependentes após o cadastro do trabalhador.
De qualquer forma, você terá de fazer 2 querys de INSERT, uma para o trabalhador e outra para cada dependente tendo como chave estrangeira de trabalhador, o trabalhador cadastrado anteriormente.
Comment: Obrigado David, parei aqui e pensei na mesma coisa, fazer separados, será o melhor caminho mesmo. Muito obrigado!


Ionic Capacitor iOS Firebase App Fails To Start

Question: My Ionic Capacitor App fails to start on iOS (White screen)
Only clue in the console is this -
[error] - ERROR Error: Uncaught (in promise): Error: This operation is not supported in the environment this application is running on. "location.protocol" must be http, https or chrome-extension and web storage must be enabled.
Working fine on Android - I'm not using social sign-ins (use email)
Really not sure on this
Answer: I did this to fix
<code>npm i @angular/fire
npm update @angular/cli @angular/core
</code>
Weird that Android worked fine on the same version of @angular/fire


Can groovy's swingbuilder get more than one look and feel in a Java swing application?

Question: Via this question, it would seem that normally you can't mix-and-match look and feels in the same swing app.
However, we've been using groovy's swingbuilder to handle all of our GUI code, and groovy seems to do enough black magic that this seemed in the Realms of the Possible.
Can swingbuilder set the LaF at, say, the Frame level?
(Specifically, the main app opens a specific sub-utility in it's own frame, rather than a dialog box.  This child frame and all of its children are what I'd like to have in a different LaF from the main app frame.)
Answer: For the record, the answer is "no."


How to determine if a set is convex?

Question: I understand what is a convex set and also know the definition of convex set (all connecting lines lie inside the set) but when i am asked to determine if a following set is convex I am not able to apply the convex rule on that set .Can someone explain how you will find out which of the following are convex sets?
<code>(a) Ω = {x ∈ Rn | x'x ≤ 10}
(b) Ω = {x ∈ Rn | ||x||2 ≤ 10}
(c) Ω = {x ∈ Rn | ||x||2 ≥ 10}
(d) Ω = {x ∈ Rn | a'x ≥ 10}
(e) Ω = {(x, y) ∈ Rn × Rn | ||y||2 ≤ 10 + x'y − ||x||22}
</code>
Image:
Question in image format
Comment: If you know a little bit of linear functional analysis, the above are easy. Maybe you can set $n=1$ or $n=2$, then you can draw a figure explicitly.
Comment: MathJax, please.
Answer: Note: This is a partial answer, motivated more towards hints, but is also incomplete since I'm not sure how to get a good grasp on the final one.

$
\newcommand{\R}{\mathbb{R}}
\newcommand{\setb}[2]{\left\{ #1 \, \middle| \, #2 \right\}}
\newcommand{\t}{\textsf{T}}
\newcommand{\n}[1]{\|#1\|_2}
$
It will help to visualize these in lower-dimensional space for your $n$ values.

For part (a):

If $n=1$ then $\Omega = \{x \in \Bbb R \mid -\sqrt{10} \le x \le \sqrt{10} \}$, clearly a convex set.

If $n=2$, let $x := (\xi_1,\xi_2) \in \R^2$. Then
$$
x^\t x = x \cdot x = \xi_1^2 + \xi_2^2
$$
and $x \in \Omega \iff \xi_1^2 + \xi_2^2 \le 10$. This should seem familiar (think of the equation of a circle).

In general, for $x := (\xi_1,\cdots,\xi_n) \in \R^n$,
$$
x \in \Omega \iff \sum_{i=1}^n \xi_i^2 \le 10
$$

For part (b): Consider the result of part (a), and how it relates to a norm. You can, for instance, recall that the dot product is an inner product, and in $\R^n$,
$$
\| x \|_2 = \sqrt{ x \cdot x }
$$

For part (c): What you have in this part is (almost) the complement of the $\Omega$ in part (b). Visualize what the $\Omega$ in part (b) looks like (some sort of circle); would space (with a hole deleted) be convex?

For part (d): Here I assume we fix some $a := (a_1,\cdots, a_n) \in \R^n$.

If $n=1$, then you get lines when you solve the inequality $a_1 x \le 10$.

If $n=2$, then you get half-planes, regardless of what $a_1,a_2$ are (unless they are both zero). (Try some values of them in this Desmos demo.)

In general you should be able to conjecture you (almost) always get half-spaces.

For part (e):

Try the $n=1$ case; with some simplification, you have
$$
\Omega = \setb{ (x,y) \in \R^2 }{ y^2 \le 10 + xy  - x^2}
$$
This curiously is a filled-in ellipse.

Obviously, we can't visualize well anything in higher dimensional spaces though, so I'm a bit lost... The standard equation for an ellipse in $n$ dimensions would be (for $x := (x_1,\cdots,x_n) \in \R^n$ the points of the ellipse, and $a_i$ the semi-axes)
$$
\sum_{i=1}^n \frac{x_i^2}{a_i} = 1
$$
but I'm not sure how to extract that easily out of what is given.
Comment: All but c) can be solved by a simple result that the set $\{f(x)\le C\}$ is convex if $f$ is convex. In Part e) the function $f(x,y)=\|x\|^2-x^Ty+\|y\|^2$ is convex (try Hessian or completing the square).
Comment: For Part d) the operator is greater than and not less than, it is convex if it is less than , is not it?
Comment: @GopalaKrishna For the part d) just apply the result to $f(x)=-a^Tx$. A linear function is convex.

How to determine if a set is convex?


Matroids and minimal dependence

Question:
Let $M = (E, S)$ be a matroid and $D$ be the set of all minimal dependent sets of $M$. Prove that if $A_1, A_2 \in D$ such that $A_1 \neq A_2$, and if $x \in A_1 \cup A_2$, then there exists $B \in D$ satisfying $B \subseteq (A_1 \cup A_2) \setminus \{x\}$.

Solution:
Assume there is a $C = A_1 \cup A_2$. Because, $A_1, A_2 \in D$, it follows that $C \in D$. This implies that $B \subset C$, which means that $B$ is independent and therefore we conclude that $B \notin D$.
My proof looks a bit vague and different, and I don't even know whether it is actually true. Any ideas?
Comment: If $A_1\ne A_2$, then $A_1\cup A_2$ is *not* in $D$: it's dependent, but it's not minimal dependent, because all minimal dependent sets are the same size.
Comment: So therefore, assuming $|A_1| = |A_2| + 1$, and $x \in A_1$. We get that $A_1$ is also not minimal. And that $B = A_2$, where both are minimal. But according to this we can get that $A_2 \subset A_1$, which in turn will mean that $A_2$ is independent and not in $D$. Any thoughts?
Answer: Is the question phrased correctly?
See the following link: Preposition 1.2
http://math.mit.edu/~goemans/18438F09/lec9.pdf
This link also contains a proof for preposition 1.2
It is the same axiom, but with intersection in place of union
Comment: @portal: I know. But if $x\in A_1\cup A_2$, then either $x\in A_1\setminus A_2$, $x\in A_2\setminus A_1$, or $x\in A_1\cap A_2$. I pointed out why the first two cases are pretty trivial, and the argument in the PDF takes care of the third.
Comment: I don't believe it's the same thing.
Comment: @portal: Yes, the second part of Proposition 1 is exactly your problem: *circuit* is the same thing is *minimal dependent set*.
Comment: @BrianM.Scott: The problem is the question in the link is phrased slightly different...it involves an intersection and not a union. I am wondering if the question in OP is written incorrectly.
Comment: The proposition in the linked PDF deals with the hard case. If $x\in A_1\setminus A_2$, you can just take $B=A_2$. Similarly, if $x\in A_2\setminus A_1$, you can take $B=A_1$. Thus, it's only when $x\in A_1\cap A_2$ that you really have anything much to prove.
Comment: I checked again, and yes my problem involves union.
Comment: What does it want to say with this part: Extend X − f to a maximal independent set in X ∪ Y? How can we extend? Or is it just assuming?

Matroids and minimal dependence


Seeking proofs that depend on the notion of even-vs-odd parity to prove their points

Question: The notion of the parity is very important in a variety of branches of mathematics. Specifically, I am looking for proofs that use parity in the even-vs-odd sense to prove their points.
For example, it is instructive to show that $\sqrt{2}$ is irrational by contradiction and assuming there exist relatively prime integers $m,n$ where $n \neq 0$ such that $\frac{m^2}{n^2} = 2$. By assuming that $m^2$ is even, you can arrive at a contradiction. A similar argument applies when assuming that $m^2$ is odd$.
Another example is showing that the alternating group of even permutations ($A_n$ within $S_n$) is a subgroup under composition of permutations. That claim can be extended to show that the odd permutations of $S_n$ do not form a subgroup.
I'm not looking for explanations of even/odd functions or how to partition $n$ into distinct odd/even parts, but rather my question is:

What proofs exists that depend on the notion of even-vs-odd parity to prove their points?

Ideally an answer will supply a description of the theorem/proof or a reference or a full proof itself.
Answer: The parity of the order of a finite group plays an enormous role in finite group theory!
The Feit-Thompson Theorem settled Burnside's conjecture that every non-Abelian simple group has even order.
There were numerous stepping-stones along the way, and a big part of the classification of finite simple groups was devoted to studying how involutions (non-identity elements of order two, guaranteed to exist in groups of even order, by Cauchy's theorem) affect the structure of a group; in particular looking at what's possible for the centralizer of an involution (apparently this is a consequence of the Brauer-Fowler Theorem, although I don't see the connection).
One such stepping stone was Suzuki's CA paper, which studied groups (now called CA groups) in which the centralizer of any non-identity element is Abelian. In this paper, Suzuki showed that any CA group with odd order is solvable, and hence not simple.
Answer: In even-dimensional Euclidean spaces, spherical waves have trailing edges; in odd-dimensional spaces they don't.
Answer: The case of even perfect numbers is settled since long ($P=M(M+1)/2$ for $M$ a Mersenne prime). That of odd perfect numbers is still open.

The diophantine equation
$$x^p+y^p=z^p$$ where $p$ is a prime only has solutions for even $p$.
Comment: Saying "the case" "is settled" seems to mean a particular case of some particular question, and you haven't said which question it is.  Much is not know about even perfect numbers; for example, nobody knows how many there are. ${}\qquad{}$
Comment: @MichaelHardy: feel free to clarify my answer.
Comment: @Yves Daoust: Macroscopic REFERENCE to parity is a far cry from microscopic USE of parity, which is evidently what the OP is seeking.
Comment: @EulerSpoiler: haha.
Answer: Euler, in his proof that all even perfect numbers have the form given by Euclid, used a very slick parity (odd/even) argument.
Also, parity is crucial in the canonical solution to the problem of generating Pythagorean triples.
Also, by a parity argument, it is proved that the number of sides of a golygon is a multiple of 8.
Here is the link to the Wikipedia article on golygons:
https://en.wikipedia.org/wiki/Golygon
It's worth noting that in Language Arts, opposite parities can co-exist. That is, certain expressions, like 'to dust' possess antonymous meanings. Such expressions are called auto-antonyms. Here is the link to the Wikipedia article on this topic:
https://en.wikipedia.org/wiki/Auto-antonym#:~:text=An%20auto%2Dantonym%20or%20autantonym,is%20the%20reverse%20of%20another.&text=This%20phenomenon%20is%20called%20enantiosemy,%22)%2C%20antilogy%20or%20autantonymy.
Answer: A really good example of a proof that depends on the notion of parity is on Don Zagier's one sentence proof that every prime $p$ of the form $4k+1$ can be written as the sum of two squares. His proof is below:
"The involution on the finite set $\left\{S=(x,y,z)\in\Bbb{N}^3:x^2+4yz=p\right\}$ defined by
$$(x,y,z)\rightarrow
\left\{
\begin{array}{ll}
(x+2z,\space z,\space y-x-z) &\text{if}\space x<y-z\\
(2y-x,\space y,\space x-y+z) &\text{if}\space y-z<x<2y \\
(x-2y,\space x-y+z,\space y) &\text{if}\space 2y<x
\end{array}
\right.
$$
has exactly one fixed point, so $|S|$ is odd and the involution defined by $(x,y,z)\rightarrow (x,z,y)$ also has a fixed point."
I have written a thorough and detailed explanation for how this proof works in case anyone is interested.
For every prime $p$ the set $S$ is non-empty and finite. The solution $(1,1,k)$ always works this demonstrates that the set always has at least one solution. The $k$ in $(1,1,k)$ comes from the $4k+1$ near the top of this answer. (The particular solution $(1,1,k)$ will be important later.) By definition $x,y,z$ are all natural numbers and each must be less than the finite number $p$ because of the equation $x^2+4yz=p$. This shows that the number of solutions is finite.
The order of the numbers in the triplet is important. For example when $p=17$ the solution  $(3,1,2)$ is a different solution from $(3,2,1)$.
An involution is defined as a function that is it's own inverse. For example $f(x)=\frac{1}{x}$ is an involution because $f(f(x))=\frac{1}{f(x)}=\frac{1}{\frac{1}{x}}=x$. A second example is $g(x)=-x\quad g(g(x))=-g(x)=-(-x)=x$.
Fixed points of functions are when the input of the function equals the output of the function. The fixed points of $f(x)=\frac{1}{x}$ occur at $x=1$ and $x=-1$ because it is when $x=f(x)\rightarrow x=\frac{1}{x}\rightarrow x^2=1 \rightarrow x=\pm1$.
The cardinality of a set is the number of elements in the set. If $A$ is a set, then the cardinality of a set can be denoted as $|A|$. If $A=\left\{1,2,3,6,8\right\}$ then $|A|=5$
I now want to show that the map:
$$(x,y,z)\rightarrow
\left\{
\begin{array}{ll}
(x+2z,\space z,\space y-x-z) &\text{if}\space x<y-z\\
(2y-x,\space y,\space x-y+z) &\text{if}\space y-z<x<2y \\
(x-2y,\space x-y+z,\space y) &\text{if}\space 2y<x
\end{array}
\right.
$$
is well defined. There are two steps to this, the first is to show that the inequalities are valid and the second is to show that the numbers in the second set of triplets are all natural numbers.  $x\neq y-z$ because if it did then the expression $x^2+4yz$ wouldn't be prime. If $x=y-z$ then $x^2+4yz=(y-z)^2+4yz=y^2-2yz+z^2+4yz=y^2+2yz+z^2=(y+z)^2$ The last expression is clearly a square which can't be prime. If $x=2y$ then $4$ divides $x^2+4yz$. $x^2+4yz=(2y)^2+4yz=4y^2+4yz=4(y^2+yz)$ the last term is clearly divisable by $4$ and therefore $x\neq 2y$. The expression $2y\le y-z$ is impossible. $2y\le y-z \rightarrow y \le -z$ a natural number can't be less than or equal to a negative number. Therefore $y-z\lt 2y$. The only possibilities left are the one shown in the mapping: $x\lt y-z\lt 2y$ or $y-z\lt x\lt 2y$ or $y-z\lt 2y\lt x$. This means that the inequalities are valid.
The mapping shows three triplets (for a total of nine entries). The entries with only positive terms must produce natural numbers. The entries that might be negative are the ones with negative terms. The inequality of the first triplet shows that the third entry is positive $x\lt y-z \rightarrow 0\lt y-x-z$. The inequality of the second term show that both the first entry and the third entry are positive. $x\lt 2y \rightarrow 0\lt 2y-x$ and $y-z\lt x \rightarrow 0\lt x-y+z$. The inequality of the third term shows that the first entry is positive $2y\lt x \rightarrow 0\lt x-2y$. If $2y\lt x$ then $y-z\lt x\rightarrow 0<x-y+z$. This shows the second entry of the third triplet is positive. All entries of all triplets are natural numbers.
Now I want to show that the new triplets are solutions to $p$. For the first triplet every $x$ in the expression $x^2+4yz$ is substituted with $x+2z$, every $y$ is substituted with $z$ and every $z$ is substituted with $y-x-z$. The substitutions look like this: $x^2+4yz \Rightarrow (x+2z)^2+4(z)(y-x-z)=x^2+4xz+4z^2+4yz-4xz-4z^2=x^2+4yz$
For the second triplet every $x$ in the expression $x^2+4yz$ is substituted with $2y-x$, all $y$'s stay the same and every $z$ is substituted with $x-y+z$. The substitutions look like this: $x^2+4yz \Rightarrow (2y-x)^2+4(y)(x-y+z)=4y^2-4xy+x^2+4xy-4y^2+4yz=x^2+4yz$
For the third triplet every $x$ in the expression $x^2+4yz$ is substituted with $x-2y$, every $y$ is substituted with $x-y+z$ and every $z$ is substituted with $y$. The substitutions look like this: $x^2+4yz \Rightarrow (x-2y)^2+4(x-y+z)(y)=x^2-4xy+4y^2+4xy-4y^2+4yz=x^2+4yz$
Now I want to show that the mapping is an involution by using the second set of triplets as an input.It is easy to get confused on this part of the post.  To try and help avoid confusion I will put down a separate mapping with slightly different labels.
$$(a,b,c)\rightarrow
\left\{
\begin{array}{ll}
(a+2b,\space c,\space b-a-c) &\text{if}\space a<b-c\\
(2b-a,\space b,\space a-b+c) &\text{if}\space b-c<a<2b \\
(a-2b,\space a-b+c,\space b) &\text{if}\space 2b<a
\end{array}
\right.
$$
Now if we use the first triplet from the $(x,y,z)$ mapping as an input to this one then $a=x+2z,b=z,c=y-x-z$ in this case the output is the third triplet of the $(a,b,c)$ mapping because $2b\lt a$. So the output is $(a-2b,\space a-b+c,\space b)$. Now we just apply the substitutions to get the output in terms of $x,y,$ and $z$. $((x+2z)-2(z),(x+2z)-(z)+(y-x-z),(z))=(x+2z-2z,x+2z-z+y-x-z,z)=(x,y,z)$
If the second triplet from the $(x,y,z)$ mapping is the input for the $(a,b,c)$ mapping then $a=2y-x,b=y,c=x-y+z$ in this case the output is the second triplet of the $(a,b,c)$ mapping because $b-c\lt a\lt 2b$. So the output is $(2b-a,\space b,\space a-b+c)$. Now we just apply the substitutions to get the output in terms of $x,y,$ and $z$. $(2(y)-(2y-x),(y),(2y-x)-(y)+(x-y+z))=(2y-2y+x,y,2y-x-y+x-y+z)=(x,y,z)$
If the third triplet from the $(x,y,z)$ mapping is the input for the $(a,b,c)$ mapping then $a=x-2y,b=x-y+z,c=y$ in this case the output is the first triplet of the $(a,b,c)$ mapping because $a\lt b-c$. So the output is $(a+2c,\space c,\space b-a-c)$. Now we just apply the substitutions to get the output in terms of $x,y,$ and $z$. $((x-2y)+2(y),(y),(x-y+z)-(x-2y)-(y))=(x-2y+2y,y,x-y+z-x+2y-y)=(x,y,z)$
This shows that the mapping is an involution. Applying the map twice got the original output back in all three cases.
Now I want to find all of the fixed points of the mapping. If the first triplet is the same as the input then $x=x+2z$ and $y=z$ and $z=y-x-z$
$x=x+2z\rightarrow 0=2z \rightarrow 0=z$
$y=z\rightarrow y=0$
$z=y-x-z\rightarrow 0=-x \rightarrow x=0$
There are no fixed points from the first triplet.
If the second triplet is the same as the input then $x=2y-x$ and $y=y$ and $z=x-y+z$
$x=2y-x\rightarrow 2x=2y \rightarrow x=y$
$z=x-y+z\rightarrow 0=x-y \rightarrow y=x$
if $y=x$ then $x^2+4yz=x^2+4xz=x(x+4z)=p=4k+1$
Since $x(x+4z)$ is prime and $x\lt x+4z$ the only way that this can produce a prime is if $x=1$. So $x(x+4z)=4z+1=4k+1\rightarrow 4z=4k\rightarrow z=k$.
The second triplet has one fixed point $(1,1,k)$.
If the third triplet is the same as the input then $x=x-2y$ and $y=x-y+z$ and $z=y$
$x=x+2y\rightarrow 0=2y \rightarrow 0=y$
$y=x-y+z\rightarrow 0=x+z\rightarrow -x=z$
$z=y\rightarrow z=0 \rightarrow -x=0 \rightarrow x=0$
There are no fixed points from the third triplet.
There is only one fixed point from the mapping. If all solutions come in pairs with the sole exception of the fixed point this means that there are an odd number of solutions or in other words $|S|$ is odd. With this new knowledge one can use a second mapping $(x,y,z) \rightarrow (x,z,y)$. This second mapping has no inequalities. The second mapping's output are clearly natural numbers. The output gives the same result for $p$, since $x^2+4yz=x^2+4zy$. This second mapping is also clearly an involution because switching the $y$ and $z$ terms twice is the same as not switching them at all. All solutions of the second mapping have two cases the first is that the two solutions $(x,y,z)$ and $(x,z,y)$ are different and in pairs. The second case is that $(x,y,z)$ and $(x,z,y)$ are the same solution (A fixed point). Since it known that $|S|$ is odd there must be an odd number of fixed points (at least one). If $(x,y,z)$ and $(x,z,y)$ are the same solution then $y=z$ which means $x^2+4yz=x^2+4y^2=x^2+(2y)^2$. This means that $p$ can be written as the sum of two squares.


Interpreting effects of categorical and continuous predictors in multiple linear mixed models

Question: I'm building a LMM model with a continuous DV (signal amplitude) and two IV: one continuous (questionnaire score) and one categorical with 3 levels (condition). Conditions are: S, M and SM (the last being a combination of the first two). They are dummy coded and SM is set as the reference level. I use one random effect - a random intercept for subjects. Each subject encountered all the conditions.
This is the model in R's lme4:
m = lmer(DV ~ Q.score * cond + (1|subj), data = df, REML = FALSE)

(I read that with balanced designs and only one random effect I can use ML instead of REML.)
lmerTest::summary() gives these estimates of fixed effects:
(According to the documentation, the t- and p- values are calculated with Satterthwaite approximation for degrees of freedom)
    Fixed effects:
                    Estimate Std. Error         df t value    Pr(>|t|)
(Intercept)        -0.941813   0.179603 103.900000  -5.244 0.000000832 ***
Q.score            -0.043102   0.024048 103.900000  -1.792       0.076 .
condSMvsM           0.752574   0.179470 104.000000   4.193 0.000057923 ***
condSMvsS           0.385522   0.179470 104.000000   2.148       0.034 *
Q.score:condSMvsM   0.005157   0.024030 104.000000   0.215       0.830
Q.score:condSMvsS   0.024290   0.024030 104.000000   1.011       0.314

Since cond is a multilevel categorical predictor, it's easier to interpret the results looking at the whole effect of the predictor. I know there are many ways of doing that so I tried a few, but I am surprised by the differences between them, especially in the p-values for the interaction (short comment: I know p-values aren't the miraculous answers to what is or is not true, but I simply have to get them, as my boss requires so, so please take a deep breath with me and be so kind to help anyway...).
1) Analysis of variance table of type II (or whatever you specify as the SS type) with  Satterthwaite approximation for degrees of freedom - lmerTest::anova
              Sum Sq Mean Sq NumDF DenDF F.value    Pr(>F)
Q.score       2.4049  2.4049     1    52  2.8717 0.0961287 .
cond         14.7285  7.3643     2   104  8.7937 0.0002961 ***
Q.score:cond  0.9501  0.4750     2   104  0.5672 0.5688346

2) Analysis of Deviance Table (Type II Wald chisquare tests) - car::Anova
               Chisq Df Pr(>Chisq)
Q.score       2.8717  1  0.0901471 .
cond         17.5875  2  0.0001517 ***
Q.score:cond  1.1345  2  0.5670901

3) The likelihood ratio test - with lmer models
> m0 = lmer(DV ~ 1 + (1|subj), data=df, REML = FALSE)
> m1 = lmer(DV ~ Q.score + (1|subj), data=df, REML = FALSE)
> m2 = lmer(DV ~ cond + (1|subj), data=df, REML = FALSE)
> m3 = lmer(DV ~ Q.score * cond + (1|subj), data=df, REML = FALSE)
> anova(m0,m1,m2,m3)
Data: df
Models:
object: DV ~ 1 + (1 | subj)
..1: DV ~ Q.score + (1 | subj)
..2: DV ~ cond + (1 | subj)
..3: DV ~ Q.score * cond + (1 | subj)
       Df    AIC    BIC  logLik deviance   Chisq Chi Df Pr(>Chisq)
object  3 513.25 522.40 -253.62   507.25
..1     4 512.45 524.65 -252.23   504.45  2.7953      1  0.0945439 .
..2     5 501.16 516.41 -245.58   491.16 13.2916      1  0.0002666 ***
..3     8 503.24 527.64 -243.62   487.24  3.9236      3  0.2698349

And here is my first question:
(1) Which test do I use to report an effect fo a categorical predictor? Should it be F-value from analysis of variance? Or chi square statistics (if so, from the analysis of deviance or from the likelihood ratio test)?
The effects don't differ very much in my example, but I am still facing another problem:
(2) How to describe the direction of an effect of a multilevel categorical predictor?
I have seen publications in which authors report coefficients, t-values and SD of fixed effects. If I understand correctly, I could do the same from the summary() output (see the first piece of code). However, since I can only report pairwise comparisons between levels, I would have to change contrasts to address the pair of levels which are not the reference level in my first model - here: S vs. M. (I don't have an easy way of deciding on the contrasts (like clinical group vs. control group), but three arbitrary conditions).
For example, this is summary for the same model with condition M as the reference value (as compared to SM above):
Fixed effects:
                    Estimate Std. Error         df t value  Pr(>|t|)
(Intercept)        -0.189239   0.179603 103.900000  -1.054    0.2945
Q.score            -0.037945   0.024048 103.900000  -1.578    0.1176
condMvsS           -0.367052   0.179470 104.000000  -2.045    0.0434 *
condMvsSM          -0.752574   0.179470 104.000000  -4.193 0.0000579 ***
Q.score:condMvsS    0.019133   0.024030 104.000000   0.796    0.4277
Q.score:condMvsSM  -0.005157   0.024030 104.000000  -0.215    0.8305

And here I have two problems:
(3) Why does the continuous predictor's coefficient and t value change with different contrasts of the categorical predictor?
The Q.score t and p values changed. Of course the overall effect of this predictor stays the same (as found by one of the above methods). Does is mean that the value of Q.score decreases more when "going" from the M than SM condition?
Should I then only report the general effect of this predictor (like in the above methods)?
(4) Shouldn't I apply some kind of correction for multiple comparisons if I change the contrasts to explore all pairwise comparisons? Can I do it at all?...
And one more general question in the end:
(5) How to acquire a general F statistic of the whole model? Or is R^2 and adj. R^2 enough?
I know it's a lot for one post, but I really read everything I could find and I'm still stuck. I would really, really appreciate your help with any of these questions!
Comment: Since your questions are almost identical to the issues I have bumped into, I was wondering if you have gotten any insights since you have posted this question? Thank you so much!
Answer: Since @mhoven asked, here are the answers to my own old questions:
I ended up following those (regarding the questions in the post):

Now I'm using the anova from lmerTest to describe the main effect of a multilevel categorical predictor;
To describe a direction, I change the contrasts. Then I do a correction for multiple comparisons.
Well, the estimate of the continues predictor changes with different contrasts of the categorical predictor, because it's estimated for the specific conditions, e.g., S-M, S-SM, M-SM. Of course it's different, as the model describes the effect of the continuous predictor for a certain pairwise comparison of the categorical levels.
Yes, as in 2. I normally just use Bonferonni.
I now report adjusted and marginal R^2 for the model.
Hope that helps!


SQL Server physical data layout for tables without indexes

Question: I'm curious to see if anyone knows how is the data physically arranged in tables that don't have an index (not even a PK). In this question the OP claims it is taking a long time to drop a clustered PK. I know that the clustered index is the data itself, but what would be the new data arrangement that explains the long processing time?
Answer: It will be a HEAP:

A heap table, by definition, is a table that doesn't have any clustered indexes.
Different pages of the heap-based table occupy different non-contiguous areas on a disk, and they are not linked together in any way.
Each non-clustered index defined on the table will have a corresponding entry in a sysindexes table with an indid between 2 and 254, pointing to the first IAM (Index Allocation Map) page.
IAM pages represent the linked list of all pages used by the database object (table or index) and used by SQL Server for allocating and deallocating storage space.
It is important to remember that IAM pages are not used to search through data or index pages, but only to allocate and deallocate them.
Comment: Hmm the link above gives me a 404.


Properties of tensor product of modules

Question: Let $M'$ be a submodule of $\mathbb{Z}$-module $M$, and let $i:M'\rightarrow M$ be a natural monomorphism.
How to prove the following theorem ? :

$i\otimes 1_N:M'\otimes_{\mathbb{Z}} N \rightarrow M\otimes_{\mathbb{Z}} N$ is a monomorphism for all $\mathbb{Z}$-modules $N$  iff for all $q\in \mathbb{Z}$ we have $M'\cap qM=qM'$.

If $N$ is finitely generated then we can use fact that $N$ is direct sum of cyclic modules and then we know that $\ker\left(M'\otimes \left(\mathbb{Z}/q\mathbb{Z}\right)\rightarrow M\otimes \left(\mathbb{Z}/q\mathbb{Z}\right)\right)\cong \left(M'\cap qM\right)/qM'$, so in this case the proof is easy. How to do it in general case ? Is it still true ?
Answer: It is still true because:

Any $A$-module is the direct limit of its finitely generated submodules (for any ring $A$).
Tensor products commute with direct limits.
Direct limit is an exact functor.

Btw, a submodule of an $A$-module with this property (the morphism $M'\hookrightarrow M$ is universally exact) is called a pure submodule of $M$, and the morphism is said to be pure.
Standard examples of pure submodules:

A direct summand is a pure submodule
If $M/M'$ is flat, $M'$ is a pure submodule of $M$.

Properties of tensor product of modules


How to save the webform data to custom table?

Question: I designed a student registration form using webforms module. My requirement is to save data from the form to table student. How can i achieve this? Is there anyway to mention this in configuration file?
Comment: You can do custom saving of data with Webform Handlers. A tutorial can be found here: https://stefvanlooveren.me/blog/how-create-mailchimp-subscription-drupal-8-webform-module
Comment: The webform data is already saver om the DB. To save it in a custom table you must implement a hook that updates your custom table when the web form is submitted.
Answer: You can add custom submit handler to your Webform through hook_form_alter for inserting it's data into your custom table.
To achieve it check the below example.
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Database\Database;

function MODULE_NAME_form_alter(&$form, $form_state, $form_id){
  if($form['#form_id'] == "YOUR_WEBFORM"){
    $form['actions']['submit']['#submit'][] = 'YOUR_CUSTOM_FUNCTION';
  }
}

function YOUR_CUSTOM_FUNCTION(&$form, $form_state){
  $query = Database::getConnection();
  $query->insert('YOUR_CUSTOM_TABLE_NAME')->fields(
    array(
      'FIELD_NAME_IN_TABLE' => $form_state->getValue('FIELD_NAME_IN_FORM'),
    )
  )->execute();
}


Limit number of upload in Imagefield depending on a specific field

Question: On my website, members can pay for 3 different offers (Gold, Silver, Bronze). I would like to limit the number of pictures a member can upload, depending on the offer he picked.
I'm using Drupal's user_form and add an "Imagefield" field, with illimited upload.
Offers are 3 taxonomy terms, and all contain a field with the max number of images allowed.
I'm able to get the amount of images allowed, from the taxonomy term, but how would i go about applying that limit to the imagefield?
Thanks a lot!
Answer: This will need customising to your specific situation, but the basic idea is to add a validation handler to the node form and perform a check in there, e.g.
<code>function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'the_form_id') {
    $form['#validate'][] = 'MYMODULE_images_validate_limit';
  }
}

function MYMODULE_images_validate_limit($form, &$form_state) {
  $images_submitted = count($form_state['values']['field_image'][LANGUAGE_NONE]);

  if ($images_submitted > function_to_get_limit()) {
    form_set_error('field_image', t('Too many images'));
  }
}
</code>


Spring Environment Variable

Question: I was planning to use @Value annotation to my service implementation class.
 @Value("${some_property:default_value}")
 private String key;

To use above annotation, I can use @Autowiredannotation.
 @Autowird
 Private Environment environment;

But, I am planning to use those setting in my applicationContext.xml file, which is something like following below.
<context: something missing here = "ENVIRONMENT"/>

Answer: Yes. You can do it  in applicationContext.xml beans tag itself there is a property called profile So you can do  profile="ENVIRONMENT" in latest spring version.

Spring Environment Variable


Como modificar a transição default de pages no Windows Phone 8.1?

Question: Olá, estou dificuldades em encontrar uma solução para  criar transições customizáveis de pages no Windows Phone 8.1, pois ao tentar utilizar o toolkit li neste blog (http://wp.qmatteoq.com) que ainda não há toolkit para 8.1 ou não é necessário. Gostaria de exemplo, só encontrei para 8.0, ou uma breve explicação do melhor caminho a tomar.
Comment: bom dia! veja se esses exemplos do MSDN pode te ajudar: http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh452703.aspx
Answer: No Windows Phone 8.1 existem 2 tipos de aplicativos, Windows Phone Store Apps 8.1 e Windows Phone Silverlight 8.1.
Se você estiver utilizando Windows Phone Silverlight 8.1, transições de página é igual o 8.0 com o wptoolkit:
<toolkit:TransitionService.NavigationInTransition>

e
<toolkit:TransitionService.NavigationOutTransition>

Mas como você esta falando que não tem o toolkit, provavelmente é Windows Phone Store Apps 8.1, então não tem o wptoolkit mesmo e deve usar a classe EntranceThemeTransition do WinRT:
<Button>
    <Button.Transitions>
        <TransitionCollection>
            <EntranceThemeTransition/>
        </TransitionCollection>
    </Button.Transitions>
</Button>

Referência: http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh452703.aspx


Preview de arquivo PDF em website desenvolvido com PHP, Jquery e CSS3

Question: Vi no website da Dropbox que meus arquivos extensão PDF são exibidos uma prévia da primeira página do arquivo, busquei soluções na internet para o mesmo mas vi que existe apenas modos de incorporar o PDF em iframe ou usando uma URL do google drive para exibi-lo, gostaria de fazer o mesmo em meu website, mas não fazer uso dessas sugestões que exibe tudo, pois são muitos PDF's e ficará pesado o carregamento da tela, gostaria de saber como fazem pra tirar esse print da primeira página do PDF, como é feito no Dropbox. Os arquivos estão com o caminho guardados no banco de dados, os arquivos físicos em uma página de upload, no website faço uso de PHP, jQuery e CSS3.
Obrigado.
Answer: Use o PDF.js
Primeiro baixe o PDF.js e pegue todos scripts e adicione ao seu projeto, então na sua página, no  deve adicionar:

Para pegar a primeira página (ou outra qualquer ) use getPage
var pdfjsLib = window['pdfjs-dist/build/pdf'];

pdfjsLib.getDocument('helloworld.pdf').then(function (pdf) {
    pdf.getPage(1).then(function(page) {
        var scale = 1.5; //Scala inicial desejada, ajuste como quiser

        var viewport = page.getViewport(scale);

        var canvas = document.getElementById('meuCanvas');
        var context = canvas.getContext('2d');
        canvas.height = viewport.height;
        canvas.width = viewport.width;

        page.render({
          canvasContext: context,
          viewport: viewport
        });
    });
});

E deve existir um canvas na página (ou gerar), com o conteúdo dele:
<canvas id="meuCanvas"></canvas>

Comment: gratidão Guilherme.
Comment: @EliseuB. sim, erro de digitação, desculpe. Corrigido ;)
Comment: Em var canvas = document.getElementById('the-canvas'); não deveria ser var canvas = document.getElementById('meuCanvas'); ?


Massive difference between R's glmnet and Python's sklearn regarding Lasso regression

Question: I have a burning question. First, in Python:
import os
import time
import numpy as np
from sklearn.linear_model import LassoCV
from sklearn.datasets import make_regression

X, y = make_regression(1000, 5000, noise = 4, random_state = 123)
if not os.path.exists("tmp"): os.mkdir("tmp")

# Save on disk to be read in R session.
np.save("tmp/X.npy", X)
np.save("tmp/y.npy", y)

# Let first 70% rows be training examples.
Nrow = int(round(len(X) * 0.7))

tik = time.time()
reg = LassoCV(cv = 5).fit(X[:Nrow, :], y[:Nrow])
time.time() - tik
# 6.59s

# Compute mse on the validation examples:
np.mean((reg.predict(X[Nrow:, :]) - y[Nrow:]) ** 2)
# 19.036

Then in R:
X = RcppCNPy::npyLoad("tmp/X.npy") # Load the data saved from Python session.
y = RcppCNPy::npyLoad("tmp/y.npy")

# First 70% rows are training data.
trainInd = 1:as.integer(round(nrow(X) * 0.7))

system.time({
reg = glmnet::cv.glmnet(
  X[trainInd, ], y[trainInd], type.measure = "mse", nfolds = 5)
})
# 1.047s

mean((predict(reg, X[-trainInd, ], s = "lambda.min") - y[-trainInd]) ^ 2)
# 32.01

Why does R glmnet result in an MSE 68% higher than that from Python sklearn? I anticipated glmnet would be faster, but a 6.6x speedup over sklearn seems to suggest glmnet skipped something important, which might contribute to its significantly worse error metric? I couldn't figure out where I did wrong..
Comment: To understand what's going on, compute the variance of Y and then compare var(Y) to the MSE. And it always helps to look at plots. In your case plotting the predictions against the true Ys will also help you figure out things.
Comment: @RichardHardy 32.01 and 19.036 are trivial compared to y's magnitude..
Comment: @dipetkov Thanks! Please post ur answer if u'd like and i'll accept it
Comment: So what did actually happen here? Where did the discrepancy come from?
Answer: As always, it helps to make plots. Here I plot the cv.glmnet predictions on the left and the LassoCV predictions on the right, against the true values in the hold out set.

We see immediately that both implementations do a great job: they explain most of the variability in $y$ and the mean squared error (MSE) is small compared to the total variability in $y$.
We can quantify the difference between the implementations in terms of the proportion of variance explained (PVE) = 1 - MSE / Var$(y_{\text{holdout}})$.

PVEcv.glmnet = .9989
PVELassoCV = .9993

Note: PVE is not the same as the R-squared, which is computed on the training data. And it's not equivalent to comparing the Lasso to the "naive" model that predicts the average $y$ observed in the training data.
So there is a difference but it is small relative to the variability of the outcome variable. I wouldn't use this example to conclude that LassoCV is a better implementation than cv.glmnet in general.
PS. An increase of .0004 could be a meaningful improvement and worthwhile to put in practice. However, to conclude that a new model is better than the production model by such a small increment, we would want to compare the models on more than 300 examples.
Comment: @Dave Or the default settings perhaps? One could repeatedly simulate data with a different seed and see how often LassoCV does better. If it was easier to jump between R and python.... But I'm not sure what we'll learn from the exercise. Visually, on this dataset, LassoCV does better at predicting the extremes.
Comment: @Dave as well as the python package rpy2 :)
Comment: There's always the R package `reticulate`!
Comment: Do you think the discrepancy is because of some kind of difference in the numerical optimization of the LASSO parameters?


When and why is a likelihood ratio preferable to a difference as a test statistic?

Question: We want to know whether two sample sets {x} and {y} were drawn from the same distribution.  The null hypothesis $H_0$ is that they are.  As statisticians we test the hypothesis by calculating the p-value: the probability of observing those sample data if the null hypothesis is correct.
As statisticians with computers we can avoid thinking too hard about the characteristics of their distribution and just run a permutation test on whatever statistic we care about.  Well, we said earlier that we care about whether they are different.  So I guess we have to come up with some MLE $\hat{\theta}$, and then look at the difference: $\hat{\theta_x}-\hat{\theta_y}$, right?
But we've been reading all about Likelihood Ratio Tests, which have some nice features, and a difference is just a ratio in log space, so: are there advantages to running the permutation test on the ratio $\frac{\hat{\theta_x}}{\hat{\theta_y}}$ instead of the difference?  IIUC, using the ratio gets us into a situation, via  Wilks' theorem, where we approximate the $\chi^2$ distribution.  But we already decided our computer can do a permutation test – potentially even exhaustively for small sample sizes – and isn't that preferable in practice to a closed-form solution that is only asymptoticly correct?
Or maybe we pick up some power if we mix LRT with the permutation concept and look at $\frac{\hat{\theta_{xy}}}{\hat{\theta_x}\hat{\theta_y}}$?
Comment: The likelihood ratio is the ratio of the likelihoods, which is not usually the ratio of the parameters.  I'm sorry to say there is a lot else that isn't correct in your question statement, but that's probably the most obvious error.
Comment: @jbowman The question includes statements of my current understanding, which I suspect contains errors and is missing important qualifications.  Any explanations of things that I have wrong (and why) could be helpful answers.
Answer: There are hidden problems with permutation tests, the first and foremost being their reliance on choosing the "correct" statistic to permute.  With heavy tails in the data distribution, the sample mean has problems with overly influential observations, and permuting the data doesn't fix that.  Using a likelihood ratio $\chi^2$ test or a Bayesian regression model implies that you have thought about the choice of the raw data model, and such thinking may involve transforming Y in a certain way.  For example if Y has a log-normal distribution, one computes the mean and SD after taking log(Y), and the mean of Y on the original scale is estimated by anti-logging a function of the estimated mean and SDs of the logs.


Expression Encoder 4 live stream consumed by HTML 5

Question: I'm trying to serve up a live stream (ie. completely buffered in memory, cannot access the past) and am having trouble with Expression Encoder 4.
Ideally, I'd like to just stream a bare H.264 byte stream to the client consumed by:
<code> <video id="mainVideoWindow">
     <source src='http://localhost/path/to/my/stream.mp4' type='video/mp4' />
 </video>
</code>
I figured I could stream it to the client just like any other byte stream over HTTP. However, I'm having trouble figuring out the appropriate code required to do (first day with Expression Encoder, not sure how to go about getting the raw byte stream) so nor do I know if it would work in the first place.
An alternate was to use IIS Live Streaming server:
<code>        var source = job.AddDeviceSource(device, null);
        job.ActivateSource(source);
        job.ApplyPreset(LivePresets.VC1IISSmoothStreaming720pWidescreen);

        var format = new PushBroadcastPublishFormat();
        format.PublishingPoint = new Uri("http://localhost/test.isml");

        job.PublishFormats.Add(format);
        job.StartEncoding();

        // Let's listen for a keypress or error message to know when to stop encoding
        while (Console.ReadKey(true).Key != ConsoleKey.X) ;

        // Stop our encoding
        Console.WriteLine("Encoding stopped.");
        job.StopEncoding();
</code>
However, I'm having trouble getting the client side markup to want to display the video on Chrome and I haven't seen anything to indicate that it'd work on Chrome (though http://learn.iis.net/page.aspx/854/apple-http-live-streaming-with-iis-media-services indicates how it would work with an iOS device).
Anyone have any insights?
Answer: You are trying to consume (with your sencond example) a Smooth Streaming feed (HTTP-Adaptive Streaming by Microsoft) through HTML5, which is not supported.
This could work on iOS devices if you enable the Apple HTTP Live Streaming to transmux the fragments into MPEG-2 Transport Stream. This will also generate an Apple HTTP Live Streaming manifest which than can be called though the video tag.
Answer: ...I saw that you have the IIS link.  The  Apple HTTP Live Streaming needs to be enabled on the IIS Server (IIS Media Services).  This will work for iOS devices. Quicktime will get into play...


On the resolvent set of an unbounded operator

Question:
Suppose $A$ is the infinitesimal generator of a $C_0$ semigroup $S(t)$ on an Hilbert space $X$. If
  $$\langle Ax, x\rangle \leq \omega \|x \|^2 \ \ \ \forall x \in \mathfrak{D}(A)$$
  then
  $$\|S(t)\| \leq e^{\omega t} \ \ \forall t \geq 0$$

How do I prove this? Notice that $A$ is unbounded, closed and densely defined, but we don't know anything else.
My idea until now is to prove that we are in the hypotheses of the Hille-Yosida theorem, namely that:
$$\rho(A) \supset (\omega, \infty) \ \ \ \mathrm{and} \ \ \ \|R_{\lambda}\| \leq \frac{1}{\lambda - \omega} \ \ \forall \lambda > \omega$$
In particular, it is easy to see that if $\omega < \lambda \in \rho(A)$ then the second hypothesis is immediately satisfied. Therefore, I only need to show that $(\omega, \infty) \subset \rho(A)$. Now, if by contradiction we assume that $\lambda > \omega$ is not in $\rho(A)$, then the image $\mathfrak{R}(\lambda I- A) \not = X$. Therefore, there exists a $y \not = 0$ such that
$$\langle x - Ax, y \rangle = 0 \ \ \ \forall x \in \mathfrak{D}(A)$$
I would like to show that $y = 0$, but I don't know how to do it. Notice, for instance, that $y \in \mathfrak{D}(A^*)$, but we don't know if $A^*$ is dissipative. At the same time, we don't know if $y \in \mathfrak{D}(A)$.
How can I approach this problem?
Comment: I think I may have solved it. Since $A$ generates a semigroup, then its resolvent is non empty. In particular, $(\lambda, + \infty) \subset \rho(A)$ and I can apply Lumer-Phillips to $A - \omega I$ to prove that this operator generates a contraction semigroup $T(t)$. But then $A$ generates $S(t) := e^{\omega t} T(t)$ which is $\omega$-contractive.
Answer: Take $B=A-\omega$. The inequality above implies that $B$ is dissipative. You need $\lambda- B$ to be surjective for some $\lambda>0$ to conclude. This follows easily since $A$ is a generator of $C_0$-semigroup. Corollary 3.20 in the book of Engel & Nagel, implies that the semigroup $T(t)=e^{-\omega t} S(t)$ of $B$ is a contraction.
Answer: Because $\frac{d}{dt}(S(t)x=AS(t)x$ for all $t > 0$ (and as a right derivative at $0$,) then
$$
         \frac{d}{dt}\|S(t)x\|^2=\frac{d}{dt}\langle S(t)x,S(t)x\rangle \\
   = \langle AS(t)x,S(t)x\rangle+\langle S(t)x,AS(t)x\rangle \\
   \le 2w\langle S(t)x,S(t)x\rangle = 2w\|S(t)x\|^2
$$
Therefore, for all $t \ge 0$, $x\in X$,
$$
                   \frac{d}{dt}\|S(t)x\|^2-2w\|S(t)x\|^2 \le 0 \\
                        \frac{d}{dt}(e^{-2wt}\|S(t)x\|^2) \le 0 \\
                        e^{-2wr}\|S(r)x\|^2|_{r=0}^{r=t} \le 0 \\
                         e^{-2wt}\|S(t)x\|^2 \le \|S(0)x\|^2 \\
                          \|S(t)x\|^2 \le e^{2wt}\|x\|^2 \\
                            \|S(t)x\| \le e^{wt}\|x\|.
$$
Because this holds for all $x$, it follows that
$$
                               \|S(t)\| \le e^{wt},\;\;\; t \ge 0.
$$


Does any rule require MLB teams to announce probable pitchers?

Question: In Major League Baseball, a few days before each game, each team typically announces a "probable" starting pitcher.
Is there a rule requiring them to do so, or is it simply a matter of tradition or courtesy to opponents and fans?  One might think teams could get a competitive advantage by keeping this secret.  (Certainly with traditional pitching rotations, it's usually easy to guess who will pitch a given game, but not always, and there are variations.)
Answer: There is no rule requiring a team to announce its probable pitcher. Nothing is official until the manager submits his lineup to the umpire before the game begins. But as you said, it is usually very easy to guess who will pitch given the traditional 5-man rotation system.
Answer: I remember in the late 80's that the Cardinals (visitors) needed to declare their starters before the Mets (home team).  The Cardinals needed to sweep the Mets and the Mets wanted to avoid Dwight Gooden being matched against John Tudor.
Comment: Welcome to SE.Sport. To make your answer credible you should add some references/links