Questions which solicit opinion

Question: According to https://magento.stackexchange.com/faq#link-dontask  we should refrain from unanswerable questions.
Can you please describe to me the major differences between this question which solicits opinion:
https://magento.stackexchange.com/questions/585/top-reasons-to-switch-to-enterprise-edition
And this one:
What is the Best Magento Server Setup?
If this is not the forum for this discussion, fine. Understood. However - is it possible that I asked it wrong? Is it possible to frame such questions in an acceptable way to get the input of the most prominent developers in the Magento community?
Answer: I would have said its in the phrasing. You are asking a broad question with no specific answer.
In the comparative question, there were specific points that could be answered.

must come in under 200ms in the UK
2 dedicated web servers, load balancer, 1 db server
coming in at 800ms.
5 customers, 2 products, 4 categories,
EngineX with Varnish.
Need to get 400% quicker!

Given the information he provided, I was in a good position to give him some relevant and direct advice. What software to use, how to best utilise his existing equipment, what targets were realistic etc.

For example, if the What is the Best Magento Server Setup? question merely said:

If you could say the 3 things that sped up your Magento store the most, what would they be

You'd get answers of varying levels of accuracy and relevance; all of which are valid to the person writing the answer; but not necessarily someone else. The individual answers might each be of benefit to the community at large - but would there be one overwhelming/clear answer?
I've always been of the opinion that for the coding-type SE sites; there is (and should be) 1 best answer.

Your question comes across more as a seeding type question than whether you were actually considering buying EE. Did you actually want or need the answer?
Perhaps if your question was more along the lines of

5,000 products, 50,000 page views
Not performing as well as we hoped
Sometimes find ourselves fixing core bugs
When is the tipping point to upgrade, do you think we'd benefit

Then again, I'd be able to tap into my experience of the stores we manage and give you an educated answer.
But as your question currently stands, I don't think I could provide a meaningful or valuable response?
My goal on SE is to help others, I enjoy it. But I can't help you with your question because there is not enough information or direction on how to answer it.
Comment: I will admit that I personally do not need the input - but I feel it is helpful for others to hear the experiences of those on EE. I have worked with EE for 3 years exclusively. The spur for the question is based on Magento's own push for CE to EE upgrades - found here:  http://www.magentocommerce.com/community-to-enterprise  - their **3 bullets** approach is FPC, Abandon Cart and Tech Support. Personally I think the community could come up with 3 better reasons to switch. That's the purpose of the solicitation. I'm not offended - merely trying to find my place in this community.
Comment: As an example. You could imagine a response to someone's answer of `FPC, Abandon Cart and Tech Support` being --- **FPC** - can be provided via many different 3rd party extensions. **Abandon Cart** can be provided via many different 3rd party extensions. **Tech Support** - expect to wait weeks to a response; that will be vauge, unhelpful and accusatory. --- I don't know, I just figure it starts a debate as no-one's one answer is going to be the same as another answer, or even *the* answer.

Questions which solicit opinion


Linear Transformations Extension of Polynomials

Question:
Let $T:P2(R)→P2(R) $be the transformation linearly extending
$T(x) = x-2$
$ T(x^2−x)=x+2x^2$
$T(x−2+x^2)=-1-x^2$
Compute $T(2+x^2)=...$

Hello Everyone, I have this question to solve but I'm kinda confused how to do it. Can someone help me with this?
Comment: $P_2(\mathbb{R})$ is space of polynomials of degree $\le 2$ (hopefully). The basis is $\{1,x,x^2\}$ using the given data you can compute the values of the transformation on the basis.
Comment: What do you mean by "Extend Polynomials"?
Answer: HINT
The trick here consists in expressing the polynomial $x^{2} + 2$ in terms of $\{x,x^{2}-x,x^{2}+x-2\}$. Precisely speaking, one has
\begin{align*}
x^{2} + 2 = ax + b(x^{2}-x) + c(x^{2}+x-2) = -2c + (a-b+c)x + (b+c)x^{2}
\end{align*}
Solving the corresponding system of equations, we get that $a = 3$, $b = 2$ and $c = -1$.
Finally, we are able to compute $T(x^{2} + 2)$
\begin{align*}
T(x^{2} + 2) = 3T(x) + 2T(x^{2}-x) - T(x^{2}+x-2) = \ldots
\end{align*}
Can you take it from here?
EDIT
Based on the given comment, here it is the full answer to the question:
\begin{align*}
T(x^{2} + 2) & = 3T(x) + 2T(x^{2}-x) - T(x^{2}+x-2)\\\\
& = 3(x-2) + 2(2x^{2} + x) + (x^{2} + 1)\\\\
& = -5 + 5x + 5x^{2}
\end{align*}
Comment: I couldn't find any examples regarding this question so I couldn't do it, can you please finish it so I can use it as an example and solve other problems similar to this one.


This certificate has an invalid issuer in ios keychain

Question: Keychain show the certificate error > This certificate has an invalid issuer
See the screen shot.

RefLink>   This certificate has an invalid issuer keychain
Also I have implemented the above url solution and ipa is created but at the time of uploading the build from Application Loader its show the error as per the screen shot.
Please help anyone.
Comment: This question is answered thousands times after Feb14 when apple's world wide certificate expired . Do you search even a single time before posting a question ?
Comment: Delete your old provisional profiles and install Apple world wide certificate . Download new provisional profile and clean build will work fine .
Comment: Just removed all the certificates and Reinstall and its shows  "This certificate has an invalid issuer " in key chain
Comment: Possible duplicate of [Uploading archive error: "Missing iOS Distribution signing identity for ..."](http://stackoverflow.com/questions/35397453/uploading-archive-error-missing-ios-distribution-signing-identity-for)
Answer:
Download https://developer.apple.com/certificationauthority/AppleWWDRCA.cer
and double-click to install to Keychain.
Select "View" -> "Show Expired Certificates" in Keychain app.
Remove Apple Worldwide Developer Relations Certificate Authority certificates from "login" tab and "System" tab in Keychain app.

Ensure the new downloaded cert is in both login and system Default to only system tab will still give error.**

Delete all your certificates and provisioning profile on developer portal.
Create certificate signing request from keychain.
Recreate all the certificate & provisioning profile using the CSR generated in step -5
Download and install those certificates created on step-6 and try.
Comment: OK I am trying again.
Comment: I have recreated the developer and distribution profile and its still show that error.
Comment: I have done all the things but still not resolved. I checked the Xcode preferences its show the ios Development and iosDistribution is revoked instead of valid. as per the image updated in the question. Can anyone confirm how this can resolved.
Comment: Finally done this question. I have missed the deleting of apple certificate from system. After removing that Invalid issuer is invalid keychain issue is resolved.
Answer: Try to install new certificate from link below.
https://developer.apple.com/certificationauthority/AppleWWDRCA.cer
This worked for me. I hope this will help you.
After this create and install new iOS Distribution and iOS Development Certificate.
Comment: I have downloaded this apple.cer and reinstall the iosDistribution and Development Certificate of app. But not resolved.
Comment: create new provisioning profile for app development,AdHoc and app distribution.And after that retry to upload or export your app.


Using Arrays.asList with int array

Question: Using java.util.Arrays.asList, why its shows different list size  for int (Primitive type) and String array?
a) With int array, whenever I execute following program the List size = 1
public static void main(String[] args) {
        int ar[]=new int[]{1,2,3,4,5};
        List list=Arrays.asList(ar);
        System.out.println(list.size());

    }

b) But if i change from int array type to String array(like String ar[] = new String[]{"abc","klm","xyz","pqr"};) , then I am getting the list size as 4 which i think is correct.
PS : With Integer (Wrapper Class) array, then result is Fine, but i am not sure why in primitive int array, the list size is 1. Please explain.
Comment: Probably your compiler even gave you a raw type warning on `List`. Many IDEs will present a couple of useful fixes, one of them changing `List` to `List`. The latter pointing you towards the answers of "daerin" and "icza".
Answer: List cannot hold primitive values because of java generics (see similar question). So when you call Arrays.asList(ar) the Arrays creates a list with exactly one item - the int array ar.
EDIT:
Result of Arrays.asList(ar) will be a List<int[]>, NOT List<int> and it will hold one item which is the array of ints:
[ [1,2,3,4,5] ]

You cannot access the primitive ints from the list itself. You would have to access it like this:
list.get(0).get(0) // returns 1
list.get(0).get(1) // returns 2
...

And I think that's not what you wanted.
Comment: So If the Arrays creates a list with exactly one item -the int array `ar` then how to traverse and access that primitive values from it using list?
Comment: Got it! It should be like `int ab[]=(int[]) list.get(0);`
Comment: Watch carefully! `list.get(0).get(0)` wouldn't be accessible directly here as last `get()` is undefined until and unless you **typecast** the whole statement to some other collection (that have `get` method)
Answer: List is a generic type, primitive types are not valid substitutes for the type parameter.
So in your first example when you call Arrays.asList() with an int[], the value for the type parameter will be int[] and not int, and it will return a list of int arrays. It will have only 1 element, the array itself.
The second case will be a List<String>, properly holding the 4 strings which you pass to it.

Using Arrays.asList with int array


Python erroring when called from Apache but not commandline with close failed in file object destructor:

Question: I've a Python script which works perfectly when called from the command-line but dies when called from a php script running on Apache on the same machine.
Error meesage (scraped from Apache error log):
<code>close failed in file object destructor:
sys.excepthook is missing
lost sys.stderr
</code>
Call in PHP:
<code>$exec_string = '/usr/bin/python /path/to/file/doSearch.py "' . $data[ 'term' ] . '"' . $id . ' &';
pclose( popen( $exec_string , 'r' ) );
</code>
The Python file is crunching data and then writing back to the filesystem.
Answer: I think you're missing a space after the first argument. Try this:
<code>$exec_string = '/usr/bin/python /path/to/file/doSearch.py "' . $data[ 'term' ] . '" ' . $id . ' &';
//      see hat here -->                                                           ^
</code>
You probably want to make sure you're escaping all that data too, to make it safe for CLI.
Answer: There should be some outputs from your process which to be executed in popen function.
However, pclose will cause this exception when do fclose this reading file stream directly.


How to add captions in each individual plot using facet_grid in R?

Question: I am using facet_grid to draw several plots and I am wondering how to add some extra information as a caption in each individual plot.
I managed to add information in the title of each plot (in order to add the Kruskal-Wallis p-value), but I would like to add more info below each plot (as a caption).
Here is a reproducible example:
library(ggplot2)
library(dplyr)
set.seed(1234)
Gene <- floor(runif(25, min=0, max=101))
Age <- floor(runif(25, min=18, max=75))
Group <- c("Group1", "Group1", "Group3", "Group2", "Group1", "Group3", "Group2", "Group2", "Group2", "Group1", "Group1", "Group3", "Group1", "Group2", "Group1", "Group2", "Group3", "Group1", "Group3", "Group3", "Group2", "Group1", "Group3", "Group3","Group2")

df <- data.frame(Gene, Age, Group)
df$Group <- as.factor(df$Group)

mybreaks <- seq(min(df$Age)-1, to=max(df$Age)+10, by=10)
df$groups_age <- cut(df$Age, breaks = mybreaks, by=10)

