Redirect URL with GET variable to site with the GET variable in it

Question: I would like to redirect, for example :
index.php?name=sarah

to
names/sarah.php

The folder structure:

names/...
index.php

I've tried :
RewriteRule index.php?name=$1 /names/$1.php

and other ones, but didn't came to a solution.
Is this possible? If so, how can you do this?

Note:
The other way round is
RewriteRule ^names/([^/]*)\.php$ index.php?q=$1 [QSA,L]

which works fine.
Answer: Here is your rule:
RewriteCond %{QUERY_STRING} name=([^&]*)
RewriteRule ^.*$ /names/%1.php?

Answer: You first example wont work as you are trying to  manipulate query strings using a RewriteRule but this is not allowed. You  can try the following :
RewriteEngine on
RewriteCond %{THE_REQUEST} / index\.php\?q=([^\s]+) [NC]
RewriteRule ^ /names/%1.php? [L,R]
RewriteRule ^names/([^/]*)\.php$ index.php?q=$1 [QSA,L]


Show that $5^n$ divides $F_{5^n}$.

Question: If $F_n$ denotes the $n$-th Fibonacci number ($F_0 = 0, F_1 = 1, F_{n+2} = F_{n+1} + F_n$), show that $5^n$ divides $F_{5^n}$.
Comment: In fact, $F_{5^n} \equiv 5^n \bmod 10^n$ and it seems that $5^n$ is the largest power of $5$ that divides $F_{5^n}$.
Comment: See http://math.stackexchange.com/questions/136901/if-m-and-n-are-positive-integers-then-f-m-f-n-f-m-n?lq=1
Comment: Is $$(2,5^k)=5^k$$  for $k\ge1$?
Answer: Note that
$$
\begin{pmatrix}a+b & a \\ a & b\end{pmatrix}^5
=
\begin{pmatrix}* & c \\ c & *\end{pmatrix}
$$
where $c=5 a (a^4 + 3 a^3 b + 4 a^2 b^2 + 2 a b^3 + b^4)$. Therefore, if $5^n$ divides $a$, then $5^{n+1}$ divides $c$.
Apply this to
$$
\begin{pmatrix}1&1\\1&0\end{pmatrix}^n
=
\begin{pmatrix}F_{n+1}&F_n\\F_n&F_{n-1}\end{pmatrix}
$$
for a proof by induction that $5^n$ divides $F_{5^n}$.
Comment: Now that we have aids like [WA](http://www.wolframalpha.com/input/?i=%5B%5Ba%2Bb,a%5D,%5Ba,b%5D%5D%5E5), we can dare compute $A^5$ just to see what comes out...
Comment: $5$ seems to be very special here: there is no obvious multiple of $k$ in $c$ for $k\ne 5$.
Comment: Interesting :-)

Show that $5^n$ divides $F_{5^n}$.


Do I need a lot of money to make music?

Question: I am just a little kid who really likes music. I have been producing EDM House and Dubstep for about 6 months. I use a free software called LMMS with my Dad's laptop and no MIDI keyboard. I also use some $40 headphones. This is just my hobby, so I can't really invest a lot of money on this. Can I still make good music? By "good," I mean NCS music that people would actually listen to. Just buying FL Studio can cost $200. Do I really need those expensive products? I know it will be beneficial, but is it worth it and is it necessary?
Thank you :-)
Comment: If you can't make music that people want to listen to with a laptop, some free software, and some $40 headphones, spending $200, $2,000, or even $20,000 won't change that situation. Just remember that probably 99% of people who "want to make music people want to listen to" never succeed - not because they don't have enough money, but because they don't have enough *talent*.
Comment: Totally agree with alephzero! Don't fall for the trap that the more expensive price tag means better music. Better music comes from the musician, not from the tech. I purchased some odd $300+ dollars of equipment and my music making ability was the same. It only progressed with practice and study (boring answer right :P well, not if you love music). SO, you don't need a lot of money, but you do need a lot of patience and time to develop your gift in music. Then hey, maybe we all will be hearing your music in movies or on the radio. Who knows :)
Comment: I'd have to absolutely support aleph and Briard on this. Tools can help but they create nothing. Only you can do that. Additionally, FL Studio is one of the cheapest tools... So if it seems expensive to you, stop focusing on tools.
Comment: How old are you, by the way?
Comment: I've seen people make exceptionally great music on a cheap laptop with MilkyTracker. In the UK some artists have had chart topping hits making music with a cheap MIDI controller and a bog standard laptop (T2 for example. I know him). You can have all the gear and still no idea.
Answer: Well, there is that apocryphal story about Hemingway asking a photographer he admired which brand of camera he was using for making his pictures.  The photographer asked in return which brand of typewriter Hemingway employed for writing his stories.
Expensive stuff is great for working with recipes.  One-man bands can make good use of good arrangers, and they come in handy for serial production of stock music styles.
Basically, they allow you to focus your creativity on where you want and provide all the rest.
Basically they are akin to what Picasso stated: "Computers are useless: they only provide answers."
Creativity is more about developing your own "questions" and approaches to them.  If you want to be an entertainer, at one point of time there is good return for invested money.  If you want to be a composer and music creator, you might be better off not overindulging on equipment that already has a mind of its own distilled into it.
Answer: If you're getting started, then there is no reason to invest a lot of money in your hobby. Producing is like a discipline or like learning an instrument. For example, if you practise the drums for 6 months, you will be able to play some limited grooves and read rhythms, but you will be far away from being an actual drummer. Furthermore, you don't know how long you will stick (sic) at this hobby.
First, push your abilities to the limit. Gear won't make you a better musician. It can assist your existing skills, but won't make you a better producer. Experiment with your existing tools. I am pretty sure that you can still find out new things, as far as you have fun playing with them. Being limited can push your skills much more further than having a lot of expensive tools. Don't try to be especially "mainstream". Find your own style, be experimental, enjoy the art of making music.
A good software choice for beginners is Magix Music Maker. There is a free version available and you can upgrade cheaply at any given time.
Being able to make "good" music (good is always subjective) will cost you many many years.
Answer: What a nice question :) If I may, I would suggest that you can make music even with a stick hitting on a bucket. I think, at a first place, no budget or nothing whatsoever can limit your creative urge. Of course, if you have the good tools, which usually cost something, you can create more easily, but the essential thing one should have at very first place is the music inside. We as musicians/artists are transmitters of something higher than us, call it inspiration, joy, divine energy, etc. Whom do we transmit it to? Others. And I personally like that you aim at creating music that people would listen to. This is the creator's mission, namely to create something people would love listening, observing, to let them dream and disconnect from day-to-day bullshit.
So, back to the point, if I may suggest: 1) Ask yourself what music really turns YOU on; 2) Focus on that feeling and again ask yourself how you can transmit it to others with what you have NOW in your hands; 3) Do you really need tools and if so, why exactly and what for? How would a tool help you? What do you want to achieve and why?
I find a good and easy-to-use music making tool Garage Band that comes with a Mac and you don't need to pay additionally for it. It is also available for iPhone/iPad for free. And in this article they list TOP 5 free linux music creation tools: http://www.makeuseof.com/tag/top-5-free-linux-music-creation-tools-artist-budget/. It is probably worth taking a look.
Good luck!
PS: I'm adding here the link from my comment below to some cool stick-bucket stuff with apparently millions of fans :)

Do I need a lot of money to make music?


Esse trecho de código é jQuery? E o que ele faz?

Question: O trecho de código abaixo:

É escrito em jQuery ou JavaScript? E o que ele faz?
Comment: Na verdade esse código é uma mistura de jQuery com PHP
Answer: Sim, a grande parte desse código é jQuery, mas ele também possui PHP, no estilo tudo junto e misturado. O que pode ser novidade é que este é um código misturado com PHP.
Explicação do código
Veja que possui a tag

Alguns pontos fáceis de identificação do jQuery, além da sua sintaxe:

O cifrão - $:

Nota: A biblioteca jQuery expõe seus métodos e propriedades através de duas propriedades do objeto de janela chamado jQuery e $. $ É simplesmente um alias para jQuery e muitas vezes é empregado porque é mais curto e rápido para escrever. 1

Método .addClass():

.addClass( nomeClasse ) - Adiciona a (s) classe (s) especificada (s) a cada elemento no conjunto de elementos correspondentes. 1

No caso desse código, quando for executado a linha, vai adicionar a classe active ao elemento com id igual ao da variável $activeMenu.
Mais informações você pode encontrar no site do jQueryen.

Algumas observações
Como dito nos comentários, e também muito importante ressaltar:

Essa integração PHP/JS só funciona quando o código JavaScript é colocado junto à página PHP. Utilizar esta sintaxe em um arquivo JavaScript não funcionará, pois o trecho em PHP não será interpretado.

E também para conseguir rodar o arquivo você deve ter um arquivo jquery.js, o qual você pode baixar no site do próprio jQuery, ou pode utilizar um CDN, mais ou menos dessa maneira:

Os atributos de integrity e crossorigin são usados para verificação de integridade de sub-recursos (SRI). Isso permite que os navegadores garantam que os recursos hospedados em servidores de terceiros não tenham sido adulterados. O uso de SRI é recomendado como uma prática recomendada, sempre que as bibliotecas são carregadas a partir de uma fonte de terceiros.

Leia mais em  SRI Hash Generator.
Comment: Vale lembrar que essa integração PHP/JS só funciona quando o código JavaScript é colocado junto à página PHP. Utilizar esta sintaxe em um arquivo JavaScript não funcionará, pois o trecho em PHP não será analisado.
Comment: Muito bem lembrado @AndersonCarlosWoss
Comment: @AndersonCarlosWoss A menos que o webserver seja explicitamente configurado para processar arquivos JS com o PHP – o que é raro, e eu não recomendaria. Só pra registrar.


problem migrating my drupal site PDOException: SQLSTATE[42000] [1044] Access denied for user

Question: I have just loaded my drupal 7.32 site to JustHost from my pc (running xampp) copied the files across, and exported and imported the database to JustHost cpanel, i browse onto the website and I get the error message below. I have triple checked my database name and username of the database and password and they are correctly specified in my settings.php file. My database was called 'school2' on the pc, but I'm not sure that will affect anything.
I get this error message:-
PDOException: SQLSTATE[42000] [1044] Access denied for user 'caerleon_prim'@'localhost' to database 'caerleon_prim' in lock_may_be_available() (line 167 of /home4/caerleon/public_html/includes/lock.inc).
Can anyone help?
Comment: "but I'm not sure that will affect anything." Yes, it will, you have to set database name, user and password correctly. All three are needed. Plus, some hosting companies use different "machine names" for databases, and different in panel. You need to ask **them** what exactly you should put as name, user and password to access your DB.
Answer: With JustHost you need to assign the user to the database from the Database Maintenance drop down page. Instructions are on their site too. I did this, and it fixed my problem.


Is it true that a sprinter ran the 100m in 21.73 seconds in a World Championship?

