How to add values in rows and pass the result to the next column using pandas?

Question: I have a pandas dataframe with the values as follows:
Start  end   Depart  Duration
  A     B      5           2
  B     C      5           3
  C     D      5           6
  D     E      5           4

I want the output as shown below. I need to add rows of 'Depart' and 'Duration' to form a new column 'Arrive' and pass the result value to the next row in Depart column and then add with Duration to form a value in Arrive and repeat the process again.
I also need to verify if the column values 'Start' is same as the 'End' value in previous row.
Start  end     Depart   Arrive
  A     B        5          7
  B     C        7          10
  C     D        10         16
  D     E        16         20

I tried something like this:
if np.where(d.Start == d.End):
    d['Arrive'] = d['Depart'] + d['Duration']
    d['Depart'] = d.Arrive.shift(1)
    print(d)

The output is as follows. It still takes the original Depart value as 5 and adds up to give the result. Where am I going wrong?
  Start End  Depart  Duration  Arrive
0     A   B     NaN         2       7
1     B   C     7.0         3       8
2     C   D     8.0         6      11
3     D   E    11.0         4       9

Answer: Try using cumsum:
depart = df['Depart'] + df['Duration'].cumsum().shift(1).fillna(0).astype(int)
arrival = df['Depart'] + df['Duration'].cumsum()

df['Depart'] = depart
df['Arrival'] = arrival
df = df.drop('Duration', axis=1)

Output:
>>> df
  Start end  Depart  Arrival
0     A   B       5        7
1     B   C       7       10
2     C   D      10       16
3     D   E      16       20

Comment: Thanks. This is what I need! But how do I add if condition to compare the start and end values?


Spoken languages in team radio

Question: I can recall moments from a few years ago when Fernando Alonso would be communicating with his race engineer Andrea Stella in either Italian or English, or sometimes even a mix of both, and they'd play it back that way on team radio.
Nowadays in F1, radio communications in the teams' native languages are noticeably absent.

Has there been any recent regulations that restrict F1 teams and drivers to communicate only in English whenever they are out on track?
Answer: On official limitations on radio communication there are no indications as to the language to use, so I believe that there are no restrictions in this regard
I can add that all pit to car radio transmissions must be open and accessible to both the FIA and broadcasters.

Spoken languages in team radio


Using hook_form_alter() to prevent free email addresses from registering on a Drupal 6 site

Question: I have been tasked with blocking specific email address domians from registering at our Drupal 6 site (gmail.com, aol.com & yahoo.com). I implemented some JQuery code to do this but the problem was that spammers with javascript disabled in their browser readily bypassed this prevention.
I also cannot use Drupal 6's Access Rules as we already have registered users on the site with those domains so this method blocks them from logging in so it's more of a going forward prevention that we would like to implement.
I found this code on Stack Overflow but the code was somewhat incomplete:
function example_data_form_user_register_alter(&$form,&$form_state) {
  $form['mail']['#element_validate'] = 'example_mail_validate';
}

function example_mail_validate($element, &$form_state) {
   if ( -- Whatever condition you like -- ) {
     form_error($element, t('Free email is not allowed.'));
   }
}

I thought it would be better to open a new question on this forum since it's Drupal specific.
I think what I need help with is filling in the gap where in the code it says: -- Whatever condition you like --
I am not a PHP guru so any help would be appreciated. I assume this is the spot where I would have some code that disallows the domains that I want to block.
Answer: A very simple example would be:
function example_mail_form_user_register_alter(&$form,&$form_state) {
  $form['mail']['#element_validate'] = array('example_mail_validate');
}

function example_mail_validate($element, &$form_state) {
   //block gmail addresses
   if (stripos($form_state['values']['mail'], 'gmail.com') > 0) {
     form_set_error('mail', t('Free email is not allowed.'));
   }
}

However you should lookout for more advanced solutions:

Simple email verification: email verify
http:BL

http:BL can prevent email address harvesters and comment spammers from
  visiting your site by using a centralized DNS blacklist.
Mollom which also prevent spam on all your content/comments forms.
Comment: Your problem is most likely what is  mentioned in your code comment. The code "array('prevent_emails_mail_validate');" should refer to the function below, which is now called: prevent_emails_email_validate. The extra e means drupal doesn't find the function, and validation fails.
Comment: Thanks for all the links, I will check those out. I created a custom module from the code above and substituted my module name for "example", activated the module and cleared my cache. However, it did not work. I have a pastebin started to see if we can work on the code a little further. http://pastebin.com/0C6LbpFK -- thanks.


Elegant Proof of the Product of Two Levi Cevita Tensors

Question: Is their an elegant way to prove the product of two Levi Cevita tensors is equivalent to a determinant of a matrix of Kronecker deltas? I know that the anti-symmetry and cyclic nature should be easily proved via determinant row-interchange laws, but is the proof inelegant when it comes to showing it zeroes out when two indices are repeated?
The property in mind is: $$\epsilon_{ijk}\epsilon_{lmn}=\det\left|
   \begin{array}{cccc}
      \delta_{il}   & \delta_{im}  & \delta_{in}   \\
      \delta_{jl}   & \delta_{jm}  & \delta_{jn}   \\
      \delta_{kl}   & \delta_{km}  & \delta_{kn}
   \end{array}
\right|
$$
Comment: Does antisymmetry not prove that it zeroes out when two indices are repeated?
Comment: I didn't mean to say antisymmetry, I only meant the sign flipping.
Answer: The determinante of $\left(A_{ij}\right)$ is defined by Leibniz as
$$\det \left(A_{ij}\right) := \sum_{\sigma}\text{sign}(\sigma)\Pi_i A_{i,\sigma(i)} $$
With permutations $\sigma$ and their sign $\text{sign}(\sigma)$ ($=+1$ if Permutation is an even of $1,2,3,4,...$, $-1$ if pertutation is odd, $0$ else)
This can be simplified with
$$\det \left(A_{ij}\right)=\epsilon_{i_i,i_2,..}A_{1,i_1}A_{2,i_2}A_{3,i_3}\cdots $$
Introducing base vectors $e_i$ of a $n$ dimensional vector space  with $i=1,2,...,n$ and $e_ie_j=\delta_{ij}$ (Here $n=3$)
Than you can write your Matrix
$$\begin{pmatrix}      \delta_{il}   & \delta_{im}  & \delta_{in}   \\
      \delta_{jl}   & \delta_{jm}  & \delta_{jn}   \\
      \delta_{kl}   & \delta_{km}  & \delta_{kn}\end{pmatrix}=
\begin{pmatrix}e_i^\top\\e_j^\top\\e_k^\top\end{pmatrix}\begin{pmatrix}e_l&e_m&e_n\end{pmatrix}$$
The determinant of a matricies build of vectors is now
$$\det\begin{pmatrix}e_i^\top\\e_j^\top\\e_k^\top\end{pmatrix}=\epsilon_{ijk}\qquad \det\begin{pmatrix}e_l&e_m&e_n\end{pmatrix}=\epsilon_{lmn}$$
Using the product rule of determinats
$$\det\begin{pmatrix}      \delta_{il}   & \delta_{im}  & \delta_{in}   \\
      \delta_{jl}   & \delta_{jm}  & \delta_{jn}   \\
      \delta_{kl}   & \delta_{km}  & \delta_{kn}\end{pmatrix}=\det\begin{pmatrix}e_i^\top\\e_j^\top\\e_k^\top\end{pmatrix}
\cdot\det\begin{pmatrix}e_l&e_m&e_n\end{pmatrix}=
\epsilon_{ijk}\epsilon_{lmn} $$
PS. I am using the notation $\left(A_{ij}\right)$ is the matrix with bound indicies and $A_{ij}$ are their elements.
PPS. This calculation can also be found on http://de.wikipedia.org/wiki/Levi-Civita-Symbol


Normal distribution and two tailed tests

Question: do we have to assume normal distribution in order for two tailed tests?
Eg: According to the Australian Bureau of Statistics, the quantity of waste ending up in municipal landfills amounts to 0.80 kg per person per day. Some claim that because of recycling and greater emphasis on the environment, this figure is now lower. Others contend that constant increases in packaging and other life-style developments have pushed this figure higher in spite of recycling efforts. To test whether the amount of garbage per person has changed, a random sample of 54 Australians was taken and they were asked to keep a log of their garbage for a day. The sample mean was 0.92 kg.
Population standard deviation is 0.5 kg, and that the amount of garbage per person per day is normally distributed, use the sample data to determine whether there is sufficient evidence at the 5% level of significance to assert that the amount of garbage per person per day has changed.
Q)Is the assumption that the amount of garbage is normally distributed necessary in order to perform this test?
Answer: Because you're looking at the mean, you can rely on the central limit theorem that says that the distribution of the mean is Normally distributed. The strength of the central limit theorem is that it works for most underlying distributions; thye don't have to be Normal. It is, however, an approximation that gets better as the sample size increases. How large your sample size needs to be depends on the kind of underlying distribution you have. As the comment says, there are some underlying distributions for which the central limit theorem doesn't work.
Comment: Well, if the distribution is Cauchy, then everything is hopeless. The mean is a lie.


What is the meaning of "Points" in ICC rankings?

Question: Today I check the ranking of test cricket.

What is the meaning of points, as Sri lanka have third highest point however they are 6th ranked team?
Answer: The points are the raw accumulation of marks from the ranking system. Since teams only win points, not lose them, teams which have played more matches will tend to have more points, even if they've also lost more matches. This point score is then averaged by dividing through by the number of matches to provide the rating.
As explained by another page on the site, the points gained are are a combination through a mathematical formula of the results of the matches in a series and the relative strength of the teams, so that a team gains more points for beating a high rated team than a low one. This is similar to the Elo rating scheme developed in chess and now being applied to other sports.
The precise scheme (from Wikipedia) is

Award 1 mark to a team for each match won.
Award ½ mark to a team for each match drawn or tied.
Award 1 bonus mark to the team winning the series.
Award ½ bonus mark to each team if the series is drawn.

The ratings points awarded are then:
If teams rating difference less than 40:
(team's own mark) x (opponent's rating+50)
+
(opponent's mark) x (opponent's rating−50)
If teams rating difference more than 40:
The ratings points for the stronger team equals:
(team's own mark) x (team's own rating + 10)
+
(opponent's mark) x (team's own rating−90)
The ratings points for the weaker team equals:
(team's own mark) x (team's own rating+90)
+
(opponent's mark) x (team's own rating−10).


Linear regression with Cauchy distribution for errors

Question: I have ran the below linear regression model and using the performance package in R I however checked whether the distribution of the residuals is normal. The performance package suggests I should be using a Cauchy distribution for the errors. In a search of stats.stackexchange and Google, it isn't clear how to do this. How can I model the data below using a Cauchy distribution for errors?
library(performance)