bp <- ggplot(df, aes(x=groups_age, y=Gene, group=groups_age)) +
  geom_boxplot(aes(fill=groups_age)) +
  facet_grid(. ~ Group)

bp

pval <- df %>%
  group_by(Group) %>%
  summarize(Kruskal_pvalue = kruskal.test(Gene ~ groups_age)$p.value)

# This is to create new labels for the facetgrid where we can show the phenotype and the KW pvalue.
labels <- c(paste('Group 1\n KW p-val:', signif(subset(pval$Kruskal_pvalue, pval$Group=="Group1"), digits = 3)),
            paste('Group 2\n  KW p-val:', signif(subset(pval$Kruskal_pvalue, pval$Group=="Group2"), digits = 3)),
            paste('Group 3\n  KW p-val:', signif(subset(pval$Kruskal_pvalue, pval$Group=="Group3"), digits = 3)))

df$KW <- factor(df$Group, levels = levels(df$Group), labels = labels)

bp <- ggplot(df, aes(x=groups_age, y=Gene, group=groups_age)) +
  geom_boxplot(aes(fill=groups_age)) +
  facet_grid(. ~ KW) +
  theme(legend.position="none")
bp

This is the result of the code above:

This is the only way that I could think of if I want to add info about each plot as a caption.
df_group1 <- df[df$Group == "Group1",]
df_group2 <- df[df$Group == "Group2",]
df_group3 <- df[df$Group == "Group3",]

myfunction <- function(DF){
  df <- as.data.frame(table(DF$groups_age))
  # This is to add  ": n = " to the first column
  df$Var1 <- paste(df$Var1, ": n = ", sep = "")
  # We join both columns in one to have the result together.
  df$X <- paste(df$Var1, df$Freq)
  # We save that column into a variable
  vec <-  df[["X"]]
  return(vec)
}

numb_group1 <- myfunction(df_group1)
numb_group1 <- paste(numb_group1, collapse = "; ")

numb_group2 <- myfunction(df_group2)
numb_group2 <- paste(numb_group2, collapse = "; ")

numb_group3 <- myfunction(df_group3)
numb_group3 <- paste(numb_group3, collapse = "; ")

numb_all <- c(numb_group1, numb_group2, numb_group3)

bp <- bp + labs(caption = paste0("Group 1: n = ", nrow(subset(df, df$Group=="Group1")),
                                 "\n",
                                 "           Groups: ", numb_all[1],
                                 "\n",
                                 "\n",
                                 "Group 2: n = ", nrow(subset(df, df$Group=="Group2")),
                                 "\n",
                                 "           Groups: ", numb_all[2],
                                 "\n",
                                 "\n",
                                 "Group 3: n = ", nrow(subset(df, df$Group=="Group3")),
                                 "\n",
                                 "           Groups:", numb_all[3]
)) +  theme(legend.position="none",
            plot.caption = element_text(hjust = 0, face= "italic")) #Default is hjust=1
bp

This is how it looks:

However, I would like to improve my code and find another way (if it exists) to put each info below to each individual plot.
Does anyone have an idea of what it can be done?
Thanks very much in advance
Comment: I don't have a multi-caption facet solution to hand, but if I didn't have to make too many plots, I would create separate plots with individual captions and add them together with the Patchwork library to give the illusion of a facetted plot (with added customisation at the cost of creating additional plots).
Answer: Generally-speaking for plot captions on multi-faceted plots:

If you want a single caption which is below alll plots, you should use theme(plot.caption = ...).

If you want the same caption to appear below each facet, you can do this using annotate() and turn clipping off.

If you want to have different captions to appear below each facet, you will need something capable of being mapped to a dataset (so you can specify the different text per facet).  In this case, I would recommend using geom_text() and doing a clever bit of formatting to fit in the caption.

An alternative to have different caption per plot would be create individual plots with captions and link them together via grid.arrange() or patchwork or cowPlot()...

Here's the example of the third case using geom_text() and mtcars.  I hope you can apply this to your own dataset.
The basic plot
Here's the basic plot we'll use for adding a caption:
library(ggplot2)
p <- ggplot(mtcars, aes(qsec, mpg)) + geom_point() +
        facet_wrap(~cyl)

Caption Data frame
To make the caption plot, we first need to define the text per each facet.  It's best to do this in a separate data frame from your bulk data.  This ensures that there is not any overplotting of the text geom (drawing in the same place multiple times), since one text geom is drawn per observation in a data frame.  Here's our dataframe for captions:
caption_df <- data.frame(
  cyl = c(4,6,8),
  txt = c("carb=4", "carb=6", "carb=8, OMG!")
)

Plotting with captions
To make the plot, we need to adjust a few things to our plot.

Add the caption.  Add a geom_text() and map to caption_df.  We'll map the text, but the position will be fixed in x and y.  The x value is set to be the minimum of our original data, but we could set that manually too.  The y value needs to be set a value that would place it below the original plot.

Confine the limits of the plot.  Since we place our text geom below the original plot area, if we did not confine the limits of the plot area, ggplot2 would just expand the y limits to fit the new text.  We need to keep the original y limits to ensure the y value of the geom_text() we add stays below this area.

Turn off clipping.  In order to actually see the new captions, you need to turn off clipping.  You can do this in any of the coord_*() functions, so we'll use coord_cartesian() to do this and set the y limits.

Increase lower margin.  To ensure we see the caption in the final image, we need to increase the margin below the plot via theme(plot.margin=...).

Here's the final result of all that.
ggplot(mtcars, aes(qsec, mpg)) + geom_point() + facet_wrap(~cyl) +
  coord_cartesian(clip="off", ylim=c(10, 40)) +
  geom_text(
    data=caption_df, y=5, x=min(mtcars$qsec),
    mapping=aes(label=txt), hjust=0,
    fontface="italic", color="red"
  ) +
  theme(plot.margin = margin(b=25))

Comment: Wow, thanks for the great and long explanation! Thanks very much for your help.
Answer: After having tried a lot of things with facet_grid and captions, I created some posts where I got really great answers that can help someone with this problem.
This is the main solution: https://stackoverflow.com/a/71557785/13997761
Although this created me some questions when I was trying to automatize the code: https://stackoverflow.com/a/71561745/13997761 and https://stackoverflow.com/a/71569950/13997761.
However, I realised that for this case it is better to put the number of observations above each boxplot. It is more visual and it is not necessary a lot of code.
myFreqs <- df %>%
  group_by(Group, groups_age) %>%
  summarise(Freq = n())
myFreqs

bp + stat_summary(geom = 'text', label = paste("n = ", myFreqs$Freq), fun = max, vjust = -1, position = position_dodge(width=0.7))


Clarifying a part of Caratheodory's theorem proof

Question: The first part of proving the collection of $\mu^*$-measurable sets is a $\sigma$-algebra is showing it is closed under finite (yes, finite) union. That is, for a set $\Bbb{X}$ and an outer-measure $\mu^*$ on $\Bbb{X}$, if $A,B$ are $\mu^*$-measurable sets, then $A \cup B$ is $\mu^*$-measurable as well. The proof starts like this:
$\mu^*(E) = \mu^*(E \cap A) + \mu^*(E \cap A^c) = \mu^*(E \cap A \cap B) + \mu^*(E \cap A \cap B^c) + \mu^*(E \cap A^c \cap B) + \mu^*(E \cap A^c \cap B^c)$.
Why is the second equality true? It actually means that a subset of a $\mu^*$-measurable set (here namely $E \cap A$ or $E \cap A^c$) is $\mu^*$-measurable, right?
Comment: It's the $\mu^{\ast}$-measurability of $B$, applied to the sets $F_1 = E\cap A$ and $F_2 = E \cap A^c$.
Answer: It's using the $\mu^{\ast}$-measurability of $B$,
$$\mu^{\ast}(F) = \mu^{\ast}(F\cap B) + \mu^{\ast}(F\cap B^c)\,,$$
for the two sets $E\cap A$ and $E \cap A^c$.


Laravel where() inside a whereHas() access other side table column

Question: Sorry for the messy title, i didnt knew how to describe it.
So i got three tables tables in re model: students, groups, and the table that relates them called courses.
Im trying to get every "student" that has no group assigned or that has assigned a group with a year greater than 2019, i got this code so far, but i cant access the year column, i tried with the "with()" method but i got no luck, any ideas?
My models on laravel:
Student:
public function courses()
{
    return $this->hasMany(\App\Models\Course::class, 'id_student');
}

Group:
public function courses()
    {
        return $this->hasMany(\App\Models\Course::class, 'id_group');
    }

Course:
public function student()
    {
        return $this->belongsTo(\App\Models\Student::class, 'id_student');
    }

public function group()
{
    return $this->belongsTo(\App\Models\Group::class, 'id_group');
}

My query:
$students_noassigned = Student::whereHas('courses', function ($query) {
            $query->where('year', '>', 2010);
        })
            ->doesntHave('courses', 'or')
            ->get();

Answer: If you don't want to set a relationship directly between Student and Group (Belongs To Many) via the pivot you could try this:
$students_noassigned = Student::whereHas('courses.group', function ($query) {
    $query->where('year', '>', 2010);
})->orDoesntHave('courses')->get();

Get students that have courses that have a group with year > 2010 or doesn't have any courses, no groups assigned.


Logit - probit regression

Question: I was running regression of - determinants of acceptance into a social science college. I found this unrelated paper (Screenshot of relevant page attached herewith). Here, they have computed logit and probit regression at probabilities =0.5 and 0.8 and compared it with linear probability regression.
I was wondering can we do the same in stata? (Can we run logistic regression in stata at a particular probability say 0.5)
I tried to look this problem over the internet but couldn't find any useful resource on this.
Answer: The authors are evaluating the marginal effects at the two levels of probability. It's just the derivative of the conditional probability for the logit or probit model times the corresponding coefficient. I knew this because the multiplicative factors on the index function coefficients (.25, .4, .16, .28) correspond to those derivatives. You can do this with lincom or margins of an expression in Stata.
This is an old fashioned approach to showing marginal effects that was more popular when statistical software was less developed.

Edit:
In response your comment, here is some code showing this calculation using lincom and margins on the cars dataset. I think you are mistaken about what these commands can accomplish. You can find the derivation of the marginal effect for logit here and probit here. There is some code at the end showing how to calculate the average marginal effects, which should have correct larger SEs, will also handle categorical variables correctly, and are arguably more representative of your data that the approach in this paper. Moreover, their approach in the paper treats the categorical variables as if they were continuous, which can be odd.
#delimit;
sysuse auto, clear;

/* OLS */
regress foreign c.mpg, robust;
margins, dydx(mpg);

/* Logit MEs at p = 0.5 and p = 0.8 */
logit foreign c.mpg, nolog;
/* NB: these SEs are too small */
lincom .5*(1-.5)*_b[mpg];
lincom .8*(1-.8)*_b[mpg];
margins, expression(.8*(1-.8)*_b[mpg]);

/* Probit MEs at p = 0.5 and p = 0.8 */
probit foreign c.mpg, nolog;
/* NB: these SEs are too small */
lincom `=normalden(invnormal(.5))'*_b[mpg];
lincom `=normalden(invnormal(.8))'*_b[mpg];
margins, expression(normalden(invnormal(.8))*_b[mpg]);