Question: In many websites (especially in Spanish), it is mentioned that the worst performance in Men's 100m is that of Kim Collins, 21.73 seconds at Athens World Championship in 1997. To make things more spectacular (and, to me, more suspicious), this is the same Kim Collins who became World Champion in the same competition five years later.
There is no mention of that abysmal 1997 performance in the wiki page, but the time indeed appears in this list and also in the IAAF page.
For me, it's hard to believe that that the record was for a real, normal run. It's also totally inconsistent with the progression timeline of that runner (it would seem credible if it were a 200m run). Does anyone know what really happened?
Comment: Is it possible that it's a recording mistake?  That time (21.73) is very close to a 200m event time.
Answer: Yes, the story is true. Here is a video showing the race (at timecode 5:51).
As you can see, Kim Collins (at lane 7: it is him indeed, cf. the IAAF official results, heat #5) makes a normal start, but apparently gets hurt after ~40 m of race, and then stops his effort, just jogging from that point on. Since he nevertheless remained in his lane (at least for what one can see on the video), assuming that he reached the finishing line without breaking the rules, it is completely logical that his time was officially recorded: and the value of 21.73 s seems perfectly coherent indeed with what one sees on the video! ;-)
Answer: Considering the fact that Kim Collins qualified for the second round in the 100 m in 1996 Summer Olympics, one year before he recorded 21.73 seconds and his record of 10.63 seconds he made in 100 meters in 1995, it seems impossible for him to have recorded 21.73 seconds unless he tripped over or was injured during the race.
It is not that uncommon for track athletes to continue to run or walk when something goes terribly wrong.
I can't find anything on the internet which shows what exactly happened.


Bootstrap JavaScript not working in production environment (Rails 4)

Question: Basics:
Rails 4
Ruby 2.0
We are stumped with why we can't get Bootstrap Javascript to work on Heroku when it works fine on our dev machine. We had it working with modals, but when we switched to tabs it stopped.
Application.js
//= require analytics
//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require turbolinks
//= require_tree

production.rb
Entreuse::Application.configure do
config.cache_classes = true
config.eager_load = true
config.consider_all_requests_local       = false
config.action_controller.perform_caching = true
config.serve_static_assets = false
config.assets.js_compressor = :uglifier
config.assets.compile = false
config.assets.digest = true
config.assets.version = '1.0'
config.log_level = :info

development.rb
Entreuse::Application.configure do
config.cache_classes = false
config.eager_load = false
config.consider_all_requests_local       = true
config.action_controller.perform_caching = false
config.action_mailer.raise_delivery_errors = false
config.active_support.deprecation = :log
config.active_record.migration_error = :page_load
config.assets.debug = true
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
config.assets.paths << Rails.root.join('app', 'assets', 'fonts')
config.assets.precompile += %w( .svg .eot .woff .ttf)

gemfile
gem 'rails', '4.0.0'
gem 'sass-rails', '~> 4.0.0'
gem "haml", "~> 4.0.5"
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.0.0'
gem "bootstrap-sass", "~> 126.96.36.199"
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 1.2'
gem 'font-awesome-sass', '~> 220.127.116.11'

group :doc do
gem 'sdoc', require: false
end

group :development, :test do
gem 'sqlite3'
end

group :production do
gem 'pg'
gem 'rails_12factor'
end

App on Heroku
http://www.entreuse.com/
Any insights would be much appreciated.
Thanks!
Comment: Link provided isn't working at the moment.
Answer: We got this fixed!
The problem was with the analytics
//= require analytics
The error we were getting had to do with the fact that analytics.js.coffee was being included at the top before jQuery was included - it should be at the bottom after jQuery is included. So when it used the dollar sign method at the top of the js file, jQuery hadn't been defined yet.
This post was very helpful:
Rails 4 turbolinks with Google Analytics


Protractor Flake with Typescript implementation not working

Question: So I have the following scenario.
We have a Protractor-Cucumber framework based on this framework.
The framework has been modified in a way that the config files are written in TS. This is an example config:
import { browser, Config } from 'protractor';
import { Reporter } from '../support/reporter';

const jsonReports = process.cwd() + '/reports/json';

export const config: Config = {

    directConnect: true,
    SELENIUM_PROMISE_MANAGER: false,

    stackTrace: true,

    capabilities: {
        browserName: 'chrome'
    },

    framework: 'custom',
    frameworkPath: require.resolve('protractor-cucumber-framework'),

    specs: [
        '../../features/*.feature',
        '../../features/**/*.feature',
    ],

    onPrepare: () => {
        browser.manage().window().maximize();
        Reporter.createDirectory(jsonReports);
    },

    cucumberOpts: {
        compiler: 'ts:ts-node/register',
        format: 'json:./reports/json/cucumber_report.json',
        require: [
            '../../stepdefinitions/*.ts',
            '../../stepdefinitions/**/*.ts',
            '../../support/*.ts'
        ],
        strict: true,
        tags: '(@e2e) and (not @ignore) and (not @notImplemented)',
        keepAlive: false,
    },
    allScriptsTimeout: 10000,
    getPageTimeout: 5000,
    onComplete: () => {
        return Reporter.generateReports();
    },
    afterLaunch: exitCode => {
        if (exitCode === 1) {
            console.log('Actual Exit code: ' + exitCode);
            process.exit(0);
        }
    }
};

Looking back at the framework this was implemented from, now they have implemented protractor-flake, which is something I need to include.
I have tried using the actual config which is being used, and can be seen here however when I try to run it I get the following error:
E/configParser - Error code: 105
[09:14:04] E/configParser - Error message: failed loading configuration file ./build/config/conf.debug.js
[09:14:04] E/configParser - Error: Cannot find module 'C:\Users\Protractor\build\config\conf.debug.js'

Please note that I have changed the protractor args to load the config shown above hence it is showing that is cannot load config.debug.js.
I have also been through Nick Tomlin's repositories for protractor flake and the cucumber specific documentation and added the necessary console.log in the After support code and tested running protractor flake from the cli but nothing seems to work. I get the error above followed by :

Using cucumber to parse output
  Tests failed but no specs were found.
All specs will be run again.Re-running tests: test attempt 2

However no tests are run .i.e. no run at all.
When I run the usual config using npm all runs well, without the re run of protractor flake.
Can anyone offer their 2 cents on this issue, what am I missing?
I have searched quite a bit to find a typescript example for this but as yet have not, unless I missed it.
Sorry I know it is long but wanted to try to cover everything I have tried.
Thanks in advance.
Comment: Could you provide the test start command with it's args ?
Comment: Sure. npm run build && protractor-flake --parser cucumber  --max-attempts=3 ./build/config/config.debug.js
Answer: I struggled with similar problems when embedding protractor-flake.
1) Check if your current debug.conf.js works. Achieve this by copying debug.conf.js into some folder on your computer and running protractor-flake with an absolute path to your debug.conf.js in args.
2) If step 1 worked, you have to migrate your debug.conf.js into typescript, by simply putting .ts at the end and changing the content to:
// debug.conf.ts
const protractorFlake = require('protractor-flake');
const argv = require('yargs').argv;

export default (function () {
  protractorFlake({
    maxAttempts: 2,
    parser: 'cucumber',
    protractorArgs: [
      './e2e-tests/config/protractor.e2e.conf.js',
      `--feature=${argv.feature || '*'}`,
      `--tags=${argv.tags || ''}`
    ]
  }, (status) => {
    process.exit(status);
  });
})();

You will have to adjust this path in config: './e2e-tests/config/protractor.e2e.conf.js', it should be correct relative path pointing to builded javascript protractor.e2e.conf.js.
In debug.conf.ts you can see a default export which is a function and this function is executed immediately.That means, if we run require('./somePath/debug.conf'), OR ts-node debug.conf.ts,  protractor-flake will directly be executed. You can then for example store following npm script for running protractor-flake:
// ...
"scripts": {
   "protractor.flake": "ts-node ./somePath/debug.conf.ts"
}
// ...

Let me know if anything is unclear or doesn't work, Cheers!
Comment: Thanks for your time. I have tried this step by step and was under the impression that I had done exactly this. But this time following this it worked woohoo. Thanks again Silvan. Now I just need to see how to merge the reports that are created with every run to include all the passes :)
Comment: Let me know if you need help :), gl


Average effect of coefficients across multiple linear models?

Question: I have several OLS models with robust s.e.'s that predict an outcome variable Y.   For instance:
Model 1:
$Y=B_0 +B_1X_1$
Model 2:
$Y=B_0 + B_1X_1 + B_2X_2$
Model 3:
$Y=B_0 +B_1X_1 + B_2X_2 +B_3X_3$
I am interested in giving an average effect for $B_1$ across Models 1-3 with an accompanied 95% CI.
Can I just take the average of $B_1$'s across Models 1-3 and the average of standard errors to construct my confidence interval?  What is this called?
Comment: Are you fitting all three models to one data set? Why would youbwant to average those parameters?
Answer: If these 3 models are estimated from independent samples, then you can assume that $\beta_1$ are independent for these 3 models. Then you can average them. The standard error of the average then will be the square root from the average of the squares of the standard errors.
However you should check if you do not have omited-variables problem. If you do, then one of the $\beta_1$ in your models is biased, so it should be discarded.
Of course if you have all the data for these 3 models, I suggest estimate Model 3 with all the data and then use the coefficient $\beta_1$ with its standard error, assuming that your model is adequate.
Comment: @Thomas, if it is the same data for all three models, then I do not suggest averaging. The common practice you mention is used  to show that there is no omited variable problem. But since the same data is used to estimate all three models, then you cannot assume independence. If there is no omitted variable bias, then the average will be unbiased, but the standard error of such average cannot be calculated easily, since the coefficients will be clearly correlated.
Comment: +1.  But what would the interpretation of the average of the $\beta_1$ be?  You might just as well average the price of bananas in Costa Rica with the answers to question #1 in the latest Gallup poll.  And the "CI" would require careful interpretation indeed; it certainly doesn't reveal anything about the relationship between $X_1$ and $Y$!
Comment: Thanks Mike.  That's what I thought.  It's just in common practice in econometrics literature to present several models to show that your result is robust across specifications. Your point about omitted variables is well taken.
Answer: This is an interesting paper one may want to read before doing model averaging:
On Model Averaging Regression Coefficients. Even though it is counter intuitive to average the coefficients as the interpretation is no longer Effect of X1 on Y in presence of X2, X3, ...., there are some ongoing investigations on how and when to do averaging of coefficients.


Truncar tabelas com cascade

Question: Tenho uma tabela hotel e a tabela reserva.
Na tabela reserva tenho a chave primária da tabela hotel como chave estrangeira.
Não consigo truncar porque há relações entre chaves. Como posso fazer?
Já fiz:
truncate table hospede on delete cascade;

Mas não consigo.
Só lembrando que as fk estão com on delete cascade. E que uso a versão 11g express edition.
Answer: O on delete cascade só deve ser usado em algumas instruções DDL (data definition language), e não em instruções DML (data manipulation language). Ou seja, é para usar apenas onde há alteração na estrutura das tabelas, e não nos dados. Porém no seu caso, você só quer apagar os dados sem alterar a estrutura das tabelas.
Assim sendo, eu faria o seguinte:
TRUNCATE TABLE hospede;
TRUNCATE TABLE reserva;
TRUNCATE TABLE hotel;

A ordem das instruções é importante.
Comment: Se isso não funcionar, edite a pergunta fornecendo nomes de colunas e como são definidos os relacionamentos.
Comment: não testei porque eu apagei as constraints e trunquei a tabela. Se estivesse uma maneira de forçar o truncate sem tanta volta, seria ideal.
Comment: As constraints existem para garantir a integridade das tabelas , não as usando pode-se fazer o que quiser mas com risco. Fora isto muitas vezes é uma simples questão de ordem em que os trucates ou deletes são feitos como disse o @Victor Stafusa.

