Simple cross domain html request with jquery? Trying to use plug-in

Question: I'm trying to perform a simple html request using jquery with the code below.
$.get('http://externalsite.com/status.html', function(data) {

if (data == 1) {
//do something
}

else {
//do something else
}

});

I'm using the cross domain request plugin found at http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/
and I added the .js script to my html file, but what's next?  The example uses a #container and a load from google, but I'm lost as to what I do for an html request.  It says it works for any .get request, I just don't know how to do it.  Thanks for your help.
Answer: i am not sure what your problem exactly is, can you for example wrap this code into the function and simple invoke it ? :)
like
function makeAjaxCall(url){
 $.get(url, function (...)
}

makeAjaxCall('http://google.com');

Comment: I just don't know how to form my request to get it to work cross domain with the plug in.  Do I need a yahoo YQL link or will any domain work?
Answer: You can do whatever you want. Read the jQuery docs for .load() and .get()
:
This example puts the contents of http://google.com in the HTML element with id="container":
$('#container').load('http://google.com');

This does the same thing but with your example site:
$('#container').load('http://externalsite.com/status.html');

This also does the same thing as above:
$.get('http://externalsite.com/status.html', function(data) {
    $('#container').html(data);
});

Comment: @trinth It's really just proxying a request through Yahoo's servers: http://jsfiddle.net/Paulpro/fDN7t/ and getting back a JSONP response even if the requested server doesn't support JSONP
Comment: @trinth He is using the cross-domain request plugin for jQuery which uses YQL (the other exception) as seen here (http://christianheilmann.com/2010/01/10/loading-external-content-with-ajax-using-jquery-and-yql/) to make the request. It is not a joke...
Comment: Ok so I'm making progress and I'm hoping you can help.  The request is going through, but when I tested but using `alert("working" + data)` the returned data was object Object.  Any suggestions?  I might be doing this completely wrong.
Comment: @Davis Are you fetching JSON?
Comment: here is the answer what to do in order to get displayed everything what is returned: http://stackoverflow.com/questions/1766795/javascript-write-console-debug-output-to-browser
Comment: surely this is a joke. cross-domain requests cannot be made from javascript PERIOD. the exception is JSONP.


Como posso detectar e alertar que um determinado usuário está enviando muitas mensagens seguidas?

Question: Em um sala de chat, como posso detectar e alertar que um determinado usuário do sistema está enviando muitas mensagens seguidas (flood)?
Answer: Sugiro guardar na sessão a data em que a mensagem foi enviada e um contador de mensagens. Se o usuário enviar outra mensagem, compare a data com a que está armazenada na sessão, se a diferença de tempo for curta, incremente um contador na sessão.
Se este contador chegar em um limite (ex: 3 mensagens) recuse os próximos requests até que um certo tempo tenha passado.
Para salvar o tempo do ultimo post
$_SESSION["LastPost"] = time();

Para comparar o tempo do post
// se o post foi feito novamente nos últimos 10 segundos
if (isset($_SESSION["LastPost"])
    && $_SESSION["LastPost"] <= (time() - 10))
{
    if (!isset($_SESSION["PostCount"]))
        $_SESSION["PostCount"] = 0;

    $_SESSION["PostCount"] += 1;
}

E para verificar se o usuário atingiu o limite de posts por segundo
if (isset($_SESSION["PostCount"]) && $_SESSION["PostCount"] == 3)
{
    // você pode setar uma trava
    $_SESSION["LockPost"] = time() + 60;
}

Se a trava existir ignore o request.
if (isset($_SESSION["LockPost"]) && $_SESSION["LockPost"] >= time())
{
    // bloqueado, ignore
}
else if (isset($_SESSION["LockPost"]))
{
    // o tempo de bloqueio passou
    // zere todas as variáveis da sessão
    unset($_SESSION["LockPost"]);
    // ...
}

Comment: Além disso, por questões de usabilidade, seria interessante **também** fazer um bloqueio redundante no *client* do *chat* para que o usuário saiba o que está acontecendo. Se ele tentar burlar, aí sim o servidor vai ignorar.
Comment: Boa observação, evitar _roundtrips_ é sempre uma boa.
Comment: Boa resposta, mas 3  mensagens a cada 10 segundos é muito pouco, pois tem gente que consegue digitar 3 mensagens em pouco mais de um segundo... :)
Comment: No meu caso, quando o servidor detectar flood, ele vai inserir uma mensagem privada no tabela de chat, que apenas o autor do flood verá, alertando o ocorrido.
Comment: Seria legal comparar se as 3 mensagens tem textos parecidos, para ai sim detectar o flood, pois um usuario também pode digitar rápido.


How to tell the coach that I don't want to play varsity?

Question: So this is how my high school basketball team system works: There are two teams, frosh-soph and varsity. Varsity is mainly for juniors and seniors, but every year, a few good sophomores get bumped up to varsity. I happened to be one of them this year. While tryouts haven't officially begun yet, the varsity coach told me to come to their open gyms and says that I will end up trying out for the varsity team (if I get cut from varsity, I automatically go to frosh-soph). After 2 months of open gym, I realized that I do not want to play for varsity. First of all, the conditioning and practices are extremely long and tough, and I have to take a deep nap after practice before I even start on my huge homework load. I also like the frosh-soph coach much more, and I have more friends in frosh-soph. Most importantly, I doubt playing varsity will be a lot of fun, since I will not get that many minutes, and it will be too tough for me overall.
How do I tell the varsity coach that I want to move back down, without hurting my chances for making varsity next year(as a junior)? Although I am a good player, I am afraid that he will see the desire to move down as a sign of weakness and not wanting to get better. Overall, I just think that playing varsity will have more cons than pros.
Answer: This will be a long comment.
Best thing you could do is to have a discussion with your coach about this issue and be confident on why you want to drop down. Is there anything that may cause you to reconsider is worth noting and may help in discussion. If I am a coach and someone comes to me and says I don't want to play ..., the first question I would ask is why, so be able to explain that.
So, just explain him why moving down will be a better move for you and how it helps in you getting better. If you show consistency, improvement in your performance it will not affect your chances of making varsity next year.
Answer: Your coach only sees one bit of your life.  You know all the bits of your life.  You may only be a sophomore but no one knows you better than you.  You are the person (along with parents) who decides what the balance among school, athletics, and social life should look like for you.
If you opt not to participate this year there will be consequences both good and bad, but you also aren't a fortune teller.  Your coach might not promote you to varsity next year because you chose not to play this year.  Or he might respect your decision to focus on balance this year.  Or all the other sophomores might become freaking awesome over the course of the year and pass you by.  You can only make a decision with the information at hand.
If you feel you can discuss this with your coach you should.  Part of adulting is having the courage to tell people what you want for yourself over what they want for you.  And @Ram Chandra Giri is right.  You need to be prepared with why you don't want to play Varsity this year and what you do want to do instead.
If that prospect is overly daunting because you aren't there yet or you know your coach would not be receptive here is trick I gave/give my kids to use:  "My mom won't let me."  When my teenagers feel like they can not say no to a particular person I ask them if they want me to tell them they cannot do it.  And sometimes they do.   The burden of saying "I want to do X" gets shared with your parents.  "My parents want X" is easier to say as a young person.  (Obviously this trick is easy at age 12, harder at 15, and counterproductive at age 18.  So be judicious.)
It sounds like you have thought a lot of this through.  Own the choice and the consequences.
Answer: This is going to be a bit direct. Please take it as constructive criticism.

First of all, the conditioning and practices are extremely long and tough

That's the idea. You'll get fitter and therefore be a better player by doing them. When it gets to double overtime in a playoff game, you'll appreciate those minutes doing conditioning because you'll have the extra step on the opposition.

Most importantly, I doubt playing varsity will be a lot of fun, since I will not get that many minutes

This sounds like a decision to prioritise game time and fun over the hard graft of practice. This is a valid decision for you to make, but it's probably not the decision which is going to make you the best player you can be in the long run.

and it will be too tough for me overall.

You don't get better by being in your comfort zone. You get better by it being tough.

How do I tell the varsity coach that I want to move back down, without hurting my chances for making varsity next year (as a junior)?

Basically, you can't. What your varsity coach is saying to you is "put the hard work in this year, you'll be a better player next year". It's up to you whether you take that option, or you take the easy option of playing on the frosh-soph team - that may well be more fun in the short term, but you need to think about what you want in the longer term.


How to send message with viber bot to group chat?

Question: Im trying to make a vibe bot that will only send announcements to group of people. The bot will not respond or interact with anyone, as its only and primary task is sending given text as an announcement to a group of people in the same chat.

I don't understand:

a. What is wrong?
b. Why its not working?
c. Where to find the viber chat id?
d. Can I hook up this bot to any chat group (group/community/channel)?
<code>
const ViberBot = require('viber-bot').Bot;
    const TextMessage = require('viber-bot').Message.Text;

    const viberBot = new ViberBot({
    authToken: process.env.VIBER_AUTH_TOKEN,
    name: "...name...",
    avatar: "...img-url..."
    });

    viberBot.sendMessage({ id: process.env.VIBER_GROUP_ID }, new TextMessage("hello world!"))
</code>
I triple-checked the auth tokens, and it's correct. But I still can't find the Viber Chat Id.
I tried to get the ending of a share link (to use it as the chat id), and the result I got was the following error:
<code>    {
      status: 10,
      status_message: 'webhookNotSet',
      chat_hostname: 'SN-CHAT-16_'
    }
    {
      status: 10,
      status_message: 'webhookNotSet',
      chat_hostname: 'SN-CHAT-20_'
    }
    {
      status: 10,
      status_message: 'webhookNotSet',
      chat_hostname: 'SN-CHAT-10_'
    }
</code>
Does anybody know how to fix this?
Answer: This is not possible to achieved with Viber.
Here is another discussion on the topic: https://github.com/Viber/sample-bot-isitup/issues/2
An alternative dirty hack solution would be to ramp up a virtual machine and using automation for windows to make it so that a Viber client is running and you send the messages to the group via the Windows Viber UI.


Write and equation and justification to find $x$.

Question: I'm a little stuck on the following question, help would be appreciated
Given that $m\angle ABD=2x+12$, $m\angle CBD= 6x-18$, and $BD$ is an angle bisector, write an equation and justification to find $x$.
Comment: Does $\text{m}\measuredangle ABD =\text{m}\measuredangle CBD$ hold?
Comment: What other information do you have?
Comment: You already have two equations.  Unless you have other information, there is no third equation.
Comment: This is all the information that I received. Btw BD is a bisector.
Comment: I think that the "justification" that a high-school teacher is looking for is the remark that the bisector divides the big angle into two *equal* smaller angles, $\angle ABD$ and $\angle DBC$.
Comment: *Btw BD is a bisector*.  So you did *not* originally provide us will all the information you received.
Answer: In the case that $BD$ is a bisector, then $2x+12 = 6x-18 \implies 4x = 30 \implies x = \dfrac{15}{2}$.
Comment: How do I "Justify" this?
Comment: It is just by definition of the problem. Unless there is any other information about the angular measure of $\angle{ABC}$ or if $BD$ is an angle bisector this is only answer.


The number of sample size in this case

Question: I'm trying to compare three conditions (A, B, C). And I have a question about the sample size in this experiment.
There were 27 participants, and each participant listened to 20 songs for each condition. (I have counter-balanced the order, and 20 songs were the same for everyone.)
So the number of the result for surveys goes like this (Px = Participant number X) ...
P1
A: 20
B: 20
C: 20
P2
A: 20
B: 20
C: 20
.
.
.
P27
A: 20
B: 20
C: 20
Every participants have done Likert scale for each music, so the total number of surveys are 1620 (27 people X 3 conditions X 20 music). And each condition has 540 surveys. (27 people X 20 music).
In this case, should I count my sample size as 27(participant number), or 540(participant number X number of songs)?
Answer: In standard formulae that apply to this case, there should be separate notation for participants, conditions, items (not necessarily called like this), so you should know what is what. What you call sample size is secondary if you use the formulae correctly.
I'd call 27 "sample size" here and 540 maybe "number of records", but note that this may depend on what exactly I'm communicating to whom. In mathematics terms are what they are defined to be, and different people may use different definitions. If there is no explicit definition, they are at least potentially unclear, and if terms are ambiguous, better use them with an exact description what they are.
Comment: Then in order to compare its means, should I use average of 27 people's data?
Comment: @user372833 If you want help with analysing your data, you better open another question.

The number of sample size in this case


Correlation in R with imbalanced data

Question: Let's say I have two vectors of different length. Of course, this will fail when I run cor.test in R.
x = rnorm(1,3,5,7,2,12,13,14,5,16)
y = rnorm(1,4,5,6,7)

cor.test(x,y)

> cor.test(x,y)
Error in cor.test.default(x, y) : 'x' and 'y' must have the same length

Obviously, regression also fails in this scenario given the length imbalance.
> lm(y~x)
Error in model.frame.default(formula = y ~ x, drop.unused.levels = TRUE) :
  variable lengths differ (found for 'x')

What is the proper statistical solution to get some sort of "correlation" or "association" metric when two variables are imbalanced? Any explanation of the stats behind it would be greatly appreciated?
Comment: These variables have no explicit connection, so what do you mean by "correlation" or "association"?  How could that possibly apply?
Comment: It is meaningless to assert "they were connected": you merely have two batches of numbers.  There is no way, without additional information, to infer anything whatsoever about any relationship between them.
Comment: I have voted to reopen on the grounds that this question is answerable, though I think it could benefit from a change of title ("data sets of different sizes" perhaps, rather than "imbalanced"?). I think the appropriate answer is to explain what [bivariate data](https://en.wikipedia.org/wiki/Bivariate_data) really means, and why "correlation" or "association" only make sense in that context. Without pairing, the concept is meaningless.
Comment: @gung Quite possibly, time-depending. I think it might be worth further searching for a duplicate first, since I have the feeling such a question must have been asked before (though cannot recall seeing it myself!)
Comment: Let's say that they were connected...updated the data so that they should have a strong positive covariance
Comment: @Silverfish, are you planning to provide such an answer, if it is reopened?
Comment: @Silverfish, when you have an answer worked up for this, ping me. I lean towards leaving this closed, but if you have an answer, I'll open it for you.
Comment: `x = rnorm(1,3,5,7,2,12,13,14,5,16) ` is not even a valid `R` expression and just throws an error.
Answer: Wikipedia writes "Correlation is any of a broad class of statistical relationships involving dependence" ( https://en.wikipedia.org/wiki/Correlation_and_dependence )
You can only have it in dependend data. Usually, when you write R-code like this:
x <- c(3, 4, 5, 6)
y <- c(1, 6, 7, 8)
cor(x, y, method="...")

this implies, that the first element in x has something in common with the first element in y and the second has something in common with the second and the third with the third and so on.
Correlation searches for things like "If some element in x is large, does the corresponding element in y have a tendency to be large as well?". Now, in something like
x = c(1,3,5,7,2,12,13,14,5,16)
y = c(1,4,5,6,7)

There is no information, what y values should be large or small if x is 12, 13, 14, 5 or 16. Therefore, R throws an error so you can think about what went wrong.
Either your data has no clear definition of what a correlation amongst them should be, because it is not dependend data, or there are data points missing, which needs to be cleared by inserting NA where the data is missing
This would work:
x = c(1, 3, 5, 7, 2, 12, 13, 14, 5, 16)
y = c(1, 4, 5, 6, NA, NA, NA, 7, NA, NA)
cor(x, y, na.rm = TRUE)

Because now it is clear, which element in xbelongs to which in y.
For a more visual and maybe intuitive approach, let's for the moment consider Pearson correlation as an answer to the question, how well a regression line fits the data points in a scatter plot (with a grain of salt). Take your data example of 10 x values and 5 y values and see, if you can draw that in a scatter plot.
Comment: This is pretty much the answer I was going to put except that I would have really emphasised one more point: *simply the fact that two univariate datasets have the same length, does **not** mean that the "correlation" between them is meaningful*. Unless we have been given more information, we do not know that the first entry of the first dataset has any meaningful correspondence with the first entry of the second.
Comment: When the datasets are of different lengths, it is obvious there *cannot* be such a correspondence; but if you have e.g. height data for 10 people and weight data for 10 different people, then we still cannot work out whether higher values of "weight" corresponded to higher or lower values of "height".

Correlation in R with imbalanced data


Cluster analysis on biased binary data

Question: I have a data set of 86 variables which contains binary and categorical variables.
I have to perform cluster analysis on the same. Also the data set which I have is biased (94% 0 and 6% 1 in dependent variable, where 0 stands for No and 1 stands for Yes). As per my knowledge, cluster analysis can't be performed on binary and categorical data. Can anyone please help me with the same? The dataset is available at the below link (Caravan Insurance data).
https://www.kaggle.com/uciml/caravan-insurance-challenge
Comment: What is dependent variable in a cluster analysis?
Answer: It can, you just need to convert the factors into dummy binary 0,1 numerical values and make sure your continuous variables have been standardised. This is essentially one-hot encoding and is used quite often to pass categories into the machine.

https://en.wikipedia.org/wiki/One-hot
Answer: If you have a good metric it can be used.
It just often does not perform well.
But if you have a target variable, then do classification, not clustering.

Cluster analysis on biased binary data


Codeigniter REST API, difference between PUT and POST

Question: I am making an API for my site using Philip Sturgeon's REST server and i am in a little dilemma. I am not shure which action to use for edit and which for create. POST or PUT?
Comment: This post explains it very well: http://stackoverflow.com/a/630475/1932551
Answer: The POST method is usually used for create operations,
and the PUT is used for edit/update operations.
Answer: Put methods are Idempotent whereas Post methods are non-Idempotent.
means put are safely repeatable and post are not safely repeatable


Landing Page Based on Role?

Question: Use Case - I've got several Dashboards (some custom View pages) in the site. Depending on the Role associated with a User, I want to direct them to thier respective Dashboard.
So an Editor would go to the Editor Dashboard, a Contributor would go to a Contributor Dashboard, etc. after they login.
(I'm using the OpenPublic distro)
Comment: Do you want to redirect user just after login???
Comment: You can do this with the rules modules.
Answer: You can redirect user after checking their role(by using below PHP snippet)
<?php $GLOBALS['user']->roles; ?>

Your code will look something like this:
<?php
if($GLOBALS['user']->roles == 'editor') {
  drupal_goto("dashboard_editor"));
}
?>

Note: this will work only when a user has single role associated with him.
Answer: You can use a panels for the dashboard and then create different variants based on roles using the Access rules.
Answer: Checkout the login destination module. Simple as that.
https://www.drupal.org/project/login_destination
Answer: Few methods you could do this:
1) hook_init() - check user's role and redirect to the correct address.
2) With the Pages module, you can set each panel's (=view's) display rule as having a certain role. With this you can stay at the same address (say, /dashboard)