/* Plot for all possible values of p (not just 0.5 and 0.8) */
tw
    (function y = .0312915)
    (function y = x*(1-x)*.1597621, range(0 1))
    (function y = normalden(invnormal(x))*.0960601, range(0 1))
, ylab(#10, angle(horizontal) grid)
ytitle("Change in Probability")
xlab(#10, grid)
xtitle("Predicted Probability of Foreign Origin")
xline(.5 .8, lpatter(dash))
title("Marginal Effect of an One Additional MPG at Different Pr(Foreign)", span size(medium))
legend(label(1 "OLS ME" ) label(2 "Logit ME") label(3 "Probit ME") rows(1));

/* Average Marginal Effects with continuous and categorical covariates */
gen high_mpg = mpg>21;
logit foreign c.weight i.high_mpg, nolog;
margins, dydx(*);

The general plot looks like this, which shows that the effect depends on the baseline probability for logit and probit, but not for OLS, where the ME is constant. That is, the effect is biggest for observations that are likely to go either way and smallest for the very likely and very unlikely observations in the non-OLS models:
Comment: Thanks you so much.
Comment: I looked into the commands that you provided. I don't know how that is useful. Lincom is used to compare variables and not model, not the way I want. Margin compute odd ratios at different values of independent variable and not for specific values of dependent variable.
Comment: @ElinaGilbert I added some more material in response to your concerns.
Comment: Great explanation indeed!

Logit - probit regression


surface area when the curve is revolved about the x-axis

Question: find the surface area when the curve is revolved about the x-axis
Steps so far:
$y=\sqrt{4x+3}$ on $[0,3]$
$$S=\int_{a}^{b} 2π \left(f(x)\right)\sqrt{1+f'(x)^2} $$
$$S=\int_{a}^{b} 2π \left(\sqrt{4x+3}\right)\sqrt{1+(\frac{2}{\sqrt{4x+3}})^2} dx $$
$$S=\int_{a}^{b} 2π \left(\sqrt{4x+3}\right)\sqrt{1+\frac{4}{4x+3}} dx$$
I get stuck here, I hope someone can guide through this problem
Comment: $y^2=4\left (x+\frac{3}{4}\right )$ is a parabola with vertex at $\left (0,-\frac{3}{4}\right )$. Just find the surface area of paraboloid formed by rotating $y^2=4x$ in $\left [0,\frac{15}{4}\right ]$ and subtract the surface area of the same paraboloid in the interval $\left [0,-\frac{3}{4}\right ]$
Comment: @AvZ wait I am confused now
Comment: The paraboloid formed $y^2=4x$ has same surface area as $y=\frac{x^2}{4}$ if you like working with $x$...
Comment: @AvZ so would the answer be $2(8\sqrt{6}-4\sqrt{3})\pi$?
Answer: Looks like you just need to do a little extra algebra. Notice that $$\begin{align}\left(\sqrt{4x+3}\right)\sqrt{1+\frac{4}{4x+3}} = \sqrt{(4x+3)\left(1+\frac{4}{4x+3}\right)} \\ = \sqrt{(4x+3)\cdot 1+\frac{4(4x+3)}{4x+3}}  \\ = \sqrt{4x+7}\end{align}$$ And hence $$2\pi\int_{0}^{3} \left(\sqrt{4x+3}\right)\sqrt{1+\frac{4}{4x+3}} dx = 2\pi\int_{0}^{3}\sqrt{4x+7} dx$$ This remaining quantity should be readily solvable with a $u$-sub.
Comment: totally got it now. thanks a lot


Why is file_managed not updated correctly?

Question: In a custom module (amap), I have a custom content entity (contract) created with Drupal Console.
There are standard CRUD functions on this entity.
One of the fields of the entity is a file field:
$fields['file1'] = BaseFieldDefinition::create('file')
  ->setLabel(t('Source file'))
  ->setDescription(t('Source file (may be modified)'))
  ->setSettings([
    'target_type' => 'file',
    'file_extensions' => 'doc docx odt pages',
    'uri_scheme' => 'private',
    'file_directory' => 'contracts',
  ])

When I create one contract adding a file (a.pages) to the entity, everything works as expected: a file with permanent status is added to file_managed table and appears in Files tab of content page:

and the corresponding record is added to file_usage table:

My first problem appears when I want to update the contract changing the file (to Contract.doc, for example):
file_usage table is correctly updated:

but file_managed table is not! The previous file (a.pages) is still there with permanent status.

The second problem is quite the same: when I delete the contract, file_usage table is correctly updated: there is no more record related to these files.
But file_managed table is not! The previous file (a.pages) is still there with permanent status (as in update mode).
My question is: is is normal?
Do I have to handle file_managed table myself?
Why is file_usage correctly updated and not file_managed?
I naively thought it was the case...
Comment: I believe there is a hidden core flag now for files that is named something like "mark unused files as temporary" and it defaults to FALSE. I don't have any code in front of me so I'm not 100%. But I just fixed something similar to your case.
Answer: I changed file.settings config entry make_unused_managed_files_temporary to true and it seems to do the job.
Just hope there won't be any side effects...
Comment: The default for that setting is `FALSE` because some sites were having their files unexpectedly deleted when usage wasn't accurately updated (e.g. I had encountered this with a WYSIWYG editor's file uploader that didn't add a usage entry).
Comment: Yeah, thats exactly why it was added.
Comment: So, I can use it if I ensure that usage is properly managed?


Is it inappropriate to use Fisher's exact test when cell counts are high?

Question: I have not been able to find an authoritative source on when it is inappropriate to use Fisher's Exact test in the context of cell counts. I know that it can be computationally intensive to use Fisher Exact test's if the cell counts are large, but if I am not concerned with computation time, is it still statistically valid to use Fisher Exact's test on a 2x2 contingency table with large cell counts?
Please let me know if I can clarify the question.
EDIT:
Some links that imply there is an issue with large cell counts for Fisher's Exact test:

https://graphpad.com/quickcalcs/contingency1/

This calculator from graphpad will not allow you to use Fisher's Exact test when cell counts are large --> it uses Chi Squared test instead.

https://stackoverflow.com/questions/30472087/r-is-fishers-exact-test-with-large-numbers-still-accurate?rq=1

This thread where a comment states "Why on earth would you do a fisher's exact test for this? That test is better suited for small counts."

That's all I have for now.
Comment: There is no assumption of "only low counts" behind the Fisher exact test, so it is OK.
Comment: Your links suggest there is a computational issue (under- or overflow as well as time). It is still theoretically valid
Comment: could you give links to some of the strong opinions?  That would give us an idea what the strong opinions are based on.  Agree with @kjetilbhalvorsen that I know of no reason other than computational not to use FET w/ large cell counts (*not* getting into the argument about fixed vs variable marginal totals ...)  I haven't checked it, but I generally suggest Agresti's [Categorical Data Analysis](https://www.amazon.com/Categorical-Data-Analysis-Alan-Agresti/dp/0470463635) as an authoritative reference on such questions.
Comment: That was what I thought.  There are some strong opinions on this subject across the web, so I wanted to get some input. Thanks
Comment: Sure, let me see if I can go back and find them.
Answer: Strictly speaking, Fisher's exact test computes the proportion of possible contingency tables (number of combinations of cell counts) conditional on the marginals that is as extreme or more extreme than your contingency table.  When the counts are large, this leads to a combinatorial explosion.  Computers really are pretty fast these days, but they can still be overwhelmed.  Here is an example, coded in R:
fisher.test(matrix(c(19874393874932817,943850439754375437,
                     19743832745983274,981749374918734987), nrow=2))
# Error in fisher.test(matrix(c(19874393874932816, 943850439754375424, 19743832745983272,  :
#   'x' has entries too large to be integer
chisq.test(matrix(c(19874393874932817,943850439754375437,
                    19743832745983274,981749374918734987), nrow=2))
#   Pearson's Chi-squared test with Yates' continuity correction
#
# data:  matrix(c(19874393874932816, 943850439754375424,
#                 19743832745983272, 981749374918734976), nrow = 2)
# X-squared = 2.0502e+13, df = 1, p-value < 2.2e-16

So there is nothing really invalid about using Fisher's exact test in these cases, it's just that the computations are intractable.
Comment: Meanwhile something like `matrix(c(1987439, 943850, 2060383, 981749), nrow = 2)` works with both tests, and the p-values of  `0.05778` and `0.05783` are close


IPhone 3GS with iOS 4.2.1 does not sync with Exchange 2003 SP2 since update

Question: lately my boss updated his iphone 3GS to iOS 4.2.1 which is causing the email sync to fail. the problem is kinda weird because, calender and contacts do sync and sending new email from the iphone is possible too, but new incoming emails wont show up.
other mobile devices work just fine (iphone 4 & some droids)
did anybody else experienced the same problem?
i already tried the following:

installed the profile from apple which changes the default timeout (http://km.support.apple.com/library/APPLE/APPLECARE_ALLGEOS/TS3398/DefaultEASTaskTimeout.mobileconfig)
removed the self-signed ssl cert and readded it
reentered all exchange related settings
Answer: the problem vanished today for no apparent reason ...


Making a Call by Image icon in a List view by fragments in android

Question: I have a list view with person picture, name and image icon for calling.
I passed the picture and name by arrays but gives errors when passing phone numbers as a array.
Arrays
String[] names = {"abc", "xyz"}
int [] pics = {getting 2 images from drawable};
String[] phone_numbers = {"0110101010","0110101010"};

My code
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);

rootView = inflater.inflate(R.layout.fragment_student_list, container,false);

studentList=(ListView) rootView.findViewById(R.id.studentListView);

//adapter object set list view to it
studentListAdapter madapter = new studentListAdapter (getActivity(),names,pics);

//calling function
studentList.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse(phone_numbers));

    }

});

Edit: My error is when Uri.parse(phone_numbers)); shows error. String phone_numbers = "0110101010" correct the error(removing as a array). But it does not the solution I want.
Please help me to launch call from list items.
Comment: what is the error?
Comment: and show your adapter code
Comment: Have you added one more parameter in ShopInfoAdapter class constructor of type String[]  to receive phone number?
Comment: @VivekMishra please check the edit in my question.
Comment: you can't pass complete array in that method add a single number in Uri.parse() method
Answer: try this:
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

    rootView = inflater.inflate(R.layout.fragment_student_list, container,false);

    studentList=(ListView) rootView.findViewById(R.id.studentListView);

    //adapter object set list view to it
    studentListAdapter madapter = new studentListAdapter (getActivity(),names,pics);

    //calling function
    studentList.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
             Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone_numbers[targetposition]));
startActivity(intent);

        }

    });

EDIT:
i edited the code above, also make sure to include this in your androidmanifest
<uses-permission android:name="android.permission.CALL_PHONE" />

Comment: by adding this shows unfortunatly stopped error. help me on this. @locomain,
Answer: Instead of Passing complete array of phone numbers to Uri.parse() method, pass a single number from your array to that method.
Like this
Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse(phone_numbers[0]));

Comment: by adding this shows unfortunatly stopped error. help me on this. @VivekMishra
Comment: add your crash logs and line on which it crashes in your question


