What is cost of context switching to secure mode (arm trustzone)

Question: I am trying to understand the cost of switching back and forth between trusted (secure) and non-secure modes in arm.
What exactly needs to happen when moving from non-secure to secure world? I know the ns bit needs to be set (based on some special instruction?), the page tables need to be flushed and updated (?), the processor caches flushed and updated. Anything else that needs to happen?
Processor caches: Are they caches segmented and shared or is the whole cache used for each mode? That determines the cost of the switch.
RAM: This must be 'partitioned' and used by both modes. So addressing is just an offset into the 'partition'. Is this right?
What is different about this from a user space to kernel mode switch or a process to process switch in user space?
Is there anything in moving from non-secure to secure modes that would make it more expensive than the regular process context switch?
Are there any articles that explain what exactly happens?
EDIT: Based on a reply below, I am looking to understand what exactly happens when a process switches from non-secure mode to a secure mode (trust zone) on an arm processor.
Comment: Can you narrow your question to a specific one so you increase your chance of getting an answer ?
Comment: @Tony, I am looking to understand what exactly happens when a process switches from non-secure mode to a secure mode (trust zone) on an arm processor. Are you looking for more specifics?
Comment: Now it's better, I don't know the specific architecture. But when you trigger a system call, it is being executed in the context of the current process, in privileged mode. There's no switching.
Answer:
What exactly needs to happen when moving from non-secure to secure world?

TL-DR; the minimum is to save/restore all  CPU registers that are needed by the secure world and change the NS bits.  Normally, R0-R14 as well as current mode, and banked LR and SP (aborts, interrupts, etc) are in this register group.  Everything else depends on your security model.

First off, there are many different models that can be used in TrustZone; TrustZone is a tool not a solution.  The most basic model is a library with API where some secure data is stored (ie decryption keys) to process by an external source (some DRM download from the 'normal world' space).  I assume you don't mean this.
An OS can be pre-emptible and non-premptible.  If you have two OSes in both worlds, then how control is relinquished, resources shared and security assets protected will all come into play on a world switch.
In many cases, the caches and TLB are world aware.  Devices may also be world aware and designed with the intent that context is built into the device.  This is not to say that some system might have information leaked in some way.

Meltdown (2017)
Specter (2017)
Hyperthreading exploit (2004)

If you are really concerned about this type of attack, it may be appropriate to mark the secure world memory as non-cached that needs to be protected.  In many ARM systems, the L1/L2 and TLB cache are unified between worlds and can provide a side channel attack.
TrustZone as implmented on many ARM devices comes with a GIC which can run FIQ in the secure world and masking of FIQ can be prevented in the normal world.  Many GIC features are banked between worlds allowing both OSes to use it without 'context switch' information.  Ie, the NS bit will automatically change the accessed GIC features based on the state of the NS bit (so it has the context stored in the device).  Many other vendor specific devices are designed to behave this way.
If both worlds use NEON/VFP, then you need to save/restore these registers on a world switch as well.  For pre-emption you may need to hook into the OS secure scheduler to allow and normal world interrupt to pre-empt the secure world main line (obviously this depends on assets you are trying to protect; if you allow this the secure mainline has a DOS vector).
If there are glitches in devices, then you may need to save/restore device state.  If the normal world is restricted from using FIQ mode, it is still needed to at least clear the SP_fiq and LR_fiq when going to the normal world (and restore the secure value the other way).  Some of these registers are difficult to save/restore as you must switch modes which can itself be a security risk if care is not taken.

RAM: This must be 'partitioned' and used by both modes. So addressing is just an offset into the 'partition'. Is this right?

Secure boot will partition memory based on the 'NS bit'.  The physical memory will be visible or not based on the partition manager device logic which can often be locked at boot.  Ie, if non-visible it is a bus error like any non-existent memory.  There is no 'switch' beside the NS bit.

Is there anything in moving from non-secure to secure modes that would make it more expensive than the regular process context switch?

Yes a normal switch is only for a 'mode'.  A world is for all ARM modes and so all banked registers must be switched.  Depending on the system the TLB and cache would not normally need to be switched.

Related:

How to introspect normal world
TrustZone monitor mode switch design
Preventing memory access from the normal world
How is a TrustZone OS secure?
TrustZone scheduler in secure/non-secure OS
IMX53 and TrustZone
ARM Trusted firmware on github
TrustZone Whitepaper


Proving the existence of a harmonic function

Question: Show that if $f(u,v)$ is harmonic, then $F(x,y)=f(x^2-y^2,2xy)$ is also harmonic.
What i did
For a harmonic function to exist, $F_{xx}$ +$F_{yy}$= 0 Hence i know that i must show this result. I then let $u=x^2+y^2$ and $v=2xy$
so $f(x,y)=f(u(x,y),v(x,y))$
from here i know that i must take the chain rule of this function but im unsure of how to peform the chain rule of this function and continue from here. Could anyone help me in this. Thanks
Answer: Look up multidimensional chain rule.
$$\frac{\partial}{\partial x_i} f \circ g(x) = \sum_{k=1}^n \frac{\partial}{\partial x_i} g_k(x) \cdot \frac{\partial}{\partial y_k} f(y)|_{y=g(x)}$$
Where $g = (g_1, g_2, \ldots, g_n)^T$. In your case $g_1 = u, g_2 = v$ and $f$ is the harmonic function. ($n=2$)


Is "aim to develop WPF unless you need to drop back to Windows Forms" the general advice?

Question: Is the general advice re windows apps technology to develop in "aim to develop WPF unless you need to drop back to Windows Forms".
I known there are some specific pros/cons for particular scenarios/requirements (e.g. assumptions about what version of .net is available on the desktop) however I'm just after overall general advice.  Like is Windows Forms on the way out so, if all else is equal, you should be learning/building in WPF?
Answer: SO already has lot of discussion on this issue.

Is it better to use WPF over WinForms?
When is Winforms the correct choice vs. WPF?
Will WinForms be deprecated in favor of WPF?
Answer: It depends on lots of factors (even if they all else is equal), in particular presentation.  Eg. If you are distributing the interface through citrix, windows forms may be a more robust solution.  What about your user base? They may be more familiar with the windows forms controls and would like a "comfortable" familiar interface.
They're just a couple of thoughts.


Applying mvc to domain-driven design

Question: From a practical point of view, how can you adapt the domain model to the MVC pattern? For example, could I use some wrapper classes?
Answer: They aren't really related.
MVC is a design pattern for separating the concerns of storing data (model), presenting various views of the data (view), and interacting with that data (controller). While it may be a "design" pattern, it is really about the design of code. The views are usually, but not necessarily used for GUIs.
Domain-Driven Design is a style of designing software where you focus on modeling the domain to create a shared well-understood model of the problem domain - a "domain model". Domain-Driven design is not just "design", but also represented in the code, requirements, conversations amongst various stakeholders, etc.
So, you wouldn't really "adapt" one to the other, though you certainly can implement MVC using objects from your domain model. For example, if you modeled a BankAccount entity and wrote a corresponding class for it, you could use that as the model in an MVC triad. Perhaps the controller handles depositing and withdrawing cash, and several views (for example a debit, credit, and summary view) are updated upon model change. There are multiple flavors of MVC, and depending on what you pick you may end up modifying your domain model. For example, you could use the observer pattern where your views are notified whenever a model entity changes. This does mean you would be mixing non-domain concepts (observer registration, notification, etc.) into your domain object. It may be better to wrap the domain object in this case to keep a clean separation between the domain model and presentation layer, if that's important to you. Perhaps that is what you mean by "adapting" one to the other.
Comment: "It may be better to wrap the domain object in this case to keep a clean separation between the domain model and presentation layer, if that's important to you. Perhaps that is what you mean by "adapting" one to the other"

Yes, that's what I meant. Since the domain Since the domain model is supposed to be anemic, I was wondering whether to use wrappers or not. Thanks for the feedback.

Applying mvc to domain-driven design


drag and drop - lag in UWP

Question: Hello drag and drop fans,
Can anyone explain why I see a long lag time when using drag and drop with my UWP apps?
I wrote a test app that contains just the drag and drop message handlers and also the pointer handlers for comparison. Here's the code...
public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();

        grid1.AllowDrop = true;
        grid1.DragOver += Grid1_DragOver;
        grid1.Drop += Grid1_Drop;
        grid1.DragLeave += Grid1_DragLeave;

        grid1.PointerEntered += Grid1_PointerEntered;
        grid1.PointerExited += Grid1_PointerExited;

    }

    //  Drag Handlers ************************
    private void Grid1_DragOver(object sender, DragEventArgs e)
    {
        msgFromPointer.Text = "  drag/drop item has entered";

        e.AcceptedOperation = Windows.ApplicationModel.DataTransfer.DataPackageOperation.Copy;
        Debug.WriteLine("in grid1 drag over handler");
    }

    private void Grid1_DragLeave(object sender, DragEventArgs e)
    {
        msgFromPointer.Text = "";
    }

    private void Grid1_Drop(object sender, DragEventArgs e)
    {
        Debug.WriteLine("in grid1 drop handler");
    }

    // pointer handlers *******************
    private void Grid1_PointerEntered(object sender, PointerRoutedEventArgs e)
    {

        msgFromPointer.Text = "POINTER has entered";
    }

    private void Grid1_PointerExited(object sender, PointerRoutedEventArgs e)
    {
        msgFromPointer.Text = "";
    }

When doing a drag and drop to my app, there seems to be about a 1/2 second delay before my app receives the dragOver message. In comparison, the pointerOver message seems to arrive almost simultaneously with the pointer movement. The slow behavior is the same when using the touch screen or a mouse. Here's a video of the behavior…
video of the laggy behavior
The PC I'm using has a touch screen and I'm wondering if there is some sort of touch "driver" or filter that is slowing down the drag and drop message. I've tried  a bunch of Windows config settings, like mouse and display settings, but no change. The PC is a Dell Inspiron 3593, with the latest drivers. My Windows 10 version is 1903, build 18362.836
The app I'm developing uses a lot of drag and drop and this slow behavior makes the user interface really difficult. It's kind of like trying to conduct a phone conversation with a 1/2 second delay.
Any ideas?
Dan
Comment: it seems like the delay it takes to load up the thumbnail of the to the DragUI,
try again with a more cache-able file thumbnail, like the one of a .txt file,
also test what happens when you drag over multiple files.
Comment: I tried dropping a .txt file and multiple files, but got the same lag. In the app I'm developing, I turned off the drawing of the thumbnail completely, but still got the same lag.
Comment: maybe it is cause you use a debug build, debug builds are much slower and use twice the ram, switch to release and check how it goes.
Comment: I'll try that later today. Thanks!
Comment: OK, I made a release build, but no change. I did discover one other thing. In the app I'm developing (as opposed to the test app) when I drop a file the app displays an image. I discovered that I can drop a file _before_ the thumbnail, glyph, and text get displayed. The, after the same lag, the image gets displayed. That makes me think that all the messages are getting delayed - the dragOver message and the drop message. Then, 1/2 second later, all the messages get delivered and the app does what it's supposed to.
Answer: The DragOver event is triggered when the application determines that the element under the current pointer is a potential placement target.
This requires the pointer to hover for a period of time. This may be the reason for the delay you think.
You can try the DragEnter event, which is triggered earlier than DragOver.
Thanks
Comment: That was interesting! I had tried DragEnter before in my main app and it gave NO reduction in the delay before the thumbnail/glyph/text appear so I wasn't optimistic. However, I implemented it in my test app just to retest and added "DRAG ENTER message" to the text string I display. Sure enough, "DRAG ENTER message" appeared immediately, but then it still takes 1/2 second for the thumbnail/glyph/text to appear. Does that mean I have to live with that delay in UWP? I have apps previously, non-UWP apps, that don't have this delay.
Comment: Hi, This part of the delay is the process of rebuilding the thumbnail of the picture, which cannot be skipped for now.
Comment: OK. That answers my question. Thank you @Richard !
As a postscript, I tried to give the user some earlier feedback by changing the opacity when the dragOver message arrives. However, the new opacity didn't appear until the thumbnail/glyph/caption was displayed. Then I stopped the display of the thumbnail/glyph/caption by using e.DragUIOverride elements, but no luck. The opacity change is still delayed even though the none of the thumbnail/glyph/caption gets displayed.