c(7L, 50L, 12L, 20L, 6L, 12L, 30L, 3L, 21L, 43L, 42L, 35L, 18L, 6L, 23L, 16L, 8L, 43L, 10L, 24L, 19L, 30L, 13L, 9L, 6L, 17L, 46L, 14L, 8L, 25L, 16L, 9L, 28L, 11L, 3L, 28L, 38L, 37L, 6L, 25L, 27L, 24L, 5L, 1L, 9L, 4L, 14L, 22L, 0L, 11L, 17L, 1L, 5L, 37L, 52L, 16L, 2L, 0L, 12L, 13L, 2L, 16L, 8L, 2L, 3L, 15L, 23L, 24L, 1L, 18L, 17L, 18L, 3L, 40L, 2L, 32L, 24L, 17L, 1L, 2L, 3L, 30L, 17L, 5L, 33L, 15L, 19L, 20L, 3L, 0L, 2L, 2L, 8L, 18L, 7L, 3L, 18L, 0L, 17L, 20L) -> dependent.var

c(4.66666666666667, 75, 28, 6, 1.83, 38.36, 80, 0, 14, 107, 137, 94.75, 36, 10.8666666666667, 44, 27, 32, 86, 52.8333333333333, 108, 76.5, 54, 26, 23.75, 11.75, 33.2133333333333, 100, 58, 50, 94, 32.25, 16, 33.75, 29.25, 7.75, 100, 98, 58.45, 4.58, 56, 59, 73.4166666666667, 6.16666666666667, 1, 53.79, 41.95, 43.25, 70.5, 0, 10, 3.25, 0, 14, 98, 112, 35, 0.25, 16.25, 30.83, 68, 1.25, 30.25, 13.25, 11.1, 1.5, 41, 45.17, 40, 6, 52.8566666666666, 43, 41, 3, 131, 0, 45.67, 74, 25.4166666666667, 0.25, 4.75, 14.58, 2.75694444444444, 32, 0, 92.25, 34, 66, 14, 1.75, 1.5, 1, 21.53, 4.08333333333333, 44.07, 55.9, 12, 20, 12.5, 48.1333333333333, 24.03) -> independent.var

lm(dependent.var ~ independent.var) -> model

check_distribution(model)

# # Distribution of Model Family
#
# Predicted Distribution of Residuals
#
#  Distribution Probability
#        cauchy         53%
#        normal         41%
#           chi          6%
#
# Predicted Distribution of Response
#
#                Distribution Probability
#  neg. binomial (zero-infl.)         59%
#               beta-binomial         34%
#                 half-cauchy          3%

