Does the square function respect the strong operator topology on self-adjoint operators?

Question: A real-valued continuous function $f:\mathbb{R}\to\mathbb{R}$ is referred to as "strongly continuous", if for every Hilbert space $\mathcal H$ and every pointwise convergent net $a_\lambda\to a$ of self-adjoint operators in $\mathcal B(\mathcal H)$, one has $f(a_\lambda)\to f(a)$ pointwise. In other words, applying functional calculus with this function on self-adjoints is continuous in the strong operator topology.
Most of the time this concept pops up only briefly before the proof of Kaplansky's density theorem, in tandem with the fact that any function with at most linear growth (as $t\to\pm\infty$) is strongly continuous. (In the newest edition of Pedersen's book "C*-algebras and their automorphism groups", this is Proposition 2.3.2.)
My question: Is the square function $f(t)=t^2$ strongly continuous?
I am currently in the last stretches of teaching a course on operator algebras, and was recently not able to rigorously answer this question by one of my students. I strongly suspect that the answer is no, but I struggle to come up with a specific counterexample. I have looked through the usual textbooks, but did not see an answer there, either. Can anybody help me come up with a rigorous answer or possibly point me to a reference where this has been done?
Answer: No, it's not.
Here is (one of?) the canonical example(s). Note that an example cannot be bounded, since multiplication is jointly sot-continuous on bounded sets.
Fix an orthonormal basis $\{e_n\}$ of $H$. Consider the set $\{\sqrt n\,e_n\}$. If $0\not\in\overline{\{\sqrt n\,e_n\}}^w$, then there exists an open neighbourhood
$$
W=\{x:\ |f_j(x)|<\delta,\ j=1,\ldots,N\}
$$
such that $W\cap\overline{\{\sqrt n\,e_n\}}^w=\varnothing$. Via the Riesz Representation Theorem this means that there exist $y_1,\ldots,y_N\in H$ and indices $j_n\in\{1,\ldots,N\}$ with
$$
\delta\leq |\langle \sqrt n\,e_n,y_{j_n}\rangle|,\qquad n\in\mathbb N.
$$
Then
$$
\sum_{j=1}^N\|y_j\|^2=\sum_{j=1}^N\sum_{n=1}^\infty|\langle \sqrt n\,e_n,y_{j}\rangle|^2=\sum_{n=1}^\infty\sum_{j=1}^N|\langle \sqrt n\,e_n,y_{j}\rangle|^2\geq\sum_{n=1}^\infty\frac{\delta^2}{n}=\infty,
$$
a contradiction.
So $0\in\overline{\{\sqrt n\,e_n\}}^w$. This means that there exists a net $\{n_j\}$ of integers such that $\sqrt{n_j}\,e_{n_j}\to0$ weakly.
Define operators $T_j\in B(H)$ by
$$
T_jx=\sqrt{n_j}\,\langle x,e_{n_j}\rangle\,e_{n_j}.
$$
Then
$$
\|T_jx\|=|\sqrt{n_j}\,\langle x,e_{n_j}\rangle|\to0,
$$
so $T_j\to0$ sot. Meanwhile, we have $T_j^2x=n_j\,\langle x,e_{n_j}\rangle\,e_{n_j}$. Let $\{n_k\}_{k\in\mathbb N}$ be a set of distinct integers such that, as sets, $\{n_k\}_{k\in\mathbb N}=\{n_j\}_j$. Put $x=\sum_k\tfrac1{n_k}\,e_{n_k}\in H$. Then
$$
\|T_j^2x\|=1
$$
for all $j$, showing that $T_j^2$ does not converge sot to $0$.
Comment: You are absolutely right, it's another more subtle argument that one needs. I'll edit a bit later.
Comment: Please see the edit.
Comment: Just commenting to add a reference from the literature: the fact that $0$ belongs to the sot closure of the rank-1 operators $T_n := \sqrt{n} e_n \otimes \overline{e_n}$ appears in Example C.10 on page 277 of *Morita Equivalence and Continuous-Trace $C^\ast$-Algebras* by Raeburn and Williams.
Comment: @MikeF: thanks. For completeness, I'll just mention that this is way older than Raeburn-Williams. [Jonas Mayer](https://math.stackexchange.com/a/42497/22857) mentions that it appears in Halmos' *Hilbert Space Problem Book*.
Comment: Thank you for your reply! This might be a case of me not seeing the forest from all the trees, but what version of Hahn-Banach are you using here? Naively I would think that you can only conclude that 0 is contained in the closed convex hull of $\sqrt{n}e_n$, which is naturally not enough. What am I missing?
Comment: It seems to me that the series defining $x$ is not garanteed to be convergent. Am I missing something?
Comment: If you put $\ell^2$ coefficients in front of an orthonormal set you get an element of the Hilbert space. What problem do you see?
Comment: Thanks, I had forgotten about the $\ell^2$ and was thinking that $\sum 1/n$ being divergent was a problem.
Comment: I am confused as to why this example does not violate the uniform boundedness principle. If $T_j \to 0$ sot, then we can conclude $\sup_j \lVert T_j\rVert < \infty$. But this does not hold for your example.
Comment: No, you cannot conclude that a convergent net is bounded. For each $x$, the net $\{T_jx\}$ converges to $0$ but it is not necessarily bounded.


How to replace "Enter quantity" text for Production variation?

Question: I'm working on Drupal commerce kickstart.
On Product variation, I need to change the text Enter quantity to Enter your quantities and change Add to Cart to Buy Now.
I tried with form alter it works to change Add to Cart to Buy Now but its not working for Enter quantity to Enter your quantities.
Can any one help on this?
Answer: I too had the same problem. Because this text is hardcoded and there is no configuration for updating the text.
Ways to change the text

Use String Overrides module.
Do a form_alter and change the text from Add to Cart to Buy Now

Form Alter for Enter quantity
<code>function module_name_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'commerce_cart_add_to_cart_form') {
    $form['quantity']['#title'] = t('Enter your Quantities');
  }
}
</code>
Hope this code helps.
Answer: This string is being set by a form_alter in the commerce_kickstart_product_ui.module.
You can use the module string_overrides: https://drupal.org/project/stringoverrides to change the string, or
You can use your own form alter code in a custom module but you may have to use the weight module https://drupal.org/project/modules_weight so that your module executes it's code after te commerce module.


Display all records of an id on separate rows for each id php

Question: i have this table resulted from some inner joins
id_outfit   | name | article
----------------------------------------
   56        | one  | shoe.png
   56        | one  | dress.png
   56        | one  | bag.png
   54        | two  | shoe1.png
   54        | two  | dress2.png

Column 'article' contains images.
I try to display in my app all the articles from an id_outfit on a single row, but I don't know how to do that.
For example I try to display all articles that have id 56 on a row ,all articles that have id 54 on the next row and so on .
I tried to do this with GROUP BY but for each id it  displays only the first image(article) .
Any suggestion is very helpful for me, thank you !
Comment: Please include the code you are using to display the table.
Comment: Please don't just repost the same question under a different userid.
Comment: Show your best attempt please. In theory if you order the query by ID, then it should be a simple case of looping the results, checking on each row whether the ID is the same as on the previous row (for that you need a variable to hold the previous row's ID) and if the IDs are different then start a new row (if not, then don't) - this logic is not complex.
Comment: What do you mean by "display in my app"?
Comment: @David  SELECT outfit_articles.id_outfit, outfits.name, outfit_articles.article FROM outfits INNER JOIN outfit_articles ON outfits.id_outfit = outfit_articles.id_outfit
Answer: Here is a way do it using the PDO syntax:
<?php
try{
    $db = new PDO("mysql:host=localhost;dbname=yourdb", $user, $pass);
}
catch (Exception $e){
    //Handle your connection errors
}

//Request the things you need
$req = $db->query("SELECT id_outfit, article FROM your_table ORDER BY id_outfit DESC");

$tempId = null;

//start to loop through your data
while ($data = $req->fetch()){

  //if the outfit id is different than the last time we went through the loop:
  if($data["id_outfit"] !== $tempId){
    //close the previous row unless this is the first time through the loop
    echo $tempId === null ? "" : "
";
    //start a new row
    echo "
";
  }

  //now we display the image
  echo "";
  //store the id we had for the next loop to check
  $tempId = $data["id_outfit"];
}

//close the last row
echo "
";

?>

This will output a div of class "row" for each different ID in your DB, contain all the images corresponding to that ID.
Then you can style those div using css to display it as a row, most likely using a flexbox:
.row{
  display: flex;
}

(you will need more css than that to make it actually pretty obviously.)


Suppressing another module's warnings

Question: Is it possible to suppress another module's warnings? My module calls another causing a warning to appear.
Comment: prepend @ with the function name that is generating the warning, howover, I would not suppress the warning, instead I will try to cure them.
Comment: Welcome to Drupal Answers! Are you talking about PHP warnings?
Answer: You could use the Disable Messages module for this. Here is a quote from its project page:

Gives a site owner options to disable specific messages shown to end users. The core drupal message system as offered by drupal_set_message is an excellent way for modules to send out messages to the end users. However not all drupal site owners are keen to show all the messages sent out by drupal core and all modules to their users. This module gives site administrators a reasonably powerful way to filter out messages shown to the end users.

Some of its features are:

Filter out messages that match a full text string exactly.
Filter out messages that match a regular expression.
Permissions to specifically hide all messages of a given type from any role.
Disable all filtering for specific users.
Disable all filtering for specific paths.
Apply filtering only for specific paths.
Debug system to get messages in the HTML without showing it to the end users.

Available for either Drupal 6 or Drupal 7 (and a DEV version for Drupal 8).
Comment: If the OP is talking about PHP warnings, this module doesn't do anything.

Suppressing another module's warnings


Martingale and submartingale

