Como eu faço para Mudar o conteúdo da tela usando php

Question: Tenho um sistema que ele possui duas possibilidades de uso para o usuário:
1.manual
2.automatica
queria que o usuário pudesse escolher entre essas duas versões no estilo input type='radio'. Assim só atualizando a página com o conteúdo que o cliente escolheu (manual ou automático)

                    <?php
                    include "TopoLogado.php";
                    ?>

     <form action="Atividade.php">
    <INPUT TYPE="RADIO" NAME="OPCAO" VALUE="1">Kanban Automático
    <INPUT TYPE="RADIO" NAME="OPCAO" VALUE="2">Kanban Manual
    <input type="submit" value="atualizar">
    </form>

Tarefas de <?php echo $tblDetalhes['nome_ATIVIDADE'] ?>

                    <?php
                    if($_POST["OPCAO"]==1 ){

                    include 'KANBAN1.php';

                    } else if ($_POST["OPCAO"]==2){
                         include 'KANBAN2.php';
                    }
                    ?>

                        <?php include "Rodape.php"; ?>

Pensei em fazer dessa forma também:

<input id="xs" value="Leia Mais" style="margin-left: 50px; padding: 0px; width: 80px; " onclick="if (this.parentNode.parentNode.getElementsByTagName('div')[1].getElementsByTagName('div')[0].style.display != '') { this.parentNode.parentNode.getElementsByTagName('div')[1].getElementsByTagName('div')[0].style.display = '';this.innerText = ''; this.value = 'Ocultar'; } else { this.parentNode.parentNode.getElementsByTagName('div')[1].getElementsByTagName('div')[0].style.display = 'none'; this.value = 'Leia Mais';}" type="button">

<?php include 'KANBAN1' ?>

Mas a primeira funciona, mas a segunda não (aparece o mesmo conteudo da primeira)
Comment: Coloque: `` e teste.
Comment: Por favor, poste o código que você possui para complementar sua pergunta. Dessa forma fica mais fácil pra comunidade poder ajudar.
Comment: @PauloImon pronto
Comment: Não seria só configurar o seu `` pra enviar os valores por `POST` para essa mesma página? Já está até fazendo a condição com os valores recebidos. Não entendi qual a sua dificuldade.
Comment: não está funcionando
Comment: @PauloImon opa, é isso mesmo +1 pro seu comentário.
Comment: Que bom! Precisando estamos aí.
Answer: Se entendi o que você quer é que quando depois da pessoa escolher uma opção essa opção ficasse salva, é isto?
E também tem o que o @Paulo disse, troque o form por:
 <form action="" method="post">

O action="" vai atualizar a página atual, assim não precisará informar a URL
Se for o caso então você pode usar cookies, deve ficar assim o seu código:
<?php
if (!empty($_POST["OPCAO"])) {
     if ($_POST["OPCAO"] == 1 || $_POST["OPCAO"] == 2) {
        //Atualiza o valor quando o usuário solicitar (o cookie expira em um ano)
        setcookie('temakaban', $_POST["OPCAO"], time() + 31536000, '/');
        $_COOKIE['temakaban'] = $_POST["OPCAO"];
     }
}
?>

....

                    <?php
                    include "TopoLogado.php";
                    ?>

    <form action="" method="post">
    <INPUT TYPE="RADIO" NAME="OPCAO" VALUE="1">Kanban Automático
    <INPUT TYPE="RADIO" NAME="OPCAO" VALUE="2">Kanban Manual
    <input type="submit" value="atualizar">
    </form>

Tarefas de <?php echo $tblDetalhes['nome_ATIVIDADE'] ?>

                    <?php
                    //Por padrão usará KANBAN1, acaso o usuário não tenha escolhido
                    if(empty($_COOKIE["temakaban"]) || $_COOKIE["temakaban"] == 1){
                         include 'KANBAN1.php';
                    } else if ($_COOKIE["temakaban"]==2){
                         include 'KANBAN2.php';
                    }
                    ?>

                        <?php include "Rodape.php"; ?>

Comment: obrigadaa ^---^
Comment: Funcionouu, muito obrigadaaa
Comment: por algum motivo mesmo eu selecionando a opção 2, volta para a 1
Comment: @J.Jones opa, vou testar e já te aviso
Comment: editei a pergunta
Comment: @J.Jones atualizei a resposta, troquei session por cookie, porque a sessão  é destruída quando fecha o navegador, dessa forma deve funcionar melhor, tinha um erro na if também, já corrigi.
Comment: em vez de echo não deveria ser include?
Comment: @J.Jones tanto dentro de um include quanto fora o funcionamento será o mesmo, o código é só um exemplo de uso pra explicar como funciona, você pode adaptar como desejar.
Comment: é que dá esse erro quando eu coloco o include no lugar do echo : Warning: include(KANBAN2.php): failed to open stream: No such file or directory in
Comment: aparece nas duas páginas, tanto na dois quanto na um
Comment: não precisa se desculpar
Comment: @J.Jones  corrigi o código. O KANBAN2.php e o KANBAN1.php estão na mesma pasta?
Comment: sim, estão na mesma pasta
Comment: você esta usando esses includes em outras páginas? O erro `Warning: include(KANBAN2.php)` continua?


Command line option 'r' [from -r'] is not known

Question: I am trying to install CUDA. The tutorial is here. When I am trying to install the required headers, I get an error.
This is my command
sudo apt-get install linux-headers-'uname -r'

This is the output
root@ubuserver3:/home/ubuadmin# sudo apt-get install linux-headers-'uname -r'
E: Command line option 'r' [from -r'] is not known.

What has happened? I am not a Linux person, FYI. I am just copying and pasting those commands from the tutorial.
Answer: The uname -r is a linux command that is supposed to be executed prior to the execution of the apt-get command.
In order to make this work you need to use back-tick characters, not the forward-single-quote characters.
On my keyboard, the back-tick is on the upper left corner key on the same key as ~:
this:
sudo apt-get install linux-headers-`uname -r`

not this:
sudo apt-get install linux-headers-'uname -r'

Answer: try 'uname -a'
It will tell you what version you have to download

Command line option 'r' [from -r‘] is not known


WordPress: LinkedIn Posting Link doesn't show meta og description or title

Question: Does anyone else have this problem or can you see what may be wrong on my end?
Problem: If I go to LinkedIn (business or personal) and post a link to one of my websites:

https://inventivewebdesign.com/
https://www.revealio.com/

I get the image, but I don't get the title or description. Both sites are using WordPress with the latest version of Yoast SEO. I asked LinkedIn and they just said that my meta og tags need to be added to my site, but when I look at the source code for each page on either site I can see them there. Is there something that I am missing?
This is what LinkedIn Customer support said:

You'll need to make sure the source code complies with Open Graph
  Protocol (OGP) and certain image requirements specific to LinkedIn.
  Our developer website contains more details on setting display tags
  for shares (available in English only). Below are the og: tags that
  must exist and their correct format:
<meta property='og:title' content='Title of the article"/>
<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>
<meta property='og:description' content='Description that will show in the preview"/>
<meta property='og:url' content='//www.example.com/URL of the article" />

Here are the image requirements specific to the LinkedIn sharing
  module:
Max file size: 5 MB
Minimum image dimensions: 1200 (w) x 627 (h) pixels
Recommended ratio: 1.91:1

These are the OG tags on my site:
<meta property="og:type" content="article" />
<meta property="og:url" content="https://www.revealio.com/features/" />
<meta name="twitter:card" content="summary_large_image" />
<meta property="og:site_name" content="REVEALiO" />
<meta property="og:title" content="How To Make Your Message Come Alive With REVEALiO" />
<meta name="twitter:title" content="How To Make Your Message Come Alive With REVEALiO" />
<meta property="og:image" content="https://www.revealio.com/wp-content/uploads/BC_phone_scan-iPhone-wText-1.jpg" />
<meta name="twitter:image:src" content="https://www.revealio.com/wp-content/uploads/BC_phone_scan-iPhone-wText-1.jpg" />
<meta property="og:description" content="REVEALiO Is a Video Marketing Technology That Makes Your Promotional Materials COME ALIVE With A Personal Video Message and Call To Action Buttons" />
<meta name="twitter:description" content="REVEALiO Is a Video Marketing Technology That Makes Your Promotional Materials COME ALIVE With A Personal Video Message and Call To Action Buttons" />
<meta name="twitter:creator" content="@Revealiocards" />
<meta name="twitter:site" content="@Revealiocards" />

Am I missing something?
Comment: Test your page(s) on [LinkedIn Post Inspector](https://www.linkedin.com/post-inspector/). I can see your correct meta info with the other ones, but not sure why they are not using the correct one.
Comment: Can you test the page(s) without minifcation?
Answer: I'm not having any trouble with your title tag, but your description tag is definitely missing.  LinkedIn provides two levels, which each are triggered in their own way, but they are mutually exclusive...

Level 1

If you supply: og:image tags.
The preview shows: title, url, image.

Level 2

If you supply: no og:image tags, but an og:description tag.
The preview shows: title, url, description.

Your site is using level 1...

The Official Microsoft LinkedIn Share Documentation makes no mention of these levels.  But I have been informed by LinkedIn support staff that they exist, and experimentation seems to confirm it.
Example: Wikipedia has og:description and is missing og:image, so, sharing Wikipedia shows the description.  But GitHub has both og:description and og:image, so, sharing GitHub shows the image.


Force implicit conversion to most general shared class?

Question: Is there a function to force implicit conversion rules onto a heterogeneous list in order to convert it to an atomic vector of the most general shared class? For example, if I have list("apple", 12, TRUE), how can I turn this into c("apple", "12", "TRUE")?
Answer: R's class hierarchy roughly is logical < factor < integer < numeric < character. So unlist whch coerces into character should help, then list again to get list format.
list(unlist(list("apple", 12, TRUE)))
# [[1]]
# [1] "apple" "12"    "TRUE"

If we have a nested list, we can create a "relistable" object which inherits from "list" and use relist after unlist:
l <- as.relistable(list("apple", list(12), TRUE))
relist(unlist(l))
# [[1]]
# [1] "apple"
#
# [[2]]
# [[2]][[1]]
# [1] "12"
#
#
# [[3]]
# [1] "TRUE"

Comment: @user20650 Thanks for pointing out! Added to answer.


Android Development: How to request permissions?

Question: I was just wondering how to request permissions when creating an android application. I am a beginner, so please explain in simple terms :D.
So I want to make it so that my app can vibrate the phone at certain times, and the permission is called "android.permission.VIBRATE." But how do I request this? I do it in the Android Manifest file right?
Thanks for all help!
Answer: You're definately right. You need to put it in the AndroidManifest.XML
If you're using eclipse you can do it quite easily and without XML by opening up AndroidManifext.xml and use the Permissions tab at the bottom and press the "Add" button and selecting "Uses Permission" Then just select vibrate from the dropdown list.
If you want to do it in XML code you can add it before the application tag, like so:
<code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.android.vending.BILLING" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:name="Application" >

(the rest of your manifest continues from here)
</code>


Android custom notification not showing code changes

Question: There's some weird behavior here. I've got a bunch of code, pictures, followed by some description of the weird behavior and then my questions.
Files
I have a file random_start_bonus_cards_notification.xml, which looks like:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
android:gravity="center">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/firstCard" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/secondCard" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/ifNotCoal"
        android:visibility="gone">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="("
            android:paddingTop="15dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/if_not_coal"
            android:paddingTop="15dp" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/thirdCard" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=")"
            android:paddingTop="15dp" />

    </LinearLayout>

And a file random_start_bonus_cards.xml
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"></RelativeLayout>

This is a deliberately blank layout, because of weirdness we'll get into. It turns out this file has to be here, but it doesn't matter what it contains.
Annnnd my styles.xml:
<resources>

And some Android code:
    private void showStartBonusCardsDialog(DrawnCards drawnCards) {
    LayoutInflater factory = LayoutInflater.from(CalculatorActivity.this);
    final View dialogContent = factory.inflate(R.layout.random_start_bonus_cards_notification, null);
    ((ImageView) dialogContent.findViewById(R.id.firstCard)).setImageResource(getDrawableIdForStartCard(drawnCards.firstCard()));
    ((ImageView) dialogContent.findViewById(R.id.secondCard)).setImageResource(getDrawableIdForStartCard(drawnCards.secondCard()));

    if(drawnCards.hasThirdCard()) {
        dialogContent.findViewById(R.id.ifNotCoal).setVisibility(View.VISIBLE);
        ((ImageView) dialogContent.findViewById(R.id.thirdCard)).setImageResource(getDrawableIdForStartCard(drawnCards.thirdCard()));
    } else {
        dialogContent.findViewById(R.id.ifNotCoal).setVisibility(View.GONE);
    }

    AlertDialog drawnCardsDialog = new AlertDialog.Builder(CalculatorActivity.this).create();
    drawnCardsDialog.setView(dialogContent);
    drawnCardsDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); }
    });
    drawnCardsDialog.show();
}