Comment: Does this package have any citations for the method used? My glance at it made it look like the answer is in the negative, and that leaves me reluctant to trust its output. The closest I found was the function documentation saying that it uses a random forest to classify the residuals into a distribution and that the algorithm for doing this might be improved in the future, but there was not a citation of a peer-reviewed article or conference paper, not even a working paper on `arXiv`. Anyone can upload a package to `CRAN` as long as it compiles; `CRAN` does not check the statistics aspects.
Comment: What are these data?  They seem to be only non-negative whole numbers.  The normality of the residuals is generally the least important assumption in an OLS model.  Even if the errors truly are Cauchy, the model fit should be fine.  It's the SE's (& thus, CIs & p-values) that would be affected.  There are robust methods to get a test, if that's what you want.  What is the point of this model?
Comment: @luciano that is not a good assumption to make for a general R package. as dave said, anyone can put code on CRAN, that doesn't mean the code implements a useful statistical method.
Comment: @wzbillings I completely agree by the way with your assessment that it's not good idea to use the `check_distribution` function blindly (at all, probably). So not sure what point I'm trying to make other than its authors are not random people who don't know what they are doing. It was reminded of [fortune](https://cran.r-project.org/web/packages/fortunes/index.html) #386: "If we put in a function into rstan that dropped chains, people would use it.".
Comment: Plotting the data makes me even more skeptical about the package output. The [QQ plot](https://i.stack.imgur.com/L7bC6.png) is not great but is not so awful to suggest infinite variance, and [a scatterplot of the data themselves](https://i.stack.imgur.com/llK0N.png) looks like a fairly routine linear trend.
Comment: It is not obvious that the package authors wrote a paper on checking residuals this way, either. Do they have any citations for their work? Peer-reviewed articles and conference presentations would be best, but even an arXiv preprint would be nice, yet that function gives no such reference.
Comment: The original implementation issue on the package GitHub (https://github.com/easystats/performance/issues/60) also does not cite any source so I am not inclined to believe that this method is rigorous or verified.
Comment: I haven't written a paper on checking distribution of residuals either. And I bet the package authors are more experienced than me. So more inclined to trust their judgement  rather than my own.
Comment: I find it amusing there is a discussion that "anyone can put code on CRAN" as relates to the `performance` package. But not about the `heavy` package, which isn't even on CRAN anymore.
Comment: @dipetkov that's a good (and fair) point. but the code for `heavyLm()` at least cites statistical references to the method that is used for fitting -- which is what we're debating about the `performance` package.
Answer: This question raises a couple of interesting points:

In a comment, @Dave points out that the normal QQ plot is "not so awful to suggest infinite variance".
In an answer (+1), @wzbillings points out that it's not clear what theory (if any) the performance package uses to justify the Cauchy distribution for the errors.

As @Dave advises, let's look at the data first. (I've renamed the independent variable $x$ and the dependent variable $y$ for clarity.)

Clearly both variables are nonnegative (and in fact the values are mostly integers but the OP hasn't provided many details about the data). The relationship between $x$ and $y$ is reasonably linear and the variability of $y$ doesn't appear to increase for large $x$. Except near the origin both variables are constrained and that "squeezes" the residuals: their variance is lower for $x$ close to 0 and as a result the distribution of the residuals is heavy tailed.
Rather than choose between the Normal and the Cauchy distribution for the errors, let's fit a simple linear regression with $t$-distributed errors. And we will use theory to explore what degrees of freedom, $\nu$, are most consistent with the data. (Recall that the Cauchy is equivalent to $t$ distribution with $\nu = 1$ degree of freedom and the Normal is equivalent to $t$ with infinitely many degrees of freedom.)
The idea is to compute (numerically) the profile likelihood $L(\nu)$ for the degrees of freedom parameter $\nu$.
We start by writing down the likelihood of all four parameters in a simple linear regression with $t$-distributed errors:
$$
\begin{aligned}
L(\beta_0,\beta_1,\sigma,\nu) = \prod_i f_\nu\left(\frac{y - (\beta_0 + \beta_1x)}{\sigma}\right) \times \frac{1}{\sigma}
\end{aligned}
$$
where $f_\nu$ is the density of the $t$ distribution with $\nu$ degrees of freedom and $1/\sigma$ is the Jacobian of the transformation $y_0 = (y - \mu)/\sigma = (y - \beta_0 - \beta_1x)/\sigma$.
Then we find the profile likelihood $L(\nu)$ of the degrees of freedom parameter by maximimizing the likelihood $L(\beta_0,\beta_1,\sigma,\nu)$ with respect to $\beta_0,\beta_1$ and $\sigma$. (Actually, we minimize the negative log likelihood; see R code below.)
$$
\begin{aligned}
L(\nu) = \max_{\beta_0,\beta_1,\sigma} L(\beta_0,\beta_1,\sigma,\nu)
\end{aligned}
$$
And here is the plot of the profile likelihood.

A couple of conclusions from this analysis:

The profile likelihood $L(\nu)$ is maximized at $\nu = 4$ but anything between 3 and 5 degrees of freedom is a good fit to the data.
As @Dave claimed, the Normal distribution ($\nu \approx 30$) is a better fit than the Cauchy distribution ($\nu = 1$).

References
[1] In All Likelihood: Statistical Modelling And Inference Using Likelihood. Y. Pawitan. Oxford University Press (2013)
[2] A note by @kjetilbhalvorsen about the dangers of maximum likelihood estimation for the degrees of freedom of the $t$ distribution. The warning is about small sample sizes in particular while in this case $n = 100$, so the profile likelihood approach is probably okay.

# Requires data x and y
n <- length(y)

m0 <- lm(y ~ x)

library("nloptr")

minimize <- function(x0, func, lb = NULL, ub = NULL) {
  opts <- list(
    "algorithm" = "NLOPT_LN_SBPLX",
    "xtol_rel" = 1.0e-6
  )
  a <- nloptr(x0, func, lb = lb, ub = ub, opts = opts)
  list(x = a$solution, fx = a$objective)
}

negloglik <- function(beta0, beta1, sigma, nu) {
  mu <- beta0 + beta1 * x
  y0 <- (y - mu) / sigma
  # Calculate the log likelihood for y0
  ll <- sum(dt(y0, nu, log = TRUE))
  # Add the log of the Jacobian
  ll <- ll - n * log(sigma)
  # Calculate the negative log likelihood foy y
  -ll
}

beta0.hat <- m0$coef[1]
beta1.hat <- m0$coef[2]
sigma.hat <- sigma(m0)

profile <- function(nu) {
  sapply(nu, function(nu) {
    soln <- minimize(
      c(beta0.hat, beta1.hat, sigma.hat),
      function(params) negloglik(params[1], params[2], params[3], nu),
      lb = c(-Inf, -Inf, 0),
      ub = c(Inf, Inf, Inf)
    )
    soln$fx
  })
}

nu <- seq(1, 30, by = 0.25)
nll <- profile(nu)
ll <- exp(min(nll) - nll)

plot(nu, ll,
  type = "l",
  xlab = quote(paste("degrees of freedom, ", nu)),
  ylab = quote(L(nu)),
  main =  quote(paste("Profile likelihood L(", nu, ")"))
)
abline(h = 0.15, lwd = 0.3)

Answer: I don't really like this approach to determining the model family, I think it should be set a priori instead of using this machine learning method that this package uses with no citations to methodological papers. But that isn't the question.
You could use the function heavy::heavyLm() with a t-distribution family and manually set the degrees of freedom to 1. (Note that this package is not on CRAN: https://github.com/faosorios/heavy)
Update: apparently the package also has a built-in Cauchy family for heavyLm(), so you could use that also. They should work out the same (to a meaningful level of precision anyways).
Comment: [Stack Overflow supports your suggestion to use the `heavy` package.](https://stackoverflow.com/questions/69029710/glm-with-cauchy-family)
Comment: The criticism about the `performance::check_distribution` function is not mis-misplaces but still the documentation states: "This function is somewhat experimental and might be improved in future releases. The final decision on the model-family should also be based on theoretical aspects and other information about the data and the model." So fair to say that the package authors are clear about the pitfalls.
Comment: @dipetkov I'm not sure I agree, I think that "this is experimental and may be improved" and "this method has no empirical or theoretical evidence to suggest it does what it is supposed" are not the same thing


Using htaccess to rewrite unless ending in a file extension

Question: How would we use the htaccess file to rewrite all URLs to index.php unless they end in a file extension.
The following:
RewriteEngine on
RewriteRule ^index.php$ - [L]
RewriteRule ^(.*)$ index.php [L,QSA]

Is rewriting everything. If the file ends in .php / .jpg / .css / .js etc.... etc... I would like it not to redirect and instead go to that file.
How is that done?
Answer: I think this is it but would appreciate some Feedback:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [L]
</IfModule>


'cl' is not recognized as an internal or external command,

Question: I am trying to compile a hello world program in Qt Using Qt Creator.
I am getting 'cl' is not recognized as an internal or external command.
I am using Windows 7 and both VS 2008 and 2010 installed in it.
When I use Mingw it is compiling fine but if use vs 2008 it is giving this error.
After Setting Env Path = ..;..;C:\Program Files\Microsoft Visual Studio 9.0\VC\bin also it is showing the same error.
Comment: Check if your compilation toolchain for VS2008 in your `PATH`.
Comment: @ereOn In the tool chain c:\Program Files\Microsoft Visual Studio 9.0\VC\bin\vcvars32.bat
Comment: See answer for http://stackoverflow.com/questions/6476607/vc-cl-exe-dll-not-found
("Run the VS command prompt shortcut")
Answer: That error happens because cl isn't in your path. You need to add it there. The recommended way to do this is to launch a developer command prompt.
Quoting the article Use the Microsoft C++ toolset from the command line:

On the desktop, open the Windows Start menu. In Windows 11, choose the All apps button to open the list of installed apps. In Windows 10,
the list is open to the left. Scroll down the list to find and open
the folder (not the app) for your version of Visual Studio, for
example, Visual Studio 2022.

In the folder, choose the Developer Command Prompt for your version of Visual Studio. This shortcut starts a developer command
prompt window that uses the default build architecture of 32-bit,
x86-native tools to build 32-bit, x86-native code. If you prefer a
non-default build architecture, choose one of the native or cross
tools command prompts to specify the host and target architecture.

For an even faster way to open a developer command prompt, enter
developer command prompt in the desktop search box. Then choose the
result you want.

As the article notes, there are several different shortcuts for setting up different toolsets - you need to pick the suitable one.
If you already have a plain Command Prompt window open, you can run the batch file vcvarsall.bat with the appropriate argument to set up the environment variables. Quoting the same article:

At the command prompt, use the CD command to change to the Visual Studio installation directory. Then, use CD again to change to the
subdirectory that contains the configuration-specific command files.
For Visual Studio 2019 and Visual Studio 2017, use the
VC\Auxiliary\Build subdirectory. For Visual Studio 2015, use the VC
subdirectory.

Enter the command for your preferred developer environment. For example, to build ARM code for UWP on a 64-bit platform, using the
latest Windows SDK and Visual Studio compiler toolset, use this
command line:
vcvarsall.bat amd64_arm uwp

From the article, the possible values for the first argument are the following:

x86 (x86 32-bit native)
x86_amd64 or x86_x64 (x64 on x86 cross)
x86_arm (ARM on x86 cross)
x86_arm64 (ARM64 on x86 cross)
amd64 or x64 (x64 64-bit native)
amd64_x86 or x64_x86 (x86 on x64 cross)
amd64_arm or x64_arm (ARM on x64 cross)
amd64_arm64 or x64_arm64 (ARM64 on x64 cross)
Comment: Finally found something that actually works !
Answer: I had the same problem.
Try to make a bat-file to start the Qt Creator. Add something like this to the bat-file:
call "C:\Program Files\Microsoft Visual Studio 9.0\VC\bin\vcvars32.bat"
"C:\QTsdk\qtcreator\bin\qtcreator"

Now I can compile and get:
jom 1.0.8 - empower your cores
11:10:08: The process "C:\QTsdk\qtcreator\bin\jom.exe" exited normally.

Answer: Make sure you restart your computer after you install the Build Tools.
This was what was causing the error for me.
Answer: I had the same problem and I solved it by switching to MinGW from MSVC2010.
Select the Project Tab from your left pane. Then select the "Target". From there change Qt version to MinGW instead of VC++.
Comment: This finally helped me to realize that anaconda supplies an old version of `scons` that does not support VS2013 (VC12). I used `conda install -c https://conda.anaconda.org/bryanwweber scons` to update and now it works fine :)
Answer: I had this problem because I forgot to select "Visual C++" when I was installing Visual Studio.
To add it, see: https://stackoverflow.com/a/31568246/1054322
Answer: You will have to set environmental variables properly for each compiler. There are commands on your Program menu for each compiler that does that, while opening a command prompt.
Another option is of course to use the IDE for building your application.
Answer: I had the same issue for a long time and I spent God knows how much on it until I accidentally figured what to do. This solution worked on windows 10. All you need to do is to add C:\WINDOWS\System32 to Path variable under User Variables in Environmental Variables... Note that if you add this to the system variables, it may also work. But, that didn't work for me.
Answer: You can use Command prompt for VS 2010 and then select the path that your boost located. Use "bootstrap.bat", you can successfully install it.
Answer: For me, this was related to the scenario described by Smi, with the difference being that vcvarsall.bat itself was failing due to an invalid path.
This was cause by line-breaks within the path, which meant vcvarsall.bat couldn't find the common tools directory for some reason.
Answer: I sometimes get this problem when changing from Debug to Release or vice-versa. Closing and reopening QtCreator and building again solves the problem for me.
Qt Creator 2.8.1; Qt 5.1.1 (MSVC2010, 32bit)
Answer: I faced this error too, checked that there are multiple versions of common tool variables for visual studio in my environment variables (VS120COMNTOOLS, VS110COMNTOOLS and so on) for different visual studio versions.
I removed the ones I did not need from the environmental variables and the issue was resolved.
Answer: I was facing the same issue and tried many solutions but nothing work ( I was using vscode 2017) . I just upgraded vscode to 2022 version and the problem is automatically
Comment: This does not really answer the question. If you have a different question, you can ask it by clicking [Ask Question](https://stackoverflow.com/questions/ask). To get notified when this question gets new answers, you can [follow this question](https://meta.stackexchange.com/q/345661). Once you have enough [reputation](https://stackoverflow.com/help/whats-reputation), you can also [add a bounty](https://stackoverflow.com/help/privileges/set-bounties) to draw more attention to this question. - [From Review](/review/late-answers/32679788)


Security group for a changing aws instance via external ip address

Question: PLEASE NOTE: port 22 is just an example port there will be instances when it is not port 22 I am trying to deal with.
Security Groups
"server-1" has a security group "group-1"
"server-2" has a security group "group-2"
"server-1" has an elastic ip address assigned to it i.e 111.222.333.444

and
"group-2" is allowed to connect to "group-1" via port 22

So if I ssh from server-2 to server-1 via the following command
ssh -iKEY.pem email@example.com

the connection is fine, works as expected.
If however I try and connect via this command.
ssh -iKEY.pem email@example.com

It does not work for what I assume are obvious reasons
I have left the aws network in order to connect to the server-1 and therefore aws sees the connection from server-2 as an external resource and no longer an aws instance. This means it will not use the Security group that says:
"group-2" is allowed to connect to "group-1" via port 22

Actual Problem
I want to connect to server-1 via the ElasticIP address so I can happily reboot server-1 and/or server-2 and not have to worry that the aws instance name/ip address has changed i.e the domain name in the first ssh example will change on a reboot/new instance taking over.
So my question really is what is the best practice way to do this. The options I can see at the moment are:

Do a reverse dns look up of the ElasticIP address and connect using this domain name
form server-2 to server-1
i.e the Elastic ip address is 111.222.333.444 and the reverse look up will return me
ec2-111-222-333-444.eu-west-1.compute.amazonaws.com
I cannot relay on building this manually as I also need to know what availability zone the instance is in in order to do that (I would like very much not to care about where it is).
I would assume there is a aws api call I can do to grab the current instance name that is attached to the ElasticIP address. Iam not overly kean on the application knowing it is on an aws server and would like to keep away form the api.
Use vpc instances within aws. This way I can always attach the same private ip address to server-1 and connect to it reliably even after a reboot of either server. This however appears to come with a lot of configuration and maintenance.
I could manually update any config settings pointing to the server-1 after a reboot (this is not a series suggestion).
Open server-1 port 22 to the world (NOTE: I want to open other ports as well not just 22) and worry about the application doing the authentication. (again not really a sensible option as if I want to open port 80 to server-2 then have to use .htaccess or alike to authenticate the connection, therefore just moving this issue and not really solving it).

The problem I have with options 1 and 2 are that I have to always do these lookups which produces massive over head on an application or I cache it and have to live with the fact that if the instance of server-1 changes i.e a reboot occurs then there is a time when server-2 will will not be able to connect to server-1 till it de-caches the instance name.
Option 3 is probably the best solution however it comes with configuration and maintenance that is time consuming and needs extra knowledge within our company.
Does anyone have an other suggestion that will work?
Answer: Given your requirements, I would agree that using a VPC is the most optimal solution.  Since it sounds like you've done your research, you know that a VPC allows much finer-grained control over subnet and host addressing.  To answer your question, that is the "best practices" approach.
What I would do is create two private subnets, one in each AZ, and place an Elastic Network Interface with a static, private IP address in each subnet.  Then you can attach/detach the ENI to the appropriate instance at will.  This allows some cool stuff and functions like hot-swapping a NIC between servers while traffic is still flowing through it.  Yes, there is a significant learning curve with setting up a VPC, but the tradeoff is greatly increased security and flexibility when using multiple EC2 instances that need to talk to each other.
It's worth noting that utilizing the AWS API (as you also mentioned) is also a viable solution for your immediate needs.  But the further you go down this path of writing a custom solution, the more time consuming it becomes to maintain as your needs grow.
Comment: Thanks that is exactly the answer I was expecting. I just wanted to make sure before I dive into VPC and find it was a waste of time. Thanks
Answer: The AWS api method to look up the instance's public dns is this:
http://169.254.169.254/latest/meta-data/public-hostname

(It's an AWS internal ip, not an external service.)
But as for the root of the issue, the public DNS for an Elastic IP is supposed to be permanently associated with that Elastic IP, regardless of reboots/new instances that it points to. All my Elastic IP public DNS look like ec2-11-22-33-44.compute-1.amazonaws.com. How come you have a region in the public DNS? What does it return with the api above?


update a spree product's price from rails console

Question: somewhat related to 1
How update a spree product's price from rails console?
what I tried:
irb(main):011:0> pp Spree::Product.last.display_amount.to_s
=> "$13.99"
irb(main):012:0>

Answer: Spree::Product.last.update(price: '1')


Return response from API and perform some other actions at the API level

Question: I am using jax-rs jersey for Rest API. I need API endpoint which needs to send response and perform some extra action after returning response which is updating the global variable. How can I achieve it?
I tried using Executor to execute a time taking task, expecting the API would return the Response and then execute this task, but the client using my API seems to be in hanged state.
Moreover, I found AsyncResponse using @Suspended annotation, but my intention is not to send the response again after the initial response. The updated stuff will only be used when the client requests again.
global_var = 0;
execute.execute(() -> {
                        for (int i = 0; i < 20; i++) {
                            try {
                                logger.error("In executor service "+i);
                                Thread.sleep(1000);
                                global_var +=i;
                            } catch (InterruptedException ex) {
                                logger.error("Exception while sleep " + ex.getMessage());
                            }
                        }
                    });
return Response.ok(global_var).build();

Expecting API will return global_var as 0 initially, later when again the request comes from client, it will send the updated global_var value.
But the API is in hanged state even on the first request
Answer: Dont use execute.execute(()
use executor.submit()
Depending on implementation, execute can be done on calling thread instead of background one.


Apache 2.4 - allow access from same IP and from curl Request

Question: I want to provide access to requests from the same server that apache is running on and to curl requests, but this section does not work, neither the first nor the second match. What am I doing wrong?
 <LocationMatch "^/myLocation">
   <If "%{HTTP_REFERER} == 'localhost'">
     Require all granted
   </If>
   <ElseIf "%{USER_AGENT} =~ /curl/ >
     Require all granted
   </ElseIf>
   <Else>
     Require all denied
   </Else>
 </LocationMatch>

Answer: Normally you shouldn't base access controls on either the HTTP_REFERER header   nor the USER_AGENT header ; both are set by the site visitor and can't be trusted, any  (malicious) user can manipulate those.
Second, to provide access to requests from the same server, that depends a bit on how you make them.

Are you making requests to http://localhost/myLocation - then requests will also originate from localhost you can base access controls on the 127.0.0.1 and/or [::1] IP-address.
Are your making requests to the external IP i.e. http://www.example.com/myLocation then you need to add your external IP-address.

Rather than an if-then-else construction Apache httpd offers the RequireAny directive to achieve what you want:
<Location /myLocation>
   <RequireAny>
       Require ip 127.0.0.1
       Require expr %{HTTP_REFERER} == 'localhost'
       Require expr %{HTTP_USER_AGENT} =~ /curl/
   </RequireAny>
</Location>

Comment: Yes, it's supposed to be low-level security, rather to be safe from ambitious users in the intranet than to russian hackers.


Prove that $2^{n} s$ can be written as the sum of perfect squares, where $s$ is the sum of perfect squares

Question: I need require assistance in proving that $$2^{n} s$$ can be written as the sum of two perfect squares, where $$s$$ is a sum of two perfect squares. My teacher has told me I'm not allowed to use induction and I'm not really sure how to go about it.
If anyone could nudge me in the night direction, I'd be appreciative.
Comment: Hint: Think about the case when n is even and the case when n is odd
Comment: Because you say you have trouble when $n$ is even, I thought it might help to remind you that $0$ is a perfect square.  E.g., $2^2=2^2+0^2$.
Comment: Relevant question (possible duplicate): http://math.stackexchange.com/q/100506/264
Comment: I've thought about that...but I get that it can be expressed as the sum of 2 perfect squares when 'n' is odd and it can't when 'n' is even but I'm required to show it works for all natural n :(
Comment: As a nuclear overkill, you can use [Fermat's classification of numbers which can be written as the sum of 2 squares](http://en.wikipedia.org/wiki/Fermat's_theorem_on_sums_of_two_squares). But please just follow Amr's hint.
Comment: Hint: zero is a perfect square.
Comment: Ahh, silly me. Thanks very much!
Comment: @user78416 Note that for the revised problem, the $n$ even case is the 'easy' one - if $s=x^2+y^2$, then $2^{2k}s = (2^kx)^2+(2^ky)^2$; the $n$ odd case is handled by Calvin's answer.
Comment: How would induction even be used? This is not a problem of proving that a property holds over a set, but of finding an instance. "Your homework consists of driving nails; note that the use of a saw is not allowed".
Answer: Hint: If the numbers $x$ and $y$ can each be written as the sum of 2 perfect squares, then so can the number $xy$. This is known as the Brahmagupta-Fibonacci Identity.
You can either prove this statement yourself, or click on the Wikipedia link.
Comment: So that covers the case of even n! Thanks very much! :D
Answer: In the case that $ n $ is odd, let $ s = k^2 $ and $ n = 2m + 1$. Hence $$ 2^{2m + 1}k^2 = \left(2^m k\right)^2 + \left(2^mk\right)^2 $$ Otherwise, $ n = 2m $ and we have that $$ 2^{2m}k^2 = \left(2^m k \right)^2 + 0^2 $$
No induction needed here. $ m $ and $ k $ are both in $ \mathbb{N} \cup \{0\} $.
You might think the zero is "cheating" but it is definitely necessary in some cases such as $ 2^n s = 16 $.
Comment: There is a problem when n is odd
Comment: Thank you. I have fixed it.
Comment: I'm sorry, I had a typo in the original problem :( s is not a perfect square, it is the sum of two perfect squares, sorry :(


Change of variable (Fourier Transform related)

Question: Consider a problem below...

The solution offered to this particular question (1)a)) simply state the change of variable ksi to by to yield the result, I'm failing miserably to see how.
Answer: First of all, write formula from $\textbf{[1]}$ for $x=yb$, that means:
$$\int_{-\infty}^{\infty}\frac{e^{i \xi yb}}{1+\xi^2}\; d\xi =\pi e^{-b|y|}$$
Next change of variables in integral:
$$\int_{-\infty}^{\infty}\frac{e^{i \xi yb}}{1+\xi^2}\; d\xi$$
Putting $\xi=\frac{\xi}{b}$:
$$\int_{-\infty}^{\infty}\frac{e^{i \xi yb}}{1+\xi^2}\; d\xi=\int_{-\infty}^{\infty}\frac{1}{b}\frac{e^{i \xi y}}{1+\frac{\xi^2}{b^2}}\; d\xi$$
Next (simple multiplying by $\frac{b}{b}=1$):
$$\int_{-\infty}^{\infty}\frac{1}{b}\frac{e^{i \xi y}}{1+\frac{\xi^2}{b^2}}\; d\xi=\int_{-\infty}^{\infty}b\frac{e^{i \xi y}}{b^2+\xi^2}\; d\xi$$
Answer: I suggest taking $s = \frac{\xi}{b}$ so the denominator looks as the denominator of the integral you know how to solve. Then, think using the condition "for any $x \in \mathbb{R} $".


CKEditor: pass value back to link-plugin

Question: To insert a link to specific files I want to add a button to the link-Dialog, which opens my own php-filebrowser.
In this filebrowser I can browse specific directories to finally select a pdf-file.
By clicking on a file I want to pass the url of this file to the link-dialogs url-field. And that is the point where I do not get ahead.
The url I alert when clicking the file is the one I need.
All I need is the javascript to pass it to the opener's url-field.
I have tried several proposed solutions I found in this forum but nothing helped.
In my filebrowser I have a list of files.
Each file has a link like this one:

*filename*

This is the javascript part I tried in my filebrowser:

The script alerts the correct value. But the next line doesn't pass the value back.
Instead of "opener.SetValue(url, 'url');" I also tried
window.opener.CKEDITOR.tools.callFunction(ckeditorfuncnum, url);
with the ckeditorfuncnum passed to the script and
opener.SetUrl(url);
UPDATE:
it seems as if the second try ('window.opener.CKEditor...') would be the right one. Since no value is displayed in my input field, I tried to return an error message...
The error message is being displayed in the window with the CKEditor-Fields.
Comment: you will need to post the code of the solutions you have tried. Stackoverflow is not meant to give you free code.
Comment: I have tried several options I found in this forum:
(url contains the value to pass back)
- "opener.SetUrl(url);"
- "opener.SetValue(url, 'url');"
- "window.opener.CKEditor.tool.callFunction(funcnum, url);"  (funcum contains the value submitted to the script)
Comment: update your original post and add as many code as you can which is relevant for your question. it is nearly impossible to answer your question with the information you have given
Answer: For everyone who might run into the same problem here is the solution:
function passvalue(url) {
    var dialog = window.opener.CKEDITOR.dialog.getCurrent();
    dialog.setValueOf('info', 'url', url);
    dialog.setValueOf('info', 'protocol', 'http://');
    window.close();
  }


GoogleMap object is null

Question: I am trying to add marker on map. But initializeMap() return null.
What could be the issue?
ActivityPlace.java
public class ActivityPlace  extends AppCompatActivity {

    GoogleMap mMap;
    LatLng latlng;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_place);

        if (initializeMap() && checkServices()) {
                latlng = new LatLng(latitude, longitude);
                MarkerOptions options = new MarkerOptions().position(latlng);
                Marker marker = mMap.addMarker(options);
                CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latlng, 12);
                mMap.animateCamera(update);
                mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
                    @Override
                    public void onMapClick(LatLng latLng) {
                        //Launch Map Page
                    }
                });
        }
    }

    /*
    Method to check Google services before initiating map
 */
    public boolean checkServices() {
        int isAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (isAvailable == ConnectionResult.SUCCESS){
            return true;
        }else if (GooglePlayServicesUtil.isUserRecoverableError(isAvailable)){
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(isAvailable, this, ERROR_DIALOG_REQUEST);
            dialog.show();
        }else {
            Toast.makeText(this, "Cant connect to mapping service", Toast.LENGTH_SHORT).show();
        }
        return false;
    }

    /*
        Initialize the map and get a handle to the map to set its location
     */
    private boolean initializeMap() {
        if (mMap == null) {
            SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_fragment);

            mapFragment.getMapAsync(new OnMapReadyCallback() {
                @Override
                public void onMapReady(GoogleMap googleMap) {
                    mMap = googleMap;
                }
            });
        }
        return (mMap != null);
    }
}

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

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical"
            android:id="@+id/place_layout">

            <TextView
                style="@style/txtPrimaryHeading"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:padding="8dp"
                android:id="@+id/place_name"/>

            <include
                android:id="@+id/map"
                layout="@layout/activity_map_embedded_fragment"
                android:layout_width="match_parent"
                android:layout_height="200dp" />
        </LinearLayout>
    </ScrollView>