Question: When $X_n$ is a martingale we know $(X_n)^+$, i.e. the positive part of $X_n$, is also a submartingale.
Is this true? It is easy to show that this is SUB-m.g. but I couldn't find a counter-example for martingale?
Thank you!
Answer: It is most certainly false.
The function $x \longmapsto x^+$ is convex so if $X_n$ is a martingale then $X_ n^+$ is a submartingale, and will not be a martingale unless $X_n \geq 0$ a.s. for all $n$ or $X_n \leq 0$ a.s. for all $n$.
Here we have used the conditional version of Jensen's inequality to show that for a convex function $\phi$
$$
E_n[\phi(X_{n+1})] \geq \phi(E_n[X_{n+1}]) = \phi(X_n)
$$
almost surely (this is the submartingale property for the new process $\{\phi(X_n)\}_n$.
For an explicit example consider a symmetric random walk with $X_0 = 0$. Clearly $E[X_n^+]>0$ as $X_n^+$ is not a.s. zero, so the process $\{X_n^+\}_n$ cannot be a martingale as this would imply $E[X_n^+]=0$ for all $n$ (martingales have constant expectation).
Comment: can you make it more explicit say you got 2 turns then E[X_2^+|X_1] > X_1^+ How to show this in this symmetric random walk? Thank you!
Comment: When we say $X_n$ is a martingale, implicitly we keep in the back of our minds that we mean $(X_n,\mathcal{F}_n)$ is a martingale on the filtered probability space $(\Omega,\mathcal{F},\{\mathcal{F}_n\}_n,P)$. I am using $E_n[\cdot]$ as shorthand for $E[\cdot | \mathcal{F}_n]$, **not** $E[\cdot | X_n]$.
Comment: Showing $\{X_n\}_n$ is a submartingale is literally just plugging in $(x \longmapsto x^+)$ for $\phi$ in the inequality above.

Martingale and submartingale


In R, why are residuals of lm() and summary(lm()) different when using weights for the regression?

Question: I am using a decay weighting scheme for time series regression in financial markets (idea is that more recent data is more relevant). However lm() residuals are different from summary(lm()) residuals. Is there a reason for this?
rr <- rnorm(500) * 50
xx <- 1:500
yy <- xx + rr
dd <- decay(500, 150)
sd(rr)
[1] 50.31787
sd(lm(yy ~ xx)$residuals)
    [1] 50.29099
    sd(summary(lm(yy ~ xx))$residuals)
[1] 50.29099
sd(lm(yy ~ xx, weights = dd)$residuals)
    [1] 50.29154
    sd(summary(lm(yy ~ xx, weights = dd))$residuals)
[1] 2.278805
dd2 <- c(rep(1, 250), rep(2, 250))
sd(lm(yy ~ xx, weights = dd2)$residuals)
    [1] 50.29102
    sd(summary(lm(yy ~ xx, weights = dd2))$residuals)
[1] 62.66624

here is my decay function, by the way:
decay <- function(len, halflife, sumone = TRUE) {
#function generates an exponentially decaying series
    t <- len:1 # generate a series of numbers reverse order so biggest weights last
    lambda <- log(2) / halflife #figure out the lambda for the halflife
    w <- exp(-lambda * t) #create the weights series
    if(sumone) w <- w / sum(w) #normalise sum to 1 if necessary
    return(w)
}

Answer: The help page for summary.lm explains that summary.lm returns "the weighted residuals, the usual residuals rescaled by the square root of the weights specified in the call to lm." So to reproduce the result, type
sd(summary(lm(yy ~ xx, weights = dd))$residuals/sqrt(dd))

This should yield the same result as
sd(lm(yy ~ xx, weights = dd)$residuals)


How to create custom Error messages for method parameters in Hibernate Validator

Question: I'm using hibernate-validator 5.3.0.
The following is my function with @NotNull constraint, where I'm making validation on method parameters.
public void test(@NotNull String firstName, @NotNull String lastName) {

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    ....
}

After reading this question I found that it's possible to put custom error message in ValidationMessages.properties file with this following format:
[ConstraintName].[ClassName].[FieldName]=[Message]

for example
NotNull.TestClass.name=My Custom Message

But this works when you're trying to validate some class fields.
So is it possible to use this or some other format and create custom error messages for method arguments?
Thanks in advance.
Answer: Have you looked at message annotation parameter ?
You can provide your own custom messages if you want using it for example like this:
public void test(@NotNull(message = "My custom message for first name") String firstName, @NotNull String lastName) {

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    ....
}

or if you need to reuse the same message a lot of times you can add it to ValidationMessages.properties as you said in your question and later in the code do something like this:
public void test(@NotNull(message = "{my.custom.message.key}") String firstName, @NotNull String lastName) {

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    ....
}

And in your ValidationMessages.properties you will have:
my.custom.message.key=My custom message goes here

You can find all you need in here - spec


How to update a storageClassName in a statefulset?

Question: I am new to k8's and trying to update storageClassName in a StatefulSet.(from default to default-t1 only change in the yaml)
I tried running kubectl apply -f test.yaml
The only difference between 1st and 2nd Yaml(one using to apply update) is storageClassName: default-t1 instead of default
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: web
spec:
  serviceName: "nginx"
  podManagementPolicy: "Parallel"
  replicas: 2
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: k8s.gcr.io/nginx-slim:0.8
        ports:
        - containerPort: 80
          name: web
        volumeMounts:
        - name: www
          mountPath: /usr/share/nginx/html
  volumeClaimTemplates:
  - metadata:
      name: www
    spec:
      accessModes: [ "ReadWriteOnce" ]
      storageClassName: default
      resources:
        requests:
          storage: 1Gi

Every-time I try to update it I get The StatefulSet "web" is invalid: spec: Forbidden: updates to statefulset spec for fields other than 'replicas', 'template', and 'updateStrategy' are forbidden
What am I missing or what steps should I take to do this?
Answer: There's no easy way as far as I know but it's possible.

Save your current StatefulSet configuration to yaml file:

kubectl get statefulset some-statefulset -o yaml > statefulset.yaml

Change storageClassName in volumeClaimTemplate section of StatefulSet configuration saved in yaml file
Delete StatefulSet without removing pods using:

kubectl delete statefulset some-statefulset --cascade=orphan

Recreate StatefulSet with changed StorageClass:

kubectl apply -f statefulset.yaml

For each Pod in StatefulSet, first delete its PVC (it will get stuck in terminating state until you delete the pod) and then delete the Pod itself

After deleting each Pod, StatefulSet will recreate a Pod (and since there is no PVC) also a new PVC for that Pod using changed StorageClass defined in StatefulSet.
Answer: apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: web
spec:
  serviceName: "nginx"
  podManagementPolicy: "Parallel"
  replicas: 2
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: k8s.gcr.io/nginx-slim:0.8
        ports:
        - containerPort: 80
          name: web
        volumeMounts:
        - name: www
          mountPath: /usr/share/nginx/html
  volumeClaimTemplates:
  - metadata:
      name: www
    spec:
      accessModes: [ "ReadWriteOnce" ]
      storageClassName: <storage class name>
      resources:
        requests:
          storage: 1Gi

in the above file add storage class and you can apply it like.
kubectl apply -f .yaml
Comment: my yaml is exactly like the one you added above. when I use it to update 'replicas' .. 'template' or 'updateStrategy' it works fine but i still get the same error when updating storageClassName... I just needed to know if this is possible or not at this point. As from the error message looks like it isnt .
see command and console output.
```kubectl apply -f test.yaml
service/nginx unchanged
statefulset.apps/web configured```
Comment: it worked there was no changes in service so service unchanged and change in deployment so it configured as per new argument.
Answer: First line of StatefulSet shoud define an "apiVersion", you can see example here statefulset. Please add it in first line:
apiVersion: apps/v1

Could you show me output of your 'www' PVC file?
kubectl get pvc www -o yaml

In PVC you have field "storageClassName", which should be set on your StorageClass you want to use, so in your case it would be:
storageClassName: default-t1


Jenkins Pipelines quiet period on downstream builds

Question: Background
I have 3 builds in Jenkins all using a Jenkinsfile:

client
ws
service

The client is an NPM/NodeJS build which Docker image running HTTPD with a front end client "installed" and the ws is a back end Java web service (again in a Docker container). Both are Multiflow pipelines that are triggered by SCM commits.
The service build will be a build that creates a service template that allows the Docker images to be deployed together.
The problem I have is not with the builds themselves but with thier relationship with one another
Developers will commit and the multibranch pipelines will happily build away in the background, however when a merge is made to master (and the corresponding build is successful) the ws or client builds should start a service pipeline.
The Problem
The service pipeline should wait for a set period of time (5 mins?) before building. This will allow developers to merge to master across both applications and give the CI a chance to build both applications before attempting to build the service.
The reason for this is that there are stories that will involve updating both the ws and client that require both for the story to be tested properly (and pass!). Having the service pipeline wait will allow a developer to merge one master at a time without the build trying to build "prematurely" and gives Jenkins a chance for both builds to complete.
To add complexity, the version of the ws and client should be passed to the service build.
What I've Tried
Currently the service build is a parametrized build that prompts for the version numbers of the ws and client. When the client or ws builds it triggers the service with a quietPeriod:
    build job: 'service', parameters: [
    string(name: 'client', value: '1.0.0')],
    quietPeriod: 60

(where 1.0.0 will be replaced with the Jenkins build number)
However this implementation causes the client/ws jobs to wait for 60 seconds before triggering the service build. What I want is for the service build to wait for 60 seconds before starting the build.
Comment: Is "_this implementation causes the `client`/`ws` jobs to wait for 60 seconds before triggering the `service` build._" really correct? According to the inline help of _Quiet period_: "_queued builds wait for the specified seconds before the actual build starts_" (or the like. I translated it from German text). So the sequence described there is: _U triggers_ → _D waits_ → _D builds_, not _U waits_ → _U triggers_ → _D builds_. Is this really different with [Pipelines](https://jenkins.io/doc/pipeline/steps/pipeline-build-step/)?
Comment: Having played about with it a bit more this morning, what actually happens is the `ws`/`client` builds actually keep hold of an executor for the 60 seconds defined in the listening period while the `service` is listening.
Comment: It's different here: U runs and waits, D is "_(pending—In the quiet period. Expires in xx sec)_". No executor is used during this quiet/pending period. Maybe dependent on what is done before building D in U.
Comment: Did you ever find a solution for this?
Answer: I believe the confusion is that you wanted the ws and client builds to trigger the service build but not wait for the service build to begin executing.  To do this you can just add:
wait: false

To you build step.  From the docs here: https://jenkins.io/doc/pipeline/steps/pipeline-build-step/


How not render a region on specific page programmatically on Drupal 8

Question: I put a custom block (develop for me) on sidebar first region for every page, every fine, but I want that this block not render on the home page.
On my module, I made this:
funtion mymodule_preprocess_page(&$variables) {
  if ($variables['is_front']) {
    unset($variables['page']['sidebar_first']);
  }
}

The sidebar not show, but the block already was rendered (I debug this code and the build function of my block was called before of mymodule_preprocess_page function). Then how I programmatically avoid that this block not render.
Answer: Got to /admin/structure/block on your domain. Click the configure button beside your block. In the lower part of the configuration form you have a section called visibility. One of the tabs in this section is labelled pages. This is where you configure where the block is permitted or forbidden to be rendered. In your case one would write <front> and choose the radio button labelled "Hide for the listed pages".
Answer: Maybe hook_block_view_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) ?
Comment: To make this answer useful, you should explain why you believe this hook will solve the OPs problem.


Prove the polynomial $P_a=X^5 + a$ is reducible over a field

Question:
Let $(K, +, \cdot)$ a finite field so that the polynomial $P=X^2-5$ is
irreducible.
Prove that:
a) $1+1 \ne 0$
b) The polynomial $P_a=X^5 + a$ is reducible $\forall a \in K$