Proof of $\sum_{k=n-1}^{n+p-1} {k \choose p}={n+p \choose p}$ using the equation $x_1 + x_2 + \dots + x_n = p$

Question: So we consider the following equation: $$x_1 + x_2 + \dots + x_n = p$$ We dnote the set of solutions (lists of $\{0, \dots ,p \}$) by $A(n,p)$.
If we write $p=1+1+\dots+1$ then the problem can be reduced to putting p indistinguishable balls in $n$ ordered containers, or in other words, how many ways there are to arrange the inner $n-1$ walls of our containers and the $p$ digits.
Thus $$|A(n,p)|={n+p-1\choose p}$$
I'm trying to use this to prove the equation $$\sum_{k=n-1}^{n+p-1} {k \choose p}={n+p \choose p}$$
The RHS is the cardinality of $A(n+1, p)$, and we can count its elements by looking at the possible values of $x_{n+1}$, this give: $$\sum_{x_{n+1}=0}^{p}|A(n, p-x_{n+1})|=\sum_{x_{n+1}=0}^{p}{n+p-x_{n+1}-1\choose p-x_{n+1}}$$
But my book writes it as: $$\sum_{x_{n+1}=0}^{p}{n+p-x_{n+1}-1\choose p}$$
Where is the error?
Thanks in advance.
Comment: Your expression looks right to me.  The book's is clearly wrong.  Try substituting $n=2,\ p=5.$
Comment: Your solution looks correct.
Answer: Your book's equation
$$
\sum_{k=n-1}^{n+p-1}\binom{k}{\color{red}p}=\binom{n+p}{p}
$$
is incorrect. However,
$$
\sum_{k=n-1}^{n+p-1}\binom{k}{\color{#080}{n-1}}=\binom{n+p}p
$$
is correct. With this, everything works smoothly:
\begin{align}
\binom{n+p}{p}
&=A(n+1,p)
\\&=\sum_{x_{n+1}=0}^p A(n,p-x_{n+1})
\\&=\sum_{x_{n+1}=0}^p \binom{n+(p-x_{n+1})-1}{p-x_{n+1}}
\\\\&(\text{reindex summation by }{k=n+p-x_{n+1}-1})\\
\\&=\sum_{k=n-1}^{n+p-1}\binom{k}{k-(n-1)}
\\&=\sum_{k=n-1}^{n+p-1}\binom{k}{n-1}.
\end{align}
Comment: Thank you, it's often hard to imagine that the book is wrong, especially when I'm still struggling.


A form of Russell's Paradox

Question: Let $S$ be some set and $A=\{x\in S \vert x \notin x \}$. Prove that $A\in S$.
If I assume $A\notin S$ then $A \notin A$ which implies $A\in A$ which is a contradiction. Therefore, $A\in S$.
Is this the correct way to go about proving these statements?
Edited to add: The OP has since aknowledged in a comment that the thing to be proven is that $A\notin S$.
Comment: In fact in $\mathsf{ZF}$ one can prove that $\forall x(x\notin x)$, so $A=S$, and $A\color{red}{\notin}S$.
Comment: I'm hesitant to say no, but I didn't follow your argument and I believe the statement you're trying to prove is false: take $S=\emptyset$ for example.
Comment: If $S$ is empty, then $A$ is also empty but $\varnothing\not\in\varnothing$.
Comment: No.  $A \not \in A$ does not imply $A \in A$ because $a \not \in S$.  S is not the universal set so if $A \not \in S$ then .... nothing.
Comment: Let S = {$\emptyset$}.  Then $A = \{\emptyset\} = S$.  But $\{\emptyset\} = S\not \in S$.  Your statement is false.
Comment: @BrianM.Scott are we assuming ZF.  By the very statement of the exercise I assumed we were deliberately not assuming ZF.
Comment: This isn't really a form of russell's paradox as for any sets in ZF yield nonparadoxical trivial results.  Even sets violating ZF need not lead to paradox.  However if we define S to include A as member (antiZF) then we do get a paradox and I believe it would be a form or Russell's paradox.
Comment: @fleablood: I was pointing out that we cannot possibly hope to show that $A\in S$. (And I see that it turns out that the question was indeed stated incorrectly.)
Comment: @BrianM.Scott  I'm not disagreeing with you.  With AFZ $x\not \in x$ would true for all $x$ and so $A $ = {all sets in S}.  And by ZFC A not in S.  But I assume to even *talk* about sets containing themselves it is assumed we are regressing to a preZFC state.  Of course then we shouldn't do proofs by contradictions because we can not assume things are well defined in the first place.  Not being able to resolve not P does not mean P can (or must) be resolved.
Answer: The statement is false.
Counter example:  $S = \{\emptyset\}$  so $A = \{x \in S|x \not \in x\} = \{\emptyset\}=S$.  But the only element in $S$ is $\emptyset$ and $\{\emptyset\} \ne \emptyset$ and $\{\emptyset\} \not \in S$.
Your argument is faulty in that to have $A \not \in A=\{x\in S|x \not \in x\} \implies A \in A$ we must have $A \in S$ which we do not.
However the opposite $A \not \in S$ can be proven.  If $A \in S$ then either $A \in A$ or $A \not \in A$.   $A \in A \implies A\not \in A \implies A\in A$.  Impossible.  So $A \not \in S$.
Of course, I'm not sure that is complete as I'm not sure we can assume $A$ is always possible.  (If $S$ equals the set of all sets this is exactly Russell's Paradox.)
Comment: Whether $A$ exists depends on your axioms of set theory. Under the axiom of separation (one of the standard axioms of ZF(C)), it always does; under (say) NF (= New Foundations) or positive set theory, it doesn't.
Comment: I was deliberately assuming we were not using the axioms of ZF(C).  If we use ZF(C) then $x \not \in x$ is a redundancy and there's no point in doing this question at all.  If so A must not only exist but be equal to S. However if we are using axioms in which $x \not \in x$ might be a significant statement (i.e. axioms in which $x \in x$ is possible) then such axioms can contain Russell like paradoxes.  Proving $A \in A$ is impossible is no the same as proving $A \not \in A$.  And Proving $A \not \in S$ doesn't mean $A \in S^c$ either.
Comment: yes, sorry - my comment was not meant as criticism of your answer (which is absolutely right), but rather as clarification for the OP.
Answer: Your argument is false. In particular your claim that since $A \notin A$ it follows that $A \in A$ is false. Let us see why. Recall that $A$ consist of those $x \in S$ such that $x \notin x$ and hence the statement $A \notin A$ only would imply that $A \in A$ if $A$ was in $S$ (which it is not). Are you sure you didn't want to prove that $A \notin S$?
Comment: Ah, I was supposed to prove that $A\notin S$. My apologies.

A form of Russell's Paradox


How to connect local machine database with the looker studio mySql Extention

Question: I have to connect a local machine database to the looker studio with MySql Extention.
I am trying to the connect my local database machine but the thing is not working because of in beetween corporate firewall.
so the firewall denied the inbound packets and got the Error on looker studio like this.
Answer: As of Looker Studio docs: Connect to MySQL:

Note: Looker Studio can't connect to localhost. You must use a public hostname or IP address.

So, to use Looker Studio MySQL Connector your Database should be publicly available.
Comment: @ Diego Queiroz Thanks for the replay. There is no any connection on publicly but my local database on 127.0.0.1 this IP on our company firewall are the denied the packet
Comment: @AdwellScott maybe you should learn a little about networking. 127.0.0.1 is a "fake" IP that means "localhost". So it is not accessible by anyone out of the local machine (and it's not due to your firewall).


Spring Data REST - RepositoryEventHandler methods not getting invoked for POST method?

Question: I have the following domain object and DTO defined.
Country.java
@Data
@Entity
public class Country extends ResourceSupport {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long countryID;

    @NotBlank(message = "Country name is a required field")
    private String countryName;

    private String countryNationality;
}

CountryDTO.java
@Data

public class CountryDTO {

    private List<Country> countries;
}

I have overridden the POST method in the RepositoryRestController for the country class.
@RepositoryRestController
public class CountryController {

    @Autowired
    private CountryRepository repo;

    @RequestMapping(method = POST, value = "countries")
    public @ResponseBody ResponseEntity<?> createCountry(@RequestBody Resource<CountryDTO> dto,
            Pageable page, PersistentEntityResourceAssembler resourceAssembler) {

        Country savedCountry = repo.save(dto.getContent().getCountries());
        return new ResponseEntity<>(resourceAssembler.toResource(savedCountry), HttpStatus.OK);
    }

}

Now I have defined a RepositoryEventHandler to handle validations.
@Component
@RepositoryEventHandler
public class CountryHandler {

    @HandleBeforeCreate
    public void handleBeforeCreate(Country country) {

        System.out.println("testing");

}

But when I send a POST request to the endpoint http://localhost:8080/countries, the eventhandler does not get invoked. Is there anything I am doing wrong?
UPDATE 1:
I am sending the following JSON to the endpoint using Postman.
"countries":[{
    "countryName":"Australia",
    "countryNationality":"Australian"

}]

Comment: How are you invoking a POST on that URL?
Comment: I am sending a JSON through Postman
Answer: It is difficult to give you an exact solution not knowing how you are invoking the request. But possible reason is that you are missing the slash symbol @RequestMapping value attribute:
@RequestMapping(method = POST, value = "countries")

Should be:
@RequestMapping(method = POST, value = "/countries")

Comment: you can ask for info you need using comments
Comment: I have updated the question with the JSON I am sending to the endpoint
Comment: Ok, did you try to put slash in RequestMapping value as I had proposed?
Answer: Define a Bean in AppConfigration as
@Configuration
@EnableAsync
public class AppConfig {

  @Bean
    CountryHandler countryHandler (){
        return new CountryHandler ();
    }

}

It will work then.
Answer: Try editing maybe  the Controller class annotation from:
@RepositoryRestController

to
@RestController

and mainly the method annotation from:
@RequestMapping(method = POST, value = "countries")

to
@RequestMapping(value = "/countries", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)

PS: produces = MediaType.APPLICATION_JSON_VALUE if you are going to return json.
Comment: If I change to @RestController my controller class will be out of Spring Data Rest scope and I will have to implement GET, PUT and DELETE methods as well
Comment: I do not think so. `Open Declaration org.springframework.web.bind.annotation.RestController`. You can have `@RestController` with `@RequestMapping(value = "/countries", method = RequestMethod.POST)` for sure. I am not sure what you mean by implementing another GET PUT DELETE methods ? For Rest controllers I have always used those two annotations for the class and the method and I have never had any problems invoking a method or else. (Of course when we are talking about Spring not `Open Declaration javax.ws.rs.*` )
Comment: I am using Spring Data Rest so there is actually no need to implement a controller. Spring does that at runtime. But since I am using a DTO I have to implement a POST method.
Answer: I know this is older but this works as it is supposed to.
The methods defined in a @RepositoryRestController implementation replace the methods in the default RepositoryEntityController which publish @RepositoryEventHandler events.
So your controller needs to publish a create event:
@RepositoryRestController
public class CountryController {

    @Autowired
    private CountryRepository repo;

    private final ApplicationEventPublisher publisher; //This changed

    @RequestMapping(method = POST, value = "countries")
    public @ResponseBody ResponseEntity<?> createCountry(@RequestBody Resource<CountryDTO> dto,
            Pageable page, PersistentEntityResourceAssembler resourceAssembler) {

        Country savedCountry = repo.save(dto.getContent().getCountries());
        publisher.publishEvent(new BeforeCreateEvent(savedCountry)); //This changed
        return new ResponseEntity<>(resourceAssembler.toResource(savedCountry), HttpStatus.OK);
    }

}


Migrate source id's and map them to already existing Drupal entity id's

Question: I've tried a bunch of different setups, but I can't get it to work. Here are the two setups I was the most confident in that it would work. I simply want to map existing id's in the source to new id's that are already created in taxonomy.
Attempt 1:
  field_season:
    # Map the seasons to our already existing taxonomy terms
    -
      plugin: static_map
      source: season
      map:
        '1': 26 # Lente
        '2': 29 # Zomer
        '3': 24 # Herfst
        '4': 28 # Winter
    -
      plugin: entity_lookup
      value_key: tid
      entity_type: taxonomy_term
      bundle_key: tid
      bundle: seasons

Attempt 2:
  field_season:
    plugin: iterator
    source: field_season
    process:
      target_id:
        # Map the seasons to our already existing taxonomy terms
        plugin: static_map
        source: season
        map:
          '1': 26 # Lente
          '2': 29 # Zomer
          '3': 24 # Herfst
          '4': 28 # Winter

Edit: FWIW, all the other processes work just fine!
Answer: This happens to me all the time, I post a question after fiddling around for hours and shortly after, I manage to find the answer myself. It appears that the first attempt was almost right. Though bundle_key should be vid, I'm not sure why though.
The config, for completeness sake.
  field_season:
    # Map the seasons to our already existing taxonomy terms
    -
      plugin: static_map
      source: season
      map:
        '1': 26 # Lente
        '2': 29 # Zomer
        '3': 24 # Herfst
        '4': 28 # Winter
    -
      plugin: entity_lookup
      value_key: tid
      entity_type: taxonomy_term
      bundle_key: vid
      bundle: seasons

Answer: The entity_lookup doesn't appear to be doing anything here - it's retrieving D8 terms by their tid, and returning their tid. The static_map alone should do it if you know the mappings from the original tids to the new D8 tids.


How to get value out of multidimensional array in php?

Question: I the following multidimensional array that I want to be able to search a particular value based on certain criteria:
$pay_rate_lookup = array(
    "text" => array( //rates for text files
        "type_of_work" => array(
            "option1" => array(
                "timeFrame" => array(
                    "within_24_hours" => 1.00,
                    "within_1_2_days" => 2.00,
                    "within_3_5_days" => 3.00,
                    "within_1_2_weeks" => 4.00
                )
            ),
            "option2" => array(
                "timeFrame" => array(
                    "within_24_hours" => 5.00,
                    "within_1_2_days" => 3.00,
                    "within_3_5_days" => 2.00,
                    "within_1_2_weeks" => 2.00
                )
            ),
            "option3" => array(
                "timeFrame" => array(
                    "within_24_hours" => 5.00,
                    "within_1_2_days" => 5.00,
                    "within_3_5_days" => 4.00,
                    "within_1_2_weeks" => 2.00
                )
            ),
            "option4" => array(
                "timeFrame" => array(
                    "within_24_hours" => 2.00,
                    "within_1_2_days" => 8.00,
                    "within_3_5_days" => 5.00,
                    "within_1_2_weeks" => 1.00
                )
            )
        )
    ),
    "non-text" => array(
        "type_of_work" => array(
            "option1" => array(
                "timeFrame" => array(
                    "within_24_hours" => 10.00,
                    "within_1_2_days" => 20.00,
                    "within_3_5_days" => 30.00,
                    "within_1_2_weeks" => 40.00
                )
            ),
            "option2" => array(
                "timeFrame" => array(
                    "within_24_hours" => 50.00,
                    "within_1_2_days" => 30.00,
                    "within_3_5_days" => 20.00,
                    "within_1_2_weeks" => 20.00
                )
            ),
            "option3" => array(
                "timeFrame" => array(
                    "within_24_hours" => 50.00,
                    "within_1_2_days" => 50.00,
                    "within_3_5_days" => 40.00,
                    "within_1_2_weeks" => 20.00
                )
            ),
            "option4" => array(
                "timeFrame" => array(
                    "within_24_hours" => 20.00,
                    "within_1_2_days" => 80.00,
                    "within_3_5_days" => 50.00,
                    "within_1_2_weeks" => 10.00
                )
            )
        )
    )
);

What I would like to do is retrieve the numeric value based on the type_of_work and timeFrame criteria given by the user.
Example1:
search the sub array "text", given:

type_of_work = "option1"
timeFrame = "within_24_hours"
Then value of "1.00" should be extracted

Example2:
search the sub array "non-text", given:

type_of_work = "option3"
timeFrame = "within_24_hours"
Then value of "50.00" should be extracted

How can I accomplish this?
Answer: Accessing a multi-dimensional array is just about the same as accessing a one dimensional array.
Here's an example based on what you're asking:
// this contains the entire "text" dimension.
$pay_rate_lookup['text'];

// contains the entire type_of_work dimension inside the text dimension.
$pay_rate_lookup['text']['type_of_work'];

So based on the above examples, keep building out your select until you have the dimension/results you want:
$pay_rate_lookup['text']['type_of_work']['option1']['timeFrame']['within_24_hours'];

That will return 1.00.
Use the same method to retrieve 50.00.


Lebesgue measure of a polynomial.

Question: Let $P:\mathbb{R} \rightarrow \mathbb{R}$ a polynomial. If $E \subset \mathbb{R}$ has measure zero, prove that $P(E)$ has measure zero.
Someone can help me? >-<
Comment: Reduce to the case where $E$ is bounded, and observe that a polynomial is uniformly continuous on bounded sets.
Comment: @Lord Shark the Unknown, uniformly continuous functions do not map null sets to null sets. You have to use the fact that a polynomial is Lipschitz on bounded intervals.
Answer: Let $n\in{\bf{N}}$ be fixed and $E_{n}=E\cap[n,n+1]$. We know that for some $M_{n}>0$, $|P'(x)|\leq M_{n}$ for all $x\in I_{n}$. Hence $\mu^{\ast}(P(E_{n}))\leq M_{n}\mu^{\ast}(E_{n})=0$, so $P(E_{n})$ is of measure zero.
Now $E=\displaystyle\bigcup_{n}E_{n}$ and hence $\mu^{\ast}(P(E))\leq\displaystyle\sum_{n}\mu^{\ast}(P(E_{n}))=0$.

Lebesgue measure of a polynomial.


Slides, transição de imagens com JS e radio, ao encostar o mouse em cima da imagem pausar a transição, ao retirar continuar a transição

Question:

 onload  = start;

function start(){
var i = 1;
function Move(){
 i = (i%3)+1; // 4 is the Number of image in slider
 document.getElementById('t'+i).checked = true;
}
setInterval(Move,3000); //change img in 3 sec
}
body{ background-color:#0066FF;}

.ct{
 position:relative;
 width:400px;
 height:220px;
 margin:auto;
 border:2px solid #000;
 overflow:hidden;
}
input{ display:none;}

.img_s{ position:absolute;
 width:100%;
 height:100%;
 z-index:-1;
 font-size:25px;
 text-align:center;
}

.im1, .im2, .im3{ position:relative; width:400px;
 height:225px;
}

.pre, .nxt{ position:absolute;
 width:12%;
 height:100%;
 top:0;
 background:rgba(88,88,88,.4);
 z-index:99;
 cursor:pointer;
 font-size:30px;
}
p{ position:relative; top:50px;
}
.pre{ left:0;
}
.nxt{ right:0;
}
.cr{ width:100%;
 height:11px;
 bottom:12px;
 position:absolute;
 text-align:center;
 z-index:99;
}
.dts{ position: relative;
 display: inline-block;
 background:rgba(0,0,0,.4);
}

#t1:checked ~ #one,
#t2:checked ~ #two,
#t3:checked ~ #three{
 z-index:99; transition:all 0.5s;
}

<input type="radio" name="tabs" id="t1" checked/>
<input type="radio" name="tabs" id="t2"/>
<input type="radio" name="tabs" id="t3"/>

01-IMG

❮

❯

02-IMG

❮

❯

03-IMG

❮

❯

Tenho um pequeno slide, que funciona com radios e transição em JS. O código ao todo funciona normal, só que eu pretendo incrementar no javascript que ao encostar o mouse em cima dentro da caixa de slide a transição JS dos radios pause dando a chance do usuário clicar nas setas laterais e selecionar as imagens e ao retirar o mouse de dentro da caixa a transição continue normalmente, seria possível incrementar com esse simples código em javascript essas funções?? tentei aqui e não tive sucesso, ?
Comment: Salve o valor retornado pela função `setInterval`, em uma variável. Após isso basta utilizar os métodos `mouseenter` e `mouseleave` para detectar quando o mouse está, ou não, sobre o *slider*. Feito isso basta utilizar [**clearInterval**](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval) ou usar o este exemplo como base https://stackoverflow.com/a/21278007/9101590
Comment: Eu tentei fazer com keyframes ao invés de utilizar esse JS, mas não deu certo, porém eu ainda sou bastante leigo em JS
Comment: Tem comandos que eu não conheço em JS e dificulta bastante, provavelmente eu não vou acerta kkkk, mas obrigado pela informação
Answer: Em vez de usar class="ct" seria mais interessante usar id="ct" se o elemento for único. Assim fica mais fácil selecionar ele:
#ct{
 position:relative;
 width:400px;
 height:220px;
 margin:auto;
 border:2px solid #000;
 overflow:hidden;
}

Em seguida pode criar eventos para parar a transição quando o mouse estiver sobre a div, inclusive precisará parar a transição no clique nas setas porque ao clicar o evento mouseleave é chamado, fazendo com que a transição continua mesmo estando com o mouse sobre o slider.
Também tem que atribuir o setInterval à uma variável para poder controlá-lo:
timer = setInterval(Move,3000);

O código bem otimizado ficaria desta forma, sem muitos arrodeios:

var timer;
var slider = document.querySelector("#ct");
var i = 1;

slider.onmouseover = slider.onclick = function(e){
   if(e.type == "click" && e.target.tagName == "INPUT"){
      i = e.target.id.match(/\d+/)[0];
   }
   clearInterval(timer);
}

window.onload = slider.onmouseleave = function(){
   timer = setInterval(Move,3000); //change img in 3 sec
}

function Move(){
   i = (i%3)+1; // 4 is the Number of image in slider
   document.getElementById('t'+i).checked = true;
}
body{ background-color:#0066FF;}

#ct{
 position:relative;
 width:400px;
 height:220px;
 margin:auto;
 border:2px solid #000;
 overflow:hidden;
}
input{ display:none;}

.img_s{ position:absolute;
 width:100%;
 height:100%;
 z-index:-1;
 font-size:25px;
 text-align:center;
}

.im1, .im2, .im3{ position:relative; width:400px;
 height:225px;
}

.pre, .nxt{ position:absolute;
 width:12%;
 height:100%;
 top:0;
 background:rgba(88,88,88,.4);
 z-index:99;
 cursor:pointer;
 font-size:30px;
}
p{ position:relative; top:50px;
}
.pre{ left:0;
}
.nxt{ right:0;
}
.cr{ width:100%;
 height:11px;
 bottom:12px;
 position:absolute;
 text-align:center;
 z-index:99;
}
.dts{ position: relative;
 display: inline-block;
 background:rgba(0,0,0,.4);
}

#t1:checked ~ #one,
#t2:checked ~ #two,
#t3:checked ~ #three{
 z-index:99; transition:all 0.5s;
}
Clique nas imagens:

   <input type="radio" name="tabs" id="t1" checked/>
   <input type="radio" name="tabs" id="t2"/>
   <input type="radio" name="tabs" id="t3"/>

01-IMG

❮

❯

02-IMG

❮

❯

03-IMG

❮

❯

Comment: No do outro usuario acima eu fiquei em duvida, sobre a quantidade de checagem que ele mudou, mas vc deixou o numero de checagens, não sei se o dele é o numero de checagens mesmo ou se é infinita, mas o seu ficou bem fluído e bem mais indicado
Comment: Ajustei o código, tinha uns bugs ainda
Comment: Na outra resposta, se vc clicar em cima da seta e deixar o mouse parado, o slide irá continuar. É porque ele não tratou do click que eu citei na minha resposta: "_inclusive precisará parar a transição no clique nas setas porque ao clicar o evento mouseleave é chamado_"
Comment: Testei e — aparentemente — está *ok*. Cliquei sobre ambas setas e aguardei alguns segundos (sem mover o *mouse*), porém a imagem não mudou. Aliás, ambos os códigos funcionam da mesma forma; ambos mudam a imagem após o clique na seta (desde que retire o *mouse* da área do *slider*).
Comment: @ValdeirPsr Verdade! Ao clicar na seta e manter o mouse sobre o elemento o slide fica pausado.
Comment: Eu estava achando estranho, porque o outro funcionava da mesma forma e a transição fazia a função de pausar e continuar, só que o mudam um do outro é o numero de checagens um possui e o outro não precisa, que se torna opcional, ambos resolveram
Answer: Separei a variavel i e a função move de dentro da função start, adicionei value para os radios para facilitar a identificação de onde está o slider corrente.
Armazena o identificador do setInterval, necessário para parar o setInterval.
Adicionei um id na div do slider apenas para facilitar a atribuição dos eventos, mouseenter para parar o slider automático e mouseleave para reiniciar o slider automático.

onload  = start;
var intervalId;
var i = 1;
function Move(){
   i = parseInt(document.querySelector('input[name="tabs"]:checked').value, 10) + 1;
   if(i > document.getElementsByName('tabs').length) {
    i = 1;
   }
  document.getElementById('t'+i).checked = true;
}
function start(){
 intervalId = setInterval(Move,3000); //change img in 3 sec
}
function stop(){
  clearInterval(intervalId);
}
var slider = document.getElementById('slider');
slider.addEventListener('mouseenter', stop);
slider.addEventListener('mouseleave', start);
body{ background-color:#0066FF;}

.ct{
 position:relative;
 width:400px;
 height:220px;
 margin:auto;
 border:2px solid #000;
 overflow:hidden;
}
input{ display:none;}

.img_s{ position:absolute;
 width:100%;
 height:100%;
 z-index:-1;
 font-size:25px;
 text-align:center;
}

.im1, .im2, .im3{ position:relative; width:400px;
 height:225px;
}

.pre, .nxt{ position:absolute;
 width:12%;
 height:100%;
 top:0;
 background:rgba(88,88,88,.4);
 z-index:99;
 cursor:pointer;
 font-size:30px;
}
p{ position:relative; top:50px;
}
.pre{ left:0;
}
.nxt{ right:0;
}
.cr{ width:100%;
 height:11px;
 bottom:12px;
 position:absolute;
 text-align:center;
 z-index:99;
}
.dts{ position: relative;
 display: inline-block;
 background:rgba(0,0,0,.4);
}

#t1:checked ~ #one,
#t2:checked ~ #two,
#t3:checked ~ #three{
 z-index:99; transition:all 0.5s;
}

<input type="radio" name="tabs" id="t1" value="1" checked/>
<input type="radio" name="tabs" id="t2" value="2"/>
<input type="radio" name="tabs" id="t3" value="3"/>

01-IMG

❮

❯

02-IMG

❮

❯

03-IMG

❮

❯

Comment: Ficou ótimo! mas caso eu queira adicionar mais imagens, eu preciso mudar o  .value, 10) + 1; ?
Comment: no caso aí vai até dez? estou correto?
Comment: se passar de 10 radios eu apenas incremento mais valores, correto?
Comment: @ElienayJunior O `10` é apenas uma base (indica que os valores retornados por `parseInt` **deve** ser decimal). Ps.: O valor `10` é opcional. Caso você queira adicionar mais imagens, não é necessário modificar o *JavaScript*.


How to use only a subset of variables in R using the lm function?

Question: If I have variable bob and I am seeing what effect variable joe has on bob, I have the following function:
model <- lm(bob ~ joe)
But what if I have a third variable tim. And I only want my model to only include the data in which tim=1. How do I do this? I was thinking something like:
model <- lm(bob ~ joe, tim=1)
That doesn't work. Sorry, I'm new to R.
Comment: Create a new dataframe that subsets your current data frame using logical indexing: `df[df$tim == 1]`.
Comment: if `tim` is a categorical variable fitting the model `lm(bob ~ joe:tim)` works as long as you are able to understand the resultant interaction terms.
Answer: One way to do this is to subset your data.
# some example data
set.seed(123)
df <- data.frame(bob = rep(1, 10), joe = rep(2, 10), tim = round(runif(10))

# subset the data to where tim == 1
df1 <- df[df$tim == 1, ]

# build model
model <- lm(bob ~ joe, data = df1)

Alternatively, you can do the subsetting directly in lm.
# build model
model <- lm(bob ~ joe, data = df[df$tim == 1, ])

In case you with to include tim in the regression, you can add it using +.
# build model
model <- lm(bob ~ joe + tim, data = df1)


How to test if two methods of measurement are consistent?

Question: I am measuring (the same) property of of 20 different objects. To measure this property I have two methods at my disposal. Which statistical test should I use to determine whether these two methods give consistent results?
Comment: What "consistent" means depends on the meaning of the measurements and the subject matter background. A difference of 5% (assuming you want the same numbers, which isn't necessarily the case in such problems) may be far too much in one situation and just fine in another.
Comment: The revision still gives no clue what you mean by 'consistent'. How much different can the new method be? Can the new method be more variable? Not clear what you're measuring and why.
Comment: I think the motivation of the question is good, but it could use some clarification. A "test" cannot have any objective meaning until you explain what you mean by "consistent."  However, if you just want to *see how consistent the results are,* why not draw their scatterplot? You can then quantify that in various ways using correlation and regression methods.
Answer: In measuring blood samples for hemoglobin content an assay for hemoglobin (Hgb in g/dl) and the percent of red cells per volume (hematocrit, Hct in %) are considered equivalent for many clinical purposes. Different units, different variances, and one is numerically very nearly 1/3 of the other (typical Hct might be 15%, typical Hgb might be 45g/dl). A regression approach shows points tightly clustered around a straight line (correlation nearly $1),$ so that
both measures are considered reliable--maybe what you're calling 'consistent'.
By contrast if the two methods of measuring something give normally distributed results, with the same units and
the same variance, then a paired t test would suffice to show they're equivalent.
Addendum, per edit and comment:
Here are two scenarios, in which paired t tests show no difference between
the two methods using $n = 20$ samples.
Scenario 1:
set.seed(928)
x1 = rnorm(20, 50, 2);  x2 = x1 + rnorm(20, 0, 5)
t.test(x1, x2, pair=T)

        Paired t-test

data:  x1 and x2
t = 1.6775, df = 19, p-value = 0.1098
alternative hypothesis:
  true difference in means is not equal to 0
95 percent confidence interval:
 -0.4867153  4.4164390
sample estimates:
mean of the differences
               1.964862

So a t test shows no difference between the two methods.
However, the differences for the 20 items are as summarized
below. Method differ on average by about 2 units with a standard
deviation of about 5 units, and correlation is low (about 0.44).
summary(x1-x2)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
 -6.115  -3.651   2.633   1.965   5.864  10.688
sd(x1-x2)
[1] 5.238252

cor(x1,x2)
[1] 0.4397941

Scenario 2:
y1 = rnorm(20, 50, 2);  y2 = y1 + rnorm(20, 0, .1)
t.test(y1, y2, pair=T)

        Paired t-test

data:  y1 and y2
t = -0.05817, df = 19, p-value = 0.9542
alternative hypothesis:
  true difference in means is not equal to 0
95 percent confidence interval:
  -0.05053764  0.04780447
sample estimates:
mean of the differences
       -0.001366584

Again no significant difference, but much better agreement:
Average differences are about 0.0014 with standard deviation
0.11, and a high correlation about 0.998.
summary(y1-y2)
     Min.   1st Qu.    Median      Mean   3rd Qu.      Max.
-0.232753 -0.063022 -0.016312 -0.001367  0.061754  0.226550
sd(y1-y2)
[1] 0.1050631

cor(y1, y2)
[1] 0.9982463

Here are scatterplots for the two scenarios:
par(mfrow=c(1,2))
 plot(x1,x2, pch=20)
 plot(y1,y2, pch=20)
par(mfrow=c(1,1))

So again, you need to decide what you mean by 'consistent': no statistically significant difference observed among 20 items? Small standard deviation of differences for individual items? Reliable small differences
below some amount of practical importance? Good correlation between the
two measurements?
Maybe you want to test whether the mean if the differences $d_i$ is smaller
than some crucial amount. What are the methods measuring and for what
purpose. Are you trying to see if a manufacturing process is out of control?
Are you trying to give customers a guarantee of a specific measurement
with a small margin of error?
By whatever meaning of 'consistent', and without knowing your objectives,
I would certainly prefer the new (2nd) method of Scenario 2.
Comment: The paired t-test cannot show they are equivalent. It tests whether the mean difference is zero. This can be the case even if the two measurements in most cases are nowhere near to each other. The thread opener will need to specify some kind of tolerance for this; also in your example people need to decide whether the points are close enough to the line. The data cannot tell you how large a correlation is large enough, and neither can any statistical test.
Comment: I've edited the question to point out more clearly that I am measuring the same property of those 20 objects. Let's assume it is length. Therefore the units are the same. My main question is how to show if the two methods give the same result.
Comment: @Lewian. Agreed (+1). (But a t test might show methods are _not_ equivalent.) Agree especially that OP needs to define 'consistency'. Points I made in the discussion at the end of my Answer. But OP may need to see a couple of methods compared in order to understand issues in defining what 'consistency' actually means. // If the measurement is used to decide which items are 'junk', then maybe an entirely new method that does not correlate with the current one would be more effective.


Showing a function that behaves like pred to be primitive recursive

Question: Let's define $M$ such that for $x \ge 0$:
$$
M(0)=0
$$
$$
M(x+1)=x
$$
Now, I want to show that $M$ is primitive recursive. How should I go about doing this?
Thanks a bunch!
Answer: The definition
A function is primitive recursive if it is in the smallest class $\mathcal C$ that contains:

$\lambda (x_1 ... x_k).0$, $k \geq 0$
$\lambda x.x+1$
$\lambda (x_1 ... x_k).x_i$ for all $1 \leq i \leq k$ (projection/identity)

And such that composition and primitive recursion hold:

For all $m$-ary $g_1, g_k \in \mathcal C$ and $h \in \mathcal C$, the followint function is in $\mathcal C$:

$$ \lambda x_1 ... x_m.h(g_1(x_1, ..., x_m), ..., g_k(x_1, ..., x_m)) $$

Given the $(k+1)$-ary function $h \in \mathcal C$ and the $(k-1)$-ary function $g \in \mathcal C$, the following $k$-ary function is in $\mathcal C$:

$$\begin{cases} f(0, x_2, ..., x_k) &= g(x_2, ..., x_k) \\ f(x_1 + 1, x_2, ..., x_k) & = h(x_1, f(x_1, ..., x_k), x_2, ..., x_k) \end{cases}$$
EDIT: note I did not use currying in defining the functions, but I listed the arguments in tuples. This is for simplicity and ease of reading.
The application
In your case you have to define the two functions:

$g = \lambda x.0$ (zero $\in \mathcal C$)
$h = \lambda (x_1, x_2, x_3).x_1$ (projection $\in \mathcal C$)

Combine them (primitive recursion) to obtain the binary function $f$ such that:
$$\begin{cases} f(0, x) &= g(x) = 0 \\ f(x_1 + 1, x_2) & = h(x_1, f(x_1, x_2), x_2) = x_1 \end{cases}$$
You now have a function $f$ that behaves like pred, but has the wrong arity. To fix this, you can use composition:

$i = \lambda x . x$ (projection/identity $\in \mathcal C$)
$\implies \text{pred} = \lambda x . f(i(x), i(x)) \in \mathcal C$


HTML page embedded Google Docs Viewer / Office Web Apps Viewer for intranet files

Question: Google Docs Viewer / Office Web Apps Viewer processes file on Google / Microsoft server. It firstly downloads file to the server and so if file is located within my private protected internal network of my organization which Google / Microsoft has no access to then it will not work.

Is information above correct?
Are there any viewers which can work with intranet files?
I'm interested in viewing Word / Excel files (not PDF - for which I can use <embed /> tag).
Thanks
Comment: I think you are right - they work with publicly available docs, only. I am also interested in alternative solution, for intranet/localhost files, but was unable to find one, so far ...
Answer: It is possible to install Office Web Apps Server locally.
https://learn.microsoft.com/en-us/webappsserver/office-web-apps-server-overview
Office Web Apps Server provides a page at the address http://OfficeWebAppsServername/op/generate.aspx that you can use to generate links to publicly available documents that have UNC or URL addresses. When a user selects a generated URL, Online Viewers enable Office Web Apps Server to get the file from its location and then render it by using Office Web Apps. The user can view the Word, Excel, or PowerPoint file in a browser with Office features intact. Formatting and layout in Word documents are preserved, data in Excel workbooks can be filtered and sorted, and animations play in PowerPoint presentations. However, be aware that Online Viewers allow users to view but not edit files, and Online Viewers can't open any files that require authentication.


is it possible to create a fixture for a body that could be broken by some other body?

Question: I really want to know, is it possible to create a fixture for a body that could be broken by some other body?
There is the example:

a body with its fixture divided into small figures:
and what happens after it is hit by another body:

P.s. Are there any programs that could help the process of creating such fixture?
Answer: yes you can do this using  Breakable spotted at :
net.dermetfan.gdx.physics.box2d.Breakable
The Breakable allows to easily make whole bodies or single fixtures breakable, which means they will be destroyed if a certain force or friction is applied to them.
How to use

A Breakable is meant to be put in a body's, fixture's or joint's user
  data. A single Breakable instance can be put in the user data of
  multiple bodies, fixtures and joints. Since this may collide with the
  Box2DSprite or other classes using the user data, the
  Breakable$Manager uses a Function to access the Breakable in the
  user data of a body, fixture or joint.Do not forget to set a Manager
  instance as ContactListener to the world and to call destroy() after
  every timestep. If the field is already in use, check out the
  ContactMultiplexer. The Manager does the actual work, the Breakables
  are just passive data holders.
A Breakable consists of a normal resistance, tangent resistance, an
  option to destroy its body in case its last fixture was destroyed and
  an option setting if the body should be destroyed no matter the amount
  of remaining fixtures.
The normalResistance is the force that can be applied to the
  Breakable before it breaks (inclusive). The tangentResistance is the
  friction the Breakable can bear (also inclusive). The
  reactionForceRestiance specifies the reaction force a joint can bear
  on each axis. The reactionForceLength2Resistance is the max squared
  length of the joint's reaction force the Breakable can bear.

referred to libgdx-utils
some other good references with good examples here and here

for the question (Are there any programs that could help the process
  of creating such fixture)

yes you can easily use box2d-editor which allows you to create complex polygons and you can also create your bodies and shapes from your images or sprites check the official documentation in the same page there are several video who explain the way box2d-editor works :
Features:

Automatically decomposes concave shapes into convex polygons,
Automatically traces your images if needed,
Supports multiple outlines for a single body,
Supports polygon and circle shapes,
Reference point location can be changed,
Visual configurable grid with snap-to-grid option,
Built-in collision tester! Throw balls at your body to test it,
Loader provided for LibGDX game framework (written in Java),
Simple export format (JSON), to let you easily create your own loader for any framework in any language.
Comment: http://www.emanueleferonato.com/2011/08/05/slicing-splitting-and-cutting-objects-with-box2d-part-4-using-real-graphics/
Comment: you may find this topic useful http://www.box2d.org/forum/viewtopic.php?f=3&t=836
Comment: you could follow the concept and do similar , jbox2d is a port of the c++ box2d library  and the classes and method most of them are the same , syntax change from java to c++ , you have instead  of  abject.doSomethink , object<-doSomthinth ...
Comment: there is a lack of java examples when it come to this library , most of them are in JS , C++, Flash, ... and here is the best reference http://www.iforce2d.net/
Comment: Well, in libgdx-utils it just destroys the body not breaking it into pieces(( I need to create a fixture of a body, which could be broken into small figures, not just destroyed.
Comment: Still, i can not create a fixture divided into smaller figures, which could be moved when a certain force or friction is applied to them. http://www.emanueleferonato.com/2011/08/05/slicing-splitting-and-cutting-objects-with-box2d-part-4-using-real-graphics/ - is only about slicing, not creating a divided fixture((
Comment: That's good, but it is written in c++ so is there something for Java?


How to add line at the top of keyboard in ios?

Question: I have a view in which I show Numeric Keyboard. My problem is that the keyboard is missing a top line. With a white background an unpleasant effect appears:

How can I add a 1pt view at the top to simulate top line?
Comment: Is this a custom keyboard or the standard phone pad keyboard type?
Comment: This is standard keyboard in simple app, @rmaddy. I have the same issue in my main app (I only use code for moving entire view so the edited control is not hidden).
Comment: Show some relevant code in your question.
Comment: 10x, @rmaddy. Accepted answer works fine for me.
Comment: If you need code like that then something else is wrong.
Comment: I don't know @rmandy. To be sure that the problem is not in my code I created new App only with one text field. I check and I see that the upper section of the Numpad keyboard is missing border.
I have this type of keyboard before but in that case my background had colour different from white. I suppose that this is the problem.
Answer: quick and dirty:
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    UIView *separatorView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), 1.0 / [UIScreen mainScreen].scale)];
    separatorView.backgroundColor = [UIColor lightGrayColor];
    textField.inputAccessoryView = separatorView;

    return YES;
}

Comment: It works, except that I have to set it on `textFieldDidBeginEditing`, not on `textFieldShouldBeginEditing `.
Comment: May be, because I have code to move view (so the edited `UITextFiled` is not hidden). Also my text field is custom control.
Comment: I added the line in the viewWillAppear method.
Answer: The easiest way would be to add a 1pt tall UIView as the inputAccessoryView to a UITextField.  See Custom Views for Data Input.
If you are using more than one field or would rather have more control over it, you can add a subview to your current controller's view and position it appropriately.  To do that you use the keyboard notifications posted by the OS (UIKeyboardWillShowNotification and UIKeyboardWillHideNotification), as described in How to make a UITextField move up when keyboard is present?.
Answer: For Swift 3, iOS 10
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
  var separatorView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 1.0/UIScreen.main.scale))
  separatorView.backgroundColor = UIColor.lightGray
  textField.inputAccessoryView = separatorView
  return true
}


