Let $\Gamma = \{(x,y) \in \mathbb{R}^2 \mid x\in \Bbb Q, y \in \Bbb R \}$. Show that $\Gamma$ is measurable and $m(\Gamma)=0.$

Question:
Let $\Gamma = \{(x,y) \in \mathbb{R}^2 \mid x\in \Bbb Q, y \in \Bbb R \}$. Show that $\Gamma$ is measurable and $m(\Gamma)=0.$

It seems that there isn't a clear definition on how to classify set as measurable? I'm trying to work with $\Gamma$ to see if I get something. It seems that $$\Gamma= \{(x,y) \in  \mathbb{R}^2 \mid x \in \Bbb Q \} \cup  \{(x,y) \in  \mathbb{R}^2 \mid y \in \Bbb R \}\\ = \Bbb Q \times \Bbb R \cup \Bbb R \times \Bbb R$$
Would it satisfy to show that these two sets $(\Bbb Q \times \Bbb R)$ and $\Bbb R^2$ are measurable?
Comment: That union is not correct. Indeed, $$(\Bbb Q \times \Bbb R) \cup (\Bbb R \times \Bbb R) = \Bbb R \times \Bbb R.$$
Answer: Your interpretation of $\Gamma$ is wrong. $\Gamma =\mathbb  Q \times \mathbb R$ which makes this set a Borel set in $\mathbb R^{2}$. Also, its measure is $m(\mathbb Q)m(\mathbb R)=0$ since $0 .\infty$ is interpreted as $ 0$ in the definition of product measure.
Comment: No. It is read as $x \in \mathbb Q$ **and** $y \in \mathbb R$. @Danlo
Comment: Isn't the comma in $\Gamma = \{(x,y) \in \mathbb{R}^2 \mid x\in \Bbb Q, y \in \Bbb R \}$ read as $x\in \Bbb Q$ or $y \in \Bbb R$?


NGINX: Send a copy of requests to another upstream

