Dropdown Menu showing invisible child boxes but only shows the child text when hovered upon them

Question: I was creating a dropdown menu which when hovered upon displays sub-links.
But, I ran into a problem as when I hover on the dropdown, it shows a blank box and only shows the text when hovered upon it specifically.
I want that the text to be displayed at all times.

// Sticky Navbar
var h = document.getElementById("navbar");
var stuck = false;
var stickPoint = getDistance();

function getDistance() {
  var topDist = h.offsetTop;
  return topDist;
}

window.onscroll = function(e) {
  var distance = getDistance() - window.pageYOffset;
  var offset = window.pageYOffset;
  if ( (distance <= 0) && !stuck) {
    h.style.position = 'fixed';
    h.style.top = '0px';
    stuck = true;
  } else if (stuck && (offset <= stickPoint)){
    h.style.position = 'static';
    stuck = false;
  }
}

// Preloader
const preloader = document.querySelector('.preloader');

const fadeEffect = setInterval(() => {
  // if we don't set opacity 1 in CSS, then   //it will be equaled to "", that's why we   // check it
  if (!preloader.style.opacity) {
    preloader.style.opacity = 1;
  }
  if (preloader.style.opacity > 0) {
    preloader.style.opacity -= 0.1;
  } else {
    clearInterval(fadeEffect);
  }
}, 200);
window.addEventListener('load', fadeEffect);
/* Navbar */
#navbar {
  height: 75px;
  display: block;
  background: #333;
  width: 100%;
}

#navbar a{
  font-size: 16px;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

.dropdown {
  padding-top: 10px;
  text-align: center;
}

.dropdown .dropbtn {
  font-size: 16px;
  border: none;
  outline: none;
  color: white;
  padding: 14px 16px;
  background-color: inherit;
  font-family: inherit;
  margin: 0;
}

#navbar a:hover, .dropdown:hover .dropbtn {
  background-color: silver;
  color: black;
}

.dropdown-content {
  display: none;
  position: absolute;
  margin-left: 49%;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

.dropdown-content a {
  display: inline-block;
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropdown-content a:hover {
  background-color: #ddd;
}

.dropdown:hover .dropdown-content {
  display: block;
}

    <button class="dropbtn">Projects

    </button>

      Drum Kit
      Coming Soon...

Apart from this, I have implemented the Sticky Navbar and a Simple Preloader using Vanilla JS which I am sharing if it might help.
Just help me with the dropdown thing.
Any help will be appreciated.
Comment: `#navbar a { color: white }`. Link color is set to white.
Comment: I have tried this but it isn't working. I think my Sticky Navbar JS Code is creating these problems as upon removing that JS Code, the dropdown works fine.
I think I will have to use JQuery instead of Vanilla JS to implement Sticky Navbar now.
Thanks Anyways.
Answer: As @Y.S. point out you have color set to white. Not sure what you've tried that didn't work, this works fine for me:

// Sticky Navbar
var h = document.getElementById("navbar");
var stuck = false;
var stickPoint = getDistance();

function getDistance() {
  var topDist = h.offsetTop;
  return topDist;
}

window.onscroll = function(e) {
  var distance = getDistance() - window.pageYOffset;
  var offset = window.pageYOffset;
  if ( (distance <= 0) && !stuck) {
    h.style.position = 'fixed';
    h.style.top = '0px';
    stuck = true;
  } else if (stuck && (offset <= stickPoint)){
    h.style.position = 'static';
    stuck = false;
  }
}

// Preloader
const preloader = document.querySelector('.preloader');

const fadeEffect = () =>
{
  setInterval(() => {
    // if we don't set opacity 1 in CSS, then   //it will be equaled to "", that's why we   // check it
    if (!preloader.style.opacity) {
      preloader.style.opacity = 1;
    }
    if (preloader.style.opacity > 0) {
      preloader.style.opacity -= 0.1;
    } else {
      clearInterval(fadeEffect);
    }
  }, 200);
}
window.addEventListener('load', fadeEffect);
/* Navbar */
#navbar {
  height: 75px;
  display: block;
  background: #333;
  width: 100%;
}

#navbar a{
  font-size: 16px;
  color: black;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

.dropdown {
  padding-top: 10px;
  text-align: center;
}

.dropdown .dropbtn {
  font-size: 16px;
  border: none;
  outline: none;
  color: white;
  padding: 14px 16px;
  background-color: inherit;
  font-family: inherit;
  margin: 0;
}

#navbar a:hover, .dropdown:hover .dropbtn {
  background-color: silver;
  color: black;
}