</RelativeLayout>

activity_map_embedded_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/map_fragment"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    map:uiRotateGestures="false"
    map:uiTiltGestures="false"
    map:uiScrollGestures="false"
    map:uiZoomGestures="false"
    map:cameraZoom="12"
    map:cameraTargetLat="-35"
    map:cameraTargetLng="150"
    />

Comment: obviously because `getMapAsync` ... you see **async?** ... it's [multithreading basics](http://ideone.com/PPHi95)
Answer: getMapAsync is async call which will be running in background and your method will return value false only.
My suggestion is to perform other operations when onMapReady is called.
mapFragment.getMapAsync(new OnMapReadyCallback() {
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        latlng = new LatLng(latitude, longitude);
        MarkerOptions options = new MarkerOptions().position(latlng);
        Marker marker = mMap.addMarker(options);
        CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latlng, 12);
        mMap.animateCamera(update);
        mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                //Launch Map Page
            }
        });
    }
});

Answer: call this before intitializing map .
GoogleApiClient mGoogleApiClient ;

synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }

}

Answer: Try this. It really works.
GoogleApiClient mGoogleApiClient ;

synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }

}

GoogleMap object is null


Can I monitor progress of spacy parsing?

Question: I have a simple program to process English text with spacy and output some of the info about the tokens. For a big text it takes a long time for spacy to process it. Is there a way to see how far the processing has progressed ideally as a percentage? I'm not using my own models, just ones provided by spacy.
import spacy

// load big text file into `text` variable