private void showStartBonusCardsNotification(DrawnCards drawnCards) {
    Intent openIntent = new Intent(CalculatorActivity.this, CalculatorActivity.class);
    openIntent.setAction(refreshStartCardsAction);
    PendingIntent openPendingIntent = PendingIntent.getActivity(this, 0, openIntent, 0);

    RemoteViews notificationView = new RemoteViews(getPackageName(), R.layout.random_start_bonus_cards_notification);
    notificationView.setImageViewResource(R.id.firstCard, getDrawableIdForStartCard(drawnCards.firstCard()));
    notificationView.setImageViewResource(R.id.secondCard, getDrawableIdForStartCard(drawnCards.secondCard()));
    if(drawnCards.hasThirdCard()) {
        notificationView.setViewVisibility(R.id.ifNotCoal, View.VISIBLE);
        notificationView.setImageViewResource(R.id.thirdCard, getDrawableIdForStartCard(drawnCards.thirdCard()));
    } else {
        notificationView.setViewVisibility(R.id.ifNotCoal, View.GONE);
    }

    NotificationCompat.Builder notification = new NotificationCompat.Builder(this);
    notification.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
    notification.setSmallIcon(R.drawable.white);
    notification.setContentIntent(openPendingIntent);
    notification.setContent(notificationView);

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    int notificationId = 1;
    notificationManager.notify(notificationId, notification.build());
}

And here's two screenshots to refer to:

Weirdness
I initially had just one layout file, since the layouts were identical. With this, the text colour of the dialog was black (good) and the text colour of the notification was white and couldn't be read on my HTC M9.
(1) If I put the XML from random_start_bonus_cards_notification.xml into random_start_bonus_cards.xml, and replace all usages of random_start_bonus_cards_notification with random_start_bonus_cards, the text colours are wrong. If I keep the code as-is, but delete random_start_bonus_cards, the text colours are wrong. If I use random_start_bonus_cards_notification.xml and keep random_start_bonus_cards.xml in the project, even if it's empty, I get black text in both the dialog and notification!
(2) The background on the notification is a pale green. This colour was in the resource file at one point, but has been removed (as shown). After removing the background colour the dialog layout has a white background, but the notification background is still pale green, no matter whether I change it to red or anything.
(3) If I stop calling the dialog code, the same behavior occurs. I've included the dialog code since I'm worried there might be some interaction here, but I don't see how.
Questions
Generally, how does RemoteViews work with custom notification layouts? Is there any kind of system caching that could account for the background colour not changing?
Why is my notification not changing background colour when I change the layout background colour?
Why does my app change behavior when I delete this empty file random_start_bonus_cards.xml, that isn't even being used?
Why does my notification text colour not work unless I use the file named random_start_bonus_cards_notification.xml? (If I remove the _notification, the text changes colour).
Thanks for reading!
Answer: My guess is that this is happenning for one of the following two reasons:

The first of these could be that somewhere else in your code, you are refering to the creation of the notification, and there the changes you have made would not affect the code.
This is more likely to happen. The build has broken down and your built version of the app is not using the latest code. You can solve this by rebuilding the app from your IDE.

If you still can't manage to get hold of why this is happenning, set a breakpoint just before calling the method to display the notification and follow the logic the app is using.
Hope this helps :)
Comment: I did confirm that without cleaning the project, no changes were made to the running app. I wonder if the incremental build is busted?

I ended up make _ and _notifications identical except for styles, added some styles to the notification and used @android:color/primary_text_light as a text colour. Which goes against all of the prevailing wisdom on this stuff.