Truncar tabelas com cascade


Complicated 'double' contextual and relationships view

Question: I would like some help on how to implement the following view:
A block that shows all the 'events' happening at any 'location' created by a user.
I have 'event' and 'location' content types. There is a field in the 'event' node which refers to a 'location' node (it's nid).
I am familiar with views, just not sure how to get the 'double filtering' required to show only events that have a location that is created by the user logged in. I cannot create an 'author' relationship to a contextual filter for the location or event to a simple filter, as the view displays events, not locations... Any ideas?
Answer: I would create a View of the Content Type Location (these are the nodes created by your users, right?).

Create a Relationship to Author.
Create a Filter to user: current and select Yes in Is the logged in user (NB: this a a regular filter, not a Contextual Filter)
Create a Relationship to the Event type through its reference field to Location (NB: select Entity Reference: Referencing Entity . If you select "Require this relationship" the View will limit the Location types to only those referenced in an Event node
Add any field to the View, but be sure to select the relationship you created in 3 above to show field from the Event type

That's it! Nice question!
Comment: Hi Argie, will that not create a list of locations, and not events? I am interested in a list of 'events' for which location fields are referring to the 'location' nodes created by the logged in user. Imagine a restaurant owner wanting the list of all events happening at his restaurants.
Answer: Thanks to Argiepiano for the direction to take. Here is what I ended up doing. Quick reminder of the objective:
a business owner (owning more than one places) wants to view all events created at any of his locations. Locations and events are separate content types and in the 'event' content type, there is an entity reference field to the location nodes.

Create a view of content type EVENT.
Create a relationship 'Entity Reference: Referenced Entity'. Call it 'location node'.
Create a relationship 'Content Author'. Call it 'location author'. Add a relationship to 'location node'.
Create a contextual filter 'Content: Author uid'. Add a relationship to 'location author'.
In that filter, in the section 'WHEN THE FILTER VALUE IS NOT IN THE URL', select 'provide default value' and choose 'User ID from logged in user'.

I hope it helps someone in the future!


Testing for a Non-Linear regression in R

Question: How do I test if a non-linear least squares regression best fits a given set of data in R? More specifically I'm interested in getting estimates for a regression like this:
$$y=\beta_0+\beta_1(x_1-a)+u$$
(for the variables $\beta_0$,$\beta_1$ and $a$). How would I code this?
Comment: What does "best fits" mean? What is it being compared with?
Comment: Your specification is linear in parameters. To test for non-linearity, you could estimate another model including a non-linear effect (e.g. Y = b0 + b1.X1 + b2.(X1*X1) + U) and use a log-likelihood ratio to compare the performance of this 2nd model with your first reference model.
Comment: @Glen_b im looking for statistically significant betas. Its being compared to a standard linear regression model without $a$  being subtracted from the $x_1$
Comment: @Umka so just throw in an arbitrary constant and see what happens?
Answer: If (as your question seems to say) that you have three parameters to estimate ($\beta_0,\beta_1,a$) then this model is not identifiable.
\begin{eqnarray}
y&=&\beta_0+\beta_1(x_1-a)+u\\
&=&(\beta_0-\beta_1 a)+\beta_1 x_1+u\\
&=&\beta_0^*+\beta_1 x_1+u
\end{eqnarray}
Now consider that there's some best estimate of slope $\hat{\beta}_1$, and a corresponding best intercept $\hat{\beta}_0^*$ (this doesn't rely on how they're estimated - it doesn't matter).
Then in your formulation the intercept (given the slope) has two free parameters ($\beta_0$ and $a$), so that for a given $\hat{\beta}_0^*$ there's an infinite set of pairs ($\hat{\beta}_0$ and $\hat a$) which will give that best fitting value of intercept. So you simply can't tell which pair it might be -- they will all give identical fits.
As it stands, there's nothing to be done here.


complicated bonding and network question

Question: I am not a network guy and would like to know how can I setup the below two configurations and their pros and cons:
Networking component: --

WAN: Cisco 2970 * 1
Load Balancer: F5 switch 1600 * 2
Private Subnet: Cisco 2960 * 2

My situation is like that, my F5 switch 1600 will connect to Cisco 2970 upstream to the public (WAN) and all my host will connect to the pair of Cisco 2960 private lan which then interconnect to the pair of F5 switch 1600 providing load balancing as well as fault tolerance function. All of my host equip with two ethernet interface (most of them are using broadcom 5700) and they will team up and each interface will connect to one cisco switch so as to privide fault tolerate as well as link aggregation.
My question is, how can I config my equipment (Cisco 2970, F5 switch 1600, Cisco 2960 as well as my host) physically (cabling) and logically (system configuration?), and what are their pros and cons?

Host using balance-ALB.
Host using 802.3ad.
Answer: Regarding load balancing you have a couple options.  If you plan to use a lot of capacity for sending responses you probably want to investigate direct server return and wire your hosts up so they don't always have to route back through the F5.  If that isn't a huge concern it makes diagnostics a little easier if the F5 handles both parts of the connection by having your hosts route through it for both the request and the response.
Regarding 802.3ad there are times when it can be beneficial.  However it also increases the failure-zone.  Where as with a separate network connection and two physically diverse network paths if you have a configuration error or software failure in one, your other path should continue to function.  If you setup everything in a bonded scenario and you experience either a configuration mistake or a software bug it is possible your entire site will go offline(because the bond will not negotiate properly).  That said it is usually easier to diagnose a 'standard' approach of using bonding with contractors and Cisco TAC staff.  This is the standard 'fail safe' vs 'fail over' approach.  Either is valid and both have pros/cons that you will want to weigh specifically to your environment.


Combination of $2\times 1\times 1$ cubes inside a $3\times 3\times n$ cube

Question: I came along this question in my math book and I can't seem to figure it out.
I searched for packing problems, but i couldn't find the answer.
You have a block with a width of $3$, depth of $3$ and a height $n$
Given height $n$, in how many ways can you fill this block with smaller blocks of $2 \times 1 \times 1$?
Comment: is it 2*2*1 or 2*1*1 ?
Comment: The problem is impossible if the smaller blocks are $2 \times 2 \times 1$, and with $2 \times 1 \times 1$ blocks it is trivial when $n$ is even and impossible otherwise.
Comment: How many solutions is not obvious to me
Comment: The cube is 2 * 1 * 1, sorry.
Comment: n can be any positive natural number. The small blocks don't have to fit perfectly, one small 1*1*1 block can be unused. With n = 1 i would have at least 22 solutions
Comment: Asked at [MathOverflow](http://mathoverflow.net/q/144733/12357), where it was pointed out that this is a [Project Euler question](http://projecteuler.net/problem=324).
Comment: Relevant Meta discussion: http://meta.math.stackexchange.com/questions/1090/re-project-euler-questions
Answer: Consider the cross-section $S_r$ at height $r\geq0$ of your $3\times3\times n$-tower. Assume you have built the tower up to height $r$. Some of the $2\times1\times1$-sticks filling the first $r$ layers  will cross the level $S_r$ and protrude into the $r+1$st layer of the tower. These sticks determine a certain subset $A$ of the $9$ squares of $S_r$. The set ${\cal P}$ of all these subsets has cardinality $2^9=512$. For each $A\in{\cal P}$  you have to determine all possibilities to lie further sticks horizontally into the $r+1$st layer (this can be done once and for all), and for each of these possibilities you have to put vertical sticks at all empty spaces in the $r+1$st layer, creating a new pattern $A'$ of protruding sticks in $S_{r+1}$.
Denote by $P_r(A)$ $\>(r\geq0)$ the number of possible arrangements up to $S_r$ with protruding pattern $A$. Then $P_0(\emptyset)=1$ and $P_0(A)=0$ for all $A\ne\emptyset$. The counting work you have done now allows you to set up a linear recursion scheme
$$P_{r+1}(A')=\sum\nolimits_{A\in{\cal P}} c_{A A'} P_r(A)\ ,$$
where the $512\times512$ coefficients $c_{A A'}\in{\mathbb N}_{\geq0}$ have been determined in the counting process described above.


How do I use a newer perf tool front end with a record from an older perf version

Question: I am running perf record on an older version of the kernel on an ARM board. The kernel version is 3.18.21-rt19
The perf version on the board is similarly perf version 3.18.21.
While I can record and use the report feature on this perf, the TUI for report on this version is quite awful/non-existent. Instead of the expandable sections (in the graph mode) it just shows up as a giant scrollable list of functions that is very tough to work with. Also for some reason my C++ function names are not de-mangled so it is really difficult to read it.
Is it possible to some how either:

Export the perf.data created on this older ARM kernel to an x86 machine running a newer kernel  and a newer version of perf and use the perf report on said machine. When I try to do that (I run on kernel 4.4.0-31-generic running perf version 4.4.13) I lose all symbols, even though running perf report on the ARM machine shows the symbols just fine (C++ names are still  mangled). I am not sure if this is just because the perf.data format has changed between these kernel versions or if the x86 version is just outright not capable of reading data generated by the ARM machine.
Build a newer perf version (at least the front end) for my older kernel that does the de-mangling and exposes the newer better TUI.

Changing the kernel version on my ARM board is not an option for me.
Comment: Building a newer perf user-space tool is possible. Your perf probably was built without TUI. To export perf.data to another machine you should use [`perf archive` command](http://man7.org/linux/man-pages/man1/perf-archive.1.html) which will copy all symbol information with `perf.data` (or try to copy files from root fs or full image of root fs, as `perf.data` after `perf record` has only instruction addresses, not full obejct/functions maps).
Answer:
Export the perf.data

Exporting of perf.data should be supported with perf archive command, check man perf-archive - http://man7.org/linux/man-pages/man1/perf-archive.1.html

perf-archive - Create archive with object files with build-ids found in perf.data file
  perf archive [file]

This command runs perf-buildid-list --with-hits, and collects the
         files with the buildids found so that analysis of perf.data contents
         can be possible on another machine.

There is no example of using perf archive in the Perf Tutorial: https://perf.wiki.kernel.org/index.php/Tutorial but mentioned in http://events.linuxfoundation.org/sites/events/files/slides/LinuxConJapan2015-DynamicProbes.pdf#page=22 "What's the Buildid-cache? .. This also allows us to analyse perf.data from remote machine (perf-archive does that)"
It can be hard to use perf with another architecture (x86) to ream ARM files, so you probably may try some ARM system emulator (like qemu/qemu-system-arm) with some recent ubuntu/arm or linaro/arm iso or root image (they should have full-featured perf).
You may also try to upload better version of perf utility (built by you or copied from ubuntu or linaro) to your  board  - perf user-space tool is compatible with perf_events kernel interface over wide range of kernel versions, and it can read perf.data recorded with different version of perf tool.
Comment: This seems like the right way to make it work. My perf version shows archive as one of the available commands but when I run perf archive it says:

`perf: 'archive' is not a perf-command. See 'perf --help'.

Did you mean this?
 archive`
Comment: Rajiv, This is strange, but I see no 'archive' command in perf's `main()` and internal [command list](http://lxr.free-electrons.com/source/tools/perf/perf.c?v=3.18#L36) too, but there is `perf-archive.sh` bash script - try it - http://lxr.free-electrons.com/source/tools/perf/perf-archive.sh?v=3.18 (download from the https://github.com/torvalds/linux/blob/master/tools/perf/perf-archive.sh). This can probably be an error in perf's documentation (if only it has documentation).
Comment: I was able to run perf-archive.sh. I noticed that the ~/.debug folder only had files for [kernel.kallsyms]. So when I use the archive file on another host and populate its ~/.debug folder with the archive file's contents, perf-report can resolve the kernel symbols. I am not sure how to get the other symbols. perf-buildid-list --with-hits shows entries like `0000000000000000000000000000000000000000 /lib/libc-2.21.so` for all entries besides [kernel.kallsyms] on the host AMR board. Not sure where perf report on the ARM board can find these symbols.
Comment: Rajiv, try to run `ldd ./your_program` and manually copy all listed binary files from ARM to the host machine.
Comment: Accepting this answer. I have issues with my toolchain that is preventing me from making this work, but looks like these steps will work fine once I get these issues sorted out.


Independence of Random Variables, a special condition

Question: Suppose the random variable $ (X,Y) $ is independent of $ Z \equiv (Z_{1}, Z_{2}) $.
1) Is it possible that $ X $ and $Z$ are not independent?
2) Is it possible that $ X $ and $Z_{1}$ are not independent?
Since $ (X,Y) $ is independent of $ Z $, I can write
\begin{align}
f_{X,Y,Z}(x,y,z) = f_{X,Y}(x,y)f_{Z}(z).
\end{align}
I guess I can integrate $y$ from both sides of the above to get
\begin{align}
f_{X,Z}(x,z) = f_{X}(x)f_{Z}(z).
\end{align}
Answer: The answers:
1) it is not possible
2) it is not possible
Let $F(x,y)=Pr(X<x, Y<y)$, $G(z_1,z_2)=Pr(Z_1<z_1,Z_2<z_2)$.
Then for the condtional probability we have:
$$
Pr(X<x, Y<y|Z_1=z_1,Z_2=z_2)=F(x,y),
$$
since $(X,Y)$ is independent from $(Z_1,Z_2)$. Put $y=\infty$ and you get 1).
For another conditional probability we have:
$$
Pr(X<x, Y<y|Z_1=z_1,Z_2<z_2)=F(x,y),
$$
since $(X,Y)$ is independent from $(Z_1,Z_2)$.
Put $y=\infty$ abd $z_2=\infty$ and you get 2).