a) This is the easy part.
Suppose $1+1=0$. Then $5=1$ therefore $P=(X-1)(X+1)$ contradiction.
b) I think the idea is to show the equation $x^5 + a=0$ has solutions $\forall a \in K$, but I failed to prove it.
Any hint for an elementary solution is appreciated.
Comment: @user148212 Over $F_{11}$ the polynomial $P=X^2-5$ is reducible
Comment: Your idea for part b) does not work: x^5=2 has no solution in F_11.
Comment: For the second part, do you mean to find all such fields where this holds?
Comment: @MattB No, to prove it for all fields.
Answer: If $a=0$,we're done. So, suppose $a\in F^\times$.
Let $p=$char$ F$. Then, $F=\Bbb{F}_{p^k}$. If $k$ is even, then, $\Bbb{F}_{p^2}\subseteq F$. However, $X^2-5$ splits over $\Bbb{F}_{p^2}$, as splitting field of a degree two polynomial is of degree two, and $\Bbb{F}_{p^2}$ is the only degree two extension of $\Bbb{F}_p$. Contradiction.
So, $k$ is odd. $x^2-5$ has no solution means $5$ is not a quadratic residue $\Bbb{F}_p$. Then, by the quadratic reciprocity law, $p$ is not a quadratic residue in $\Bbb{F}_5$. In particular $5\not\lvert p\pm 1$, so, $5\not\lvert p^k-1$. Choose a generator $g\in F^\times$. Let $-a=g^{m}$. As $5\not\lvert p^k-1$, $5$ divides one of $m,m+(p^k-1),m+2(p^k-1),m+3(p^k-1),m+4(p^k-1)$. Then, $g^\frac{m+b(p^k-1)}5$ is a root of $x^5+a$, as desired.
Comment: $\mathbb{F}_{p^2} \subset \mathbb{F}_{p^k}$ if and only if $k$ is even.
Comment: Once you show that $5\nmid p^k-1$, you're done, because by group theory $b\mapsto b^5$ is an automorphism of $F^\times$.
Comment: You're right. Forcing $k$ to be odd is enough for the solution also. Edited accordingly.
Comment: Thank you, but I need an elementary solution.
Comment: @egreg Yes, there are multiple ways of finishing the argument after that. What about getting $5\not\lvert p-1$ from a more direct way, as OP requested.
Comment: @Emre Doesn't seem to lead to solution, I deleted it


Will practicing on an Ipad hurt my playing?

Question: I have encountered many music instrument apps such as piano, guitar or even some wind instruments mapped onto the touch screen of the iPad. They can be fun to play, but would playing on the iPad and learning to adapt to the touch screen hurt my playing when I go back to the actual instrument?
Comment: Anecdotal evidence; I learned to play guitar (40 years ago) without a guitar. I drew a fretboard on some cardboard to practice the fingering... I'm past that now, I think..
Comment: You would be better off not doing anything at all
Answer: I doubt it will harm your playing, nor improve it either. They're totally different things.
It's a bit like wondering if playing Grand Theft Auto is going to affect how you drive.
Comment: Perhaps not the best example- GTA definitely affects how I drive!
Answer: I would add also that if you replace practicing on a real instrument with tablet practice for an extended period of time, yes, you will notice a decline in your technical ability at the actual instrument.
There's a limited amount of potential gain from practicing on a virtual instrument as opposed to the real. You could learn to sight read notes, guitar fingerings, etc., but there are some crucial elements of playing any instrument that can only be learned by practicing on the real thing.
So, short answer: use the tablet to (if anything) supplement, not replace.
Answer: If you feel that you may confuse the two, and imagine you're playing a touch screen when it's a real piano/sax/trumpet/whatever, then yes, it will affect your playing. If you can be sure the two aren't actually any more than similar, you'll be fine.


How to reconstruct array from string representation of array?

Question: I've got a huge CSV that was generated by a Python script. Some cells include arrays of data, while others include single-item arrays. Some examples:
cell01 == ['"July, 2002"', 'CUREE Publication No. CEA-01.', 'Project No. 3126', 'Prepared for Consortium of Universities for Research in Earthquake Engineering.']
cell02 == ['[Memorandum from Ralph J. Johnson on Andy Place].']
cell03 == ["Financial statements for the years ended March 31, 1991 and 1990 and independent auditors' report"]

Ideally, I'd like to parse all this data into structures that look like the following:
cell01_parsed[0] == '"July, 2002"'
cell01_parsed[1] == 'CUREE Publication No. CEA-01.'
cell01_parsed[2] == 'Project No. 3126'
cell01_parsed[3] == 'Prepared for Consortium of Universities for Research in Earthquake Engineering.'

cell02_parsed == '[Memorandum from Ralph J. Johnson on Andy Place].'

cell03_parsed == 'Financial statements for the years ended March 31, 1991 and 1990 and independent auditors\' report'