Check if URL is loaded through iframe

Question: Is it possible in some way to detect if a URL is loaded via. iframe?
For instance to check, if domain.com is loaded or not loaded (if the site doesn't allow iframe loading of the website)?
Comment: Do you mean that you want to detect if your own site is being framed by another?
Comment: No. If I frame another site, then I would like to detect if it's loaded or not
Comment: Ah OK I understand. Please see my answer below in that case.
Comment: Please view this link http://stackoverflow.com/questions/9249680/how-to-check-if-iframe-is-loaded-or-it-has-a-content
Answer: From the comments, the requirement is to detect when another site is loaded successfully in an IFrame under your control.
You can achieve that by simply hooking into the IFrame's onload event.
Example:

JSFiddle: https://jsfiddle.net/d1z62ctw/

Check if URL is loaded through iframe


how to send and receive objects or values using JQuery-AJAX, JSON and php?

Question: How can I send and receive values?
What is it that I'm doing wrong?
jQuery: on click of save button
$("#budget_submit").click(function(){
        var budget = $("#budget_cardno").val();
        $.ajax({
            type: 'POST',
            dataType: "json",
            url: 'budget.php',
            data: budget,
            success: function(data){
                if(data.success == true)
                alert(data.message);
        }
        });
    });

html:
<form method="post" id="budgetform">
   <fieldset>

      CARD NUMBER
      <input name="budget_cardno" id="budget_cardno" />

      MONTHLY BUDGET
      <input name="budget_monthly" id="budget_monthly" />

      <input class="submit" id="budget_submit" name="budget_submit" type="submit" value="Save"/>

   </fieldset>
</form>

Php:
<?php
$dbhost = '#';
$dbuser = '#';
$dbpass = '#';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
    die('Could not connect: ' . mysql_error());
}