Facebook Realtime Updates Multiple Posts

Question: I'm doing some test to my application on Facebook, and one of the tests is a massive POSTS in a row to see what its the behavior o the app, but some of the posts are not triggering the Real Time Update event and others are getting the field time wrong.

Example: One Event I receive comes with time=1349694666 but in
  Facebook tables it says 1349694665, so when I do the query for it it
  won't return the feed.

Can you guys know why or can you point me to an answer?
Regards,
Elkas
Answer: This was simple. Instead of doing the FQL to the table status do to the stream one. The values macth all the time, at least for me until now.


Deriving $\chi^2$ density from the standard normal $Z$ density

Question: For the sake of learning, I am trying to derive a $\chi^2$ density from the standard normal $Z$ density.
The $\chi^2_k$ is a distribution of the sum of squares of $k$ standard normal variables, where $k$ is the the number of degrees of freedom.
Taking $k=1$ for simplicity (i.e. just one standard normal variable), I have tried the following in R:
library(data.table)

DT <- data.table(x = seq(0, 3.5, by=0.01)) #In a range from 0 to 3.5

Standard normal density multiplied by 2 to calculate the density of absolute $Z$ values (i.e. negative + positive); this is equivalent to a $\chi$ density.
DT[, Z_abs := 2*dnorm(x)]

Calculate the squares:
DT[, X_squared := x^2]

And plot the density against the squares:
library(ggplot2)

ggplot(DT, aes(X_squared, Z_abs)) + geom_line() +
  scale_x_continuous(limits=c(0,3.5), breaks=seq(0,3.5,0.5))

However, this is apparently wrong as it differs from the correct $\chi^2$ density given by the built-in dchisq function (shown in red).
DT[, Chisq := dchisq(X_squared, df=1)]

ggplot(DT, aes(X_squared, Z_abs)) + geom_line() +
  geom_line(aes(y=Chisq), color="red") +
  scale_x_continuous(limits=c(0,3.5), breaks=seq(0,3.5,0.5)) +
  scale_y_continuous(limits=c(0,0.8)) +
  ylab("Density")