drag and drop - lag in UWP


Pre-process drupal_goto or use hook_exit() to stop redirect

Question: I want to unit test some custom modules but drupal_goto() is causing problems by creating header errors (for example, PHP Warning:  session_start(): Cannot send session cookie).
Is it possible to stop drupal_goto() from redirecting to the destination page or somehow tap into hook_exit() to return $destination?
Answer: This is most often caused by UTF-8 with BOM. Check your editor and change the file format if it is.
The only way to redirect in hook_exit() is another drupal_goto(). Be careful that you don't create redirection loops.
Answer: You may be interested in:
hook_drupal_goto_alter
function EXAMPLE_drupal_goto_alter(&$path, &$options, &$http_response_code) {
  // example debug
  drupal_set_message('
'.print_r(func_get_args(),1).'
');
  drupal_set_message($_REQUEST['destination']); // maybe
}

Answer: I would prefer to use either of following options for redirection in this scenario.
$_GET['destination'] = $redirect_url;

or
$form_state['redirect'] = $redirect_url;.


Proving if $f$ is differentiable at 0 when f(0) = 0

Question: Suppose that we have a function $f$ that $f(0)=0$ and for any $x$,
$$|f(x)|>=\sqrt{|x|}$$
How could we prove that $f(x)$ is differentiable at zero or not?
P. S. My first attempt was to prove something like a discontinuity for $f$ at zero that not being differentiable would be quickly implied from it, but haven't reached to anything interesting. However, any solution is acceptable.
Comment: You can't: $f(x)=x^\alpha$ satisfies this inequality if $\alpha\ge \frac12$, yet it is differentiable at $0$ if and only if $\alpha\ge 1$.
Answer: Hint :
\begin{align*}
\left| f(x) \right| \geq \sqrt{\left|x\right|} &\Leftrightarrow \left| f(x)\right| - \left| f(0)\right| \geq \sqrt{\left| x\right|} - \left|f(0)\right| \\ &\Leftrightarrow \frac{\left|f(x)\right| - \left|f(0)\right|}{\left|x\right|-0} \geq \frac{\sqrt{\left|x\right|} - \left|f(0)\right|}{\left|x\right|-0} \\ &= \frac{\left|f(x)\right|}{\left|x\right|} \geq \frac{\sqrt{\left|x\right|}}{\left|x\right|} \\ &= \frac{\left|f(x)\right|}{\left|x\right|} \geq \frac{1}{\sqrt{\left|x\right|}}
\end{align*}
Answer: Suppose $f'(0)$ exists. Call $l$. There exists $\delta$ such that $|\frac {f(x)-f(0)} x-l|<\epsilon$ for $|x| <\delta$. Hence $\frac {|f(x)|} {|x|} <|l|+\epsilon$ for $|x| <\delta$. This implies $1 <\sqrt |x| (|l|+\epsilon)$ for  $|x| <\delta$. You get a contradiction by letting $x \to 0$


How to conditionally match location in nginx

Question: I'd like to set up nginx location match but only for a specific source address. Unfortunately if I already match a location, but not the condition I can't fall through to the next location. What's the way to solve it nicely?
server {
    ...
    location / {
        index app.php;
        try_files $uri @rewriteapp;
    }
    location @rewriteapp {
        rewrite ^(.*)$ /app.php/$1 last;
    }
    ...
    location ~ ^/admin {
        if ($source_trusted = "UNKNOWN") {
            return 403;
        }
    }
    ...
    location ~ ^/... {
        fcgi_pass ...
        ...
    }
}

With this config going to /admin from a source that sets $source_trusted = OK (via geo module) results in a 404, rather than the page loading.
Answer: Remember that nginx generally only evaluates one location unless specifically instructed to use another, such as when calling to a named location in try_files (which you do).
So when you hit the ^/admin location, you only need to do whatever is appropriate. In this case, it's most likely going to be exactly the same try_files as you used in location /.
    location ~ ^/admin {
        if ($source_trusted = "UNKNOWN") {
            return 403;
        }
        try_files $uri @rewriteapp;
    }


Is there a non-decreasing sequence $(a_n)$ such that $\sum 1/a_n=\infty$ and $\sum1/(n+a_n)<\infty$?

Question: This question is motivated by this one. In the accepted answer, two positive non-decreasing sequences $(a_n)$ and $(b_n)$ are given such that
$$
\sum_{n=1}^\infty\frac{1}{a_n}=\sum_{n=1}^\infty\frac{1}{b_n}=\infty,\quad\text{but}\quad \sum_{n=1}^\infty\frac{1}{a_n+b_n}<\infty.
$$
Now take $b_n=n$.

Is there a positive non-decreasing sequence $(a_n)$ such that
  $$
\sum_{n=1}^\infty\frac{1}{a_n}=\infty,\quad\text{but}\quad \sum_{n=1}^\infty\frac{1}{n+a_n}<\infty\,?
$$

Some remarks:

If $a,b>0$, then $\max(a,b)\le a+b\le2\max(a,b)$. Thus
$$
\sum_{n=1}^\infty\frac{1}{n+a_n}<\infty\quad\text{is equivalent to}\quad\sum_{n=1}^\infty\frac{1}{\max(n,a_n)}<\infty
$$
If we eliminate the condition that $(a_n)$ be non-decreasing, it is easy to find an example, like $a_n=n^2$ if $n$ is not a squere, $a_n=\sqrt{n}$ is $n$ is a square.
If such a sequence existes, it must satisfy
$$
\sup\frac{a_n}{n}=\sup\frac{n}{a_n}=\infty.
$$
Answer: We use  Abel's (or Pringsheim's) theorem:

If $b_n$ is decreasing and positive, and if $\sum b_n$ converges, then $\lim\limits_{n\rightarrow\infty} nb_n=0$.

Now,
if $\sum {1\over n+a_n}$ converged, we would have the string of implications:
$${n\over n+a_n}\rightarrow 0\quad \Rightarrow \quad{a_n\over n} \rightarrow\infty
\quad\Rightarrow\quad {n\over a_n}\rightarrow0\quad\Rightarrow \quad\sup{n\over a_n}<\infty.$$
Comment: @Gortaur: If $b_n = n^{\alpha}$ with $\alpha > 1$, then $\sum \frac{1}{a_n + b_n}$ converges for every non-negative sequence $a_n$ using the comparison test.
Comment: @Gortaur I think you mean $\alpha<1$ (otherwise $\sum1/n^\alpha<\infty$). This is the first thing I checked, and it works. However, I cannot make it work for $n\log n$.
Comment: @Willie: thanks a lot
Comment: @Julian: I meant $\alpha>1$ since was focused only on the technique David advised - for $\alpha<1$ it was clear that it works. I missed a point that the case $\alpha>1$ would be rejected even before. Nice question by the way!
Answer: A self contained and elementary proof. (See below the cut for the "explanation" invoking Abel's theorem.)
As noted by the OP, it suffice to consider the series $\sum \max(a_j,j)^{-1}$. Let $(n_k)$ and $(m_k)$ be two sequences of increasing positive integers satisfying
$$ 0 < \cdots < n_k < m_k < n_{k+1} < m_{k+1} < \cdots $$
such that when $n_k \leq j < m_k$ we have $a_j \geq j$ and $m_k \leq j < n_{k+1}$ we have $j > a_j$.
This implies that (using monotonicity of $a_j$)
$$ \sum_{j = 1}^\infty \frac{1}{\max(a_j,j)} = \sum_{k = 1}^{\infty} \left( \sum_{j = n_k}^{m_k-1} \frac{1}{a_j} + \sum_{j = m_k}^{n_{k+1} - 1} j^{-1}\right) \geq \sum_k (1-n_k/m_k) + \ln \frac{n_{k+1}}{m_k} $$
But observing that $\ln$ is concave, we have that
$$ \geq - \ln \frac{n_k}{m_k} + \ln \frac{n_{k+1}}{m_k} = \sum \ln n_{k+1} - \ln n_{k} $$
a telescoping sum. Using that $(n_k)$ is strictly increasing and integer valued, we get a contradiction.

Basically this is a modification on Abel's theorem as in David Mitra's answer. If $a_j$ and $j$ interchanges "leads" infinitely often, then $\limsup \frac{n}{n+a_n} \neq 0$, and hence $\frac{1}{n+a_n}$ cannot be convergent. Therefore for that series to converge, there exists some $M < \infty$ such that $a_l > l$ for all $l > M$. This implies than the $(a_l)^{-1}$ must also be a convergent series.
Answer: Let $S=\{n:n\leq a_n\}$. Then $\sum_{n=1}^\infty\frac{1}{\max(n,a_n)}=\sum_{n\in S}1/a_n+\sum_{n\in N-S}1/n$
In this question it is showed that if a subseries of a diverging sequence has indices dense in N then it diverges.
But if S is not dense in N, then N-S must be dense in N, hence one of the sums must diverge.
This also seems to imply a positive answer to the Slowing down divergence 2 question.
Comment: Asymptotic density is not necessarily well defined. In the solution to the question you linked to, it is necessary to have a $\liminf$ (lower asymptotic density) be bounded away from zero. It is, however, possible to concoct cases where the lower asymptotic densities of both $N$ and $N-S$ be zero (see the solution to the question linked in the OP). In fact, this property is crucially used in that answer.


Why isn't char of type SPACE_SEPARATOR recognized as whitespace?

Question: I have String like "12 345 678" and I wanted to remove whitespaces (because of conversion to int). So I did the usual: myString.replaceAll("\\s", "");, but what a surprise! It did nothing, the space was still there.
When I investigated further, I figured out that this space character is of type Character.SPACE_SEPARATOR (Character.getType(myString.charAt(<positionOfSpaceChar>))).
What I don't get is why isn't this oblivious space character (from Unicode category Zs
http://www.fileformat.info/info/unicode/category/Zs/list.htm) recognized as whitespace (not even with Character.isWhitespace(char)).
Reading through java api isn't helpful (so far).
note: In the end, I just want to remove that character... and I will probably find a way how to do it, but I'm really interested in some explanation of why it's behaving like this. Thanks
Comment: The Javadoc for `java.util.regex.Pattern` states that `\s` means `[ \t\n\x0B\f\r]`, and the Javadoc for `java.lang.Character.isWhitespace` states that it does not include non-breaking spaces.
Comment: Strings are immutable. Did you assign the return value of the method to another String variable?
Comment: Yes. The problem is, that those spaces aren't just "ordinary spaces". They are probably non-breaking spaces or something like this.
I found a solution of my problem here: http://stackoverflow.com/questions/1060570/why-is-non-breaking-space-not-a-whitespace-character-in-java
`replaceAll(\\p{javaSpaceChar}", "_"))`
But I couldn't find there some satysfying explanation why it is like this...
Answer: Your problem is that \s is defined as [ \t\n\x0B\f\r].  What you want to use is \p{javaWhitespace}, which is defined as all characters for which java.lang.Character.isWhitespace() is true.
Not sure if it applies in this case, but note that a non-breaking space is not considered whitespace.  Character.SPACE_SEPARATOR is generally whitespace, but '\u00A0', '\u2007', '\u202F' are not included because they are non-breaking.  If you want to include non-breaking spaces, then include those 3 characters explicitly in addition to \p{javaWhitespace}.   It's kind of a pain, but that's the way it is.
Actually, in your specific case of converting to int, I'd recommend:
myString.replaceAll("\\D", "");,

to strip out everything that is not a digit.
Comment: Thanks for explanation. Weird thing, that `Character.isWhitespace(char)` returned false (when I tried it), but `\p{javaWhitespace}` behaves correctly in my case (this was the solution i went for).

But using \D is much better. I wonder how could I miss so oblivious solution. Thanks!


What is a non-normal modal logic? Is there a family of semantics that covers both normal and non-normal modal logics?

Question: What is a non-normal modal logic?
Is there a semantics for modal logic that's broad enough to cover a range of normal and non-normal modal logics and has the normal modal logics as a definable subfamily?

What follows is my attempt to answer the question myself and some background on where the question comes from.

The first section of the Open Logic Project book Boxes and Diamonds covers normal modal logics.
The discussion of validity on pages 10-11 (pdf 25-26) contains the following, which seems like almost a definition of a normal modal logic.

[Validities] represent those modal propositions which are true
regardless of how $□$ and $◇$ are interpreted, as long as the
interpretation is "normal" in the sense that it is generated by some
accessibility relation on possible worlds.

This suggests to me that a normal modal logic is one with a semantics that can be produced by taking the semantics for System K and imposing additional frame conditions. This gives us the familiar family of modal logics including B, S4, and S5.
The problem with this, though, is that I'm having a hard time picturing a semantics for a modal logic that's more general than K's semantics.
This lecture by Graham Priest seems to suggest that a non-normal modal logic is one with a set of impossible worlds $I$ ... where  every complex formula $\varphi$ is assigned a truth value $\{0, 1\}$ in an arbitrary fashion. I'm not sure whether the complex formula is required to be $\square\lozenge$-free or not. This would make a normal modal logic simply a not-necessarily-normal modal logic where the set of impossible worlds is constrained to be empty.
I think this means we have to expand our Kripke model from $\langle W, R, \Vdash \rangle$ to $\langle I, W, R, \Vdash \rangle$ where $I \subset W$ and the rules restricting how $\Vdash$ behaves for complex formulas are inapplicable to worlds in $I$. This seems kind of unsatisfying though.
Answer: Word 'normal' in 'normal modal logic' merely refers to the fact that the the logic satisfies all propositional tautologies, all instances of axiom K $\square(\varphi \to \psi) \to (\square \varphi \to \square \psi)$, and all instances of $\Diamond \varphi \leftrightarrow  \lnot \square \lnot \varphi$,  plus modus ponens, $\square$-necessitation, and uniform substitution are validity-preserving.
Thus, any logic that fails to satisfy any of the requirements, is non-normal. An example of a non-normal modal logic is alternating-time temporal logic.
Answer: I would point your attention to to Heinrich Wansing's  work on impossible worlds semantics for modal logics. In a series of papers Wansing formulates a generalization of standard Kripke semantics for normal modal logics that  comprises both normal logics as well as classical modal logics. See his papers "Bemerkungen zur Semantik nicht-normaler möglicher Welten", Zeitschrift für Mathematische Logik und Grundlagen der Mathematik, 35 (1989): 551–7; "A General Possible Worlds Framework for Reasoning about Knowledge and Belief", Studia Logica, 49 (1990): 523–39.
I think there has also been much relevant work in the area of neighbourhood semantics for modal logics. One of the main applications of neighbourhood semantics indeed consists in providing an interpretation for non-normal logics (as was originally also the case with the impossible worlds stuff, see some early papers by Kripke and Cresswell). See Pacuit's nice intro text 'Neighbourhood semantics for modal logic'.


Connection between invariant subspaces and eigenvalues

Question: Suppose map $A: R^n \rightarrow R^n$ has invariant subspaces $L_1,L_2$ such that $\dim (L_1 \cap L_2) = 1$. Does A have real eigenvalue?
The only link between eigenvalues and invariant subspaces I know is that linear span of set of eigenvectors corresponding to the same eigenvalue is invariant with respect to A. But I don't see how it relates to being real?
Answer: Let $X=L_1\cap L_2$, $X$ is also an invariant subspace isomorphic to $\mathbb R$, so $A$ induces a linear mapping $A':\mathbb R\to \mathbb R$.
Then $A'(1)$ is a real eigenvalue of $A$, corresponding to the eigenvector generating $X$.
Answer: Hint: $L_1\cap L_2$ is also an invariant subspace. Since it is one-dimensional, it is a subspace of an eigenspace.
Comment: So one-dimensional eigenspace cannot correspond to complex eigenvalue?
Comment: Of course not. Every real eigenspace of a real matrix must correspond to a real eigenvalue. Suppose $Ax=\lambda x$, where $A\in M_n(\mathbb{R})$ and $x\in\mathbb{R}^n\setminus0$ are real. If $\lambda$ is nonreal, then the LHS ($Ax$) is real but the RHS ($\lambda x$) is nonreal, which is impossible.


gcp dataproc how to use the same python between interactive login and ssh commands

Question: for a gcp dataproc cluster, if I ssh to run a command
gcloud compute ssh --internal-ip mycluster-m some_command.sh

the python I get is
/usr/bin/python

However when I login, I get a system conda python --
/opt/conda/default/bin/python

sourcing .bashrc in my script doesn't help, and I see the .bashrc has
# If not running interactively, don't do anything
case $- in
    *i*) ;;
      *) return;;