$cardNo = $_POST['budget'];     #This statement does not work.
if($cardNo == "")
{
    mysql_close($conn);
    $data = array('success' => true, 'message' => 'ENTER DETAILS');
    echo json_encode($data);
}

else
{
}
?>

how can I send the value budget to the PHP file and store it in $cardNo and return the message?
I don't want to check for the condition at the client side because I have other conditions to check which needs data from database.
Comment: you can check the $_POST received by the php script by using echo print_r($_POST); it will tell you the key and the value of the data received (if any). I don'T see any trouble at first glance. You might want to consider using cosole tools like firebug or something similar to see what is sent and retuned.
Answer: actually this seems weird to me.
if($cardNo == "")
{
    mysql_close($conn);
    $data = array('success' => true, 'message' => 'ENTER DETAILS');
    echo json_encode($data);
}

This will trigger only if the value is EMPTY. So if you send a value, it won't trigger since the statement is false.
Change your == to != so it state: if $cardNo IS NOT EMPTY like so:
if($cardNo != "")
{
    mysql_close($conn);
    $data = array('success' => true, 'message' => 'ENTER DETAILS');
    echo json_encode($data);
}

Comment: further more, i sugest you start using mysqli instead of mysql as it is (or soon will be) deprecated.
Comment: I'm just checking whether the code works for empty value. The actual condition is different from the one I posted.
Answer: I think the problem is that you're treating the incoming data as a normal form, when in fact you're sending JSON. PHP is therefore not finding any $_POST parameter with name 'budget'.
You need to get the raw post data using file_get_contents('php://input'); and then use json_decode() to convert it into an object. From it you could then get the budget parameter.
So something like this should work:
$formdata = file_get_contents('php://input');
$formdata_obj = json_decode($formdata);