Where did I get it wrong ?
Comment: Have you heard of a change of variable for densities, also called the Jacobian formula?
Comment: you do not take into account how squaring $x$ "stretches" the interval over which the pdf takes values.  The correct density would be `DT[, Chi2 := Z_abs* 1/(2*sqrt(X_squared))]`. See [this answer for an intuitive explanation](https://stats.stackexchange.com/a/14490/61836)
Comment: This is not how densities transform.  Please search our site for information: https://stats.stackexchange.com/search?q=transform+pdf.
Comment: Yes: In addition to the explanation referenced by @matteo, some intuition is also given at https://stats.stackexchange.com/questions/4220/can-a-probability-distribution-value-exceeding-1-be-ok/4223#4223.
Comment: @whuber OK, I now see there are special formulae for this, but can you explain intuitively where is the flaw in my logic above?
Answer: Let us first find the density of the absolute value of $X\sim N(0,1)$, $Y=|X|$, $g(y)$. For $y>0$,
\begin{eqnarray*}
G(y)\equiv\Pr(Y\leqslant y)&=&\Pr(|X|\leqslant y)\\
&=&\Pr(-y\leqslant X\leqslant y)\\
&=&F(y)-F(-y)
\end{eqnarray*}
and hence
$$g(y)=G'(y)=f(y)+f(-y)$$ (note the second inner derivative equals $-1$). Since $y=|x|$ cannot be negative, we have $g(y)=0$ for $y<0$. For densities symmetric about zero (such as the normal density) we have
$$f(y)=f(-y)$$
and therefore
$$
g(y)=\begin{cases}0&y<0\\
2f(y)&y\geqslant0\end{cases}
$$
For the second step (the change of variable technique that you were referred to in the comments), we have $y=w(z)=\sqrt{z}$ and hence $w'(z)=\frac{1}{2}z^{-\frac{1}{2}}$. Thus,
\begin{eqnarray*}
h(z)&=&\frac{2}{\sqrt{2\pi}}\exp\biggl\{-\frac{(\sqrt{z})^2}{2}\biggr\}\left|\frac{1}{2}z^{-\frac{1}{2}}\right|\\
&=&\frac{1}{\sqrt{2\pi}}z^{-\frac{1}{2}}e^{-\frac{z}{2}}
\end{eqnarray*}
for $z>0$ and 0 elsewhere. This is the density of the chi-square distribution with $\nu=1$.
Answer: As pointed out in the comments, your error here is that your density transformation does not take account of the nonlinearity of the transformation.  I will show you a better empirical demonstration of the distributional equivalence, where we don't attempt the transform at all, but simply compare the kernel density of simulated values of the sum with the postulated chi-squared density.  I will also show you a simple proof of the distributional equivalence at issue.

Empirical simulation: Rather than attempting the density transformation, let's proceed by simulation, by simulating $N=10^5$ sets of $n=4$ standard normal random variables.
#Generate matrix of simulations
set.seed(1)
N <- 10^5
n <- 4
SIMS <- matrix(rnorm(N*n), nrow = N, ncol = n)

#Compute statistic of interest and its kernel density
STAT <- rep(0, N)
for (i in 1:N) { STAT[i] <- sum(SIMS[i,]^2) }
DENS <- density(STAT)

#Set chi-squared density function
CCC  <- function(x) { dchisq(x, df = n) }

#Plot the kernel density against the postulated chi-squared density
plot(DENS, xlim = c(0, 20), lwd = 2, main = 'Simulation of Density')
plot(CCC,  xlim = c(0, 20), lwd = 2, lty = 2, col = 'red', add = TRUE)

As you can see from the plot, the simulated values closely follow the postulated chi-squared density.  You can easily repeat this simulation analysis for different values of $n$ if you would like to demonstrate the distributional equivalence for other values.

Proving equivalence in distribution: For completeness, I supply you here with a proof of the distributional result you are trying to show by simulation.  The simplest way to prove this result is via moment generating functions (or characteristic functions).  Let $Z_1, ..., Z_n \sim \text{IID N}(0,1)$ be a set of IID standard normal random variables and let $G = \sum_{i=1}^n Z_i^2$.  Using the law of the unconscious statistician and the substitution $y = z \sqrt{1/2-t}$, for all $t < \tfrac{1}{2}$ we have:
$$\begin{align}
\mathbb{E}(\exp(t Z_i^2))
&= \int \limits_{-\infty}^\infty
\exp(t z^2) \cdot \frac{1}{\sqrt{2 \pi}} \exp \bigg( -\frac{1}{2} z^2 \bigg) \ dz \\[6pt]
&= \frac{1}{\sqrt{2 \pi}} \int \limits_{-\infty}^\infty
\exp \bigg( - \Big( \frac{1}{2} - t \Big) z^2 \bigg) \ dz \\[6pt]
&= \frac{1}{\sqrt{(1-2t) \pi}} \int \limits_{-\infty}^\infty
\exp ( -y^2 ) \ dy \\[6pt]
&= \frac{1}{\sqrt{(1-2t)}}, \\[6pt]
\end{align}$$
Thus, for all $t < \tfrac{1}{2}$ the moment generating function for $G$ is:
$$\begin{align}
m_G(t)
&\equiv \mathbb{E}(\exp(tG)) \\[10pt]
&= \prod_{i=1}^n \mathbb{E}(\exp(t Z_i^2)) \\[6pt]
&= \prod_{i=1}^n \frac{1}{\sqrt{(1-2t)}} \\[10pt]
&= (1-2t)^{-n/2}. \\[6pt]
\end{align}$$
This is the moment generating function for the chi-squared distribution, which demonstrates that $G$ is a chi-squared random variable.  (See here for proof that the moment generating function determines the distribution.)


How to test normalized frequencies

Question: I have extracted the frequency of two words (can, may) from two corpora (Corpus1, Corpus2).
I want to test if there is a significant difference between the counts in the two corpora, but since the corpora are of different different sizes I have to normalized these counts (for instance to occurrence per 1000 words).
Any ideas for how I can do this in R? And what statistical test would you recommend?
Comment: "What statistical test..." is an on-topic question here, but "how can I do it in R" is not. Be aware that you may not get answers for the latter.
Answer: In statistical terms, your question is about a test for the difference in probability for two binomial random variables with different population sizes. I.e.
we have that number of occurrences of a word in the corpora are distributed
$X_1 \sim \text{Binomial}(n_1, p_1),$ and  $X_2\sim\text{Binomial}(n_2, p_2),$ and we want to test the hypothesis
$$H_0: p_1 = p_2.$$
In this setting, I would recommend using the function prop.test(), which computes the test you want if you give it the data in the form a vector of occurrences $(x_1, x_2)$ and a vector of corpus lengths $(n_1, n_2).$
I.e. If there are 400 words in the first corpus, with 20 occurrences of "can", and 700 words in the second corpus with 60 occurrences of "can", then executing the line
prop.test(x=c(20, 60), n=(400, 700))
will compute the test (p-values, confidence interval for $p_1 - p_2$, etc) for the difference.

How to test normalized frequencies


Como a função include do PHP funciona por trás dos panos

Question: Digamos que eu tenha duas páginas, uma chamada teste.php e a outra teste2.php.
Na página teste.php eu tenho o seguinte código:
...
$usuario = new Usuario();
$usuarios = $usuario->getUsuarios();
...

E na página teste2.php tenho o código:
...
include "teste.php";
...

Ao fazer o include da página teste.php na página teste2.php qual processo ocorre por trás disso? O php serializa o OBJ da página teste.php e ao fazer o include ele usa a function unserialize() nesse OBJ por trás dos panos?
Answer: Não há serialização de objetos quando está usando include. Porém, o PHP processa o arquivo e da a ele um escopo específico, dependendo de onde inclui o outro artigo.
A documentação explica bastante sobre como o include funciona, os escopos diferentes, etc.
http://php.net/manual/pt_BR/function.include.php
Comment: Eu cheguei a olhar a documentação. Mas eu acredito que ela esteja incompleta. Pq o programa Burp Suite está alertando para 'Serialized object in HTTP message' justamente em um arquivo q faz include de outro q estancia um OBJ. :/


How to handle new refresh token events for multiple users in google api

Question: I'm working on an MVP for a web app using nodejs. I use gmail/google API for authentication and login. I've set up the login and OAuth2.0 and it's working. However, there is one part in the documentation I'm not sure about. Here is the documentation I'm referring to
https://github.com/googleapis/google-api-nodejs-client
Specifically the "Handle Refresh Tokens" part.
It says that I should listen to the tokens event for new refresh_tokens and store the new refresh_token in the database
<code>oauth2Client.on('tokens', (tokens) => {
  if (tokens.refresh_token) {
    // store the refresh_token in my database!
    console.log(tokens.refresh_token);
  }
  console.log(tokens.access_token);
});
</code>
What I don't understand is how would you know which refresh_token is for which user? Would you have to associate a unique identifier earlier in the process, then when the event occurs check for the identifier?
Comment: Each users should have a refresh token stored for them.  You dont want to mix them up.
Answer: Yes, you need to create a unique identifier and map that to the refresh token as the value if you're going to store it in a database, which is recommended.
Remember that the refresh token grants another access token without requiring the user to authenticate. Which means if you use the refresh token with a request for another user, you're giving the other user access!
A common way to create a unique identifier is with a session token or session id as the unique identifier. You can use that as the key mapped to the refresh token in your database.
See here for some explanation and things to watch out for:
OWASP Session Management Cheat Sheet
You also need to think about how you're going to store that unique identifier. So you know when to use the associated refresh token at the right time. It depends on your use case, but if you're using it to avoid requiring the user to re-authenticate, stored securely in a cookie is often how it's done. So, the next time the user revisits your app, you can check for the cookie and lookup the unique identifier in your database.
From the same cheat sheet.
And MDN has some helpful docs on cookies.
OWASP Nodejs cookie security
If you're doing something like running some kind of automation for the user when they aren't present, it'll look different. Encrypting the user's email or whatever identifier you're using for the use is one way. Use the result of that as the key/session token. That's, of course, a simplified view, but it gives you an idea.


Not able to delete with LIMIT in mysql join query between multiple tables

Question: This is my sql query:
DELETE gur
FROM group_master gm
JOIN group_users gu
ON gu.group_id=gm.id
JOIN group_user_roles gur
ON gur.group_user_id=gu.id
WHERE gm.school_code = 14741359 AND gm.ayid=3
LIMIT 1;

I get the error saying there is a syntax error near LIMIT. I found a solution here: DELETE using LEFT JOIN with LIMIT in MySQL.
I am not able to transform my query into select statements.
Comment: [mre] Put all & only what is needed to ask your question in your post, not at a link. Paraphrase or quote from other text with credit. Give just what you need & relate it to your problem.
Answer: Only single-table DELETE supports LIMIT.
Use your query as SELECT with LIMIT and get ID of the row (remember - LIMIT without ORDER BY is a lottery). Then delete according row from another table copy.
DELETE group_user_roles
FROM group_user_roles
JOIN (SELECT gur.id
      FROM group_master gm
      JOIN group_users gu ON gu.group_id=gm.id
      JOIN group_user_roles gur ON gur.group_user_id=gu.id
      WHERE gm.school_code = 14741359 AND gm.ayid=3
      /* ORDER BY ??? */ LIMIT 1
      ) USING (id)

Replace id with primary key or unique column/expression for group_user_roles table.


Drupal table name which has the name of person who last modified the node

Question: Which is the name of the table which has the author / and or last modifier of the nodes I can find in the table node_field_data ? (drupal 8 )
Answer: There are two tables to get node user information from:
node_field_data has the uid of the creator in it.
node_revision has the last uid to edit a revision of the node.
Note that if you allow revisions, there can be multiple revisions including ones that have been rolled back.  Use the node table's vid to find the current revision.


Examples of uniformly bounded random variables

Question: In my textbook there is the following definition:
A sequence of random variables $\{X_n\}$ is uniformly bounded if there exists $K>0$ such that $P(|X_n|\ge K)=0$ for all $n$.
There are no examples given, so am I right saying that a sequence of normal random variables, $X_n\sim N(\mu_n, \sigma_n)$, will not be uniformly bounded, but a sequence of Bernoulli random variables, $X_n\sim B(p_n)$, or Binomial random variables, $X_m\sim Bin(n_m, p_m)$ will be if the parameters of the distributions are fixed?
Answer: You are correct, a normal random variable has density $e^{-(x-\mu)^2/2\sigma^2}$ which does not have compact support, hence $P(X\le x)>0$ for all $x\in\Bbb R$. On the other hand, if you have a sequence of Bernoulli random variables, parameter fixed or not does not matter, you know they take values in the set $\{0,1\}$, so let $K=2$ no matter what $p$ is $P(X<-2)=P(X>2)=0$. Binomial random variables are sums of Bernoulli random variables, so if you have $n$ bounded, then the answer is yes as it will be supported on $[-n,n]$ so $P(X<-n-1)=P(X>n+1)=0,\;$ independent of $p$. The converse is also true.
In the case of any discrete random variable on $\Bbb N$ you can easily see that it is bounded as an individual random variable iff its generating function is a polynomial, so a sequence of discrete, random variables is uniformly bounded iff the degrees of their generating functions are finite and uniformly bounded.
This all comes from the more general fact that a random variable (resp. sequence of random variables) is bounded (resp. uniformly bounded) iff it has compact support (resp. are all supported on a common compact set). In the case it is discrete, you use that discrete + compact implies finite to get the second paragraph I mention.
Comment: Thank you. This helps a lot.
Comment: @user_0_1_2 my pleasure. Since you're new a pro-tip:  be sure to upvote helpful answers you get, and accept ones that give you what you're looking for. It helps future users to know what you found helpful and in searching out good information. Welcome to MSE!
Comment: It says that "votes cast by those with less than 15 reputation are recorded but do not change the publicly displayed post score".


Beginner guitar learning I,IV & V

Question: I'm learning Green Onions. I have the base part down, simple Fm, Bb, Cm. but I can't figure out the chords, I, IV,V to play along with that. I have recorded the base part on a looper and want to play a rhythm over it. I'm told to use 1st inversions. But I'm lost.
Comment: So, F, Bb, C are intended bass melody, and you want to decide chords on it? But if you have made up your mind that they are Fm, Bb, Cm, then isn't it f minor? Then what is the question? I don't get it, sorry....
Comment: I added a comment below Tim's answer.
Answer: It's in a pretty standard 12 bar format, originally in Fm. So, 1st 4 bars, F, Ab, Bb. Next 2 Bb(maj) Db,Eb, 2 as beginning, then - C, Eb, F; Bb,Db,Eb; last 2 as beginning.
The only questionable bit for me is bar 9, where I've heard C or Cm. However it's a blues, so could be either - I play whatever sounds better on the night...
Bass pattern for 8 of the bars is F F Ab Bb C. Other bars follow on appropriate roots.It appears to be in a Dorian mode.
Comment: Realize I'm new with this, but what I think I'm wanting to do is play the 12 bar part through a looper and play rhythm chords on top of it? If that makes sense. Since I'm by myself but want to hear more than the bass. My teacher has me trying to use inversions over it, but I'm just confused..
Comment: OP, can you write down a instance you are dissatisfied with? This is too abstract.
Comment: It's 12 bar blues as Tim pointed out. Please see his answer above. I have recorded the 12 bar bass in Fm, using the 12 bar format. Now I want to play a complimentary rhythm on top of that. So it sounds like two guitars. Listen to an original recording of Steve Cropper playing along with Booker T & The MG's. I hope I'm doing better st explaining.
Answer: It follows a standard blues progression of I IV I V IV I, but it includes other chords, playing the 3rd and 4th chords above the primary chords. The riff plays F5 (or Fm) for the I chord, and riffs Ab Bb, so F5 F5 Ab Bb, then when it changes to the IV chord Bb Bb Db Eb (Db is the third above Bb and Eb is the forth).  On the V chord it goes C Eb F.
Your bass notes should be F Ab Bb C.
Comment: Standard blues progression is mostly 12 bars long - as is Green Onions.

Beginner guitar learning I,IV & V


Overwrite field description in an image widget

Question: I have an image field (multiple).
In the node form, the ImageWiget has a process method that adds previews and form fields for images that have already been uploaded.
The description for the title tag is hard-coded on line 278: '#description' => t('The title is used as a tool tip when the user hovers the mouse over the image.'). We are actually showing the title as a caption and not a tooltip.
How can I override the description?
Comment: Have you found a way around ?
Answer: Using hook_field_widget_form_alter You can do this:
function MYMODULE_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
  if ($context['field']['field_name'] == 'field_image_top') {
    // Loop through the element children (there will always be at least one).
    foreach (element_children($element) as $key => $child) {
      // Add the new process function to the element

      $element[$key]['#process'][] = 'MYMODULE_image_field_widget_process';
    }
  }
}

function MYMODULE_image_field_widget_process($element, \Drupal\Core\Form\FormStateInterface $form_state, $form) {
  // Change the title field label and description

 $element['title']['#description'] = 'SOME NEW DESCRIPTION HERE.';
 return $element;
}

Comment: Unfortunately this answer mixes D7 code `element_children()` with D8 code so it's not working :/
Comment: Try using [\Drupal\Core\Render\Element::children](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element.php/function/Element%3A%3Achildren/) (and note that Element::children returns the array keys)
Answer: Using a hook_form_alter() you will be able to change that '#description' inside the structured $form array.
Comment: Can't find it in D8.9.x $form array


How to generate duplicate records in dataflow with different value

Question: I need to generate a column based on some logic. example:
If Column1=A then Column2='A1' and If Column=A then Column2='A2'
like for one source row, I need to generate 2 rows in dataflow with different values.
for one single records from source, dataflow should populate 2 different values in another column.
how can I achieve this, can anyone help?
Answer:
As per your ask, If Column1=A then Column2='A1' and If Column=A then Column2='A2' like for one source row, I need to generate 2 rows in dataflow with different values. for one single records from source, dataflow should populate 2 different values in column.