However, when I use a csv.reader() or csv.DictReader(), these lines are parsed as strings, not arrays. What would be an easy way to do this? I can't use split(',') since some of the strings have commas in the middle of items.
Comment: [`shlex.split()`](https://docs.python.org/3.5/library/shlex.html#shlex.split) will preserve quoted characters...
Comment: I'm not sure what your issue is. I just used `csv.writer()` to write out the data from the first code section and read it back using `csv.reader()`. The result was exactly like you expected it to be. I think there is something you haven't explained getting in the way. How is the data written?
Comment: I was using `csv.DictWriter()` originally since all of the data had up to 31 columns, but not exactly.
Answer: You could try to split your strings by regex (find out one that fits your data) like so:

import re
test_str = '"July, 2002", CUREE Publication No. CEA-01.'
re.compile(',(?!.+\")').split(test_str)

Comment: I've got a considerable amount of data to process (15k rows, 31 columns), so I fear regex may mess up/misinterpret some data. I think I'll go with `shlex.split()` as @pycoder suggester


Visual Studio 2022, Can I control how the immediate values are generated for arm64 compilation?

Question: When I have the following code:
int value2 = 0x11223344;

The VS2022 compiler (arm64) generates:
StarFunction PROC

...
ldr         w8,|value_label|
...
...
...

ret

|value_label|
    DCD         0x11223344

ENDP

As you can see, the value 0x11223344 is generated as "data" at the end of the function.
Is there any way to have some control on that so it generates instead:
mov  w8, 0x1122
movk w8, 0x3344, lsl 16

I cannot use compiler optimizations as I need to have control over the generated
code to patch specific code sequences. With compiler optimizations, I loose that control.
I have tried different compiler optimization switches but some of them have no effect and
other more aggressive optimizations even remove the declaration of "0x11223344" and directly
use it in code afterwards.
Summing up, can I "force" somehow the compiler to avoid that "data" mixed with code for immediate values in arm64?
Comment: Have you tried writing it out, something like:  `int a = 0x1122;  a = (a << 16) + 0x3344;`?
Comment: Thanks @ErikEidt, but it generates more code than expected:  ```mov  w8,#0x1122;  str w8,[sp,#8]; ldr  w8,[sp,#8];  lsl  w9,w8,#0x10; mov  w8,#0x3344; add  w8,w9,w8; str w8,[sp,#8] ```
Comment: If you use global variables to store intermediate values then you force the compiler to generate code for lines even with optimizations on. Try assigning 0x11223344 to a global variable and compile with -O2.
Answer: I found that declaring the local variables with "volatile" such as:
void MyFunction()
{
   volatile int i = 0x1123344;

   // some code here
}

And also compiling with /Ox, makes the compiler generate the wanted mov Wn, imm16_low; movk Wn, imm16_high, lsl 16 at the expected location where it was declared.
Here is a full example (compiled with /Ox)
int TestFunction()
{
    volatile int a = 0x11223344;
    volatile int b = 0x77887788;
    return 0;
}

Generates:
|int TestFunction(void)| PROC
|$LN6|
        sub         sp,sp,#0x10
        mov         w8,#0x3344
        movk        w8,#0x1122,lsl #0x10
        str         w8,[sp]
        mov         w8,#0x7788
        movk        w8,#0x7788,lsl #0x10
        str         w8,[sp]
        mov         w0,#0
        add         sp,sp,#0x10
        ret

        ENDP  ; |int TestFunction(void)|, TestFunction

Comment: With optimization enabled, it uses `mov`/`movk` to put 32-bit constants into registers in general, including for `return x + 0x1123344;` .  (https://godbolt.org/z/K1jM4bo9M ).  But with optimization disabled, it loads from memory (PC-relative from nearby data it looks like), even if it's going to assign the result to a `volatile`.  So it seems `volatile` is irrelevant to how it materializes constants, only optimization level.
Comment: Of course, if you let it optimize, it might constant-propagate the constant into a different value for the asm, so maybe `volatile int modifiable_a = 0x11223344;` / `int a = modifiable_a;` so you aren't forcing the inefficiency of `volatile` on every later use in the function.  (Seems like it might be easier and more efficient to just have a global variable, or maybe volatile static, for external modification with a symbol attached to the value.  Then it would just be one adrp/ldr.)


How to create a params dict from **kwargs in an if chain in Python?

Question: I'm working on an API wrapper for a weather API. Here are two snippets of my code, which don't quite work:
def payload_helper(self, *args, **kwargs):
    if args:
        paylouad = args
    else:
        payload = {
            "units": "metric",
        }
    payload.update(kwargs)
    return payload

def weather(self, lat="", lon="", zip_code=""):
    payload = self.payload_helper()
    if lat:
        payload = self.payload_helper(payload, lat=lat)
    elif lon:
        payload = self.payload_helper(payload, lon=lon)
    elif zip_code:
        payload = self.payload_helper(payload, zip_code=zip_code)

The goal of payload helper is to create a dict that adds a set to:

if no payload is passed: a new payload dict
if a payload is passed: update the payload and return the new (merged) one

I know I could solve this if I would just make weather(self, *args, **kwargs) but I don't want that. I always find it nice if the user that uses the API wrapper also has intelli sense (see what variables the method expects), which is not possible with **kwargs. I don't have to do this with the if elif else chain. This was just my approach. There is probably a mew python way of doing this.
Comment: You probably don't want to chain those `if..elif..elif`, but just have a bunch of separate `if`s?
Comment: what is your question?
Comment: You're looking to add all the named arguments from the method to a dictionary, correct?
Comment: How I can create the payload dict in the if chain. Because right now, my payload dict is always only len = 1. Which I don't understand. Even if I pass both lat and lon.
Comment: @Grismar Yes, that explains it even better. But these arguments can be empty.
Comment: I voted to reopen - I think the question is clear (and an obvious solution could be presented with `locals()`). It's not at all due to a typo or anything of the sort and the question should not have been closed for such a reason.
Answer: Your main goal seems to be that you want to create a dictionary that contains all the keyword arguments that were included in the call to your original function.
A very straightforward way to achieve what you want:
def func(a="", b="", c=""):
    payload = locals()
    # do something else
    print(payload)

func(a=1, b='2', c=3.)

Result:
{'a': 1, 'b': '2', 'c': 3.0}

But note that your idea to define the keyword parameters as empty strings means they are implicitly strings. This will lead to a decent IDE giving you all warnings about the types of the arguments being passed.
A better way would be to specify their type, but set them to be None initially. Optional helps to allow the None value in spite of their type:
from typing import Optional

def func(a: Optional[int] = None, b: Optional[str] = None, c: Optional[float] = None):
    payload = {name: value for name, value in locals().items() if value is not None}
    # do something else
    print(payload)

func(b='2', c=3.)  # no warnings

Result:
{'b': '2', 'c': 3.0}

Note that the solution above does have the (perhaps unwanted) side effect of including any positional arguments as well. For example:
def func(a: int, b: Optional[int] = None):
    payload = locals()
    # do something else
    print(payload)

func(1, 2)

Result:
{'a': 1, 'b': 2}

It's relevant, because your functions appear to be methods, so they will at least have the positional parameter self, which would need to be removed:
from typing import Optional

class MyClass:
    def func(self, x: Optional[int] = None):
        payload = {k: v for k, v in locals().items() if v is not None and k != 'self'}
        # do something else
        print(payload)

mc = MyClass()
mc.func()
mc.func(1)

Result:
{}
{'x': 1}

Also note that, if you need your keyword arguments to actually be able to have the value None assigned, the above still need some extra work, and you might look into __defaults__.
On a more general note: have you looked at dataclasses at all? Because it seems that what you're ultimately after might be better achieved using those.
Answer: The only thing the helper should do is filter out None-valued arguments to weather. The "base" payload should be created in weather itself, then updated using the return value of the helper.
def weather(self, lat=None, lon=None, zip_code=None):
    def helper(**kwargs):
        return {k: v for k, v in kwargs.items() if v is not None}

    payload = {'units': 'metric'}
    payload.update(helper(lat=lat, lon=lon, zip_code=zip_code))

    ...


is there a graphical interpretation for the integral of a single parameter vector-valued function

Question: On single variable calculus integrals have a nice graphical interpretation as the area under the curve of a function $f(x)=y$ who's graph is built with 2 axis where the $x$ axis is the domain and the $y$ axis is the image of the function.
I would like to know if, Given some single parameter vector valued function, for example $f(t)=<x(t),y(t),z(t)>$, is there any graphical interpretation (or intuition) for $\int f(t)\,dt$?
Note: My question is limited to functions with domains in $\mathbb{R}^1$ but NOT limited to functions with images in $\mathbb{R}^3$
Comment: You should know that what you've written down is not what you've encountered. $\int f(t)\,dt$ (you left out the $dt$) is the integral of a vector function, so it just integrates each component individually. But that is *not* what usual line (path) integrals are at all.
Comment: Yeah, then that's all you can say. If you talk about the line integral $\int_C f\,ds$ of a function over a curve $C$, integrating with respect to arclength, then you can generalize the interpretation you have in mind. Make a fence with height $f(x)$ over the point $x$ of the curve $C$ (going into one more dimension with the fence). The integral then gives you the area of that fence (if you unroll it into a plane, for example).
Comment: Thanks for the intent on foresight, I dont think I have encountered line integrals yet.  When I wrote $\int f(t)\,dt$ I did mean the integral of a vector function of a single parameter, which is indeed as far as i know just the integral of each component individually. I just added the $\,dt$, sorry im not used to write it down when I only have a single variable.
Comment: Interestng. Im just getting bits and pices of what you say . My calculus course kind of goes from derivatives and integrals of functions $f:\mathbb{R}^1 \to \mathbb{R}^n$ (and it does not talk about line integrals, it does talk about getting arclength using integrals tho),then it just seems to go to derivatives and integrals on functions $f:\mathbb{R}^n \to \mathbb{R}^1$ (partial derivatives and the like). I will look line integrals up to see what's the deal with that.
Comment: It may or may not be of interest or helpful, but you might want to check out my YouTube videos. There's perhaps more applications — and definitely more rigor and proofs — than in many multivariable courses; but it's all integrated with the linear algebra needed to make sense of the concepts carefully.
Comment: This playlist? I see line integrals are introduced very late, I'm about 30% in my course so that may have something to do with it. https://www.youtube.com/watch?v=8hX0QePiWlw&list=PL5I-Eyk8l9FHdJUd9UujGcvumjCFPHbrd
Answer: You can think of $\textbf{a}(t) = (a_{1}(t),a_{2}(t),a_{3}(t))$ as the acceleration of a moving particle within $\textbf{R}^{3}$. Consequently, its integral between the instants $t_{1}$ and $t_{2}$ gives the difference between its inicial and final velocities, respectively.
Similarly, you can think of $\textbf{v}(t) = (v_{1}(t),v_{2}(t),v_{3}(t))$ as the velocity of a moving particle within $\textbf{R}^{3}$. Consequently, its integral between the instants $t_{1}$ and $t_{2}$ gives the difference between its inicial and final position, respectively.
Another interesting example comes from physics as well. Let us consider the resultant force acting upon a particle is expressible as a function $\textbf{F}:\textbf{R}^{3}\rightarrow\textbf{R}^{3}$, where $\textbf{s}:\textbf{R}\rightarrow\textbf{R}^{3}$ is the function which expresses its position over time. Then the work corresponding to the time interval $t_{1}$ and $t_{2}$ is given by
\begin{align*}
W = \int_{t_{1}}^{t_{2}}\langle\textbf{F}(\textbf{s}(t)),\textbf{s}'(t)\rangle\mathrm{d}t
\end{align*}
Comment: Thanks for the answer. Im familiar with this, but it's not a relationship that has a geometric meaning in the graphs (at least I understand it as the relationship between the integral and the antiderivative).
Comment: @JoaquinBrandan I don't have an answer for you, but I can say that graphical interpretation is not necessarily the best thing to look for. The reason is because as soon the input and output spaces dimensions add up to more than $3$, a graph is not the natural setting for objects such as functions. Functions and their graphs are distinct objects and it is helpful to begin to think of them as such when progressing to more math.
Comment: Thanks. With time I have come to realize that the more angles, perspectives and intuitions I can merge into a single math concept the better I understand it and I can use it with more flexibility to solve problems.That's why I asked the question. Maybe the answer at the end is that the graphical interpretation has no relevance at all, and that's usefull to know in itself.


Polynomial regression as equation for a paper

Question: I need to write the following model in equation form for a paper:

Is the following equation describing the model correctly?

Edit:
I forgot to mention that this is a machine learning model. The purpose of the equation is simply to state it in the methodology in a paper not to calculate anything.
Here is the code used:
<code>df.shuffled <- fullsample5[sample(nrow(fullsample5)),]

#define number of folds to use for k-fold cross-validation
K <- 100

#define degree of polynomials to fit
degree <- 5

#create k equal-sized folds
folds <- cut(seq(1,nrow(df.shuffled)),breaks=K,labels=FALSE)

#create object to hold MSE's of models
mse = matrix(data=NA,nrow=K,ncol=degree)

#Perform K-fold cross validation
for(i in 1:K){

  #define training and testing data
  testIndexes <- which(folds==i,arr.ind=TRUE)
  testData <- df.shuffled[testIndexes, ]
  trainData <- df.shuffled[-testIndexes, ]

  #use k-fold cv to evaluate models
  for (j in 1:degree){
    fit.train = lm(ROI ~ poly(Freq,j), data=trainData)
    fit.test = predict(fit.train, newdata=testData)
    mse[i,j] = mean((fit.test-testData$Freq)^2)
  }
}
</code>
Comment: Why not just perform that calculation on your data and confirm it agrees with the values returned by the `predict` function?  Even when you are absolutely sure of the answer, such a check confirms the software is doing what you think it should do.
Comment: I hope you would want to check anything you put into a publication.
Comment: this is not for checking purposes, cf. edit
Answer: Because you used raw and not orthogonal polynomials, the fitted model could be written as follows (with four significant digits):
$$
\widehat{ROI}_i=-39.15-0.5117\times Freq_i + 0.004323\times Freq^{2}_{i}
$$


Usando o Identity com Entity Framework para fazer relacionameto one-to-many com outras tabelas

Question: No meu cenário um usuário tem várias embarcação e uma embarcação tem vários apontamentos. Então eu preciso relacionar o usuário com a embarcação para que esse usuário possa ver esses apontamentos.
Estou o usando o template default do identity do projeto MVC 5.
Portanto, preciso relacionar a tabela AspNetUser com a tabela Barco.
Alguém ja precisou fazer isso para que possa me ajudar?
   public class Barco : Entity
   {

    public string Nome { get; private set; }

    public bool Ativo { get; private set; }

    public bool Excluido { get; private set; }

    public int SapId { get; private set; }

    public int CapacidadeAgua { get; private set; }

    public int CapacidadeOleo { get; private set; }

    public int Velocidade { get; private set; }

    public decimal AreaReal { get; private set; }

    public decimal AreaProgramada { get; private set; }

    public decimal AreaLivre { get; private set; }

    public string Email { get; private set; }

    public string Setor { get; private set; }

    public DateTime DataCadastro { get; private set; }

    public Guid? ClasseBarcoId { get; set; }

    public virtual ClasseBarco ClasseBarco { get; set; }

    public Barco(
        String nome,
        bool ativo,
        bool excluido,
        int sapid,
        int capacidadeAgua,
        int capacidadeOleo,
        int velocidade,
        string email,
        string setor,

        DateTime dataCadastro)
    {
        Nome = nome;
        Ativo = ativo;
        Excluido = excluido;
        SapId = sapid;
        CapacidadeAgua = capacidadeAgua;
        CapacidadeOleo = capacidadeOleo;
        Velocidade = velocidade;
        Email = email;
        Setor = setor;
        DataCadastro = dataCadastro;

        ClasseBarco = new ClasseBarco();
    }
   }

Answer: Procure pelo seu IdentityModel.cs
em geral fica dentro de Models/IdentityMode.cs
Dentro de sua classe public class ApplicationUser : IdentityUser
Crie uma nova propriedade do tipo
public virtual Barco Barco {get; set;}

Agora na class Barco
crie uma propriedade ApplicationUser
public virtual ApplicationUser ApplicationUser {get; set}

Agora em seu  mapeamento do Application user
faça o seguinte
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<ApplicationUser>()
    .HasOptional(s => s.Barco)
    .WithRequired(ad => ad.ApplicationUser);

    //isso tem  que vir por ultimo
    base.OnModelCreating(modelBuilder);
}

Não tive como testar mas  creio  que isso deva resolver.
para mais informações consulte configuring one to one relationship in asp.net identity


Como mudar o estilo de um grupo de vertices em JGRAPHX?

Question: Estou trabalhando em um projeto UML e utilizando o JGRAPHX, ou mxGraph como preferirem.
No caso, quando eu tenho um grupo de vértices, é adicionado uma linha pontilhada para marcar que aquele vértice é um grupo.
Como posso mudar o estilo dele como as figuras abaixo?
Quando não é um grupo de vértices:

Quando for um grupo de vértices:
Answer: Solução:
<code>mxIGraphModel model = graph.getModel();
// start to change model
model.beginUpdate();
mxGeometry geo = new mxGeometry(0, 0.5, PORT_DIAMETER,
                        PORT_DIAMETER);
// Because the origin is at upper left corner, need to translate to
                // position the center of port correctly
                geo.setOffset(new mxPoint(-PORT_RADIUS, -PORT_RADIUS));
                geo.setRelative(true);

 mxCell port = new mxCell(cell.getAttribute("label"), geo,
                        style);
port.setVertex(true);
//is not a port!!!!!!!!
port.setConnectable(false);
graph.addCell(port, cell);
//send to back!
graph.cellsOrdered(new Object[]{cell}, true);
// end changes, generate the events and     update UndoManager
                model.endUpdate();
</code>
Att,
Alexandre.


How can I pass a UILabel as a URL in Swift?

Question: I have a UILabel called itemOneURL which reads a URL from an external database and adds the value to this label as a string. I've got a separate button called viewItemOne (using a working segue) which once selected, will take the contents of the itemOneURL URL and open this link using the default browser. Here is the code I am currently using.
@IBOutlet weak var itemOneURL: UILabel!

@IBAction func viewItemOne(_ sender: UIButton) {

    let firstURL = itemOneURL as? String

    UIApplication.shared.open(URL(string:"\(firstURL)")! as URL, options: [:], completionHandler: nil)

}

However, once I select this button on the UI my application doesn't do anything, whereas when I use the following syntax elsewhere, it works and loads the URL?
UIApplication.shared.open(URL(string:"https://stackoverflow.com")! as URL, options: [:], completionHandler: nil)

Is there something I am doing wrong which is currently causing the button to not perform any action once selected?
Comment: You want itemOneUrl.text
Comment: itemOneUrl is a label, not a String. The as? String won't work.
Answer: "How can I pass a UILabel as a URL in Swift?"
Short answer: Don't. Don't use view objects to store information.
Give your viewController a property itemOneURL.
Rename your label itemOneURLLabel. (Use the refactor>rename menu item and Xcode will rename every occurrence, including any outlet links in your storyboard(s) or XIB files.)
Add a didSet method to your itemOneURL variable:
var itemOneURL: String {
   didSet {
      itemOneURLLabel.text = itemOneURL
   }
}

Then, if you need the string URL value, it's in a String variable like it should be. Problem solved.


document.getElementsByClassName mostrar antes

Question: Queria que mostrasse quantas classes "twitter-tweet" tem no html na parte de cima, e não na parte de baixo.
se eu coloco na parte de cima aparece "0 videos" e se eu coloco na parte de baixo aparece a quantidade certa.

<title>Passinho</title>
<link rel="stylesheet" type="text/css" href="/style.css">

Passinho:  videos

   <-- aqui fica 0 videos

ESSE VÍDEO É VICIANTE  pic.twitter.com/blLqQhWes6
— PASSINHOS E DANCINHAS (@ilovepassinhorj) December 14, 2019

 pic.twitter.com/orvqANs3VQ
— Bia Das Dancinhas (@Ofcquebradeira) December 17, 2019

Já que pedirammm ♂
Tivemos que quebrar @eilaryssamoraes pic.twitter.com/Sp3dipMm0o
— Lc Quebradeira (@lucasalveslc1) December 3, 2019

Passinho:  videos

 <-- aqui mostra a quantidade certa de videos
queria fazer isso só que na parte lá de cima no primeiro

Answer: É porque os elementos não existem ou não foram renderizados antes do primeiro script, ou seja eles só existem depois do primeiro script, logo ou você usa o evento load para checa quando a página carregou:
window.addEventListener('load', function () {
    var len = document.getElementsByClassName("twitter-tweet").length;
    console.log(len);
});

Ou prefira o evento DOMContentLoeaded (é um evento do objeto document) que não irá precisar que tudo carregue (como imagens e outros scripts), apenas o HTML:
document.addEventListener('DOMContentLoaded', function () {
    var len = document.getElementsByClassName("twitter-tweet").length;
    console.log(len);
});


Componente é impresso 2 vezes no browser

Question: Bom galera, estou desenvolvendo um app com angular2 versão final utilizando rotas.
Criei alguns arquivos e então me deparei com um problema de rotas.
Meu component Home é impresso 2 vezes no browser.

No Console do Firebug:

Segue código:
login.ts
// app/login/login.ts

import { Component } from '@angular/core';

@Component({
  selector: 'login',
  templateUrl: 'app/login/login.html',
  styleUrls: ['app/login/login.css']
})

export class Login { }

home.html

Angular Router

<router-outlet></router-outlet>

home.ts
// app/home/home.ts

import { Component } from '@angular/core';

@Component({
  selector: 'home',
  templateUrl: 'app/home/home.html',
  styleUrls: ['app/home/home.css']
})

export class Home { }

app.routing.ts
// app/app.routing.ts

import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { Login } from './login/login';
import { Home } from './home/home';

const appRoutes: Routes = [
    {
        path: '',
        component: Home,
        pathMatch: 'full'
    },
    {
        path: 'logar',
        component: Login
    }
];

export const appRoutingProviders: any[] = [

];

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

app.module.ts
//app/app.module.ts

import { NgModule }                      from '@angular/core';
import { BrowserModule }                 from '@angular/platform-browser';
import { routing, appRoutingProviders }  from './app.routing';
import { Login }                         from './login/login';
import { Home }                          from './home/home';
@NgModule({
  imports: [
    BrowserModule,
    routing
  ],
  declarations: [
    Home,
    Login
  ],
  providers: [
    //appRoutingProviders
  ],
  bootstrap: [ Home ]
})
export class AppModule {
}

main.ts
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
platformBrowserDynamic().bootstrapModule(AppModule);

Answer: Consegui resolver o problema.
Removi do home.html a tag router-outlet e criei um appComponent para iniciar a aplicação.
Com isso resolveu o problema.


How to strengthen $ h \big( 2 h ( x ) \big) = h ( x ) + x $ to force $ h $ to be linear?

Question:
Let $ h : \mathbb R \to \mathbb R $ be an injective function such that
$$
h \big( 2 h ( x ) \big) = h ( x ) + x
$$
for all $ x \in \mathbb R $, and $ h ( 0 ) = 0 $. What would be an as mild as possible extra condition such that the only solution of the equation $ h ( x ) = - \frac x 2 $ is $ x = 0 $?

Note that the function $ x \mapsto - \frac x 2 $ satisfies the conditions, so somehow we need to fully exclude this function.
For example, both the extra condition $ h ( x ) \le x \ \forall x $ as well as the extra condition $ h ( x ) \ge x \ \forall x $ force $ h ( x ) = x \ \forall x $, and thus $ 0 $ is the only solution to the equation in question. But what about other conditions as e.g. monotone or surjective?
Comment: As an example of why such conditions are needed: $f(x)=x$ solves Babbage's functional equation $f(f(x))=x$, but so do $f(x)=1-x$, $f(x)=1/x, -x$, and so forth. (See the Wikipedia page on [functional square roots](https://en.wikipedia.org/wiki/Functional_square_root) for some additional details on this case.)
Comment: To be honest I don't understand the premises you have and what your goal is. Do you assume h is linear or want a condition that forces h to be linear? Or do you want to enforce h(x) = 0 ?
Comment: Not sure if this is  the correct answer, but if you want h to be 0 everywhere and assume the equation $h(2h(x)) = h(x)+x$ as well as h(0) = 0, I  think it is not possible:
$$
h(1) = 0 \\ \Rightarrow 0 = h(0) = h(2 h(1)) = h(1) + 1 \neq 0
$$
Comment: If you want h to be linear and assume the equation as well as h(0) = 0 then i think you need to assume continuity or smoothness of some kind, otherwise you could define h as something like identity on the rational numbers and 0 everywhere else.
Answer: I focus more on the question as was originally posted (and still stands to be so in the title), that what would be a rather mild condition sufficient to force $ h $ to be linear. Also, defining $ g : \mathbb R \to \mathbb R $ with $ g ( x ) = 2 h ( x ) $, the functional equation becomes
$$ g \big( g ( x ) \big) = g ( x ) + 2 x \text , \tag 0 \label 0 $$
and we can see that $ g $ is continuous/increasing/decreasing/injective/surjective/linear/… iff $ h $ is so. Thus, I only talk about $ g $ and conditions on it (because it is more convenient), as they can be easily translated to conditions on $ h $.
First, note that \eqref{0} implies injectivity of $ g $, since if $ g ( x ) = g ( y ) $ for some $ x , y \in \mathbb R $, then
$$ x = \frac { g \big( g ( x ) \big) - g ( x ) } 2 = \frac { g \big( g ( y ) \big) - g ( y ) } 2 = y \text . $$
Next, observe that $ g ( 0 ) = 0 $ is consequence of \eqref{0}. To see this, put $ x = 0 $ in \eqref{0} to get $ g \big( g ( 0 ) \big) = g ( 0 ) $, and use injectivity. So, both conditions were redundant in the original question.
For any nonnegative integer $ n $, denote the $ n $-th iteration of $ g $ by $ g ^ n $; i.e. $ g ^ 0 $ is the identity function on $ \mathbb R $ and for any nonnegative integer $ n $, $ g ^ { n + 1 } = g ^ n \circ g $.

Lemma 1. For any $ x \in \mathbb R $ and any nonnegative integer $ n $, we have $ g ^ n ( x ) = a _ n g ( x ) + b _ n x $, where $ a _ n = \frac { 2 ^ n + ( - 1 ) ^ { n + 1 } } 3 $ and $ b _ n = \frac { 2 ^ n + 2 ( - 1 ) ^ n } 3 $.

This can be proved by mathematical induction. The base case $ n = 0 $ is easy to verify. Assuming
$$ g ^ n ( x ) = a _ n g ( x ) + b _ n x \tag 1 \label 1 $$
for all $ x \in \mathbb R $, we can substitute $ g ( x ) $ for $ x $ in \eqref{1} and use \eqref{0} to get $ g ^ { n + 1 } ( x ) = ( a _ n + b _ n ) g ( x ) + 2 a _ n x $. It's straightforward to verify that $ a _ { n + 1 } = a _ n + b _ n $ and $ b _ { n + 1 } = 2 a _ n $.

Lemma 2. If $ g $ is decreasing, then $ g ( x ) = - x $ for all $ x \in \mathbb R $.

If $ g $ is decreasing, then we must have
$$ ( y - x ) \big( g ( y ) - g ( x ) \big) \le 0 \tag 2 \label 2 $$
for all $ x , y \in \mathbb R $. Letting $ y = g ^ n ( x ) $ in \eqref{2} for any positive integer $ n $, we get
$$ \big( a _ n g ( x ) + ( b _ n - 1 ) x \big) \big( ( a _ { n + 1 } - 1 ) g ( x ) + b _ { n + 1 } x \big) \le 0 $$
by Lemma 1. This can be written as
$$ \left( g ( x ) + \frac { b _ n - 1 } { a _ n } x \right) \left( g ( x ) + \frac { b _ { n + 1 } } { a _ { n + 1 } - 1 } x \right) \le 0 \text , $$
which by taking the limit as $ n $ tends to infinity, gives $ \big( g ( x ) + x \big) ^ 2 \le 0 $, and the result follows.

Lemma 3. If $ g $ is increasing and surjective, then $ g ( x ) = 2 x $ for all $ x \in \mathbb R $.

As $ g ( 0 ) = 0 $ and $ g $ is increasing, we will have $ g ( x ) < 0 $ for negative $ x $, and $ g ( x ) > 0 $ for positive $ x $. Therefore, we can define the function $ c : \mathbb R \setminus \{ 0 \} \to \mathbb R ^ + $ with $ c ( x ) = \frac { g ( x ) } x $. For any $ x \in \mathbb R \setminus \{ 0 \} $, \eqref{0} gives
$$ \frac { g \big( g ( x ) \big) } { g ( x ) } \cdot \frac { g ( x ) } x = \frac { g ( x ) } x + 2 \text , $$
which can be rewritten as
$$ c \big( g ( x ) \big) = f \big( c ( x ) \big) \text , \tag 3 \label 3 $$
where $ f : \mathbb R ^ + \to \mathbb R ^ + $ is defined with $ f ( y ) = 1 + \frac 2 y $. Note that $ f ( y ) > 1 $ for all $ y \in \mathbb R ^ + $, and thus by \eqref{3} and surjectivity of $ g $, we get $ c ( x ) > 1 $ for all $ x \in \mathbb R \setminus \{ 0 \} $. Again, since $ y > 1 $ implies $ f ( y ) < 3 $, by a similar argument, we get $ c ( x ) < 3 $ for all $ x \in \mathbb R \setminus \{ 0 \} $. Generally, we can use mathematical induction to prove that for any nonnegative integer $ n $ and any $ x \in \mathbb R \setminus \{ 0 \} $,
$$ c ( x ) > f ^ { 2 n } ( 1 ) = 2 - \frac 3 { 2 ^ { 2 n + 1 } + 1 } \quad \text {and} \quad c ( x ) < f ^ { 2 n + 1 } ( 1 ) = 2 + \frac 3 { 2 ^ { 2 n + 2 } - 1 } \text . $$
As $ \left( f ^ { 2 n } ( 1 ) \right) _ { n = 0 } ^ \infty $ is an increasing sequence convergent to $ 2 $, we have $ c ( x ) \ge 2 $ for all $ x \in \mathbb R \setminus \{ 0 \} $. Similarly, since $ \left( f ^ { 2 n + 1 } ( 1 ) \right) _ { n = 0 } ^ \infty $ is a decreasing sequence convergent to $ 2 $, we have $ c ( x ) \le 2 $ for all $ x \in \mathbb R \setminus \{ 0 \} $. The result follows.

Lemma 4. If $ g $ is continuous, then it is monotonous and surjective.

Define $ d : \left\{ ( x , y ) \in \mathbb R ^ 2 \big| x < y \right\} \to \mathbb R $ with $ d ( x , y ) = g ( y ) - g ( x ) $. Because $ g $ is continuous, $ d $ is a composition of continuous functions, and thus continuous itself. Since the domain of $ d $ is connected, its range must be an interval (possibly unbounded). As $ g $ is injective, $ d $ never takes the value zero. This means that the value of $ d $ is either always negative or always positive, which means that $ g $ is either decreasing or increasing; i.e. monotonous.
In case $ g $ is decreasing, it is surjective by Lemma 2. In case $ g $ is increasing, $ g ( x ) $ has the same sign as $ x $, for all $ x \in \mathbb R $. This, by \eqref{0}, proves that $ \big| g \big( g ( x ) \big) \big| > | g ( x ) | $ for all $ x \in \mathbb R \setminus \{ 0 \} $. Since $ g $ is continuous, $ g ^ 2 $ is continuous, too, and thus its range is an interval (possibly unbounded). By the previous result, this interval contains the range of $ g $. Conversely, the range of $ g ^ 2 $ is contained in the range of $ g $ (as is true for any function on $ \mathbb R $), which means that the ranges of $ g $ and $ g ^ 2 $ are the same. Hence, because $ \require {color} { \color { red } g } $ is injective and $ g ^ 2 = { \color { red } g } \circ { \color { blue } g } $, therefore $ { \color { blue } g } $ must be surjective.

Theorem. Assume that a function $ g : \mathbb R \to \mathbb R $ satisfies \eqref{0} for all $ x \in \mathbb R $. Then, the following are equivalent.

Either $ g ( x ) = - x $ for all $ x \in \mathbb R $, or $ g ( x ) = 2 x $ for all $ x \in \mathbb R $.
$ g $ is linear.
$ g $ is monotonous.
$ g $ is continuous.

So, having any of these additional conditions, you would only need to rule out $ x \mapsto - x $, which can be done for example by any of these:

$ g $ is not decreasing.
There is some $ x \in \mathbb R $ with $ g ( x ) \ne - x $.
$ g ( 1 ) \ne - 1 $.
$ g \left( - \sqrt 2 \right) < g ( \pi ) $.
…

Whether being monotonous or continuous is considered to be a mild condition is a matter of taste. But I can't see any milder conditions that guarantee $ g $ to be linear. It seems that there are uncountably many functions $ g : \mathbb R \to \mathbb R $ satisfying \eqref{0}. This comes from noting that choosing a point $ x _ 0 $ and a value for $ f ( x _ 0 ) $, \eqref{0} seems to force the value of $ f ( x ) $ only for countably many $ x $. Choosing $ x _ 1 $ to be a point other than those, it seems that we're able to choose the value of $ f ( x _ 1 ) $ almost freely. This comes from the observation that the previous step seems to exclude at most countably many values. It seems that using axiom of choice and transfinite recursion, we can continue this process, and get uncountably many different solutions. A condition that rules out this many wild solutions and keeps only two tame ones, should be a harsh one; shouldn't it? It seems that continuity is mild enough in this context.
Answer: It works if $h$ is an increasing bijection.
First define $g=2h$. If $h$ is an increasing bijection, so is $g$.
Notice that $$g(g(x))=(g(x)+x)+x.$$
If $y$ is such that $g(y)+y=0$, which is equivalent to $h(y)=-\frac{y}{2}$, then  $g(g(y))=y$.
Since $g$ is surjective, there is $z$ such that $y=g(z)$. So $g(g(y))=g(z)$.
Since $g$ is injective, $g(y)=z$.
Now $g(y)=z$, $y=g(z)$ and the fact that $g$ is increasing imply that $y=z$.
Hence, $g(y)=y$.
Since $g(g(y))=g(y)+2y$, $g(y)=y$ and $g(g(y))=y$, we obtain $y=0$.
Comment: Why do "$ g ( y ) = z $, $ g ( z ) = y $ and the fact that $ g $ is monotone imply that $ y = z $"? Note that we have $ g ( y ) + y = 0 $, and thus $ z = - y $. So, if $ y \ne 0 $ then one of $ y $ and $ z $ is negative, and the other one is positive. This leaves open the possibility of $ g $ being decreasing.
Comment: @MohsenShahriari You are completely right. The argument only works with increasing bijections. Note that $h(x)=-\frac{x}{2}$ is a decreasing bijection and satisfies the required equation as pointed by the OP.


Correlation coefficient for three variables in r

Question: For three n-dimensional non-zero-variance variables a, b, and c, n > 2, if
r(ab), r(bc), and r(ac) are Pearson's correlation coefficients between a and b, between b and c, and between a and c, respectively, then correlation coefficient r(abc) among a, b, and c is defined as:
r^2(abc) = ( r^2(ab) + r^2(bc) + r^2(ac) ) - ( 2 x r(ab) x r(bc) x r(ac) )
I was able to get the code for a manual way of doing it:
a <- c(4, 6, 2, 7)
b <- c(8, 1, 3, 5)
c <- c(6, 3, 1, 9)

al <- data.frame(a, b, c)
al

ab_cor <- cor(al$a, al$b, method = c("pearson"))
bc_cor <- cor(al$b, al$c, method = c("pearson"))
ac_cor <- cor(al$a, al$c, method = c("pearson"))

abc_cor <- sqrt( ( (ab_cor)^2 + (bc_cor)^2 + (ac_cor)^2 ) - ( 2 * ab_cor * bc_cor * ac_cor) )
abc_cor

But I was wondering if this could be done with less lines of code, for example with a for loop. Addittionaly, how would I write it so that I could do it with more than 3 variables as well, for example, r(abcd) i.e. r(ab), r(ac), r(ad), r(bc), r(bd), and r(cd).
Comment: The formula is basically the summation of the square of all the correlation combinations subtracted by 2 times the multiples of all the correlation combinations. I can add an image link if its harder to see when written out in text
Comment: To me it's not clear what you would want the calculation to look like for more than 3 variables. If you provide an example of the more generalized version (or even just for 4 variables) then that would be helpful.
Comment: The equation would look like this: r^2(abcd) = ( r^2(ab) + r^2(ac)  + r^2(ad) + r^2(bc) + r^2(bd)+ r^2(cd) ) - ( 2 x r(ab) x r(ac) x r(ad) x r(bc) x r(bd) x r(cd) )
Comment: Did you mean for there to be more in there?
Comment: But doing this manually would be tedious, especially when we start adding more and more variables. The equation would get exponentially longer, but if there is a way I can do it via a for loop, it should be able to reiterate through all the correlation combination and just dump out the values into a list.
Answer: The cor function already creates a matrix of the correlations.  You just need to pick out the relevant ones and then use some vector operations.
cs <- cor(al, method = "pearson")

cs <- cs[upper.tri(cs)]

#sqrt(sum(cs^2)) - 2*prod(cs)
# apparently it's
sqrt(sum(cs^2) - 2*prod(cs))

This generalizes to your larger case as well assuming that you have all the variables you want in your al data.frame.
Comment: @IceCreamToucan Thanks for catching that


Edittext input validation in android

Question: I have a scenario in which I have a form with four fields. In which one field will take same input only 5 times. On entering in 6th times activity will not go to another activity on button click. Please somebody help me as I have spent so many hours.
Here is my code
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class LoginFragment extends Fragment {

    private EditText phone, emailId, doctorName, doctorUniqueNumber;
    private Button submitButton;

    private String code;

    public LoginFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);

        phone = (EditText) rootView.findViewById(R.id.phoneNumber);
        emailId = (EditText) rootView.findViewById(R.id.emailId);
        doctorName = (EditText) rootView.findViewById(R.id.doctorName);
        doctorUniqueNumber = (EditText) rootView.findViewById(R.id.doctorUniqueNumber);
        submitButton = (Button) rootView.findViewById(R.id.button);
        submitButton.setOnClickListener(click);

        return rootView;
    }

    View.OnClickListener click = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if ((!phone.getText().toString().isEmpty()) && (!doctorName.getText().toString().isEmpty())
                    && (!emailId.getText().toString().isEmpty()) && (!doctorUniqueNumber.getText().toString().isEmpty())){
                AuthenticateDoctor doctor = new AuthenticateDoctor();
                doctor.execute();
            }

        }
    };

    private void setPrefs(String key, int value){
        SharedPreferences preferences = getActivity().getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putInt(key, value);
        editor.apply();
    }

    private int getPrefs(String key, int defaultValue){
        SharedPreferences preferences = getActivity().getPreferences(Context.MODE_PRIVATE);
        return preferences.getInt(key, defaultValue);
    }

    private void setStringPrefs(String key, String value){
        SharedPreferences preferences = getActivity().getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(key, value);
        editor.apply();
    }

    private String getStringPrefs(String key, String defaultValue){
        SharedPreferences preferences = getActivity().getPreferences(Context.MODE_PRIVATE);
        return preferences.getString(key, defaultValue);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    private class AuthenticateDoctor extends AsyncTask<Void, Void, String>{

        private final String LOG_TAG = AuthenticateDoctor.class.getSimpleName();

        @Override
        protected String doInBackground(Void... params) {

            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;

            // Will contain the raw JSON response as a string.
            String data;

            try {
                // Construct the URL for the OpenWeatherMap query
                // Possible parameters are avaiable at OWM's forecast API page, at
                // http://openweathermap.org/API#forecast
                URL url = new URL("http://spirantcommunication.com/andriod/grl/show.php?" + "code=" +
                        doctorUniqueNumber.getText().toString());

                // Create the request to OpenWeatherMap, and open the connection
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();

                // Read the input stream into a String
                InputStream inputStream = urlConnection.getInputStream();
                StringBuffer buffer = new StringBuffer();
                if (inputStream == null) {
                    // Nothing to do.
                    return null;
                }
                reader = new BufferedReader(new InputStreamReader(inputStream));

                String line;
                while ((line = reader.readLine()) != null) {
                    // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
                    // But it does make debugging a *lot* easier if you print out the completed
                    // buffer for debugging.
                    buffer.append(line + "\n");
                }

                if (buffer.length() == 0) {
                    // Stream was empty.  No point in parsing.
                    return null;
                }

                data = buffer.toString();
                Log.v("Data", data);

            } catch (IOException e) {
                Log.e(LOG_TAG, "Error ", e);
                // If the code didn't successfully get the weather data, there's no point in attemping
                // to parse it.
                return null;
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException e) {
                        Log.e(LOG_TAG, "Error closing stream", e);
                    }
                }
            }
            return data;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            try {
                JSONObject object = new JSONObject(result);
                JSONArray array = object.getJSONArray("Message");
                code = array.getString(0);
                Log.v("Code", code);
            }catch (JSONException e){
                e.printStackTrace();
            }
            if (code.equals("success")){
                int numberOfTimes = getPrefs("Number of Times", 0);
                if (numberOfTimes > 5){
                    Toast.makeText(getActivity(), "Exceed value", Toast.LENGTH_SHORT).show();
                    setStringPrefs("Doctor Unique Number", " ");
                }else {
                    numberOfTimes++;
                    setPrefs("Number of Times", numberOfTimes);
                    setStringPrefs("Doctor Unique Number", doctorUniqueNumber.getText().toString());
                    Intent intent = new Intent(getActivity(), DoctorDashboardActivity.class);
                    startActivity(intent);
                }
            }else if (code.equals("Faliure")){
                Toast.makeText(getActivity(), "This unique number is not present", Toast.LENGTH_SHORT).show();
            }
        }
    }

}