Landing Page Based on Role?


Is the B. C. Rich Beast NJ Series with the Floyd Rose Speedloader tremolo rare?

Question: I've been googling around for articles or anything that mentions the B. C. Rich Beast with the Floyd Rose Speedloader tremolo, but all I can find is obscure forum postings, reviews and old-looking shops that claim to have once sold it. One website claims to have the last remaining one in Australia.... I'm not sure on the date that page was last updated though.
I understand that it is no longer manufactured by B. C. Rich, which may be why I can't find anything of note on their website about it. I checked eBay too and didn't find anything there.
So is this guitar rare now?
Comment: About $650.00 in here the States!!
Answer: That's a tricky one. You must consider the question of why B.C. Rich aren't making one anymore.
I don't know how long the run was, but given that the Speedloader is a fairly recent development, it's likely that not very long. I am therefore guessing that the reason it went out of production is that it wasn't very popular.
It's likely that the Speedloader is the primary reason for this, or rather the proprietary string design required. I've just done a quick scan of the Net and I see that things haven't changed much in terms of string availability. Having to jump through hoops in order to restring the thing will probably be a deal-breaker for most.
The fact that a guitar is rare doesn't necessarily mean that you'll be able to get a good price for it. Selling it off now might mean that you'll have to offer a good deal in order to find a buyer. You might be better off holding on to it with the hope of future collector interest.
The other option is getting rid of the Speedloader and installing a standard Floyd. However, it would be a major modification and probably not cost-effective. Plus, such a mod would remove the only differentiating factor, making it just another used NJ Beast.
Comment: "Rare" is one thing. This guitar was unpopular and undesirable due to the need for proprietary special-order strings. So while it's rare, it isn't worth a lot of money.


Having issues with my websites htaccess

Question: I recently uploaded a PHP theme on my server.  It's working fine on any other sections except my home page.  For example, when accessing www.mywebsite.com/anything the theme is working but when on homepage www.mywebsite.com the server's default page is shown.
I was playing with the htacess RewriteEngine and it was working in some cases but probably not correct.  This is what I have so far:
<IfModule mod_rewrite.c>
RewriteEngine on
Options -Multiviews
RewriteCond %{REQUEST_URI} !-d
RewriteCond %{REQUEST_URI} !-f
RewriteRule ^(.*)?$ index.php?a=$1  [QSA,NC,L]
ErrorDocument 404 /new/404.php
</IfModule>

This is making my home page work, but the title is not showing it's saying "Page Not Found" on the title.  The page is working and all I'm changing is the two RewriteCond above.  They were set to {REQUEST_FILENAME} but that made my website homepage not work and show the default server page.
Answer: It isn't clear in your question if the correct PHP files are being hit. Assuming the syntax of your .htaccess is correct:
Your RewriteRule is indicating your index.php as the receiver for any files and directories that do not exist, with the path (I believe) being sent to $_GET['a']... it is up to your index.php to detect and handle this appropriately.
ErrorDocument is a separate mechanism and once again, if the 404.php is being hit it is up to it to e.g. header('HTTP/1.1 404 File Not Found') and then output HTML that indicates a page not found.
Comment: this is what i have found in my index.php

run();
?>
Comment: So this is an application someone else wrote? Which application is it? Is there any documentation on how to accomplish this redirect?

Having issues with my websites htaccess


Rendering large number of objects in realtime using RealityKit or Metal