To achieve Above scenario, you can follow below steps:

My source dataset is a CSV file in Azure data lake gen2.Source1 .

At DerivedColumn1 activity, we can select the Column2 column and enter expression concat(Column1,'2',',',Column,'1') to generate and concat the values with comma.

At DerivedColumn2 activity, we can select the Column2 column and enter expression split(Column2,',') to split this column to an Array.

At Flatten1 activity, select Column2[] as Unroll by and Unroll root.

The debug result is as follows:
Comment: I am trying this approach but in my case, I have few rows for which I do not want to populate multiple row values. example- If I have 2 rows in source files as A and B, the in column2 I want to populate like for A--A1 and A2(in 2 rows) and for B--B1 (only single row). So If I concat the data then I can have it for only 1 source row and I cannot split as not all column2 has concat value. can you suggest anything in this issue?
Comment: Can you seperate rows for which you want two values and rows for which you want only single value?
Comment: No, I cannot as I have to us that one column to generate primary key in my table..and map it to one single database column
Comment: please add more delails what exactly your reqirements.


What are LS means useful for?

Question: I have recently learned about LS means (estimated marginal means, predicted marginal means) and I am trying to understand what they could be used for and under what circumstances.
For concreteness, consider a dependent variable $y$ and two categorical independent variables, $x_1$ with two categories and $x_2$ with three categories. One could create dummy variables corresponding to these categories and call them $d_{1,1}, d_{1,2}$ and $d_{2,1}, d_{2,2}, d_{2,3}$. One could then have a linear model (without interaction terms)
$$
y = \beta_0 + \beta_{1,2} d_{1,2} + \beta_{2,2} d_{2,2} + \beta_{2,3} d_{2,3} + \varepsilon
$$
where $d_{1,1}$ and $d_{2,1}$ are the reference categories. LS means for $x_1$ would be
\begin{align}
\bar y_{1,1} &= \beta_0 &+ \frac{1}{3}(\beta_{2,2} + \beta_{2,3}), \\
\bar y_{1,2} &= \beta_0 + \beta_{1,2} &+ \frac{1}{3}(\beta_{2,2} + \beta_{2,3}). \\
\end{align}
Uses I can think of
Given $x_1$ and $x_2$, the best (in MSE sense) prediction of $y$ is $\beta_0 + \beta_{1,2} d_{1,2} + \beta_{2,2} d_{2,2} + \beta_{2,3} d_{2,3}$. This is also the expected result after treatment if $x_1$ and/or $x_2$ are interpreted as levels of treatment.
Given $x_1$ alone, the best prediction of $y$ is $\frac{1}{n}\sum_{i=1}^n y_i \mathbb{1}_{d_j=1}$ for $x_1$ being in the category $j$. This is also the expected result after treatment if $x_1$ are interpreted as levels of treatment.
None of these two coincides with $\bar y_{1,1}$ or $\bar y_{1,2}$.
I get that

Least-squares means [are] predictions from a model over a regular grid, averaged over zero or more dimensions

(which is the Wiki excerpt for the lsmeans tag), but is what is the practical use of that?
So far I can see only one situation in which this could be useful; this is if we know that in population the proportion of observations that have $d_{i,j}=1$ and $d_{k,l}=1$ is the same for all combinations of $i,j,k,l$. Is that the intended use of LS means? Or can it be useful for description or hypothesis testing?
Comment: @MartijnWeterings, but the only valid interpretation (AFAIK) is under the assumption that the each category is equally likely in population. Otherwise it is misleading rather than easy to interpret, IMHO. You want effect size? Go for the regression coefficients. You want expected values given just one predictor? Go for conditional means. In this perspective, what question would the LS means be an answer to?
Comment: I agree it is misleading. One could still correct for the unequal distribution, but indeed it remains misleading. It is after all a fictitious value, some artificial construction of combining different groups. Still going back to my initial comment: I don't think that the LS means are so much in use as an alternative expression of the regression coefficients, but more as an alternative to group means (correcting for correlating covariates).
Comment: In this question ( https://stats.stackexchange.com/questions/308556/both-variables-of-my-glmm-output-are-significant-dont-know-how-to-interpret-it ) a person desires some interpretation for the 4 coefficients in a 2x2 model (with cross terms). The summation of the coefficients provides an intuitive interpretation of the outcome of the model. I guess that the LS means do something similar for the case without the cross-term and only main-effects. The LS means solve the problem/question of presenting the model values in a way that is more easy to interpret (the scale is more intuitive).
Comment: I often model `y ~ 0 + x` instead of  `y ~ 1 + x` because I find this intercept term in place of a variable term annoying.
Comment: I guess that this answer, https://stats.stackexchange.com/a/162093/164061 , explaining lsmeans in a very concise way, also provides a very good reason to use these means. You make use of lsmeans when you wish to control for covariates.
Comment: @MartijnWeterings, so far I do not see the added value of LS means over the regression coefficients, but I see added confusion. I know how LS means are calculated, this is not the problem. The problem for me is in interpretation and use.
Comment: Brian Ripley wrote: "Some of us feel that type III sum of squares and so-called ls-means are
statistical nonsense which should have been left in SAS."  https://biostat-lists.wustl.edu/sympa/arc/s-news/1999-05/msg00320.html (But he doesn't say why)
Comment: @RichardHardy It was unclear to me that this was your angle. So if I get it correctly now, you do not wonder so much about the value of LS means, but more specifically about the added value in comparison to regression coefficients. I guess that they are just a different way to express the results of the regression and a different way to present the coefficients. It is a different representation of the model.
Comment: @MartijnWeterings, you got me right this time. The biggest issue so far is the population parameters LS means correspond to, and I do not find such ones. Thus LS means seem kind of artificial to me... I guess this is also what Brian Ripley meant?..
Comment: You could see it as a re-parameterization of the model into:

$$y = \bar{y}_{2,1} d_{2,1} + \bar{y}_{2,2} d_{2,2} + \bar{y}_{2,3} d_{2,3} + 0.5*(\bar{y}_{1,2}-\bar{y}_{1,1}) (d_{1,2}-d_{1,1})+ \epsilon$$

or

$$y = \bar{y}_{2,1} d_{2,1} + \bar{y}_{2,2} d_{2,2} + \bar{y}_{2,3} d_{2,3} +  \left(\bar{y}_{1,1}-\frac{\bar{y}_{2,1}+\bar{y}_{2,2}+\bar{y}_{2,3}}{3}\right) d_{1,1}- \left(\bar{y}_{1,1}-\frac{\bar{y}_{2,1}+\bar{y}_{2,2}+\bar{y}_{2,3}}{3}\right) d_{1,2}+ \epsilon$$
Comment: @MartijnWeterings, Or maybe (given these parameterizations) I should have said that I do not see any interesting question that the LS means would give an answer to.
Answer: I disagree strongly with the "only situation" in the OP. EMMs (estimated marginal means, more restrictively known as least-squares means) are very useful for heading off a Simpson's paradox situation in evaluating the effects of a factor. In your example, consider a scenario where these three things are true:

When $x_2$ is held at any fixed level, the lowest mean response occurs at $x_1=1$.
For $x_1$ held fixed at either level, the highest mean response occurs when $x_2=3$.
The combination $(x_1=1, x_2=3)$ has a disproportionately large sample size, while $(x_1=1,x_2=1)$ and $(x_1=1,x_2=2)$ have small sample sizes.

Then it is possible that the marginal mean of $x_1$ is higher than that for $x_2$, even though the mean for $x_1=1$ is less than that for $x_1=2$ for each $x_2$.
If one instead computes EMMs, the observed means at $x_1=1$ and $x_2=1,2,3$ receive equal weight, so that the EMM for $x_1=1$ is less than that for $x_1=2$.
EMMs are comparable to what is termed "unweighted means analysis" in old experimental design texts. The idea was useful many decades ago, and it still is.
The "basics" vignette for the R package emmeans has a concrete illustration and some discussion of such issues.
Disclaimer
I have spent the last 5 years or so developing/refining R packages for such purposes, so I'm not exactly an objective observer. I hope to hear other perspectives.
Comment: My basic problem remains that this object does not seem to be an answer to any interesting question. Useless objects are typically neither discussed nor even reported, but this one is, suggesting it is not useless. What I am trying to find out is, what use it could have. The uses I have seen so far do not seem to be of any practical interest. Just to note, my intention is not to bash LS means but to understand why they were created. So far I am failing at this. Perhaps Brian Ripley and I just think alike :)
Comment: Suppose you do a controlled experiment and collect 5 observations at each combination of two factors. Then you compute the marginal means. Are you comfortable with that? And what population are you making an inference for? Didn't you define this population by your choice of factor levels and by your choice to run a balanced experiment?
Comment: Thank you for your answer. I am genuinely curious and I do not wish to imply that there is only one situation where LS means are useful. To the contrary, it is the only situation I could come up with independently, and that is it. That is also why I am asking the question. I am now trying to understand your main argument, and the source you refer to is very helpful. Therefore, +1. *EMMs <...> are very useful for heading off a Simpson's paradox situation in evaluating the effects of a factor*. For one, the *regression coefficients* are a great way for evaluating the effects of a factor. ...
Comment: ...Meanwhile, EMMs seem to take this one step forward into a fantasy land (sorry about strong the wording) where the proportion of observations in each category is equal in population. The regression coefficients are straightforward to interpret while the EMMs reflect conditional means of some fictitious population which is different from the one we are dealing with (except when it is not). I could understand the use of EMMs minus the intercept, but it is a bit harder to justify EMMs when the intercept is included. I guess I should not be ranting like that, though :) Once again, thanks!
Comment: I invite you to try an example fitting a model with the default parameterization `contr.treatment`, and then using EMMs and pairwise comparisons. The regression coefficients then estimate comparisons between certain cases. Compare those to the corresponding pairwise comparisons of EMMs. Then notice that you can get all the comparisons easily from the EMMs, whereas you get only some of them from the regression coefficients. The more factors are involved, the less useful the regression coefficients become.
Comment: (mu11 + mu21 + mu31)/3 is a parameter too. Read the paper by Searle, Speed, Milliken. They define EMMs as estimates of population marginal means.
Comment: BTW, that same vignette has a discussion of analysis objectives where EMMs are not useful.
Comment: I've thought about this a bit, and think the fantasy land characterization is probably pretty appropriate. But that seems ok to me. In a lot of ways, any kind of a mean is an abstraction. A community may average 3.79 fire calls per day, for example, even though we can never have that many on a given day. We explain that this is what happens on average, just as we can explain that a certain EMM is the average of three predictions. It's just an average, and it is useful in presenting model results without introducing bias in comparisons thereof.
Comment: Thanks. Still, 3.79 is an estimate of a population parameter for a real population, while LS means is an estimate of population parameters for a fictitious population. This is disturbing, given that we actually have the real population and could easily get an estimate for it, but we choose a fictitious population instead.
Comment: https://www.jstor.org/stable/2684063?seq=1#page_scan_tab_contents
Comment: OK, but for one, I was curious to see why anyone would be interested in this. Moreover, if I were to teach this to my students, I would have trouble finding any logical examples to illustrate this with. This year I skipped LS means because I could not find one. I was hoping for better luck for the next year. I am sorry, perhaps this is getting unproductive, but I appreciate your input.
Comment: So far I am not comfortable with LS means unless they coincide with something else that I am comfortable with. In a balanced case, they coincide with conditional means given just one of the factors, which answers the question "What is the expected result after treatment in a balanced population if I do not know anything about the other factor?". Why would one do a balanced experiment? Either the population is balanced or one wants to estimate the effects on different categories with equal precision. But if the population is not balanced, LS means does not seem to answer any relevant question.
Comment: The equal weights that LS means use are as insensible for an unbalanced population as would unequal weights be for a balanced population. Why would one want to distort the category proportions that are found in the actual population? Think of it this way: why would I use LS means if my categories were severy unbalanced in population? Why should I give such a disproportionately high weight for the smallest categories? LS means neither helps predict the result in absence of the other factor nor measures the "average result" since simple average disregards the imbalance (the two are the same).
Comment: @Richard Hardy: Designed experiments are often used in settings where the population concept itself is artificial. One is studying a process, not a population.
Comment: Years later in reviewing this discourse, I am still surprised by it. I can only refer you to a whole lot of work by giants like Fisher, Yates, Tukey, Box, Snedecor, Cochran, Cox, ... in which balanced experiments are designed and analyzed with equally weighted averages.