Comment: what is error? try to see if numberOfTimes in SHaredPreference changes correctly
Answer: First, you will have an int member in LoginFragment which will store the attempts. Then, in onClick you will check: if(attempts > 5) return; attempts++;
View.OnClickListener click = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
             if(attempts > 5) return;

             attempts++;

            if ((!phone.getText().toString().isEmpty()) && (!doctorName.getText().toString().isEmpty())
                    && (!emailId.getText().toString().isEmpty()) && (!doctorUniqueNumber.getText().toString().isEmpty())){
                attempts = 0;
                AuthenticateDoctor doctor = new AuthenticateDoctor();
                doctor.execute();
            }

        }
    };

Hope it helps

Edittext input validation in android


Double quotient isomorphic to tensor product

Question: Assume the following result

Let $R$ be a ring with $1$, $I$ a right ideal of $R$, and $M$ a left $R$-module. Then $$\frac{R}{I} \otimes_R M \cong \frac{M}{IM}$$as abelian groups, where $IM$ is the submodule of $M$ generated by $\{rx \mid r \in I, x \in M\}$.

Great. I want to  use this result to prove the corollary:

Let $R$ be a ring with $1$, $I$ a right ideal of $R$, $J$ a left ideal of $R$. Then $$\frac{R}{I}\otimes_R\frac{R}{J} \cong \frac{R}{I+J}$$as abelian groups.