nlp = spacy.load("en_core_web_sm")
nlp.max_length = len(text)+1
doc = nlp(text)

// output info

Answer: In general I would not advice to parse the entire text as one big blob of text and instead try to split it into smaller paragraphs first.
For example, you can split at every \n\n first.
Then you can hand multiple documents to SpaCy at once using nlp.pipe(), which you can use a tqdm progress bar on.
Alternatively, you can create batches within the document and then concatenate the results.
Comment: Can you elaborate why you would generally advise splitting texts into smaller paragraphs? Don't you lose some accuracy by parsing each paragraph in isolation? I guess normally it might not reduce accuracy, but maybe sometimes it would, such as when there are bullet points which appear as separate paragraphs? In my case the user may be supplying text from PDFs or OCR which could have page breaks as \n\n inside sentences.


How do I hide YouTube Data API key in public repo on GitHub?

Question: I am writing a Python script that uses the YouTube Data API to obtain public data from YouTube.
I want to put up my script on Github and make other users be able to use my script on behalf of my API Key. I know that including my API key in the script is bad. As far as I have understood, OAuth is required to access the private data of users, but I intend to access only public data from YouTube Data API.
So is there a way for me to make my API key hidden to users accessing my project from GitHub while enabling them to use my script, without them having to make an API key for themselves?
This is my first Python project using any API, so if there are any errors in how I have understood stuff, do correct me.
Answer: You say that (quote):

I know that including my API key in the script is bad.