What are LS means useful for?


Polynomial And Quadratic equation

Question: Let $p(x)$ be a polynomial of degree grater than 2. If $p(x)$ leaves a remainder $a$ and $-a$ when divided by $x+a$ and $x-a$ respectively, then what is the remainder when $p(x)$ is divided by $x^2-a^2$?
Comment: Shouldn't it be divided by x^2-a^2??
Comment: I edited it to reflect that. If the OP objects, please let us know!
Comment: oh sry my bad its x^2 -a^2
Comment: solution plzz ...
Answer: Hint: the two conditions give $p(-a)=a$ and $p(a)=-a$.
Writing the Euclidian division $p(x)=(x^2-a^2)\,q(x) + r(x)$ the remainder $r(x)$ must be a $1^{st}$ degree polynomial $r(x)=r_1x + r_2$. Evaluate the division equation at $x = \pm a$ to determine $r_1,r_2$.
Comment: got the answer  thanks bro..
Comment: can u explain how do i evaluate the equation at +-a thanks..
Comment: For $+a$ for example: $p(a)=(a^2-a^2)q(a) + r(a)$ which reduces to $-a = r_1 \cdot a + r_2$.
Comment: sry but i cant makeout whats written
Comment: @user383808 You take the division $p(x)=(x^2-a^2)q(x) + r(x)$ and substitute $x=a$. The term $(a^2-a^2)q(a)$ is obviously 0, which leaves $p(a)=r(a)$. You know that $p(a)=-a$, and $r(a)=r_1 \cdot a + r_2$ so in the end you have $-a = r_1 \cdot a + r_2$. Repeat the above for $x=-a$ and you get a 2nd equation in $r_1,r_2$. Solve the system of two equations (in this particular case you can simply add and subtract them) and you get $r_1,r_2$. More hint: $r_1=-1,r_2=0$.

Polynomial And Quadratic equation


HTML: show different sized tables on the same page depending on the user's choice

Question: Is it possible to implement two different sized tables where only one would be displayed on the page depending on the user's choice?
E.g.: user chooses data table which has the following columns: country, price, date, so 3 columns would be displayed.
Then the user chooses the users table with columns: name, email, so now 2 columns would be displayed.
Answer:

const inputs = document.querySelectorAll("input")
const country = document.querySelectorAll('td.country')
inputs.forEach(e => e.onchange = ({
  target: {
    checked,
    name
  }
}) => {
  document.querySelectorAll(`td.${name}`).forEach(e => e.style.display = checked ? "table-cell" : "none")
})
table {
  border-collapse: collapse;
}