Ok, since $J$ is a left ideal of $R$, we have that $R/J$ has a natural left $R$-module structure. The first result then says that $$\frac{R}{I}\otimes_R \frac{R}{J} \cong \frac{R/J}{I(R/J)},$$so it all boils down to checking that $$\frac{R/J}{I(R/J)} \cong \frac{R}{I+J}.$$Since $J \subseteq I+ J$, the identity of $R$ passes to a surjective map $$\frac{R}{J} \to \frac{R}{I+J},$$but I'm screwing up right at the end. How does one check that the kernel of this last map is $I(R/J)$?
Answer: Say $r+J\to 0$ then $r\in I+J$, so we could write that as
$$r=a+b$$ with $a\in I$ and $b\in J$ now we have
$$a+b+J=a+J$$ so $$r+J=a(1+J)$$ and so $$r+J\in I\frac{R}{J}.$$
Comment: Seems good. Thanks.


IP blocking doesn't prevent requests

Question: I am getting a lot of bad requests from a crawler at a specific IP Address non-stop. I added the IP to the blocked list and cleared the cache, but I still see more requests in the dblog coming in from the IP:
HTTP response: Bad Request. URL: https://valid.url.example.com/api/123456>; rel="canonical",<https:.json.

Why can they still send requests? Is there a way to prevent these?
Comment: I guess you can't prevent requests on request process layer because that layer only happens when a request is processed. Although you see the dblog entry, Drupal is not processing the request (serving content), because the IP module blocks further processing. If you want to avoid requests completely you have to di it at webserver/proxy/load balancer level.
Comment: @sanzante I suppose if the IP keeps flooding the logs in the same way for another week or two, I could look into that.
Answer: Flood control is just for failed login attempts and some other stuff like forms being filled out.  It will not keep your bad bot from the site.
Assuming you have an Apache server, you can modify the .htaccess file in the root of your site to block specific ip with the DENY FROM {ip} directive. E.g. adding something like this to the top.
order allow,deny
deny from 255.0.0.0
deny from 123.45.6.
allow from all