esac

which I think means it wont do anything - however I don't see how python gets set to the conda environment in what follows in the bashrc (this is dataproc image version 1.4)
The other confusing thing is how to install packages in the initialization script. I primarily do adhoc interactive work on the dataproc, and I've learned to do things like
sudo /opt/conda/default/bin/python3 -m pip install tensorflow<1.15 google-cloud-storage

to get my packages available. But now when I run a ssh command, I'm given a different python?
What do I source to get the conda python running when I ssh commands?
Comment: Compare which user you are logging in as after logging in: `whoami`
Answer: SSH-with-command just runs the command by forking instead of creating a new login shell which is why python env is not activated. This is one of several cases where you do not get the user python.
For your use case, sourcing /etc/profile.d/effective-python.sh is a reasonable approach.


Custom classpath for Gradle for Android Studio

Question: My company admin helped me to install the Android Studio, but when I try to create a project, it come with error

Error:A problem occurred configuring project ':app'.
  > Could not download junit.jar (junit:junit:4.12)
  > Could not get resource 'https://jcenter.bintray.com/junit/junit/4.12/junit-4.12.jar'.
  > Could not GET 'https://jcenter.bintray.com/junit/junit/4.12/junit-4.12.jar'.
  > sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

After investigate the log file, I found that Gradle cannot download the JUnit library, which possibly caused by firewall.

org.gradle.internal.resource.transport.http.HttpRequestException: Could not GET 'https://jcenter.bintray.com/junit/junit/4.12/junit-4.12.jar'

However, if I use browser go to this URL, I'm able to grab this jar (with warning, but can bypass it).
So my question is, can I pass this jar to Gradle or append to classpath for Gradle?
And one more thing, I don't have admin right and can't modify the Program Files
Thanks in advance!
UPDATE
At the end, I have solved this problem by following steps:

Fix the SSL problem, as my company's firewall will alter the certificate, I need to add that into java keystore (Details in Here)
After fixed the SSL problem, it throw another exception Failed to resolve: junit:junit:4.12 and more other library, I follow another post "Error:(23, 17) Failed to resolve: junit:junit:4.12" to solve this.

Hope this can help if anyone have the same problem.
Happy coding~~~
Answer: A very simple way is you can put the junit jar file in the android project "libs" folder
Gradle will add this to the classpath, if you open the build.gradle file, you will get something like
dependencies {
    compile fileTree(dir: 'libs', include: '*.jar')
    ......
}

Comment: Thank, but still have the same issue
Comment: After put the jar to this folder, did you refersh the gradle project?
Comment: I have tried `Sync Project with Gradle Files`, Close Project and open it again.  Is it same as refresh the gradle?
Comment: Should the same, can you find the junit jar in the "External Libraies" in the project view?
Comment: I can't, maybe I misunderstood your `libs` folder? Is it the `libs` in my project or it have a folder named `android project`? Thanks
Comment: It's in your project root folder.


Is there a way to scroll to end of page in pyppeteer

Question: I have tried looking in documentation and such, but not able to find a way to scroll down to bottom of page while using pyppeteer library with python3.
Would be great if anyone could point me to the right direction or solution.
Comment: just user hover functionality to point to your element it automatically scrolls  https://miyakogi.github.io/pyppeteer/reference.html#pyppeteer.element_handle.ElementHandle.hover
Comment: Could you provide an example to the same.
Answer: I was able to resolve this by doing something like this.
await page.hover(".class name")
Thanks everyone


React Hooks Rendered more hooks than during the previous render

Question: A component that renders a preview of filled out forms, as you click on the forms on the left it displays them on the right.
The first handleSwitchReview throws me the React Hooks Rendered more hooks than during the previous render error
The second does not. When I console log the props for example I am getting them 4-5 times when the view with the first function is shown, but not the second, the second only shows 1 time in the console log.
Tried moving the setState around and logging the parents in the console but this component is the only one that's firing a bunch  of times and breaking, and maybe I just dont have a firm understanding on how to structure this.

const SimpleFormPreview = (props) => {
    //Deconstructing Props
    const { childAndButtonWithStylesForPreview } = props;

    //Setting State
    const [child, setChild] = useState({
        childToDisplay: childAndButtonWithStylesForPreview ? childAndButtonWithStylesForPreview[0].child : {}
    });

    //Deconstructing State
    const { childToDisplay } = child;

    const handleSwitchReview = (childWithIconArr) => {
        setChild({ childToDisplay: childWithIconArr.child });
    };

    const renderPreview = () => {
        if (childToDisplay.hasOwnProperty('schema')) {
            return <SimpleFormView children={undefined} schema={childToDisplay.schema} onValChange={{}} onSatisfiedOrPercentageChange={{}} vals={{}} existingLookupOriginalVals={{}} nonStandardKeysInPropInfo={{}} satisfiedOverrides={{}} />;
        } else {
            var reviewItems = _.map(childToDisplay, function (val, key) {
                console.log('here', val, key);
                if (!key.startsWith('customer') && (key.startsWith('custom') || key.endsWith('Cost'))) {
                    //skip rendering these
                    //they will be attached to the main settings rendering below
                    return null;
                } else {
                    if (key === '_id' || key === 'id') {
                        return null;
                    }

                    var costEl;
                    var customEl;

                    _.each(childToDisplay, function (customOrCostVal, customOrCostKey) {
                        if (customOrCostKey === 'custom' + key) {
                            customEl = (

                                    {'Customized to ' + customOrCostVal.toString()}

                            );
                        }

                        if (customOrCostKey === key + 'Cost') {
                            costEl = (

                                    {'+ $' + customOrCostVal.val}

                            );

                            totalAdditionalCost = totalAdditionalCost + customOrCostVal.val;
                        }
                    });
                    return (

                            {costEl}

{key.toString()}
:
{val.toString()}

                            {customEl}

                    );
                }
            });
            return reviewItems;
        }
    };

    return (
        <Grid container direction='column' justify='flex-start' spacing={0}>
            <Grid item xs={12}>
                <Grid container wrap='wrap' spacing={0}>
                    <Grid style={{ position: 'fixed', width: 100 }} container direction='column'>

                            {_.map(childAndButtonWithStylesForPreview, function (childObj, idx) {
                                var innerIconElText = '';
                                // if ((idx + 1) > 99) {
                                //     innerIconElText = '...' + (idx + 1)
                                // } else {
                                //     innerIconElText = idx + 1
                                // }
                                if (childObj.iconEl) {
                                    childObj.iconEl.props.style.boxShadow = childToDisplay.id === childObj.child.id ? 'green 0px 0px 33px 5px' : null;
                                    return
 handleSwitchReview(childObj)} key={idx}>{childObj.iconEl}
;
                                } else {
                                    return (
                                        <Button style={{ boxShadow: childToDisplay.id === childObj.child.id ? 'green 0px 0px 33px 5px' : null, height: 100, margin: '25px', borderRadius: 60 }} key={idx} onClick={() => handleSwitchReview(childObj)}>

                                            {innerIconElText}
                                        </Button>
                                    );
                                }
                            })}

                    </Grid>
                    <Grid id={'simpleForm'} style={{ height: '100%', width: '100%', overflow: 'auto' }} container>
                        <Paper style={{ marginTop: '25px', marginLeft: '165px', padding: '15px', width: '80%' }} elevation={24}>
                            hello

                                <Button id='localSaveBtn' onClick={() => handleSave(document.querySelector('#simpleForm'))} variant='contained' color='secondary' size='large' style={{}}>
                                    Save File
                                </Button>

                        </Paper>
                    </Grid>
                </Grid>
            </Grid>
        </Grid>
    );
};