$cardNo = $formdata_obj->budget;

If you're actually just sending one value (as you seem to be doing) the first line alone might suffice, because the whole data would be the value itself rather than a JSON encoded object:
$cardNo = file_get_contents('php://input');

Comment: Just saw the same thing over here.
Comment: @jbx: how to use file_get_contents('php://input');
Comment: @jbx: $requestBody = file_get_contents('php://input');
$requestBody = json_decode($requestBody);

$cardNo = $requestBody -> budget;
Comment: Yeah, but it has to be json_decode() not jsonDecode(), and don't use the same variable for 2 different things ($requestBody) it just confuses you. Why don't you copy my example?
Comment: If it still doesn't work put some 'echo' lines here and there to see what you are receiving in the file_get_contents (to make sure that you are really receiving the JSON), and maybe use var_export() to view the contents of the object generated from `json_decode()`. We've put you on the right track, we can't debug your application!
Comment: @jbx: It says Trying to get property of non-object to $cardNo line
Comment: Are you sure you are actually receiving the data? Try to print out the contents of `$formdata` first. Then try to print out a `var_export($formdata, true)`. This way you verify you're getting the right things in each step.
Comment: It could be that since you're actually sending one value, its not even a JSON object, but just a string with the budget. So you might find that $formdata is in fact already the budget value and you don't need to do any further json_decode() calls. Only debugging properly will help you understand.