td {
  padding: 8px;
  border: 1px solid #777;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>table</title>

        country
        price
        date

        USA
        234
        3-9-2022

        fr
        234
        3-9-2022

        dz
        234
        3-9-2022

what to display :

show country : <input checked type="checkbox" name="country" id="country">

show price : <input checked type="checkbox" name="price" id="price">

show date : <input checked type="checkbox" name="date" id="date">

i think this will do the job ?
Comment: Would this work for 2 different tables? I am not looking to hide a specific column, but rather display a different table (from the one currently shown), with different column names and different column size. So If i select User table, a table with attributes name and email would be displayed. If I select the data table, then another table should be shown, with attributes country, price, date


Generate pseudo random float number between 0.0 (inclusive) and 1.0 (exclusive) in C++/Qt5

Question: I want to generate a pseudo random number between 0.0f (inclusive) and 1.0f (exclusive) in C++ using Qt5.
How can I do this in the recommended/Qt way?
Answer: y can divide a random number by double(RAND_MAX) as following:
srand((unsigned)time(NULL));
for(int i=0;i<10;i++)
{
    cout<<rand()/double(RAND_MAX)<<'\t';
}

Comment: Does that imply there is no Qt spesific way that relates to Qt PRNG?


Proof of divisibility by 7 rules

Question: I am stuck on a problem involved with proving divisibility rules for 7.
Let $n\in \mathbb{N}$ and let $\displaystyle n=\sum_{i=0}^k a_i \cdot 10^i$ be its decimal expression where $a_i\in \{0,1,2,3,4,5,6,7,8,9\}$. Find a necessary and sufficient condition on $\{a_i\}$ so that $7|n$, and please provide proof.
Basically this problem asks you to give a set of rules to predict the divisibility of 7. For instance, for an integer to be divisible by 3, the sum of its digits must be divisible by 3. So I need to get a rule for that. I have wiki'ed the rule and know what it is, but I also need to provide proof. That is where I am stuck.
Comment: I know of at least $5$ tests on divisibility by $7$. You should tell us which one you want to prove.
Comment: http://math.stackexchange.com/questions/328562/divisibility-criteria-for-7-11-13-17-19
Comment: I guess which ever one that is the simplest to prove.
Answer: Here is one divisibility rule:

Remove the last digit, double it, subtract it from the truncated original number and continue doing this until only one digit remains. If this is 0 or 7, then the original number is divisible by 7.

Hint: To prove, use this recursively: $10A+B=10(A-2B) \mod 7$.
Some tests

Proof of divisibility by 7 rules


Finding invert for complicated function

Question: I'm looking for an invert for this function (when x > 0): wolframalpha
Just wondering if there is any chance it exists..
Maybe some numerical methods could help finding it?
Comment: Newton-Raphson?
Answer: Your function is
$f(x)
=log((x*x+9)/(x*x))*sqrt((3*x-x*x*atan(3/x))/atan(3/x))/(-2*x*atan(3/x)+6)\\
=\log\left(\dfrac{x^2+9}{x^2}\right)\dfrac{\sqrt{\dfrac{3x-x^2\arctan(3/x)}{\arctan(3/x)}}}{-2x\arctan(3/x)+6}\\
=\log\left(1+\dfrac{9}{x^2}\right)\dfrac{\sqrt{\dfrac{3x}{\arctan(3/x)}-x^2}}{-2x\arctan(3/x)+6}\\
=\log\left(1+(3/x)^2\right)\dfrac{\sqrt{\dfrac{3}{x\arctan(3/x)}-1}}{-2\arctan(3/x)+6/x}\\
=\frac12\log\left(1+(3/x)^2\right)\dfrac{\sqrt{\dfrac{3}{x\arctan(3/x)}-1}}{-\arctan(3/x)+3/x}\\
$
Letting
$3/x=y$, so $x = 3/y$,
$f(3/y)
=\frac12\log\left(1+y^2\right)\dfrac{\sqrt{\dfrac{y}{\arctan(y)}-1}}{-\arctan(y)+y}\\
=\frac12\log\left(1+y^2\right)\dfrac{\sqrt{\dfrac{y-\arctan(y)}{\arctan(y)}}}{y-\arctan(y)}\\
=\frac12\log\left(1+y^2\right)\sqrt{\dfrac{1}{\arctan(y)(y-\arctan(y))}}\\
=\dfrac{\log\left(1+y^2\right)}{2\sqrt{\arctan(y)(y-\arctan(y))}}\\
$
Letting $y = \tan(z)$,
$f(3/\tan(z))
=\dfrac{\log\left(1+\tan^2(z)\right)}{2\sqrt{z(\tan(z)-z)}}\\
$
Considering that
$\tan(z)-z$
can't be inverted
(at least I don't think it can),
there is,
in my opinion,
no hope of
inverting this.
Comment: Thanks a lot for doing this! I also don't think it can be inverted directly because it is symmetrical about the Y. Was just thinking maybe it makes any difference that we limit the argument to be always positive.

Finding invert for complicated function


How can you take ownership of a hid device?

Question: What I would like to take ownership of a hid device that may already have been plugged in, consume it's output, while preventing others(X11 or terminal) from consuming it.
If I can help it, I don't want to pretend to be a terminal, but rather to monopolize a particular hid or character device. The idea is that some hid devices may be recognized as mice/keyboards by x/terminal, but a second mouse or keyboard  could be used for something else, but to do that you need to make sure they aren't sending spurious input into an open terminal.
Does anyone have any insight as to how this might be done?
Answer: I have done this - my specific application was a daemon that read events from a USB HID barcode reader (which presents as a USB HID keyboard device).
To do this I used the event device interface, opening the /dev/input/event* device corresponding to the device I was after.  You can then issue the EVIOCGRAB ioctl on the device, which grabs it for exclusive use, and read events (which represent keypresses, mouse movements etc) from the device as they become available.
(When the device is grabbed for exclusive use, only your application will see events from it).
Comment: Sounds just what I need for a RFID reader that reads a 10-digit number from a tag and presents the information as a keyboard input so as to use as an access control device in conjunction with a Raspberry Pi Home-automation project - and still be able to log in with a keyboard/mouse/monitor for other (debugging) purposes.
Comment: @MichelL - it is still incomplete but eventually I'll try to make it available in my GitHub repositories - but it will be GPLed 2+ so I don't want to post it here as I've not got to the bottom of exact terms for stuff published here! Basically use `int fd= open( devPathFile", O_RDWR|O_NONBLOCK, S_IRUSR|S_IWUSR )` to open the device and get the file descriptor number `fd`,  then use `ioctl( fd, EVIOCGRAB, 1 )` to grab exclusive use. Don't forget to handle the signals that will close your program so that you can release that exclusivity (though it might happen automatically on application...
Comment: Sometimes I wonder if stackexchange was sent on Earth to save us all ! Is your project Open source ? Do you mind sharing the sources ? I'love to control a few things using custom printed QR-codes.
Comment: @SlySven Is your project Open source too ? Do you mind sharing the sources ?
Comment: @MichelL: I'll see if I can dig up the code but it's nothing super complicated.
Comment: Ok, thank you. I think I will capture the input and send it to a REST webservice. In my case, The input is not fixed-length.
Comment: @SlySven ok, thank you. I'll see how I can handle the events with Qt. I will eventually mix Qt and non Qt code.
Comment: ... exit anyhow!) In my case I then had to write a simple event handler to parse the keyboard events that my RFID receivers produce (as that is what they emulate but we are __intercepting__ the events that are produced so they never get to the kernel's keyboard handler as we desire!)  The events are received from the open file as a number of `struct input_event` and we are particularly interested in those of type `EV_KEY` as defined in `linux/input.h`.
Comment: Perhaps you can - just remember: "we are not inside Qt own keyboard code now, Toto". Oh, and IIRC, you usually have to be root or otherwise privileged to grab devices from the `/dev/` part of the file-system!
Comment: For another example of handling the keyboard events that I presume you will get, the question: "[Accessing Keys from linux input device](http://stackoverflow.com/questions/20943322/accessing-keys-from-linux-input-device)" might give you some more pointers as to the code needed in a handler...
Comment: I have a program that does this in node (not the usb exclusive reading, which is why I'm here). The interesting bits are:  process.stdin.resume();
 process.stdin.on("data", function (chunk) {
  console.log(chunk.toString());
 });
 process.on("SIGINT", function() {
  console.log("Detected Ctrl+C (SIGINT)");
  process.exit();
 });


React accessing setState in callback without arrow function

Question: I am developing code for the corporate intranet.  Once the base was built using arrow functions I tested in Internet Exploder.  Discovering that it will not accept arrow functions.  I am using React for this project and have since refactored all the code to use classic function calls.
It mostly works except for one minor glitch:  I cannot access this from inside the function call.
Here is one example of code, although there are others:
<NavLink onClick={function () {
    this.setState({ openCount: item.pageId });
    this.props.CurrentPage_Update(item)
    }
}
className="menu menu-link"
key={"DDNavLink_" + item.pageId}>
{item.title}
</NavLink>

How can I access the 'this' object for all my function calls?  I tried creating a variable in the order of var set=this.setState; but that failed, although it does work with bound functions.
I am not sure where to go although I have read about babel but am completely agnostic about it's use and function, especially for such a seemingly simple refactor.
Thanks
Answer: At the end of every function call I used .bind(this) to enable the function to use the external this rather than the internal.
//blah blah blah
}.bind(this)

I found that I have to do it at the end of every closing brace if there are any calls to this within the function.  I plan on making it a habit for every classic function call whether it is necessary or not.


UWP Change Grid.HorizontalAlignment to stretch/left using VisualStateManager

Question: I'm having trouble getting the visual state manager to correctly change the HorizontalAlignment/VerticleAlignment of the main grid of my application.
For screen sizes that would be used on phone, I want the HorizontalAlignment/ VerticleAlignment to stretch, with Height/Width set to Auto.
For Desktop it should be Left/Top with Height/Width set to a specific size. For whatever reason when I try to mess with the alignment it acts quirky and does not do what I want
Here is an example of what I have tried:
<code>  <VisualStateManager.VisualStateGroups>
        <VisualStateGroup>
            <VisualState x:Name="PhoneView">
                <VisualState.StateTriggers>
                    <AdaptiveTrigger MinWindowWidth="0"/>
                </VisualState.StateTriggers>
                <VisualState.Setters>
                    <Setter Target="Grid.HorizontalAlignment" Value="Stretch"/>
                    <Setter Target="Grid.VerticleAlignment" Value="Stretch"/>
                    <Setter Target="Grid.Height" Value="Auto"/>
                    <Setter Target="Grid.Width" Value="Auto"/>
                </VisualState.Setters>
            </VisualState>

            <VisualState x:Name="DesktopSmall">
                <VisualState.StateTriggers>
                    <AdaptiveTrigger MinWindowWidth="1920"/>
                </VisualState.StateTriggers>
                <VisualState.Setters>
                    <Setter Target="Grid.HorizontalAlignment" Value="Left"/>
                    <Setter Target="Grid.VerticleAlignment" Value="Top"/>
                    <Setter Target="Grid.Height" Value="1280"/>
                    <Setter Target="Grid.Width" Value="1920"/>
                </VisualState.Setters>
            </VisualState>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>
</code>
Another issue is when I try to set the max resolution to 1920x1280, if I manually set the height/width of the Grid, the Windows TaskBar (the OS taskbar, not the applications app bar/command bar) cuts off part of my application. I don't want to set the alignments to stretch, because I'm trying to limit the real time stretching of the view.
Thanks! Let me know if more details are needed.
Comment: Is `Grid` is your name of your `Grid`? If yes then change it to a different name. If no then Use `Grid` name instead of `Grid`.
Comment: Grid is not the name of my grid. I've been using "Container", so Container.HorizontalAlignment for example.
Comment: I used grid as a placeholder in this example only, so it would be clear that it was a grid I was using.
Answer: It should write like this -
<code><Setter Target="Container.(Grid.HorizontalAlignment)" Value="Left" />
<Setter Target="Container.(Grid.VerticalAlignment)" Value="Top" />
</code>

I have some tips here for creating visual state setters without writing a single line of code.
Comment: Agreed, most likely a bug. If I find a definite fix to it, I will be sure to update this thread. Thank you again for your help.
Comment: I will try that, thank you. I remember now that the nesting is sometimes really strange. Would you have any idea why visual states are not working when the visualstatemanager is placed inside of a Pivot DataTemplate? I've done it with listviews with no problem, but it's acting funky in the pivot.
Comment: You will need to wrap what's in your data template in a `UserControl`. Please see my answer [here](https://stackoverflow.com/questions/32088500/adaptivetrigger-and-datatemplate).
Comment: Ok, so I tried as you suggested and originally it threw an exception. I tried your second method and it seems to be working. The code that it auto writes is:  ``
Comment: I'll also try the UserControl, thanks for the advice!
Comment: That's because the type of your control is not a `Grid` as you mentioned in your question. :) And Yes, `FrameworkElement` will work too. If you think this helps you, consider marking it as the answer.
Comment: I think there may have been miscommunication on my part, apologies. The control "Container" is a Grid, but either way you lead me to the answer so I am grateful. Can I use the method you described to also modify the width of ColumnDefinitions? I can't seem to find that option using the States/Object&Timeline tabs
Comment: Hmm that's weird. Because if it's a Grid then it should just work as Grid inherits from FE.   I also use this piece of code in my project. Regarding column definitions I believe it can be code generated too but I will need to test it out. Will let you know.
Comment: Hmm... Looks like you can change the column/row definitions on the Properties of the Blend Designer, but the value is not recorded in the timeline. So you will have to manually write it unfortunately.
Comment: Came across something strange. I tried to use the automatic method to modify the Horizontal/Verticle alignments just as I did in a test project. For whatever reason, when I go into the Grid's properties, it's not adding the Setter, but instead modifying the actual initial properties. When I tried to do it manually as I did before (which had worked), I get an exception stating that it can't find the property.
Comment: I suspect this is a VS/ Blend bug. Maybe try restarting your VS/Blend.


How to use a same DB with 2 different React applications

Question: I have to make an offline application that sync with another online app when it can.
I developed the offline app using PouchDB. I create this app thanks to the github repo create-react-app. This app is running at localhost:3000. In this app, I create and manage a little DB named "patientDB".
I manage the db with the classical put method like we can see in the documentation:
var db = new PouchDB('patientDB')
db.put({
_id: 'firstname.lastname@example.com',
name: 'David',
age: 69
});

With the development tool for chrome given by PouchDB, I can see that the DB is working like I want (the documents are created):

The other application is another React application with a node server. During the development, this app is running at localhost:8080.
In this app I try to fetch all the docs contained in the "patientDB" with the following code:
const db = new PouchDB('patientDB', { skip_setup: true });
    db.info()
    .then(() => {
    console.log("DBFOUND")
    db.allDocs({include_docs: true})
    .then(function (result) {
      console.log("RESULT" , result)
    }).catch(function (err) {
      console.log("NOPE")
      console.log(err);
    });
    })

My problem is that I can't get the "patientDB" created with the offline app in the online app. When I do a var db = new PouchDB ('patientDB') it create a new and empty db because it can't find a db which is already present.
I use google chrome to run all my application so I thought that the dbs could be shared.
However I did  little and very simple tests with two html files:
First.html which initialize a new db with a doc
Second.html which read the db create in First.html
In this case, I can fetch the doc created with First.html in Second.hmtl even if the are two separated "website".
I think that the application which run at a localhost are like isolated of the rest of the application even if, like I said before, I use the same browser for all my applications...
I don't know what to do or I don't know if it's even possible to do what I want to do. If someone has an idea for me, I would be pleased.

EDIT
I can see why my DBs are not shared:
When I look at all my local DBs after running an html file I can see the following thing :

As we can see, the DBs come from the files _pouch_DB_NAME - file://
When I check my DB from the application running localy (localhost), I can see this :
The DB don't come from file but from localhost:8080

If you know how I can fetch doc from a local db in an app running in a server, it could be really helpful for me!
Answer: PouchDB is using IndexedDB in the browser, which adheres to a same-origin policy. MDN says this:

IndexedDB adheres to a same-origin policy. An origin is the domain, application layer protocol, and port of a URL of the document where the script is being executed. Each origin has its own associated set of databases. Every database has a name that identifies it within an origin.

So you have to replicate your local database to a central server in order to share the data. This could be a PouchDB Server together with your node app. You can also access PouchDB Server directly from the browser:
var db = new PouchDB('http://localhost:5984/patientDB')

As an alternative, you can use CouchDB or IBM Cloudant (which is basically hosted CouchDB).


Find expectation for $x$

Question: for $f(x) = \frac{1}{(x+1)(x+2)}$, $x = 0,1,2,3,\dots$
Find $E(X)$
So far I have got to Summation infinity $x = 0$ to $x = \inf\{\frac{x}{(x+1)(x+2)}\}$
How do you work out the summation? The answer they gave is infinity which doesnt make sense.
Comment: The sum "behaves like" $\sum \frac{n}{n^2}$, and we know the harmonic series diverges.  One can make this more formal in various ways, Limit Comparison, or noting that the denominator is $\le (n+n)(n+2n)$.
Comment: @Drhab Whoops, sorry.
Comment: Your discrete random variable $X$ has PDF $f(x) = \frac{1}{(x+1)(x+2)},$ for $x = 0, 1, \dots.$. You should be able to verify that $\sum_{x =0}^\infty f(x) = 1$. The sum of the first thousand terms is about 0.9990. However, $E(X)$ does not exist because the infinite series $\sum_{x =0}^\infty xf(x)$ diverges. Do you know how to check whether such an infinite series converges or diverges?
Answer: I assume by $f(x)$ you mean the probability mass function of random variable $X$. The definition of the expectation in this discrete setting is $\mathbb{E}(X)=\sum \limits_{x=0}^\infty xf(x) = \sum \limits_{x=0}^\infty \frac{x}{(x+1)(x+2)}$.
This partial fraction may be split as $\sum \limits_{x=0}^\infty (\frac{2}{x+2} - \frac{1}{x+1})$. The first and second terms sum up the same basic fractions starting at different limits and scales. Noting that $\sum \limits_{x=0}^\infty \frac{2}{x+2}= \sum \limits_{x=1}^\infty \frac{2}{x+1} = -2+\sum \limits_{x=0}^\infty \frac{2}{x+1}$, our overall expectation sum simplifies to $\mathbb{E}(X) = -2 + \sum_{x=0} \limits^\infty (\frac{2}{x+1} -\frac{1}{x+1})$.
This is nothing but $-2 + \sum \limits_{x=0}^\infty \frac{1}{x+1}$, and this series is well known to diverge, specifically to $+ \infty$. To see why, visit https://en.wikipedia.org/wiki/Harmonic_series_(mathematics).

Find expectation for $x$