export default SimpleFormPreview;
Comment: can you add a bit more to your code snippet -> how are you rendering `SimpleFormPreview`
Comment: absolutely its not a big file so I'll insert the whole thing.Ok done....
Comment: I can't see anything immedaitely in that file that looks like it would throw that error. Are you rendering it with create element like `` because I vaguely recall it throwing that error for me once just calling the component like `SimpleFormPreview()`. Do you have any examples of what data you passing in for props like  `childAndButtonWithStylesForPreview`?
Comment: props example=  [
  {
    "id": 0,
    "child": {
      "_id": "60143a2576ee585c52ffdfe0",
      "partNumber": "a",
      "createdBy": "Jacob1 Wazydrag",
      "createdOn": "2021-01-29T16:39:01.012Z",
      "id": "1611938341138"
    }
  }
]
Comment: how i am rendering it in parent:
return
Comment: I added a gif to show what it looks on the client , the first button clicks are the render of the second handleSwitchReview(childObj) the one in
Comment: Seems like something simple I am missing....
Comment: Unless I'm being really blind, I can't see anything that jumps out at me that I know would cause that error to be thrown. I noticed you were doing some logic with `iconEl` and it seems like you were directly mutating props of a component here `childObj.iconEl.props.style.boxShadow`? Can the child sometimes have a property called `iconEl` which is a component? Does the one it errors on happen to have `iconEl` present?
Comment: I uncommented that line and it works!! So my iconEl ends up being an element passed in by a parent and looks like this: , am i not allowed to mutate it when it comes in or can i just add a property after it comes in? Whats best practice here? Also once we come up with a direct answer you can post it and I'll accept!
Comment: This actually falls outside of my wheelhouse and I'm not immediately sure what the best way of moving forward is. I assume that the issue you are mutating a prop value directly and this then triggers multiple renders to happen? I think that you need to use `cloneElement` to achieve your desired result: https://reactjs.org/docs/react-api.html#cloneelement so I think you will end up with something like this: `{React.cloneElement(childObj.iconEl, { style: {...childObj.iconEl.props.style, boxShadow: childToDisplay.id === childObj.child.id ? "green 0px 0px 33px 5px" : null }})}` ?
Comment: var clonedElementWithInjectedStyles = React.cloneElement(childObj.iconEl, { style: {...childObj.iconEl.props.style, boxShadow: childToDisplay.id === childObj.child.id ? "green 0px 0px 33px 5px" : null }})
made it a var put it in instead of {childObj.IconEl} and worked like a charm THANKS MAN! Put it in an answer and ill hit that accept!
Answer: Mutating the prop directly after the if statement " if (childObj.iconEl) " was causing the app to re render repeatedly.
with cloneElement I was able to have my element will have the original element's props with the new props merged in shallowly: reactjs.org/docs/react-api.html#cloneelement the error stopped and I was able to achieve the desired result which was to change the box shadow onClick of a button that was passed down to a child element as props.
Below is the code to replace the lines after the " if (childObj.iconEl) " If Condition.

                                    var clonedElementWithInjectedStyles = React.cloneElement(childObj.iconEl, { style: { ...childObj.iconEl.props.style, boxShadow: childToDisplay.id === childObj.child.id ? 'green 0px 0px 33px 5px' : null } });
                                    return (

 handleSwitchReview(childObj)} key={idx}>
                                            {clonedElementWithInjectedStyles}

                                    );


Using nginx as a reverse proxy for tomcat results in new jsessionids for every ssl request