Project structure

Question: I was wondering what would be the best way to setup a Drupal 8 website that has about 15 mostly static pages in three languages? Static pages are somewhat similar but do contain different content.
Since it's multilanguage site and has different static and some dynamic content am i supposed to put everything in blocks to be translatable or is there a better way?
Views maybe? I'm a little bit confused and don't even know if Drupal way is the good way to do it.
I know that my question is broad and not so specific but any help is much appreciated!
Comment: Enable the Language and Content Translation modules, create the content in one language as usual, then just translate everything into those additional languages.
Answer: This is an extremely broad question, so I can only give you a broad answer.
You don't create pages in Drupal like you might be used to from other CMS. You create content.
You need to change how you think about content to work efficiently with Drupal. First off, create your content, and then think about how to display it.
The closest to creating pages is creating nodes/content. Go to /node/add (or Manage > Content > Add content) and create a few pieces of content, for example of type Page. Make sure you enable the content translation module and add your languages so that you can translate it.
Each node (technical term)/piece of content is by default visible at node/ID or an alias that you define. That's your "page". But you can also create a view to create a list of content somewhere, based on some conditions.
Blocks are used when you want to place a certain piece of content into one of the block regions on all/many pages.
Do that, and then come back and ask more specific questions.
Comment: Thank you very much Berdir. I did this already. I do understand the philosophy of creating content, at least basics, but my confusion comes from not knowing if it's possible to represent HTML code as content. I know i can put stuff in templates also and basically put anything I want there but that can't, i guess, be translated if it's not formalised as Drupal content. I'm seeking a way to wrap my HTML code in Drupal system so it can be translated and extended by blocks on some of the pages.
Comment: You can translate things in templates if you do it correctly, but as interface translations. You don't really want to do it. You can't transform html templates 1:1 to drupal, you need to identify patterns, structures, blocks.. and then create those. E.g. you create a theme with regions, then you have the main region there and other blocks if you have additional pieces of content. To structure your main content area, you can you the CKEditor in the body or multiple fields, or you look into the Paragraphs module, or something like Page Manager.
Comment: Keep in mind that Drupal 8 is still alpha, and those modules and concepts are still being fleshed out. Drupal core doesn't offer much more than blocks/regions + wysiwyg/fields in the main content area.
Comment: Got it. I noticed that body field's text format, when creating basic page (content of type basic page), can be set to Full HTML. But when i do that i still get plain text with html tags. Could setting text format be the thing i'm looking for or it's used for some other purpose. If this is possible on entire project scope it looks like optimal solution.
Comment: Then that's because you entered html tags in the wysiwyg editor, you need to click on the source button to edit/enter raw html. Or create a text format that doesn't use an editor. Yes, you can use that, but it's recommended to use multiple fields or a project like paragraphs to better structure your content, that will make it much easier to manager translations, for example, compared to a single, huge textfield.

Project structure


MySQL: arrays contains another array

Question: I have created two arrays with GROUP_CONCAT function. Now, I need to check if the first one is contained in the second one.
Here's some examples:
Arr1: '1,2'
Arr2: '1,2,3'

RESULT: YES

Arr1: '2,3'
Arr2: '1,2,3'

RESULT: YES

Arr1: '1,3'
Arr2: '1,2,3'

RESULT: YES

I have tried to use the LOCATE function, but the third case is not covered.
Comment: Why have you used `GROUP_CONCAT()`? This is much easier to do with the original normalized data. MySQL has no easy way to do this with comma-separated values.
Comment: The basic function for searching for a value in a comma-separated string is `FIND_IN_SET()`. But you need to call it separately for each value to search for, there's nothing that will loop over all the items.
Comment: @Barmar maybe a regex can help me? You know?
Comment: @Barmar I need to group the t1 rows and i need to maintains the information of a field for each row.

Like for a team: you group by for team's name and want to maintains all players name for each country.

After, you group the players for the nations teams and try to search if the players of a team, for a nation, are players of the nation team too. I also tried `FIND_IN_SET()` but, how you said is not helpful for my case
Answer: You can try with the following regex syntax:
SELECT @arr2 REGEXP CONCAT('(^|,)', REPLACE(@list1, ',', ',([0-9]+,)*'), '(,|$)'),
       @arr2 REGEXP CONCAT('(^|,)', REPLACE(@list2, ',', ',([0-9]+,)*'), '(,|$)'),
       @arr2 REGEXP CONCAT('(^|,)', REPLACE(@list3, ',', ',([0-9]+,)*'), '(,|$)'),
       @arr2 REGEXP CONCAT('(^|,)', REPLACE(@list4, ',', ',([0-9]+,)*'), '(,|$)'),
       @arr2 REGEXP CONCAT('(^|,)', REPLACE(@list5, ',', ',([0-9]+,)*'), '(,|$)'),
       @arr2 REGEXP CONCAT('(^|,)', REPLACE(@list6, ',', ',([0-9]+,)*'), '(,|$)'),
       @arr2 REGEXP CONCAT('(^|,)', REPLACE(@list7, ',', ',([0-9]+,)*'), '(,|$)')

Basically replaces the commas with a regex that matches at least a comma, and any combination of numbers followed by a comma, then encloses this between:

the start of string or comma (^|,)
the end of string or comma (,|$)

In this way arr2 should contain all numbers of the lists, and any other number.
The output is 0 when the elements of the list are not found in arr2, and 1 when they are. If you want to get 'YES' and 'NO', it's sufficient to include the result of the REGEXP operation inside an IF statement:
IF(@arr2 REGEXP CONCAT(...) = 1, 'YES', 'NO')

Hence replace variable names with the corresponding columns you have in your table.
Check the demo here.
Comment: https://www.db-fiddle.com/f/9UJAAGygLzZgCpkgSvVUbg/5 can you tell me if this works in your query?  @betta7391
Comment: It works!! Thank you so much! :) but can you explain me why mine doesn't work? If you know
Comment: It's a good solution but, there is a drawback: for your regex `'[,0-9]+'` if the **@arr2** is `'1,14,2,3'` and the **@list** is `1,4`, there is a match and it's not correct for what I need. I need to match only the whole numbers. I'm not familiar with regex, so if you can help me wuold be great! :)
Comment: You're definitely right, I've just updated my answer with an improved version of it. @betta7391
Comment: better, but still with drawback:  `@arr2 = '1,1444,2,3'` matchs `@list4 = '1,144'`. I'm trying to use this one `^(?=.*\b144\b)(?=.*\b1\b).*$` and it's seem to work fine in the little example that we are using, but in my real query no.. I don't now why
Comment: can you share the fiddle corresponding to your regex up here (`^(?=.*\b144\b)(?=.*\b1\b).*$`) that works with the examples? @betta7391
Comment: https://www.db-fiddle.com/f/aykTccB4dpMiej1n2eW3yk/0 this is the link
Comment: I've been looking for a while at your regex, it's really difficult to understand what outlying cases are not allowed by your solution, though I may give you a small general tip to follow: as long as `.` matches any character (except new line), it can easily be a source of error. My recommendation is to avoid using it unless you can't have any other option to follow up with. If you want to debug further the issues of your query, I'd suggest to reverse your regex condition (with a `NOT`) and check for the matched values that actually should be included in the solution of this problem. @betta7391
Comment: Wouldn't `FIND_IN_SET()` be simpler?
Comment: Didn't know the existence of this method, that's a great tip, thanks for sharing! @RickJames

MySQL: arrays contains another array


Maximum number of real solutions of a polynomial

Question: Question statement: Find the maximum number of real solutions of $ax^n+x^2+bx+c$ where $a,b,c \in \mathbb{R}$ and $n$ is an even positive number.
Approach: The double derivative of the polynomial is
$f''(x)= n(n-1)ax^{n-2}+2$
For $a>0$, $f"(x)$ is never zero for real $x$. Hence there exists atmost 2 real solutions for $f(x)$.
Can't really proceed with the $a<0$ case.
Any better approach is invited.
PS: Sorry for the bad formatting. I am new here.
Answer: For $a<0$ and $n\ne 2$, $f''$ will have exactly two zeroes.  Hence at most three roots for $f'$ and at most four roots for $f$. Four roots are achieved e.g. for
$ -\frac1{10}x^4+x^2-1$.
If $a=0$ or $n=2$, we have a quadratic or lower polynomial, hence at most two roots. The only exception is: $n=2,a=-1,b=c=0$, which makes $f$ identically zero and hence uncountably many solutions.
Comment: That's what I had done for a<0. But the answer given is 2 maximum solutions. Perhaps it's a typing error. Thanks for help.


Will there be a conflict when doing a merge after removing a particular branch folder?

Question: A project has two branches: master and dev.
Suppose a folder was removed from the dev branch, but not the master.
If a commit is sent to GitLab, will there be a conflict when merging?
Answer: There might be tree conflicts if on the other branch one of those deleted files is modified, or renamed.
Answer: Conflicts occur when there are different changes to the same lines of code in the same file on each branch. So the only way to be conflicts here is if some other work on master that modifies these files in some way, either by editing their contents or deleting or moving them.