But it's a hobby project, so someone can complain if it doesn't work for them...>.>
Comment: Unfortunately, neither of these are the reason, that I can see. I put some stuff back, and now my notification is a lighter gray where the dialog is black text. It's readable, but not perfect how I want it. Thanks anyway.
Comment: Have you tried debugging the logic which is displaying the notification? The text color is controlled by the value of `textColorPrimaryInverse` so check the value in the strings.xml file. There must be some logic which is busting the build and forcing you to clean each time you make an update to the code.
Comment: Thanks for your eyeballs! I found a solution that isn't terrible, and posted about it below.
Answer: This was maddening, and is still not great.
(1) After confirming that my phone was doing some caching, I started using the emulator and it worked better.
(2) I left the notification with a separate layout files from the dialog, even though they are identical. My reasoning is that apparently the notification background can change between Android releases (there's a lot of complaints).
(3) I didn't post it above, but at one point I had a "v9/styles.xml". I didn't realize this applied to all versions above API9.
The final solution looks a bit like the following code. I copied from this SO answer (5.1.1 notification TextView, the correct way to deal with white text?) and used textAppearance instead of style.
        <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/if_not_coal"
        android:textAppearance="@style/NotificationText"
        android:paddingTop="15dp" />

textAppearance is great.

Gives the text a black colour for API >= 21.


Create EC2 Userdata for AWS EC2 using Powershell with Terraform challenge

Question: Honestly I have spent an absolute eternity trying to install the SSM Agent and get it to work on a Windows EC2 (base AMI) launched via Terraform.  All I need it to do is launch a EC2 instance (Windows) with the SSM agent installed ( I believe this comes by default, but unless I'm hallucinating on magic mushrooms I just cannot connect to it when it's provisioned in the console - says error SSM agent not installed) - It has ADMIN privileges also and has instance profile with the god mode.  I also need the TF Userdata to create a folder on boot and it's totally not happening.  Any ideas?  Thanks.   Here's the powershell userdata. (p.s) - instance launches ok, it's just not accepting userdata on launch.
<code>            <powershell>
            Invoke-WebRequest `
                https://s3.amazonaws.com/ec2-downloads-windows/SSMAgent/latest/windows_amd64/AmazonSSMAgentSetup.exe
                -OutFile $env:USERPROFILE\Desktop\SSMAgent_latest.exe

            Start-Process `
                -FilePath $env:USERPROFILE\Desktop\SSMAgent_latest.exe `
                -ArgumentList "/S"

            New-Item -ItemType directory -Path C:\Cats
            <powershell>
</code>
Comment: The instance role used, it does not work only for windows ec2? If you apply the same role for linux instance, ssm works?
Comment: I have not tried Linux.  BUT, i'm pretty sure it would work as there's 1000000000000000000 articles online explaining how to achieve this.  BUT, for Windows with EC2 userdata and Powershell comands it's few and far between.  Any ideas?
Comment: If my file name for the Powershell userdata is ended with a .txt what do i need to enter in main.tf to reference it?  would it be ```user_data  = "${local_file.user_data.txt.content}"
Comment: So you are using custom vpc? Is the intance launched in public subnet or private with nat gateway?
Comment: Yeah all in a public subnet
Comment: Windows2016 and Windows2019 official AMIs do come with the SSM agent pre-installed. If the userdata is "not working", then try verifying the userdata is loaded from the console, and then debug the PS script itself.
Comment: this is fixed. The solution was that in fact the instance when spinning up with Terraform DIDN'T have the line "associate_public_ip_address = true" - ...... How do you get it to run without this being assigned?  Nothing should be public especially compute.
Answer:
How do you get it to run without this being assigned? Nothing should be public especially compute.

Since the primary issue has been solved (see comments) I can comment on the above question.
By definition if an instance is in public subnet, it will be publicly available with the public IP assigned. To ensure that your instances are private but can still connect internet, three things are required:

a private subnet without a route to internet gateway,
NAT gateway in a public subnet
route table of the private subnet must be configured to route internet traffic to the NAT gateway.

With this setup, launching an instance in the private subnet ensures that it will be able to access internet (e.g. to download software or updates), but it will bo non-accessible from the internet.
Answer: Confirm the following

IAM role created
Instance role with appropriate policies attached
ec2 instance in the correct subnet with internet access


Heteroskedasticity and residuals normality

Question: I have a linear regression that's quite good, I guess (it's for a university project so I don't really have to be super accurate).
Point is, if I plot the residuals vs. predicted values, there is (according to my teacher) an hint of heteroskedasticity.
But if I plot the Q-Q-Plot of the residuals, it's clear that they are normally distributed.
Moreover, the Shapiro test on the residuals has a $p$-value of $0.8$, so I think there's no doubt the residuals are actually normally distributed.
Question: How can there be heteroskedasticity on predicted values if the residuals are normally distributed?
Comment: One very short addition to @whubers excellent answer: You could use the `ncvTest` function of the [car package](http://cran.r-project.org/web/packages/car/index.html) for `R` to conduct a formal test for heteroscedasticity. In whuber's example, the command `ncvTest(fit)` yields a $p$-value that is almost zero and provides strong evidence against constant error variance (which was expected, of course).
Answer: One way to approach this question is to look at it in reverse: how could we begin with normally distributed residuals and arrange them to be heteroscedastic?  From this point of view the answer becomes obvious: associate the smaller residuals with the smaller predicted values.
To illustrate, here is an explicit construction.

The data at the left are clearly heteroscedastic relative to the linear fit (shown in red).  This is driven home by the residuals vs predicted plot at the right.  But--by construction--the unordered set of residuals is close to normally distributed, as their histogram in the middle shows.  (The p-value in the Shapiro-Wilk test of normality is 0.60, obtained with the R command shapiro.test(residuals(fit)) issued after running the code below.)
Real data can look like this, too.  The moral is that heteroscedasticity characterizes a relationship between residual size and predictions whereas normality tells us nothing about how the residuals relate to anything else.

Here is the R code for this construction.
set.seed(17)
n <- 256
x <- (1:n)/n                       # The set of x values
e <- rnorm(n, sd=1)                # A set of *normally distributed* values
i <- order(runif(n, max=dnorm(e))) # Put the larger ones towards the end on average
y <- 1 + 5 * x + e[rev(i)]         # Generate some y values plus "error" `e`.
fit <- lm(y ~ x)                   # Regress `y` against `x`.
par(mfrow=c(1,3))                  # Set up the plots ...
plot(x,y, main="Data", cex=0.8)
abline(coef(fit), col="Red")
hist(residuals(fit), main="Residuals")
plot(predict(fit), residuals(fit), cex=0.8, main="Residuals vs. Predicted")

Comment: ok so you're saying that if I associate low residuals with high predicted values, heteroscedasticity can arise even if residuals are normally distributed? I think I've got it, though i should really think more about it.. anyhow thank you!
Comment: ...or low residuals with low predicted values (as in the example here), or even in more complex ways.  For instance, heteroscedasticity exists when the average magnitude of residuals oscillates with the predicted value.  (Most formal tests of heteroscedasticity will not detect this, but the usual diagnostic plots will clearly show it.)
Answer: In weighted least squares (WLS) regression, it is the random factors of the estimated residuals that you might want to be able to see are normally distributed,  though it often isn't terribly important. The estimated residuals may be factored, as shown in a simple ( one regressor and through the origin) regression case, at the bottom of page 1, and bottom halves of pages 2 and 7 in https://www.researchgate.net/publication/263036348_Properties_of_Weighted_Least_Squares_Regression_for_Cutoff_Sampling_in_Establishment_Surveys
Anyway, this might help show where normality can come into the picture.
Comment: We are trying to build a permanent repository of high-quality statistical information in the form of questions & answers. Thus, we're wary of answers that depend on links, due to linkrot. Can you post a full citation & a summary of the information (eg, figures / explanations) from the link so the information will stay useful even if the link goes dead?
Comment: Welcome to the site, @JimKnaub. We'd love to have you around to lend your expertise on the occasional question. Why not register your account? You can find out how in the **My Account** section of our [help]. Since you're new here, you may want to take our [tour], which has information for new users.


How to align hub tiles programmatically in wp8 app

Question: I am creating a Windows phone app.
I am creating hub tiles dynamically i.e pragmatically and adding in the stack panel.
I have around 10 hubtiles and what I want is to show in the stack panel 2 in a single row.
I mean let say I have hubtliles as A, B , C , D...
I have to align them as
A    B
C    D
....
How to do this alignment progmatically
Answer: Why not just create a 5 row, 2 column grid and assign hub tiles to correct cell programmatically?


Select specific string allowing for minor misspelling

Question: I have a lot of german street names. Most of them end with the word ...strasse. I want to replace strasse with its abreviation str allowing for minor misspellings (1 or 2 characters missing or wrong) such as strae or strassee.
I tried many things and looked up some more:
street_names <- c("GERBERSTRAE", "NEUE STRAASSE", "SCHLOSSSTASSE", "HAUPTSTRASSE", "WINZERGASSE")

> gsub("[STRASSE]{5,7}S?T?R?A?S?S?E?$" , "STR", street_names, perl = T)
[1] "GERBSTR"     "NEUE STR"    "SCHLOSTR"    "HAUPSTR"     "WINZERGASSE"

> gsub("S?T?R?A?S?S?E?$" , "STR", street_names, perl = T)
[1] "GERBERSTR"    "NEUE STRASTR" "SCHLOSSSTR"   "HAUPTSTR"
[5] "WINZERGSTR"

But so far all of them get some right and some wrong, and I don't know how to combine them. ("Winzergasse" should not be matched, as it ends on Gasse which translates to alley)
Any help is greatly appreciated.
EDIT:
more examples
street_names <- c("GERBERSTRAE", "NEUE STRAASSE", "SCHLOSSSTASSE", "HAUPTSTRASSE", "LINDENSASSE",
                  "WINZERGASSE", "PARKSTRASE", "ALTE STTRASSE", "BACHSTRAS", "LANGE SRASS")

Comment: you might want to take a look at the `stringdist` package
Answer: You could use
gsub("GASSE(*SKIP)(*FAIL)|ST*R?[ASE]+$", "STR", street_names, perl = T)

Which yields
[1] "GERBERSTR"   "NEUE STR"    "SCHLOSSSTR"  "HAUPTSTR"    "WINZERGASSE"

The pattern here is
GASSE(*SKIP)(*FAIL) # match "GASSE" and let it fail
|                   # or
ST*R?[ASE]+         # S, T (0 or more times), R (optional), any A, S or E
$                   # end of the string

See a demo on regex101.com.
Answer: I don't know how many different types of typografic errors you can encounter. For the examples you have given, something like this would work:
gsub("STR.*|STA.*","STR",street_names)
[1] "GERBERSTR"   "NEUE STR"    "SCHLOSSSTR"  "HAUPTSTR"
[5] "WINZERGASSE"

Answer: Appending a question mark to every character in the pattern makes them all optional, so the pattern will basically match everything.
It's much easier to just list common misspellings fully and live with the fact that some people will find creative spellings that you didn't think of.
Answer: A bit brute force, but save I think:
gsub("(STRAE$)|(STRAASSE$)|(STASSE$)|(STRASSE$)", "STR", street_names)
[1] "GERBERSTR"   "NEUE STR"    "SCHLOSSSTR"  "HAUPTSTR"    "WINZERGASSE"


retornar select "tabela relacionada" no laravel

Question: Olá minha aplicação foi desenvolvida em laravel e como complemento estou usando alguns componentes do VueJS.
Vamos ao problema, tenho uma tabela cliente fazendo relacionamento com país.
Na mesma view index.blade de clientes eu abro uma modal para criar, editar e visualizar o cliente.
A questão é que para criar o cliente ele apresenta o select com os países cadastrados, porém ao editar ou visualizar ele não retorna os países. Vamos ao código:
ClientesController: (Nele eu chamo tb o model pais)
public function index()
{
    $listaClientes = Cliente::select('id', 'nome', 'tva', 'pais_id', 'cp', 'cidade', 'endereco')->paginate(10);

    $pais = Pais::all();

    return view('app.clientes.index',compact('listaClientes', 'pais'));
}

Model Pais:
{
use SoftDeletes;

protected $table = 'paises';
protected $fillable = ['id', 'nome'];

protected $dates = ['deleted_at'];

Model cliente:
use SoftDeletes;

protected $table = 'clientes';
protected $fillable = ['nome', 'tva','pais_id', 'cp', 'cidade', 'endereco'];

protected $dates = ['deleted_at'];

public function pais() {
    return $this->belongsToMany('App\Pais', 'pais_id', 'nome');

Select do modal adicionar:
<select name="pais_id" class="form-control">
   @foreach ($pais as $pais)
      <option value="{{ $pais->id }}">{{ $pais->nome }}</option>
   @endforeach
</select>

Select do modal editar:
<select name="pais_id" class="form-control">
   @foreach ($pais as $pais)
      <option value="{{ $pais->id }}">{{ $pais->nome }}</option>
   @endforeach
</select>

Meus formulários de adição e edição estão no mesmo arquivo blade e abre a modal...
Desde já agradeço por sua atenção, se tiver algo mais que eu precise enviar...
Comment: Posta a saida de dump($pais); ou dd($pais);
Dica, muda  $pais = Pais::all(); pra  $paises = Pais::all(); para que no foreach não fique tão confuso :)
Comment: Opa, obrigado Marcos.
Eu consegui aqui com a ajuda de um outro rapaz, exatamente como você indicou.
Valeuuu
Answer: Em ambos os foreach, você utilizou o nome do item igual o nome da collection $pais => $pais, isso é uma possível fonte do bug. Para corrigir isso sugiro que no controller, substitua a variável $pais por $paises, como no exemplo abaixo:
public function index()
{
    $listaClientes = Cliente::select('id', 'nome', 'tva', 'pais_id', 'cp', 'cidade', 'endereco')->paginate(10);

    $paises = Pais::all();

    return view('app.clientes.index',compact('listaClientes', 'paises'));
}

E na view, altere @foreach($pais as $pais) por @foreach($paises as $pais)


c++ How would I output an an array which I manipulated within a function?

Question: I am new to C++ and I am making a program for class. The program is a game of Tic Tac Toe between two people. I have have already completed a version of the program which does not use functions and I have trying to make use of them.
I would like to edit an array within a function and output the function to be used later in the program.
Here's the code;
// This is a assessment project which plays ticTacToe between two players.

#include <iostream>

using namespace std;

int main() {

    void displayBoard(char ticTacToeGame[][3]); // sets up use of displayBoard()
    char userPlay(); // sets up use of userPlay()
    char addplayToBoard(char play, char ticTacToeGame[][3] ); // sets up use of addPlayToBoard()

    char ticTacToeGame[3][3] = {'1', '2', '3', '4', '5', '6', '7', '8', '9'}; // game board array

    // declaration of variables
    char play;

    displayBoard(ticTacToeGame); // displays the board to user
    play = userPlay(); // gets users play and stores it as a char

    return 0;
} // end of main()

// function used to display the board
void displayBoard(char ticTacToeGame[][3]) {

    // display board
    for (int row = 0; row < 3; row++) {

        cout << endl;

        for (int column = 0; column < 3; column++) {
            cout << "| " << ticTacToeGame[row][column] << " ";
        }

        cout << "|\n";

        if (row < 2) {
            for (int i = 0; i < 19; i++) {
                cout << "-";
            }
        }
    }

} // end of displayBoard()

// function used to get users play
char userPlay() {

    // declaration of variables
    char play;

    cout << "Play: ";
    cin >> play;
    cout << endl;

    return play;

} // end of userPlay()

// function used to add users play to board
char addPlayToBoard(char play, char ticTacToeGame[][3]) {

    for (int row = 0; row < 3; row++) {
        for (int column = 0; column < 3; column++) {
            if (ticTacToeGame[row][column] == play){
                ticTacToeGame[row][column] = 'O';
            }
        }
    }
    return ticTacToeGame;

} // end of addPlayToBoard()

How would I do this?
Comment: Use std::vector or std::array.
Comment: You might also want to look into the difference between pass by reference and pass by value in functions. Specifically in your function `addPlayToBoard`
Comment: Thanks for a reply, will look into how to use them.
Answer: A good C++ course would cover classes before arrays. The sort of array you're using here is a primitive building block, that's why you are struggling.
We're guessing here a bit in what your course already covered, but this is how you'd normally do it :
class Board {
   char fields[3][3];
public:
   // Class methods
};

Here's the important reason why: C++ classes are full-blown types and can be returned from functions, just like int values. But often that's not even needed: class methods work on the class in-place.


Expectation of first-passage-time of a diffusion process with negative drift

Question: Take  the stochastic process $X_0 = 0$ and $X_t = \nu t + \sigma W_t$  where $W_t$ is standard Brownian motion and $\nu$ is a drift which may be negative (this is the key complexity to the question)
Let $\alpha > 0$ be a fixed level, then define the first passage time as the random variable: $T = \inf\{ 0 < t \mid X_t=\alpha \}$.
Then, given some $r > 0$, what is the following expectation?
$$
U \equiv \mathbb{E}\left(e^{-r T} \right)
$$
A related question may be: what is the moment generating function for the $T$ stopping time?  Note that I do not care about the pdf or cdf of $T$, just the above expectation.

Solving the $\nu \geq 0$ case:
I believe this turns out to be easy as this follows the example in https://en.wikipedia.org/wiki/Inverse_Gaussian_distribution#Relationship_with_Brownian_motion .  Hence, $T$ is distributed as an Inverse Gaussian: $T\sim IG(\tfrac\alpha\nu, \tfrac {\alpha^2} {\sigma^2})$ in that notation.
Moreover, the moment generating function for the $IG(\mu,\lambda)$ is $$M(t;\mu,\lambda) \equiv \exp\left[{\frac{\lambda}{\mu}\left(1-\sqrt{1-\frac{2\mu^2t}{\lambda}}\right)}\right]$$
Finally, note that the expectation I gave is exactly the definition of the MGF at $t=-r$, so we have our answer,
$$
\mathbb{E}\left(e^{-r T} \right) = M\left(-r;\tfrac\alpha\nu, \tfrac {\alpha^2} {\sigma^2}\right)
$$

Solving the $\nu < 0$ case:  If you look carefully at theorems such as in Karlin  and Taylor "A First Course in Stochastic Processes" page 362 and theorem 5.3, or the wikipedia page above, they always assume that $\nu \geq 0$.  As Karlin and Taylor puts it: "When $\nu < 0$, $T$ has a defective probability distribution, that is $T$ is infinite with positive probability".
However, to find $\mathbb{E}\left(e^{-r T}\right)$ we don't really need to find the probability distribution.  Is the moment generating function (and hence the direct solution for $U$) still defined?  Is the formula the same as above?
Comment: Please see Theorem 2 in Feller (who i believe coined the term defective density). http://math.ucsd.edu/~lni/math257/Tauberian-Theorem.pdf
Comment: For the less general case, see http://stats.stackexchange.com/questions/232363/survivor-function-of-hitting-timei-e-first-passage-time-for-a-standard-sde  for more details and the connection to the IG distribution.
Comment: Is it possible for your model to consider the case when a is also less than zero when the drift coefficient is negative,  as in that case first passage density is well defined and not defective.
Comment: Thanks. You are right that it works if the drift is towards the barrier.  Sadly, I need it to move in the opposite direction
Comment: @ComicBookGuy  Thank you, very helpful.  I don't quite understand the application of the theorem to my problem (if you mean the continuity theorem on page 431) since the limits are unclear for me.  However, this may be part of the solution:  There is no problem whatesoever in using laplace transforms/mgfs of distributions with defective densities
Comment: Filling in a few blanks from what you suggested here, and definition 1, and theorem 1 of Feller: (1) The derivation in karlin taylor of the MGF of stopping times does not require $\nu \geq 0$.  It is only at the point where they need to take the inverse laplace tranform to get the PDF of the CDF that it is needed. (2) Since I don't require a PDF or CDF for my calculation, and can use the laplace transform directly, this holds for any $\nu$?
Comment: I do not think it is possible to get the Laplace transform without using the PDF or CDF. no ? At best you can get a defective mgf.
Comment: I believe the Karlin Taylor derivation does it the opposite direction, only getting the pdf at the end with an inverse transformation.
Answer: The answer is
$$ E[e^{-rT}] = exp\left\{\frac{\mu+\sqrt{\mu^2+2\sigma^2r}}{\sigma^2} \alpha\right \} $$ if $\alpha<0$, and
$$ E[e^{-rT}] = exp\left\{\frac{\mu-\sqrt{\mu^2+2\sigma^2r}}{\sigma^2} \alpha \right\} $$ if $\alpha>0$
To establish these formulas one can follow the approach from Karlin and Taylor. Since Karlin and Taylor provide the derivations for the case $\alpha>0$, I derive the formula for the case $\alpha<0$.
Let $V_{\lambda}(t)=exp\{\lambda X(t) - q(\lambda)t \}$ where $q(\lambda) = \mu \lambda+\frac{1}{2}\sigma^2\lambda^2$. Note $V_{\lambda}(t)$ is a martingale.
Consider $V_{\lambda}(t \wedge T )$. Then $V_{\lambda}(t \wedge T )$ is also a martingale and is bounded for $\lambda<0$. We assume then that $\lambda<0$, and from the above observations we have,
$$ E[V_{\lambda}(t \wedge T )] = E[V(0)] = 1  $$
Moreover
$$\lim_{t \rightarrow \infty} V_{\lambda}(t \wedge T) =  \left\{ \begin{array}{ll}
exp\{\lambda T - q(\lambda) T & \text{  if  } T<\infty \\
0  & \text{ if } T=\infty
\end{array}
 \right.  $$
Therefore,
$$\lim_{t \rightarrow \infty} E[V_{\lambda}(t \wedge T )]= E\left[\lim_{t \rightarrow \infty} V_{\lambda}(t \wedge T )\right] = e^{\lambda \alpha}E[e^{-q(\lambda)T}] $$
From the above derivations it follows that
$$1=e^{\lambda \alpha}E[e^{-q(\lambda)T}]$$ or
$$e^{-\lambda \alpha}=E[e^{-q(\lambda)T}]$$
Set $q(\lambda)=r$ and solve the resulting quadratic to obtain
$$ \lambda=\frac{-\mu \pm \sqrt{\mu^2+2\sigma^2 r}}{\sigma^2}$$
Since we require $\lambda<0$ the correct root is the negative one. Thus, we obtain
$$ E[e^{-rT}]=\exp \left\{ \frac{\mu + \sqrt{\mu^2+2\sigma^2 r}}{\sigma^2} \alpha \right\}$$
Finally, note that if $\mu>0$ then $\lim_{r \rightarrow \infty} E[e^{-rT}] \neq 1$ which implies that the associated distribution function is defective, while if $\mu>0$ then $\lim_{r \rightarrow \infty} E[e^{-rT}]=1$ and the associated distribution is not defective (Theorem 2 in Feller that  Comic Book Guy referred to).
Comment: Looks good to me. Any comments from others?


ProgressBar doesn't update while calling database

Question: I've an issue with progress bar since it was not showing until the data is loaded.
I'm not sure whether my code is right or wrong. Please help on this issue and its cracking my head. Any suggestions would be really helpful for me plzzz..
progressBar1.Minimum = 0;
progressBar1.Maximum = short.MaxValue;
progressBar1.Value = 0;

double value = 0;

UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(progressBar1.SetValue);

foreach (CDType ctp in dgAttributes.ItemsSource)
{
    if (ctp.IsSelected == true)
    {
        //Mouse.OverrideCursor = Cursors.Wait;
        var CDTypeID = ctp.TYPE_ID;

        label3.Content = "Loading.." + CDTypeID;

        SqlCommand sqlCommand = new SqlCommand(conn.ConnectionString);
        sqlCommand.CommandType = CommandType.StoredProcedure;
        sqlCommand.CommandText = "LOAD_DATA_SOURCE_SAVE";

        sqlCommand.Parameters.AddWithValue("CDTYPE_ID", CDTypeID);

        sqlConnection.Open();
        sqlCommand.Connection = sqlConnection;

        do
        {
            value += 1;
            Dispatcher.Invoke(updatePbDelegate,
                              System.Windows.Threading.DispatcherPriority.Background,
                              new object[] { ProgressBar.ValueProperty, value });
            //i'm not sure whether its correct way or not to give below line here..? I mean execute non query...since it was looping all the time untill its reaches Maximum value
            //sqlCommand.ExecuteNonQuery();
        }
        while (progressBar1.Value != progressBar1.Maximum);

        sqlConnection.Close();
        //label3.Content = "Sucessfully Loaded..!";
    }
}

Comment: You haven't given us the context of this code. My guess is that *all* your code is running in the UI thread.
Comment: please fix the indentation. It's not that hard.
Comment: Well... at first glance... do you really want your progress bar to run from 0 to 32767? This also might be a good example of using an "unknown" progress time as you're just hitting the database with no definitive start/end values or concept of "progress". See using a "marquee" style for your progress bar: http://social.msdn.microsoft.com/forums/en-US/winforms/thread/9e51ad57-988e-4c17-98f0-cd2a8abec503/ EDIT: Ooops, WPF, just use `IsIndeterminate`: http://msdn.microsoft.com/en-us/library/system.windows.controls.progressbar.isindeterminate%28VS.100%29.aspx
Comment: @user1990395 In that case, have your progress bar max value be the number of seconds (5 * 60) and consider using a background timer (like `System.Threading.Timer`) that runs every second and have it update your progress bar.
Comment: @user1990395 Are you loading your data in the UI thread?
Comment: Thanks Daniel, I've copied the text and not able to formatting the code and if I formatted it was deleting...
Comment: Hi Chris, Actually I really don't need the maximum time. Only I need for execution time of the stored proc and untill the data loads into database.
Comment: You need to show more code to get a proper answer. My guess is this is running off some UI event which means you are querying the database on the UI thread and tying it up. Your call to the `Dispatcher` is thus a waste of time.
Comment: ExecuteNonQuery method will executing the storedproc and assume it will take 5 mins so I need to run the progressbar untill 5 mins
Comment: I was just calling the delegate --> UpdateProgressBarDelegate and Invoking this delegate based on progressbar maximum value
Comment: Thanks Chris, I've set up Timer and set that value into progressbar maximum value...Thanks a ton :-)
Answer: As long as you cannot determine how long it will take you might want to use a progressbar with its style set to indeterminate.
<ProgressBar IsIndeterminate="True" />

If you use the UI thread to load the data the Progressbar might not update because the thread is busy. See this post on how to fix that using a background worker to load the data. You can search on StackOverflow too; there are many questions on the backgroundworker.
If the database is passing data back in batches you could might be able to keep track of the number of batches on their way and use a progressbar with an actual value.


c# remove 3rd party application from taskbar

Question: How to remove an 3rd party application from the Windows taskbar by its handle?
I've found this:
Remove application from taskbar with C# wrapper?
But it doesnt worked for me.
It only sets another style (small x to close, no maximize/minimize button) to the Window i selected (notepad).
Any ideas about this?
EDIT: I dont want to remove MY application from the taskbar, i want to remove an external application by handle
Comment: possible duplicate of [Win32: How to hide 3rd party windows in taskbar by hWnd](http://stackoverflow.com/questions/7219063/win32-how-to-hide-3rd-party-windows-in-taskbar-by-hwnd)
Answer: To hide it from windows task bar you just need to set ShowInTaskbar property to false :
this.ShowInTaskbar = false;

As for moving of windows you can use spy++ to check windows events and identify it.
Answer: If you have the handle to the window you can call ShowWindow() through the Win32 API. Then you can do:
// Let the window disappear (even from taskbar)
ShowWindow(this.Handle, WindowShowStyle.Hide);

// Revive the window back to the user
ShowWindow(this.Handle, WindowShowStyle.ShowNoActivate);

So from now, all your problem is to get the handle of the window you like to hide:
Process[] procs = Process.GetProcesses();
IntPtr hWnd;
foreach(Process proc in procs)
{
   if ((hWnd = proc.MainWindowHandle) != IntPtr.Zero)
   {
      Console.WriteLine("{0} : {1}", proc.ProcessName, hWnd);
   }
}

Comment: this doesnt worked for me. after hiding the windows they are invisible, after setting shownoactivate they are visible again but also shown in the taskbar.
Comment: @user1216595: In that case [this question has already been answered](http://stackoverflow.com/questions/7219063/win32-how-to-hide-3rd-party-windows-in-taskbar-by-hwnd).
Comment: @user1216595: Ok, i misunderstood you. You want to see the window, but it should not appear within the taskbar. I thought you would like to hide the window (like minimize) AND remove it from the taskbar.
Comment: this aint restore :                 IntPtr hWnd = p[0].MainWindowHandle;

                ShowWindow(hWnd, WindowShowStyle.ShowNoActivate);
Answer: How to remove an application from the Windows taskbar?
this.ShowInTaskbar = false;

Answer: Easy:
this.ShowInTaskbar = false;

As for the Form movement: you can use the Move event under Layout events


Implementation of SQL Data Export Service in c#

Question: I'm new to Azure, I want to know about how we can implement SQL Data Export Service in c#.
my actual problem is "I am using C#.net to implement some web services and also use SQL azure as database for that services. So there each day i want to check whether there is any updation in my database. If there is an updation then i want to read only that updated data from my sql azure database and load that datainto some another sql database(both SQL Server and SQL Azure)". So i want to implement this function as windows azure worker role. So each and every day these worker role be executed. How i can implement that entire operation using c#.net.
If anyone know the solution please help me. Thanks
Answer: For that you will have to create a "Worker Role", which is similar to a window service.
For details have a look at
How to create a worker role
and also
Building Windows Azure Service: Worker Role Background Tasks Handler


Meaning of a Notation Symbol (

Question: I wonder if anyone can tell me what the curved notation next to the 8th notes are. If it helps, this is a score for saxophone.
Thanks.
Comment: Looking at the amount of discussion arising in the currently only answer, the question should deliver significantly more context: Style, period, name of the piece, composer just for the beginning.
Comment: A nice check would be to listen to a recording of whatever it is - obviously if available.
Comment: @guidot The tags might give you a clue!  'Notation, jazz, saxophone'.
Answer: It's a "scoop" or "slide". It means you bend into the note, starting a bit flat and then bending the note upward until it's in tune.
Typically, the symbol looks like ")" rather than "(".
Comment: Probably all it can be, although a lift is a straight line rising and a scoop is a 'bracket' opposite to the direction here.
Comment: @user1079505 I know it because I've seen it for trumpet, so it applies to brass, but I don't know about, say, flute, or string instruments.
Comment: Is this notation used for saxophone or wind instruments only?
Comment: Not really how you write a scoop.  But yes, possibly a 'best attempt' in a rudimentary notation program.
Comment: @user1079505: I've seen it in guitar notation for when the bend is less than a half-step. This example I'd interpret as: one fret down from normal, pre-bend the string 1/4-step, strike it, and quickly bend it another 1/4-step to the given note.

Meaning of a Notation Symbol (


Cloud Armor + Recaptcha with domain validation

Question: Am trying to configure Recaptcha enterprise with WAF using cloud armor (with action tokens), but I have a problem, the cloud armor rule that validates the token/score never gets triggered if the domain validation is enabled on the recaptcha key. I have a very simple cloud armor policy:

And the recaptcha key looks like a normal key with the WAF enabled:

To get the token I just have a simple localhost site that just run the enterprise sdk and sends the token in the X-Recaptcha-Token header.
My problem is that, when the Disable domain verification is off, the cloud armor rules are never triggered (and for the LB logs it seems that the token does not even appear), so it only triggers the deny-all rule. But as soon as I enable the Disable domain verification then the rules are correctly triggered and the logs shows the score of the token.
Someone knows what could be happening?.
Some more info about my setup, the WAF is protecting an API thats running on Cloud Run (which is configured as a backend service inside the load balancer).
I also create an issue tracker here
Comment: Cloud Armor does not check the domain list registered on the reCAPTCHA side. So the only option currently is to turn off domain protection. But if you think the domain protection is a must for you, then you need to wait for our feature enhancement.

There are already internal discussions for the said feature. However, for feature requests there is no guarantee of any time frame for updates or that the requested feature will be implemented.
Comment: Thank you very much!, Is this mentioned on some documentation?, I couldn't find it :/. So when using a WAF Recaptcha Key (with cloud armor), its expected that the domain validation is OFF?, that does not let the recaptcha key a little bit vulnerable as mentioned in the guides?
Answer: As mentioned by Siegfred (thank you very much!), this is a missing feature on the integration between recaptcha enterprise and cloud armor and currently the only way to integrate them is by disabling the domain verification in the recaptcha enterprise panel.
As he mentioned this is a feature that should be developed (and its currently on internal discussions), hopefully they'll release it on the near future. Also its worth mention, that there should be a revisit on the documentation to avoid any misunderstanding, as this behavior is not mentioned explicitly.
There is still the issue I created on googles issue tracker here. So you can check from time to time to see if there is any news.
Answer: As a stop gap, you could consider making a compound rule within Cloud Armor where you check that the domain name isn't the target property (meaning it is something else other than your desired hostname) and then add the recaptcha language:
request.headers['host'].matches('www.example.com') && token.recaptcha_action.score >= 0.8

This isn't as strong as doing the domain validation within ReCaptcha, but it essentially would mitigate domain hijacking.
Depending on what you wanted to do with potential hijacked requests, you could have a Cloud Armor rule that tests for the anti-pattern, e.g. domain doesn't match and then deny/redirect the request elsewhere. You would probably want this anti-pattern rule to fire before the recaptcha so as to dump unwanted requests before hitting reCaptcha evaluation.
!request.headers['host'].matches('www.example.com')


Computar dados seguros randômicamente

Question: Funções randômicas não são totalmente aleatórias na computação.Gostaria de saber se existe uma maneira segura de gerar um salt,ou qualquer outra string aleatória de forma segura,sem usar hardware externo.
A randomização pode ser obtida sem o uso de hardware externo,por exemplo usando o tempo em que um processo demora para ser feito?Isso não é algo que é intrínseco aos estados quânticos dos materiais do processador?Se não,teoricamente,na menor unidade calculável de tempo por um computador,um processo exatamente igual é sempre calculado na mesma velocidade.
Comment: Por favor evitem longas discussões nos comentários; a conversa de vocês foi [movida para o chat](http://chat.stackexchange.com/rooms/54210/discussion-on-question-by-weslley-c-x-sardinha-computar-dados-seguros-randomicam)
Answer: Use hardware externos
Não é possível gerar números totalmente aleatórios sem hardware externo.
Como já foi indicado nos comentários da sua resposta, poderia usar ou o Lavarand
Se entrar nos sites que utilizam de serviços Realmente Aleatórios (Random.org  ou HotBits) usam hardware externo para garantir que os números sejam aleatórios:
Random.org: usa ruídos em sinais atmosféricos (referência).
HotBits: usa o decaimento de particulas radioativas (referência).
Não consigo ver o por que de usar um hardware externo, como a API do Random.org poderia te trazer problemas de segurança.
Se insistir em não usá-los:
Como solicitou (exemplos em PHP ou C++), irei postar abaixo a melhor forma de obter números pseudo-aleatórios em PHP:
<?php
mt_srand((double)microtime()*1000000);

echo "mt_rand() com mt_srand()

";

for($i = 0; $i != 5; $i++)
{
    echo mt_rand(0, 100)."

";
}
?>

O mt_rand() é muito superior ao srand() por usar o Marsenne Twister é provavelmente uma das melhores implementações de números pseudo-aleatórios que existe.
Se quiser comparar com as outras formas em php:
<?php

echo "rand() sem srand() (semente/alimentação)

";

for($i = 0; $i != 5; $i++)
{

echo rand(0, 100)."

";

}

srand((double)microtime()*1000000);

echo "rand() com srand()

";

for($i = 0; $i != 5; $i++)
{

echo rand(0, 100)."

";

}

echo "mt_rand() sem mt_srand()

";

for($i = 0; $i != 5; $i++)
{

echo mt_rand(0, 100)."

";

}

mt_srand((double)microtime()*1000000);

echo "mt_rand() com mt_srand()

";

for($i = 0; $i != 5; $i++)
{

echo mt_rand(0, 100)."

";

}

?>

EDITADO:
Achei um tanto suspeita as imagens da resposta aceita e resolvi fazer o teste:
Random.org

rand()

mt_rand()

O código deste teste está no gist o experimento foi realizado com PHP 5.3
e também pode ser executado online (sem ter que instalar nada nesse site).
Comment: "Não consigo ver o por que de usar um hardware externo, como a API do Random.org poderia te trazer problemas de segurança." Usar um hardware que você possui ([e confia](http://blog.cr.yp.to/20140205-entropy.html)) é uma coisa, usar um serviço de terceiros para algo que deveria ser confidencial é outra. O próprio Random.org diz na sua FAQ: ["...anyone genuinely concerned with security **should not trust anyone else** (including RANDOM.ORG) to generate their cryptographic keys."](https://www.random.org/faq/#Q2.4) (ênfase minha)
Comment: Sim, ao fazer isso [almentará a entropia dos dados](http://en.wikipedia.org/wiki/Entropy_%28information_theory%29) o que tornará os seus números mais aleatórios mas mesmo assim sugiro combine com o microtime em algo tipo `mt_srand((double)microtime()*$IP);`
Comment: Que tal ``mt_srand((double)microtime()*($IpClient[rand(0,3)] * $IpServer[rand(0,3)]));`` ?
Comment: Gostei da resposta @Kyllopardium. Deixe-me viajar um pouco: Poderíamos o usar como input uma variável disponível no ambiente, que seja imprevisível, como por exemplo, a terceira parte do IP de client multiplicado pela quarta parte do IP do server ?
Comment: Sim, exatamente como pensei: ``mt_srand((double)microtime()*($IpClient[2] * $IpServer[3]));``
Comment: PS: sugiro não manter o ip do server na multiplicação caso o mesmo seja estático.
Comment: Cuidado. Se você usa a hora do servidor para gerar a semente, então o cliente pode descobrir qual é essa semente (se você der uma margem de erro 5 segundo (muito) há apenas 10.000.000 possibilidades de sementes (já que usou microtime), basta testar todas). Utilize uma fonte de hardware, como ler o `/dev/random` do linux, que pode usar o tráfego de rede para randomizar. Imagino que um servidor tenha bastante.
Comment: Todas as vezes que consumimos um serviço de terceiros, que geralmente envolve tráfego por redes de terceiros, existem vários perigos dependendo da implementação, seja sua, seja do terceiro. Quanto mais 'pessoas' estão envolvidas num processo, maior a complexidade para gerenciar a segurança.
Comment: Quando à imagem "suspeita" do `rand`, o artigo citado explica que esse resultado foi obtido somente no Windows, que no Linux não houve padrão semelhante. O que mostra que o gerador de números aleatórios *daquela versão do Windows* era ruim. Não sei se isso se aplica a versões recentes. De todo modo, nada disso "prova" nada, pois pode-se criar resultados que *pareçam* aleatórios, mas que ainda escondam um padrão. A qualidade de um PRNG deve ser testada usando [métodos específicos](http://en.wikipedia.org/wiki/Randomness_tests).
Answer: Antes de responder diretamente a sua pergunta, eu gostaria de estabelecer alguns paralelos que irão ajudar no entendimento da resposta.
Primeiro, avalie as sequências abaixo e suas fórmulas correspondentes:
01010101010101010101010101   f(X) = NOT X
AAAAAAAAAAAAAAAAAAAAAAAAAA   f(X) = "A"
ABCDEFGHIJKLMNOPQRSTUVWXYZ   f(X) = CHAR(ASCII(X) + 1)

Sem muito trabalho, chegamos à conclusão que a previsibilidade (ou definição determinística) dessas sequências é muito alta - ou, inversamente, que a entropia é muito baixa.
Mas o que é entropia? É a medida de caos de um sistema. O termo foi originalmente criado para descrever sistemas termodinâmicos, mas o conceito é também aplicável a outros domínios - dados, por exemplo.
Quando falamos da geração de conteúdo aleatório ou randômico por parte de computadores, estamos falando de fórmulas que geram valores que possuem uma distribuição similar à encontrada em sistema com alta entropia e distribuição uniforme contínua.
Um exemplo de distribuição uniforme contínua de fácil visualização é o ruído branco, onde a distribuição é aparentemente impossível de ser descrita com uma fórmula determinística - mas onde podemos usar estatística para descrever a densidade. Este é um bitmap de ruído branco gerado no Random.org:

Para comparação, este é o mapa de bits da função Rand() do PHP como demonstrado pelo desenvolvedor Bo Allen em um post de 2012 no seu blog pessoal intitulado Pseudo-random vs. True random. Note o quão facilmente você detecta o padrão de geração:

Enquanto que na natureza sistemas perdem ordem e ganham entropia, o inverso ocorre em sistemas de dados. Sempre que você 'gera' números aleatórios, você está roubando o sistema de entropia, e inserindo ordem.
Como exemplo, vamos assumir que eu possuo a seguinte sequência aleatória de letras via Random String Generator do random.org:
Chave
JPVPUUWWJAZEEUMLXDVT

Que utilizo em uma fórmula simples de encriptação, onde eu 'adiciono' a variação em relação à letra A de cada posição quando aplicando à uma letra do meu payload na mesma posição.
Payload               Conteúdo encriptado
AAAAAAAAAAAAAAAAAAAA  JPVPUUWWJAZEEUMLXDVT
BBBBBBBBBBBBBBBBBBBB  KQWQVVXXKBAFFVNMYEWU

Mas note que, se meu payload for igual ou maior que a chave, eu zerei a entropia do sistema. Assim, assuma que eu concateno minha chave, para o seguinte payload:
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

Meu conteúdo encriptado seria:
JPVPUUWWJAZEEUMLXDVTJPVPUUWWJAZEEUMLXDVT
^^^                 ^^^

Posso assim facilmente detectar a repetição e prever o resto da sequência.
Do ponto de vista de segurança, funções aleatórias seguras são aquelas que periodicamente se recarregam com entropia, com o objetivo de prevenir previsibilidade.
Você pode recarregar entropia de várias maneiras; A melhor fonte de entropia é o mundo real. Alguns exemplos, que podem ser utilizados em conjunto com uma função pseudo-randômica na forma de seeds (sementes):

Acesse os trending topics do Twitter. Pegue os últimos 128 tweets gerados. Extraia o dia e hora de cada um, converta para um byte array.
Capture imagens de 2 ou mais webcams públicas ao redor do mundo. Extraia o MD5 de todas. Converta para um byte array.
Deixe seu gato andar em cima do teclado. Converta os caracteres gerados para um bytearray. (Adicione um hamster ao sistema para maior quantidade de dados. Previna o abandono de escopo do sistema com uma caixa ao redor dos três.)

Cada um desses exemplos fornece tamanho e taxa de amostragens diferentes. Quanto mais dados de origem aleatória você inserir em um sistema híbrido com um gerador pseudo-randômico acoplado, menores são as changes de detecção de padrões.
A resposta, portanto, é não: Você precisa importar entropia de um sistema externo.
Fontes:
http://www.random.org/strings/?num=10&len=10&upperalpha=on&unique=on&format=html&rnd=new
http://boallen.com/random-numbers.html
edit-disclaimer: Adicionada, diretamente no texto, a menção ao post onde o imagem do função RAND() foi retirada.
Comment: 2) Ao contrário do que diz nosso senso comum, [adicionar entropia a um sistema pode **piorar** sua segurança!!!](http://blog.cr.yp.to/20140205-entropy.html) Eu não tenho conhecimento suficiente para opinar sobre o assunto, mas de qualquer forma sugero evitar fontes de entropia que podem estar sob controle de um adversário (dependendo do seu nível de "paranoia", evite coletar entropia da internet, por mais inócuos que pareçam os dados consultados).
Comment: Retirei meu voto pra fechar (como duplicada) porque essa resposta fez valer muito a pergunta. :)
Comment: Eu realmente gostei da resposta,esclareceu muitas coisas a mim, abriu uma porta para a solução da pergunta, computadores não possuem um pouco de entropia? Pois seus relógios internos geralmente se dessincronizam. Essa  dessincronia é sinal de uma entropia mesmo que baixa(tendo em vista sua imprevisibilidade) ou de algum efeito desconhecido por mim?
Comment: Sim, sistema externo, mas sem hardware externo.Esclareceu minhas duvidas sobre o assunto.
Comment: Boa resposta, só tenho duas coisas a comentar: 1) Seu exemplo de "fórmula simples de encriptação" é uma [cifra de vigénere](http://pt.wikipedia.org/wiki/Cifra_de_Vigen%C3%A8re), totalmente "quebrada" nos dias atuais; creio que você tentou usá-la como um *one-time-pad* (e se foi isso, seu comentário sobre o tamanho da chave ser menor que o da mensagem está totalmente correto), mas acabou fazendo um "two-time-pad" quando combinou tanto com `A*` quanto com `B*`... Na minha opinião sua resposta ficaria melhor sem esse exemplo, ele não acrescenta nada, e o resto da resposta já está ótimo como está.
Comment: Funções para geração de aleatoriedade são feitas para serem rápidas. Minha pergunta ignora essa necessidade.
Comment: @WeslleyCXSardinha Você está certo - sim, algumas características entrópicas estão presentes nos computadores modernos. Entretanto, várias sofrem algum tipo de tratamento na camada de hardware, não sendo expostas para nenhum tipo de consumo ou inferência por parte do software. Tempo de processamento, entretanto, é uma inferência possível, como você apontou. O efeito fotoelétrico também. Ainda assim, você está importando entropia de um sistema externo.
Comment: @mgibsonbr Agradeço os comentários - em relação a (1), o foco foi em demonstrar a introdução de entropia, enquanto que a segunda parte demonstra a exaustão de entropia, tornando o sistema perfeitamente previsível. O exemplos dados não devem ser seguidos como recomendações de algoritmo. A necessidade de introdução a partir de um sistema externo ainda é necessária, e sua ressalva em (2) é coerente; os exemplos assumem que entropia está sendo guarantida para o sistema mencionado.
Answer: Dados aleatórios só podem ser obtidos a partir de procesoss aleatórios. Fisicamente, apenas processos quanticos são realmente aleatórios e por isto existem dispositivos externos que geram dados aleatórios: contadores geiger, junções PN polarizadas reversamente etc.
Sem usar um equipamento externo, você pode:

obter dados de sites que geram números aleatórios: se você confiar nestas fontes e no processo que elas utilizam, pode obter estes dados externamente
utilizar os números pseudo-aleatórios gerados em seu próprio computador: as melhores fontes são as do seu sistema operacional, pois devem ter sido construídos seguindo as melhores práticas vigentes à época de sua construção.
em geral, se você utilizar as funções/métodos/o que quer que seja da sua linguagem de programação, ele buscará as do sistema operacional. E serão as melhores fontes disponíveis para você.
fazer sua própria fonte: em geral, é muito fácil cometer algum engano e acabar gerando números menos aleatórios dos que os obtidos pelo próprio sistema operacional. A não ser que você desconfie/saiba que os números do seu SO não são confiáveis, o que no caso significa que seus problemas são piores do que só confiar ou não nos números que ele fornecer.

[Editada por alteração da pergunta]

A randomização pode ser obtida sem o uso de hardware externo,por exemplo usando o tempo em que um processo demora para ser feito?

Sim, o tempo que um processo demora pode sofrer alterações, já que a frequência de processamento de um processador pode variar com temperatura, tensão etc. Mas esta variação pode ser extremamente pequena, talvez imperceptível. Poderia ser verificada com o uso de um relógio? Sim, poderia, com um relógio extremamente preciso, ex., um relógio atômico ou GPS. Mas isto não é "interno" a um computador. Um programa, rodando dentro de um computador, não sabe quanto tempo levou para executar, sem utilizar um relógio de precisão externo.

Isso não é algo que é intrínseco aos estados quânticos dos materiais do processador? Se não, teoricamente, na menor unidade calculável de tempo por um computador, um processo exatamente igual é sempre calculado na mesma velocidade.

Exatamente. Se você tem um processador rodando a 3.2GHz e cada instrução levar um ciclo para ser executado, significa que cada instrução será executada em 0,3125 nanosegundos para executar. Se o seu processador estiver rodando a 3.199GHz, cada instrução levará 0,3126 nanosegundos. Não é simples possuir um relógio que consiga detectar esta diferença de tempo.

Computar dados seguros randômicamente


subprocess.Popen trying to open the module instead of executing it on shell

Question: action_publisher = subprocess.Popen(
                ["bash", "-c", "/opt/ros/melodic/bin/rostopic pub -r 20 /robot_operation std_msgs/String start"],
                env={'ROS_MASTER_URI': 'http://10.42.0.49:11311\''})

I tried to run it shell=True and shell=False. Also calling it with bash or just running my executable and I am always getting an error:
Traceback (most recent call last):
File "/opt/ros/melodic/bin/rostopic", line 34, in <module>
    import rostopic
ImportError: No module named rostopic

How can I make a call of a shell executable with open through python removing this issue? Tried all combination possible and also other stack proposed solution and still, it tries to import the executable instead of running it on a shell.
Comment: The `env` would shadow all your environment variables; does the tool you run from Bash need e.g. `PYTHONPATH` to be set in its environment?
Comment: The shell doesn't seem to add any value here at all anyway; why do you not simply `subprocess.run(["/opt/ros/melodic/bin/rostopic", "pub", "-r", "20", "/robot_operation", "std_msgs/String", "start"])`?
Comment: Have you tried to run `/opt/ros/melodic/bin/rostopic pub -r 20 /robot_operation std_msgs/String start` directly from CLI? Did it work well? And `bash -c /opt/ros/melodic/bin/rostopic pub -r 20 /robot_operation std_msgs/String start`?
Answer: I can identify several problems with your attempt, but I'm not sure I have identified them all.

You should use subprocess.check_call or subprocess.run if you just want the subprocess to run, and your Python script to wait for that to complete.  If you need to use raw subprocess.Popen(), there are several additional required steps of plumbing which you need to do yourself, which check_call or run will perform for you if you use these higher-level functions.
Your use of env will replace the variables in the environment.  Copy the existing environment instead so you don't clobber useful settings like PYTHONPATH etc which may well be preventing the subprocess from finding the library it needs.
The shell invocation seems superfluous.
The stray escaped single quote at the end of 'http://10.42.0.49:11311\'' definitely looks wrong.

With that, try this code instead; but please follow up with better diagnostics if this does not yet solve your problem completely.
import subprocess
import os

# ...
env = os.environ.copy()
env['ROS_MASTER_URI'] = 'http://10.42.0.49:11311'
action_publisher = subprocess.run(
    ["/opt/ros/melodic/bin/rostopic", "pub", "-r", "20",
     "/robot_operation", "std_msgs/String", "start"],
    env=env, check=True)

If rostopic is actually a Python program, a better solution altogether might be to import it directly instead.
Answer: It sounds like the code of that file is trying to import the Python module. If you're getting that import error even when you try to execute the file in bash/from a shell, then it has nothing to do with subprocess.Popen.
From the traceback, it looks like it's a Python file itself and it's trying to import that module, which would explain why you see the issue when executing it from a shell.
Did you go through the installation correctly, specifically the environment setup? http://wiki.ros.org/melodic/Installation/Ubuntu#melodic.2FInstallation.2FDebEnvironment.Environment_setup
It sounds like you need to source a particular file to have the correct paths available where the Python module is located so it can be found when you execute the script.
Answer: As far as I can see, your .Popen command will try to execute
bash -c /opt/ros/melodic/bin/rostopic pub -r 20 /robot_operation std_msgs/String start
while bash -c has to be followed by a string. Thus, you may need to add single quotes.
Comment: No, the argument to `bash -c` should be exactly one string; and there is nothing in this particular string which requires additional quoting.
Comment: Precisely that may be the problem. `/opt/ros/melodic/bin/rostopic pub -r 20 /robot_operation std_msgs/String start` probably will not be seen as _one string_ unless in quotes. The way you use `bash -c "vi"` and not just `bash -c vi`.
Comment: Bot work fine. In fact you could say `"bash" "-c" "vi"` and that too will work.


How to get return value from a forked / spawned process in Ruby?

Question: My simple test program:
pid = Process.spawn("sleep 10;date")

How can I place the output (eg stdout) of the "date" command in a variable when it is available? I don't want to use a file for the data exchange.
Answer: There are a whole bunch of ways to run commands from Ruby. The simplest for your case is to use backticks, which capture output:
`sleep 10; date`
# "Tue Jun 23 10:15:39 EDT 2015\n"

If you want something more similar to Process.spawn, use the open3 stdlib:
require 'open3'

stdin, stdout, wait_thr = Open3.popen2("sleep 10; date")

stdin.close
Process.wait(wait_thr.pid)
stdout.read
# "Tue Jun 23 10:15:39 EDT 2015\n"
stdout.close


,How to show that a set is empty?

Question: How can one show that a set is empty? For example, let the set $A = \{1,2,3\}$  and let the set $B = \{4,5,6\}$. I want to show that $A \cap B = \emptyset$.
I know that the typical approach to showing set equality would be, for this case, to show that $A \cap B \subseteq \emptyset$ and that $\emptyset\subseteq A \cap B $. Is this the correct approach?
Comment: there is no common element between $A,B$
Answer: For a set to be empty, its enough to show that no element belongs to it. If $x \in A \cap B$ as defined, then $x$ belongs to both $A$ and $B$. But if $x \in A$, $x = 1, 2$ or $3$, and that contradicts the fact that $x \in B$. Hence $x \not \in A \cap B$ and the intersection is empty.
Answer: Showing the first condition only ($A\cap B\subseteq \emptyset$) suffices. The empty set is anyway a subset of any set, so you don't have to show this.
Answer: Suppose $A\cap B$ is not empty. Then, by definition, there exists some $x$ such that $x\in A$ and $x\in B$. In your example, the first condition implies that either $x=1$, $x=2$, or $x=3$. Suppose that $x=1$ Since $x\in B=\{4,5,6\}$, it must mean that $1=4$, or $1=5$, or $1=6$. Any of these is clearly absurd. You can show similarly that the cases in which $x=2$ and $x=3$ lead to analogous absurdities. We have a contradiction, whence there must be no element in $A\cap B$. So, $A\cap B$ must be empty.

,How to show that a set is empty?


Exclude the www- append to only one multisite

Question: Stock Drupal 7 contains the following in the .htaccess file
  # To redirect all users to access the site WITH the 'www.' prefix,
  # (http://example.com/... will be redirected to http://www.example.com/...)
  # uncomment the following:
  RewriteCond %{HTTP_HOST} .
  RewriteCond %{HTTP_HOST} !^www\. [NC]
  RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

As per client request, this works just dandy! However, on a multisite installation, one site wants to be excluded from this rule. I tried to get them to remove the auto-www-append, but alas, that failed.
So now I'm in a situation which some multisites (most of them) want the www appended and a small group doesn't want it.
My question: Can I exempt some sites from this rule? Can I throw these exceptions into an apache conf file in /etc/httpd/conf.d/www-exceptions.cnf so that it's not overwritten in a core update?
Answer: Unfortunately putting separate htaccess files in each sites folder doesnt work, otherwise it would be quite straight forward.
Perhaps you can use REWRITECOND to do this?
RewriteCond %{REQUEST_URI} yourclientsdomain.com
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


The maximum value of r?

Question: A point  $A = (a,b)$ is defined such that it lies on the graph $y = x^2 +1$
A point $B = (c,d)$ is defined such that it lies WITHIN the area of $ (x+2)^2 + (y+2)^2 = r^2$
Let's define a matrix $M = \begin{pmatrix}
a &b \\
 c& d
\end{pmatrix}$ so that M always has an inverse. (i.e. determinant does not equal 0)
What is the maximum possible $50r^2$?

Apparently this is a highschool math problem, but I just can't solve it. I feel ashamed now.
Comment: You have $a=b^2+1$, $(c+2)^2+(d+2)^2=r^2$, and $ad-bc\neq0$. I don't see how that gives a bound on $r^2$.
Comment: @SuzuHirose apparently there is..
Answer: I've enquired in the comment and you seem to think this is the correct question, so let's analyze it.
You have $a=b^2+1$, $(c+2)^2+(d+2)^2\leq r^2$, and $ad-bc\neq0$. Let $d=0$, $b=1$, $a=2$, then $c$ may take any value except zero, thus this imposes no restriction on $r^2$.

The maximum value of r?


Determining a cut-off value from two populations of unequal sample sizes

Question: I have two groups (healthy and disease, different sample sizes) of data, pooled from the individual subject's measurements of a certain region of the brain.  The size of the brain region may be different from each individual and the sample sizes were different in these two groups.  I have just carried out the ks.test using R on the data.  They are not normally distributed.
As such, I ended up having 2500 samples for the healthy group and 1000 samples for the disease group.
I have plotted the histogram of these two groups (using normalized counts for y axis) and they appeared to be two different distributions, with overlapping. I would like to determine the cut-off value between two groups.  What would be the correct way to go about it?
Comment: Follow the advice from @FrankHarrell in his answer. Much better than a cutoff is to describe and compare the full distributions for the two groups.
Answer: Forcing any continuous assessment to be classified using a cutoff/threshold is ultimately non-reproducible, arbitrary, and has very low precision.  Plus if you use the data to select the cutoff you will need to bootstrap the whole process to get a reasonable measure of variability/stability.
Natura non facit saltus (Nature does not make jumps)
-- Gottfried Wilhelm Leibniz


How can I get the date_popup module to display AM/PM in the time selector?

Question: In date_popup's README.txt, it states that

The time selector will add AM/PM if 'a' is in the format string.

Which leads me to believe that
<code>'#default_value' => date("m/d/Y H:ia"),
'#date_format' => 'm/d/Y H:ia',
</code>
should result in a textfield for the time picker that looks like:

[2:25pm]

but instead I just get a blank text field. I can't get any combination of default_value / date_format to result in what I'm looking for. Am I reading the documentation wrong, or can this be achieved?
Update: I couldn't get this darn thing working and decided to disable the timepicker (admin/config/date/date_popup) and added the timepicker from http://jonthornton.github.com/jquery-timepicker/ using the following code:
<code>  $form['#attached']['css'][] = 'path/to/jquery-timepicker/jquery.timepicker.css';
  $form['#attached']['js'][] = '//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js';
  $form['#attached']['js'][] = array('data' => "var jq9 = jQuery.noConflict();", 'type' => 'inline');
  $form['#attached']['js'][] = 'path/to/jquery-timepicker/jquery.timepicker.js';
  $form['#attached']['js'][] = array(
    'data' => "
      jq9(document).ready(function() {
        jq9('#edit-start-date--popup-1').timepicker();
      });",
    'type' => 'inline',
  );
  $form['start_date'] = array(
    '#title' => 'Start Date',
    '#type' => 'date_popup',
    '#required' => TRUE,
    '#date_type' => DATE_DATETIME,
    '#date_timezone' => date_default_timezone(),
    '#default_value' => date("m/d/Y h:ia"),
    '#date_format' => 'm/d/Y h:ia',
    '#date_increment' => 1,
    '#date_year_range' => '-1:+1',
  );
</code>
Answer: I remember having a similar issue - I fixed it using a custom module like this, the possible cause was probably that Drupal and jQuery returned different formats...
<code>$GLOBALS['locale'] = $locale = 'fr';

/* [...] */

function x_form_alter(&$form, &$form_state, $form_id){
    // Fix date format in some exposed date filters (cck date)
    $date_format = 'd/m/Y'; /* Should be same as in "sites/all/js/jquery.datepicker/$locale.js" */
    foreach($form as $key => $value){
        isset($value['value']['#date_format']) && $form[$key]['value']['#date_format'] = $date_format;
        isset($value['min']['#date_format']) && $form[$key]['min']['#date_format'] = $date_format;
        isset($value['max']['#date_format']) && $form[$key]['max']['#date_format'] = $date_format;
    }
}
</code>
I guess you can adapt this code to your situation and even better, suggest a cleaner solution.
Comment: Thanks. I couldn't get this working and ended up replacing the default timepicker. Updated my question with that info for others.
Comment: You may be interested in the jQuery plugin **timepicker** - Preview: http://s1.postimage.org/k5o2gue8v/datetimepicker.png
Comment: I actually saw that when trying to find an alternate plugin, but I don't find using a slider to pick a time very helpful.
Comment: I read you comment but I insist - That plugin is highly customizable, the slider can be modified to suit your need (eg. move by steps of 10 minutes). Another less usable solution would be http://haineault.com/media/jquery/ui-timepickr/page/
Comment: I've used the second one you listed – that's a good one. Ultimately, I am finding the one I linked to in my question to be the fastest, "most expected" interface for the users that have to use this.


Storyboard - dynamically change height of UIView

Question: popup1

popup2

Is it possible to create single popup in storyboard & dynamically change - decrease/increase their height when error occurs (as shown in popup2)
I expect a correct approach to create such view.
Answer: One way to achieve this easily is by using a vertical UIStackView in interface builder. For example, I have a simple stack view set up that contains two labels:

Now, in your view controller you can simply set your error label to hidden or not and the stack view will dynamically take care of the rest. e.g:
Without hiding anything:

Hiding error label:
[_errorLabel setHidden:YES];

Answer: You can do it. Just put Error view in the middle of the popup and when error occurs change height of this view (error, heightConstraint.constant = 50, for example).
Then call
[self.view setNeedsUpdateConstraints];
[self.view updateConstraintsIfNeeded];

But important to note, that you should configure all constraints correctly that the popup view is stretched properly.
Comment: Ok. I will try this.
Comment: But this will not increase the height of the container view aka the popup itself.


DreamWeaver with PHP

Question: Greetings ! I have a project that has php index.php file in /htdocs. Also include files like dboperaitons.php, config.php and css file also in /htdocs/themes. Now I set up New site in dreamweaver opened the index.php file, it is running fine , but when I click on properties and ry to add or modify css property from dreamweaver, it gives me error saying unable to open file http://localhost/themes/en.css file because it is not found in the hard disk.
1. Why is it searching for file as http://localhost instead of c:/xampp/themes.
2. It says en.css file is remote file and cannot be edited.
How can I resolve this. Please guide.
Comment: You've probably referenced the CSS file that way in your HTML output. Use a relative path instead.
Answer: you can fix this problem by browsing the file manually from its location.
Answer: When you define a site in Dreamweaver you need to make sure you set up both the local and remote locations in order for it to know where files are.  It sounds like you have not defined the local site folders properly and DW is confused about where things go.

DreamWeaver with PHP


Drools Fusion De-duplication

Question: I defined a class which acts as event to the rule engine
It has the following members
1. phone number
2. latitude
3. longitude
How do I formulate a rule wherein
1. The rule counts the number of distinct people in the same location
2. Same person if crossing the same location more than once during a 1 minute interval should be counted only as one and should not be duplicated
I made the below rule but it doesn't seem to be working
import locationbasedservices.LocationEvent;

declare LocationEvent
  @role(event)
  @expires(1m)
end

rule "footfallcount"
when
  LocationEvent ( $msisdn : msisdn )
  $footfallcnt : Number(intValue > 0)
    from accumulate( LocationEvent(latitude=="77.77", longitude=="77.77",
                                   age>31 && <40, arpu>40.00, gender=="MALE")
                       from entry-point LocationSvc,
  not ArrayList( size >= 2 )
    from collect( LocationEvent( msisdn == $msisdn )
                    from entry-point LocationSvc),
          count(1))
then
  System.out.println("Footfall: " + $footfallcnt);
end

Can someone help?
Regards
Subbu
Comment: This is a case where a custom accumulate operation with inline custom code is advisable. See the Drools documentation - it's really not very difficult.
Comment: Can u provide me a sample rule so that it is bit easy for me to understand as I am very new to drools fusion and the doc is a bit confusing for me
Answer: This is what I had in mind:
$m2e: Map( $size: size )
        from accumulate ( $le: LocationEvent ( latitude == "77.77", longitude == "77.77",
                                               age > 31 && < 40, arpu > 40.00,
                                               gender == "MALE", $msisdn : msisdn )
                                 over window:time( 1m ),
                          init( Map m2e = new HashMap(); ),
                          action( m2e.put( $msisdn, $le ); ),
                          result( m2e ) )

Note carefully what the Drools manual says in the section on accumulate: It is better practice to develop an accumulate function in Java code, implementing org.drools.core.runtime.rule.TypedAccumulateFunction and running this using simple syntax.

Drools Fusion De-duplication


iptables traversal and the chain policies, manual editing

Question: I like editing the iptables file manually, but there's something that confuses me a bit.
From how I have understood iptables from the manual, it traverses the rules from top to bottom, and if no match is possible it will be logged and denied by the default rules in the bottom.
All good.
But what does these mean:
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
<accept ssh, ssl, etc>
<log all, deny all>

The chains in the top has default policy "accept" - is this only a way of saying that we accept the packets into the filter table, for later matching? For me, after reading the manual, it feels as if it would accept everything and then not read the rules, because that's how rules work by default - if anything matches it will stop reading rules and then do what the policy sais. Any documentation of this behaviour? I cannot find anything specific enough.
I have also seen this, after the *filter table:
*filter
:RH-Firewall-1-INPUT - [0:0]

Which gives the ability to add your own chains and route other chains to this chain:
-A INPUT -j RH-Firewall-1-INPUT
-A FORWARD -j RH-Firewall-1-INPUT

But here the "ACCEPT" or "DROP" is not specified at all for this chain, but instead there's a dash (-).
Which makes me even more confused - how does it work?
Answer:
The policy on a built-in chain determines what happens to packets that make it through all the rules in the chain without matching a single one with a dispositive target.  In your example above, packets that make it all the way through the FORWARD chain without matching any rule with a dispositive target will be ACCEPTed, because the chain's policy is ACCEPT.
User-defined chains cannot have a policy.  Packets that pass all the way through a user-defined chain without matching a rule with a dispositive target return to the chain from which they were sent to the user-defined chain (the "calling chain") at the rule after the one that sent them there.

A dispositive target is one which disposes of a packet; examples include DROP, ACCEPT, and MASQUERADE; non-dispositive targets include LOG, and the null target (it's quite legal to have a rule that has no target).  When a packet matches a rule with a dispositive target, the packet is considered disposed of, and no further rule processing occurs.  When a packet matches a rule without a dispositive target, packet processing continues at the next rule.
An important corollary of this logic on target-matching and disposition is that first-dispositive-match wins.  Too often we see questions on SF where people have a chain that says, eg,
Chain INPUT (policy ACCEPT 210 packets, 22621 bytes)
 pkts bytes target     prot opt in     out     source        destination
3224K 1330M DROP       tcp  --  *      *       0.0.0.0/0     0.0.0.0/0     tcp dpt:80

which contains a single rule to block access to a web server (tcp dpt:80).  They wish to allow a single external IP address, say 188.8.131.52, to access this web server, so they add a rule with
iptables -A INPUT -p tcp --dport 80 -s 22.214.171.124 -j ACCEPT

and they end up with a chain like this
Chain INPUT (policy ACCEPT 210 packets, 22621 bytes)
 pkts bytes target     prot opt in     out     source        destination
3224K 1330M DROP       tcp  --  *      *       0.0.0.0/0     0.0.0.0/0     tcp dpt:80
    0     0 ACCEPT     tcp  --  *      *       126.96.36.199       0.0.0.0/0     tcp dpt:80

As you can see, the packet counts on that last rule are zero - and they will always be zero.  No packet can match that last rule without having matched the one before it, and the one before it is dispositive (DROP), so no packet will ever reach that last rule.
The way to deal with this correctly is to ensure that your exceptions come before your rules, like this:
Chain INPUT (policy ACCEPT 210 packets, 22621 bytes)
 pkts bytes target     prot opt in     out     source        destination
   20   875 ACCEPT     tcp  --  *      *       188.8.131.52       0.0.0.0/0     tcp dpt:80
3224K 1330M DROP       tcp  --  *      *       0.0.0.0/0     0.0.0.0/0     tcp dpt:80

Now, the exceptional acceptances are handled first, then other web server packets that don't come from the exceptional server are handled and dropped, and finally the chain policy takes care of all other packets and accepts them.
Comment: Perfect! Thank you, that makes a lot of sense. I will accept your answer when allowed to do so.
Comment: Thanks for that.  It looks like you've bothered to read a bit about SF and the culture (including answer acceptance!) before posting.  Not all new users seem to be prepared to bother with that, so **thank you** - I hope you stay around on SF as an active participant.
Comment: Thanks for the warm welcome! And wow, you added a lot more information, thanks again!


apply values of inputs to all its td innerhtml

Question: is it possible to change the innerhtml of all the td when it has the input inside, i mean to take the input's value and apply it to it's td innerhtml, for example, here's the table and its input inside:

  <input value="test" />
  123

to change it smth into this:

  test
  123

for all of the td and input values without applying id's and classes?! please pay attention that td innerhtml didnt change :) thank you all for the help! ;)
Answer: That's pretty easy.
Name your table first (to find it easily).

  <input value="test" />

Then you can do this:
$('#the_table td input[type="text"]').each(function() {
  var val = $(this).val();
  $(this).parent('td').html(val);
});

Live demo.
Explanation:

find all inputs that are within  that are in this certain table.
for each input:
2.1 retrieve value from the input
2.2 find first parent of the input that is a  tag and set its innerHTML to that value
Comment: got one more problem! what if there are input whose types are: hidden, and i need to use just the inputs whose type is text?! 3 min left, will accept ur answer, no worries ))
Answer: Yes, you can do it like this:
$('table td:has(:input:only-child)').each(function () {
    $(this).html($(':input', this).val());
});

It assumes there only is an input in the td. If that is not the case, then remove :only-child.
Explanation of table td:has(:input:only-child)
It says, take any td within a table, which has an input as the only child.
You can test it here: http://jsfiddle.net/eydtw/
Update: take the input which is not hidden.
$('table td:has(input[type!="hidden"])').each(function () {
    $(this).html($('input[type!="hidden"]', this).val());
});

http://jsfiddle.net/eydtw/1/
or: take the input which is text.
$('table td:has(input:text)').each(function () {
    $(this).html($('input:text', this).val());
});

http://jsfiddle.net/eydtw/3/
Answer: $.each($('table td'),function(){

    if($(this).children().length !=0)
    {

        var temp = $($(this).children()[0]).val();
        $(this).html(temp);

    }

})


Is there any built in function to render image file extension like jpg, png etc?

Question: Is there any built in function in Drupal 7 to render image file extension like jpg, png etc on node load.
I have tried image_get_info etc.
Answer: image_get_info() should do the trick.
//if you want to get the extension of image1.jpg
$filepath = "sites/default/files/images/image1.jpg";
$info_var = image_get_info($filepath, FALSE);
echo "the image extension is ".$info_var['extension'];