If you don't have Apache / .htaccess support, the process will be different.
Comment: I use Nginx, but it would be pretty simple to find how to do that.

IP blocking doesn't prevent requests


expand the width of a ul if the text overflows

Question: Is it possible to expand a ul li ul (drop down) if the text of ul li ul li goes outside the width of the box?
jsfiddle: http://jsfiddle.net/KAVzf/1/
Thanks :-)
Answer: Remove all references to width: 100% from your menu (#midwrap #nav li ul, #midwrap #nav li ul li, #midwrap #nav li ul li a)
Working example: http://jsfiddle.net/KAVzf/13/
Update
To resolve the issue with only the text being highlighted in the sub-menu on hover you need to add the following CSS to #midwrap #nav li ul li:
#midwrap #nav li ul li {
    ...
    float: none;
    display: block;
    ...
}

Working example: http://jsfiddle.net/KAVzf/22/
Comment: @A.K could you expand on what is "not working as expected"? I have just updated my answer to remove all `width: 100%` references so maybe this resolves the issue you have found.
Answer: Check this
http://jsfiddle.net/KAVzf/14/
Remove width 100% from #midwrap #nav li ul li {}   and #midwrap #nav li ul {}
Have width 100% for anchors only.
Comment: Hey, thanks for this, only problem is now, on the shorter ones the hover effect (color change) only applies to the width of the text rather than the entire box if this makes sense?
Comment: I checked and did not find any issue. Can you please show a screenshot of the issue?
Comment: Sure, this here is it with the mouse hovered over the text "tt" http://imgur.com/ZmoX3
Comment: @MyHeadHurts I checked your jsfiddle output. The issue is not there. But in my case also I am not getting the issue.
Comment: @Rain If you hover `Accommodation > tt` (you must hover over the actual `tt` text) then only `tt` will be highlighted. I get the same on both my original answer and your answer (in FF). It is strange that you are not able to reproduce as this is actually the expected behaviour since `float` causes a div to wrap to fit its content rather than the remaining space
Comment: Yes, in my end I am not getting this issue.


Enhancing the effect of Crescendo/Diminuendo in musescore

Question: I just want to know how can I steep the gradient of crescendo (or diminuendo) effect in Musescore?
In normal situations it's like there are no effects at all.
I'm using Musescore 3.2.
Comment: Are you trying to enhance the visual effect (hairpin size, etc.) or the volume effect? If you mean the latter, then a crescendo/diminuendo does nothing without dynamics flanking it (hidden or not).
Comment: I've also added dynamics before hairpin but finally changing the velocity parameter in inspector for the hairpin does the trick.
Answer: Just found the answer.Actually I needed to change Hairpin parameters in the inspector for the hairpin.Furthermore, dynamics besides the hairpin is necessary as others pointed out.
Also Exponential Dynamics method makes the effect more audible and less gradual.


Quando devo usar o ConstraintLayout?

Question: Além do RelativeLayout, FrameLayout, LinearLayout, TableLayout, dentre outros já existentes, que suprem bastante as necessidades relacionadas a layout, o Google anunciou no Google I/O 2016  o ConstraintLayout. Veja abaixo um exemplo:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</android.support.constraint.ConstraintLayout>

Observando que tem muita semelhança com RelativeLayout, qual seria a diferença entre os dois?
Quando devo usar o ConstraintLayout?
Answer: Quando você precisar de layouts mais complexos e que irão precisar de uma hierarquia mais precisa.
O ConstraintLayout foi criado, de acordo com a doc, para criar telas com uma hierarquia mais precisa, sem precisar aninhar as views. Ou seja, sempre que tu for fazer um layout relativamente complexo e que precise de um alinhamento preciso, tu tem que usar ConstraintLayout. O objetivo desta view é justamente isso, permitir que os desenvolvedores possam otimizar as hierarquias das suas telas.

Vantagens

Otimizado para hierarquias de exibição
Você não terá problemas se o estado de visibilidade da sua view for GONE, o alinhamento funcionará mesmo assim e você não vai mais se preocupar com layouts quebrados.
Editor completamente amigável
Fácil de usar e feito para desenhar telas responsivas

Desvantagens

O layout editor vai simplesmente mover suas views sem motivo algum, isso deve ser causado quando tentamos mover uma view e acabamos clicando em outra.
Performance. A performance em que as views são criadas é um pouco inferior se comparar ao RelativeLayout ou LinearLayout.
O principal problema é o editor. Com o passar do tempo, tu vai perceber que o editor faz coisas inesperar, então tu vai acabar preferindo por criar teus layouts manualmente. Eu prefiro. É melhor e um pouco mais rápido.

Quando devo usar o ConstraintLayout?


Entity updated in a controlled not updated in a Job

Question: Hi I'm having a problem with my project. I have a background job
running which updates one entity. The problem is that if I update
another entity from a controller the first one doesn't react to the
updated entity. But if I try to access from a controller the second
entity I can see that it was updated,
Here's the code:
Second entity
package models;
import javax.persistence.Entity;

import play.db.jpa.Model;
@Entity
public class GameMap extends Model {
    static int convPx=16;   //converts game pixels in the map rap.
    int[][] array;
    public GameMap(int[][] array) {
        this.array=array;
    }