.dropdown-content {
  display: none;
  position: absolute;
  margin-left: 49%;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

.dropdown-content a {
  display: inline-block;
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropdown-content a:hover {
  background-color: #ddd;
}

.dropdown:hover .dropdown-content {
  display: block;
}

    <button class="dropbtn">Projects

    </button>

      Drum Kit
      Coming Soon...


When to apply time series models?

Question: When should I apply traditional time series models (e.g. additive, ARIMA) versus other models such as linear regression?
For example, if I wanted to build a predictive model for website traffic, I could approach it with:

Use previous traffic data + time series technique like exponential smoothing
Collect other data features such as advertising spend, social media activity, email campaigns and run a linear regression model

The former approach is more straight forward, faster to implement and likely to fit better compared to the latter. What disadvantages am I not taking into account here?
The only thing I'm coming up with is that approach #2 will provide some insight into the weighting of the feature data (e.g. relationship between ad spend and traffic).
Answer: The answer you are looking for is completely dependent on what you are attempting to model.
If you are looking to forecast future website traffic without changing anything in your website, then use some sort of time series forecasting algorithm.  This ensures you will not have to worry about annoying autocorrelation or other external factors.
If you are interested in understanding what factors drive the website traffic, you will want something a bit more in-depth, which allows you to include and interpret external variables.  A simple example is linear regression, which allows you to interpret variance in website traffic by a number of input variables (one of which may be time-of-day).

The former approach is more straight forward, faster to implement and likely to fit better compared to the latter. What disadvantages am I not taking into account here?

This may not always be true, but in some cases it is.  Statistical modeling packages are quite robust and this makes for easy time series modeling.  However, using a simple ARIMA model may not actually predict very well without giving you extremely high errors.  Plus, traditional ARIMA does not allow you to incorporate external factors driving website traffic; it is completely dependent on previous values of your measure of interest.  So, if you edit your website in any way, your forecast could be very very inaccurate (since you are not accounting for external factors which could have a huge impact on traffic).

The only thing I'm coming up with is that approach #2 will provide some insight into the weighting of the feature data (e.g. relationship between ad spend and traffic).

Understanding how different variables are affecting your output (website traffic) could be very important if you are interested in, say, increasing traffic in the future, not just modeling future traffic.  For example, if one of your variables is percentage_of_blue_on_page, and you find that it is inversely linearly related to the amount of website traffic you are seeing, you may want to try to decrease the amount of blue on your page to increase website traffic.  This is a silly example, of course, but it is meant to be demonstrative.
Comment: Thanks for that detailed explanation! I'm still pretty new to the industry, and appreciate the insight. What are your thoughts then towards ARIMAX in this situation?

It seems like it'll allow for that added insight on external variables and how they affect the output.
Comment: That could work, to add additional covariates.  I am still partial against ARMA-based models, personally.  I like to understand data on a more granular level.  This way you can make more informed projections moving forward without relying so heavily on one specific algorithm.  For example, understanding how three factors influence your output would allow you to intelligently forecast future values of your output based on different scenarios where you vary your input variables.

When to apply time series models?


Laravel Job for Bulk Mail

Question: this is the first time I am using laravel queue jobs, and somehow i could not get it working.
This is my mail class:
class TopluKabulMektubu extends Mailable
{
    use Queueable, SerializesModels;
    public $letter;

    public function __construct(AcceptLetter $letter)
    {
        $this->letter = $letter;
    }

    public function build()
    {
        $letter = $this->letter;

        return $this->subject('Mail Title')
            ->view('emails.topluKabulSon')
            ->attach(public_path($letter->pdf), [
                            'as' => 'AcceptanceLetter.pdf',
                            'mime' => 'application/pdf',
                        ]);
    }
}

And I created a function inside my AcceptanceLetter model to use mail easier :
public function sendAcceptanceLetter(){
        Mail::to('******@gmail.com')->queue(new TopluKabulMektubu($this));
        if(Mail::failures()){
                   $this->email_send = 2;
                   $this->save();
                }else{
            $this->email_send = 1;
            $this->save();

                }
    }

I created a queue table with php artisan queue:table and migrated, also changed queue connection to database from env file.
And my job file:
class QueueJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $letter;

    public function __construct($letter)
    {
        //
        $this->letter = $letter;
    }

    public function handle()
    {
        $this->letter->sendAcceptanceLetter();
    }
}

Web route triggers my job :
Route::get('/topluDeneme', [PaginationController::class, 'topluQueue']);
And the controller:
public function topluQueue(){
        $letters = AcceptLetter::where('email', '!=', null)->where('passport_number','!=','0');

        foreach($letters as $letter){
            QueueJob::dispatch($letter);
        }
    }

I expect when i run php artisan queue:listen on terminal and go to /topluDeneme route, mails to be sent. But nothing happens on terminal, mails not sent and nothing changes on job datatable.
Answer: I found whats wrong with my code. It seems I forgot to use get() in the controller, here is the correct version :
public function topluQueue(){
    $letters = AcceptLetter::where('email', '!=', null)->where('passport_number','!=','0')->get();

    foreach($letters as $letter){
        QueueJob::dispatch($letter);
    }
}

Laravel Job for Bulk Mail


Showing that the power of a test approaches 1 as the sample size approaches infinity

Question: I'm working on some exercises for my econometrics class and I'm a little confused. I'm meant to consider a model
$$Y=\beta_0 +\beta_1X+u$$
and propose a test (test statistic and critical value) of $H_0:\beta_1 =0$ against $H_1:\beta_1 \ne 0$ such that the Type 1 error goes to 5% and the power of the test goes to 1 as the sample size goes to infinity.
Pretty standard I think, I'm pretty sure that we just want to use the test statistic $\tau=| \frac {\hat{\beta_1}}{\hat{SE}(\beta_1)}|$ with a critical value of 1.96. By the central limit theorem, under the null hypothesis, we have
$\frac {\hat{\beta_1}}{\hat{SE}(\beta_1)}\longrightarrow_d N(0,1)$
and so we can show the type 1 error in the limit pretty easy.
If anything is wrong so far, please let me know.
The problem I'm having is showing that the power of the test approaches 1. Under $H_1$, for large sample sizes
$\frac {\hat{\beta_1}}{\hat{SE}(\beta_1)}\approx \frac {\hat{\beta_1}}{{SE}(\beta_1)}=\frac{\hat{\beta_1}}{\sqrt{\frac{\sigma^2}{nVar(X)}}}\longrightarrow_d ???????$
Now this is where I'm confused... Does that term converge to something? Am I meant to make an argument about convergence in distribution?
The one thing I was thinking is that we can argue that
$$\frac{\hat{\beta_1}}{\sqrt{\frac{\sigma^2}{nVar(X)}}}\longrightarrow_p \frac{\beta_1}{\sqrt{\frac{\sigma^2}{nVar(X)}}}$$
And that this number is clearly increasing with n, so the test statistic goes to infinity in the limit. Is this a correct argument though? My problem with this is that, why don't we then say that that implies that the test statistic goes to 0 in the limit under $H_0$? We don't say that, we say that it goes to a distribution, not a number, but
Comment: What is your noise model? Presumably your $X$ values are fixed and known, rather than random. If the noise is Gaussian, e.g., you know the distribution of the test statistic exactly under the null hypothesis and for each fixed value of the parameter under the alternative. Everything should be able to be written pretty explicitly under such assumptions.
Answer: You are almost there, but you need to make your arguments more formal.
Rewrite the null and alternative hypothesis more generally so that they read
$$
\begin{align}
\mathfrak{h}_0{}:{}\beta_1 &= \beta^0_1\\
\mathfrak{h}_a{}:{}\beta_1&=\beta_1^a
\end{align}
$$

Then, using standard machinery, and under the linear regression model, we can show that under the null:
$$
\begin{align}
\dfrac{\sqrt{n}\left(\widehat{\beta}_1- \beta_1^0\right)}{\widehat{\text{a.var.}}(\widehat{\beta}_1)} &\rightarrow^d X\\
&{\sim}\text{t}(n-K)
\end{align}
$$
where $t(n-K)$ is the t-distribution with $n-K$ degrees of freedom, and $K$ is equal to the total number of regressors ($K=2$). Now recall that the definition of convergence in probability is that the distribution functions of the sequence of statistics converges to the distribution function of the limiting random variable at each continuity point of the limiting distribution. In this case,
$$
\scriptstyle
\begin{align}
\lim_{n\to\infty}\mathbb{P}\left[\left|\frac{\sqrt{n}\left(\widehat{\beta}_1- \beta_1^0\right)}{\widehat{\text{a.var.}}(\widehat{\beta}_1)} \right| > t_{1-\tfrac{\alpha}{2}}(n-K)\right] &= \lim_{n\to \infty}\mathbb{P}\left[\frac{\sqrt{n}\left(\widehat{\beta}_1- \beta_1^0\right)}{\widehat{\text{a.var.}}(\widehat{\beta}_1)}  > t_{1-\tfrac{\alpha}{2}}(n-K)\right] \\
&\quad+ \lim_{n\to \infty}\mathbb{P}\left[\frac{\sqrt{n}\left(\widehat{\beta}_1- \beta_1^0\right)}{\widehat{\text{a.var.}}(\widehat{\beta}_1)}  \leq -t_{1-\tfrac{\alpha}{2}}(n-K)\right] \\
&= \mathbb{P}\left[X  > t_{1-\tfrac{\alpha}{2}}(n-K) \right] + \mathbb{P}\left[X \leq -t_{1-\tfrac{\alpha}{2}(n-K)} \right] \\
%&= 1-\Phi(z_{1-\tfrac{\alpha}{2}}) + \Phi(z_{\tfrac{\alpha}{2}}) \\
&= \alpha
\end{align}
$$
where $\alpha$ is the nominal size of the test, and $t_\alpha(d)$ is the $\alpha$-th quantile of the t-distribution with $d$ degrees of freedom. This proves that the t-test has the correct size asymptotically.

Now, under the alternative, we have that
$$
\begin{align}
\dfrac{\sqrt{n}\left(\widehat{\beta}_1- \beta_1^a\right)}{\widehat{\text{a.var.}}(\widehat{\beta}_1)} &\rightarrow^d X\\
 &{\sim}\text{t}(n-K)
\end{align}
$$
This implies that
$$
\begin{align}
\dfrac{\sqrt{n}\left(\widehat{\beta}_1- \beta_1^0\right)}{\widehat{\text{a.var.}}(\widehat{\beta}_1)} &=\dfrac{\sqrt{n}\left(\widehat{\beta}_1- \beta_1^a\right)}{\widehat{\text{a.var.}}(\widehat{\beta}_1)}+\dfrac{\sqrt{n}\left(\beta^a_1- \beta_1^0\right)}{\widehat{\text{a.var.}}(\widehat{\beta}_1)} \\
&= \mathcal{O}_p(1)+ \mathcal{O}_p(\sqrt{n}) \\
&= \mathcal{O}_p(\sqrt{n})
\end{align}
$$
By definition of orders of magnitude, this means that w.p.a. 1 under the alternative, the t-statistic is greater than any fixed (finite) critical value.


Local DNS for AWS instance

Question: Amazon provides a domain names like blah-blah.amazonaws.com.  They want us to use the domain name instead of an IP because the IPs are transient.
The local hosts file on my computer only takes IP addresses.
So, how can I redirect dev.example.com to blah-blah.amazonaws.com locally from my machine?
Comment: Why do you need to do this on your local hosts file? Can you create a DNS entry?
Comment: what is your computer? And what are you trying to access?  Something in public dns or private ??
Answer: In the DNS zone for for example.com you create a cname record of dev, pointing to blah-blah.amazonaws.com. (the trailing dot in the URL is very important).

Local DNS for AWS instance


Can sidearm or submarine pitching be harmful to youth baseball players?

Question: As a fairly new fan to baseball back in the late 1970's and early 1980's I enjoyed watching pitchers like Kent Tekulve and Dan Quisenberry pitch with their submarine deliveries. At the time, I remember hearing that pitching that way is a more natural motion for the arm and shoulder, and would be less likely to cause injury.
Now, decades later I find myself coaching youth baseball. I considered teaching sidearm and even submarine delivery. However, other coaches have warned me that such deliveries can be harmful to young players. Is this true?
Answer: This is anecdotal, so keep that in mind, but as a young pitcher, I threw out my shoulder (some undiagnosed rotator cuff issue probably) by throwing overhand.
All I wanted to do in the world was pitch, and my coaches were idiots, so they let me keep pitching even though I was in pain.
Gradually I switched first to sidearm and then to full submarine.  Two things happened:

My accuracy increased dramatically with no loss of velocity
The pain virtually stopped.  I could pitch 3 innings easy (which is what I was pitching at the time)

Long term - I have a rotator cuff injury now (but it's from co-sleeping with my son, not sports related) - and I'm 38 and still play softball.
I'd check out what the experts say, but for what it's worth, it worked for me.
Comment: Co-sleeping with your son gave you a rotator cuff injury? That's weird. Then again I thought my kid had given me a concussion once when we were co-sleeping ... I got kicked in the head! Later concluded it was an inner ear problem.
Comment: @GreenMatt - lol - in my case, I was so worried that I'd roll over on him, I had my arm permanently in a funny position, and it began to hurt over time.  I'd sleep with my arm behind his head, while on my back, so that I'd really have to work at it to roll over.


Posterior distribution dependent on two variables make inferences about one

Question: If I have some model for X that depends on $\theta_1, \theta_2$ and has a posterior $P(\theta_1, \theta_2 | x_1, ... x_n)$, how would I make inferences just about $\theta_1$?
What I am thinking so far is just to integrate $P(\theta_1, \theta_2 | x_1,...,x_n)$ over $\theta_2$ to get $P(\theta_1 | x_1,...,x_n)$.
Comment: You are right in your approach but what is your doubt?
Comment: That would indeed be the standard approach to obtain the marginal posterior and to make the desired inference.
Answer: Calculating the marginal, if tractable, is a good approach. Another, perhaps easier approach is to calculate the full conditional of $\theta_1\: |\: x_1, ..., x_, \theta_2$ and $\theta_2\: |\: x_1, ..., x_, \theta_1$. These are sometimes easier to find analytically. Then you could simply perform Gibbs sampling to find the posterior for $\theta_1$ and make inferences on that. Personally, I try to avoid integrals when possible.


Desabilitar classe ao fechar modal

Question: Tenho o seguinte JS para minha modal:

Quero remover a classe modal-lg do ID="modalDialog" quando fechar a modal. Como fazer? A forma como fiz não está funcionando.
Answer: Fiz um exemplo aqui e tudo funciona normal.
Segue meu exemplo.

 $(function () {
            $('#modalDialog').on('hidden.bs.modal', function () {
                $("#modalDialog").removeClass("modal-lg");
                alert("Fechou.");
            });
        });

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">

Teste

                    <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>

    <button type='button' class='btn btn-primary' data-toggle='modal' data-target='.bs-example-modal-lg'>Visualizar</button>

Desabilitar classe ao fechar modal


Can a React Native or NativeBase Picker have Items which include images?

Question: I'm new to smartphone programming and have joined a project using React Native and NativeBase.
I'd like to include an image/icon in each Item in a Picker, which doesn't seem like an exotic concept, but it doesn't seem to be supported and I can't find anyone discussing doing it on SO or by Googling.
I've tried a couple ways of adding things inside the <Picker.Item> and </Picker.Item> but anything put there seems to simply be ignored.
Is it possible or is there a different approach to do what I want using these frameworks?
Comment: do you mean something like modal dropdown? https://github.com/sohobloo/react-native-modal-dropdown
Comment: sure glad to do it :), please let me know if you have trouble in implementing this
Comment: hmmm seems like a little bit advance for me, please let me know if you able to achieve your goal. I would like to know it as well :), good luck with the project
Comment: @GaneshCauda: That looks exactly like what I was looking for if you want to submit it as an answer.
Comment: In my case the images were flags and I was able to use Unicode emoji flags as an alternative so I won't have to implement it just yet after all (-:
Comment: let me know how to render base64 string in that renderRow . Tnx.                          https://github.com/sohobloo/react-native-modal-dropdown/issues/180
Answer: You can try this package
https://github.com/sohobloo/react-native-modal-dropdown
the complete example you can check here
https://github.com/sohobloo/react-native-modal-dropdown/blob/master/example/index.js
the use is something like this
_dropdown_2_renderRow(rowData, rowID, highlighted) {
let icon = highlighted ? require('./images/heart.png') : require('./images/flower.png');
let evenRow = rowID % 2;
return (
  <TouchableHighlight underlayColor='cornflowerblue'>
    <View style={[styles.dropdown_2_row, {backgroundColor: evenRow ? 'lemonchiffon' : 'white'}]}>
      <Image style={styles.dropdown_2_image}
             mode='stretch'
             source={icon}
      />
      <Text style={[styles.dropdown_2_row_text, highlighted && {color: 'mediumaquamarine'}]}>
        {`${rowData.name} (${rowData.age})`}
      </Text>
    </View>
  </TouchableHighlight>
);
}