But if you were to observe the specifications of DTOS (you're compelled to do so in case you need your app to be successfully audited by Google), then you'll find that sharing API credentials is forbidden. The paragraph III.D.1.d of that document says:

You may share your API Credentials with agents operating solely on your behalf and under a written duty of confidentiality. However, you must not share or disclose your API Credentials to any other third party, allow access to or use of your API Credentials by any other third party, or embed your API Credentials in open source projects.

Do note the last statement above: it pertains precisely to your use case, specifying that it's not allowed to include your API key in source files published on Github.
Therefore, there's nothing else you can do, but having each user of your Github project using their own API key.
Comment: Thanks for the input. So Oauth is an option for me to make my script usable for others?
Comment: OAuth access and refresh tokens and API keys are API credentials. You're not allowed to share on Github OAuth tokens (that one obtains upon OAuth flows) either.


How do you select multple rows from table and put in seperate arrays?

Question: just wondering if anyone can help. I am trying to load data into tabs from my SQL database and was wondering if anyone knows how to load four rows of data into four different arrays. I think I am nearly there with my code but am a bit stuck.
Alternatively if anyone knows of any tutorials for loading data from a database into tabs that also loads data into each [li] it would be much appreciated.
Thanks for the help.
<?php
$query = mysql_query("SELECT title, author, date_added FROM table ORDER BY date_added DESC LIMIT 4");
$array = array();
while($row = mysql_fetch_assoc($query)){
$array[] = $row1;
?>

<?php echo $row1['title'];?>

<?php echo $row2['title'];?>

<?php echo $row3['title'];?>

<?php echo $row4['title'];?>/a>

Written by

<?php echo $row1['author']?>

Date Added

<?php echo $row1['date_added']?>

Comment: don't forget the closing bracket } after $array[] = $row; before ?>
Answer: I think you mess it up a bit. The variables $row1, $row2, $row3, $row4 you use are not declared anywhere. What you you need is a while loop to populate your $array as follows:
$array[] = $row;
Then you can have access in the different rows like this:
echo $array[0]['title'];
Answer: Replace
$array[] = $row1;

With:
$array[] = $row;

And then:

<?php echo $array[0]['title'];?>

<?php echo $array[1]['title'];?>

<?php echo $array[2]['title'];?>

<?php echo $array[3]['title'];?>

Answer: Replace your
$array[] = $row1;

With this
$array[] = $row;

It's simple way to achieve that create reach row of table as array.
Then we can traverse into each array using their index like $array[0]['title']
Comment: nice try, but should be the other way around. edit your question and try explaining a bit to
Comment: Do you want more explanation?
Comment: not me, but it's better to explain your answer then to just burst it out. and you still have it the other way around


Function of a templated class as template parameter

Question: I want to create a template class for generic operators. The class will have two structs representing a value as input:
struct Value {
   DataType type;
   size_t dataSize;
   char* data;
};

I already have written a type deduction with oldschool switch-cases. After a cast of the data-ptr to the type, I want to apply an operation on the input values like this:
template<class Operation>
class ApplyOperation {
    Value* operator()(const Value* a, const Value* b) const {
    //find type of a and b
    //cast a and b to their types
    Operation<aT,bT> op;
    return op(a,b);
  }
};

Now I could write for each operation a little struct like this:
template<class A, class B>
struct Add {
  A operator()(A a, B b) const { return a + b; }
};

I have seen a boost class called operators: http://www.boost.org/doc/libs/1_59_0/libs/utility/operators.htm
which I want to use for my purpose. But I don't know how to integrate it since the operators in the structs are no functors. So would it be possible to use it like this?:
ApplyOperation<boost::addable::operator+> add;
add(a,b);

Actually I'm trying it for testing with this class:
template<template<class T, class U, class...> class OperatorClass,class F>
struct ApplyOperator {

    template<class T, class U>
    T foo(T a, U b) {
        OperatorClass<T,U> opClass;
        return opClass.operator+(a,b);  //this works of course
    }
};

What I want to get is this:
template<template<class T, class U, class...> class OperatorClass,class F>
struct ApplyOperator {

    template<class T, class U>
    T foo(T a, U b) {
        OperatorClass<T,U> opClass;
        return opClass.F(a,b);
    }
};

Instantiated like that:
ApplyOperation<boost::addable, operator+> add;

This doesn't work of course because of the unknown type operator+. So how can I call the operator+-function with templates?
Is there a way to get this solved?
Comment: please post a [mcve] of what you are trying to accompilish
Comment: http://pastebin.com/yihHAMR0
Answer: I am not sure I fully understood the question. But it looks like you are trying to provide an object instance (not type) to your template ApplyOperator. Since operator+ is definitely not a type and not an integral constant, it can not be used as a template argument in no way. What you will have to do is to make an operation an argument to the constructor, not the type of the object.
Comment: Is there a way to tell via templates which member function to use?
Comment: No. The only 2 things which can be an argument of a template are type or integral constant. Function pointers are neither.


Checking if chosen tiles on a 2d matrix are all connected

Question: I'm creating a game with a map which is a [100 tile x 100 tile] matrix. Players will be able create "Duchies" by combining 4 tiles. The game will let the player choose 4 tiles and check if those tiles are all connected to each other and let the player create the Duchy only if they are so.
So my isConnected() method will take in an ArrayList<Tiles> and the tiles have getX() and getY() methods, which returns their X and Y coordinates on the grid. If the tiles are connected to each other, it will return true, or false, if they are not. Note that the tiles can not be connected diagonally.
It is worth mentioning that the method will need to work for ArrayList's of tiles with more than 4 tiles since it will need to check bigger lists of tiles and that the Duchy scenario was an example of how the method will be used.

Just to visualize the whole thing;
Example Input 1 (X's are the selected tiles):
[X][X][X][ ][ ]
[ ][X][X][ ][ ]
[ ][ ][X][ ][ ]
[ ][ ][X][ ][ ]
[ ][ ][ ][ ][ ]

Example Output 1:
true

Example Input 2 (X's are the selected tiles):
[X][X][X][ ][ ]
[ ][X][X][ ][ ]
[ ][ ][ ][X][X]
[ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ]

Example Output 2:
false

I thought of comparing all tiles to all the others one by one and assume that the tiles were all connected if all tiles were connected to at least one other tile, but realized that it wouldn't work because it would return true for something like this:
[X][X][ ][ ][ ]
[ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ]
[ ][ ][X][X][ ]
[ ][ ][ ][ ][ ]

I couldn't figure out a way to do this and I couldn't find a solution for such a problem online.
Answer: Sort of a flood fill algorithm; takes one of the tiles and recursively consumes adjacent tiles in the selection. If all tiles in the selection were consumed in this way, all selected tiles are connected.
boolean isConnected(List<Tile> selection) {

    if (selection.isEmpty())
        return true; // ?????

    Queue<Tile> toConsume = new LinkedList<>(selection);
    Queue<Tile> queue = new LinkedList<>();
    queue.add(toConsume.remove());

    while (!queue.isEmpty() && !toConsume.isEmpty()) {
        Tile tile = queue.remove();
        findNeighbours(tile, toConsume)
        .forEach(n -> {
            toConsume.remove(n);
            queue.add(n);
        });
    }
    return toConsume.isEmpty();
}

List<Tile> findNeighbours(Tile tile, Collection<Tile> tiles) {
    return tiles.stream()
        .filter(t -> distance(t, tile) == 1)
        .collect(Collectors.toList());
}

int distance(Tile a, Tile b) {
    int dx = a.getX() - b.getX();
    int dy = a.getY() - b.getY();
    return Math.abs(dx) + Math.abs(dy);
}


Number of "passing" paths in football

Question:
In a football match, $M$ decides to do $N$ passes with $K$ players helping him out, so that $M$ could get the ball back at last to make the goal. In how many ways can $M$ do this?

Examples:

If the number of players helping him is $K = 2$ (say $a$ and $b$) and if there are $N = 4$ passes between them, then the number of ways is $6$.

$$M - a - b - a - M$$
$$M - b - a - b - M$$
$$M - a - M - a - M$$
$$M - b - M - b - M$$
$$M - a - M - b - M$$
$$M - b - M - a - M$$
Answer: You are looking for the number of walks from $M$ to $M$ of size $N$, in the complete graph $K_{k+1}$, where $k$ is the number of players other than the one who makes the goal.
This can be done by taking the $N^{th}$ power of the adjacency matrix of the complete graph and picking the main diagonal entry for the row corresponding to $M$.
If you are writing a program, it might be easily done. It might even be possible to give a mathematical formula, by diagonalizing the matrix.
Here is an explanation: http://www.math.dartmouth.edu/~m68f11/algcomb.pdf (look at the proof of Theorem 1.1)
In fact that pdf, has a derivation using diagonalization (as mentioned earlier) and derives the following as your answer (see Corollary 1.6 in the pdf):
$$  \dfrac{k^N + (-1)^Nk}{k+1}$$
Which matches what you got for $k=2$ and $N=4$.
Comment: Wow Brilliant! Thanks! If it's not much trouble, an in-depth explanation would be impressive.
Comment: Is it $K_{N+1}$ or $K_{N-1}$?
Comment: @TheProgrammer: Sorry, there is a typo there. I will correct. It Is $K_{k+1}$. I found a pdf on the web with more explanation, which also has a derivation of the formula you need!
Comment: I checked with higher values of N and K. But this formula doesn't hold good. Values for which I checked are N=4 K=3 (answer would be 21), N=3 K=3 (answer would be 6), N=3, K=4 (answer would be 12). I think there's a minor glitch in the formula.
Comment: @TheProgrammer: The answer is brackets is what you are expected to get? If so, the formula seems to work.

Number of "passing" paths in football


Clicar em Link Dentro de DIV Clicável

Question: No código abaixo vem demonstrando uma div clicável para o caso de ser mobile. Quando for full tem um ícone que aparece dentro da div ao passar o mouse por cima, hover.
HTML

id_categoria !!}" data-categ="{!! $prod->slug_categoria !!}" data-slug="{!!
$prod->slug !!}">

        {!! HTML::image('img/produtos/'.$prod->imagem, $prod->produto) !!}

        {!! HTML::image('img/details.png', 'Ver Produto', ['class' => 'detail']) !!}
        {!! HTML::image('img/add-cart.png', 'Adicionar ao Orçamento', ['class' => 'add-cart']) !!}

{!! $prod->produto !!}

O código que faz a função do clique é esse abaixo. Eu tentei usar a seguinte síntaxe:
$(elemento-principal).not(elemento).on()
Eu quis dizer assim: quando clicar na div com exceção do ícone add-cart me direcionar para a página do produto.
JS
// Seleciona Produto
$('.item').not('.item > .icons > .add-cart').on(clickDeviceEvent, function(){
    var prod = $(this).data('filter');
    var catg = $(this).data('categ');
    var slug = $(this).data('slug');
    document.location.href = urlBase + '/produtos/'+catg+'/'+slug;
});

Não funcionou. Não sei como faz ou se é possível fazer.
Quero clicar no link dentro da div, mas que não rode a função.

Consegui fazer de um jeito aqui e gostaria de saber se é o correto ou se tem outra maneira de fazer.
O motivo de eu querer a solução acima é que eu precisava aplicar outra função ao ícone. Então eu criei a função agora:
// Add Produto ao Orçamento
$('.item > .icons > .add-cart').on(clickDeviceEvent, function(){
    console.log('Vixi');
    return false;
});

Funcionou! Mas funcionou porquê eu coloquei o return false. Daí quando clico no ícone dentro da div, roda essa função primeiro. E com o return false não deixa rodar a função da div.
Deu certo, mas esse é o melhor jeito ? Ou esse jeito é bom ?
Answer: Neste caso o ideal é adicionar um evento click para o img.add-cart, nele você chama o event.stopPropagation(), desta forma o evento click do div.item não será executado.

var tmplItem = document.getElementById("tmplItem").content;
for (var indice = 1; indice < 20; indice++) {
  var item = document.importNode(tmplItem, true);
  document.body.appendChild(item);
}

var cards = document.querySelectorAll(".card");
console.log(cards);

var onCardClick = function (event) {
  alert("Click no Card");
};

var onIconClick = function (event) {
  alert("Click no icone");
  event.stopPropagation();
};

[].forEach.call(cards, function (card, indice) {
  var icon = card.querySelector(".icon");
  var content = card.querySelector(".content");
  var menu = card.querySelector(".menu");

  console.log(card, icon, content, menu);

  card.addEventListener("click", onCardClick);
  icon.addEventListener("click", onIconClick);
});
.card {
  position: relative;
  width: calc(100% - 20px);
  height: 128px;
  box-sizing: border-box;
  margin: 10px;

  box-shadow: 0px 0px 5px black;
  background-color: white;
}

.card .icon {
  position: absolute;
  top: 0px;
  left: 0px;
  height: 128px;
  width: 128px;

  background-image: url('http://cdn.flaticon.com/svg/34/34363.svg');
  background-size: calc(100% - 10px);
  background-position: center;
  background-repeat: no-repeat;
  border-right: 1px solid gainsboro;
}

.card .content {
  position: absolute;
  top: 0px;
  right: 0px;
  bottom: 40px;
  left: 128px;
}

.card .menu {
  position: absolute;
  right: 0px;
  bottom: 0px;
  height: 40px;
  left: 128px;
  border-top: 1px solid gainsboro;
}
<template id="tmplItem">

</template>

Clicar em Link Dentro de DIV Clicável


Simple algebra of integral

Question: I'm studying economics and I'm having trouble with math calculations.
In my economics textbook, the following equation comes out, and for me it's hard to understand how this relationship is established.
I know a very basic concept of calculus, so could you explain the formula below in detail?
Thank you.
Note. Everything is a continuous concept

$t$ is the time index,
$\pi(K(t))$ is the profit function with capital($K$),
$r$ is the interest rate,
$e^{-rt} = (1+r)^t$ (at least in the limit),
$q(t)$ is the cost function,
$\dot q(t)$ is the time derivative of $q(t)$,
$\pi(K(t))=r\cdot q(t)-\dot q(t)$

For arbitrary $T>t$, the relationship below is established.
$$
q(t)=\int\limits_{\tau=t} ^\infty e^{-r(\tau-t)}\pi(K(\tau))d\tau+e^{-r(T-t)}q(T)
$$
Comment: Please define what these functions are supposed to represent
Comment: @KamalSaleh I edited my question
Comment: The lower limit of integration currently reads $\tau$, which is probably not correct. Did you mean $T$?
Comment: @EricNathanStucky In my textbook it is written as $\tau=t$
Comment: Hm, then something is still amiss. For instance, if you take that whole integral and subtract it from both sides, doesn't the (new) left side not depend on $T$, but the (new) right side does? Is $T$ truly arbitrary, or are we thinking of it as growing out to infinity?
Answer: It looks like you're doing something along the lines of a present value computation, where you are trying to look at costs into the future; since currency is worth less as time goes on, those costs can be backward-extrapolated to the present day and you can see how much of a burden they are in today's dollars.
You probably remember from calculus that $\int_a^b \frac{d}{dx}f(x)\,dx = f(a)-f(b)$; this is one of the Fundamental Theorems of Calculus and basically it's what we always use to solve integrals. We apply this principle for $f(x)= q(x)e^{-r(x-t)}$, and $a=t$ and $b=T$. Recalling the product and chain rules for derivatives, this yields
\begin{align*}
\int_t^T\left[\dot q(x)e^{-r(x-t)}-q(x)re^{-r(x-t)}\right]\,dx &= q(T)e^{-r(T-t)}-q(t)e^0 \\
\int_t^T -\left[-\dot q(x)+q(x)r\right]e^{-r(x-t)}\,dx &= q(T)e^{-r(T-t)}-q(t) \\
q(t)-\int_t^T e^{-r(x-t)}\pi(K(x))\,dx &= e^{-r(T-t)}q(T) \\
\end{align*}
Adding the integral to both sides yields the given equation, except that the upper limit is $T$ instead of $\infty$.* I suspect your text is taking the limit as $T\to\infty$ (in practical terms: looking at the costs further and further into the future), in which case the $T$ in the integral does become an $\infty$, but we have to figure out what happens to the "extra" right-hand side term for large $T$. So I'm hoping the next bit of the text is devoted to that; but do let me know if I'm off base.
(* And my variable of integration is $x$ instead of $\tau$. This doesn't matter; it's just a name. Remember that when you have $\int_a^b g(x)dx$, all that matters is that you plug in $x=a$ and $x=b$ at the end, and then the $x$ has disappeared. So of course we can just as well call it $\tau$. I chose the notation that stuck closer to a calculus course than to your text so that the theory part would look more familiar.)
Comment: Yes, you're right! I skipped the latter part(infinity part) because I thought it doesn't matter, but thank you for pointing it out.

Simple algebra of integral


How to tune the weak learner in boosted algorithms

Question: It is commonly said that boosted algorithms (adaboost, gradient boosted trees) are composed of many "weak" learners. Let's stick to decision trees as the base learners. Some empirical studies recommended using trees with something like 5-10 terminal nodes (e.g. stochastic gradient boost paper). However, these results were obtained when computation was more expensive, and datasets were smaller/ had lower dimensionality than contemporary ones. Nowadays, people win kaggle competitions by using deep boosted trees (base learners with depth 6 or even 10 are not uncommon). These are arguably weak learners, which begs the question: Are weak learners necessary at all?
This answer from stats stackexchange, suggests that the reason for using weak learners was that they are faster to train. This seems to be only part of the picture: An early motivation of boosted models was that weak learners are less prone to overfitting. At the same time, some sources suggest that too strong a learner can lead to overfitting, while too weak a learner can lead to poor performance (see "Caveats" slide).
Putting all of this together, I am left with a huge parameter space to scan when training an algorithm (base learner depth can be 1-10, iterations can be 100-2000, learning rate can be 0.01 to 0.99). One simplification could be to say: I am going to vary the depth of a single decision tree until I get an AUC of between 0.5 and 0.55 on my dataset, and I will call this my "weak" learner. Then I will use trees of this depth in my boosted algorithm.
Is that the best I can do? Are there some other common rules of thumb that could help (e.g. keep iterations at around 500, and scan learning rate and depth until you get optimal performance, or something along these lines)?
Answer: Yes, weak learners are absolutely required for boosting to be really successful.  That is because each boosting round for trees actually results in more splits and a more complicated model.  This will overfit quite quick if we let it. On the other hand, if we pass a more complicated model such as a large polynomial linear regression then boosting will actually apply some regularization.  Although, linear models won't be able to give you the best accuracy when boosting (typically).
You mention kaggle and deep trees.  There is a significant difference between standard boosting trees and the base trees used for xgboost or lightgbm (what wins Kaggle).  The trees in these algorithms are heavily regularized which allows us to use deeper trees and still keep them 'weak'.
In terms of param spaces to try, it depends on the algo.  If you are using some basic boosted tree like scikit-learn's then you will typically be dealing with really short trees (so max depth around 1-3ish).  Whereas with xgboost or lightgbm you will get good results typically going deeper to something like 8-16. Learning rates typically are lower around .01 - .1 although I have seen some go up to .5 for optimal solutions.
Overall though, the huge param space search is the price we pay for state-of-the-art results.  As Tim mentioned in his answer we typically leverage hyperparameter packages to speed this up like hyperopt or optuna.
Answer: The definition of weak learner is:

Something better than a random guess (1), (2), (3)

There is nothing in that about overfitting, though weakness means overfitting is highly likely.  Being a very bad estimator and being a robust estimator tend to not coincide.
Whether or not your learners are weak, you can do a primitive statistical design of experiment on your grid searching to accelerate the overall testing by orders of magnitude.
Instead of uniform, try random sparse.  Look at the functions that make autoplotting, how they bisect and look for changes, and use those.  Use the multivariate versions.
These two things are not necessarily connected, and the second one has some very good solutions to be had.
Answer: One of the practical reasons why we use weak learners is that we don't need to care about issues like this. In many cases ensembling many weak learners is just enough to achieve good performance. Weak learners are simple by design, we don't usually tune them. You are correct, if you wanted to tune them, this becomes a complicated optimization problem. If you really want to do this, one thing that could make things easier is to use a more clever optimization algorithm than grid search, for example Bayesian optimization that "cleverly" explores the parameter space.


Help me find the number of sets

Question: Let $A$ and $B$ be disjoint sets such that
$$
\begin{array}{lll}
n(U)=60, & n(A\setminus B)=13, & n(B\setminus C)=16,\\
n(C\cap B)=4, & n(C\setminus A)=22, & n(A\cap C) = 5
\end{array}
$$
Find the following.
$a)$ $n(A\setminus(B\cup C))$
$b)$ $n((A\cup B\cup C)')$
$c)$ $n(C\setminus(A\cup B)')$
$d)$ $n(A\cap B)$
Thanks.
Comment: Is $U=A\cup B\cup C$?
Answer: It might be best to make a type of Venn Diagram.
$\hskip{.75in}$
$A$ and $B$ are disjoint, so I'm not letting the blue and red circles touch. Let's start filling in parts. We know directly that:
$n(B\setminus C)=16$,
$n(C\cap B)=4$,
$n(A\cap C) = 5.$
$\hskip{.75in}$
We can fill in the rest of the green $C$ circle knowing that $n(C\setminus A)=22$. This means there must be a total of $22$ in the green circle that isn't touching the blue $A$ circle. Since we already have $4$ in the green/red part, that leaves us with $18$ in the rest of the green $C$ circle.
We can fill in the rest of the blue $A$ circle from either $n(A\setminus B)=13$ or $n(U)=60$. In the latter case, we know $A + B + C = 60$, and since $B= 20$ and $C = 27$, that leaves us with $A = 13$, so the remaining blue should be $8$.
$\hskip{.75in}$
This should help with parts $a$, $b$, and $c$. For part $d$, notice that $A$ and $B$ are disjoint.

Help me find the number of sets


Change print $node_url To a Link Fields Value

Question: Hello i would like to change the destination of a url in a node.tpl (in a view) from this-
<a href="<?php print $node_url; ?>">

to something like this-

where the field viewslink is a link field in the node itself.
I know i could do it if the view used fields but it doesnt its using a content teaser.
Anyone got any advice?
Thanks
sites/all/themes/other_sub/templates/nodes/node--view--portfolio-block.tpl.php
<li class="<?php print str_replace(',-', ' ', str_replace(' ', '-',strip_tags(render($content['field_portfolio_category'])))); ?>">
    <?php print render($content['field_portfolio_image']); ?>

        <a href="<?php print render($content['field_viewslink']); ?>">

<?php print $title; ?>

<?php print strtolower(render($content['field_portfolio_category'])); ?>

Answer: If it is a field with in the node then you should be able to use the $node object.
The object contains all the fields associated with the node.
if you are not sure of the name of the field then you could try to print the object using the print_r function.
You could also try try the $content object which contains the fields as well.
print render($content['field_viewslink']);

That should render the variable.
Comment: thanks for the replies guys. I think Mohammed's way is more like the way that i am used to. I will edit my original post to put in the code i have now (which still links to the node funniliy enough)
Comment: Could you check the content of the $node variable by using print_r may be it will give you some clue.
Comment: ive added it to my pag.tpl whichy you can see here mohammed http://islifeshit.com/ but nothing showing. If they had simply done it with fields and not using teaser conent id be ok.
Comment: sorry the block view wasnt showing to non regustered guests. it is now. Ive tried prin r and devel and everything. It SHOULD work as it is but for some reason it isnt. im all drupal depressed. been at ut for 7 days solid. i give up for now i think :(
Comment: mmmm well ive finally got it down to showing an array. the field is being loaded in the view mohammed. Ach ill get there yet. Maybe ill go for a walk around the park to get my mind back
Comment: you should add the print_r statement in the node--view--portfolio-block.tpl.php. this will show the value in the variable and you can get the exact variable to print.
Comment: I am having a bit of problems with the print r statement Mohammed but ive got Devel on the case and i think this does the same thing no? In my content type i have added a field 'field_internal_link'. Due to the bizarre way the themer has made up the node.tpl i cant use the content type display pages for fields to show up in the node. i have added  to the node.tpl. When i visit the view and look at the devel side of things my field isnt being rendered or loaded. im a little lost now. Sorry Rupesh i dont think yousuggestion would work in thi
Comment: in this user case. my node.tpl looks like this though http://pastebin.com/wpd1dTzm
Comment: a wait a sec....silly old me put it in the wrong node.tpl. lets see.....ive nearly got it working. you can see it here http://islifeshit.com the node--view--portfolio-block.tpl.php i have is http://pastebin.com/mf7wPE7H not only will i need to hide the link i need it somehow to be in the url part. Anyone? tx
Answer: You can use template_preprocess_node function to modify value of node.tpl.php
e.g:
function MYTHEME_preprocess_node(&$variables) {
//$variables['node_url'] = url($uri['path'], $uri['options']);
$variables['node_url'] = url(YOUR-CUSTOM-URL);
}

Answer: finally got there with this
<a href="<?php print strip_tags(render($content['field_viewslink'])); ?>">


useRef hook with typescript doen`t work. All was fine in jsx

Question: So I have a copy of working code , and I was trying to adapt it for typescript.
I have a modal window , that I want to close if I click on anything but not modal window itself.
Again - in jsx it was legit functioning code , but with typescript I have numerous errors.
First of them is:
Type 'MutableRefObject<HTMLButtonElement | null>' is not assignable to type 'LegacyRef<HTMLDivElement> | undefined'. Type 'MutableRefObject<HTMLButtonElement | null>' is not assignable to type 'RefObject<HTMLDivElement>'. Types of property 'current' are incompatible. Type 'HTMLButtonElement | null' is not assignable to type 'HTMLDivElement | null'. Property 'align' is missing in type 'HTMLButtonElement' but required in type 'HTMLDivElement'
import { useEffect, useRef } from 'react';
import './ModalforSelect.scss';

type Props = {
  options: string[][];
  setClick: React.Dispatch<React.SetStateAction<boolean>>;
};

export const ModalforSelect: React.FC<Props> = ({ options, setClick }) => {
  const modal = useRef<HTMLButtonElement | null>(null);

  useEffect(() => {
    const closeHandle = (event: MouseEvent) => {
      if (modal !== null) {
        if (!modal.current?.contains(event.target as HTMLInputElement)) {
          setClick(false);
        }
      }
    };

    document.addEventListener('mousedown', closeHandle);

    return () => document.removeEventListener('mousedown', closeHandle);
  }, []);

  console.log(modal.current);

  return (

      {
        options.map(el => {
          return (

              {el[1]}

          );
        })
      }

  );
};

So, I decided that maybe problem was in useEffect , so I commented out some of it functionality,
but now there is another mistake that doesn't make any sence to me:
Type 'MutableRefObject<HTMLButtonElement | null>' is not assignable to type 'LegacyRef<HTMLDivElement> | undefined'. Type 'MutableRefObject<HTMLButtonElement | null>' is not assignable to type 'RefObject<HTMLDivElement>'. Types of property 'current' are incompatible. Type 'HTMLButtonElement | null' is not assignable to type 'HTMLDivElement | null'. Property 'align' is missing in type 'HTMLButtonElement' but required in type 'HTMLDivElement'
import { useRef } from 'react';
import './ModalforSelect.scss';

type Props = {
  options: string[][];
};

export const ModalforSelect: React.FC<Props> = ({ options }) => {
  const modal = useRef<HTMLButtonElement | null>(null);

  console.log(modal.current);

  return (

      {
        options.map(el => {
          return (

              {el[1]}

          );
        })
      }

  );
};

Will be glad for any advice.
Answer: You're trying to use a ref for a <button> (HTMLButtonElement) element for a div.
The correct type is
const modal = useRef<HTMLDivElement>(null);

Also, unless you really want to accept the children prop, don't use React.FC; a plain function is enough.
import React, { useRef } from "react";

type Props = {
  options: string[][];
};

export function ModalforSelect({ options }: Props) {
  const modal = useRef<HTMLDivElement>(null);
  return (

      {options.map((el) => {
        return (

            {el[1]}

        );
      })}

  );
}

Comment: Thank you. 'MutableRefObject' and 'LegacyRef' description of error really confussed me and I failed to see that endeed I was assigning in generic HTMLButtonElement to HTMLDivElement.


How can I get auto-width columns in Bootstrap?

Question: How do I get auto-width-columns in Bootstrap like in UIKit?
I need 5 columns with auto width.
In UIKit you get it with

Comment: Foundation has this feature.
Comment: not really clear what is asked: auto-width on content, or equal column auto-width on available space
Answer: Bootstrap 4+ you can use the col class alone and it will resize to what space is available.

Comment: Hi Josh. How can I implement that with bootstrap 3.3.7?
Comment: You can't. Auto width calculation is a feature only available with `flexbox`
Comment: @AllanJebaraj although flexbox is only present at Bootstrap 4+, it doesn't mean you can't. You can study flexbox and apply your own CSS rules to override the columns styles and apply the auto-width. =]
Comment: It's been a year and a half ! :P Thank you @giovannipds I didn't have control over the library as many components and layouts have been defined in that version and I didn't want to complicate the already complicated codebase ;)
Comment: @AllanJebaraj haha, no worries! If you need it anytime, just say it, it's simples to implement a little css class extension for that. =]
Answer: Using class="col" will automatically make the columns equal in size.
But if you want some column(s) to resize depending on its/there content(s), use something like class="col-auto".

Use class="col-{breakpoint}-auto" classes to size columns based on
  the natural width of their content.
Reference:
  https://getbootstrap.com/docs/4.0/layout/grid/#variable-width-content
Answer: Bootstrap 5 (update 2023)
Bootstrap 5 still uses a flexbox grid so auto-sizing is still possible using the .col to .col-auto classes so that columns take up as much space as needed.
Bootstrap 4
Bootstrap 4 uses a flexbox grid so auto-width columns are achieved using the col and/or col-auto classes. The col class will create equal width columns, while col-auto columns will shrink to fit the width of their content.
Bootstrap 3 (original answer)
The 5 columns aspect of this question has been answered here. Since Bootstrap has 12 columns, you only use 10 of them with 5 col-*-2 units
http://codeply.com/go/QXiPmtgJUJ
In terms of "auto-width", Bootstrap 4 will have new auto-layout columns that consume the remaining portion of any row, but this is still based on a 12 column grid.


How to always run a background service even application gets killed by user from background

Question: My Solution to write sticky service is working fine below Android version Lollipop but above Lollipop version service is getting closed when user kills the application from background.
Any suggestion guys.
Comment: Don't do it. It does not work for a reason.
Comment: you got to reschedule it using job schedular
Comment: This discussion may help you: [Android service not restarting in lollipop](https://stackoverflow.com/questions/35747624/android-service-not-restarting-in-lollipop)
Comment: for new APIs you can use this : https://stackoverflow.com/a/49878237/2201814
Answer: Use can start service as Foreground even os can't kill it for more info check linkRunning a service in the foreground
Comment: But in case of foreground service we have to show service notification, that I don't want
Comment: You can hide that notification I am using it like this    Notification notification = new NotificationCompat.Builder(service).build();
        service.startForeground(NOTIFICATION_ID, notification);
Comment: try this method just pass it service name which you want to run as foreground private static void startForeground(Service service) {
        Notification notification = new NotificationCompat.Builder(service).build();
        service.startForeground(NOTIFICATION_ID, notification);
    }
Comment: like you can hide notification  startForeground(Yourservice.instance);
            startForeground(this);
            //Cancel this service's notification, resulting in zero notifications
            stopForeground(true);
Answer: I got solution about it not why it's work for me but try this.
Override the onTaskRemoved()

<code> @Override
    public void onTaskRemoved(Intent rootIntent) {
        // TODO Auto-generated method stub

        //Write your stuff which you set in onDestroy()
    }</code>

and set same code which you set in onDestroy() it work for me.
Answer: For instance below code will work on Lollipop.
<code> @Override
public void onTaskRemoved(Intent rootIntent) {
        Intent restartService = new Intent(getApplicationContext(),
                this.getClass());
        restartService.setPackage(getPackageName());
        PendingIntent restartServicePI = PendingIntent.getService(
                getApplicationContext(), 1, restartService,
                PendingIntent.FLAG_ONE_SHOT);
        AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000, restartServicePI);
}
</code>
But Things are getting quite tricky Since android N release. And now android O put some more restrictions on background tasks. So the thing in In Android O no background service can run the service will kill by OS just after your application gone from the foreground(Only Foreground services can run i.e Service with a notification on top). Here is a informative solution.


Detecting if emulator has started completely

Question: I want to check if all the emulators has booted successfully. I have tried with this command adb shell getprop sys.boot_completed this works if i am running one emulator. But if i have more than one emulator this command returns error as following: error: more than one device/emulator.How to solve this?
Comment: Possible duplicate of [How to use ADB Shell when Multiple Devices are connected? Fails with "error: more than one device and emulator"](http://stackoverflow.com/questions/14654718/how-to-use-adb-shell-when-multiple-devices-are-connected-fails-with-error-mor)
Answer: You should specify the device serial number on the adb command line to let it know which one you want to interact with.
Something like
adb -s emulator-5554 shell ...

Also, if you are doing it from the command line, multiple times and you are starting to be annoyed by that, you can try https://gist.github.com/dtmilano/4537110 which allows you to select the device
$ adb shell
1) 02783201431feeee device           3) emulator-5554
2) 3832380FA5F30000 device           4) emulator-5556
Select the device to use, <Q> to quit: 1
$

Comment: Diego, if that's your understanding of the OP's question, then why did not you just mark it as duplicate?


how to hiden the unncessary lines or edges on the same complete plane when pyqtgraph displays a STL file

Question: I found a STL viewer program using pyqtgraph from STLViewer
pyqtgraph document
the key parameters are set as
# color is a tuple in the form RGBA  (0.4,0.9,0.6,1)`
mesh = gl.GLMeshItem(meshdata=meshdata, smooth=True, drawEdges=True, drawFaces=True,  shader='balloon',color= (0.4,0.9,0.6,1))

a stl file appearance displays as the following

This appearance is not I want, since it displays many edges even though on the same complete plane.
and if set drawEdges=False then it displays as

However, the concrete edges I can touch are also hidden, this is not I want too.
What I want is like this

this is painted by pyVTK
the main  program is
import vtk
reader = vtk.vtkSTLReader()
reader.SetFileName(filename)
mapper = vtk.vtkPolyDataMapper()  # maps polygonal data to graphics primitives
mapper.SetInputConnection(reader.GetOutputPort())
actor_0 = vtk.vtkLODActor()
actor_0.SetMapper(mapper)
actor_0.SetScale(1000, 1000, 1000)
actor_0.GetProperty().SetDiffuseColor(0.4,0.9,0.6)
actor_0.GetProperty().SetDiffuse(.8)
actor_0.GetProperty().SetSpecular(.5)
actor_0.GetProperty().SetSpecularColor(1.0, 1.0, 1.0)
actor_0.GetProperty().SetSpecularPower(30.0)

Answer: You can change the color of the surface based on the normal vector by specifying the shader. viewNormalColor seems to fit what you're looking for among the builtin shaders.
Using viewNormalColor shader
mesh = gl.GLMeshItem(meshdata=meshdata, smooth=True, drawFaces=True, drawEdges=False, shader='viewNormalColor', glOptions='opaque')

There's an example code of using builtin shaders.
https://github.com/pyqtgraph/pyqtgraph/blob/master/examples/GLshaders.py
But this is too flashy. So, I did a search and found that it is possible to add a custom shader.
https://github.com/pyqtgraph/pyqtgraph/blob/master/pyqtgraph/opengl/shaders.py
Here is the code for adding a custom shader. I don't know much about shaders, but I modified the viewNormalColor shader to make the surface green.
gl.shaders.Shaders.append(gl.shaders.ShaderProgram('myShader', [
    gl.shaders.VertexShader("""
            varying vec3 normal;
            void main() {
                // compute here for use in fragment shader
                normal = normalize(gl_NormalMatrix * gl_Normal);
                gl_FrontColor = gl_Color;
                gl_BackColor = gl_Color;
                gl_Position = ftransform();
            }
        """),
    gl.shaders.FragmentShader("""
            varying vec3 normal;
            void main() {
                vec4 color = gl_Color;
                color.x = 0.0;
                color.y = (normal.y + 1.0) * 0.5;
                color.z = 0.0;
                gl_FragColor = color;
            }
        """)
]))

Then pass the shader name.
mesh = gl.GLMeshItem(meshdata=meshdata, smooth=True, drawFaces=True,
                         drawEdges=False, shader='myShader', glOptions='opaque')

Using myShader
I hope you will find it useful.


S3A: fails while S3: works in Spark EMR

Question: I'm using EMR 5.5.0 with Spark.  If I write a simple file to s3 using an s3://... URL it writes fine.  But if I use an s3a://... address, it fails with Service: Amazon S3; Status Code: 403; Error Code: AccessDenied
Using the AWS command line I'm able to cp, mv, and rm any file in the path I'm writing to.  But from spark, s3a fails on the put command.
We have Server Side Encryption Enabled, and I know spark knows because the s3 URLs work.  Any ideas?
Failed PUT DEBUG logs here.  Maybe its important to note, I'm doing an rdd.saveAsTextFile(path) but the put command says its trying to write to /my-bucket/tmp/carlos/testWrite/4/_temporary/0/ which it should only do in parquet?  Not sure if that detail is relevant but thought I would mention.
Answer: s3a is the actively maintained S3 client in Apache Hadoop. AWS forked their own client off from the Apache s3n:// client many years ago & (presumably) have massively reworked theirs.
They can read and write the same data, but some bits of EMR expect extra methods in the filesystem client which only EMR s3 supports...you cannot safely use s3a.
There's also the original ASF s3:// client which is incompatible with everything else, but was the first code used to connect Hadoop with S3, way before EMR was a product from amazon.
Which is better? S3A is probably, as of Aug 2017, faster on aggressive read IO of columnar formats like ORC and Parquet. EMR S3, with emrfs probably has the edge in terms of resilience and consistency. But the open source ASF S3A client is moving to address those
Comment: Do you happen to know if the `EMR` `s3` protocol allows predicate pushdown in Parquet?  (Similar to how it allows it with `s3a`)
Comment: that's not at the FS level, it's between Spark & the Parquet lib. Depends on what AWS have done with those two projects & whatever settings are needed for pushdown. You're best off testing it to see
Answer: Turns out EMR does not support s3a protocol at all as of today.  In addition, it says s3 and s3n are interchangable, but you should use s3
https://aws.amazon.com/premiumsupport/knowledge-center/emr-file-system-s3/
http://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-plan-file-systems.html
One thing to Note is that s3a although not supported, seems to work for reading, but not writing.
Update May 29, 2018:
Just to give a fuller answer, the s3a protocol is supported with s3+emr if you're using them with Databricks.
https://docs.databricks.com/spark/latest/data-sources/aws/amazon-s3.html

S3A: fails while S3: works in Spark EMR


Invalid requirement, parse error at "'--instal'" while trying to use --install-option in requirements.txt

Question: I'm trying to install a python module using setup.py with requirements.txt. I'm installing the module using pip install -U . in the directory where I have a setup.py file.
My setup.py file parses the requirements.txt file by storing the requirements in a list of strings:
def get_requirements():
    root_path = os.path.abspath(os.path.dirname(__file__))
    requirements_file_path = os.path.join(root_path, 'requirements.txt')

    # example: `numpy >= 1.13`
    with open(requirements_file_path) as file:
        requirements = [requirement.strip() for requirement in file.readlines()]
        requirements = filter(lambda requirement: len(requirement), requirements)
        requirements = filter(lambda requirement: not requirement.startswith('-'), requirements)
        requirements = list(requirements)

    return requirements

requirements = get_requirements()
config = {'name': name,
          'install_requires': requirements
}
setuptools.setup(**config)

My requirements file looks like:
numpy >= 1.13
pyyaml >= 3.12
matplotlib
opencv-python >= 3.2
setuptools
cython
mock
scipy
six
future
protobuf
yacs
ninja
colour
torchvision_nightly
torch_nightly --install-option="--find-links https://download.pytorch.org/whl/nightly/cu92/torch_nightly.html"

However, when I try to install the module with pip install -U ., I get the following parsing error:
Processing /home/my-module
    Complete output from command python setup.py egg_info:
    error in my_module setup command: 'install_requires' must be a string or list of strings containing valid project/version requirement specifiers; Invalid requirement, parse error at "'--instal'"

----------------------------------------

Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-req-build-rf9439sf/
Any idea on why passing --install-option causes a parse error?
Answer: Declaration of dependencies in setuptools has a different syntax than for pip. You have to convert one to the other automatically or manually.


I'm having trouble installing perl module Crypt::OpenSSL::AES

Question:
I'm having trouble installing a perl module onto my server called
Crypt::OpenSSL::AES
I'm using cpan to try to install it but it keeps coming back with an error:
<code>Checking if your kit is complete...
Looks good
Writing Makefile for Crypt::OpenSSL::AES
cp lib/Crypt/OpenSSL/AES.pm blib/lib/Crypt/OpenSSL/AES.pm
/usr/bin/perl /usr/share/perl5/ExtUtils/xsubpp -typemap /usr/share/perl5/ExtUtils/typemap -typemap typemap AES.xs > AES.xsc && mv AES.xsc AES.c
gcc -c -I. -D_REENTRANT -D_GNU_SOURCE -fno-strict-aliasing -pipe -fstack-protector -I/usr/local/include -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -DVERSION=\"0.02\" -DXS_VERSION=\"0.02\" -fPIC "-I/usr/lib64/perl5/CORE" AES.c
/bin/sh: gcc: command not found
make: *** [AES.o] Error 127
TTAR/Crypt-OpenSSL-AES-0.02.tar.gz
make -- NOT OK
Running make test
Can't test without successful make
Running make install
Make had returned bad status, install seems impossible
</code>
I have the crypt modules installed already:
Crypt::CBC
Crypt::Rijndael
but can't get Crypt::OpenSSL::AES installed. Any help would be much appreciated.
I'm using perl, v5.10.1 and Plesk Panel version 11.0.9 Update #63
Thanks
Comment: Did you read through the error message? It's pretty clear what is missing.
Answer: Your system is missing a C compiler. Install gcc and try again.