Question: I am currently working on a project where I need to render a large number of objects in 3D. However, I have encountered performance issues when attempting to render a significant number of objects.

To provide some context, I have tried looping through my simd3 array, creating sphere meshes, and adding model entities one by one. Unfortunately, this approach is quite slow a. For instance, it takes several seconds to render just 50 objects.
I am seeking solutions or guidance on how to optimize the rendering process to achieve significantly faster results.
Ideally, I would like to render around 10,000 objects in approximately 1/90th of a second. Furthermore, I am curious to know if it is possible to render even larger quantities, such as 100,000 or even 1 million objects, in realtime.
Are there any recommended techniques, approaches, or alternative frameworks that can help me?
Answer: For optimal performance you will want to use instancing.
Here is a tutorial on the subject.
It is also worth mentioning that running in a simulator will not offer the same performance as on actual hardware.
Comment: For RealityKit, it appears there isn't a way to do instancing. When I clone a `ModelEntity`, and add it to scene, I get 1 draw call per `ModelEntity` – even if I don't change any properties on the entity, etc. I'm surprised there's not a batching mechanism of some sort.

I was looking at RealityKit for a 3D `.nonAR` game, I guess this is another area where SceneKit wins, despite being so much older.
Comment: I should add that I am sharing/using the same MeshResource and not creating one per ModelEntity too
Comment: It's buried a bit, but on https://developer.apple.com/documentation/arkit/arkit_in_ios/adding_visual_effects_in_ar_quick_look_and_realitykit# it says:

> While utilizing features to present virtual content effectively, take steps to keep the AR experience responsive. Because each model mesh results in a draw call, for best results, limit the number of meshes in a USDZ file to around 50. To reduce draw calls while maintaining the same amount of geometry, merge objects that share a material.
Comment: For instancing, have you investigated `MeshResource/Contents/instances`? https://developer.apple.com/documentation/realitykit/meshresource/contents-swift.struct/instances ? Each instance gets its own transform https://developer.apple.com/documentation/realitykit/meshresource/instance This seems promising but I have not tried it myself yet. The documentation for this feature is surprisingly hard to find, even if you already know it exists. I'm curious what the effect on draw calls is.
Comment: Also it's worth noting that if you're calling `MeshResource/generateSphere(radius:)` to create the spheres in your screenshot, each sphere will consist of 8,064 triangles.


How could the result of a decicion tree (maximum depth) be converted to probabilities

Question: I would like to compute a ROC-Curve for a decision tree created with
sklearn based on the CART algorithm.
Logically, if I compute it with maximum depth I always get a probability of 1 or 0 (discrete classifier) for a classification.
I red https://datascience.stackexchange.com/questions/323/how-can-we-calculate-auc-for-a-simple-decision-tree
on how to get probabilities from the ration in the end node, but this would mean, that I would have to crop the tree, by limiting the depth.
But its often those last decisions that can be crucial for a correct classification.
Therefore I would like to know, if there is a way to create a score or probability for a maximum depth decision tree, (for example by taking
into account the number or previous nodes or the summarized entropy or
the fraction of the training data in that node)
Comment: You really need to just fit a shallower tree, as what you've described is overfitting.  Im not sure what you mean by "But its often those last decisions that can be crucial for a correct classification".  That may be true through the lens of the training data, but on test data those final nodes are just overfitting.
Comment: The decision thresholds involved in ROC analysis need not be probabilities. Which do you want, a ROC curve or probabilities?
Comment: @Kodiologist I'd like to compute a ROC curve, therefore I need some kind of 'goodness' score (could be probabilities) as a threshold, that's why I asked if someone has an idea to evaluate the decision.
Comment: @MatthewDrury Your argument seems reasonable, I will continue with a shallower tree, but I would still like to know (out of interest), if and how a maximum depth tree could be scored (maybe by taking the number of nodes into account and thereby showing the over-fitting).
Answer: You're trying to have your cake and eat it, too.

Logically, if I compute it with maximum depth I always get a probability of 1 or 0 (discrete classifier) for a classification. I red https://datascience.stackexchange.com/questions/323/how-can-we-calculate-auc-for-a-simple-decision-tree on how to get probabilities from the ration in the end node, but this would mean, that I would have to crop the tree, by limiting the depth. But its often those last decisions that can be crucial for a correct classification.

A tree that has probabilities in the leafs compute the probability by taking the proportion of each class in that leaf. If you want pure leafs, then your probabilities are going to be $\mathbb{P}(class = 1)=1$ or $\mathbb{P}(class = 1)=0$ by construction. If you want predicted probabilities that are greater than 0 and less than 1, then you need impure leafs. You can't have both.
If you're willing to use an ensemble of trees, then you have more flexibility. Random forests, for example, take the average predictions over randomized trees trained on randomized data, so predicted probabilities can be found by averaging over binary votes of fully-grown trees.


Best way to present a random forest in a publication?

Question: I am using the random forest algorithm as a robust classifier of two groups in a microarray study with 1000s of features.

What is the best way to present the random forest so that there is enough information to make it
reproducible in a paper?
Is there a plot method in R to actually plot the tree, if there are a small number of features?
Is the OOB estimate of error rate the best statistic to quote?
Comment: There is not a single tree... But see @Shane's response for plotting one of them for illustrative purpose.
Comment: you could try my random forest visualization package, forestFloor - http://forestfloor.dk/
Comment: I certainly worth considering randomForest::partialPlot, http://stats.stackexchange.com/questions/92150/r-what-do-i-see-in-partial-dependence-plots-of-gbm-and-randomforest/112603#112603
Answer: Regarding making it reproducible, the best way is to provide reproducible research (i.e. code and data) along with the paper.  Make it available on your website, or on a hosting site (like github).
Regarding visualization, Leo Breiman has done some interesting work on this (see his homepage, in particular the section on graphics).
But if you're using R, then the randomForest package has some useful functions:
data(mtcars)
mtcars.rf <- randomForest(mpg ~ ., data=mtcars, ntree=1000, keep.forest=FALSE,
                           importance=TRUE)
plot(mtcars.rf, log="y")
varImpPlot(mtcars.rf)

And
set.seed(1)
data(iris)
iris.rf <- randomForest(Species ~ ., iris, proximity=TRUE,
                        keep.forest=FALSE)
MDSplot(iris.rf, iris$Species)

I'm not aware of a simple way to actually plot a tree, but you can use the getTree function to retrieve the tree and plot that separately.
getTree(randomForest(iris[,-5], iris[,5], ntree=10), 3, labelVar=TRUE)