the end product example is look like this :

all copyrights belongs to :
https://github.com/sohobloo
Comment: I believe you can use any react-native component for the row component, and default  component supposed to be able to load base64 sources
Comment: let me know how to render base64 string in that renderRow . Tnx.          github.com/sohobloo/react-native-modal-dropdown/issues/180                        .Please check this


Is there a way to keep costs low with AWS Amplify DataStore @searchable directive?

Question: I'm using AWS Amplify DataStore to create an offline first notes app. To be able to search my notes I just add the @searchabledirective to the Schema and my DB documents are streamed to an AWS elastic service.
But, my initial test of this ended up costing me a lot of money. My dev project went from $2/month to $30/month just by adding the ES node. There doesn't seem to be a way to downscale the service from the AWS console.
Does anyone know of a way to not pay $30/month for 12kb of data in ES?
Answer: I also found the cost of Elasticsearch to be annoying when developing my MVP so I created the graphql-algolia-transformer which allows you to use Algolia instead for your searches which has a decent free quota and is pay per record/request from there.
Comment: This is great @thefinnomenon!
Answer: As per the documentation the @searchable directive sets up an ElasticSearch instance and streams data there. Moreover, t2.micro instances are not compatible - probably why you can't downscale.
There are a number of issues on the AWS Amplify Github repo similar to your question - see this and this.
I am in a similar boat and debating setting up a small server running MeiliSearch or migrating to Algolia.
FWIW, the AppSync documentation search is powered by Algolia :-).
Answer: If your schema isn't so complicated, then you can just use filter.
Let's assume you has got schema.graphql:
type Person @model {
  id: ID!
  firstName: String!
  lastName: String!
}

Then you can search by query:
listPersons(filter: {
  or: [
    { firstName: { contains: "Alex" } },
    { lastName: { contains: "Alex" } }
  ]
}) {
  items {
    id
    firstName
    lastName
  }
}

But if your search queries are more complicated you need to use ElasticSearch.
https://docs.amplify.aws/cli/graphql-transformer/examples#blog-queries
Comment: Just a caution, the listPersons runs a Scan on the database and then only filters what it gets, as your data scales the scans become a very heavy operation to run on all your data.

https://youtu.be/VG2XWoD-rS0?t=460


How to copy only a specific amount of file?

Question: I have a directory with almost 100,000 files inside. I want to copy 20,000 of them to another directory. Is it possible to do this with the cp command or is there any other way?
Comment: Which 20,000 do you want to copy?
Answer: <code>for FILE in `find /your/directory ! -type d  | head -n 20000`; do cp $FILE /destination/dir/; done
</code>


Interpretability for chi-squared test?

Question:

Sex
DiabetesNOTPresent
DiabetesYESPresent

Female
50
55

Male
124
70

So I have this chi-squared test that I performed. My result was statistically significant. The data relates to heart failure in patients at a certain hospital. How would I interpret this? Please correct me if I'm wrong but...
My finding is that the proportion of women that have diabetes is expected to be higher than the proportion in that of men, correct?
Is this true for all patients coming into that hospital? Is it true for only the amount of patients similar to that of those found in my dataset, and this just repeats for every new "group" of patients? Would saying that "the proportion of men having diabetes is smaller than the proportion of women with diabetes" be just as valid?
Also, just because it is significant, does that mean that it's actually helpful? Or is the proportion difference just too small? Wouldn't the proportion difference be just as large whether I have 100 samples vs 10,000 samples... increasing as I have more patients?
Please nitpick everything I've spoken. This is probably one of the first chi-squared tests I've performed.
Comment: What it tells it that in the sample you selected, the probability of seeing the result you saw or one as or more extreme would have been unlikely if males and females were equally likely to have diabetes present.  We do not know how you selected the sample (e.g. why are there more females than males in total?), and so whether this is suggestive about others going in to the hospital.  Nor do we know whether the difference between male and female proportions is helpful in taking decisions, as we do not know what decisions you might make.
Comment: @Henry meant to switch the sex inputs around...
Comment: OK - so with that edit, part of my comment would switch too
Answer: The chi-square test of a 2x2 contingency table such as this basically tests the following null hypothesis: gender should produce no difference in diabetes rates. Essentially, your chi-square test poses the following question: "Is the difference in diabetes rates by gender more than we would expect?".
In this case, you have a lot of males that do not have diabetes. Because this number is disproportionate, your chi square is consequently 6.78, giving a significant value. However, you don't know the strength of this association yet, so it may also help to also obtain Yule's Q coefficient. You can get this by using the psych package in R, using the Yule function. I demonstrate with your data below:
#### Construct Contingency Table ####
diabetes <- matrix(c(50,55,124,70),
                   ncol=2,
                   byrow=TRUE)
rownames(diabetes) <- c("Female","Male")
colnames(diabetes) <- c("No Diabetes","Diabetes")
diabetes

#### Test Table ####
chisq.test(diabetes) # chi square
psych::Yule(diabetes) # Yule's Q coefficient

The association is moderate, as shown by the result:
[1] -0.3217054