    public boolean isSolid(int x,int y){
        try{
        if (array[y][x]==0)
            return false;
        else
            return true;
        }catch(Exception e){
            return true;
        }
    }
    public String collides(GameObject object){      //TODO fix if it collides top and left scenario
        if(isSolid((object.x+object.width/2)/convPx,object.y/convPx))
            return "top";
        if(isSolid((object.x+object.width/2)/convPx,(object.y+object.height)/
convPx))
            return "bottom";
        if(isSolid((object.x)/convPx,(object.y+object.height/2)/convPx))
            return "left";
        if(isSolid((object.x+object.width)/convPx,(object.y+object.height/2)/
convPx))
            return "right";
        else
            return "false";
    }

    public void addPoint(int x, int y, int what) {
        array[x/convPx][y/convPx]=what;
        this.save();
    }
}

I update it calling the appPoint() method from this controller
public static void addMapPoint(int x, int y){
            GameMap map =(GameMap) GameMap.findAll().iterator().next();
            map.addPoint(x, y, 1);

    }

This is the job that doesn't get updated
package controllers;
import java.util.Iterator;
import java.util.List;

import models.Ball;
import models.GameMap;
import play.jobs.Job;

public class BallJob extends Job {
    public void doJob() {
        List<Ball> balls;
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        new Ball(40,40,4,4,10,10).save();
        int[][] mapArr = {

{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},

{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},

{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},

{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},

{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},

{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},

{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},

{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},

{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},

{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},

{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},

{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},

{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},

{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},

{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},

{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},

{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},

{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},

{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},

{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},

{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},

{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},

{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},

{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},

{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},

{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},

{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},

{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},

{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
        };
        GameMap m= new GameMap(mapArr);
        m.save();
        Long time = System.currentTimeMillis();
        while (true){
        try {
            if(25-System.currentTimeMillis()+time>0){
                Thread.sleep(25-System.currentTimeMillis()+time);
            }
                time =System.currentTimeMillis();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        balls = Ball.findAll();
/***************************************************************
****************************************************************
* This map doesn't change
****************************************************************
***************************************************************/
        GameMap map = (GameMap) GameMap.findAll().iterator().next();

        for (Iterator iterator = balls.iterator();
iterator.hasNext();) {
            Ball ball = (Ball) iterator.next();
            ball.applyForces();
            if(ball.collides(map)){
            ball.applyForces();
            }

        }
        }
    }

}

Any idea?
Thanks
Answer: JPA doesn't propagate changes from the database to the existing entities into persistence context. I guess you need to refresh it:
map.refresh();

Comment: This works, but I can't understand why. with this line :GameMap map = (GameMap) GameMap.findAll().iterator().next();  I should get a new entity from the database, why should I need to update it manually?
Comment: @MaurizioPz: I'm not sure how Play Framework manages this, but from basic JPA understanding, calls of `findAll()` method happen inside the same persistence context, therefore loaded entities are cached by the context, and subsequent calls return cached instances.


How to create a tuple using constructor inside macro in crystal lang

Question: I am trying to create a empty tuple inside macro but getting error - Error: undefined macro method 'TypeNode#new'

{% empty_tuple = Tuple.new %}

Here is link to crystal play - https://play.crystal-lang.org/#/r/8mxf
If i can't do this way, please tell me if there is any alternative
Update 1
I am trying to initialize a class - cases are some class constructor has arguments and some has not
So i thought of using tuple with splat for argument passing.
Here is crystal play link of what i am trying to do - https://play.crystal-lang.org/#/r/8n4g
Update 2
You can create a tuple using direct syntax
args = {1}

but this won't work in case you want to create empty tuple because hash syntax is similar & compiler throws error for providing type for hash declaration.
So i thought about using constructor syntax - Tuple.new
but it didn't work either.
Comment: Can't you create the empty tuple outside of macro code? Why do you need it in macro code?
Comment: Sounds like you're abusing macros a bit, I can't fathom a legit usecase for this.  Anyways, just using a constant outside macro land should work and be possible to reference in macro land.
Comment: @JonneHaß i am working on big project, so i need to use macro at multiple place to get things done. Could you please provide me a crystal play link of what you are saying ?
Comment: Why do you need this?
Comment: @asterite i am trying to create an instance of class & using splat for args pass to constructor. I am able to solve this problem using conditional check but initially i thought about this way.
Answer: I was trying to create instance of many classes using macro & that's why i chooses this approach.
As i was unable to create empty tuple in macro. I came up with a hack - what if i get args of some method which does not have any args which means it will be empty tuple right ?

but it was not, it was an empty array

And again i was stucked. So i used

if else

to solve this problem. Basically check if class needs to be initiated with args, then create a class & pass arguments in constructor else initiate class without any args.
Hope this helps someone.


Views question with user reference

Question: I have a content type courses with course name, instructor, coordinator and ta fields. Instructor and coordinator are of type user_reference.
My data looks like below
course   instructor    coordinator
101       joe           guo
102       joe           larry
103       guo           joe
My course view has filter criteria as below
content access: access and Contextual filter : author ID
When Joe logs in, the display looks like
Courses
101
102
103
I'm trying to figure out how to display only the courses joe is an instructor for. It should not show 103.
Any ideas?
Answer: What you want is a contextual filter on your user reference field. It should be label like Content: Instructor (or whatever you named your instructor or coordinator field). For the When the filter value is not in the URL option, select Provide the default value and use the User ID from logged in user option.
Comment: Thanks you. This worked. How do I show all records 1/when administrator logs in and 2/user has a role 'chair'
Comment: Not sure. I've not had to use contextual filters for roles & role references. DA isn't a help forum, but a knowledge base. Mark this question as answered and ask that as a new question (after searching the site to see if it's been already asked).
Answer: I actually found the answer to my question. I add this code php code
WHEN THE FILTER VALUE IS NOT AVAILABLE -> Provide default value -> Type is PHP Code.
<code>global $user;
if (in_array('administrator', $user->roles)) {
  return 'all';
}
else {
  return $user->uid;
}
</code>

Views question with user reference


ordinal regression or Spearman correlation?

Question: I am conducting research investigating two different groups of women: one group of Short-Stature Women (SSW) and another with Non-Short Women (NSW). We have the hypothesis that SSW has an inaccurate auto-perception of their current body size (CBS). We assessed CBS with a figure rating scale, consisting of 9 different silhouettes, ranging from 1 to 9 (which would assess something like from "malnourished" to "very obese"). We know that CBS is highly determined by the person's Body Mass Index (BMI). Hence, we would like to know if the BMI is a significantly better "predictor" of CBS in NSW compared to SSW.
My first approach was to run two Spearman  rho rank correlation test (one for each group (SSW and NSW), between BMI and CBS) and then to compare both coefficients using the Fisher's Z-test. Nevertheless, I am pretty sure that I can treat CBS as an ordinal variable, right? So, it seems to me like an ordinal regression (using CBS as DV and BMI as IV) would be more suitable to my data. If this is true, my problem is that I do not know how to compare coefficients for ordinal regression. Would it be comparing Nagelkerke-R²? How can I do this?
To summarize I have 2 main questions: a) Is Spearman rho rank correlation with comparison of the coefficients by Fisher's Z-test adequate in this case? and b) If ordinal regression is more adequate, how can I compare the coefficients of the regression between my two groups?
Answer: Yes, CBS sounds ordinal. If you're only interested in comparing bivariate relationships, comparison of Spearman's $\rho$s seems fair enough to me. However, an ordinal regression model would allow you to estimate the independent relationships of BMI and stature while controlling the effects of each other predictor. You could also test whether these factors moderate each other by including an interaction term. For more on that, see "How to test whether a regression coefficient is moderated by a grouping variable?" and "What is the correct way to test for significant differences between coefficients?"
The method described in the latter question is correct for your purposes in multiple regression (though it wasn't in that OP's case). If you want to calculate the probability that your two predictors' slope coefficients would differ by at least as much as they do in your sample if (1) you were to collect another equivalent sample from the exact same population, and if (2) your predictors are actually equally related to CBS, then
 you can do this with a z-test:
$$Z = \frac{b_1 - b_2}{\sqrt{SE_{b_1}^2 + SE_{b_2}^2}}$$
You can convert the resultant z statistic to a probability using pnorm in r or with other methods described here: "How to deal with Z-score greater than 3?"
By the way, if you have continuous height data, you probably ought to reconsider dichotomizing stature into short and non-short. This wastes information that could improve your regression model and correlation estimates; you would probably get smaller standard errors by entering both BMI and height data as originally measured (if you have it) as predictors in multiple ordinal regression of CBS.
Comment: Thanks Nick. First, I do have continuous height data, but the design of the research is to strictly compare SSW (<150cm defined by World Health Organization) and NSW (>160 cm). So I have nobody between 150-160 cm. Hence, my interest is really comparing findings between groups.
I was somehow aware that I could include a dummy variable in the model to compare regression coefficients, but only for a linear regression. Actually, my SPSS output for ordinal regression using BMI as IV and CBS as DV does not show something like a "coefficient" of the linear regression, except for the pseudo-R².
Comment: @NassibBueno: that might be an unfortunate consequence of using SPSS ;) you should be able to write the syntax manually to produce slope coefficients for your predictors if necessary; there are such components of the ordinal regression model. Maybe it's time to switch to R? I'm getting slope coefficients out by default using `polr` from the `MASS` package...
Comment: You are right, I began to use SPSS due to it "deceiving" user-friendly interface, and now I feel its lack of extra resources. Nevertheless, I am able to use Stata, and I will find out how to calculate coefficients for the ordinal regression there and then I will apply the methods described by you to compare coefficients. If I fail in last case, I am at least safe to use the Spearman correlation with Fisher Z-test approach, right? Thank you again, Nick.
Comment: Yeah, it's not an unsafe method AFAIK; it's just rather limited. You can do a lot more with ordinal regression than with comparison of bivariate correlations.
Comment: Nick, I think I did it. I run the ologit command in Stata (and realized that SPSS do show me a coefficient for the ordinal regression, but he calls it "estimate"). The I found both coefficients and SE, for SSW (0.1754 ; 0.06262) and NSW (0.2639, 0.0528). I applied your equation and found a Z-value of -13.4, which means a a really small p-value, right? (I could not calculate the exact p). Hence I conclude that BMI predicts CBS in significantly different ways between SSW and NSW (P < .01), right? the problem is that the CI95% I receive are: SSW [0.0526 to 0.2981] and  NSW: [0.1603 to 0.3675].
Comment: ... but assuming my rather equal SE between groups, and my sample size of 113 (56/57), it is possible to do not rely on CI95% comparisons and use the Z-test approach? Thank you again, Nick.
Comment: The *z* for the difference between those two coefficients – given those standard errors – is 1.08. That corresponds to a *p* = .14, assuming a normal distribution where appropriate. You should be able to get a similar *p* by testing the interaction of stature and BMI as a predictor of CBS. I was under the impression you were trying to compare stature and BMI as separate predictors, rather than trying to test stature as a moderator of the relationship between CBS and BMI...
Comment: wow, I forgot to square root the denominator. As my objective is to compare both groups (SSW and NSW; so I will not use continuous height data), I decided to remove stature from the model and run two separate regressions.