Question: Our team has developed an analytic app which records and analyses all incoming (not dropped) requests. To that extent, I have to send a copy of all requests to another upstream in my reverse-proxy solution.
Is it possible with NGINX alone? Or is there any other solution with minimum impact on the current reverse-proxy structure?
It is preferable to do so within NGINX so that processes on requests by NGINX is already done and the request will be the same as it is sent to destination upstream.
PS: The analytic app does not return any response
Comment: @iMil post_action is not documented and there is a reason. It clogs up the connection until the post_action is done and reduces performance. Since it is on a reverse proxy server it severely damages the delivery time of all services.
Comment: speaking of, you also could do port mirroring on your server, it's a bit tricky but can be achieved, here's well written blog post on the subject https://adamkuj.net/blog/2016/05/18/pro-tip-port-mirroring-in-linux/
Comment: After some searhing in nginx docs I found a directory mirror in http://nginx.org/ru/docs/http/ngx_http_mirror_module.html. Think, this is what u need.
Comment: Seems like there was a topic with an answer to that question http://serverfault.com/questions/515284/copy-and-deliver-a-request-to-another-nginx-server-for-real-traffic-testing/515531#515531
Comment: I came across this blog post from nginx.com that might be of interest in your situation https://www.nginx.com/blog/performing-a-b-testing-nginx-plus/
Comment: @iMil Thanks! This is an interesting article. It is somewhat different with A/B testing in which I need all requests mirrored into two destinations. I have managed to do a brainstorm with network staff and lower level solutions were offered like port mirroring on a switch or NetFlow/sFlow solutions, syslog parsers and such. Thanks again! I think I leave this question open in case a better solution emerges.
Comment: @aligin I think that's the answer. Thank you! and if you wouldn't mind, submit this as an answer so It could be marked as the solution. Thanks again!
Answer: After some searhing in nginx docs I found a directory mirror in nginx.org. Think, this is what u need.
We are using kubernetes with nginx as ingress, so our config is
<code>      location /api/what-i-want-to-mirror {
          set $proxy_upstream_name "gateway-api-service-svc-80";
          proxy_pass http://upstream_balancer;
          mirror /mirror;

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

      location = /mirror {
          set $proxy_upstream_name "integration-gateway-api-service-svc-80";
          proxy_pass http://upstream_balancer;
          internal;
          proxy_set_header Host $host;
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

          proxy_set_header X-Original-URI $request_uri;
      }
</code>
We've done this as ASAP but it works like a charm.


ENVIO DE REQUISIÇÃO PUT COM PHP E GUZZLE

Question: Preciso de uma ajudinha de vocês.
Tenho tentado enviar requisições do método PUT através de um Json utilizando o Guzzle, mas sempre obtenho o erro de TRUNCATED ou:

{   "message": "cURL error 18: transfer closed with outstanding read
data remaining (see
http://curl.haxx.se/libcurl/c/libcurl-errors.html)",   "code":
500 }

Seria correto fazer o request PUT dessa forma?
<code>$reqProduto = $this->client->request('PUT', 'company-products/'.$params['id'], [
                    "headers" => [
                        "Authorization"=> "Bearer ".$this->authToken['token'],
                    ],
                    "json" => [
                        $params
                    ]
                ]);
</code>
Bom, pessoal. Consegui resolver o problema. Coisinha simples.
O fato era que eu estava passando o $params dentro de colchetes, e o acabou que quando tirei os colchetes e deixei o array apenas <code>"json" => $params</code> funcionou e resolveu o probleminha.
Answer: Basicamente Sim!
<code>$r = $this->client->request('PUT', 'http://httpbin.org/put', [
    'headers' => [
         'Authorization'=> "Bearer ".$this->authToken['token'],
     ],
     'json' => [
         'foo' => 'bar'
     ]
]);
</code>
De uma olhada na propria documentação do Guzzle
https://docs.guzzlephp.org/en/stable/index.html
E de também uma olhada neste blog que cita o mesmo problema
https://bobcares.com/blog/curl-18-transfer-closed-with-outstanding-read-data-remaining/
Comment: Obrigado, Fernando! Consegui resolver o problema.
Eu estava passando `"json" => [$params]` ao invés de `"json" => $params`.


Translation for error message

Question: I created a feedback form using the Webform module and the  Internationalization module for the English and the Japan version.
Feedback is required. is translated as 「ご意見・ご感想」は必須項目です。 where the translation for Feedback is ご意見・ご感想. I need to show 「本文メッセージ」は必須項目です。 as error message.
How can I do this?
Comment: You want the error message to be `「本文メッセージ」は必須項目です。` but the translation for feedback is `ご意見・ご感想`?  Why not just change the feedback translation to `本文メッセージ`?
Comment: No I need feedback translation as ご意見・ご感想 and error message as 「本文メッセージ」は必須項目です。
Answer: By default, Drupal (and Webform) show the error message as Field_name is required, so if you want to show an error message that uses something other than field_name, you will have to override/write your own validation function.
The Webform Validation module may be of assistance here, particularly the code examples for custom validation hooks.
P.S. "本文メッセージ" is probably a mistranslation; it most likely should be flipped ("メッセージ本文", "message body").

Translation for error message


Usar valor de $_SESSION em função

Question: Tenho essa função Javascript abaixo, onde quero mudar o display de um link caso o valor de uma variável de sessão seja igual a determinado valor.
Porém, dessa forma que eu fiz, não está dando certo, ainda me confundo muito ao usar Javascript e PHP.
Alguém poderia dar uma ajuda?
E seria possível fazer isso usando apenas PHP ao usuário carregar a página?

Comment: Qual o valor de $_SESSION['aprovado']? Pelo restante do seu código parece ser um objeto... Se for, tenta usar o json_encode no echo e no javascript você faz um JSON.parse nesse valor: var select = JSON.parse("");
Comment: @JuniorNunes O valor de `$_SESSION['aprovado']` seria ou `sim` ou `não`
Answer: Provavelmente é a falta de aspas:
var select = <?php echo $_SESSION['aprovado']?>;

Deveria ser:
var select = "<?php echo $_SESSION['aprovado']?>";

E um detalhe citado pelo @JuniorNunes é que isto esta errado select.value == 'sim', o select deverá retornar uma string, deve ficar assim:
txt.style.display = select == 'sim' ? "block" : "none";

Outro detalhe muito importante, isto esta errado:
document.onload=function mostraCampominha() {

O correto é:
window.onload=function mostraCampominha() {

Sobre as aspas
Sem as aspas provavelmente a página esta sendo gerada assim depois que é baixada pelo navegador:
var select = sim;

Ou
var select = não;

No caso do primeiro, o JavaScript irá procurar uma variável chamada sim ou não, como provavelmente não existe ele setar o var select como undefined, provavelmente o seu console do navegador deve estar emitindo este erro:

Uncaught ReferenceError: não is not defined
Comment: @JuniorNunes obrigado, era isso mesmo que faltava, editei a resposta e lhe citei.
Comment: Eu coloquei as aspas mas ainda continua não mostrando link quando o valor é igual a ´sim´
Comment: @ArthurOliveira faça isso `var_dump($_SESSION['aprovado']);` fora da tag `
Comment: O var_dump retorna isso `string(3) "sim"` . Eu fiz essas mudanças, porém ainda não está funcionando
Comment: @ArthurOliveira o problema era o `select.value == "sim"` também, eu ajustei a resposta para isto `txt.style.display = select == 'sim' ? "block" : "none";`
Comment: Mesmo com essa mudança ainda continua não dando certo, eu tentei também usando o JSON igual o Junior disse, mas não da certo!
Comment: Entra no chat por favor, [vamos continuar esta discussão no chat](http://chat.stackexchange.com/rooms/69755/discussion-between-guilherme-nascimento-and-arthur-oliveira).

Usar valor de $_SESSION em função


How to replace the 3rd character and multiple of 3 's character in a string with a \n in javascript

Question: I have a string like 'oeew9w79WMIGL'. I want to get an output like below,
oee
w9w
79W
MIG
L

How to do it with plain JavaScript?
Comment: This is not "replace". This is insert.
Comment: @evolutionxbox OP is not replacing. OP is adding `\n` every 3 characters
Comment: Use regex to capture three or less consecutive alphanumeric characters.
Comment: @TatsuyukiIshi I don't think so, as OP is converting `79W` to `79w`
Comment: @Weedoze again, I don't think it is, as the OP isn't inserting, but is replacing. The question seems to be more about splitting the string into an array.
Comment: Ah. Right, that's not an array... sigh. I'm tired this morning.
Answer: You could replace a part of the string.

var string = 'oeew9w79WMIGL';

console.log(string.replace(/.../g, '$&\n'));
Comment: Thanks for your one liner approach. Both of you and @Viking code are right.. But I can't tick two solution.
Answer: if you use regex

let str = 'oeew9w79WMIGL';

document.write(str.match(/.{1,3}/g));

Comment: Thanks for ur one liner
Answer:

$(document).ready(function(){
 var foo = "oeew9w79WMIGL";
$('#test').html(foo.match(/.{1,3}/g).join("
") );
 });

 var str= "oeew9w79WMIGL";
console.log( str.match(/.{1,3}/g).join("
") );

Comment: he asked plain js not JQuery
Answer:  each_slice = function(enm, slice_size) {
   var results = [];
     slice_size = (slice_size < 1 ? 1 : slice_size );
       for (var i=0; i<=enm.length; i=i+3) {
         results.push(enm.slice(i, i+3));
      }
  return results;
}

var x = "oeew9w79WMIGL";
each_slice(x,3).join("\n")

//oee
//w9w
//79W
//MIG
//L

for reference: https://stackoverflow.com/a/41219012/4481312


sfml platformer error: missing type specifier - int assumed

Question: Hey im trying to check to see if my bounding box from my player class is colliding with the bounding box of my map tiles. however it is coming up with that error. i have a definition in my map.h called Player playermap; with an include of my player h. i then go onto check if they both intersect by saying if mapplayer.boundingbox.intersects(platformboundingbox) then collision occured. take a look and any insight would be much appreciated
here is a part of my map class
if(mapVector[i][j] == 1)
                         {
                            sprite.SetImage(BlockImage);
                            sprite.SetPosition(j * BLOCKSIZE, i * BLOCKSIZE);
                            platformBoundingBox.Top = sprite.GetPosition().y - 5;
                            platformBoundingBox.Bottom = sprite.GetPosition().y;
                            platformBoundingBox.Left = sprite.GetPosition().x - 5;
                            platformBoundingBox.Right = sprite.GetPosition().x;
                            Window.Draw(sprite);
                            if(mapPlayer.boundingBox.Intersects(platformBoundingBox))
                                cout<<"collision occured";
                         }

here is where it comes up with the error in my map.h file
Player mapPlayer;

Comment: Please edit your question to include the _complete_ error message, _all_ of the messages, and please also point out on which line in the code they are about. It would also be good if you included the _definitions_ of all involved classes/structures that you made.
Comment: I have shown where the error comes up. at the end Player mapPlayer. and the two classes involved. map and player. i just want to use the bounding box from player in my map class. and that is error. apart from the error code "error c4430: missing type specifier - int assumed. Note c++ dies not support default-int.
Comment: But what is `boundingBox`? What is `platformBoundingBox`? And what version of SFML?
Comment: Yeah sorry i should of included them details.

sfml 1.6 and they are both sf::Rect
Comment: Are you doing `using namespace sf;` in the source file, or an included header file?
Comment: Yes in my map header file
Answer: The problem is your
using namespace sf;

This will make your variable Window clash with the sf::Window class.
Either use e.g.
this->Window.Draw(...);

Or (what I recommend) stop with the using statement. It's only four characters more to write in declarations, and will also have the good thing that it makes your code much clearer.
Comment: okay, thanks for the input. i dont think this would solve my problem though.
Comment: @TomFlan Why don't you try it? If it doesn't work then at least it's one thing to cross out as the possible error.
Comment: I did. with no luck. and you are right it is something to cross off the list. i might just try a whole different approach at comparing the bounding boxes. I have this project to hand in next week and already spent the whole day trying to solve 1 problem.
Comment: @TomFlan Get a good nights sleep, and you might see it all in a new light tomorrow. :)
Comment: aha thanks I shall be sure to do that! thanks for your help anyway


Accuracy, Sensitivity, Specificity, & ROC AUC

Question: In the context of predictive modeling, when comparing clasification models, What statistic should be considered more important over the others: Accuracy, sensitivity, specificity, or area under ROC curve? Would you suggest other statistics?
Thanks & regards.
Comment: I think this could be closed as a duplicate of multiple targets to cover all aspects of the question. I've voted for one of them.
Answer: In case if dataset is imbalanced.
I would suggest to use a Precision & Recall metric or Precision | Recall curve instead of ROC and Accuracy.
[https://www.kaggle.com/general/7517]
[https://classeval.wordpress.com/simulation-analysis/roc-and-precision-recall-with-imbalanced-datasets/]
The Precision-Recall Plot Is More Informative than the ROC Plot When Evaluating Binary Classifiers on Imbalanced Datasets
Answer: Accuracy, sensitivity and specificity are improper scoring rules. They all have major problems in unbalanced datasets, and almost as big problems in balanced datasets. See Why is accuracy not the best measure for assessing classification models?
AUROC is slightly better, it is a semi-proper scoring rule: What does it mean that AUC is a semi-proper scoring rule?
The best approach is to use probabilistic predictions and proper scoring rules. See my answer to the thread cited above.
Answer: For an apples to apples comparison, the area under the ROC (AUC) would be the best metric. This is because the AUC does not depend on the thresholding value. It is also not sensitive to imbalances in the dataset. (Ideally, we should use the same validation/test data to perform comparisons, so one could argue that the dataset imbalance is not such a big deal.)
Depending on the application, the sensitivity or specificity might be more important. For example, you might have high penalties for false negatives, which implies you want high sensitivity but can tolerate some loss in specificity. In such cases, it will make sense to check what is the best sensitivity (or specificity) you can achieve, this can be obtained from the ROC (the complete curve). The AUC might be misleading, in such cases.
For alternate metrics, you could also consider the Precision-Recall (Recall = Sensitivity) curves (see https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0118432).
Note however that Precision is affected by data imbalance.

There is some good discussion here:
https://lukeoakdenrayner.wordpress.com/2017/12/06/do-machines-actually-beat-doctors-roc-curves-and-performance-metrics/
https://lukeoakdenrayner.wordpress.com/2018/01/07/the-philosophical-argument-for-using-roc-curves/
https://www.site.uottawa.ca/~stan/csi7162/presentations/William-presentation.pdf


C# Using Equals method in a generic list fails

Question: I have a project where I have class State which uses templates.
I have a class Cell, and I use it as State, so State holds a Cell as genericState.
Now I have a generic function which checks if two instances are equal.
Problem is, it never leaves the State Equals method to Cell Equals method.
public class State<T>
{
    public T genericState;  //in my case T is a cell
    public State(T cellState) // CTOR
    {
        this.genericState = cellState;
    }

    public override bool Equals(object obj)
    {
        return genericState.Equals((obj as State<T>).genericState);
    } //never leaves
}

and code of Class Cell, in which it never gets:
public class Cell
{
    public int row, col;
    public bool visited;
    public char value;
    public bool Equals(Cell other)   //never gets here
    {
       return other != null && other.row == row && other.col == col;
    }
 }

I don't understand why it never gets to Equal method of Cell. What could be wrong with the code?
Comment: I think maybe [this](https://msdn.microsoft.com/en-gb/library/ms173147(v=vs.80).aspx) might help you
Comment: @Squirrel5853 yours link isn't valid anymore, it's just redirecting to other page :(
Answer: The problem is that your code does not know that T has a special method
bool Equals<T>(T other)

It thinks that it should be calling Cell's override of Equals(object), which your code does not override.
Fixing this is simple: add IEquatable<Cell> to the list of interfaces implemented by Cell, and add a constraint on T to ensure that it implements IEquatable<T>:
public class State<T> where T : IEquatable<T> {
    ... // The rest of the code remains the same
}
...
public class Cell : IEquatable<Cell> {
    ... // The rest of the code remains the same
}

Answer: Firstly, you should override object.Equals to defer to this Equals:
public override bool Equals(object obj) => Equals(obj as Cell);

And if you are overriding object.Equals then you also need to override object.GetHashCode():
public override int GetHashCode() => row * 31 + col;

Further to this, for better performance you could have Cell implement IEquatable<Cell>, and in your State<T>.Equals use EqualityComparer<T>.Default. This will be better because EqualityComparer<T>.Default uses IEquatable<T>.Equals(T) when implemented, falling back to object.Equals(object) when that isn't available.
Comment: where should i put this piece of code? but this way I ignore the generic templates, no?
Comment: Override in all types, which can fill T at compile type in the generic template, it will automatically pick up
Comment: Which, the use of `EqualityComparer.Default`? You use `EqualityComparer.Default.Equals(genericState, (obj as State).genericState)` instead of calling `genericState.Equals((obj as State).genericState)`.
Answer: genericState.Equalsis the equality method derived from object. In your Cell class, you are not overriding object.Equals(object), so your equality method (Cell.Equals(Cell)) is not being called, but instead, Cell.Equals(object) is being called. So what you can do to fix this is change your Cell class to override the default equality method:
public class Cell
{
    public int row, col;
    public bool visited;
    public char value;
    public override bool Equals(object other)   //never gets here
    {
       if(!(other is Cell)) return false;
       return other != null && other.row == row && other.col == col;
    }
 }

Answer: I hope this method will help you, it should to handle also the situations when obj or genericState could be null.
public override bool Equals(object? obj)
{
    return obj is State<T> state && object.Equals(state.genericState, this.genericState);
}


Chained branching merging strategy

Question: I created branch A from master. After finishing I created pull request to master. While work from A was under review I started working on task that is based on branch A, so from branch A I created branch B. Then I merged branch B to A and wanted to merge B to master, but conflict appeared. What is best practice to avoid conflict in this scenario? Both branches were local, before pull request from A.
[edit]
Any same line was edited in both branches A and B, so why it is not merged automatically?
Comment: I would recommend using GitFlow as you asked for best practice. This way you will never branch from a feature branch (A) but from develop and all the merges are done through develop reducing code conflict risk.
Comment: `wanted to merge B to master` ... why?  I think `B` should go back to `A`.  Note in general that there isn't always a way to avoid merge conflicts.
Comment: Why are you wanting to avoid conflicts? Such is the nature of a DVCS.
Comment: Yes B merged with A and there was not conflicts, but then I want to make pull request, so I wanted to merge B to master, because I wanted base branch pointing to master.
Comment: @evolutionxbox Because I was working on features locally, so this is why conflicts seems strange.
Comment: Not really, if you change the same file in two different commits (on the same line) and then merge, one would expect a conflict.
Answer: Git (emphasis required here, because you are probably using more than just Git itself) doesn't have a concept of a "base branch".
When you use a web interface like those on GitHub or Bitbucket to create a "pull request", it's the web interface that chooses the upstream's branch name against which to suggest the pull request.  Git itself has no idea that you will make a pull request.1  All Git knows and cares about are the commits, usually by hash ID.
When you run git merge, you choose two commits, usually two branch tips.  You choose one by running git checkout, typically git checkout <somebranch>.  That commit becomes your current commit.  This is the commit that Git calls local or --ours; I generally call it L for left, local, or --ours.  (Note that if you don't run git checkout just before git merge, whatever you have checked out right now remains your current commit, and you are therefore choosing that as your L commit.)
You then run git merge <name-or-hash-id>.  Git translates the name, if you give it one, to a commit hash ID.  This is how you choose the other commit, which Git sometimes calls the remote or other or --theirs commit, and I call R.
Git uses the L and R commit hash IDs, plus all the other commits in the repository, to find a merge base commit hash ID.  This merge base commit is, in short, the "nearest" commit at which the two branches "come back together".  The commit that Git will find here depends on the topology of the existing commit graph.
If Git is able to do the merge on its own, Git makes a new commit holding the merge result.  The new commit has two parents, instead of just one: the first parent is the commit that was L at the time you ran git merge, and the second is the commit that was R.  The new commit goes on the current branch, so that the current branch name—the one you have checked out—now points to the new merge commit.
The graph you drew above is hard for me to interpret: I cannot tell, from your drawing, which commits are reachable from which branch-tip commits, or for that matter, which commits are the branch tips in the first place.  In particular you have drawn two commits that appear to be merge commits, but I do not know whether earlier (ancestor) commits are on the left or the right.  Moreover, your text describes making one merge, not two.  Using the assumption that earlier commits are towards the left—that time flows left-to-right, as it were—here is how I might draw most of this graph in text:
       o--o   o--o   <-- branch-B
      /    \ /
     | __---o   <-- branch-A
     |/
...--o   <-- master

Note, however, that this graph has only one merge commit, which in this case is the commit to which the name branch-A points.  The name branch-B points to the right-most commit on the top line.
In this particular example, branch-B contains every commit drawn in the graph, while branch-A contains all but the two most recent commits, and master contains only the commits on the bottom line plus any earlier commits leading up to that point.  The merge base of the tip commit of branch-B (commit L) and the tip commit of master (commit R) would be the tip commit of master, i.e., commit R itself.  Running git merge while on branch branch-B would therefore choose that as the merge base.  The merge would be trivial to make (but in fact refused) as there would be no merge conflicts.2  So that's clearly not what you are doing, and clearly not the correct graph.
Without the correct graph, it's impossible to say what Git chose as the merge base.  But if you did get a merge conflict, it is because when comparing the merge base commit to commit L, Git saw one change to some line of some file, and then when comparing the merge base commit to commit R, Git saw a different change to the same line of the same file.  Git was unable to choose between these two changes, so it stopped with a merge conflict, leaving the work-tree version of the file with both changes applied.  It is now up to you to resolve this conflict (and any other conflicts), git add the correct merge result, and run git merge --continue to finish the merge; or run git merge --abort to stop the merge and put things back to the way they were before Git attempted the merge.

1While they are related, don't confuse these externally-provided web interfaces with the git request-pull command-line command.  That one is built in to Git, but it requires that you, not Git, choose the <start> commit.  When GitHub makes the choice for you, they are using information not available to Git itself.  Specifically, GitHub knows—has recorded for itself, in a location it effectively keeps secret from Git—which upstream project you used when you clicked the GitHub "fork" button.  They (GitHub) also control the Git repository for that upstream project, so they can peek inside it and choose a <start>.  But they do that; Git doesn't.
2Remember, after computing the merge base commit, Git effectively runs:
git diff --find-renames <base> L   # see what we did on --ours
git diff --find-renames <base> R   # see what they did on --theirs

and then tries to combine these two sets of changes into one big "everyone's changes since the base" change-set, and apply the combined changes to whatever is in the <base> commit.  We have just made the claim that <base> and R are the same commit, so there must be no changes at all here.  The result of such a merge would match commit L exactly.  In fact, though, Git would say "already up to date" and refuse to do anything, for this case.

Chained branching merging strategy


Array index is out of bounds while using bvp solver in python

Question: I am using the bvp solver in Python to simulate a 4th order boundary value problem, of the form d4y/dx4= F(y)/(t-y)^2, where F(y) is a complicated function of the variable y. The code that I have written for the same has been attached below :

import numpy as np
from scipy.integrate import solve_bvp
from numpy import arange
import matplotlib.pyplot as plt
from scipy.optimize import root

def xmesh(k1):
 return np.linspace(0,L,k1)

def solveit(gamma):
 def fun(x,y): # this function returns all the derivatives for the bvp solver
  m1=y[0] # m1 is an 1-D array
  array=np.empty(10,)
  def calc(): # this function calculates F(y) at all the mesh points and finally returns an array
    for i in range(10) :
     def fun2(var):
       return gamma*(var)+var**(0.5)+var**(3)+m1[i]

     sol= root(fun2,x0=0.00001,method='krylov',tol=1e-12)
     array[i]=sol.x

    return array

  m2=calc() # m2 is an 1-D array and is equal to F(y)
  rhs= m2/((t-m1)**2) # rhs contains the RHS of the differential equation
  return np.vstack([y[1],y[2],y[3],rhs])

 def bc(ya,yb): # boundary conditions for the bvp solver
    return np.array([ya[0],ya[1],yb[0],yb[1]])
 q= 10
 yinit= np.zeros((4,len(xmesh(q))))
 sol= solve_bvp(fun,bc,xmesh(q),yinit,tol=1e-6,max_nodes=5000)
 arr= sol.sol(xmesh(q))[0] # array containing y
 return arr
a=solveit(0.1)

Whenever I try to run the above code, I bump into the error : index 9 is out of bounds for axis 0 with size 9. I don't understand why this error is raised. It means that the array has 9 elements and I am trying to refer to the 10th element of the array and hence it raises this error. But all the arrays defined in the code above have 10 elements each. So, I don't understand why this error is even being raised. I have been stuck with this for 2 days now. Any solution to the above problem will highly be appreciated.
P.S.- The functions that I have defined in the code above have no physical meaning and are completely random. So, I do not need a correct numerical solution to the above code. All I need is the code to work fine without any error. Also, I have previously used the bvp solver in Python with success.
edit : I have added the stack trace.
IndexError                                Traceback (most recent call last)
<ipython-input-4-8423177548fe> in <module>()
     34  arr= sol.sol(xmesh(q))[0] # array containing y
     35  return arr
---> 36 a=solveit(0.1)

12 frames
<ipython-input-4-8423177548fe> in solveit(gamma)
     31  q= 10
     32  yinit= np.zeros((4,len(xmesh(q))))
---> 33  sol= solve_bvp(fun,bc,xmesh(q),yinit,tol=1e-6,max_nodes=5000)
     34  arr= sol.sol(xmesh(q))[0] # array containing y
     35  return arr

/usr/local/lib/python3.6/dist-packages/scipy/integrate/_bvp.py in solve_bvp(fun, bc, x, y, p, S, fun_jac, bc_jac, tol, max_nodes, verbose, bc_tol)
   1084                                        fun_jac_wrapped, bc_jac_wrapped, x, h)
   1085         y, p, singular = solve_newton(n, m, h, col_fun, bc_wrapped, jac_sys,
-> 1086                                       y, p, B, tol, bc_tol)
   1087         iteration += 1
   1088

/usr/local/lib/python3.6/dist-packages/scipy/integrate/_bvp.py in solve_newton(n, m, h, col_fun, bc, jac, y, p, B, bvp_tol, bc_tol)
    439     n_trial = 4
    440
--> 441     col_res, y_middle, f, f_middle = col_fun(y, p)
    442     bc_res = bc(y[:, 0], y[:, -1], p)
    443     res = np.hstack((col_res.ravel(order='F'), bc_res))

/usr/local/lib/python3.6/dist-packages/scipy/integrate/_bvp.py in col_fun(y, p)
    324
    325     def col_fun(y, p):
--> 326         return collocation_fun(fun, y, p, x, h)
    327
    328     def sys_jac(y, p, y_middle, f, f_middle, bc0):

/usr/local/lib/python3.6/dist-packages/scipy/integrate/_bvp.py in collocation_fun(fun, y, p, x, h)
    311     y_middle = (0.5 * (y[:, 1:] + y[:, :-1]) -
    312                 0.125 * h * (f[:, 1:] - f[:, :-1]))
--> 313     f_middle = fun(x[:-1] + 0.5 * h, y_middle, p)
    314     col_res = y[:, 1:] - y[:, :-1] - h / 6 * (f[:, :-1] + f[:, 1:] +
    315                                               4 * f_middle)

/usr/local/lib/python3.6/dist-packages/scipy/integrate/_bvp.py in fun_p(x, y, _)
    648     if k == 0:
    649         def fun_p(x, y, _):
--> 650             return np.asarray(fun(x, y), dtype)
    651
    652         def bc_wrapped(ya, yb, _):

<ipython-input-4-8423177548fe> in fun(x, y)
     23     return array
     24
---> 25   m2=calc() # m2 is an 1-D array and is equal to F(y)
     26   rhs= m2/((t-m1)**2) # rhs contains the RHS of the differential equation
     27   return np.vstack([y[1],y[2],y[3],rhs])

<ipython-input-4-8423177548fe> in calc()
     18        return gamma*(var)+var**(0.5)+var**(3)+m1[i]
     19
---> 20      sol= root(fun2,x0=0.00001,method='krylov',tol=1e-12)
     21      array[i]=sol.x
     22

/usr/local/lib/python3.6/dist-packages/scipy/optimize/_root.py in root(fun, x0, args, method, jac, tol, callback, options)
    197         sol = _root_nonlin_solve(fun, x0, args=args, jac=jac,
    198                                  _method=meth, _callback=callback,
--> 199                                  **options)
    200     else:
    201         raise ValueError('Unknown solver %s' % method)

/usr/local/lib/python3.6/dist-packages/scipy/optimize/_root.py in _root_nonlin_solve(func, x0, args, jac, _callback, _method, nit, disp, maxiter, ftol, fatol, xtol, xatol, tol_norm, line_search, jac_options, **unknown_options)
    300                                   line_search=line_search,
    301                                   callback=_callback, full_output=True,
--> 302                                   raise_exception=False)
    303     sol = OptimizeResult(x=x)
    304     sol.update(info)

/usr/local/lib/python3.6/dist-packages/scipy/optimize/nonlin.py in nonlin_solve(F, x0, jacobian, iter, verbose, maxiter, f_tol, f_rtol, x_tol, x_rtol, tol_norm, line_search, callback, full_output, raise_exception)
    277
    278     dx = np.inf
--> 279     Fx = func(x)
    280     Fx_norm = norm(Fx)
    281

/usr/local/lib/python3.6/dist-packages/scipy/optimize/nonlin.py in <lambda>(z)
    273
    274     x0 = _as_inexact(x0)
--> 275     func = lambda z: _as_inexact(F(_array_like(z, x0))).flatten()
    276     x = x0.flatten()
    277

<ipython-input-4-8423177548fe> in fun2(var)
     16     for i in range(10) :
     17      def fun2(var):
---> 18        return gamma*(var)+var**(0.5)+var**(3)+m1[i]
     19
     20      sol= root(fun2,x0=0.00001,method='krylov',tol=1e-12)

IndexError: index 9 is out of bounds for axis 0 with size 9

Comment: Please give the stack trace so that people can see where the error is happening.
Comment: @alaniwi, I havd added the stack trace
Answer: In the function
  def calc(): # this function calculates F(y) at all the mesh points and finally returns an array
    for i in range(10) :
        def fun2(var):
            return gamma*(var)+var**(0.5)+var**(3)+m1[i]

you are iterating over m1 inside the nested function with i but in the above code on the line
m1=y[0] # m1 is an 1-D array

you define this value as a scalar (or a 1D-array) which cannot be iterated over.
This gives you the error you are observing; for the 1D-array you have defined, m1, any index greater than 0 is out of range for this 1D-array.
This should give you what you need to change your code so that it works.
I won't complete this for you, because we don't know what you need done, but I expect that defining a function again and again in a for loop is unnecessary.
Comment: m1 is an 1d array of size 10 because y[0] is an 1d array of size 10.
Comment: And the error suggests that the array is of size 9 which is anyway greater than 0.


one to one relationship in Phalcon model not returning object

Question: I have two models in Phalcon .I am getting the model object of the first model using the Placon Model::find().
The problem is I cannot get model object which has an one to one relation with the first model.
I have tried everthing given in Phalcon tutorial.
Gave hasone in first Model on initialize
 public function initialize()
 {
     $this->hasOne("emp_id", "Employee", "emp_id");
 }

Where emp_id is the primary key of Employee table and Foreign key in Salary table, which is my second model.
Answer: For that you have to specify the relation between 2 models, and how those two models are related. To get one-to-one relation object you can use hasOne relation  or hasMany for many-to-many relations.
  $this->hasOne('emp_id', '(path to your model)', 'emp_id', array(
                'alias' => 'employeeId',
                'reusable' => true
            ));

Ex: if you have a Employee object and you need access the one-to-one related objects you must use Employee.employeeId to get the related object.


R: How does one perform multiple classification in data with many levels?

Question: I am trying to classify invoice data into UNSPSC categories. I have 2.2 million invoices and there are around 250 UNSPSC categories the data needs to be divided into. I have labeled data divided into training and test data sets.
The data has the following structure:
<code>UNSPSC-code    Product        Price    Seller
809080         Apple Juice    10       Super Brugsen
802830         iPhone         6000     Electronics Center
902310         Hat            40       Funny Hats Inc
</code>
For each variable I have many levels (1000-12000), thus it is not feasible to use random forests for classifications. Random Forests have a limit of around 54 levels in current implementations in R. I also tried support vector machines, but they have no way of handling the memory requirements.
Is there a classification algorithm appropriate for this problem that does not have the same limitations as RF and SVM? I am currently considering doing a KNN search using a custom distance measuring algorithm, but I probably again run into the problem of memory, as KNN will require a distance matrix.
Answer: I ended up writing a custom distance function and to do a custom Nearest Neighbour Search. It worked out pretty well with a 96 % accuracy.
Concept for distance calculation:
<code># Vectors to calculate distance between
Product        Price    Seller
Apple Juice    10       Super Brugsen
iPhone         6000     Electronics Center
Samsung S7     5000     Electronics Center

# Distance "Apple Juice" vs "iPhone"
sqrt(sum(c(1,5080,1)))
5008

# Distance "iPhone" vs "Samsung S7"
sqrt(sum(c(1,1000,1)))
1000
</code>
Thus the nearest neighbout for the iPhone would be the Samsung S7. Ofcause I have normalized the prices to run from 0 to 1.


Which distribution or process should be used for wearout reliability modeling?

Question: When modeling the reliability of a system, it is usual to use exponential distribution to model errors that occur randomly throughout the system's useful lifetime (the middle part of the well-known bathtub curve).
When modeling the wearout/aging of the system when it approaches the end of its lifetime, what distribution or processes can be used?
My intention is to use NHPP to model minimal repairs and then model imperfect repairs. However, it is not clear in the literature what kind of distributions I can use and how I can obtain my $w(t)$ ROCOF.
Thank you in advance.
Answer: I'm not familiar with your kind of modelling, but I know the Weibull distribution is used to describe system failures/reliabilities over time due to wearout.
https://en.wikipedia.org/wiki/Weibull_distribution#Applications
Comment: Thanks for the tip. I've seen that, but the point is how can it be used? It is hard to find usefull examples.


Why final classes cannot be overridden in java?

Question: I was asked about the reason of why a final class cannot be overridden. I tried to explain that it is more of design approach where by you don't want your class to be extended or methods to be overridden and a final class also helps to make an object immutable (though there are more steps to be done rather than just declaring the class as final).
However I would like to know if there is more to thought process behind declaring a class as final or the fact that it cannot be overridden?
Comment: It's a good way how to piss off people that would like to extend your class for whatever reason and force them to copy&paste the code… :P
Comment: This may be a better fit for Programmers.SE
Comment: That's exactly what the `final` keyword means there.
Comment: Performance issue too. A compiler may inline methods that otherwise could have been overriden; thus being able to remove null tests and such.
Comment: If it is a class, it should be "extended" not "override"...
Answer: Because them's the rules; It's a part of the design of the language.
http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-184.108.40.206
As a designer you say "my class is not suitable for inheritence"; Java honours this by explicitly preventing someone from doing so.
Answer: final methods can't be overriden, because that's what final is designed to do: it's a sign saying "do not override this".
From Wiki

A final method cannot be overridden or hidden by subclasses. This is used to prevent unexpected behavior from a subclass altering a method that may be crucial to the function or consistency of the class.
A common misconception is that declaring a class or method as final improves efficiency by allowing the compiler to directly insert the method wherever it is called (see inline expansion). But because the method is loaded at runtime, compilers are unable to do this. Only the runtime environment and JIT compiler know exactly which classes have been loaded, and so only they are able to make decisions about when to inline, whether or not the method is final.
Comment: The question is about final classes, not final methods.
Comment: @pablosaraiva class's cannot be  override, it should be extended... his question abt override so I answered as final methods...
Answer: Final class cannot be extended because Java compiler will not allow it, because Java compiler follows the rules defined by Java Language Specification which does not allow it.
Answer: A final class is a class that can't be extended, thats the reason u cannot override the final class
it is also used  to make the class immutable
and one good advantage of defining class as final that it improves JVM performance
see this
Comment: It's still confusing.  Immutability has nothing to do with this, and `final` does not implicitly make a class immutable.
Comment: You're confusing different uses for the `final` keyword.
Comment: @SLaks ya I have corrected
Comment: @SLaks My friend but final can be used to make the class immutable
Comment: Not here, and only carefully.


Converting from Swift string to const char*

Question: I'm trying to pass a const char * to an old C library converted from a Swift string in Swift.
This is the C function I'm calling:
artnet_node artnet_new(const char *ip, int verbose) { ...

how can I convert a Swift string to this const char type? It works when I pass ipAddress like this:
internal var ipAddress = "192.168.1.43"

but dit does not work when I pass it like this
internal var ipAddress:String = "192.168.1.43"

I need this in a function where I need to specify the type:
internal func setupArtnode(ip:String) -> Int{

I tried using AnyObject instead of String but that doesn't work either.
Thanks.
Comment: Please add clarification on what doesn't work- compilation or execution, and any associated error messages.
Answer: You should be able to pass a String directly to a C function expecting const char * and it will be automatically converted to a null-terminated UTF-8 string:
let string = "string"
let node = artnet_new(string, 1)

See Interacting with C APIs  for more information.  Here is the relevant excerpt:

When a function is declared as taking an UnsafePointer argument,
  it can accept any of the following:

A String value, if Type is Int8 or UInt8. The string will automatically be converted to UTF8 in a buffer, and a pointer to that
  buffer is passed to the function.
Comment: for some reason the function wont take the argument and takes the default value, i updated the question with some more info
Comment: your quote got me to use UnsafePointer which seemed to work, I added my working code. thanks!!
Answer: Not sure why but this code is working. This passes a string to a C function expecting a const char* which seems to be the same as a unsafePointer.
internal func setupArtnode(ipAddress:String) -> NSInteger{
    let cString = self.ipAddress.cString(using: String.defaultCStringEncoding)!
    let newString:String = NSString(bytes: cString, length: Int(ipAddress.characters.count), encoding:String.Encoding.ascii.rawValue)! as String
    let key2Pointer = UnsafePointer<Int8>(newString)

    node = artnet_new(key2Pointer, Int32(verbose))     // VERBOSE : true(1) , false(0)
...

Answer: Simple way for Swift 3
var ipAddress: String = "192.168.1.43"
var verbose: Int = 1
artnet_node artnet_new((ipAddress as NSString).utf8String, verbose)

Comment: While using sqlite3 API sqlite3_bind_text() with swift, I was seeing memory corruption and weird results if the String was directly passed. `(ipAddress as NSString).utf8String` fixed this.
Answer: You didn't specify what your Swift array contains. In any case, you need to convert your Swift array to an array of Int8:
let str = "Hello world"
let cArray = str.cString(using: .utf8)

artnet_new(cArray, 1)

Comment: I'm sorry i mistyped, I'm trying to change a single string to a const char :s, edited the question


Neural Networks interaction between input variables

Question: I want to build a regression NN model that predicts Y variable but takes into account the interactions between input variables (x1,x2,x3,x4,x5) without explicitly specifying them. My current NN model implementation has:

5 input variables (x1,..x5)
1 hidden layer with 5 neurons
1 output (Y)
logistic activation function

My question is: Can this architecture capture the interactions (if exist) or do I need an extra layer for this?
Thank you!
Answer: Think of a neural network as an additive model: Without the hidden layer, you already achieve the same as a regression model without interactions, as the network can learn the weight of each of the individual inputs, which is just like estimating the coefficients of the input variables in a regression model.
A single hidden layer can learn how simple combinations of the input relate to the output. Think of this as a regression model with first-order interactions (except that it is not limited to linear combinations). So yes, your model should already be able to capture interactions. However, with only 5 nodes in the hidden layer, it may not capture many different combinations, if there are indeed many different interactions that affect the outcome. Whether this is likely is highly dependent on what kind of data these are and what kind of outcome you are predicting.
Adding more layers would allow the network to make further abstractions from those made in the first hidden layer. This is analogous to higher order interactions in a regression model.
Comment: Perfect answer.. I was editing an answer saying the same thing about regression similarity
Comment: @nba2020. You're welcome! Good questions are at least as valuable as good answers.
Comment: This is actually completely wrong. As I understand it, additive models cannot capture interaction effects as those require a multiplicative network.
Comment: Thank you so much @Frans Rodenburg! Helps me so much in my current project :)
Comment: See also: https://stats.stackexchange.com/questions/279525/how-do-neural-networks-model-interaction-terms
Comment: @FransRodenburg I'm interested in your thoughts about PascalVKooten's comment about additive vs multiplicative for modeling interactions.


Como colocar uma gif antes de exibir a página do site

Question: Gostaria de colocar uma gif de loading no meu site. Quando eu acessar a página antes de abrir o site, primeiro abriria o gif e ficaria por 1,5 segundos mais ou menos. Isso é possível?
Obs: Quero algo mais ou menos assim http://ivang-design.com/chronos/videoyt/
Comment: http://pt.stackoverflow.com/questions/8581/mostrar-gif-enquanto-p%C3%A1gina-carrega
Comment: possível duplicata de [Como aplicar um efeito de Loading antes do carregamento da página?](http://pt.stackoverflow.com/questions/18869/como-aplicar-um-efeito-de-loading-antes-do-carregamento-da-p%c3%a1gina)
Comment: @Lucas amigo entao esse jeito que voce mandou no link nao serve para min quero assim http://ivang-design.com/chronos/videoyt/
Comment: Você não escolheu nenhuma resposta. Nenhuma o satisfaz?
Answer: Fazer isso é extremamente simples e pode ser feito tanto pelo tempo de 1,5 segundos, como apenas desaparecer quando concluir o carregamento.

O evento setTimeout define que após o tempo "1500" milisigundos = 1,5 segundos, a imagem ira desaparecer. Pois ao declarar que o objeto (pelo seu id) "loader", recebe o método style, o qual possui o parâmetro display com seu atributo 'none', que é invisível.
Ou pelo carregamento mesmo:

O evento window.onload executara a função a ela atribuída.
Comment: Pode atribuir a imagem style="position:fixed;z-index:10000;left:44%;top:43%;", logo após o ID para posiciona-lo no centro e acima dos objetos. dependendo do tamanho da imagem e/ou do navegador isso pode variar. isso é um exemplo, precisa testar e validar com sua imagem se a posição esta adequada.
Answer: O plugin que você quer é o Royal Pre Loader.
Uma dica que eu dou é pesquisar no código do site, no meu caso uso o Chrome, eu entro no Dev Tools, vou na aba Source e procuro nas pastas relacionadas com Javascript, no seu caso está na pasta "/js".
Os outros navegadores também possuem esse recurso para inspecionar elementos, então sempre quando achar um efeito diferente, antes de tudo dá uma olhada no código do site.
Answer: Faça sem recursos externos e com um efeito fade:
HTML

CSS
.preload{
    position: fixed;
    z-index:99999;
    top:0; left:0;
    width:100%; height:100%;
    opacity:1;
    background-color:#000;
    background-image:url('../images/721.gif');
    background-position:50% 50%;
    background-repeat:no-repeat;
}

JS
window.onload = function(){
    var div = document.getElementById('preload');
    preload(div, 50);
};
function preload(el, interval){
    var op = 1;
    var timer = setInterval(function () {
        if (op <= 0.1){
            clearInterval(timer);
            el.style.display = 'none';
            el.className = '';
        }
        el.style.opacity = op;
        op -= op * 0.1;
    }, interval);
}

Answer: Existe um opção em JQuery bem simples.
Utilizando dos exemplos já citados:
JQUERY
$(document).ready(function() {
  setTimeout('
              $("#preload").fadeOut(100);
  ', 1500);
});

Quando a página for completamente "lida" a div desaparecerá.
O fadeOut(100) fará com que a div desapareça de forma "suave" em 100 milissegundos.
Veja mais acerca do fadeOut aqui: http://api.jquery.com/fadeout/
A contagem do setTimeout também é em milissegundos, então se você quer 1,5 segundos, basta multiplicar por 1000, no caso 1500.
CSS
body {
  background: #cccccc;
}
.preload {
  position: fixed;
  z-index: 99999;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 1;
  background-color: #fff;
  background-image: url('https://38.media.tumblr.com/bec5933eea5043acf6a37bb1394384ab/tumblr_meyfxzwXUc1rgpyeqo1_400.gif');
  background-size: 298px 298px;
  background-position: center;
  background-repeat: no-repeat;
}

No background-position basta colocar center. O z-index: 99999, fará com que a div sempre esteja acima de todos os outros elementos da página contanto que eles possuam um z-index inferior a "99999".
HTML

Veja o resultado aqui: http://jsfiddle.net/SamirChaves/6ns0grm0/2/


Integral $\lim_{k\rightarrow\infty}\int_\pi^{2\pi}{\sum_{n=1}^k}\left(\sin x\right)^n\ \text{dx}$

Question: I need help with this integral:
$$I=\lim_{k\rightarrow\infty}\int_\pi^{2\pi}{\sum_{n=1}^k}\left(\sin x\right)^n\ \text{dx.}$$
The integrand graph looks like this:

I have rewritten the integral as $$I=-\int_\pi^{2\pi}\frac{\sin x}{\sin x-1}\ \text{dx}$$
But I'm not sure how to move forwards from here.
Answer: $\newcommand{\angles}[1]{\left\langle\,{#1}\,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\Li}[1]{\,\mathrm{Li}_{#1}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\ol}[1]{\overline{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
I & = \color{#f00}{-\int_{\pi}^{2\pi}
{\sin\pars{x} \over \sin\pars{x} - 1}\,\dd x} =
\int_{\pi}^{2\pi}{\sin\pars{x} + \sin^{2}\pars{x} \over \cos^{2}\pars{x}}\,\dd x
\\[5mm] & =
\int_{\pi}^{2\pi}{\sin\pars{x} \over \cos^{2}\pars{x}}\,\dd x
+ \int_{\pi}^{2\pi}\tan^{2}\pars{x}\,\dd x =
\int_{\pi}^{2\pi}{\sin\pars{x} \over \cos^{2}\pars{x}}\,\dd x
+ \int_{\pi}^{2\pi}\sec^{2}\pars{x}\,\dd x - \int_{\pi}^{2\pi}\dd x
\\[5mm] &=
\left.{1 \over \cos\pars{x}} + \tan\pars{x} - x\,\right\vert_{\ \pi}^{\ 2\pi} =
\color{#f00}{2 - \pi}
\end{align}
Answer: Hint
$$ -\int \limits^{2\pi }_{\pi }\frac{\sin \left( x\right) }{\sin \left( x\right) -1} dx= -\int \limits^{2\pi }_{\pi }\frac{1}{\sin \left( x\right) -1} dx-\pi $$
Comment: Could you explain how you came about to this?
Comment: @WillSherwood the integral can be written like
$$ -\int \limits^{2\pi }_{\pi }\frac{\sin \left( x\right) -1+1}{\sin \left( x\right) -1} dx=-\int \limits^{2\pi }_{\pi }\frac{1}{\sin \left( x\right) -1} dx-\int \limits^{2\pi }_{\pi }1 dx $$


How come Netlify CMS on localhost is not working?

Question: I'm from Taiwan and not good at English, but I'll try my best to explain my question.
I use Netlify CMS to build my Hugo website.
Everything runs well, but when I want to change and check if the CMS's configuration and style is okay, I always need to push my repository to Github, which is disturb me a lot.
So I tried to use local_backend: true in admin/config.yml, then used this command: npx netlify-cms-proxy-server.
then the window showed:
info: Netlify CMS File System Proxy Server configured with C:\Users\june.wu\Documents\GitHub\house-blog-hugo-cms
info: Netlify CMS Proxy Server listening on port 8081

It looked it ran successfully on localhost:8081.
But when I type localhost:8081 in browser it showed: Cannot GET /
How can I solve this problem?
Comment: Netlify CMS is dead
Answer: I can confirm what said in the previous answer. Run npx netlify-cms-proxy-server and go to localhost:8080/admin or try also localhost:8080/admin/ (with ending slash). It should work if you are using default 8080 port.
Ignore that CMS is on port 8081 as said in the script log
Answer: for anyone looking at this in and still finding it unclear, as said in the docs you need to go to your regular development server based on the SSG (static site generator) that you are using once you have started both the NetlifyCMS and SSG dev servers. See point 5 in the beta features docs here.
You are not supposed to try visit the NetlifyCMS 8081 default port to use the CMS locally.
I have also seen behaviour mentioned by a few people that it only works with a / at the end of the path. So for example if using Astro as your SSG (which uses the port :3000 for it's dev server) you should try both:

http://localhost:3000/admin/
http://localhost:3000/admin

Although I have been having issues with the NeltlifyCMS dev server with Astro still...


Mapping an oracle number type in Hibernate

Question: I have a column (OCPR_TIMESTAMP) in oracle of type NUMBER(18) and want to select this column using hibernate.
I have the hibernate mapping file mapped as..
<property name="timestamp" column="OCPR_TIMESTAMP" type="java.lang.Double" />

and the timestamp property in my VO as a Double type.
When I select a record, the timestamp is always returned as null.
An example of the data stored in this column is:
7.18575602814979E15

I have tried various different types in the hibernate mapping, any ideas?
Thanks
Comment: The data point you showed us should be within range of Java's `double` type.  Can you show us any relevant Java code?
Answer: Apologies - the persistence method being used was not hibernate, this was a web service using jdbc template so column needed adding to query string. Thanks for your response anyway Tim.


Why can we prove that this piecewise function is continuous at $x = 0$?

Question: I have this piecewise function
$f(x) = \begin{cases} \frac{\sin(-8x)}{8x} & x < 0
\\ (2x + 9k - 7)  &  x \ge 0 \end{cases}$
Now the formula for calculating the limit of $\frac{\sin(x)}{x}$ is
$\frac{\sin(x)}{x} = 1$
So in this case, you would divide $-8$ by $8$, to show that the limit of the first function is $-1$
However, I have a problem with this.
To solve if two functions are continuous, you have to determine that the limit of the first function is equal to the limit of the second function. This is typically done, by setting the limit equal to where they would converge, in this case at $0$.
Here is the formula
$\lim \limits_{x \to a- } f(x)= \lim \limits_{x \to a+ } g(x)$
This would make the denominator for the first function $0$, and you can't divide by $0$.
So why does the first function evaluate to $-1$ instead of undefined.
Comment: Don't forget that as $x$ goes to zero, $\sin x$ also goes to zero. This is why you don't (necessarily) have a division by zero problem.
Comment: If a limit were simply a matter of evaluating (plugging in x) there'd be no point.  We'd just evaluate functiins.  But we use limits when functions aren't "nice" to determine how functions behave near trouble points.  So f (x) tends toward -1 when x tends toward 0, is in no way in conflict with f (x) going batshit crazy and undefined *at* 0.
Comment: There is no reason to assume lim f (x) = f (x).  In fact it's because there are "trouble points" where f (x) doesn't "behave properly" that we invented limits.  f (x) is undefined.  But lim f (x) = -1 $\ne $ f (x).  That's a perfectly reasonable and consistent statement.
Comment: https://proofwiki.org/wiki/Limit_of_Sine_of_X_over_X/Geometric_Proof
Answer: So your question basically boils down to:

Why the value of $\lim_\limits{x\to 0}\frac{\sin x}{x}$ is $1$ and not
  $\infty$?

For that answer, I am putting this answer of mine from this question:
From the Maclaurin series expansion of $f(x)=\sin x$,we have that
$$\sin x=x-\frac{x^3}{3!}+\frac{x^5}{5!}-\ldots$$
or, considering $x\not = 0,$ $$\frac{\sin x}{x}=1-\frac{x^2}{3!}+\frac{x^4}{5!}-\ldots$$
And hence by using the notion of uniform convergence of a power series, it can be said that
$$\lim_\limits{x\to 0} \frac{\sin x}{x} = 1$$
Thus at $x=0$, the function $f(x)=\frac{\sin x}{x}$ has R.H.L.=L.H.L.=$1 \not = f(0)$
So at $x=0$, $f(x)$ has removable discontinuity.
Hence to make the function continuous at $x=0$, $f(0)$ is defined to be $1$.
So the actual function should be like
$$f(x)=\begin{cases}\frac{\sin x}{x} &  x\not = 0 \\ \, \, \,  1 &  x=0\end{cases}$$
Answer: Another way to calculate $$\lim_{x \to 0}\frac{\sin(x)}{x} = 1$$ is to use l'Hôpital's rule, which states, barring certain conditions, that: $$\lim_{x \to c}\frac{f(x)}{g(x)} = \lim_{x \to c}\frac{f'(x)}{g'(x)}$$ which means $$\lim_{x \to 0}\frac{\sin(x)}{x} = \lim_{x \to 0}\frac{\cos(x)}{1} =\lim_{x \to 0}\cos(x) =\cos(0) = 1$$


am I able to use android serives in the first time I run my application

Question: I want to get event when I use my program for the firt time so I decided to use this service
<code>public class PackageChangeReceiver extends BroadcastReceiver {

    Context context;

    @Override
    public void onReceive(Context ctx, Intent intent) {
}}
</code>
and in the mainfest
<code> <receiver android:name=".PackageChangeReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.PACKAGE_REMOVED" />
                <action android:name="android.intent.action.PACKAGE_REPLACED" />
                <action android:name="android.intent.action.PACKAGE_ADDED" />
                <data android:scheme="package" />
            </intent-filter>
        </receiver>
</code>
but this services don't work in the fist time I install my application , how can I make it run in the first time ?or it is not possible to do that ?
I have to update the application from eclipse second time to make this service working , what is the problem.
when does android system make its services available to use , I heart onetime that I should run one of my activity to make the service available ,is it true?
Answer: Starting Android 3.1, any app that wishes to receive broadcasts must have had one of its UI components (i.e an Activity) run at least once before Android sends any broadcasts to it. This is done for security reasons, to prevent malicious apps from auto launching.
Comment: Eclipse doesn't really replace a package. It updates your existing install. If you've run anything before the update, then Android will continue to give you broadcasts.


Dynamically display content based on web address after '/'?

Question: I am wondering if this is possible with PHP, or if not with ASP since it's relatively similar and I could pick it up quickly.  Let's say I have a text input for a user to search a database; as an alternative to using the text field I want a user to be able to go to 'www.examplesite.com/SEARCHTERM'.  Is this possible?  I've seen it done, but I can't figure out how.  Thanks!
Comment: This can be done with PHP, but it's simpler and easier doing it through the server configuration. What server are you using? IIS or Apache?
Comment: The thing you are looking for is called "URL rewriting."  It's done differently on every platform.  An answer that would be valid for ASP Classic on IIS will not work for PHP on Apache (or maybe not even PHP on IIS), and vice versa.
Comment: Also can do with $_GET ..
Answer: You might have to look in to url rewriting based on the server you use.
URL Rewritting
Answer: Yes that's easily possible. For example if you have apache  server then you can enable mod rewrite and write one rule to redirect all such requests to your script in a variable and it will then handle accordingly
Answer: This can be done:
1) Using $_GET
www.examplesite.com/?SEARCH=SerachTermHere

In the page you can get the search variable with $_GET['SEARCH']
2) Using URL Rewritting
Answer: It is possible, you have two options.

Using URL Rewritting in your server configuration.
Using $_GET global. Everything in URL after your actual page address is available through $_GET.

This goes a bit beyond your question but might prove to be very useful. Even though it is a framework, you might want to look at Symfony 2 routing for ideas how to implement it. Specifically at "Under The Hood" section. You can even explore their routing code on github. Applications made in it have exactly the form you are searching for (content displaying based on $_GET data).


Computing the probability that at least four telephone lines are not in use.

Question: A mail-order computer business has six telephone lines. Let $X$ denote the number of lines in use at a specified time. Suppose the pmf of $X$ is as given in the accompanying table:
 $p(0)=.10$, $p(1)=.15$, $p(2)=.2$, $p(3)=.25$, $p(4)=.2$, $p(5)=.06$, $p(6)=.04$
Calculate the probability of $\{\text{at least four lines are not in use}\}$.
I interpreted the problem as find $P(4 \leq X \leq 6)$ but I'm not getting the correct answer. Can someone help me see what I'm doing wrong?
Answer: We want $P(0 \le X\le 2)$. Remember it said not in use.
Comment: Yeah but why wouldn't we include 3? so that X is between and including 0 and 3?
Comment: @user23793: If there are six total lines and four of them are not in use, what's the maximum number that could be in use?
Comment: Sigh* thank you for that epiphany.
Answer: To help you understand it, think of this
$$
P(0) = P(\text{ 6 lines not in use} )\\
P(1) = P(\text{ 5 Lines not in use })\\
P(2) = P(\text{ 4 Lines not in use })
$$
Then
$$
P(\text{ 6 Lines not in use })+P(\text{ 5 Lines not in use })+P(\text{ 4 Lines not in use })= \\
P(0)+P(1)+P(2)=0.1+0.15+0.2=0.45
$$


Sair do laço For quando digitar a nota 1

Question: Esse código que estou escrevendo, onde a opção 1 o usuário digita notas que deseja inserir num caixa eletrônico onde era pra parar quando a nota 1 fosse inserida.
Na opção 2 é pra inserir o valor do saque e esse saque só usará as notas que foram inseridas.
Na opção 0 o programa se encerra.
Alguma maneira de eu conseguir injetar essa condição de a nota 1 encerrar o laço?
public static void main(String[] args) {
        // TODO Auto-generated method stub
        String menu = "* MENU OPÇÕES * " + "\n" + "1 - Notas Existentes" + "\n" + "2 - Saque" + "\n" + "0 - Sair" + "\n";
        int [] possiveis = new int [7];
        int work = 1;
        int div1=0,div2=0,div3 = 0,div4 = 0,div5 = 0,div6 = 0,div7 = 0;
        int resto1=0,resto2=0,resto3 = 0,resto4 = 0,resto5 = 0,resto6 = 0,resto7 = 0;
        while (work!=0) {
            System.out.println(menu);
            Scanner entrada = new Scanner (System.in);
            System.out.println("Digite a opçao desejada: ");
            int opcao = entrada.nextInt();
            if (opcao==1) {
                for (int i=0;i<possiveis.length;i++) {
                    System.out.println("Digite as notas disponiveis");
                    possiveis[i] = entrada.nextInt();
                }
                for (int i =0; i<possiveis.length;i++) {
                    if(possiveis[i]!=1) {
                        System.out.println(possiveis[i]);
                    }else if (possiveis[i]==1 ){
                        System.out.println(possiveis[i]);
                    }
                    work=1;
                }
            }else if (opcao==2) {
                System.out.println("Digite o valor do saque");
                int saque = entrada.nextInt();
                if ((possiveis[0]>0)|| (possiveis[1] >0) || (possiveis[2] >0) || (possiveis[3] >0) ||(possiveis[4]>0) || (possiveis[5]>0) || (possiveis[6]>0)){
                div1 = saque / possiveis[0];
                resto1 = saque % possiveis[0];
                if (resto1>0){

                div2 = resto1 / possiveis[1];
                resto2 = resto1 % possiveis[1];}
                if (resto2>0){
                div3 = resto2 / possiveis[2];
                resto3 = resto2 % possiveis[2];}
                if (resto3>0){
                div4 = resto3 / possiveis[3];
                resto4 = resto3 % possiveis[3];}
                if (resto4>0){
                div5 = resto4 / possiveis[4];
                resto5 = resto4 % possiveis[4];}
                if ( resto5>0){
                div6 = resto5 / possiveis [5];
                resto6 = resto5 % possiveis [5];}
                if (resto6>0){
                div7 = resto6 / possiveis [6];
                resto7 = resto6 % possiveis [6];}
                }

                if (div1!=0) {
                    System.out.println("Total de notas de  " + possiveis[0] + " = " + div1);

                }
                if (div2!=0) {
                    System.out.println("Total de notas de  " + possiveis[1] + " = " + div2);

                }
                if (div3!=0) {
                    System.out.println("Total de notas de  " + possiveis[2] + " = " + div3);
                }
                if (div4!=0) {
                    System.out.println("Total de notas de  " + possiveis[3] + " = " + div4);
                }
                if (div5!=0) {
                    System.out.println("Total de notas de  " + possiveis[4] + " = " + div5);
                }
                if (div6!=0) {
                    System.out.println("Total denotas de  " + possiveis[5] + " = " + div6);
                }
                if (div7!=0) {
                    System.out.println("Total de notas de  " + possiveis[6] + " = " + div7);
                }
                work=1;
            }else if (opcao==0) {
                work=0;
            }else {
                System.out.println("Opcão invalida");
            }

        }
    }

Comment: Usando um `break`?
Comment: Mas no caso era pra parar de digitar as notas depois de digitar 1,usando o break só vai resolver a questão da impressão de notas
Comment: Vc quer interromper o primeiro `for` (o que tem `possiveis[i] = entrada.nextInt()`)? Se for isso, pode colocar o `break` dentro do `for`, que somente o `for` é interrompido e o `while` continua rodando. Outra coisa, no segundo `for` vc faz: se o valor é diferente de 1, imprime, e se for igual a 1, também imprime, qual é o objetivo disso?
Comment: Realmente esse segundo for foi erro lógico meu haha,obrigado pelo toque
Answer: Pelos diversos comentários, dá a entender que você quer interromper este laço, quando for digitado 1:
for (int i=0;i<possiveis.length;i++) {
    System.out.println("Digite as notas disponiveis");
    possiveis[i] = entrada.nextInt();
}

Pois bem, basta usar o break:
for (int i = 0; i < possiveis.length; i++) {
    System.out.println("Digite as notas disponiveis");
    int valor = entrada.nextInt();
    if (valor == 1) {
        break;
    }
    possiveis[i] = valor;
}

Esse break só interrompe o for, e o while continua rodando normalmente (já que era essa a sua preocupação, segundo este comentário).
O problema é que, ao interromper o for, os elementos não inicializados terão o valor zero. E dependendo das notas e do valor do saque, você pode acabar dividindo por zero, o que causa um ArithmeticException.

Bom, vou aproveitar para sugerir algumas alterações no seu código.
Você está criando um Scanner dentro do while, o que quer dizer que a cada iteração é criado uma nova instância. Mas não precisa disso, pode criar apenas um no início (antes do while) e usá-lo em todo o programa.
O seu segundo for está bem estranho:
for (int i = 0; i < possiveis.length; i++) {
    if (possiveis[i] != 1) {
        System.out.println(possiveis[i]);
    } else if (possiveis[i] == 1) {
        System.out.println(possiveis[i]);
    }
    work = 1;
}

Se o valor for diferente de 1, imprime, e se for igual a 1, também imprime. Não sei o que você tentou fazer aqui, se foi algum erro de digitação ou outra coisa, mas do jeito que está não faz sentido. A atribuição de work = 1 também é feita várias vezes, o que é redundante. Pelo que vi, essa linha pode ficar fora do for, logo depois dele.
Outro ponto é que você não precisa da variável work, basta fazer while (true) (um loop infinito) e interrompê-lo com break quando a opção for zero:
while (true) {
    System.out.println(menu);
    System.out.println("Digite a opçao desejada: ");
    int opcao = entrada.nextInt();
    if (opcao == 1) {
        ...
    } else if (opcao == 2) {
        ...
    } else if (opcao == 0) {
        break; // <---- AQUI
    } else {
        System.out.println("Opcão invalida");
    }
}

Esse break acima interrompe o while, e ele não se confunde com o break que colocamos dentro do primeiro for. Tem quem critique o uso de break, mas sinceramente, criar essa variável work eu acho pior.
Sugiro também quebrar cada funcionalidade em um método próprio. Por exemplo:
public void lerNotas(Scanner entrada, int[] possiveis) {
    for (int i = 0; i < possiveis.length; i++) {
        System.out.println("Digite as notas disponiveis");
        int valor = entrada.nextInt();
        if (valor == 1) {
            break;
        }
        possiveis[i] = valor;
    }
    for (int i = 0; i < possiveis.length; i++) {
        System.out.println(possiveis[i]);
    }
}

public void saque(Scanner entrada, int[] possiveis) {
    System.out.println("Digite o valor do saque");
    int saque = entrada.nextInt();
    int divs[] = new int[possiveis.length];
    int resto = saque;
    for (int i = 0; i < divs.length; i++) {
        if (possiveis[i] != 0) {
            divs[i] = resto / possiveis[i];
            resto = resto % possiveis[i];
            if (resto == 0)
                break;
        }
    }
    for (int i = 0; i < divs.length; i++) {
        if (divs[i] != 0) {
            System.out.println("Total de notas de  " + possiveis[i] + " = " + divs[i]);
        }
    }
}

Repare que mudei o seu algoritmo de saque para usar loops. Não conferi se ele funciona para todos os casos possíveis, só peguei a sua lógica e transformei em um loop. De qualquer forma, se pesquisar no site, provavelmente encontrará vários algoritmos para este problema (vale lembrar que o seu algoritmo considera que existe uma quantidade ilimitada de notas - se quer considerar a quantidade de cada nota, aí é outro algoritmo e já foge do escopo da pergunta).
E no segundo for, retirei o if/else que não fazia sentido. Agora é só mudar o while para usar os métodos acima:
Scanner entrada = new Scanner(System.in);
String menu = "* MENU OPÇÕES * " + "\n" + "1 - Notas Existentes" + "\n" + "2 - Saque" + "\n" + "0 - Sair" + "\n";
int[] possiveis = new int[7];
while (true) {
    System.out.println(menu);
    System.out.println("Digite a opçao desejada: ");
    int opcao = entrada.nextInt();
    if (opcao == 1) {
        lerNotas(entrada, possiveis);
    } else if (opcao == 2) {
        saque(entrada, possiveis);
    } else if (opcao == 0) {
        break;
    } else {
        System.out.println("Opcão invalida");
    }
}

Answer: Para forçar a saída de um while basta usar a palavra reservada break. Exemplo:
while(condicao){
  if (opcao == 1) {
  // seu codigo aqui
  break;
  }
}

Comment: Mas no caso eu n posso sair do while,ele tá sendo usado como menu do meu programa,eu queria era parar de digitar dentro do for quando inserir a nota 1


How do I fetch username so that I can put it in the page title using useLayoutEffect?

Question: I am writing a simple app (in react native), where when the user navigates to the profile page the title of the page is the user's user name. Hence why I am using useLayoutEffect to set the options. I have something like:
useLayoutEffect(() => {
      props.navigation.setOptions({
        title: props.route.params.name,
      });
  }, [props.route.params.name]);

which works fine. Obviously, when I navigate to the "Profile" page, I have something like
<Tab.Screen
        name="My Profile"
        component={ProfileScreen}
        listeners={(props) => ({
          tabPress: (event) => {
            props.navigation.navigate("Profile", {
              uid: currentUser.id
              name: currentUser.name,
            });
          },
        })}
      />

Which again works fine. However What if I navigate to some other profile? Do I always have to use
props.navigation.navigate("Profile", {
                  uid: user.id
                  name: user.name,
                });

That is to pass both user's id AND user's name to navigate to the profile page. To me that seems like unnecessary. Ideally I would like to pass user's id only (when navigate to the profile page) and from there to fetch user's name. Something like this:
props.navigation.navigate("Profile", {
                      uid: user.id
                    });

and then inside the profile screen:
useLayoutEffect(() => {
          props.navigation.setOptions({
            title: fetchUsersNamebasedOnId()
          });
      }, [props.route.params.id]);

Is this possible? I tried the following:
useLayoutEffect(() => {
    (async () => {
      props.navigation.setOptions({
        title: getName(),
      });
    })();
  }, [props.route.params.name]);

and then getName is async function which returns the name. However it doesn't work for me. Is it possible to fetch the name inside "Profile" screen and to put it in the title of the page?
Answer: Yes, it is possible. You are quite close to it.
When you want to use the async function you have to wait till the request is done. For that, you use the await keyword. See the example below:
  useLayoutEffect(() => {
    const setName = async () => {
      const title = await getName(props.route.params.id)
      props.navigation.setOptions({
        title,
      })
    }
    setName()
  }, [props.route.params.id])

Comment: Thank you for your answer. I tried the above, but title comes as undefined. I added my getName() function in my question, if that helps. I also console.log(snapshot.data().name) and yes, it returns the name, but for some reason I can not assign it to the title
Comment: Add `id` to your `getName` function. So it will be `await getName(props.route.params.id)` inside component and then inside `const getName = async (id) => {....` you probably need to use `doc(id)`.


How to calculate mean and standard deviation based on percentage

Question: Here is my data:
df1 <- read.table(text = " Group L1 L2 L3 L4 l5
Q 0% 10% 0% 70% 20%
K 20% 20% 20% 10% 30%", header = TRUE)

I want to calculate L1 times 1, L2 times 2, L3 times 3, L4 times 4 and L5 times 5 for Q and k.
I want to get the following table:
Group  L1  L2  L3  L4  l5 Mean   SD
    Q  0% 10%  0% 70% 20%  0.8 1.19
    K 20% 20% 20% 10% 30% 0.62 0.51

Note: I have 100 rows and this is part of my sample to show the purpose of my question. Much appreciated for your help.
Comment: How is the mean of the vector `0% 10% 0% 70% 20%` equal to 0.8? On a related note: Calculating the mean of percentages (proportions) can be dangerous (the mean of a ratio is not the same as the ratio of the means!). Is that really what you want to do?
Comment: Instead of repeatedly stating "It does not reflect my table/output" to the answers posted here, please *explain* how those numbers are derived (which you've now changed by the way). How is the mean of `0% 10% 0% 70% 20%` 0.8? How is the mean in the second line 0.62?
Comment: @MauritsEvers; take the mean and sd of 1:5*x/100, where x is the values in each row
Comment: @user20650 *"Sorry, I feel your question is not relevant as you can easily see the output of intrest. Just devote , I understand"* I, unfortunately, don't understand a word you're saying.
Comment: not tidyverse but... `library(data.table); setDT(df1) ; melt(df1, id.vars = "Group")[, value := as.numeric(gsub("%", "", value))][ , .(mean=mean(1:5*value/100), sd=sd(1:5*value/100)), by=Group]`
Comment: ... but to get full outcome you can `cbind` or merge `df1[m, on="Group"]`, where `m` is the previous results
Answer: We could first remove the "%" sign from the columns. Multiply df1 by 1:5 and calculate rowwise mean and sd.
df1[-1] <- lapply(df1[-1], function(x) as.numeric(sub('%', '', x)))
temp <- as.matrix(sweep(df1[-1], 2, seq_along(df1[-1]), `*`))
df1$Mean <- rowMeans(temp)/100
df1$Sds <- matrixStats::rowSds(temp)/100
#Or to keep it in base R
#df1$Sds <- apply(temp, 1, sd)/100
df1

#  Group L1 L2 L3 L4 l5 Mean     Sds
#1     Q  0 10  0 70 20 0.80 1.19164
#2     K 20 20 20 10 30 0.62 0.51186

data
df1 <- structure(list(Group = structure(2:1, .Label = c("K", "Q"),class = "factor"),
L1 = structure(1:2, .Label = c("0%", "20%"), class = "factor"),
L2 = structure(1:2, .Label = c("10%", "20%"), class = "factor"),
L3 = structure(1:2, .Label = c("0%", "20%"), class = "factor"),
L4 = structure(2:1, .Label = c("10%", "70%"), class = "factor"),
l5 = structure(1:2, .Label = c("20%", "30%"), class = "factor")),
class = "data.frame", row.names = c(NA, -2L))

Comment: @use2020 It reflected your original input. If you run this on your updated data, it still gives you the expected output.
Comment: @use2020 I have updated the answer based on your new data. Let me know what do you mean by "wrong" ? As I said earlier it works for me for the data you have shared and expected output you have shown.
Answer: library(tidyverse)

df %>%
  mutate(id = row_number()) %>%
  pivot_longer(L1:L5) %>%
  mutate(value = as.numeric(sub("%", "", value))/100 * 1:5) %>%
  group_by(id) %>%
  summarise(Mean = mean(value), SD = sd(value)) %>%
  bind_cols(df, .)

#   Group  L1  L2  L3  L4  L5 id Mean        SD
# 1     Q  0% 10%  0% 70% 20%  1 0.80 1.1916375
# 2     K 20% 20% 20% 10% 30%  2 0.62 0.5118594

Data
df <- structure(list(Group = structure(2:1, .Label = c("K", "Q"), class = "factor"),
  L1 = structure(1:2, .Label = c("0%", "20%"), class = "factor"),
  L2 = structure(1:2, .Label = c("10%", "20%"), class = "factor"),
  L3 = structure(1:2, .Label = c("0%", "20%"), class = "factor"),
  L4 = structure(2:1, .Label = c("10%", "70%"), class = "factor"),
  L5 = structure(1:2, .Label = c("20%", "30%"), class = "factor")),
class = "data.frame", row.names = c(NA, -2L))

Comment: @use2020 just revise `pivot_longer(L1:L5)` to `pivot_longer(L1:l5)`.
Comment: @use2020 `L1:l5` mean `L1 L2 L3 L4 l5` in syntax of `pivot_longer`.
Comment: Excellent. Thank you for your help; @Darren Tsai


Find the Product $abc$

Question: if $a$,$b$,$c$ $\in$ $\mathbb{R}$ and if $$a+\frac{1}{b}=\frac{7}{3}$$ $$b+\frac{1}{c}=4$$ $$c+\frac{1}{a}=1$$ Then find the value of $abc$
I multiplied the three equations with $bc$, $ca$ and $ab$ respectively we get
$$abc+c=\frac{7bc}{3}$$ $$abc+a=4ac$$ $$abc+b=ab$$ Again multiplying above three equations with $a$,$b$ and $c$ respectively we get
 $$a(abc)+ac=\frac{7abc}{3}$$ $$b(abc)+ab=4abc$$ $$c(abc)+bc=abc$$ $\implies$
$$ac=(\frac{7}{3}-a)abc$$
$$ab=(4-b)abc$$ and $$bc=(1-c)abc$$ Multiplying above all three equations we get
$$a^2b^2c^2=(\frac{7}{3}-a)(4-b)(1-c)a^2b^2c^2$$ $\implies$
$$1=(\frac{7}{3}-a)(4-b)(1-c)$$ But from first set of equations $\frac{7}{3}-a=\frac{1}{b}$ and so on finally we get
$$1=\frac{1}{abc}$$ so $$abc=1$$
I feel this method is little long...can i have any other approach
Comment: Your multiplication of three equations in the end should produce $a^2b^2c^2=(\ldots)a^3b^3c^3$
Comment: oh yeah then my approach does not work...thanks
Answer: Hint: Multiplying the first three expressions we get $$abc+\left(a+\dfrac{1}{b}\right)+\left(b+\dfrac{1}{c}\right)+\left(c+\dfrac{1}{a}\right)+\dfrac{1}{abc}=\dfrac{28}{3}.$$

Find the Product $abc$


How to make a vector of sf::sound

Question: I use the SFML library and more specifically the audio part of SFML. I would like to store multiple sf::Sound, so it occurred to me to make a class that handles sounds and to make a vector of sf::Sound.
However, when I try to play a sound, only the last element of the list of my vector can be played, the rest does not play.
I really can't understand why.
audio.hpp
#ifndef AUDIO_HPP
#define AUDIO_HPP
#pragma once

#include <SFML/Audio.hpp>
#include <vector>
#include <string>

enum {SELECTION_SOUND, DEAD_SOUND};
enum {MAIN_THEME_MUSIC, GAME_MUSIC, GAME_OVER_MUSIC};

class Audio
{
public:
    Audio();
    void setVolumeMusic(const float v);
    void setVolumeSound(const float v);
    float getVolumeSound() const;
    float getVolumeMusic() const;
    void playSound(const unsigned int soundExecute);
    void stopMusic();
    void deleteMusicTheme();
    ~Audio();
private:
    bool m_musicThemeUse;
    float m_volumeMusic, m_volumeSound;
    std::vector <sf::SoundBuffer> m_buffer;
    std::vector <bool> accessMusic, accessSound;
    std::vector <sf::Sound> m_sound;
    std::vector <sf::Music*> m_music;
    std::vector <std::string> m_nameFileMusic, m_nameFileSound;

    /*
    * m_musicThemeUse : If this variable is equal to "true" then, the main menu music is deleted from memory.
    * m_volumeMusic, m_volumeSound : Music/sound volume, it is fixed between 0.f and 100.f.
    * m_buffer: vector containing the audio files of the sounds.
    * accessMusic, accessSound : bool vector determining whether a music is available for playback or not. Useful when a file is deleted.
    * m_sound: vector containing the audio files of the sounds.
    * m_music: vector containing the audio files of the musics.
    * m_nameFileMusic, m_nameFileSound : vector of string containing the path of the audio files.
    */
};

#endif

The constructor of the Audio class.
Audio::Audio() : m_nameFileMusic{ "data/mainTheme.ogg", "data/game.ogg", "data/gameOver.ogg" }, m_nameFileSound{"data/selectionSound.ogg", "data/dead.ogg" },
m_musicThemeUse(true), m_volumeMusic(0.f), m_volumeSound(100.f)
{
    //Fill the values of accessMusic and accessSound to "true"
    accessMusic.assign(std::size(m_nameFileMusic), true);
    accessSound.assign(std::size(m_nameFileSound), true);

    //Loads music files.
    for (unsigned int i = 0; i < std::size(m_nameFileMusic); i++)
    {
        m_music.push_back(new sf::Music);
        if (!m_music[i]->openFromFile(m_nameFileMusic[i]))
            accessMusic[i] = false;
    }

    //Set the music files by setting the volume to them and activating repeat when the music files are finished.
    setVolumeMusic(m_volumeMusic);
    for(unsigned int i = 0; i < std::size(m_music); i++)
        if(m_nameFileMusic[i] != "data/gameOver.ogg")
            m_music[i]->setLoop(true);

    //Load sound files.
    const sf::SoundBuffer a;
    const sf::Sound b;
    for (unsigned int i = 0; i < std::size(m_nameFileSound); i++)
    {
        m_buffer.push_back(a);
        m_sound.push_back(b);
        if (!m_buffer[i].loadFromFile(m_nameFileSound[i]))
            accessSound[i] = false;
        else
            m_sound[i].setBuffer(m_buffer[i]);
    }
    //Fix the volume of the sound files.
    setVolumeSound(m_volumeSound);
    //If the main menu music file is available then play the music file.
    if(accessMusic[0])
        m_music[0]->play();

    m_sound[0].play();
}

Answer: When you copy SFML sound objects they stop playing. That's what happens when you relocate objects in an std::vector. I would recommend storing them in pointers as with
using SoundPtr = std::shared_ptr<sf::Sound>;
std::vector< SoundPtr > m_sound;

Answer: Yes I am coming back to tell you that I have solved the problem, in reality I had to separate the initialization phase of std::vector<sf::SoundBuffer> and the initialization phase of std::vector std::shared_ptr<sf::Sound>
Thank you everyone !
    //Loads Buffer file
for (unsigned int i = 0; i < std::size(m_nameFileSound); i++)
{
    m_buffer.push_back(sf::SoundBuffer{});
    if (!m_buffer[i].loadFromFile(m_nameFileSound[i]))
        accessSound[i] = false;
}

//Loads Sound file
for (unsigned int i = 0; i < std::size(m_buffer); i++)
{
    m_sound.push_back(std::make_shared<sf::Sound>(sf::Sound{}));
    if (accessSound[i])
        m_sound[i]->setBuffer(m_buffer[i]);
}

Comment: Hey thanks for giving me the answer and still responding your own giving us feedback! Thats' very noble

How to make a vector of sf::sound


What is the function that plots these curves?

Question: I have a number of plots that appear as shaded squares on a grid:

The plots (apart from the rogue squares to the leftmost part of each plot) resemble $a\zeta(bx+c)-dx$, where $a$,$b$,$c$ & $d$ are constants (as shown on the left plot) but not exactly. I am looking for the function that generates each plot. Is there any way I can improve the fitting function, other than by trial & error?
Comment: If you have a family of functions in mind, try a least squares fit.
Comment: OK - will do :)
Comment: Post your results as an answer when you are satisfied.
Comment: Yes - I will :)
Answer: I'd recommend Excel as a good way to experiment with curve fitting. Use your point data to make a chart. Then right-click on the graph, and choose "Add Trendline". A dialog appears that lets you fit several different types of curves to your data.
By default, the displayed equation will show the coefficients accurate to 4 decimal places, which may not be good enough for you. If so, right-click on the displayed equation, and choose Format Trendline Label. A dialog appears that lets you change the number of decimal places displayed. Then you can copy/paste this equation to anyplace you want.
If you need the actual coefficients for further calculations, or if you want things like the R^2 and so forth, you can use the =LINEST() array function in Excel to get these. Google for details.
Comment: True. You said the plots look like a Zeta function, but I didn't realise that you definitely want to use a Zeta function for fitting. If so, then just do least squares with your $a$, $b$, $c$, $d$ as the independent variables. Non-linear, but probably tractable.
Comment: Thanks for the detailed answer. Only problem is Excel doesn't recognise special functions (eg - Zeta function) - just gives logarithmic, polynomial, linear, exponential, etc. I have tried XNumbers addin for Excel, but don't think it can be applied to plot fitting.
Answer: Solved, using Mathematica's FindFit option:

With:
data = {{2, 26}, {2, 25}, {2, 21}, {3, 22}, {3, 21}, {2, 22}, {3, 19}, {4, 20},
{4, 19}, {3, 20}, {4, 17}, {5, 18}, {4, 18}, {5, 17}, {6, 18}, {6, 17}, {6, 16},
{7, 17}, {7, 16}, {8, 17}, {8, 16}, {8, 15}, {9, 16}, {9, 15}, {10, 16},
{10, 15}, {11, 16}, {11, 15}}

model = a Zeta[b n + c]
fit = FindFit[data, model, {a, b, c}, n]
modelf = Function[{n}, Evaluate[model /. fit]]

Plot[modelf[x], {x, 0, 11}, Epilog -> Map[Point, data], PlotRange ->
{{0, 11}, {0, 50}}, AspectRatio -> Automatic]

(Points where $x\leqslant1$ omitted to avoid problems with complex infinity.)


Are there digital keyboard that will play music I write on the computer?

Question: I have been trying to compose tracks using the synthesizers provided by software like Sibelius and Finale, but it sounds terrible in terms of the sound quality.
I tried playing some of the stuff on my friend's digital Yamaha keyboard and it sounded just like a real piano when I recorded it.
Is there a model pian or software or both that would allow me to write the music on the computer and then have it played with the digital keyboard?
Comment: You should be able to "play" a digital keyboard from Finale or Sibelius with nothing more complicated than a MIDI cable from your computer to the keyboard. You have to tell the notation program to generate MIDI output instead of using its own synthesizer, of course. But if you mean the software's *interpretation* of the music is "terrible" compared with a *human* performance, changing the playback device won't alter that. The way to get the best results from any sample library is usually to play the samples "live" from a keyboard, not from a notation program.
Comment: You certainly don't *have* to buy a digital keyboard to get a pretty good piano sound. Here's a demo comparing three different computer-generated pianos (all "playable" from Sibelius or Finale - I personally use one of the three)  compared with a "real" digital piano. https://www.youtube.com/watch?v=ZoEBnCEYmlA
Comment: Hmmm I think that may answer my question. I will have to get such a cable and keyboard try.
Answer: You would use a good plugin (probably a VST) like Addictive Keys to get the MIDI tracks generated by those other programs to sound realistic. A lot of times, the built-in instruments for music programs sound pretty fake.
I don't use Finale myself, but it looks like it supports VST instruments. I'd recommend starting with the Addictive Keys demo so you can hear what it sounds like. Personally, I think it sounds quite realistic, and I use it with a digital piano I have.


How to print link text in twig?

Question: I've attached file to a node with Media module. I have custom templates/file/file-link.html.twig file, which is rendering the download link with {{ link }} tag.
{{ devel_dump(link) }} outputs this:

I need to print File name as pure text without any link rendering for some cases.
I've tried {{ link.text }}, {{ link.text.string }} and other options, but none of them gave me what I wanted.
Answer: Maybe this is a render array and you need to use link['#text'] here (sorry if I'm on the wrong track).
Edit: If {{ link.text }} worked on subsequent tries, then my answer is definitely wrong, and the reason for your problem was probably related to caching or something.
Comment: Thanks a lot! I don't know why, but `{{ link.text }}` worked, when I tried it again.
Comment: That's really odd, and my only guess is that it might have been a caching problem?
Comment: Could be, but I always clear it before looking for any change. Anyway, thanks a lot for such a quick response for my problem.
Answer: I don't know why, but when I tried {{ link.text }} one more time - it worked great!
Maybe I forgot to clear cache, when I used it for the first time, I don't know, but I think I should leave this answer for anyone who will search for it.

How to print link text in twig?


IEnumerable<> to ObjectSet<>, reason: INCLUDE

Question: I am working on MVC3 app, using Entity Framework 4.1. I did LINQ query, and returned it as IEnumerable<T>. But, in controller, I have to use Include(other entity), like in ObjectSet, so I can show in view other entity values (which is associated to the one I am doing query on). I tried explicit cast from IEnumerable<T> to ObjectSet<T>, but it throws exception. Is there any way I can get ObjectSet from IEnumerable, or to include entity in IEnumerable?
Thanks in advance.
Answer: If your context is still alive (if you haven't left the using) and if you haven't done .ToList() you should be able to cast to ObjectQuery<T>.
A safer practice would be to use an extension method on IQueryable<T> which checks if queryable is a ObjectQuery<T> and if so casts to ObjectQuery<T> and returns result .Include() otherwise returns the input query.
Comment: Expanding on this, you could return is there a particular reason you're using IEnumerable?  If you returned IQueryable to your controller, it can use the IQueryable Include
Comment: If I use IQueryable, I get "The entity or complex type  cannot be constructed in a LINQ to Entities query."
Answer: Once you have it cast to an IEnumerable, it becomes disconnected from the datasource.
You should include the related entities in the DAL while it is still an IQueryable or IObjectQuery and then return the complete result as an IEnumerable.
Otherwise, you will be doing an extra hit on the DB.
Si
Comment: Do you see the entities being populated before they leave the Dal, are they being lost on the transfer to the controller?
Comment: When I use query directly on ObjectSet, it works even without include, I'm getting all fields. But when I use query on query I mentioned in last sentence, it doesn't. It's lost when I use query on IEnumerable (as result of query)...
Comment: I wouldn't try using the include on the IEnumerable, but rather in the source on the object set and return the entity ready for use.  If you need access to other properties of the entity (such as navigation properties) perhaps it might be more prudent to put those into their own function with their own views to manage the view complexity etc.


Azure DevOps UserEntitlements REST API with filter fails for single quoted string value

Question: I am using the userentitlement REST API in Azure DevOps and when using the filter parameter with a single quoted string as a value , I get the error .
Here is my request
<code>https://vsaex.dev.azure.com/{Myorganization}/_apis/userentitlements?$filter=name+eq+'Gary D'Jessi'&api-version=5.1-preview.3
</code>
This is the response I get
<code>{
"$id": "1",
"innerException": null,
"message": "Invalid filter: \"name eq 'Gary D'Jessi'\"",
"typeName": "Microsoft.VisualStudio.Services.WebApi.Exceptions.InvalidQueryStringException, Microsoft.VisualStudio.Services.WebApi",
"typeKey": "InvalidQueryStringException",
"errorCode": 0,
"eventId": 3000
</code>
}
I tried using the solution with https://stackoverflow.com/a/4483742/7841330 but did not help.
Comment: As you said, you tried a solution from other SO question. Can you provide your request with `''` and the response, please?
Answer: The correct way to escape is to place two single quotes into the string instead one.
For example  name+eq+'Gary D''Jessi'
I tested in postman and it worked fine.

Hope it can help you.