So to summarize, your test is significant, indicating that you can say with some level of certainty that we cannot support the null hypothesis: gender seems to be associated with diabetes rates. Your Yule coefficient explains that this association is moderate.
To answer some of your additional questions, this test only relates to the sample size you have, so it is not generalizable to all hospitals. This should make sense intuitively, as 1) your sample size isn't extremely large and 2) hospitals can vary a lot, such as how doctors are trained, access to resources, etc. Is this helpful? Certainly. While we would want more people to test and more sophisticated ways of tackling this question, this at least informs us that at the very minimum there is in fact a trend at this hospital, and it may (with caveats) indicate that this could be the case elsewhere. To your question about proportionality, there is no way of knowing whether or not this would hold for larger samples, but theoretically if the effect is consistent, the underlying assertion of the test would still hold. Only more testing in more settings can answer how generalizable your findings actually are.
To see what is going on under the hood, this video shows how to calculate both chi-square and Yule's coefficient by hand. This video is also an accessible summary of what chi-square tests do.
Comment: I'm wondering whether the first paragraph might be a bit misleading? I refer to "tries to refute this hypothesis with an alternative" and later on "you can say with some level of certainty that the alternative hypothesis is true". In NHST the statistic is computed assuming the null hypothesis is true. So we can decide to reject or not reject the null, but not accept the alternative.
Comment: I think I see your point. I've amended my answer, though I'm not sure if that is any better worded.
Comment: This is rad. So just to be crazy clear, the finding of women holding a higher number of diabetes patients compared to men, is *only* true if a new --same number-- set of patients were to come into this *same* hospital, correct?
Comment: If you mean an additional number of patents, the exact amount doesn't really matter. More participants means more data, which means more precision of your test. So whatever your previous result would be, the result with more data would be more powerful and potentially more generalizable. But given you are testing in one hospital, its of course difficult to say if its true across the broad spectrum of hospitals. So many environmental factors can be potentially confounding the results.
Comment: Ah, it looks like Chi-Squared just measures if there is a statistically significant correlation between two variables in the dataset it is being performed on and **not** applicable to other, new, data (new patients)-- though it could give clues depending on how many samples it had. Got it. Thanks tons!
Comment: Well the chi-square test by itself doesn't test a correlation per se, just the counts of your tables and the variation therein. But yeah, new patients would have different outcomes, so its impossible to say what your test would look like after. Glad I could be helpful. You are encouraged to accept this answer by clicking on the checkmark next to it if you found it helpful.
Comment: Expressing what the results of a statistical test tells us can be tricky. Take a look at this paper: [Statistical tests, P values, confidence intervals, and power: a guide to misinterpretations](https://doi.org/10.1007/s10654-016-0149-3). And perhaps this recent crash of a CV thread which exemplifies how hard it can be to say it right, let alone to do in an intuitive way: [Why can't we accept the null hypothesis...](https://stats.stackexchange.com/q/587383/237901). Note that the title of the question makes a wrong statement.
Comment: Thanks for the useful insight. Ill give those a read.

Interpretability for chi-squared test?


Saving C# decimal to SQL decimal(18,4) SQL

Question: I've got a slight issue.  I have a field where my customer wishes to store up to 4 decimal places back for a price (weird to say the least but still).  So far, I'm only able to commit 2 decimal places back to the DB.
I am using Code First with Entity to do the saving and SQL Server 2008 R2 for my DB.  Here is what I have fore each.
PurchaseOrder.cs (Code First)
public virtual decimal ShippingCost { get; set; }

PurchaseOrderService.cs (Service layer to save to Entity)
public virtual void UpdatePurchaseOrder(PurchaseOrder purchaseOrder)
{
    if (purchaseOrder == null)
       throw new ArgumentNullException("purchase order");

    _purchaseOrderRepository.Update(purchaseOrder);
}

PurchaseOrder table:
ShippingCost decimal(18, 4) NOT NULL

Ex.  Shipping Cost is input as 10.5555 on the UI.  All the way down throught the Service layer, it holds onto that value.  Once it hits where it is sending it to Entity to save, the DB does not keep those extra values beyond 10.55.
Answer: Theree is an Entity Framework default value that uses only 2 decimals.
Decimal precision and scale in EF Code First
shows how to change that.


Navigate through pages using Redux and React-router

Question: I have a series of pages to capture data from a user. I would like to use Redux with React-Router, to navigate through my pages, rather than link to each page manually.
I have a very simple Router setup.
import Screen1 from './components/Screen1';
import Screen2 from './components/Screen2';
import Screen3 from './components/Screen3';
import Screen4 from './components/Screen4';
import Screen5 from './components/Screen5';
import Screen6 from './components/Screen6';

let store = createStore(lydApp);

render(
    <Router>

            <Route path="/" component={Screen1} />
            <Route path="/1" component={Screen2} />
            <Route path="/2" component={Screen3} />
            <Route path="/3" component={Screen4} />
            <Route path="/4" component={Screen5} />
            <Route path="/5" component={Screen6} />

    </Router>,
    document.getElementById('root')
);

And a very basic reducer:
import { NEXT_PAGE, PREVIOUS_PAGE } from '../constants/ActionTypes';

const initialState = [
  {
    title: 'Screen1',
    complete: 0,
  },
  {
    title: 'Screen2',
    complete: 0,
  },
  {
    title: 'Screen3',
    complete: 0,
  },
  {
    title: 'Screen4',
    complete: 0,
  },
  {
    title: 'Screen5',
    complete: 0,
  },
];

export default function PageChecker(state = initialState, action) {
  switch (action.type) {
    case NEXT_PAGE:

    //somehow check page is complete and move to next page

    default:
      return state;
  }
}

how can I use my NEXT_PAGE action to navigate through my app?
Comment: Have you tried to use a thunk and call the history from there ? You should achieve this with a `hsitory.push(nextPage)`
Answer: You can do something like like async action, but you have to have redux-thunk middleare https://github.com/gaearon/redux-thunk attached.
Here's example code:
export default function PageChecker(state = initialState, action) {
  return (dispatch, getState) => {
    switch (action.type) {
      case NEXT_PAGE:

        dispatch(go(`/page/${action.page + 1}`))

        return state;
      break;
      default:
        return state;
    }
  }
}


Servidor TCP + Servidor Web na mesma aplicação

Question: Seguinte pessoal, estou com algumas ideias de um projeto e estou com algumas dúvidas ...
1ª É possivel criar um Servidor TCP que vai tratar a conexão com o Cliente junto com um Web Server usando express que vai ter funções como start, stop e restart do servidor tcp?
2ª Se for possivel, eu devo fazer isso? Seria uma boa ideia colocar os dois na mesma aplicação ou é melhor separar as duas? (Levando em consideração que o servidor tcp ira ter muitos acessos)
3ª Existe uma estrutura ideal para as pastas e arquivos para um servidor tcp ? Posso aplicar o conceito MVC ? Se sim, a responsabilidade de criação do server tipo net.createServer() ficaria no controller ?
Obrigado,
Grande abraço.
Answer:
É possivel criar um Servidor TCP que vai tratar a conexão com o Cliente junto com um Web Server usando express que vai ter funções como start, stop e restart do servidor tcp?

Sim, é possível. Para tanto você precisa inicializar um listener TCP:
var net = require('net');

var server = net.createServer();
server.on('connection', handleConnection);

server.listen(9000, function() {
  console.log('server listening to %j', server.address());
});

function handleConnection(conn) {
  // [...]
}

(Exemplo parcial de https://blog.yld.io/2016/02/23/building-a-tcp-service-using-node-js/#.WTYTdWjythE )

2ª Se for possivel, eu devo fazer isso?

Vai depender exclusivamente da sua modelagem. Você pode estar querendo escrever uma solução compacta, onde listeners HTTP + TCP podem co-existir - ou um uma implementação separada por serviços.

3ª Existe uma estrutura ideal para as pastas e arquivos para um servidor tcp? Posso aplicar o conceito MVC?

De novo, a resposta depende da sua modelagem. Eu confesso que tenho uma certa dificuldade em visualizar um modelo de pastas para uma solução TCP, já que estamos falado de um stream. Se você está se referindo às classes, aí é um outro papo.
Quando ao modelo MVC, sim, existem vários módulos NodeJS que adotam este modelo. Já que net.createServer() tem a ver com manutenção de estado, eu diria que sim, a camada do controller seria uma boa candidata a host das funcionalidades de controle de conexão.


Preventing FlexiSlider (Adaptive) to resize beyond a certain minimum height

Question: I am using Flexi-Slider and AIS to create a responsive (full-width in this case) Images Slider for a front page on a Drupal 7 install.
I got it working perfectly but I would like to restrict the resizing function when the images reach a certain size. Meaning for example, if the height = 500px, even if the device screen size or resolution is smaller than that, or the user resizes the browser window, I don't want the image to get smaller than that.
Is that at all possible? Anyone has done it or could guide me into it? Thank you everyone for your time.
Answer: I hope my auto-reponses to the last 3 or 4 questions I posted, serve to the rest :)
Just wrap the block where your flexislider slide views is contained in a div and give it a min-width with !important and set the height to "auto".
Have not tested this in IE yet tho. Let's see.


How to combine MembershipReboot and Thinktecture.IdentityServer?

Question: I was able to download and run locally, the MembershipReboot project.  I was able to download and run on our test server the Thinktecture IdentityServer project.  No major issues with each one by themselves.  Now, I want to use MembershipReboot as part of my IdentityServer.  I downloaded the sample code and I think I see where code replaces code.  However, I'm blind as to what happens with the database.  Which database becomes the master?  Or do I run something to "upgrade" the IS database?  How about a tutorial or guide for dummies like me?  I'm given a six month project of building a SSO and asked to complete it in 5 days.
Comment: As a follow up, I was finally able to setup the MembershipReboot as the datastore for IdentityServer fairly easily, once I figured out how.  Now, I'm trying to figure out how to get all the goodness of the MembershipReboot login while still issuing a token via IdentityServer.
Answer: There are two databases with IdentityServer v2: One for the IdSrv configuration and another for the identity database (MR in your case). So in short, they are configured separately.
Comment: A bit closer to clear, still wrapping my head around this.  We're going from zero (old school form and query) to 60 in a week when we really need 6 weeks.  Plus, having to learn EF, plus...  If anyone has a guide for dummies with step by step that would be great.  Too bad ISv3 is just starting out since it has this integration out of the box.


How can I serve a separate CSS file for Internet Explorer?

Question: I am setting responsive design for only IE (Internet Explorer) in Drupal 7.
Is there any method or solution this file is working with only IE not for Firefox and Chrome?
Answer: You can either use drupal_add_css() with the optional browser type parameter, or go the easier route and use the Conditional Styles module which allows you to add CSS files via your themes info file. First lets use drupal_add_css() with the browser type. You should use this in themename_preprocess_html() (which goes in your themes template.php file) such as this:
<?php
function my_groovy_theme_preprocess_html(&$vars) {
  drupal_add_css(drupal_get_path('theme', 'my_groovy_theme') . '/lte-ie-8.css', array(
    'group' => CSS_THEME,
    'browsers' => array(
      'IE' => 'lte IE 8',
      '!IE' => FALSE
      ),
    'preprocess' => FALSE
  ));
}
?>

-Which is of course absurdly complicated just add a conditional CSS file, so I'm not even going to try and explain what all that actually means - you can just play around with the important bit (see the next code snippet) - the first line is declaring the conditional statement - here this is targeting IE8 or less. The second line you don't have to worry about, just don't change it.
'browsers' => array(
  'IE' => 'lte IE 8',
  '!IE' => FALSE
  ),

There is a much easier way to declare conditional stylesheets in Drupal - use the Conditional Styles module. This module allows you to declare conditional CSS in your themes info file, just as easily as the very first examples in this article. Just install the module and you can do stuff like this in your themes info file:
stylesheets-conditional[lte IE 8][all][] = lte-ie-8.css

So that's a basic round up of how to add CSS to your Drupal projects - I hope this helps you get started with Drupal theming a bit easier. If you are building a module please think twice about adding CSS for it - more often than not module CSS is not required, unless you are building something like Toolbar or Overlay which really demands it. Just let the theme layer handle the style - adding module CSS can often make the themers life that much harder.
Answer: Use drupal_add_css with the option 'browsers'.
drupal_add_css(
  path_to_theme() . '/ie.css',
  array(
    'browsers' => array(
      'IE' => 'lte IE 9',
      '!IE' => FALSE
    )
  )
);

You should add this function call in your theme's template.php file through template_preprocess_html like this:
function MYTHEME_preprocess_html(&$vars){
  drupal_add_css(
      path_to_theme() . '/css/ie.css',
      array(
        'browsers' => array(
          'IE' => 'lte IE 9',
          '!IE' => FALSE
        )
      )
    );
}

Comment: where is define this function i mean in which file
Answer: If you are looking to add the css from a theme and not module, using conditional stylesheets directly in your theme's .info file may be preferable to the drupal_add_css answer mentioned.
Comment: ; Set the conditional stylesheets that are processed by IE.
stylesheets-conditional[IE][all][] = css/responsive_ie.css  Add this file in info file but they cannot load
Answer: If you are using Zen as your base theme, the conditional stylesheets module should already be included.  If not you should download that module.
After downloading and enabling it, it will automatically add the markup in your html.tpl.php file for the ie stylesheets.  Be careful, ie only supports this until ie9.  ie10+ will need their own stylesheet(s) to work with some css hacks.
Here is a similar post I made a few weeks ago about my issue with it: Need help defining IE specific stylesheet with Zen Starter-kit and Conditional Stylesheet Module
In order to style for ie10 and above, you can currently use an odd media-query target found here: http://www.limecanvas.com/css-hacks-targeting-ie-10/
Comment: i am using bootstrap theme i am applying conditional stylesheets but they cannot work


Can't compile WebKit .NET 0.5 in VS 2010

Question: I'm trying to compile WebKit .NET 0.5 in VS 2010 Professional but I'm getting the error:

"Could not load file or assembly
  'C:\Users\Juan
  Luis\Desktop\WebKit.NET-0.5-src\bin\Debug\WebKitBrowser.dll'
  or one of its dependencies. The system
  cannot find the file specified."

I tried removing the WebKitBrowserTest project from the solution but now I'm getting

"The type or namespace name 'WebView'
  could not be found"

errors everywhere. Any idea what am I doing wrong?
Answer: replace the .dll in the projects debug folder with the original .dll's. When VS make a copy of the .dll's, it does something wrong, replacing them should fix the problem.
Answer: Try to copy '\WebKit.NET-0.5-src\bin' to your 'bin' folder.
Answer: With me, I can't build whole solution, but it runs when I select WebKitBrowserTest as StartUp project, then Ctrl + F5 (Visual Studio would ask me for rebuild JSCore, just click Yes).
If you see an error like "Retrieving the COM class factory for component with CLSID...",this link can help http://dotnetgenetics.blogspot.com/2013/06/retrieving-com-class-factory-for.html


How do I push a NuGet package from Appveyor build only if all builds in matrix are successful?

Question: I have a library with source code hosted on GitHub and configured to build on Appveyor CI (e.g. https://github.com/vostok/temp-library/blob/master/appveyor.yml).
I'd like to build and test this library on different platforms:

.NET Framework on Windows
.NET Core on Windows
.NET Core on Ubuntu

Naturally, I would configure a build matrix to build on different platforms. But then, I'd like to build and push a NuGet package only if all builds on all platforms were successful.
How do I configure something like this on Appveyor?
Comment: Each job in this matrix produces it's own artifacts. Which artifacts you plan to publish to Nuget?
Comment: I'd like to run tests on Ubuntu and Windows, and build a package on Windows only if tests on all platforms were successful.
Answer: To run tests on Ubuntu and Windows, you also need to build before. So what you need to do is to make Windows job to wait for others (I am not sure which Windows job, as you have 2 of them but I believe you know).
So to make one matrix job wait for others, you need to do some scripting. Please use this sample as a reference.
write-host "Waiting for other jobs to complete"

$headers = @{
  "Authorization" = "Bearer $env:ApiKey"
  "Content-type" = "application/json"
}

[datetime]$stop = ([datetime]::Now).AddMinutes($env:TimeOutMins)
[bool]$success = $false

while(!$success -and ([datetime]::Now) -lt $stop) {
    $project = Invoke-RestMethod -Uri "https://ci.appveyor.com/api/projects/$env:APPVEYOR_ACCOUNT_NAME/$env:APPVEYOR_PROJECT_SLUG" -Headers $headers -Method GET
    $success = $true
    $project.build.jobs | foreach-object {if (($_.jobId -ne $env:APPVEYOR_JOB_ID) -and ($_.status -ne "success")) {$success = $false}; $_.jobId; $_.status}
    if (!$success) {Start-sleep 5}
}

if (!$success) {throw "Test jobs were not finished in $env:TimeOutMins minutes"}

If you have more than one concurrent job, you can make it wait longer. If you have only one concurrent job, make it wait less (because with one concurrent job when last job started, others already finished one way or another)
To make this script and Nuget deployment run only in specific Windows job, specialize matrix job configuration
$env:ApiKey you get at https://ci.appveyor.com/api-token and store as secure variable.
Comment: If I recall correctly, Free, Basic and Pro plans all have a limit of 1 concurrent job. I don't need a Premium plan, because I'm okay with all builds in a matrix running consecutively. But this code seems to require a Premium subscription, because a sleeping job is still a job, and it will lock queued jobs indefinitely waiting for them.


Can't typecast 'void*' to 'double*' nor 'float*' using C language

Question: Sorry if this question already have a solution over there somewhere, but all answers of similar questions I found wasn't helping me.
void imprimePilhaDouble (void *vetor, int tam)
{
    int i;
    double *vetorDouble;

    vetorDouble = (double*) vetor;

    for (i = 0; i < tam; ++i)
    {
        printf("%e\t", *((double*) vetorDouble[i]));
    }
    printf("\n");
}

void imprimePilhaFloat (void *vetor, int tam)
{
    int i;
    float *vetorFloat;

    vetorFloat = (float*) vetor;

    for (i = 0; i < tam; ++i)
    {
        printf("%f\t", *((float*) vetorFloat[i]));
    }
    printf("\n");
}

The code above is returning these errors when compiled:
In function 'imprimePilhaDouble'
erro: cannot convert to a pointer type
In function 'imprimePilhaFloat'
erro: cannot convert to a pointer type

For the lines printf("%e\t", *((double*) vetorDouble[i])); and printf("%f\t", *((float*) vetorFloat[i])); respectively.
Is there any way to stop those errors? I made another similar function that seems to work right:
void imprimePilhaInteiro (void *vetor, int tam)
{
    int i, *vetorInt;

    vetorInt = (int*) vetor;

    for (i = 0; i < tam; ++i)
    {
        printf("%d\t", *((int*) vetorInt[i]));
    }
    printf("\n");
}

Comment: It looks okay.  Did you transcribe it here correctly?  Which compiler?
Comment: `vetorDouble[i]` is a `double`, so you're casting a `double` to a `double*`...
Answer: The problem is that this line:
printf("%e\t", *((double*) vetorDouble[i]));

tries to cast a double to a double *.  You can't cast a floating point value to a pointer, thus you get the error you report.  The same thing happens with your float function.
When you cast an int to an int *, that doesn't cause an error, but is pretty much nonsense.
What are you trying to do?
Answer: vetor is a (void *).
vetorDouble is casted to (double *)
vectorDouble[i] is in fact *(vetorDouble + i), i.e. what is pointed to by the base address vetorDouble with an offset of (i) * size of (double), because vetorDouble is of type (* double).
So, vetorDouble[i] is *(vectorSouble+i).
It is already a double. You don't need to cast it to a (double*) again, and the compiler is right when it tells you you can't convert a double to a (double*): it has no meaning.
So, you must write:
void imprimePilhaDouble (void *vetor, int tam)
{
    double *vetorDouble = (double*) vetor;

    for (i = 0; i < tam; ++i)
    {
        printf("%e\t", vetorDouble[i]);
    }
    printf("\n");
}

You can even write (because, readingthe name of your function, it await a double):
void imprimePilhaDouble (double *vetorDouble, int tam)
{
    for (i = 0; i < tam; ++i)
        printf("%e\t", vetorDouble[i]);

    printf("\n");
}


Simulate keydown in React aplication from contentscript

Question: I'm developing tiny bot for pinterest and noticed that pinterest uses React. And I have issue with message sending. I can enter message text to <textarea> and can simulate input event (to update React state), but can't simulate keydown event (with code 13) to send message. React just ignores my tries.
let textarea = $(".reactConversationsContainer .reactNewMessageInput");
let node = textarea[0];

let event = document.createEvent('UIEvents');
event.initEvent('focus', false, false);
node.dispatchEvent(event);

event = new KeyboardEvent('keydown', {
   code: "13",
   keyCode: 13,
   charCode: 13,
   key: 13,
   which: 13
});
node.dispatchEvent(event);

I will be grateful for any information on the topic
Answer: Okay, I solved this myself.
Firs of all, this library works fine for me: simulate.js. You can extract code that you need, lib is pretty simple.
Notice, that contentscripts can't fire page handlers, because it isolated from page (see this question) and you need to inject script, that will trigger event (this also described in link above).


How to find all positive integer solutions of a Diophantine equation?

Question: Here is the equation
$$
    6a+9b+20c=16
$$
To solve this, i follow the below steps :
$\gcd(6,9)(2a+3b)+20c = 16$
let, $w = 2a+3b$
So, $3w+20c =16$
then, specific solution of $w = 112+20n$, $c = -16-3n$ ; where $n \in \mathbb{Z}$.
After that,
$w = 2a+3b$
So, $2a+3b = 112+20n$, I need to solve this equ. To find the solution of $a$ and $b$.
Finally I got,
$$
A = -(112+20n)+3m \\
B = 112+20n-2m \\
C = -16-3n
$$
I tried to do above by Euclidean algorithm.
Now, my question is, is it ok or the solving is right?
and how do i got the positive ans for $a,b,c$ ?
If there's any wrong in solving process , please explain me that.
Comment: I didn't read your solution but it came to me that since the coefficient of $c$ is 20,  a, b, c, can not all be positive. If they were all positive integers, $a, b, c\geq 1$ which means, $6a+9b+20c \geq 35>20$.
Comment: See [here](http://math.stackexchange.com/questions/1429727/find-all-the-solutions-of-6a9b20c-2?rq=1) for a solution (replace $16$ by $-2$).
Comment: @zxcvber The OP asked "how do i got the positive ans", which I think means "how can I get the solutions, in case the answer to solvability is positive". So we may be looking at integer solutions.
Comment: I have no better idea than to determine the solution over $\mathbb{Z}^3$ and then restricting to $(a,b,c) > 0$.
Comment: Have you inserted your solution into the original equation to verify it?
Comment: COMMENT.-It is clear that there are not positive solutions because $6\cdot1+9\cdot1+20\cdot1=35\gt16$ You can verify this another way taking the parametrics given by the identity $$6(-3s-10t-4)+9(2s)+20(3t+2)=16$$
Answer: Consider $6a + 9b + 20c = 16$ as the equation of a plane, in $a,b,c$.
Once that you know three points in it, with integer coordinates, ${\bf v}_{\bf 0},{\bf v}_{\bf 1},{\bf v}_{\bf 2} $, from ${\bf v}_{\bf 1}-{\bf v}_{\bf 0}$ and ${\bf v}_{\bf 2}-{\bf v}_{\bf 0}$ you can determine two vectors ${\bf u}_{\bf 1},{\bf u}_{\bf 2} $ having components with $gcd=1$.
Then all the solutions will be given by
$$
{\bf v} = {\bf v}_{\bf 0}  + n\,{\bf u}_{\bf 1}  + m\,{\bf u}_2 \quad \left| {\;{\rm integers}\;n,m} \right.
$$
The ${\bf u}$ vectors can be more easily determined considering the parallel plane through the origin (the "homogeneous" solution).
Therefore consider
$$
6a + 9b + 20c = 0
$$
here ${\bf v}_0  = \left( {0,0,0} \right)$ and ${\bf u}_{\bf 1}  = \left( {3, - 2,0} \right)\quad {\bf u}_{\bf 2}  = \left( {10,0, - 3} \right)$ follow immediately by putting one of the variables at zero.
Then we can easily find a "particular" solution by putting, e.g., $b=0$ and achieving
$$
6a + 9b + 20c = 16\quad  \to \quad 6a + 0 + 20c = 16\quad  \to \quad 3a + 0 + 10c = 8\quad \to \quad {\bf v}_{\bf p}  = \left( {6,0, - 1} \right)
$$
The solution is therefore
${\bf v} = {\bf v}_{\bf p}  + n\,{\bf u}_{\bf 1}  + m\,{\bf u}_2\quad$ that is: $\quad
\left\{ \matrix{
  a = 6 + 3n + 10m \hfill \cr
  b =  - 2n \hfill \cr
  c =  - 1 - 3m \hfill \cr}  \right.$
In fact: $\quad16 = 6a + 9b + 20c = 16 + 0n + 0m$


Cox proportional hazards model formulation with two correlated covariates

Question: I want to set up a Cox proportional hazards model with two correlated covariates $x$ and $y$.
The two covariates are defined as this in R:
x <- rexp(n)
y <- 2x + rnorm(n)

Does the hazard function look like this:
$h(t|x) = h_0(t)\times e^{\beta_1x+\beta_2y}$ or $h(t|x) = h_0(t)\times e^{\beta_1x+\beta_2y+\beta_1\beta_2xy}$?
Answer: This depends on how you want to model survival: with x and y independently associated with outcome (although they are correlated) or if you want their product (interaction) also to be associated with outcome. In other words: do you want the effect of x on outcome to depend on the value of y (and vice-versa) or not?
For the simple no-interaction situation, your first formula is correct.
An interaction would most generally be modeled as
$$h(t|x) = h_0(t)\times e^{\beta_1x+\beta_2y+\beta_3 xy}.$$
If you are simulating data and want to define $\beta_3=\beta_1 \beta_2$ exactly, your second formula would be OK. If you are fitting a model with an interaction to data, then the above form is what is assumed: $\beta_3$ is modeled separately from either of $\beta_1$ or $\beta_2$.


AWS API Gateway Slowness

Question: This has me perturbed. I have a basic API gateway that is supposed to be capped at 10,000 requests per second with 5,000 request bursts. However, when hooked up to Lambdas, best I can hit currently is ~70 requests / second.
The end-points I have are basic Lambda proxies created with Serverless framework (HTTP EDGE).
I know that the lambda itself is not the bottleneck as I have the same issue when I replace the lambda with an empty function. I have 100+ allocated concurrency for the lambda, but the lambda never appears to hit the limit.
functions:
  loadtest:
    handler: loadtest/index.handler
    reservedConcurrency: 200
    events:
      - http: POST load_test

I'm wondering if there's something that I am overlooking here. My test runs for a minute and attempts to hit 200 req / sec (works fine with other so it's not my bandwidth). The delays grow to be as much as 20-30s at some point, so clearly something is choking up.
If it's a warm up issue - how long am I expected to run such load until everything is running warm?
Any ideas on where to look or additional information that I could share?
[Edit] I am using node12.x and I even tried with this code:
const AWS = require('aws-sdk');

AWS.config.update({region: '<my-region>'});

var sqs = new AWS.SQS({apiVersion: '2012-11-05'});

exports.handler = async (event, context) => {
  return {"status":"ok", ... }
};

The results were basically the same. I'm not sure where the bottle neck is, to be honest. I can try further testing with concurrency on the lambda side, but going from 100 to 200 had no effect - the completed requests clocks at around 70/s for an empty function.
Also, I'm using loadtest npm package to perform the loadtest and this is what the output looks like:
{ totalRequests: 8200,
  totalErrors: 0,
  totalTimeSeconds: 120.00341689999999,
  rps: 68,
  meanLatencyMs: 39080.6,
  maxLatencyMs: 78490,
  minLatencyMs: 427,
  percentiles: { '50': 38327, '90': 70684, '95': 74569, '99': 77679 },
  errorCodes: {},
  instanceIndex: 0 }

Here's a picture of how provisioned concurrency looked like over that period of time. I ran this over 2 minutes with the target at 200 req/sec.
Comment: Warm up time depends on your language of choice. But generally speaking warm up time is extremely quick. For my nodejs lambdas, it's about 300ms to warm up a cold function.
Comment: Can you provide more information about the language you're using, and an example of the code you're using for the function?
Comment: node12.x - added some info above. I'm fairly certain this is some sort of configuration issue somewhere because otherwise this makes little sense. :)
Comment: Is there any layer like CloudFront or such in between that could do per IP throttling. I didn't set anything up but I have not ran load tests of this level before.
Comment: I think api gateway might have throttling built in
Comment: They do but it's supposed to be at 10k requests per second. Thinking this is probably something else.
Comment: Well do I feel silly. I just ran the test on a MacBook and it ran with 200+ request / second no problem. It appears to be an issue with WSL2 and something related to networking - some posts suggest DNS issues. I'm still not sure why the other URL would run at a higher rate, but perhaps it returns faster and the results have to do with amount of concurrently open connections.
Answer: Appears that this is actually an issue with WSL2 and NodeJS. The exact nature of it is still unclear, but it is not an issue with the API gateway itself. I demonstrated this by running it on MacBook and everything worked fine and request counts were high.
There are posts suggesting that this is an issue with the Node HTTP client & DNS, so perhaps that's a good starting point, but the above question is moot.

AWS API Gateway Slowness


No module named 'sqlalchemy'

Question: There's an issue with from sqlalchemy.orm import relationship, when I try to run my app with that import, ModuleNotFoundError is raised and it says No module named 'sqlalchemy'.
But when I delete the from sqlalchemy.orm import relationship, I can run my app well with no issue whatsoever. Am I missing a module or something?
Other imports from sqlalchemy seems to run smoothly, e.g
from sqlalchemy import Column, Integer, String, Boolean, ForeignKey
I'm using SQLAlchemy-1.3.22 and I installed sqlalchemy by using the command pip3 install sqlalchemy
Here's my requirements.txt
APScheduler==3.6.3
certifi==2020.12.5
cffi==1.14.4
cryptography==3.2.1
decorator==4.4.2
mysqlclient==2.0.2
pycparser==2.20
PyMySQL==0.10.1
python-dotenv==0.15.0
python-telegram-bot==13.1
pytz==2020.4
six==1.15.0
SQLAlchemy==1.3.22
SQLAlchemy-ImageAttach==1.1.0
tornado==6.1
tzlocal==2.1
Wand==0.6.5

Comment: It's probably an issue with the way you've installed SQLAlchemy. Can you add your installation details here? Check if you are running your code in the same virtual environment where you installed it.
Comment: I tried reinstaling by doing pip3 uninstall sqlalchemy and pip3 install sqlalchemy, to no avail
Comment: Create a new file `foo.py` and insert the following: `import sys; print(sys.version)` --> what do you see when you run this?
Answer: Solved. I tried reinstalling the package and also rewrote my entire code. The import works now!

No module named 'sqlalchemy'


Tell git never to update a file

Question: I have a few files in git (namely configure files), that I need to be in the git repo, but I don't want them to ever update (for some reason, running them, and make, changes the configure file).
So is there any way I can tell git to ignore any CHANGES to the file, but to keep the original file still in the repo?  Currently the only way I've found out to do something like this is to add the file to the .gitignore file, and the git add the file to the project directly (using -f to override).  Is there any better way?
Answer: You could use git update-index --assume-unchanged on the file.

--assume-unchanged option can be used as a
  coarse file-level mechanism to ignore
  uncommitted changes in tracked files
  (akin to what .gitignore does for
  untracked files). You should remember
  that an explicit git add operation
  will still cause the file to be
  refreshed from the working tree. Git
  will fail (gracefully) in case it
  needs to modify this file in the index
  e.g. when merging in a commit; thus,
  in case the assumed-untracked file is
  changed upstream, you will need to
  handle the situation manually.
Comment: That seem to have worked for me.  Although it seems like this will not be sent to the larger repo when I do a git push.  Is this correct?
Comment: _[Leif Andersen](http://stackoverflow.com/users/288439/leif-andersen)_: You are right.
Comment: This is dangerous as your local file may in some cases be overwritten/updated with data from origin. See discussion at https://stackoverflow.com/questions/13630849/git-difference-between-assume-unchanged-and-skip-worktree
Answer: I wouldn't manage those files with git at all. I'd put them in your .gitignore so git would ignore them, and put template files (such as foo.template for a file named foo, or maybe template/foo) into git. Then when you clone the repo, you can copy them out, and modify them, and git won't do anything with the copies, while still managing the templates. If you have several such files, you can supply a script or make rule or something of the sort to populate all of your config files from their templates, to make it easier to get set up.
A better design would be to separate project config from local config, or have project level defaults that can be overridden in a separate local file. The project level files get committed, the local files get ignored, and they are both used. Perhaps some config settings only make sense for the project and some only make sense locally, in which case you just pull the appropriate setting from the appropriate file; or you could use the project setting as defaults, and let the local config override the defaults. This way, you can update the project settings, which are shared, for everyone at once, while not interfering with people's local settings. Of course, this depends on having control of the settings format; if you're using a third-party tool that takes its settings in a particular format, all mixed into one file, you'll probably have to use the template approach.
Comment: Committing `.sample` files is what we typically do too; but be careful about people using outdated copies. We've also cheated by committing the file to the repo and **then** adding it to `.gitignore` -- though I would only do this in a pinch.
Comment: @Uriah Yeah, you do have to be careful about outdated copies, but you need to be careful about that in any system in which you have config files that are supposed to be locally modified but are complex enough to need version controlled templates. I'll add a note about a better design to my answer as well, though it's one that may not be available depending on whether they control the config file format.

Tell git never to update a file


Sign up with no price

Question: What we need is essentially a free product order. We need viewers to be able to sign up for free classes where there is a limit on the number of students. The registration requirement and the inventory limit indicate that it should be a shopping cart function, but the module that allows for free orders is only available in a Drupal 6 module. Is there such a function for Drupal 7?
Answer: Ubercart for D7 has a built in free order payment method so the UC Free Order module isn't needed here. You can configure the conditions under which the payment method is available under the payment method configuration page (Store > Configuration > Payment method).
If you need to limit available purchases, the included UC stock module enables restricting products to a limited quantity of available purchases.
Comment: This answer was very helpful, but it feels disconnected to my assumption that the condition of "free" would be attached to the specific art classes in question. That assumption is based on my client's situation where specific classes are free to all comers within the class size available, as opposed to meeting some conditions of buying other products. With the method you describe, can free be attached to a class type product?
Comment: The way the questions is titled/worded made it sound like it was only concerned with free products. I added a line about the UC stock module. That should enable limited purchases that you need for registration.
Comment: It looks like I've been unclear yet again. The question is can a product, in the form of a class, be set to be free for all members or non-members. I have the Free Order Payment Method set, but that is a "free order." What I really need is a "free product." Or, maybe this is as simple as leaving the price at 0?

Sign up with no price


Solving feature bias issues in Learning to Rank with implicit feedback

Question: I have a learning to rank system where implicit feedback (from user clicks) is used to determine +ve and -ve examples for the training. The problem is that (obviously) the learner sees only the top few ranked results (+ve or more relevant examples will appear at the beginning). This introduces some kind of a bias in the learning problem.
Is there a way to solve this?
Answer: It's problematic that you're not getting full support.
One way to solve this is to produce:

A model to decide whether or not results are shown - $P(shown)$, and then
Another model, $P(relevant|shown)$.

Then $P(relevant)=P(relevant|shown)P(shown)$.
Of course, as your model drifts over time, it can be tough to maintain.  But you might be able to maintain a time-based $P(shown|time)$ model, where each time you update your model you keep the old model and maintain a link to the training data used to generate it.


Cross Dominance - does it effect piano playing ability?

Question: I am quite cross-dominant - in some areas more than others. For instance, I consider myself right-handed, I write right-handed, I'd kick a football with my right-foot, but I play snooker/pool left handed and I'm more dexterous (sinistrous?) at some things with my left-hand. (e.g., I can twirl a stick much better left handed than right handed, but if I need to do precise motor movements I'd use my right hand). For things like sweeping or digging, I'm equally comfortable with either hand.
When playing piano and trying to relax and play fluently, one of my most common errors is that my left hand starts to play right-hand parts, or vice versa. I'm sure there is an element of this for all piano players, what with trying to do two things somewhat independently at the same time, but do any other cross-dominant players suffer especially from this? And what do you do about it? (if anything other than practice, practice, practice!)
Comment: What counts as cross-dominant? I'm right-handed, but I shoot right instead of left, and I unscrew jars with my left hand (because my right hand is too busy holding the jar down). I also tend to flip pages with my left hand. (My trills and tremolos are faster in my right hand, though.)
Comment: Is your left hand playing the right-hand music? Or does it just start to play, for instance, the *rhythms* of the right-hand music?
Comment: Most often it's notes in the wrong octave (e.g., I play the RH notes in the LH octave). Some pieces I find particularly difficult to 'de-sync' to the extent that (for instance) I concentrate hard on correcting the mistake in my LH only to find I then play the RH incorrectly...it is very annoying....and persists even when I slow right down
Comment: Practice, practice, practice.  That's all there is to it.
Answer: Sounds like your situation is somewhat like ambidextrousness.
You should practice each hands' part individually, if you have not done so already. When practicing together, focus on one hand (the hand that has harder music). You shouldn't play the same thing in both hands if you focus on one.
Comment: I don't know anything about ambidextrousness so I can't contribute a full answer, but it seems to me that focusing on only one hand might actually cause the problem of the two hands "joining". Removing focus from one hand makes it a prime candidate to join the one you concentrate on. Instead I would recommend focusing on how the hands combine (which notes are together, which intervals do they create). When one hand forgets its own part and joins the other hand, the relation between the two hands is lost, so if you focus on this relation, both hands have to contribute.
Answer: I am cross dominant, and I suspect one of the most fortunate kinds for playing piano. I write and eat with my left hand and do almost everything else right-handed, though I'm often comfortable using my left hand if necessary for things like throwing or punching, but not for very intricate and ingrained things like guitar. I started playing piano three years ago aged 31 and within a few weeks was playing music that may take the average learner a few years, and although I would say I am gifted with an ear for music, I feel like my cross dominance has been a huge asset from the very beginning. I have achieved in three years what others take ten years or longer on the instrument all without the aid of formal training or tuition. Both my hands are very often able to perform independent of one another and I find I can even swap hands easily. I learnt how to improvise twelve bar blues in just a couple weeks, to a very high standard and I pick up new techniques all the time that I don't even know the names for (in fact I could still not tell you barely any of what it is I'm able to play). I think there are several things that have compounded to make me a natural pianist and composer/music producer, and I feel like being cross dominant is certainly one of them.
Answer: This has been an issue for me with learning musical instruments for most of my life. I have always been better at wind instruments, which only required one active hand at a time. I could never play piano without my hands 'fighting' over the melody.
Finally, however - and at 35 years old, I managed to work it out. It was on the accordion of all things. I can't tell you a specific exercise I did, other than constantly forcing the fingers on one hand to play a different rhythm than the fingers on the other, even when not actively practicing.
I have no certain idea of what happened neurologically. My best guess is the practice eventually engaged the right synapses. But I can tell you I was losing hope, and one day it just clicked.
My best advice is not to practice each part separately so much as very slowly with carefully monitored tempo. It's all about the timing.
Answer: You ability will get better with practice. As Piano players, I am sure we all have had such experiences at some point in our musical journey. Struggling is normal. It doesn't matter which hand one uses to engage in his/her day to day activities. Playing piano depends mostly on for how long you practice.


Reading JSON Object from @RequestHeader

Question: I am recieving a JSON object which is comes to me as a String from the front end and I want spring-boot to parse it into a Map for me.
I've tried @RequestHeader("header-name") Map header and @RequestHeader Map header but both give me a map of all the headers instead of the one I'm target which contains the JSON.
public ResponseEntity<MyObject> getStuff(@RequestHeader("My-Header") Map myHeaderJSON)

I expect the variable myHeaderJSON string to be parsed into a Map by Spring. Is there any way to achieve this? To have spring-boot parse a String into a JSON or Map for me?
Answer: if you want a single http request header to be "injected" into your controller method (as an argument) by Spring try it this way:
@RequestMapping("/your-path")
public ResponseEntity<MyObject> getStuff(@RequestHeader("My-Header") String jsonValue) {
   //...
}

also see here: https://www.viralpatel.net/spring-requestheader-example/
you can also try to implement a custom converter, see here for an example:
https://stackoverflow.com/a/50996349/150623
the way to go would be to use an ObjectMapper instance from the Jackson lib to convert the JSON string to a java.util.Map object...
could work this way (not tested though):
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

@Component
public class JsonToMapConverter implements Converter<String, Map<String,String>> {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public Map<String, String> convert(final String json) {
        try {
           return objectMapper.readValue(json, Map.class);
        } catch (IOException e) {
           //handle exception...
        }
    }
}

don't forget to add Jackson to your dependencies, e.g. in Maven:
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version>
</dependency>

Comment: Any way to avoid using String and go straight to a Map?
Answer: No, you will need to de-serialise it yourself.
From the spring docs:

If the method parameter is Map<String, String>, MultiValueMap<String, String>, or HttpHeaders then the map is populated with all header names and values.

It will not extract and deserialise json from the map, instead you will need to do something like:
public ResponseEntity<MyObject> getStuff(@RequestHeader Map myHeader) {
    String json = myHeader.get("My-Header");
    MyClass myClass = objectMapper.readValue(json, MyClass.class);

    ...
}

Comment: Thank you. I ended up doing it like this!

Reading JSON Object from @RequestHeader


What does one need to know to learn to improvise with other musicians?

Question: I came across the following video on YouTube in which two random people play the same piano together and to me it sounds really amazing. It's something that I couldn't do myself if someone started randomly playing together with me.
Video:

How do people do people do this? What would one need to know to improvise with a complete stranger that is already playing the piano?
Comment: Also, maybe to give a bit of context: this is in France and pianist #1 is playing variations around a theme by ludovico Einaudi that was in the ost of a movie which has a real huge success there (Intouchables). Just to say that because of that, the theme is known by most people, or was, a few years ago, which also helps to build a improvisation.
Comment: One important point: There are many different improvisatory genres, and they operate in different ways. This example is tonal and follows a repeating progression of chord "changes." Even if Pianist #2 didn't already know the song, he could have picked up on this pattern after listening for a bit, and then it becomes a question of how one improvises over a chord progression. Free improvisation would be another matter, as would other genres like jazz, "jam" rock, or Indian classical music.
Comment: This question is incredibly broad, and very few people have the skill to improvise with *any* stranger playing *anything* on the piano.  I only watched the very beginning, and I do notice a few things that the first pianist does (for example playing in a C pentatonic scale) that make it easier for others to join in.
Comment: I've watched bits of this video and it seems like it's IV V vi, repeated over and over. Once both pianists come to this understanding, it's not too hard to improvise over this. It reminds me of a lot of anime songs, since the royal road progression uses IV V III vi.
Comment: -- oh that's a typo, I meant it reminds me of IV V iii vi. Though, III works too. They're the V chord of the minor key.
Answer: Not knowing your particular background or skill level the question is incredibly broad. From the point of view of an experienced improviser what's going on here is fundamentally very simple.
Pianist 1 is playing around in A minor. If you don't have the ability to recognise a pitch from memory (perfect pitch, I don't have it and it's a very rare ability) then it will take some little initial guess, or watching the pianists fingers for the notes they are using, to determine the key. A bit of aural skill helps here, as in after a few seconds listening you hear they are going to a home chord of some kind of minor tonic. Pianist 2 looks at pianist 1's hands and see's there are no flats or sharps used, so it must be in C or A minor (or some mode, but that would sound 'different' and is less likely to be the case in the majority of simple jams like this). Next up he determines it sounds minor, so it's probably A minor. Although this is easy to determine with a bit of practice, especially when you are hearing someone play diatonically, if there was any doubt in pianist 2's mind that it was an a minor tonic and not another minor chord from our diatonic list of chords a quick peek at pianist 1's hands and what keys he is playing would answer any question right away, it all looks familiar, uses all the white notes and ends on an A minor, it's in A minor.
Pianist 1 is playing two chords to reach the final one. Given that we are probably in the key of A minor (down to seeing the lack of black keys pianist 1 is playing) now a bit of ear training will quickly tell you that the approaching chords are from the same key as the home chord, and a bit of knowledge of chord theory will tell you that the chords that reside under the tonic of A minor, stepwise, are F major and G major. This sounds a little abstract, but as almost all music obeys, to some degree, the patterns found in the diatonic major/minor scale remembering the order of chords (and how they sound) becomes second nature, as you have to recall it so often.
So we are left with pianist 2 having identified pianist 1 is in A minor, and playing the two chords below it to lead up to the tonic.
Although I don't have perfect pitch and couldn't accurately guess that it was in A minor without looking at the video or grabbing an instrument it's very easy to hear that we are going 'IV V vi' in some key. This may be familier to you, but if not you just need to look into 'chords in a major scale' and 'relative minors', then spend a bit of time playing around until you start to hear the relationships and recognise the movements we have here. In time you can listen to a chord sequence and make a pretty good guess at what's going on before even playing a note.
After that, it's simply 'variations on a theme'. The two pianists are now feeding off each other and reacting to the confidence built each time the chord sequence is completed in such a way that they are able to experiment a little, confident that they can predict the next chord based on the repetition. Then you can just try out different techniques. Pianist 2 is accompanying, broadly, and varies the way he plays the chords with arpeggios, a bit of stride playing and some melodic playing. Pianist 1 is then free to worry less about the chord accompaniment and focus' on melodic playing around the A minor scale. He plays it safe, sticking mainly to minor pentatonic playing with the odd passing note, following the basic rules of beginner improvising ie. stick to strong chord tones, resolve nicely each time the sequence ends etc. Playing it safe is absolutely fine in this kind of impromptu jam.
Developing your own feel for how to improvise a melody is something with no strict rules, it's on-the-spot composing in some way, but with a bit of practice you can find some ways that make your ideas sound more lyrical, and more musical. Very broadly these can be;
Don't start on the 1 of each chord all the time.
Don't start on beat one of each chord all the time.
Try and construct short phrases, like sentences, that have a beggining, middle and end.
Repeat ideas to build up a sense of some kind of intent,
develop a phrase once it's established.
These are a very simple starting points, I could carry on writing arbitrary ideas like this for days, and in the video the musicians don't follow even points 1 and 2 of these very much at all. They make up for it by following points 3 and 4 quite nicely, and after all this is a jam at a train station between strangers, not a composed piece! It's a form of very simple improvisation demonstrated very well in an odd, impromptu setting. I don't mean to sound derogatory to the musicians, it really is a good example of how you can get something basic going between two stranger-musicians with no forward planning.
I would suggest just playing the chords, F  G  Am  Am (as they are here) in your left hand and just noodle in the right hand on the white keys and you'll get something similar. Once you have gotten used to that you can explore how to embellish it in ANY direction, from additional notes, chord extensions, different keys, different techniques etc. The biggest thing to learn will be the sound of each note choice on each chord, get used to how some sound simple or sombre, some sound exciting, some sound floaty, some sound beautiful. Build up a dictionary of what intervals sound like to you. After that it's phrasing of melodies in the right hand. Once you are satisfied with that stuff and want more then you just add ever more complex chord sequences, new sounds and techniques until you get to jazz and beyond!
Answer: Accompanists tend to mainly think in terms of chord sequences rather than individual notes. Guitar of course is primarily used today as an accompanying instrument, but piano was and is also regularly used. This is the core skill required for playing with other people and for improvising.
Experienced players can identify the chords played by looking at a player's fingers, but also from a root chord can identify other chords by ear based on their interval from the root. Some sequences like "F G Am" or "C G Am F" are very common (the Axis of Awesome videos on YouTube demonstrate a lot of these), and experienced players will be highly familiar with them and already know riffs which work within those structures.
After that, we're into generally how to improvise. The most popular way is to start with the pentatonic scale, because the scale doesn't form unpleasant dissonances for any intervals. Add on tricks like octaves, arpeggios, and runs from regular scales. (This is why you practise scales and arpeggios, so that you can pull them out when you need them.) Then go your own way with different voicings of chords, passing notes, and so on.
Improvising is a skill which needs practise. It's largely ignored by the classical world, in a traditional (and in many people's opinion mistaken) view that you shouldn't be improvising until you reach higher grades. Of course the end result is that many classically trained people at higher grades simply forget that it's allowed to play music that isn't on the dots, or find that it's so hard to go back to sounding like a beginner that they don't want to.
Comment: +1. Improvising should be parallel to learning from the dots in every practice session - from the start.
Answer: I'm not a piano player, but a hobby guitarist (classical trained as an adolescent + e-guitar in later life). Since I started out purely classical for many years, especially during my "formative" years, I was playing 100% from musical notes. When I transitioned myself to more contemporary playing styles, I found that I can easily learn the scales and was able to play solo improvisation - but only if someone told me which scales are the correct ones, and then it also usually sounded quite boring; and was more stressful than enjoyable to me.
Some ways which worked to improve this for me, which might be applicable in general:

Learn some music theory. It does not need to be full-scale jazz-level theory, but at least a little bit; figure out how and why the usual scales and chord progressions work. Really, at least for your run-of-the-mill blues it's not a lot to learn, and not particularly hard either.
Learn exceptions to the music theory. For example, in the guitar world, there is a standard pattern for the beginner-level pentatonic scale. Turns out that there are many notes not on that scale that work very well to create and release tension, especially if used as a small sliding or bending motion instead of a full-blown note. One can easily experiment with these things alone and build a repetoire of interesting variations.
Learn "licks" - on the guitar, these are a few notes or finger movements strung together; not a long phrase, just a tiny little figure. Basically just a little trick or cheat that sounds good, and gives you kind of an anchor point if you run out of ideas while playing. If you listen to a lot of solos, you notice some familiar bits all over the place. I assume the same exists in the piano world, not sure how you call it though.
Sing along, wordlessly. Don't only play scales or chords without any intention, but try to get some actual melodies together. Can be humming or just "thinking" as well if singing is not your thing. (Unrelated to improvisation, a famous example is one of the recordings of the Goldberg Variations by Glenn Gould, were you hear his humming frequently on the record).
Play excessively slow. Play so slow that you can think about every next note before playing it. Try to imagine how it will sound before you play it. This is the same as learning anything on an instrument - starting too slow is usually better than too fast. Eventually, the "decisions" will move to your fingers instead of your brain and you'll automatically speed up.
Listen to and play a lot of music in styles that are open to improv. Rock, Blues, Jazz etc. - maybe find iconic players you like and try to play along. Eventually, your fingers will have so much material to draw from even without conscious thought that to an uninitiated it may sound like you're a gifted improvisationer, while in fact you're mostly stringing phrases together... and if it then turns out that you hear someone play exactly that song in a train station, you can also just play along.
Comment: The "sing along" tip is very good. Singing improvisation is usually much easier than doing it on an instrument. Mimicing a saxophone solo with your voice, for example. When you understand your instrument as well as your voice, improvising on the instrument will become second nature, like humming a melody.
Answer: What does one need to know? Quite a bit - which is why the 2nd pianist managed a heck of a lot more than the 1st !
I don't doubt that if p2 had changed key, p1 couldn't have followed. P2 was watching and listening (not just looking and hearing) what was being played. He worked out, both by ear and by eye, what the basic chord sequence was. From that, he could play along, even in a rudimentary fashion. For that, he knew where the notes were for that key, what chords could be/were used, and what bass line and top notes would be likely to fit.
P1 knew that sequence, and pretty well kept to what he knew well. Only after several minutes did he feel he could experiment at the top end, and using mainly pentatonic notes - and certainly no black keys, given key A minor - did have a good try, probably feeling totally supported by p2.
So, being able to recognise chord patterns, being able to know which notes work best over certain chords, being able to map out the chord sequence being played, knowing which notes to avoid (very important), being aware of where they were in the bar and sequence, thus knowing which out of several available notes fitted best, having a sense of timing, to stay with, and complement the other player, and listening constantly, to accomodate any off-timings the other guy might make. Those are all skills which I need as part of open mic nights in a backing band, and all come into (and out to) play when someone just starts playing - exactly like what happened in the video. Best way to start doing this is to play along with the radio, or favourite tracks, starting with songs you have a clue about - key is paramount - which then gives the list of likely chords, which then gives the list of available 'safe' notes, and so on...
Answer: I will offer my advice, and use a lot less vowels and consonants.

Be fearless. Step up, step into it, and go for it. Whatever IT is. Whatever it is is a whole lot better than sitting back and wondering how it would be to jam and improvise with a stranger. What have you got to lose, after all?

Use whatever you have in your experiential tool kit, and don't be afraid to explore the edges. Only you and the other guy will know if you mess up. The audience certainly won't, trust me!

Play with joy, and play with complete and utter abandon.
The only way you will suck is if you hold back, become timid, and worry about what people might think.

That's all I have.
Have fun with it.
Comment: This *could* work, but chances are, with just playing random stuff - which is what you're advocating, it will sound like neither of you know what you're doing. There's a heck of a lot more needed - experience, knowledge, for starters. Been there, done it, and it works in < 5% of cases where neither knows what to do, or react to the other, or can listen well - and play well.
Comment: This is probably the most important advice of all


Disable USB Storage in General But Include Exceptions for Specific Devices

Question: There are several questions here about disabling USB storage in general via GPO but I can find no information on whether it is possible to add exceptions for specific devices. Put another way, can USB drive types that include builtin encryption be enabled but generic USB drives disabled?
This needs to work on Windows XP.
Answer: Checkpoint have a product that we use called Pointsec Protector. This does a whole load of policy enforcement for USB connections (and optionally CD/DVD too) which we use for our XP machines.
We use it to enforce that all company USB sticks are properly encrypted to a decent level (with decryption keys accessible by the helpdesk for when users forget their passwords). It also blocks all access to non-company approved USB devices and non-encrypted devices. All managed from a central server and console with a small client on every XP machine.


What is wrong with my proof that $\lim\limits_{n \to \infty} (n!)^{\frac{1}{n}} =1$?

Question: This question has been asked before but I did not understand the accepted answer and it was 8 years old so I did not want to comment on it.
I want to understand what is incorrect in my working of the following-
$$ \lim \limits_{n \to \infty} (n!)^{\frac{1}{n}}  =   \lim\limits_{n \to \infty}[n^{\frac{1}{n}}\cdot (n-1)^{\frac{1}{n}} \cdot (n-2)^{\frac{1}{n}} \cdot \ldots\cdot 1^{\frac{1}{n}}] \tag{1}$$
Now, the product rule of limits says, $$ \lim\limits_{x \to a}[f(x) \cdot g(x)]  = \lim\limits_{x \to a} f(x) \cdot \lim\limits_{x \to a} g(x)$$
Let $f(n) = n^{\frac{1}{n}}$, and the remaining be $g(n)$. Using this in $(1)$, I get-
$$\lim\limits_{n \to \infty}(n!)^{\frac{1}{n}}  = \lim\limits_{n \to \infty}n^{\frac{1}{n}} \cdot \lim\limits_{n \to \infty}[(n-1)^{\frac{1}{n}} \cdot (n-2)^{\frac{1}{n}} \cdot \ldots \cdot 1^{\frac{1}{n}}]$$
Repeating the step and continuously breaking the rightmost limit using product law of limits, I get-
$$\lim\limits_{n \to \infty}(n!)^{\frac{1}{n}}  = \lim\limits_{n \to \infty}n^{\frac{1}{n}} \cdot \lim\limits_{n \to \infty}(n-1)^{\frac{1}{n}} \cdot \lim\limits_{n \to \infty}(n-2)^{\frac{1}{n}} \cdot \ldots \cdot \lim\limits_{n \to \infty}1^{\frac{1}{n}}$$
Now, I know the limit of each of these individual terms is $1$. So, I write it as- $$\lim\limits_{n \to \infty}(n!)^{\frac{1}{n}}  = 1 \cdot 1 \cdot 1 \cdot \ldots \cdot 1  = 1$$
I know this answer is incorrect as the correct limit is $+\infty$, which can be seen through Stirling's Approximation, but I don't know what is incorrect in my working.
Comment: The product rule for limits holds only for a product of a (finite and) *fixed* number of factors.
Comment: You could apply the same line of reasoning to $\displaystyle (1+1/n)^n\color{red}{\to} \underbrace{1\cdot \ldots\cdot 1}_{n}=1$, which should really be $\ldots \to e$. As the above comments have noted, you cannot generally apply $\lim (a\cdot b)=\lim a\cdot \lim b$ infinitely many times in one go.
Comment: The number of breaking the limit is $n$, which depends on $n$, which approaches to $\infty$. This cannot be done.
Comment: You cannot treat the limit of an infinite product as the products of the limits. By the same reasoning, you would have the limit of the Riemann sum of a function always result in zero, which is false. You have to treat the function as a whole.
Comment: It is a worthwhile exercise, in thinking through the various ways this doesn't work, to address the question: what is the generic term in the ". . ." in the expression $$ \lim\limits_{n \to \infty}n^{\frac{1}{n}} \cdot \lim\limits_{n \to \infty}(n-1)^{\frac{1}{n}} \cdot \lim\limits_{n \to \infty}(n-2)^{\frac{1}{n}} \cdot \ldots \cdot \lim\limits_{n \to \infty}1^{\frac{1}{n}}$$ supposed to be?  (In all the expressions before that, it is easy to explain.  In that one, no so much, since $n$ does not exist outside the limit.)
Comment: Thank you everyone for your thoughtful replied. I understand the issue now. Thanks again!
Answer: You cannot use the product rule as the number of terms in the sequence is not fixed. Instead, if you consider $a_n$ as the sequence, then as the terms of the sequence are positive you have:
$a_n = \text{exp}(\log(a_n)) = \exp(\frac{1}{n}\sum^{n}_{i=2}\log(i))$. Now since $\log$ is strictly increasing we have(when $n$ is even),
$a_n =\exp(\frac{1}{n}\sum^{n}_{i=2}\log(i)) \geq \exp(\frac{1}{n}\sum^{n/2}_{i=2}\log(i)) + \frac{1}{2}\log(\frac{n}{2})) \geq \exp(\frac{1}{n}\sum^{n/2}_{i=2}\log(2)) + \frac{1}{2}\log(\frac{n}{2}))\geq \sqrt{\frac{n}{2}}\exp(1/6), n \geq 4$.
Hence the sequence is unbounded.