The Strobl/Zeileis presentation on "Why and how to use random forest variable importance measures (and how you shouldn't)" has examples of trees which must have been produced in this way.  This blog post on tree models has some nice examples of CART tree plots which you can use for example.
As @chl commented, a single tree isn't especially meaningful in this context, so short of using it to explain what a random forest is, I wouldn't include this in a paper.
Comment: Small extension about plots: `plot.randomForest` shows how OOB error and in-class OOB error evolved with increasing number of trees; `varImpPlot` shows attribute importance measures for top attributes and `MDSplot` all objects plotted on the 2D projection of RF object proximity measure.
Comment: +1 for citing the `MDSplot()` function. I must admit I often use RFs as a way to highlight clusters of individuals (based on the RF proximity measure) rather than selecting the best features. Clinicians often read much easily such plots than dotplot of var. importance...
Answer:
As Shane wrote; make it reproducible research + include random seeds, because RF is stochastic.
First of all, plotting single trees forming RF is nonsense; this is an ensemble classifier, it makes sense only as a whole. But even plotting the whole forest is nonsense -- it is a black-box classifier, so it is not intended to explain the data with its structure, rather to replicate the original process. Instead, make some of plots Shane suggested.
In practice, OOB is a very good error approximation; yet this is not a widely accepted fact, so for publication it is better to also make a CV to confirm it.
Comment: The main problem is that it is really hard to compare two models (model=learning method+feature selection method), but for simplicity you can just assume something (like I'll use RF and select top 10 attributes) and admit that you know that this may be suboptimal, but you agree on that while you are for instance satisfied with the accuracy. In that case your only problem is to remove bias of attribute selection. tbc.
Comment: So, I would do a simple bagging: you create 10 (or 30 if you have a good computer) random subsamples of objects (let's say by random picking with replacement), train RF on each, get it's importance and return a rank of each attribute averaged over all repetitions (best attribute gets rank 1, second best 2 and so on; it can be averaged so the attribute that was 12 times 1st and 18 times 2nd have rank of 1.6), finally select 10 with best ranks and call them your markers. Then use a CV (LOO, 10-fold or preferably random sampling) to obtain an error approximation of RF using your markers. tbc.
Comment: Report the ranks (hopefully they should be pretty near 1,2,3...), CV error with its deviation (just count standard deviation of results of each CV round) and OOB error (probably will be identical to CV error). DISCLAIMER: This is not a method for selecting optimal number of attributes -- you need RFE and nested CV to do that. DISCLAIMER2: I haven't worked with such a data, so I don't guarantee that your referees will be happy with it (though I believe they should).
Comment: @danielsbrewer I would do this in some other way (paying more attention to feature selection), but this is correct; yet it is more on the topic of benchmarking RF feature selection than on selecting best markers for your biological problem.
Comment: So @mbq when doing a CV is it valid to firstly do a random forest with all samples selected; doing it twice once with all and secondly with the top 10 variables (which can be quoted in a paper).  Then do a leave-one out cross-validation (selecting the 10 top genes each try) and quote the CV error from that?
Comment: @mbq, sorry to go on, but I am very new to the machine leaning classification area.  So if you wanted to select the best discriminating markers for my sort of problem how would you go about it? and what error would you report?  I appreciate all the input.
Answer: Keep in mind the caveats in the other answers about the plot necessarily being meaningful.  But if you want a plot for illustrative/pedagogical purposes, the following snippet of R might be useful.  Not hard to add "split point" to the edge text if you need it.
to.dendrogram <- function(dfrep,rownum=1,height.increment=0.1){

  if(dfrep[rownum,'status'] == -1){
    rval <- list()

    attr(rval,"members") <- 1
    attr(rval,"height") <- 0.0
    attr(rval,"label") <- dfrep[rownum,'prediction']
    attr(rval,"leaf") <- TRUE

  }else{##note the change "to.dendrogram" and not "to.dendogram"
    left <- to.dendrogram(dfrep,dfrep[rownum,'left daughter'],height.increment)
    right <- to.dendrogram(dfrep,dfrep[rownum,'right daughter'],height.increment)
    rval <- list(left,right)

    attr(rval,"members") <- attr(left,"members") + attr(right,"members")
    attr(rval,"height") <- max(attr(left,"height"),attr(right,"height")) + height.increment
    attr(rval,"leaf") <- FALSE
    attr(rval,"edgetext") <- dfrep[rownum,'split var']
    #To add Split Point in Dendrogram
    #attr(rval,"edgetext") <- paste(dfrep[rownum,'split var'],"\n<",round(dfrep[rownum,'split point'], digits = 2),"=>", sep = " ")
  }

  class(rval) <- "dendrogram"

  return(rval)
}

mod <- randomForest(Species ~ .,data=iris)
tree <- getTree(mod,1,labelVar=TRUE)

d <- to.dendrogram(tree)
str(d)
plot(d,center=TRUE,leaflab='none',edgePar=list(t.cex=1,p.col=NA,p.lty=0))

Comment: The code produces very good tree plot. But the values are not being displayed. Probably a text() function needs to be added after last (plot) statement.


Why is the Prüfer sequence in a labeled tree always unique?

Question: The Prüfer sequence (also Prüfer code or Prüfer numbers) of a labeled tree is a unique sequence associated with the tree.

as we can see from the picture there is a unique sequence {4,4,4,5} #
 but how can we prove that it is unique for a particular tree ?
Edit: Extracting from the wikipedia article on Prüfer sequences, the Prüfer sequence of a labeled tree is defined as follows:

One can generate a labeled tree's Prüfer sequence by iteratively
  removing vertices from the tree until only two vertices remain.
  Specifically, consider a labeled tree T with vertices {1, 2, ..., n}.
  At step i, remove the leaf with the smallest label and set the ith
  element of the Prüfer sequence to be the label of this leaf's
  neighbour.
Comment: It seems like your question is *why* is the code unique for the tree? Referring also to wikipedia :) ... "Somewhat less obvious is the fact that for a given sequence S of length n–2 on the labels 1 to n, there is a unique labeled tree whose Prüfer sequence is S."
Comment: Your question was put on hold, the message above (and possibly comments) should give an explanation why. (In particular, [this link](http://meta.math.stackexchange.com/a/9960) might be useful.) You might try to edit your question to address these issues. Note that the next edit puts your post in the review queue, where users can vote to reopen this. (Therefore it would be good to avoid minor edits and improve your question as much as possible with the next edit.)
Comment: The Prüfer sequence of a labeled tree is ***obviously*** unique, because it is defined by a deterministic algorithm; if you input the same labeled tree again, you are sure to get the same output. The more interesting question, ***which you have not asked***, is why a given Prüfer sequence corresponds to a unique labeled tree.
Comment: Yes, the [Wikipedia article](https://en.wikipedia.org/wiki/Pr%C3%BCfer_sequence) clearly says it's unique.
Comment: Yes, but why it is unique
Comment: @MartinSleziak thank you, I have aupdated !
Answer: The uniqueness of the prufer sequence comes from the fact that the trees are reconstructable.
For example, with $\{4,4,4,5\}$
The first number not in the code is $1$, so we attach vertex $1$ to $4$(the first entry in the code) now drop the $4$ from the code and add a $1$ to the back to get $\{4,4,5,1\}$.
The first number not in the code is $2$, so attach $2$ to $4$, drop the $4$ and add $2$ to the back to get $\{4,5,1,2\}$.
The first number not in the code is $3$, so attach $3$ to $4$, drop the $4$ and add $3$ to the back to get $\{5,1,2,3\}$
The first number not in the code is $4$, so attach $4$ to $5$, drop the $5$ and add $4$ to the back to get $\{1,2,3,4\}$.
Now we have exhausted the entire original code. The final step is to add an edge between the two numbers not shown in our new code, so attach $5$ to $6$.
This will give you back the original tree. Since we have a way to "Uncode" the prufer code, it is unique.
Comment: Do you know a formal proof?
Comment: The original algorithm with the reconstruction algorithm gives you a function and its inverse from labelled trees on $n$ vertices to sequences of length $n-2$ using $1$ through $n$ as the entries. Thus the prufer algorithm is a bijection and thus 1-1. Does that help? If not, try to expand on where you are lost and I will try to help.
Comment: @FawziBelal do you not understand the original algorithm, the reconstruction algorithm or something else?
Comment: Thank you
I understand the example, but since it is just an example, I prefer the solution to be: formal rather than proof by example.
What you have explained: "Prüfer Code" is unique as you claim that it is comes from the construction "is this proof by construction"?
again : what is the point "formally" that guarantee that Prüfer Code => gives always "one" Labeled Tree!?
Comment: The fact that there is a way to decode the tree from the sequence doesn't alone prove it is unique. Imagine a code similar to the Prüfer code but where each vertex $i$ in the code is either labelled $2i$ or $2i+1$. We can reconstruct a tree given this new code, but the code is not unique. You also need a unique way to construct the code from the tree, which we have for the Prüfer code.
Comment: @MichaelMior Sure, but uniqueness follows here because there is a unique way to go from the tree to the code, then a way to go back. Of course, if you change it so that there is not a unique way to go from a tree to the code, there is more work to be done. The unique way to go from tree to code gives us an injection from trees to codes. Showing there is a way to reverse this process gives us that this is also a surjection, and thus a bijection. This is equivalent to showing uniqueness of codes.
Comment: @SeanEnglish Agreed :)


Comparar duas listas de objetos e pegar apenas os diferentes

Question: Estou com problemas para comparar duas listas do mesmo tipo List<Produto> na minha classe produto tenho a seguinte estrutura.
public class Product
    {
        public int IdProduct { get; set; }
        public String Name { get; set; }

        public Supplier supplier { get; set; }

        public Product(){}
    }

E na minha classe de Supplier tenho:
public class Supplier
{
    public int IdSupplier { get; set; }
    public string Main { get; set; }
    public string Name { get; set; }
}

E eu gero uma lista inicial, e uma final. A final contem mais elementos de produtos.
Teste
List<Product> listaProdutosDiferentes = listaPrincipalProdutos.Union(listaFinalProdutos).ToList();

Porem esse teste apenas concatenou as duas listas e não pegando formando uma lista com produtos diferentes do outro.
Edição
Eu tenho duas listas, a primeira tem alguns produtos podendo ser
(id;nome)
1, Celular Motorola One;
2, Celular Motorola G6;
3, Celular Motorola E5;
Na minha segunda lista terá a mesma lista da primeira (Não necessariamente seguindo uma sequência).
5, Celular Samsung Galaxy;
1, Celular Motorola One;
2, Celular Motorola G6;
3, Celular Motorola E5;
4, Celular Iphone 6S;
A minha lista final precisa ser
1, Celular Motorola One;
2, Celular Motorola G6;
3, Celular Motorola E5;
4, Celular Iphone 6S;
5, Celular Samsung Galaxy;
Por que faço isso? pra que quando uma pessoa for fazer uma busca no meu sistema, o sistema apresente primeiro a pesquisa que o cliente fez, exemplo "Celular Motorola", e depois os outros itens que tem um relacionamento, nesse caso outros celulares.
[Duplicada]
Marcaram como duplicada, porem na resposta que deixaram não resolveu meu problema eu fiz os códigos proposto, porem todos não excluem o item que já tem na outra lista, vou mostrar pela imagens:

Aqui tem 4 produtos.

Aqui tem 9 produtos

E na minha lista que deveria ser a lista diferente contem 9 produtos e não 5
Comment: O que esse `Supplier` tem a ver com o problema?
Comment: Só gerei o que eu tenho, pois não sabia se ele poderia influenciar no resultado
Comment: Não esqueça que a classe Product deve prover uma implementação própria dos métodos GetHashCode() e Equals(). Ou use, no método Except(), um "comparador de Products" que implemente a interface IEqualityComparer
Comment: @LeandroPenhalver A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo
Comment: @Maniero olha cara, eu não consegui fazer como vocês fizeram a proposta, ai então eu fiz como deu, joguei isso pra tratar no sql
Answer: Você deve usar o Except() do LINQ, o que uso junta as listas sem distinguir o que já está na outra.
var listaProdutosDiferentes = listaPrincipalProdutos.Except(listaFinalProdutos);

Por outro lado pode ser que queira isto (não tenho como afirmar, a pergunta é um pouco ambígua, veja qual produz o resultado que espera):
var listaProdutosDiferentes = listaPrincipalProdutos.Except(listaFinalProdutos).Concat(listaFinalProdutos.Except(listaPrincipalProdutos));

Ou ainda usar o Intersect():
var listaProdutosDiferentes = listaPrincipalProdutos.Intersect(listaFinalProdutos);

Coloquei no GitHub para referência futura.
Outro ponto é que só deve usar ToList() quando realmente precisa concretizar a lista, pode até ser que seja o seu caso, não tenho como contestar isso, mas pode ser que não precise, então preferi não usar.
Comment: Então, eu preciso que seja uma lista, por que eu ao final do código eu retorno uma lista do tipo produto.
Comment: O código que você fez ali em cima não funcionou, eu preciso comparar as duas listas e depois preciso que esse LINQ me retorne apenas os produtos que não tem na primeira lista.
Comment: Quase sempre as pessoas acham que precisam converter el lista e não precisam, muitas vezes o erro está na API criada. Mas eu não tenho com afirmar neste caso porque não tem informação sobre. Eu dei mais uma opção, se nada disso resolver a pergunta não está clara mesmo.
Comment: Maniero, eu adicionei a pergunta uns resultados para explicar melhor o que eu quero e o motivo de estar tentando fazer dessa forma, caso tenha outra forma de resolver se não no linq não tem problema também.


Spring add default value to form:options in jsp

Question: Is it possible to select some default value in my dropdown list, which is in my .jsp implemented like this:

   <form:label path="month">Select month</form:label>
   <form:select path="month" class="form-control">
   <form:options items="${months}" />
   </form:select>

And in my controller I have method:
private List<String> getMonths() {
    List<String> months = new ArrayList<String>();
    months.add("January");
    months.add("February");
    months.add("March");
    months.add("April");
    months.add("May");
    months.add("June");
    months.add("July");
    months.add("August");
    months.add("September");
    months.add("October");
    months.add("November");
    months.add("December");
    return months;
}

and it is added to .jsp like this:
model.addAttribute("months", getMonths());

I need to have pre-selected some value after loading a page, for ex. "March".
Comment: Maybe look at http://stackoverflow.com/questions/21711670/jstl-preselect-dropwdown-value
Comment: You already did set selected value for the dropdown. Spring will use value in property "month" of the Model as selected value. All you need to do is set "month" property a value from your Java action method.
Answer: You need to iterate through the list using forEach and then use if condition to choose whichever month you want to be selected as default. See below a sample:
<c:choose>
    <c:forEach items="${months}" var="month">
        <c:when test="${month == 'March'}">
            <option value="${month}" selected>${month}</option>
        </c:when>
        <c:otherwise>
          <option value="${month}">${month}</option>
        </c:otherwise>
    </c:forEach>
  </c:choose>

Comment: Now dropdown shows only one value: March, not other months.
Comment: I updated the answer, the previous answer had one if condition hence, it only printed the option when the condition was satisfied and did not print for other values, which is why you had only March.
Comment: I was getting an error without  tag, so I added it, now it's again displaying all values, but ' March  ' is not selected.
Comment:  does not iterate through your list.  iterates through each element of the list and then assign it to **month** variable then  and  is applied to the value of variable month. What was the error?
Comment: I got this:

    org.apache.jasper.JasperException: An exception occurred processing JSP page /WEB-INF/views/myTeams.jsp at line 111

108:
109:           <%--  --%>
110:
111:
112:         ${month}
113:
114:

    Caused by: javax.servlet.jsp.JspTagException: Illegal use of -style tag without  as its direct parent.
Comment: replace the line inside ${month}  with ${month} .
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/94752/discussion-between-raf-and-lenusska1414).


Positive recurrent point, but not negative recurrent in the shift space

Question: Consider the shift space $\Sigma_2 = \{\omega = (...\omega_{-1} \; \omega_0 \; \omega_1, ...) : \omega_i \in \{0, 1\}, \; i \in \mathbb{Z}\}$ and the shift map $\sigma : \Sigma_2 \to \Sigma_2, \; \sigma(\omega)_i = \omega_{i+1}$.
$\omega \in \Sigma_2$ is $\textit{positive recurrent}$ if $\; \exists n_k \nearrow \infty$ such that $\omega = \underset{n_k \to \infty}{lim} \sigma^{n_k}(\omega)$.
$\omega \in \Sigma_2$ is $\textit{negative recurrent}$ if $\; \exists n_k \searrow -\infty$ such that $\omega = \underset{n_k \to -\infty}{lim} \sigma^{n_k}(\omega)$.
The metric we consider is the following:
$$d_\lambda(\omega, \eta) = \sum_{i=-\infty}^{\infty} \frac{|\omega_i-\eta_i|}{\lambda^{|i|}}.$$
Can someon give me a hint on how to find a point in $\Sigma_2$ that is positive recurrent, but is not negative recurrent?
Thank you!
Answer: Hint: To the negative side choose 1's and let $\omega_0=0$. Then it is not negative recurrent. On the positive side construct recursively the sequence so that it contains arbitray long finite sequences of the form $(\omega_{-N},...,\omega_{N-1})$, i.e. given the construction for a given $N$, add that word from $N$ to $3N-1$ and redo the recursive step for $N'=3N$, etc...
Answer: I'll try to give hints only.
Suppose we put some arbitrary word at the origin. Say $u_0 = 00.10$. If our word is right recurrent, then certainly that length-4 word at the origin should appear infinitely often to the right. So let's extend our word to the right by that word to get $u_1 = 00.100010$. Ok, but then how do we extend to the left? Well we don't want the word to be left-recurrent so we should probably avoid the word that is at the origin. The word $0000$ doesn't appear at the origin so let's extend by that to the left to get $u_2 = 000000.100010$.
Can you see what the next step $u_3$ would be? How about $u_4$?
Write a rule for $u_{2k}$ in terms of $u_i$ where $i\leq 2k$. Then do the same for $u_{2k+1}$.
Why does this word have the properties that you asked for?
Comment: I think you might be mistaking the definition of positive recurrent with just recurrent. Otherwise wouldn't the result you stated imply that left recurrence and right recurrence are equivalent? That's what you're trying to prove is false!
Comment: The word isn't left recurrent because the subword $0010$ does not appear anywhere to the left of the origin.
Comment: We have the following property: $\omega \in \Sigma_2$ is positively recurrent iff every block in $\omega$ occurs infinitely often. Hence your word, $00...0 0010 0010 ... 0010$, is positively recurrent. But I don't understand why this word is not negatively recurrent. Can you explain me? Thank you!
Comment: So, the word is positively recurrent because the subword 0010 occurs infinitely often to the right of the origin?
Comment: Not just the word $0010$ but every word that appears in $\omega$, because of how we have constructed $\omega$.
Comment: In general, how can be described positively recurrent but not negatively recurrent points? I have to show that such points are dense in $\Sigma_2$. So I have to prove that in every symmetric cylinder there exists such a point, but I don't know how to describe them in general. Thank you!
Comment: All you have to do is show that for every finite word, there exists a right recurrent bi-infinite word which is not left recurrent that contains the finite word as a subword. You can use the exact same construction as in this answer to show that such a bi-infinite word exists.


Why Clang supports dereferencing uninitialized pointer

Question: I am trying to understand what happened to my knowledge of C programming. Let's start with a CLASSICAL problem (dereferencing uninitialized pointer):
int main( void ) {
    char *p;
    *p = 'a';
    printf( "%c\n", *p );
    return 0;
}

This is obviously WRONG! I know it. However, when I ran this on my MacOS 10.12 with LLVM Clang 8.1.0 implemented as compiler, it not only failed to detect uninitialized pointer, but also displayed the character 'a' on the screen, as if nothing was wrong. At least I expect something like "Segmentation Fault".
Please hold your thought and bear with me a moment to see the following code:
int main( void ) {
    int i;
    char **strPtr;
    char *string = "Hello, world!";

    *strPtr = string;

    printf( "%s", *strPtr );
    return 0;
}

This time, I ran the code with GCC-4.8.5 which has successfully detected the segmentation fault in the first code. To my dismay, the string "Hello, world!" appeared on the screen after I ran the code as if nothing was wrong with it.
I wonder, since strPtr is also a pointer (though a pointer to pointer), by dereferencing and assigning value to strPtr, shouldn't I commit the same fault as I did in the first code?
Comment: Tell your clang that you want it to warn you about such stuff (`-Wall`), and that it should consider such warnings errors (`-Werror`). In other words, use e.g. `clang -Wall -Werror source.c -o binary`.
Comment: Your pointer is not uninitialised. And any god compiler, including clang will warn about a nonsensical conversion. It s not the compiler's fault if you ignore them (or don't enable the recommended warnings)
Comment: "but also displayed the result" - which result? That code does not make any sense, but invokes undefined behaviour.
Comment: When you write a program that invokes undefined behavior, which yours does, _any_ behavior is "correct" with respect to the C standard. Seg faults aren't guaranteed.  You'd get a seg fault if the junk contents of `p` happened to be an address not within a valid segment of the program. As luck would have it, the junk contents of `p` in your case happened to point to read/write memory allocated to your program.
Comment: Truly, compilers' divergence in undefined behaviors explains the question, but how would you enlighten me with the 2nd pice of code?
Comment: @DragScorpio: Which part of `-Wall -Werror` did you miss? If you do not specify any options to the compiler, the compilers default to their own settings, which in many cases is not even standard C. GCC, for example, defaults to a GNU dialect of C. The behaviour you want or expect, you can only get from gcc and clang if you use `-Wall -Werror` options.
Comment: @Nominal Animal: Thanks,  -Wall -Werror options did filter the error out. I did not used the options before.
Answer: It doesn't support it; it's just that the compiler assumes that you know what you are doing.
It's just that the behaviour on dereferencing an unintialised pointer is undefined.
It appearing to work is a manifestation of that undefined behaviour.
Remember the old maxim: C gives you the ability to shoot yourself in the foot.


composer won't update 8.7.10 to 8.8.2 - "Nothing to install or update"

Question: When I try to use composer to update Drupal, it  fails to follow through, and gives me several abandoned items.
Not sure where to go from here, but maybe someone can give pointers on what might be causing the issues, and how to resolve the abandoned packages?
Sorry if this is vague. I don't know what next steps should be.
[user@ip-000-00-00-000 sitefolder]$ sudo -u nginx composer update drupal --with-dependencies
No composer.json in current directory, do you want to use the one at /var/lib/nginx/sitefolder? [Y,n]? Y
> DrupalProject\composer\ScriptHandler::checkComposerVersion
Package "drupal" listed for update is not installed. Ignoring.
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Package container-interop/container-interop is abandoned, you should avoid using it. Use psr/container instead.
Package phpunit/phpunit-mock-objects is abandoned, you should avoid using it. No replacement was suggested.
Package webflo/drupal-core-require-dev is abandoned, you should avoid using it. Use drupal/core-dev instead.
Package zendframework/zend-diactoros is abandoned, you should avoid using it. Use laminas/laminas-diactoros instead.
Package zendframework/zend-escaper is abandoned, you should avoid using it. Use laminas/laminas-escaper instead.
Package zendframework/zend-feed is abandoned, you should avoid using it. Use laminas/laminas-feed instead.
Package zendframework/zend-stdlib is abandoned, you should avoid using it. Use laminas/laminas-stdlib instead.
Writing lock file
Generating autoload files

I also did "composer outdated -Dm" to see what I'd get, if it helps:
sudo -u nginx composer outdated -Dm
No composer.json in current directory, do you want to use the one at /var/lib/nginx/sitefolder? [Y,n]? Y
drupal/browserclass            1.0.0-alpha1 1.0.0-alpha2 Adds a browser class to the body tag.
drupal/core                    8.7.10       8.8.2        Drupal is an open source content management platform powering millions of websites...
webflo/drupal-core-require-dev 8.7.10       8.8.1        require-dev dependencies from drupal/core

I tried composer why-not drupal/core:8.8.1, and 8.8.2 and got:
webflo/drupal-core-require-dev  8.7.10  requires          drupal/core (8.7.10)
drupal/core                     8.8.1   requires          typo3/phar-stream-wrapper (^3.1.3)
drupal-composer/drupal-project  -       does not require  typo3/phar-stream-wrapper (but v2.1.3 is installed)
drupal/core                     8.8.1   requires          pear/archive_tar (^1.4.9)
drupal-composer/drupal-project  -       does not require  pear/archive_tar (but 1.4.8 is installed)

I've also attempted to replace the webflow/drupal-core-require-dev item, and when I did the reinstall, using "composer require --dev drupal/core-dev", I ran into a confusing result:
 Problem 1
    - Conclusion: don't install drupal/core-dev 8.8.2
    - Conclusion: don't install drupal/core-dev 8.8.1
    - Conclusion: don't install drupal/core-dev 8.8.0
    - Conclusion: don't install drupal/core-dev 8.8.0-rc1
    - Conclusion: don't install drupal/core-dev 8.8.0-beta1
    - Installation request for webflo/drupal-core-require-dev (locked at 8.7.10, required as ^8.7.0) -> satisfiable by webflo/drupal-core-require-dev[8.7.10].
    - Conclusion: don't install drupal/core-dev 8.9.x-dev
    - Conclusion: don't install drupal/core-dev 8.8.x-dev
    - Can only install one of: drupal/core[8.8.0-alpha1, 8.7.10].
    - Can only install one of: drupal/core[8.8.0-alpha1, 8.7.10].
    - Can only install one of: drupal/core[8.8.0-alpha1, 8.7.10].
    - drupal/core-dev 8.8.0-alpha1 requires drupal/core 8.8.0-alpha1 -> satisfiable by drupal/core[8.8.0-alpha1].
    - Installation request for drupal/core-dev ^8.8 -> satisfiable by drupal/core-dev[8.8.0, 8.8.0-alpha1, 8.8.0-beta1, 8.8.0-rc1, 8.8.1, 8.8.2, 8.8.x-dev, 8.9.x-dev].
    - Installation request for drupal/core (locked at 8.7.10, required as ^8.7.0) -> satisfiable by drupal/core[8.7.10].

Installation failed, reverting ./composer.json to its original content.

Comment: Firstly, I think `composer update drupal` is flawed. It would probably be `drupal/*`, `drupal/core`, `webflo/drupal-something` depending on what composer project you used (if any). [Check these docs](https://www.drupal.org/docs/8/update/update-core-via-composer#s-special-considerations-for-upgrading-to-drupal-880-and-later) as they cover quite a few scenarios.
Comment: @stevekeiretsu Not sure if it's what you mean, but I tried with 'composer update drupal/core' and got the same result
Comment: sorry, I accidentally submitted the comment before I finished writing it.  I have now included the link to the docs which got me through similar issues last week.
Comment: What does `composer why-not drupal/core:8.8.1` and `composer why-not drupal/core:8.8.2` show?  Bit I highly suspect it is the `webflo/drupal-core-require-dev` requirement, as the project is abandoned in favor of `drupal/core-recommended`.
Comment: @mpdonadio I suspect that's the case too, after reviewing the info in stevekeirestsu 's link. I tried removing it and re-adding and ran into errors.  I add the why-not results for 8.8.1 to the question
Comment: did you `composer remove --dev webflo/drupal-core-require-dev`?  it seems from `Installation request for webflo/drupal-core-require-dev` that it is somehow still being required by your composor.json/lock.  I seem to remember I ended up composer `remove`-ing then `require`/`install`-ing and not actually ever `update`-ing anything.
Comment: @stevekeiretsu yeah, I composer remove'd the webflo before. In fact, I also tried doing the update without re-installing drupal/core-dev. Everything choked and killed the site, so I'm currently re-pulling into my test environment, to try things again. EDIT - side note, while repulling content, I got a strange message: In ` InfoParserDynamic.php line 43:

  The 'core' or the 'core_version_requirement' key must be present in core/mo
  dules/path_alias/path_alias.info.yml `  ... Seems all out of synch
Comment: @stevekeiretsu Got it to work, finally. In the end following the link was the ticket. It just helps if I type ".lock" instead of ".log". hah! thank you!
Answer: As other's have mentioned, drupal/core-recommended should be used going forward.
Try:
composer remove webflo/drupal-core-require-dev --no-update
composer require drupal/core-recommended --no-update
composer update webflo/drupal-core-require-dev drupal/core drupal/core-recommended --with-dependencies
You could also try adding composer require drupal/core:8.8.1 specifically, before running the update command.
Comment: monk , in the end, it was a combination of removing webflow/drupal-core-require-dev as well as the lock file. It didn't work at first because i inexplicably typed ".log" instead of ".lock"
Answer: Sleepingmonk's answer is good, above. What most helped me, though, was to follow the information in the link, provided by stevekeiretsu in one of the sub-comments:
https://www.drupal.org/docs/8/update/update-core-via-composer#s-special-considerations-for-upgrading-to-drupal-880-and-later
For me, it was a combination of removing "webflo/drupal-core-require-dev" as well as the 'composer.lock' file.
Answer: I had the same problem. You have to migrate from webflo/drupal-core-strict to drupal/core-recommended.
Solution and steps are here :
https://www.drupal.org/docs/8/update/update-core-via-composer#migrate-webflo-drupal-core-strict-to-core-recommended

The simplest way to accomplish this migration and avoid conflicts is to remove your composer.lock file entirely as part of the update. However, doing so will mean that other dependencies (e.g. contributed Drupal modules) might be updated, too. Following these steps will ensure that you update exactly what you intend:

composer update # To update any dependencies as a separate step.
git add composer.lock; git commit # Save the updates as a separate commit.
composer remove webflo/drupal-core-strict --no-update
composer remove drupal/core --no-update
composer require 'composer/installers:^1.7' --no-update
rm composer.lock
rm -rf vendor # Also helps avoid conflicts.
composer require drupal/core-recommended:^8.8 --update-with-dependencies
git add composer.json composer.lock; git commit -m "Update Drupal to 8.8.0 and use drupal/core-recommended instead of webflo/drupal-core-strict"
Answer: For a strange reason, I couldn't upgrade from 8.8.1 to 8.8.2 with webflo/drupal-core-require-dev installed.
To resolve it quickly I just:
// Remove webflo
composer remove --dev webflo/drupal-core-require-dev

// Add drupal/core-dev  (This step is not mandatory, only for dev purpose)
composer require --dev drupal/core-dev

// Update Drupal core from 8.8.1 to 8.8.2
composer update drupal/core --with-dependencies

Hope this helps.
Answer: As other answered, you can try to migrate to drupal/core-recommended. I found this Composer plugin very easy to use :
https://github.com/grasmash/composerize-drupal
I've successfully tested it on several Drupal installation.


Como criar uma diretiva em AngularJs que crie uma máscara e não modifiquei o ng-model?

Question: Criei uma diretiva onde a mesma serve de máscara para conta corrente, então quanto digito um valor sempre o valor mais a direita no input é o dígito da minha conta, até então beleza, está funcionando. O problema é que eu não quero alterar o valor do meu ng-model se eu informo por exemplo 123456 deve aparecer na minha view 12345-6 e no meu ng-model deve estar apenas 123456 (sem o traço). O que está acontecendo e que o meu ng-model está sendo alterado (12345-6). Alguém sabe como resolver isso??
Na minha view está correto, a diretiva me atende
OBS.: No canto esquerdo inferior olhe meu ng-model

angular.module('app').directive('contaCorrenteMask', function () {
    return {
        restrict: 'A',
        require: "ngModel",
        link: function (scope, element, attrs, ctrl) {

            var _formatContaBanco = function (data) {

                if (!data)
                    return data;

                if (data.length == 1)
                    return data;

                data = data.replace(/[^0-9]+/g, "");

                var digito = data.slice(-1);
                var conta = data.slice(0, -1);

                return conta + '-' + digito;
            };

            // Send out changes from inside:
            scope.$watch(attrs.ngModel, function (val) {
                scope.model = val;
                ctrl.$setViewValue(_formatContaBanco(scope.model));
                ctrl.$render();
            });
        }
    };
})
Answer: Então seu problema é que você está usando o setViewValue.
ctrl.$setViewValue(_formatContaBanco(scope.model));

Isso faz com que o ngModel também seja atualizado, para ter o viewValue e modelValue diferentes você deve usar:
Formata o texto do ngModel para o view
ngModel.$formatters.push(function(value) {
   return value.toUpperCase();
});

Formata o texto do view para o ngModel
ngModel.$parsers.push(function(value) {
   return value.toLowerCase();
});

Agora o seu código corrigido
angular.module('app').directive('contaCorrenteMask', function () {
    return {
        restrict: 'A',
        require: "ngModel",
        link: function (scope, element, attrs, ctrl) {

            var _formatContaBanco = function (data) {

                if (!data)
                    return data;

                if (data.length == 1)
                    return data;

                data = data.replace(/[^0-9]+/g, "");

                var digito = data.slice(-1);
                var conta = data.slice(0, -1);

                return conta + '-' + digito;
            };

            // Send out changes from inside:
            ctrl.$formatters.push(function (modelValue) {
                return _formatContaBanco(modelValue);
            });
        }
    };
})


Javascript restrict special chracters in a username field

Question: I found a premade form on the internet I am integrating into my site. However this registration form allows the use of any character. I am trying to limit it to just A-Z, a-z, 0-9, underscores, and spaces.
<code>$(function(){

var form    = $('form');
var submit  = $('#submit');
var alert   = $('.alert');

$.validator.addMethod("regex", function(value, element, regexp) {
var check = false;
var re = new RegExp(regexp);
return this.optional(element) || re.test(value);
},
"No special Characters allowed here. Use only upper and lowercase letters (A through Z; a through z), numbers and punctuation marks (. , : ; ? ' ' \" - = ~ ! @ # $ % ^ & * ( ) _ + / < > { } )"
);

// validate form
form.validate({
    // validation rules
    rules: {
        // name field (required , minimum length 3)
        name: {
            required: true,
            minlength: 3,
            maxlength: 25
        },
        // username field (required , minimum length 3, max 8)
        username: {
            required: true,
            minlength: 3,
            maxlength: 8,
            regex: /^[a-zA-Z0-9_]+$/
        },
        // password field (required , minimum length 6, max 16)
        password: {
            required: true,
            minlength: 6,
            maxlength: 16
        },
        // password2 field must be equal to password field
        password2: {
            equalTo: '#password'
        },
        // email field only required
        email: 'required'
    },
    // submit ajax request
    submitHandler: ajaxSubmit
});

// jQuery ajax submit function
function ajaxSubmit() {
    $.ajax({
        url: 'ajax.php',
        type: 'POST',
        // form serialize data
        data: form.serialize(),
        beforeSend: function(){
            alert.fadeOut();
            submit.val('Sending...').attr('disabled', 'disabled');
        },
        success: function(data){
            console.log(data);
            if ( data.status === 'success' ) {
                // if responce status == success redirect to success page
                $(location).attr('href','success.html');
            } else {
                // not success! show error messages
                alert.html(data.status).fadeIn();
                submit.val('Sign Up').removeAttr('disabled');
            }
        },
        error: function(e){
            console.log(e);
            // show error message
            alert.html('Sending request fail').fadeIn();
            submit.val('Sign Up').removeAttr('disabled');
        }
    });
};
});
</code>
This is the javascript code that I am trying to edit. I just am unsure what to add for the username to limit the characters. I have tried searching google but all the answers I found come up with a function which I am unsure how to add into this.
Comment: Take a look at regular expressions (regex), they will do what you want :)
Comment: This looks like you're probably using [this jQuery validation library](http://jqueryvalidation.org/). Is that correct?
Comment: Sorry I am new to JS, Jquery, AJax, etc. But yes I think this is jQuery validation.
Comment: @user3764729: Look at the scripts being included in the page to be sure. But it certainly looks like it is.
Answer: check this link denying special characters jQuery Validate and below code for you
<code>$.validator.addMethod(
"regex",
function(value, element, regexp) {
    var check = false;
    var re = new RegExp(regexp);
    return this.optional(element) || re.test(value);
},
"No special Characters allowed here. Use only upper and lowercase letters (A through Z; a through z), numbers and punctuation marks (. , : ; ? ' ' \" - = ~ ! @ # $ % ^ & * ( ) _ + / < > { } )"
);

username:{
required: true,
        minlength: 3,
        maxlength: 8,
         regex:/^[a-zA-Z0-9_]+$/
}
</code>
Comment: Numeric digits are also allowed :)
Comment: replace  regex:/^[a-zA-Z0-9\_]+$/
Comment: Now thats similar to mine answer! ;)
Comment: am I able to just add "regex: /^[a-zA-Z0-9_]+$/" to the username or do I need the $.validator.addMethod to? I will add the entire .js script to first post.
Comment: Ok, I added that method to the very top of the script. Should I put it just above the username validation part?
Comment: just above form.validate({
Comment: Ok, I have added it and updated my first post with the code as it stands now. I have tried to register with a username such as "d@b!d=-" and it still gets put into the database.
Comment: check this  regex:/^[A-Za-z\d=#$%...-]+$/
Comment: Tried with the username "admin=-@1" and it still went through. Also, I am using Cpanel code editor and it has highlighted some of that code a tan color. /^[A-Za-z\d has been highlighted
Comment: after doing some more testing it appears I have another problem. my validation isn't working properly. I am able to add a name, username, and even password that all consist of 1 letter. Something isn't working right.
Comment: add check with form.valid() in your ajaxSubmit method
Comment: I am unsure how to do that.


Why would you use EAP-TTLS instead of PEAP?

Question: As I understood EAP-TTLS and PEAP share same level of security when implemented in wireless networks. Both only provide server side authentication via certificate.
The drawback of EAP-TTLS can be non native support in Microsoft Windows so every user has to install additional software.
The benefit of EAP-TTLS can be support for less secure authentication mechanisms (PAP, CHAP, MS-CHAP) but why would you need them in modern and properly secure wireless system?
What are you opinions? Why should I implement EAP-TTLS instead of PEAP?
Let's say that I have most Windows users, medium Linux users and least iOS, OSX users.
Answer: Client restrictions

iOS clients won't support EAP-TTLS with PAP (only MsCHAPv2) unless you manually (via a computer) install a profile.
Windows clients won't support EAP-TTLS out-of-box (you'll need to install a software like secure2w), unless they have Intel wireless cards.
Android support almost all combinations of EAP and PEAP.

Password database restrictions
Thus, the real problem is how your passwords are stored.
If they are in:

Active Directory, then you can use EAP-PEAP-MsCHAPv2 (Windows boxes) and EAP-TTLS-MsCHAPv2 (with iOS clients).
If you store passwords on LDAP, you can use EAP-TTLS-PAP (Windows boxes) but you will be lost about iOS.

Important Security Concerns

Both EAP-TTLS and PEAP use TLS (Transport Layer Security) over EAP(Extensible Authentication Protocol).

As you may know, TLS is a newer version of SSL and works based on certificates signed by a trusted central authority (Certification Authority - CA).
To establish a TLS tunnel, the client must confirm it is talking to the correct server (In this case, the radius server used to authenticate users). It does that by checking if the server presented a valid certificate, issued by a trusted CA.
Problem is: normally, you won't have a certificate issued by a trusted CA, but one issued by an ad-hoc CA you made just for this purpose. Operational system will complain to users that it doesn't know that CA and users (as oriented by you) will happily accept that.
But this poses a major security risk:
Someone can setup a rogue AP inside your business (in a bag or even on a laptop), configure it to talk to his own radius server (running on his laptop or at the own rogue AP).
If your clientes find this AP to have a stronger signal then your access points, they will try connecting to it. Will see an unknown CA (users accept), will establish a TLS tunnel, will send authentication information on this tunnel and the rogue radius will log it.
Now the important part: if you are using a plain text authentication scheme (PAP for example), the rogue radius server will have access to your users passwords.
You can solve that by using a valid certificate issued by a Certification Authority both iOS, Windows (and Android) trust. Or, you can distribute the CA root certificate to your users and inform them to refuse connecting when they see certificate problems (good luck with that).
Comment: really great stuff & thanks for raising solid security knowledge here
Comment: What you've done here is sold the importance of still using a good password scheme (e.g. MS-CHAP-v2), though the CA issue isn't a problem for managed devices (e.g. corporate workstations/phones/etc) as an administrator would be able to add the CA to the OS' trust in advance.
Answer: PEAPv0, PEAPv1 and TTLS have the same security properties.
PEAP is a SSL wrapper around EAP carrying EAP.
TTLS is a SSL wrapper around diameter TLVs carrying RADIUS authentication attributes.
EAP-TTLS-PAP can be useful (rather than EAP-PEAP or EAP-TTLS) if the backend authentication database store credentials in a non-reversable hash format such as bigcrypt or any form not compatible with MSCHAP (NT-OWF) In this case it is not possible to authenticate using any of the CHAP based methods.
While you could also emulate PAP using EAP-PEAPv1-GTC this is not as widely supported by clients.
PEAP has some added baggage over TTLS in the form of PEAP version negotiation headaches and historical incompatibilities in PEAPv1 (Such as client magic when deriving master key from PRF) which have made their way into early implementations.
I normally see EAP-TTLS implemented in embedded clients such as subscriber modules in wireless gear with PEAP used more by laptop computers and mobile handsets.
EAP-TTLS has historically not been supported in Windows clients without having to install third party software. EAP-TTLS is now supported starting with Windows 8.
Some additional thoughts:
EAP-TTLS was invented by a RADIUS vendor.
EAP-PEAPv0 was invented by Microsoft.
EAP-PEAPv1 came out of the IETF process.
There was some additional IETF work on a PEAPv2 which would have made the system more secure by way of crypto bindings to inner authentication methods.  This has not gone anywhere as near as I can tell.
Answer: As disk eater wrote, the main reason people use TTLS is you can allow your radius server to see the cleartext password that way, which can be useful depending on your authentication backend.
A newer consideration that might favor PEAP is that SoH is AFAICT only presented to the RADIUS server if it asks for it, and the only way to ask for it on Microsoft systems is during a PEAP session.  So if you want to get agent-like assessment out of agentless assessment (support by more AV vendors probably forthcoming) you'd want PEAP, however if you are looking to work around a 1-factor OAUTH backend by taking a naked password (because heck, the big IDPs that won't provide an inner tunnel service deserve no less and their users are clueless enough to type it in) use TTLS.
Answer: You can support both, if your RADIUS backend supports it. However some clients "auto"-connects (Mac OS X >= 10.7 + iOS for example), and they might work less than optimal if you support more than one type, since they just try different combinations until one of them works i.e. they  connect with less hassle if there's only one way to connect.
So Basically: support PEAP only, or PEAP+TTLS if you have clients that require TTLS.
Answer: You have to consider what EAP methods the client supports natively vs. with additional software and what inner authentication methods the server supports.
PEAP and EAP-TTLS are designed to let you validate the identify of the server, but you have to make sure that clients are properly configured to validate the certificate.
PEAP and MS-CHAPv2 are well-supported by clients, but if your server doesn't support MS-CHAPv2 (because you don't store cleartext passwords), you have to come up with another solution. That's the main reason you'll see people use EAP-TTLS and PAP.
Answer: I think auto-connect would benefit from both options, the more options the less hassle...
eg. if auto-connect tries TTLS-PAP first and then PEAP-MSCHAP, the auto-connect is faster with TTLS-PAP available. So basically: support both, I can't see a disadvantage.
Since MSCHAPs security is broken (google for "crack mschap") pap with cleartext password through ttls has the same level of security as PEAP-MSCHAP.
Answer: I don't know of any differences in security between EAP-TTLS and PEAP, so it basically comes down to support, where PEAP is the winner.


Equivalent norms proof

Question: Is the standard $L^2$ norm
$$\|u\|^2=(u,u)$$
equivalent to a weighted $L^2$ norm
$$\|u\|^2_g =(gu,u)$$
with g>0? If so, how can one prove this?
Comment: @uniquesolution $g$ is an operator, not a constant
Comment: If $g$ is a function (that is not clear as you've written your question), then you should add an assumption on $g$, because if you take $g=\exp(x^2/2)$ for example, then $u(x)=\exp(-|x|/2)$ has a finite $L^2$ norm but not in the weighted norm.
Comment: What does $g$ stand for? A scalar? A function? A linear operator?
Answer: It depends. If $g \in L^{\infty}(X, \mu)$ with $\def\essinf{\mathop{\rm ess\,inf}}\essinf g > 0$, then obviously
$$ \essinf g \int_X |u|^2\, d\mu \le \int_X g|u|^2\, d\mu \le \|g\|_{\infty}\int_X |u|^2 \, d\mu $$
so the answer is yes, if on the otherhand $\essinf g = 0$, then for every $n \in \mathbf N$, there is a measurable $A_n$ with $\mu(A_n) > 0$, $g|_{A_n} \le \frac 1n$. Now let $u_n := \chi_{A_n}$, we have
\begin{align*}
  \|u_n\|^2 &= \int_{A_n}\, d\mu\\
            &= \mu(A_n)\\
  \|u_n\|_g^2 &= \int_{A_n} g\, d\mu\\
            &\le \frac 1n \mu(A_n)
\end{align*}
So
$$ \frac{\|u_n\|_g^2}{\|u_n\|} \le \frac 1n \to 0$$
and $\|\cdot\|_g$ and $\|\cdot\|$ are not equivalent.

Equivalent norms proof


Jenkins startup process: how delete or fix warning messages

Question: When I execute:
java -jar jenkins.war --httpPort=9090

For 2.25 version, the app starts up and works fine but I did realize in the terminal/console always appears these two warnings:
Main deleteWinstoneTempContents
WARNING: Failed to delete the temporary Winstone file /var/folders/nf/ql69b5zd7w54jw6nb5zmvck80000gn/T/winstone/jenkins.war

and
org.eclipse.jetty.util.log.JavaUtilLog warn
WARNING: Empty contextPath

How I can fix them? Even when they are warnings, I want remove them.
For the first, yes, I've confirmed the path only exists until /var/folders/nf/ql69b5zd7w54jw6nb5zmvck80000gn/T/, the rest winstone/jenkins.war does not exist.
Why does the second appear?
Answer: I have faced the same issue.But i fixed it.Please download apache-tomcat-8.5.16 or the latest one.Run the startup.bat file and type http://localhost:8080/ and you will see Apache Tomcat up & running on your local host.
Now run java -jar jenkins.war and type http://localhost:8080/jenkins/ and jenkins will be up and running on your local host.
Hope it will solve your issue.
Comment: You can also start jenkins (standalone) on different port                            run java -jar jenkins.war --httpPort=9090
Comment: Is just a warning, is not critical. be aware both can't use the same port. Therefore `--httpPort` is mandatory
Answer: Corrected Command:
java -jar jenkins.war -httpPort-9090


Warning: mysqli_connect(): (HY000/1044): Access denied for user ''@'localhost' to database 'dbtest'

Question: When i try to connect to my sql server, it gives me the error:

Warning: mysqli_connect(): (HY000/1044): Access denied for user ''@'localhost' to database 'dbtest'.

I just created the user and gave it all permissions, but i still dosent work. Before i used another account, but i couldn't change the database perssions for it. Anybody who have a potential fix?
Here is the connect code.
<?php

    // this will avoid mysql_connect() deprecation error.
    error_reporting( ~E_DEPRECATED & ~E_NOTICE);
    // but I strongly suggest you to use PDO or MySQLi.

    $DBHOST= "localhost";
    $DBUSER= "testadmin";
    $DBPASS= "";
    $DBNAME= 'dbtest';

    $conn = mysqli_connect(localhost, testadmin, $DBPASS, dbtest);
//  $dbcon = mysql_select_db($DBNAME);

    if ( !$conn ) {
        die("Connection failed : " . mysql_error());
    }

?>

Comment: _Note:_ You're mixing API's. `mysqli_*` and `mysql_*` are _not_ the same or interchangeable. You should also wrap strings in quotes (`'localhost'` instead of `localhost` etc).
Comment: _"this will avoid mysql_connect() deprecation error"_ **1.** You're not using `mysql_connect()`. **2.** Instead of hiding problems, solve them. Suppressing errors is a really bad practice, making it much harder for you to debug your own code.
Comment: Possible duplicate of [mysql\_connect(): No connection could be made because the target machine actively refused it](https://stackoverflow.com/questions/21987746/mysql-connect-no-connection-could-be-made-because-the-target-machine-actively)
Answer: I know this thread is old, but Ahmad Sharif is correct. The best way to quickly resolve this issue, especially if you're with a new hosting company, is to just create a new database using the "MySQL Database Wizard" in cPanel, then grant ALL privileges to everyone to ensure the remote access will work. Just make sure that ALL check boxes are checked while creating the new database from the "MySQL Database Wizard".
Answer: In my case grant all privileges to 'my_user' solved the problem
GRANT ALL PRIVILEGES ON *.* TO 'my_user'@'%' ;

You can check the following link for further information
https://mariadb.com/kb/en/grant/
Answer: There is no host, no user and no db-name in your mysqli_connect call. Do:
$conn = mysqli_connect($DBHOST, $DBUSER, $DBPASS, $DBNAME);

or
$conn = mysqli_connect('localhost', 'testadmin', $DBPASS, 'dbtest');

And if you wouldn't suppress E_NOTICEs, you'd see that php is looking for undefined constants.
Comment: $conn = mysqli_connect(localhost, 'testadmin', $DBPASS, 'dbtest');
Comment: @FirozAhmad - You should wrap `localhost` inside quotes as well, unless there are some unknown constant called `localhost` in the code.
Comment: I tried you solutions, but it unfortunatly still dosen't work, i have changed the code to

        $conn = mysqli_connect('localhost', 'testadmin', $DBPASS, 'dbtest');
    // $dbcon = mysql_select_db($DBNAME);

     if ( !$conn->connect_erno) {
      printf("Connection failed: %\n", $conn->error);
     }
Comment: @ChristianFrandsen and what error does it print now?
Comment: @simon.ro It still comes with the error "Warning: mysqli_connect(): (HY000/1044): Access denied for user ''@'localhost' to database 'dbtest' "
Comment: @ChristianFrandsen - Are you sure that you're using the correct credentials? Are you sure this is where the error actually happens? (since you actually are passing the username).
Comment: smile @MagnusEriksson
Comment: Did you assign the user with the database? @Christian Frandsen
Comment: @simon.ro i just restarted the sql server, and now im getting a different error. Warning: mysqli_connect(): (HY000/2002): No connection could be made because the target machine actively refused it.
Answer: Please check that you check all grant privileges. If you do not then delete the previous DB and create a new Db from Mysql Database Wizard (I guess it is shared hosting). In the last step, you can check all the privileges.
I have got the same error and I could solve my problem by grant all privileges.
Answer: I don't know if anyone had a solution to this I have just been trying to create a separate table for a list of emails with a same key column. I got exactly the same error message but solved it by writing a php file which i can run on the server.... The php file creates the table ! And it had permissions to let me write to it as well !
Here is the file i used to let the server make the table i needed. And let me access it from my other php files. I will call it here "LetServerMakeTable.php" ha! When i uploaded it to my 'ricky' heliohost server i ran it on the browser thus:
http://virowiz.heliohost.org/LetServerMakeTable.php
Result:... I had a php file which collecter email addresses and a used ID code and the wrote it successfully to my new Emails table within my database.

<?php
$conn = mysqli_connect("localhost", "virowiz_Kevin", "password", "virowiz_Covid3a");

// Check connection
if (!$conn)         //<---- ! conn = NOT conn
    {
    echo "Failed";
        die("Connection failed: " . mysqli_connect_error());
    }
else
    {
    echo "Connected successfully";
    }

//---------------------------------- Create the table.
$sql = "CREATE TABLE Emails
(
CVTRn BIGINT(12),
Email char(254),
Mobile char(13)
)";
//----------------------------------

mysqli_error($conn);

if (mysqli_query($conn, $sql))
    {
        echo "Table created successfully";
    }
else
    {
        echo "Error creating table: " . mysqli_error($conn);
    }

mysqli_close($conn);

?>

Comment: Hello Myself... I have made a mistake: The HY000/1044 arose for me because in phpmyadmin I created the first file with the MySql Databases  facility - which gave me a page of permissions to modify (i accepted them all) and the 2nd unsuccessful time with the MySQL database Wizard. Which at that time did not give me a permissions page to alter or accept. The table created resulted in php files returning a permissions error. With me the jury is still out as to whether this is the reason but one way works and the other doesnt. Kevin.


drupal panels ipe toolbar

Question: I added custom buttons to the panels ipe toolbar. The toolbar only shows when you have the right permissions, and when the page is a panelized page. I want to display the ipe toolbar also for other pages, containing that page his tabs (view/edit/devel/translate). Is it possible?
Answer: yes, this is possible. I had a similar need in one of my projects. What I did in a custom module was:

Use hook_page_alter to add the ipe toolbar when buttons DON'T exist (Panels IPE adds them when they do exist)
Use hook_theme_registry_alter to use my own template function instead of the one provided by Panels IPE.
Create a custom theme function that adds my custom buttons

In code it is something like this:
/**
 * Implements of hook_page_alter()
 */
function MYMODULE_page_alter(&$page) {
  // Check if Panels IPE is turned on.
  if (!module_exists('panels_ipe'))
    return;

  // Let Panels IPE add the buttons if they exist > If there are no buttons
  // then we'll still add the toolbar anyway.
  $buttons = &drupal_static('panels_ipe_toolbar_buttons', array());
  if (!empty($buttons)) {
    return;
  }

  $output = theme('panels_ipe_toolbar', array('buttons' => $buttons));

  $page['page_bottom']['panels_ipe'] = array(
    '#markup' => $output,
  );
}

/**
 * Implements hook_theme_registry_alter().
 */
function MYMODULE_theme_registry_alter(&$theme_registry) {
  // Check if Panels IPE is turned on.
  if (!module_exists('panels_ipe'))
    return;
  // Inject our own theme function instead of the one from Panels IPE
  $theme_registry['panels_ipe_toolbar']['function'] = 'theme_MYMODULE_panels_ipe_toolbar';
}

// This function is to be adjusted to add buttons and things.
function theme_MYMODULE_panels_ipe_toolbar($vars) {
  $buttons = $vars['buttons'];

  $output = "
";
  foreach ($buttons as $key => $ipe_buttons) {
    $output .= "
";

    // Controls in this container will appear when the IPE is not on.
    $output .= '
';
    foreach ($ipe_buttons as $button) {
      $output .= is_string($button) ? $button : drupal_render($button);
    }
    $output .= '
';

    // Controls in this container will appear when the IPE is on. It is usually
    // filled via AJAX.
    $output .= '

';
    $output .= '
';
  }

  $output .= "
";

  return $output;
}

drupal panels ipe toolbar


Why does Chebyshev's inequality yield that the probability of Laplacian noise being bigger than x is bounded like this?

Question: I am trying to understand this proof of the bounds of Laplacian noise used in a paper on differential privacy.
Given a random variable $Lap\left ( \frac{\Delta f}{\varepsilon } \right )$, apparently the probability that the Laplacian noise is bigger than $x$ is bounded by:
$\mathbb{P}\left [ \left | Lap\left ( \frac{\Delta f}{\epsilon } \right ) \right | > x \right ]= e^{-\frac{x \cdot \epsilon}{\Delta f}}$
The proof for this is that the variant below of Chebyshev's inequality "directly" yields this result:
$\mathbb{P}\left [ \left | X - E\left [ X \right ] \right | \geq k^{2}\right ]\leq \frac{\sigma^{2}}{k^{2}}$
The paper doesn't explain this, since it should be very obvious. It is not obvious to me. This is what I did so far:
$E\left [ X \right ]$ denotes expected value.
If I understand it correctly $E\left [ X \right ] = 0$ for
I also think I understand that $\sigma^{2} = \frac{2\cdot \left ( \Delta f \right )^{2}}{ \epsilon^{2}}$ for $Lap\left ( \frac{\Delta f}{\varepsilon } \right )$
But how do you get from that to this: $e^{-\frac{x \cdot \epsilon}{\Delta f}}$??
My first (and only step):
$\mathbb{P}\left [ \left | Lap\left ( \frac{\Delta f}{\varepsilon } \right ) \right | \geq x\right ]\leq \frac{\frac{2\cdot \left ( \Delta f \right )^{2}}{ \epsilon^{2}}}{x}$
Apparently the rest should be completely obvious, but I am completely stumped.
Answer: This can be shown without Chebyshev's inequality. The pdf of a Laplace distribution with scale parameter $b$ and mean $0$ is $f(x) = \frac{1}{2b}e^{-\frac{|x|}{b}}$. Using the symmetry of the distribution about $0$:
$\mathbb{P}(|Lap(b)| > c) = 2\mathbb{P}(Lap(b) > c) = 2\int_c^\infty\frac{e^{-\frac{x}{b}}}{2b}dx = e^{-\frac{c}{b}}$
Comment: It does seem unlikely that you would be able to prove an equality from an inequality.
Comment: Your approach makes complete sense to me. Reading it I started doubting whether you can even use Chebyshev's inequality to come to the same result. You would have to use the pdf anyway, at wich point using Chebyshev seems moot. What do you think?


On the fractional parts of the roots of the Alternating Harmonic Numbers

Question:
We define $$\bar{H}_x=\ln2+\cos(\pi x)\left(\psi(x)-\psi\left(\frac x2\right)-\frac1x-\ln2\right)$$As the $x$th Alternating Harmonic Number (test out a few values to see why). Let $x_n$ be the $n$th largest zero of the Alternating Harmonic Numbers, show that $\lim_{n\rightarrow\infty}\{x_n\}=\eta$ converges (where $\{x\}$ denotes the fractional part of $x$) or equivalently $\lim_{n\rightarrow\infty}(x_n-x_{n+1})=1$.

This definition of the alternating harmonic number originates from my terribly formatted paper where I generalize sigma notation for non-integer upper and lower bounds. Graphically speaking, the conjecture (I called it so in my paper because I couldn't solve it) seems to be true and $\eta\approx-0.431$. Some interesting approximations are $\frac{7\pi}{51}$ and this seemingly random integral $$\int_0^1\frac{\bar{H}_x\bar{H}_{-x}\sin(\pi x)}{\pi x}dx\approx0.43141591$$Not only does it hold for three digits, but there is a decimal representation of pi mixed in, up to 5 accurate decimal digits. Anyway, using the reflection formula derived for $\bar{H}_x$: $$\bar{H}_x-\bar{H}_{2-x}=\pi\cot(\pi x)-\left(\frac1{1-x}+\frac1x-\frac1{2-x}\right)\cos(\pi x)$$ we get that the conjecture is equivalent to finding the limit of the fractional part of the roots of $$\bar{H}_x-\bar{H}_{2-x}+\ln2=\ln2+\pi\cot(\pi x)-\left(\frac1{1-x}+\frac1x-\frac1{2-x}\right)\cos(\pi x)$$I got stuck here.
Comment: If $x_n$ converges to a finite limit as $n\to\infty$, then surely $x_n-x_{n+1}$ converges to zero, not $1$.
Comment: @GerryMyerson Good point, I forgot to add something.
Answer: I finally solved the conjecture. Notice that as $x$ approaches negative infinity, the reflection formula becomes $\ln2+\pi\cot(\pi x)$ and so $\ln2+\pi\cot(\pi x_n)\sim0$. Solving for $x_n$ we get that $x_n\sim-n-\frac1{\pi}\arctan\left(\frac{\pi}{\ln2}\right)$ implying that $\eta=-\frac1{\pi}\arctan\left(\frac{\pi}{\ln2}\right)$, which agrees with numerical evidence ($\eta\approx-0.430876945137$) and has nothing to do with the integral in the OP.