Question: I am using nginx as a reverse proxy for a tomcat setup, and everything works fine for the MOST part, the only issue I am having is that every request to an http address results in a new JSESSION ID being created(this doesn't happen in http), here is the relevant part of the NGINX configuration:
location / {

            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            proxy_set_header X-Real-IP $remote_addr;

            proxy_set_header X-Forwarded-Proto https;
            proxy_redirect off;
            proxy_connect_timeout      240;
            proxy_send_timeout         240;
            proxy_read_timeout         240;
            proxy_pass http://localhost:8080;
      }

Any idea why I am constantly genning new jsessionids?
Answer: Add the following snippet to your configuration file and try again:
if ($http_cookie ~* "jsessionid=([^;]+)(?:;|$)") {
    set $co "jsessionid=$1";
}
proxy_set_header Cookie "$co";

Answer: In my environment this behavior was caused by Tomcat or the servlet was expecting a different cookie path due to changing the root while proxying:
Setting the path via proxy_cookie_path helped:
location / {
    proxy_pass http://localhost:8080/webapp/;
    proxy_cookie_path /webapp/;

    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}


Should I use independent- or propensity score matching?

Question: I work on data form an observational study (n=34) and want to compare the outcome of the individuals to an historic cohort (n=600). Subjects in the observational study received additional treatment compared to the historical cohort. I collected data on disease type, disease intensity, response and demographics for both groups.
Now, I want to perform survival-analysis using the Kaplan-Meier-Estimator, comparing both groups overall and matched 1:1, 1:2. Could you advise on the recommended matching method to use for matching the 34 subjects of the observational study to the historical cohort, to adjust for disease type, disease intensity, and response?
Answer: Use whatever matching method yields the best balance. Sometimes that will be propensity score matching and sometimes it will be some other form of matching. I recommend genetic matching, which optimizes balance. Ideally you will retain the largest sample size you can, so you should try multiple different matching ratios (e.g., 1:1, 1:2, 1:10, etc.) to find the one that yields the greatest remaining sample size and balance.
Read the MatchIt vignette on matching methods, which provides a guide on all the matching methods available in the package and how to choose among them and customize them. It's good that you are not blindly using propensity score matching just because it is the most common matching method, but the specific matching methods that will work best for your data must be discovered by trying multiple and comparing their performance at balancing the covariates.


How can Google Docs go fullscreen in JavaScript

Question: How can Google Docs go fullscreen in JavaScript?
In a Google Docs Presentation, when you press the fullscreen button at the lower left corner of the window, the window goes fullscreen.
It is not Flash so I am curious that how can Google do that?
Added
Note that it is not creating a big window that fits the screen (that's fake fullscreen). It is actually in fullscreen mode, and Google Chrome asked for my permission.
Comment: where is the fullscreen button? I can't seem to find it.
Comment: @tr4656, In a Webkit browser, open a Google Docs Presentation (new), and the button is at the lower left corner of the window.
Comment: OK, I myself did a little research on it and found out that a little trick would do it: `Fullscreen`
Answer: It seems they are using the technique described in this article: http://www.thecssninja.com/javascript/fullscreen
// Mozilla
element.mozRequestFullScreen();

// Webkit
element.webkitRequestFullscreen();

Edit: That article forgets to mention that if you want the whole page fullsreen you can do document.body.webkitRequestFullscreen();.
Answer: I've tested the code given in this question on Internet Explorer 9:
How to make browser full screen using F11 key event through JavaScript
At least for Internet Explorer 9, though, the permission dialog might be misleading.
Comment: Now we can make it goes fullscreen on the major browsers! Thanks.


Post review for anonymous, save as draft or save unpublished

Question: I have a form that allow anonymous user to send a job offer. Everything working fine but I don't want users to be able to publish node on the spot. I want it to publish as a draft/unpublished for reviewing before.
Can I alter my form in some way to prevent this?
Like only use save unpublished button action.
Answer: Does your form after submission creates a node programmatically? If so you can just set the status of the node to 0.
Comment: No, it's set by drupal like a regular add form. I don't do anything programmatically. Everything is manage by drupal. It seems like you can't only display "Save as a draft" button action. It's always the two sided button


multi-master over multi-region Aurora - possible?

Question: I am relatively experienced with many AWS services - but I do have a large gap around Aurora/RDS
I'm trying to create a multi-region multi-master (write replicas) setup
The purpose is to give low latency to users (if each read and write replica is in the user's region) and to give resilience (if there is a region outage, the users can have their requests routed to another region (the latency will be higher, but reduced service is better than no service))
I'm trying to learn about AWS Aurora and I've created a toy cluster to learn. It seems I can create a cluster that is served out of multiple regions (and Aurora replicates data between regions automatically). I've also read that it is possible to have a multi-master setup (in my toy cluster, it only had one write partition, I couldn't work out how to create another write partition in another region, which made me question if it's possible?)
Here is a diagram of what I'm thinking:
https://i.stack.imgur.com/bfigZ.jpg
Thank you in advance!
Answer:
The purpose is to give low latency to users (if each read and write replica is in the user's region)

I couldn't work out how to create another write partition in another region, which made me question if it's possible?

That is not possible (at least not currently) because of multi-master Aurora limitations.

all DB instances in a multi-master cluster must be in the same AWS Region.

and others such as

you can have a maximum of two DB instances in a multi-master cluster
You can't enable cross-Region replicas from multi-master clusters.

You can read more here

The best thing you can do in your scenario is to create single master and place read replicas into those additional regions (possibly with some caching in necessary).
Comment: So I'd have to look into another solution...
I guess a separate cluster for each region, and then use lambda/DMS to replicate between clusters manually (and resolve conflicts)

The only time there would be conflicts is where users change region (either by themselves physically moving, or a region going down) - either way there shouldn't be many conflicts

Are there any common patterns that I can follow here?
Surely others have solved this problem?
Comment: I am not sure if speed at such scale is of the utmost importance that the SQL based databases are the right choice. Other have solved this issue usually by turning into NoSQL DBs that are much easier to shard and scale. The issue is that you would need to be able to perform eventually consistent writes (due to cross region distance) and SQL databases are not designed to be used like that. For example, in DynamoDB, you can have global tables with multiple cross region master writers who can handle eventually consistent writes.
Answer: As mentioned earlier it is not possible with Aurora.
However DynamoDB supports multi-active multi-region:
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GlobalTables.html
Answer: As others have said, with Amazon Aurora, you cannot deploy multi-Region and multi-master. However you can deploy multi-Region using Aurora Global Database. Then one writer endpoint would be in one Region, while reader endpoints would be available in all the other Regions. Then you can also use write forwarding (assuming you are using the MySQL flavor of Aurora) in the read-only Regions. I know latency is a concern for you, so note the write actually goes back to the primary Region, so writes will incur that extra latency.
Answer:
The purpose is to give low latency to users and to give resilience.

Then you can use Amazon Aurora Global Database. This solution provides replication from the Aurora storage layer across Regions. The reader endpoint in the secondary endpoint can be promoted in the event of a DR scenario to be the main database which takes on read/write responsibilities.


Safari and background-clip: text not working well on multiple lines of display:inline text element

Question: I don't know why, but when I set
background-clip: text
to clip a gradient/image/whatever with text (display: inline), only Safari doesn't work as it is supposed to.
I recreated a pen with this issue: https://codepen.io/steexd/details/qBZVbWY
Test it with Firefox or Chrome and then with Safari: you will notice that multi-line text won't clip correctly the background gradient.
Expected result:

Safari:

Any help would be really appreciated :)
Answer: You can add -webkit-box-decoration-break: clone;
It will make the text legible, however it isn't exactly what you're asking for as it will repeat the gradient on each line.
box-decoration-break property on MDN

h1 {
  max-width:120px;
}
span {
  background-image: -webkit-linear-gradient(right, red, pink);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  -webkit-box-decoration-break: clone;
}

Hi, i'm a text with a long span gradient.


How to generate random number that must contains predefined characters?

Question: In my application i need to generate random numbers that should contain certain character like capital letter, a number and of certain length.
It will be an honor if you guys help me out.
Comment: Generate arrays/lists of characters that you want to require (one for lower, one for upper, one for numbers...etc). Pick however many characters you want from each list and join them together.
Comment: You should not just simply join them, though. You should a) randomize the number of characters you take from each list (ensuring the required minimum amount from each list), then *shuffle* the results together so that a hacker doesn't know you first have the lower case, then the upper case, then the numbers.
Comment: post what have you tried please
Answer: I have a script that requires the word "Lock" followed by a 2 digit number followed by a random four-letter word. This is an abbreviation of what I used...
<code>$words = array("Pick","Hard","Gene","Boat","Pass");
// Make that list as long as you like...
function get_random_string()
{
    global $words;
    shuffle($words);
    return 'Lock'.rand(10,99).$words[0];
}
</code>
Answer: <code>function rand_string( $length ) {

    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    return substr(str_shuffle($chars),0,$length);

}

echo rand_string(8);
</code>


When destructuring tuples in Haskell, where can the elements be used?

Question: I am reading a tutorial that uses the following example (that I'll generalize somewhat):
f :: Foo -> (Int, Foo)
...
fList :: Foo -> [Int]
fList foo = x : fList bar
  where
    (x, bar) = f foo

My question lies in the fact that it seems you can refer to x and bar, by name, outside of the tuple where they are obtained. This would seem to act like destructuring parameter lists in other languages, if my guess is correct. (In other words, I didn't have to do the following:)
fList foo = (fst tuple) : fList (snd tuple)
      where
        tuple = f foo

Am I right about this behavior? I've never seen it mentioned yet in the tutorials/books I've been reading. Can someone point me to more info on the subject?
Edit: Can anything (lists, arrays, etc.) be destructured in a similar way, or can you only do this with tuples?
Comment: If you don't eventually run into an explanation of pattern matching in that tutorial, you might want to supplement it with a more complete explanation of Haskell. Pattern matching is basic and important to the language.
Answer: Seeing your edit, I think what your asking about is Pattern matching.
And to answer your question: Yes, anything you can construct, you can also 'deconstruct' using the constructors. For example, you're probably familiar with this form of pattern matching:
head :: [a] -> a
head (x:xs) = x
head []     = error "Can't take head of empty list"

However, there are more places where you can use pattern matching, other valid notations  are:
head xs = case xs of
              (y:ys) -> y
              []     -> error "Can't take head of empty list"

head xs = let (y:ys) = xs
          in y

head xs = y
  where
    (y:ys) = xs

Note that the last two examples are a bit different from the first to because they give different error messages when you call them with an empty list.

Although these examples are specific to lists, you can do the same with other data types, like so:
first :: (a, b) -> a
first tuple = x
  where
    (x, y) = tuple

second :: (a, b) -> b
second tuple = let (x, y) = tuple
               in y

fromJust :: Maybe a -> a
fromJust ma = x
  where
    (Just x) = ma

Again, the last function will also crash if you call it with Nothing.
To sum up; if you can create something using constructors (like (:) and [] for lists, or (,) for tuples, or Nothing and Just for Maybe), you can use those same constructors to do pattern matching in a variety of ways.
Comment: I don't understand how it can destructure the array to tupple
e.g., why this works
`head :: [a] -> a
head (x:xs) = x`

But this does not work
`head :: [a] -> a
head [x:xs] = x`
it's unintuitive for me
Answer:
Am I right about this behavior?

Yes. The names exist only in the block where you have defined them, though. In your case, this means the logical unit that your where clause is applied to, i.e. the expression inside fList.
Answer: Another way to look at it is that code like this
x where x = 3

is roughly equivalent to
let x = 3 in x

Answer: Yes, you're right.  Names bound in a where clause are visible to the full declaration preceding the where clause.  In your case those names are f and bar.
(One of the hard things about learning Haskell is that it is not just permitted but common to use variables in the source code in locations that precede the locations where those variables are defined.)
The place to read more about where clauses is in the Haskell 98 Report or in one of the many fine tutorials to be found at haskell.org.


Evaluate $\sum_{k=0}^{\infty} \sum_{j=0}^{\infty} \sum_{i=0}^{\infty} \frac{1}{3^i3^j3^k}$ for $i\neq j\neq k$

Question:
Evaluate $$\sum_{k=0}^{\infty} \sum_{j=0}^{\infty} \sum_{i=0}^{\infty} \frac{1}{3^i3^j3^k}$$ for $i\neq j\neq k$

My Attempt
Evaluate the summation with no restriction on $i,j,k$. Let this be $a_0$
When $i= j=k$. Let this be $a_1$.
When $i\neq j=k$, let this be $a_2$.
The required answer would be $a_0-a_1-3a_2$.
I got \begin{align}a_0&=\frac{27}{8}\\\\
a_1&=\frac{27}{26}\\  \\
a_2&=\frac{135}{208}\end{align}
And therefore, my answer is
\begin{align}a_0-a_1-3a_2&=\frac{27}{8}-\frac{27}{26}-3\times\frac{135}{208}\\\\
&=\frac{81}{208}\end{align}
Is everything correct? The method and the calculation? Also if anyone has a better method, please tell.
Answer: Let's rearrange the sum:
$$ S := \sum_{i,j,k \ge 0, \ i \neq j \neq k} 3^{-i} 3^{-j} 3^{-k} = \sum_{j \ge 0} \left( 3^{-j} \sum_{i \ge 0, \ i \neq j} 3^{-i} \sum_{k \ge 0, \ k \neq j} 3^{-k} \right). $$
The two inner sums are equal
$$ \sum_{i \ge 0, \ i \neq j} 3^{-i} = \left( \sum_{i \ge 0} 3^{-i} \right) - 3^j = \frac{3}{2} - 3^{-j}, $$
so we're left with
\begin{align*}
S & = \sum_{j \ge 0} \left( 3^{-j} \left(\frac{3}{2} - 3^{-j}\right)^2 \right) \\
& = \left( \frac 32 \right)^2 \sum_{j \ge 0} 3^{-j}
- 2 \cdot \frac 32 \cdot \sum_{j \ge 0} 3^{-2j}
+ \sum_{j \ge 0} 3^{-3j} \\
& = \frac 94 \cdot \frac 32 - 3 \cdot \frac 98 + \frac{27}{26} \\
& = \frac{27}{26}.
\end{align*}

If I understand your notation correctly, the sum should be equal to
$$ S = a_0 - a_1 - 2 a_2, $$
but substituting the values of $a_0,a_1,a_2$ you calculated gives a negative result. Since you haven't included your reasoning, I cannot say more.

If you're interested in $i,j,k$ pairwise distinct, this is a different problem. By the inclusion-exclusion principle, we get
\begin{align*}
\sum_{i,j,k \text{ distinct}} 3^{-i-j-k}
& = \left( \sum_{i,j,k} 3^{-i-j-k} \right)
- 3 \left( \sum_{i=j, \ k} 3^{-i-j-k} \right) +
2 \left( \sum_{i=j=k} 3^{-i-j-k} \right) \\
& = \left( \frac 32 \right)^3 - 3 \cdot \frac 32 \cdot \frac 98 + 2 \cdot \frac{27}{26} \\
& = \frac{81}{208},
\end{align*}
which happens to coincide with your result.
Comment: @Tilly Of course you can. I had the same doubt. The OP didn't include the restriction $i \neq j \neq k$ into the summation, but mentioned it below the sum.
Comment: Can I just ask (as someone who has happened to come onto this post), why is the sum not equal to $\frac{27}{8}$? We get this from summing over i, geometric series, then j, then k, so to get $\left(\frac{27}{8} \right)^3$?
Answer: I have the same answer.
\begin{align*}
\sum_{k\in\mathbb{N}} \sum_{j\in\mathbb{N}\setminus\{k\}} \sum_{i\in\mathbb{N}\setminus\{j,k\}} \frac{1}{3^i3^j3^k}&=\sum_{k\in\mathbb{N}} \sum_{j\in\mathbb{N}\setminus\{k\}} \left(\frac{1}{3^j3^k}\sum_{i\in\mathbb{N}\setminus\{j,k\}} \frac{1}{3^i}\right)\\
&=\sum_{k\in\mathbb{N}} \sum_{j\in\mathbb{N}\setminus\{k\}} \left[\frac{1}{3^j3^k}\left(\frac{1}{1-\frac{1}{3}}-\frac{1}{3^j}-\frac{1}{3^k}\right)\right]\\
&=\sum_{k\in\mathbb{N}}\left[\frac{1}{3^k}\left(\frac{3}{2}-\frac{1}{3^k}\right)\sum_{j\in\mathbb{N}\setminus\{k\}} \frac{1}{3^j}-\frac{1}{3^k}\sum_{j\in\mathbb{N}\setminus\{k\}} \frac{1}{3^{2j}}\right]\\
&=\sum_{k\in\mathbb{N}}\left[\frac{1}{3^k}\left(\frac{3}{2}-\frac{1}{3^k}\right) \left(\frac{3}{2}-\frac{1}{3^k}\right)-\frac{1}{3^k}\left(\frac{1}{1-\frac{1}{9}}-\frac{1}{3^{2k}}\right)\right]\\
&=\sum_{k\in\mathbb{N}}\left(\frac{9}{8}\cdot\frac{1}{3^k}-3\cdot\frac{1}{3^{2k}}+2\cdot\frac{1}{3^{3k}}\right)\\
&=\frac{9}{8}\cdot\frac{3}{2}-3\cdot\frac{9}{8}+2\cdot\frac{1}{1-\frac{1}{27}}\\
&=\frac{9}{8}\cdot\frac{3}{2}-3\cdot\frac{9}{8}+2\cdot\frac{27}{26}\\
&=\frac{81}{208}
\end{align*}
Comment: You're assuming that $i,j,k$ are pairwise distinct, not that $i \neq j \neq k$. I believe this is what the OP wanted, though not what he asked for.


Linq Extension Method - GetYearWeekFormat Extension

Question: I'm looking for help on the following linq query and extension method:
DateTime? ddStartOfTime = Convert.ToDateTime("2016/04/10 11:15:00");
DateTime? ddEndOfTime = Convert.ToDateTime("2017/06/25 13:15:00");

List<int> doWeeksNeeded = new List<int>();

doWeeksNeeded.Add(201614);
doWeeksNeeded.Add(201616);

var dq1 = (from c in tblschedulefulldates
       where doWeeksNeeded.Contains(c.ddJobStart.GetYearWeekFormat())
       orderby c.diEmployeeID
       select new
       {
           diEmployeeID = c.diEmployeeID == null ? 0 : (int)c.diEmployeeID,
           dnDayOfWeek = c.ddJobStart.DayOfWeek == null ? 0 : (int)c.ddJobStart.DayOfWeek
       });

The following are the Extension Methods:
public static int GetYearWeekFormat(this DateTime pddate)
{
    int weekNo = GetIso8601WeekOfYear(pddate);
    int year = pddate.Year;
    if (weekNo == 1 && pddate.Month > 1) year = year + 1;
    return Convert.ToInt32(year.ToString() + weekNo.ToString().Trim());
}

public static int GetIso8601WeekOfYear(this DateTime pddate)
{
    System.Globalization.Calendar cal = System.Globalization.CultureInfo.InvariantCulture.Calendar;
    // Seriously cheat.  If its Monday, Tuesday or Wednesday, then it'll
    // be the same week# as whatever Thursday, Friday or Saturday are,
    // and we always get those right
    System.DayOfWeek day = cal.GetDayOfWeek(pddate);
    if (day >= System.DayOfWeek.Monday && day <= System.DayOfWeek.Wednesday)
    {
        pddate = pddate.AddDays(3);
    }

    // Return the week of our adjusted day
    return cal.GetWeekOfYear(pddate, System.Globalization.CalendarWeekRule.FirstFourDayWeek, System.DayOfWeek.Monday);
}

However when I run this I get:
Method 'Int32 GetYearWeekFormat(System.DateTime)' has no supported translation to SQL

So I decided to create another extension called In:
public static bool In<T>(this DateTime value, IEnumerable<Int32> values)
{
    if (values == null)
        throw new ArgumentNullException("values");
    int lnWeek = GetYearWeekFormat(value);
    return values.Contains(lnWeek);
}

And called it like this:
var dq1 = (from c in tblschedulefulldates
       where c.ddJobStart.In(doWeeksNeeded)
       orderby c.diEmployeeID
       select new
       {
           diEmployeeID = c.diEmployeeID == null ? 0 : (int)c.diEmployeeID,
           dnDayOfWeek = c.ddJobStart.DayOfWeek == null ? 0 : (int)c.ddJobStart.DayOfWeek
       });

Except I can't get this to work either. It gives the following error:
The type arguments for method 'DateTimeExtensions.In<T>(DateTime, IEnumerable<int>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

Can someone help please?
Comment: Are you using this with Entity Framework?
Comment: This won't work either, not all queryables can be translated to sql queries, especially those containing custom logic like in GetYearWeekFormat.
Comment: No this is an old system - it uses Linq 2 Sql - a dbml file
Answer: LINQ 2 SQL doesn't know how to translate GetYearWeekFormat to SQL.
You would need to query the database first and then do your work on the local list.
var localList = (from c in tblschedulefulldates
   select new
   {
       ddJobStart= c.ddJobStart,
       diEmployeeID= c.diEmployeeID,
   }).ToList();

var dq1 = (from c in localList
       where doWeeksNeeded.Contains(c.ddJobStart.GetYearWeekFormat())
       orderby c.diEmployeeID
       select new
       {
           diEmployeeID = c.diEmployeeID == null ? 0 : (int)c.diEmployeeID,
           dnDayOfWeek = c.ddJobStart.DayOfWeek == null ? 0 : (int)c.ddJobStart.DayOfWeek
       });


Help calculating relative pseudo-complements in a Heyting algebra/lattice

Question: I'm trying to work some examples of relative pseudo-complements in lattices, to make sure I understand them. I wonder if anybody could check my examples, and tell me if I'm correct or if I've misunderstood.
I'm looking at the definition of relative pseudo-complement in Rasiowa/Sikorski, The Mathematics of Metamathematics, p. 54. It says that an element $c$ is the pseudo-complement of $a$ relative to $b$ (denoted $a \Rightarrow b$), if $c$ is the greatest element such that $a \wedge c \leq b$.
I think I grasp why it is that if $a \leq b$, then $a \Rightarrow b$ is always 1. I'm now trying to understand $a \Rightarrow b$ when $a \not \leq b$.
Example 1.
Suppose I have this lattice:
<code>  1
 / \
a   b
 \ /
  0
</code>
I want to figure out which element $x$ is $b \Rightarrow 0$, i.e., which element $x$ is the pseudo complement of $b$ relative to $0$.
If I follow Rasiowa/Skiorski's definition, I find this by putting together the set $\{ x : b \wedge x \leq 0\}$, and then I take the greatest element from that.
Here, I see $\{ x : b \wedge x \leq 0\}$ = $\{ 0, a \}$, since $b \wedge 0 = 0 \leq 0$, and $b \wedge a = 0 \leq 0$. Then, the greatest of $\{ 0, a \}$ is $a$, so I conclude that the pseudo complement of $b$ relative to $0$ is $a$, i.e., that $b \Rightarrow 0 = a$.
Did I do that correctly?
Example 2a.
Suppose I have this lattice (a powerset lattice on three elements $a$, $b$, $c$):
<code>    abc
  /  |  \
 ab  ac  bc
 | x   x |
 a   b   c
  \  |  /
     0
</code>
I want to find $c \Rightarrow 0$.
I follow the same procedure: I find $\{ x : c \wedge x \leq 0 \}$, which is $\{ 0, b, a, ab\}$. Then I take the greatest element from that, which is $ab$. So I conclude that $c \Rightarrow 0 = ab$.
Did I do that correctly?
Example 2b. By a similar argument to 2a, the pseudo-complement of $c$ relative to $b$ is $ab$ as well, i.e., $c \Rightarrow b = ab$.
Am I understanding this correctly?
Comment: You are right in all cases. By the way, both your examples you presented are Boolean algebras and in these, $x\to 0 = x'$, which gives the same answer in (1) and (2a). For (2b), notice that, in BA, $x\to y=x'\vee y$; as $c'=ab$, we get $$c\to b=ab\vee b=ab.$$
Comment: Thank you @amrsa! That's neat about BA too.
Answer: Thanks to @amrsa's comment above, I'll post the answer.
The answers I calculated above in the original post are correct.
@amrsa also noted that the two examples of lattices I used are Boolean algebras. In these, $x \Rightarrow 0$ always equals the complement of $x$ (sometimes written $x'$).
In example (1) above, $b \Rightarrow 0$ will thus be the complement of $b$. If we consider the lattice in example (1) to be the powerset of $\{a, b\}$, then the complement of $\{b\}$ is $\{a\}$, which is indeed the pseudo-complement of $\{b\}$ with respect to $\varnothing$.
In example (2a) above, $\{c\} \Rightarrow \varnothing$ will be the complement of $\{c\}$, which is $\{a, b\}$, and that is the pseudo-complement of $\{c\}$ with respect to $\varnothing$.
In example (2b), there is the principle that in Boolean algebras, $x \Rightarrow y$ is the same as $x' \lor y$, i.e., the complement of $x$, or $y$. In the lattice from (2b), the complement of $\{c\}$ is $\{a, b\}$, which is the pseudo-complement of $\{c\}$ relevant to $\{b\}$.
Comment: I actually didn't mentioned in the comment, but perhaps you noticed, that $x\to 0=x'$ also follows from $x\to y=x'\vee y$, since from this latter formula, $$x\to 0 = x' \vee 0 = x'.$$ It's rather trivial, but it could have gone unnoticed...


What is the sports bra looking thing soccer players wear?

Question: I've seen many male soccer players - specially famous players who play for well-known teams - wear a piece of clothing that looks like a sports bra. They're usually worn during practice, and a few other times I've seen them worn under the jersey during the games. I'm guessing it has some training benefits, but what is the bra looking thing? What's the purpose of wearing it?
Here are 2 pictures of Lionel Messi and Zlatan Ibrahimovic wearing the bra.
Answer: They are performance trackers. They track a player's vital statistics (heart rate, etc) as well as their movement, their average speed, their distance covered, etc. As for the "bra-like" design, it would appear to just be the result of needing a small and unencumbered design that allows for minimal interruption, maximum body contact, and full range of motion.
Link to the manufacturer of Zlatan's bra
Answer: GB11's answer summarized it well what are the tracking devices. From the YouTube page of GPSSports Systems you can see that what Zlatan wears is called GPSports SPI HPU tracking device, which according to its brochure has many features, some of them being GPS, accelerometer, wireless communication, water resistance, 5.5 hours battery life, etc.
The data collected by tracking device from players is auto-analysed to provide practical information on players' performance, like:

Establish the session load for each player
Identify outliers in the group
Identify players under significant training stress
Compare sessions to recent history
Produce high quality reports
Periodise training using a range of variables
Monitor individual training demands
Monitor rehabilitation and reconditioning programs
Compare players, sessions, drills and games

Note that those kind of tracking devices are used on a very high level in many team sports, and not just in football.
Answer: The "bras" contain a small pouch in the back which is used to hold a small GPS device. This device records many different variables such as average speed, distance traveled, fastest recorded sprint, and areas of the pitch that said player has traveled to. The bras are perhaps the most popular method to hold this device but vests and sleeveless shirts are also popular options amongst players who do not enjoy the tight fit of a sports bra.


Why is $x^4-3x^2+18$ irreducible over the $3$-adics?

Question: Let $f = x^4 - 3x^2 + 18 \in \mathbb{Q}_3[x]$. Since there is an LMFDB page of an extension defined by this polynomial, I assume that $f$ is irreducible. Could you verify if this is true and also why that is (not) the case?
It is not an Eisenstein polynomial (as $3^2$ divides $18$, the constant coefficient of $f$). I also tried the substitution $y = x^2$ and asked myself if $g = y^2 - 3y + 18$ is irreducible. Its reduction mod $3$ is $y^2$ which is not irreducible, so I cannot say whether $g$ is irreducible or not.
Comment: Because it is irreducible $\bmod 3^8$.
Answer: As others have explained $f(x)$ has no zeros in $\Bbb{Q}_3$ because $x^2-3x+18$ doesn't have any. Therefore the remaining possibility is that $f(x)=g(x)h(x)$ is the product of two irreducible monic quadratics, $g(x),h(x)\in\Bbb{Q}_3[x]$.
For another way to a contradiction consider the following. The polynomial $f(x)$ is even. Implying that if $g(x)\mid f(x)$ then also $g(-x)\mid f(-x)=f(x)$. In other words, $g(-x)$ is also an irreducible monic factor of $f$. The same applies to $h(-x)$ as well. We have two possibilities:

If $g(-x)=g(x)$ and $h(-x)=h(x)$, then $g(x)$ and $h(x)$ are both even. That is, $g(x)=x^2-a, h(x)= x^2-b, a,b\in\Bbb{Q}_3$. Then $a$ and $b$ would be zeros of $x^2-3x+18$, which is absurd.
If $g(-x)=h(x)$ (when automatically also $h(-x)=g(x)$) then we run into the following problem. If $g(x)=x^2+a_1x+a_2$, then $g(-x)=x^2-a_1x+a_2$, and
$$f(x)=g(x)g(-x)=x^4+\cdots+a_2^2.$$
So $18=a_2^2$. But this is impossible, because $18=2\cdot3^2$, and there is no $\sqrt2$ in $\Bbb{Q}_3$.

No factorization exists, so $f$ is irreducible.
Comment: This trick comes in handy in proving irreducibility of even polynomials. I think I have used it  on this site at least once already. Soon I will have to start CWing my answers based on this trick.
Comment: This is quite nice.
Answer: The polynomial $x^2 - 3 x + 18$ is irreducible over $\mathbb{Q}_3$.  Consider the quadratic extension  $F=\mathbb{Q}_3[\sqrt{-7}]$ over which it decomposes as $(x-x_1)(x-x_2)$.  So we have
$$x^4 - 3 x^2 + 18= (x^2-x_1)(x^2 - x_2)$$
Now it is enough to see that $(x^2 - x_1)$, $(x^2 -x_2)$ are irreducible over $F$, equivalently $x_i$ are not squares in $F$.
Consider the extension of the valuation $v_3$ to $F$. We have $v_3(x_i) = 1$. It is easy to see that there are no elements in $F$ of value $\frac{1}{2}$.
Note: the extension of the valuation $v_3$ to $F$ is $v(a + b \sqrt{-7}) = \frac{1}{2}v_3(a^2 + 7 b^2)$
Comment: $v(x_1) = 1$ doesn't imply that there is no element of $\Bbb{Q}_3(x_1)$ of valuation $1/2$ (try with $x_1= 3 (1+\sqrt{3})$). You need to say that $\Bbb{Q}_3(x_1)=\Bbb{Q}_3(\sqrt{\Delta}) =\Bbb{Q}_3(\sqrt{-7})$ is an unramified extension (because $x^2+7$ is irreducible $\bmod 3$)
Comment: @reuns: Very good point, let me add some details.
Answer: Well, here's an argument that uses a somewhat non-elementary fact about $p$-adic field extensions, namely that if the residue-field extension degree is $f$ and the ramification degree is $e$, then the total degree $n$ is $n=ef$. This $f$ is also the degree over the base field of the maximal unramified intermediate extension.
I'm about to show that if $\alpha$ is a root of $F(x)=x^4-3x^2+18$, then the extension $\Bbb Q_3(\alpha)\supset\Bbb Q_3$ has $f$ and $e$ both equal to $2$, so that $[\Bbb Q_3(\alpha):\Bbb Q_3]=4$. This shows that your polynomial $F$ is irreducible.
You've already seen that $G(x)=x^2-3x+18$ has $\alpha^2=\gamma$ for a root, and as I've pointed out in a comment, $\gamma/3$ is a root of $x^2-x+2=g(x)$. Use the Quadratic Formula to see that to get roots of $g$, you need $\sqrt{-7}$, and since $x^2+7\equiv x^2+1\pmod3$, adjoining $\sqrt{-7}$ is same as adjoining $i$ to $\Bbb Q_3$, giving the quadratic unramified extension of $\Bbb Q_3$. So $f=2$ for the extension $\Bbb Q_3(\gamma)\supset\Bbb Q_3$.
Since the roots of $g(x)$ are $3$-adic units (the constant term of the minimal polynomial is a unit), we have $v_3(\gamma)=1$, as @RobertIsrael has shown by different methods. This means that $v_3(\alpha)=v_3(\sqrt\gamma\,)=1/2$, which in turn means that the ramification degree $e$ of $\Bbb Q_3$ over $\Bbb Q_3$ is at least two. Thus we have $f\ge2$, $g\ge2$, and their product $n$, the degree of the minimal polynomial for $\alpha$ over $\Bbb Q_3$, is $\le4$. It follows that all three inequalities are equalities, and $F$ is irreducible.
Answer: If it's reducible, it has a factor of degree $1$ or $2$.  I'll leave it up to you to
show there is no factor of degree $1$ (i.e. no root in $\mathbb Q_3$).  So suppose
$x^2 + \alpha x + \beta$ divides $x^4 - 3 x^2 + 18$.  The remainder on this division
is $$(-\alpha^3 + 2 \alpha \beta + 3 \alpha) x - \alpha^2 \beta + \beta^2 + 3 \beta + 18$$
If $\alpha = 0$ we'd have $\beta^2 + 3 \beta + 18 = 0$, which has no root in $\mathbb Q_3$,
so $\alpha \ne 0$ and $\beta = (\alpha^2-3)/2$.  Substituting in to the remainder,
this gives us $$-\frac{\alpha^4}{4} + \frac{3}{2} \alpha^2 + \frac{63}{4} = 0$$
which has no solution in $\mathbb Q_3$.
EDIT: Here's one way to see $\beta^2 + 3 \beta + 18=0$ has no solution in $\mathbb Q_3$. If $\beta$ has $3$-adic order $m$, then $\beta^2$ has order $2m$ and $3\beta$ has order $m+1$, while of course $18$ has order $2$.
So the only possibility is $m=1$.
Thus we have the $3$-adic expansion $\beta = \beta_1 3^{1} + \beta_2 3^{2} + \ldots$, with $\beta_i \in \{0,1,2\}$.  But these three possibilities make $\beta^2 + 3\beta + 18 =
2 \cdot 3^2 + \ldots, 1 \cdot 3^2 + \ldots, 2 \cdot 3^2 + \ldots$ respectively, and not $0$.
Comment: It's much easier than that to see that $h(X)=X^2+3X+18$ has no root in $\Bbb Q_3$. Form $H(X)=\frac19h(3X)=X^2+X+2$, which doesn't even have any roots in $\Bbb F_3$.
Comment: I generally have trouble to understand how to see if a polynomial over $\mathbb{Q}_p$ has a root. Could you please explain how you can see why $\beta^2+3\beta +18=0$ and $-\alpha^4/4+3\alpha^2/2+63/4=0$ have no solutions in $\mathbb{Q}_3$? Maybe then I can understand why $x^4-3x^2+18$ has no roots in $\mathbb{Q}_3$.
Comment: @Lubin: That's a nice explanation! Can this trick you used be generalized?
Comment: Are you asking whether it's a good idea to check whether the (monic) polynomial has no roots by looking modulo a maximal ideal? The answer is Yes, @Rotdat ,  Sure, and you should always try that, as long as you're trying to show that there are no roots. If there's a root modulo $p$, there's no guarantee that there'll be a root upstairs in characteristic zero, unless your big ring is complete, like $\Bbb Z_p$, and even then you have to check that Hensel applies.
Comment: @Lubin: I'm sorry, I should have been more specific. I meant the following: Modulo $p$, your polynomial $h$ had a root but your polynomial $H$ in your comment did not have. I think it has something to do with $h$ having coefficients divisible by $p$. I was interested in the method on how you derived $H$ from $h$. I feel like this is something which can be generalized.
Comment: Sorry for the misunderstanding, @Rotdat . I guess I'm always looking at any polynomial like that whose roots may all be divisible by $p$. So you transform (make a coordinate transformation) so you get an equivalent polynomial whose roots aren't all divisible by $p$. It's not so different from starting with the polynomial $(x^p-1)/(x-1)$ and shifting the roots over by $1$ to get a polynomial that Eisenstein applies to.


Can I plug my guitar into my keyboard?

Question:
My amp just died and I need something to plug my guitar into.
I have and old CASIO CT-700 tone bank keyboard witch has 4 ports:

MIDI in
MIDI out
phones/output
sustain

Is it possible?
Answer: No, you cannot plug your guitar in this particular keyboard. The Phones jack is a stereo output for headphones, the sustain connector is for a pedal/controller and the midi connectors are for midi control signals to and from an audio interface of some description.
It is possible to connect guitars to some keyboards, as I have utilized this functionality in the past, but they tend to be very expensive keyboards and you're not really meant to do it.
You could however invest in an audio interface and plug your guitar into your PC, then use a guitar effects/amp simulation or modeling program. That or invest in a new amplifier.
Comment: To add to Kyle's idea of plugging it into the computer, I believe you could plug it into the microphone jack of the computer.  So you may already have one built in.  Depending on plug size you might need a 1/4 inch to 3.5 mm adapter.
Comment: If you have an iPhone, or an iPad, or a Mac, there are interfaces that are not so expensive, like the iRig, see http://www.ikmultimedia.com/products/cat-view.php?C=interfaces
Comment: @jcadcell true, but the sound quality will be horrible.
Comment: If you buy an audio interface, you can use a virtual amp and have excellent quality (with effects, distortions and everything) just by plugging your guitar straight to the audio interface. another thing you can do is use a pedalbord and then plug to the computers microphone (red input) or the blue input (if there is such). The quality will be slightly increased from just plugging to your pc
Answer: Fit a Roland GK3 to your guitar and you can play the keyboard tones via your guitar using Midi.
I realise that's not what you want to achieve, but it's cool none the less!

Can I plug my guitar into my keyboard?


Uninitialized constant error with Sidekiq and Rails

Question: I've been getting a whole bunch of uninitialized constant errors lately and I can't figure out why.  Below is a specific example.  In this example, I am calling a job from within a job.  But I am getting a similar uninitialized constant error will many of my other jobs.  All jobs are in app/jobs.  Am I missing something?  Sidekiq has been working just fine until recently.
I've purged my Heroku cache and killed all retries in Sidekiq and I'm still getting these issues. There's something really strange here. With another error I'm getting related to a sidekiq job, I'm getting "wrong number of arguments (given 2, expected 1)". I updated the function in question to receive two arguments weeks ago. Is it possible that Sidekiq is somehow stuck on a cached version of the codebase?
Ruby version: ruby 2.5.3p105
Sidekiq version: 6.0.7
app/jobs/process_email_notifications_job.rb
class ProcessEmailNotificationsJob < ApplicationJob
  queue_as :default

  def perform
    user_ids = UserNotification.where(is_read: false).pluck(:user_id).uniq
    user_ids.each do |user_id|
      ProcessIndividualEmailNotificationsJob.perform_later user_id
    end
  end
end

app/jobs/process_individual_email_notifications_job.rb
class ProcessIndividualEmailNotificationsJob < ApplicationJob
queue_as :default
  def perform(user_id)
     ...
  end
end

Error message:
2020-05-06T20:07:45.720Z pid=56028 tid=owp0sdcm8 DEBUG: enqueued retry: {"retry":true,"queue":"production_default","class":"ActiveJob::QueueAdapters::SidekiqAdapter::JobWrapper","wrapped":"ProcessIndividualEmailNotificationsJob","args":[{"job_class":"ProcessIndividualEmailNotificationsJob","job_id":"4b31bc4f-d034-4190-b24f-d0464cf81df0","provider_job_id":null,"queue_name":"production_default","priority":null,"arguments":[988],"executions":0,"locale":"en"}],"jid":"0ecc861f5870a7b9a70f176f","creat
4:07:45 PM sidekiq.1 |  >  ed_at":1588794273.2726498,"enqueued_at":1588795006.4009435,"error_message":"uninitialized constant ProcessIndividualEmailNotificationsJob\nDid you mean?  ProcessEmailNotificationsJob","error_class":"NameError","failed_at":1588794279.9911764,"retry_count":5,"retried_at":1588795006.763224}

Initializer:
require 'sidekiq'
require 'sidekiq/web'

Sidekiq.configure_client do |config|
  config.redis = { :size => 5 }
end

Sidekiq.configure_server do |config|
  config.redis = { :size => 25 }
end

Sidekiq::Web.set :sessions, false

sidekiq.yml
:concurrency: 18

development:
  :verbose: true
  :queues:
    - [development_priority, 2]
    - development_default
    - development_mailers

staging:
  :queues:
    - [staging_priority, 2]
    - staging_default
    - staging_mailers

production:
  :queues:
    - [production_priority, 2]
    - production_default
    - production_mailers

Answer: OK. I seem to have resolved the issue by adding a namespace to sidekiq on redis per what was suggested here: https://github.com/mperham/sidekiq/issues/2834


how can I define strings in resource file and use them in qml

Question: I want to define a number of xml formatted strings in resource file and use the strings in qml code. Is it possible? How to do it? I would be really appreciated any example.
Answer: As I know there is no way to store strings in resource file. But you still do that in another way.
First way: create language file with qt translation tool. As bonus you can store string in several languages.
Using in QML is very easy:
<code>Text {
    text: qsTr("myTextId");
}
</code>
See that link for more info.
Second way: store each string in different resource file.
But in this case you need to extend QML with C++ plugin to get ability to read files.
See that link for more info.


Why should I make annotations when creating a dataset for YOLO and SSD models

Question: I am currently preparing my dataset in order to train a SSD model on it.
I was wondering if I have to make annotations on each of my images for each of my classes,
or if I could crop my images to isolate each of my class and put them in the class folder they belong to.
With the first method I would get something like
dataset
    |
    |_annotations
    |   |
    |   |_001.xml
    |   |_002.xml
    |   |_...
    |
    |_images
        |
        |_001.jpg
        |_002.jpg
        |_...

With the second method:
dataset
    |
    |_class1
    |   |
    |   |_crop01.jpg
    |   |_crop02.jpg
    |   |_...
    |
    |_class2
        |
        |_crop01.jpg
        |_crop02.jpg
        |_...

Would there be a difference in the training process by using one or the other method?
I have noticed that for classification models, the second method is used while for detectors (such as YOLO or SSD) the first one is used?
Is it just a kind of habit or a have to, or both can be used for both classification and detection?
What would be the influence of training a detection model using the cropping method?
Thanks in advance for your help
Answer: The SSD model gets fed the whole image along with the bounding boxes of the objects. That is something you can't recreate using the second approach (which is, as you said, used for classification). The detection model learns to output the bounding box offset along with the class, so it requires the original image along with the annotations.


SWT: Convert keycode to string

Question: I'm writing a text widget in Java SWT that displays a user-defined keyboard shortcut, such as CTRL + A. Is there some way to map SWT's internal stateMask-keyCode pairs to a string, or do I have to do this by hand?
Answer: See org.eclipse.jface.bindings.keys.KeySequenceText and org.eclipse.jface.bindings.keys.KeySequence for a similar usage.
Answer: org.eclipse.jface.bindings.keys.SWTKeyLookup would help for simple string [Upper Case] to SWT keycode mapping

SWT: Convert keycode to string


What will these do (map[x][y]=2; , map[x][y]=3; , and map[x][y]=4; in the lines below?

Question: I'm studying this C++ code of A star algorithm and the full code as shown below and under the full code the part that contains what I need to know in my question:
The full code of the A star Algorithm in C++ language:
// Astar.cpp
// http://en.wikipedia.org/wiki/A*
// Compiler: Dev-C++ 220.127.116.11
// FB - 201012256
#include <iostream>
#include <iomanip>
#include <queue>
#include <string>
#include <math.h>
#include <ctime>
using namespace std;

const int n=60; // horizontal size of the map
const int m=60; // vertical size size of the map
static int map[n][m];
static int closed_nodes_map[n][m]; // map of closed (tried-out) nodes
static int open_nodes_map[n][m]; // map of open (not-yet-tried) nodes
static int dir_map[n][m]; // map of directions
const int dir=8; // number of possible directions to go at any position
// if dir==4
//static int dx[dir]={1, 0, -1, 0};
//static int dy[dir]={0, 1, 0, -1};
// if dir==8
static int dx[dir]={1, 1, 0, -1, -1, -1, 0, 1};
static int dy[dir]={0, 1, 1, 1, 0, -1, -1, -1};

class node
{
    // current position
    int xPos;
    int yPos;
    // total distance already travelled to reach the node
    int level;
    // priority=level+remaining distance estimate
    int priority;  // smaller: higher priority

    public:
        node(int xp, int yp, int d, int p)
            {xPos=xp; yPos=yp; level=d; priority=p;}

        int getxPos() const {return xPos;}
        int getyPos() const {return yPos;}
        int getLevel() const {return level;}
        int getPriority() const {return priority;}

        void updatePriority(const int & xDest, const int & yDest)
        {
             priority=level+estimate(xDest, yDest)*10; //A*
        }

        // give better priority to going strait instead of diagonally
        void nextLevel(const int & i) // i: direction
        {
             level+=(dir==8?(i%2==0?10:14):10);
        }

        // Estimation function for the remaining distance to the goal.
        const int & estimate(const int & xDest, const int & yDest) const
        {
            static int xd, yd, d;
            xd=xDest-xPos;
            yd=yDest-yPos;

            // Euclidian Distance
            d=static_cast<int>(sqrt(xd*xd+yd*yd));

            // Manhattan distance
            //d=abs(xd)+abs(yd);

            // Chebyshev distance
            //d=max(abs(xd), abs(yd));

            return(d);
        }
};

// Determine priority (in the priority queue)
bool operator<(const node & a, const node & b)
{
  return a.getPriority() > b.getPriority();
}

// A-star algorithm.
// The route returned is a string of direction digits.
string pathFind( const int & xStart, const int & yStart,
                 const int & xFinish, const int & yFinish )
{
    static priority_queue<node> pq[2]; // list of open (not-yet-tried) nodes
    static int pqi; // pq index
    static node* n0;
    static node* m0;
    static int i, j, x, y, xdx, ydy;
    static char c;
    pqi=0;

    // reset the node maps
    for(y=0;y<m;y++)
    {
        for(x=0;x<n;x++)
        {
            closed_nodes_map[x][y]=0;
            open_nodes_map[x][y]=0;
        }
    }

    // create the start node and push into list of open nodes
    n0=new node(xStart, yStart, 0, 0);
    n0->updatePriority(xFinish, yFinish);
    pq[pqi].push(*n0);
    open_nodes_map[x][y]=n0->getPriority(); // mark it on the open nodes map

    // A* search
    while(!pq[pqi].empty())
    {
        // get the current node w/ the highest priority
        // from the list of open nodes
        n0=new node( pq[pqi].top().getxPos(), pq[pqi].top().getyPos(),
                     pq[pqi].top().getLevel(), pq[pqi].top().getPriority());

        x=n0->getxPos(); y=n0->getyPos();

        pq[pqi].pop(); // remove the node from the open list
        open_nodes_map[x][y]=0;
        // mark it on the closed nodes map
        closed_nodes_map[x][y]=1;

        // quit searching when the goal state is reached
        //if((*n0).estimate(xFinish, yFinish) == 0)
        if(x==xFinish && y==yFinish)
        {
            // generate the path from finish to start
            // by following the directions
            string path="";
            while(!(x==xStart && y==yStart))
            {
                j=dir_map[x][y];
                c='0'+(j+dir/2)%dir;
                path=c+path;
                x+=dx[j];
                y+=dy[j];
            }

            // garbage collection
            delete n0;
            // empty the leftover nodes
            while(!pq[pqi].empty()) pq[pqi].pop();
            return path;
        }

        // generate moves (child nodes) in all possible directions
        for(i=0;i<dir;i++)
        {
            xdx=x+dx[i]; ydy=y+dy[i];

            if(!(xdx<0 || xdx>n-1 || ydy<0 || ydy>m-1 || map[xdx][ydy]==1
                || closed_nodes_map[xdx][ydy]==1))
            {
                // generate a child node
                m0=new node( xdx, ydy, n0->getLevel(),
                             n0->getPriority());
                m0->nextLevel(i);
                m0->updatePriority(xFinish, yFinish);

                // if it is not in the open list then add into that
                if(open_nodes_map[xdx][ydy]==0)
                {
                    open_nodes_map[xdx][ydy]=m0->getPriority();
                    pq[pqi].push(*m0);
                    // mark its parent node direction
                    dir_map[xdx][ydy]=(i+dir/2)%dir;
                }
                else if(open_nodes_map[xdx][ydy]>m0->getPriority())
                {
                    // update the priority info
                    open_nodes_map[xdx][ydy]=m0->getPriority();
                    // update the parent direction info
                    dir_map[xdx][ydy]=(i+dir/2)%dir;

                    // replace the node
                    // by emptying one pq to the other one
                    // except the node to be replaced will be ignored
                    // and the new node will be pushed in instead
                    while(!(pq[pqi].top().getxPos()==xdx &&
                           pq[pqi].top().getyPos()==ydy))
                    {
                        pq[1-pqi].push(pq[pqi].top());
                        pq[pqi].pop();
                    }
                    pq[pqi].pop(); // remove the wanted node

                    // empty the larger size pq to the smaller one
                    if(pq[pqi].size()>pq[1-pqi].size()) pqi=1-pqi;
                    while(!pq[pqi].empty())
                    {
                        pq[1-pqi].push(pq[pqi].top());
                        pq[pqi].pop();
                    }
                    pqi=1-pqi;
                    pq[pqi].push(*m0); // add the better node instead
                }
                else delete m0; // garbage collection
            }
        }
        delete n0; // garbage collection
    }
    return ""; // no route found
}

int main()
{
    srand(time(NULL));

    // create empty map
    for(int y=0;y<m;y++)
    {
        for(int x=0;x<n;x++) map[x][y]=0;
    }

    // fillout the map matrix with a '+' pattern
    for(int x=n/8;x<n*7/8;x++)
    {
        map[x][m/2]=1;
    }
    for(int y=m/8;y<m*7/8;y++)
    {
        map[n/2][y]=1;
    }

    // randomly select start and finish locations
    int xA, yA, xB, yB;
    switch(rand()%8)
    {
        case 0: xA=0;yA=0;xB=n-1;yB=m-1; break;
        case 1: xA=0;yA=m-1;xB=n-1;yB=0; break;
        case 2: xA=n/2-1;yA=m/2-1;xB=n/2+1;yB=m/2+1; break;
        case 3: xA=n/2-1;yA=m/2+1;xB=n/2+1;yB=m/2-1; break;
        case 4: xA=n/2-1;yA=0;xB=n/2+1;yB=m-1; break;
        case 5: xA=n/2+1;yA=m-1;xB=n/2-1;yB=0; break;
        case 6: xA=0;yA=m/2-1;xB=n-1;yB=m/2+1; break;
        case 7: xA=n-1;yA=m/2+1;xB=0;yB=m/2-1; break;
    }

    cout<<"Map Size (X,Y): "<<n<<","<<m<<endl;
    cout<<"Start: "<<xA<<","<<yA<<endl;
    cout<<"Finish: "<<xB<<","<<yB<<endl;
    // get the route
    clock_t start = clock();
    string route=pathFind(xA, yA, xB, yB);
    if(route=="") cout<<"An empty route generated!"<<endl;
    clock_t end = clock();
    double time_elapsed = double(end - start);
    cout<<"Time to calculate the route (ms): "<<time_elapsed<<endl;
    cout<<"Route:"<<endl;
    cout<<route<<endl<<endl;

    // follow the route on the map and display it
    if(route.length()>0)
    {
        int j; char c;
        int x=xA;
        int y=yA;
        map[x][y]=2;
        for(int i=0;i<route.length();i++)
        {
            c =route.at(i);
            j=atoi(&c);
            x=x+dx[j];
            y=y+dy[j];
            map[x][y]=3;
        }
        map[x][y]=4;

        // display the map with the route
        for(int y=0;y<m;y++)
        {
            for(int x=0;x<n;x++)
                if(map[x][y]==0)
                    cout<<".";
                else if(map[x][y]==1)
                    cout<<"O"; //obstacle
                else if(map[x][y]==2)
                    cout<<"S"; //start
                else if(map[x][y]==3)
                    cout<<"R"; //route
                else if(map[x][y]==4)
                    cout<<"F"; //finish
            cout<<endl;
        }
    }
    getchar(); // wait for a (Enter) keypress
    return(0);
}

The part that I want to understand, I hope if I can get some explannation of these lines below:
if(route.length()>0)
    {
        int j; char c;
        int x=xA;
        int y=yA;
        map[x][y]=2;
        for(int i=0;i<route.length();i++)
        {
            c =route.at(i);
            j=atoi(&c);
            x=x+dx[j];
            y=y+dy[j];
            map[x][y]=3;
        }
        map[x][y]=4;

Comment: `map[x][y]=?`, `?` is just a state recorded. 2 is start, 3 is route, 4 is end, you can replace it with any number if you can retrieve its meaning.
Comment: @pwxcooThank u so much sir
Answer: if(route.length()>0) /* If we have a route*/
    {
        int j; char c; /* Declarations for variables used*/
        int x=xA; /* xA is our starting x location */
        int y=yA; /* yA is our starting y location */
        map[x][y]=2; /* Mark in the map our starting location with a 2 */

        for(int i=0;i<route.length();i++) /* For every step in our route */
        {
            c =route.at(i); /* Get the next character */
            j=atoi(&c); /* atoi(&c) converts c into an int */

            x=x+dx[j]; /* move x in the x_direction specified by j */
            y=y+dy[j]; /* move y in the y_direction specified by j */
            map[x][y]=3; /* Mark our new location with a 3 */
        }
        map[x][y]=4; /* Mark our location finish with a 4 */

The confusing part here is what dx, and dy are and how j updates our direction.
static int dx[dir]={1, 1, 0, -1, -1, -1, 0, 1};
static int dy[dir]={0, 1, 1, 1, 0, -1, -1, -1};
/*              j = 0, 1, 2, 3, 4,  5,  6,  7  */

From this we can see that if:
j == 0, add 1 to x and 0 to y.
j == 1, add 1 to x and 1 to y.
ect...
After this is done, Map will contain our path specified by route. The start of the path is where the 2 is, the finish is where 4 is and the 3's show the route from start to finish.
EDIT
Do the x and y will start with (0,0) as initial point?
No, They are set to xA and yA which a set to random numbers in main().
Thank you so much dear sir, for your reply. But I didn't get 2,3,and 4 yet for map[x][y]. What is the benefit of them?
The only purpose I can see is to print out the map. At the end of main, the map is iterated over and depending on the value something is printed. So it should print a map showing the path computed based on 2,3 and 4.
Comment: Thank you so much dear sir, for your reply. But I didn't get 2,3,and 4 yet for map[x][y]. What is the benefit of them?.