Is each function $A^{\mathbb{Z}}\to A^{\mathbb{Z}}$ continuous?

Question: Let $A$ be some finite alphabet. Let $A$ be equipped with the discrete topology and $A^{\mathbb{Z}}$ equipped with the associated product topology.
Am I right that each function
$f\colon A^{\mathbb{Z}}\to A^{\mathbb{Z}}$ is continuous?
Comment: I'll give an answer shortly.
Comment: Which topology do you consider?
Comment: @Mathematician42 Sorry, forgot to mention that. Added it to my question.
Answer: Let $A=\left\{a,b\right\}$. Consider the map $f:A^{\mathbb{Z}}\rightarrow A^{\mathbb{Z}}$ that maps $f(\prod_{-\infty}^{\infty}a)= \prod_{-\infty}^{\infty}a$ and anything else to $\prod_{-\infty}^{\infty}b$. Then $f^{-1}(\prod_{i=-\infty}^{\infty}X_i)= \prod_{-\infty}^{\infty}\left\{a\right\}$ where $X_i=A$ for all $i\neq 0$ and $X_0=\left\{a\right\}$. Since $\prod_{i=-\infty}^{\infty}X_i$ is open in $A^{\mathbb{Z}}$ and $\prod_{-\infty}^{\infty}\left\{a\right\}$ is not, $f$ is not continuous. Using this argument you can easily see that $f$ need not be continuous as soon as $|A|\geq 2$.
Comment: Since $X_0=\left\{a\right\}$ we need sequences that are mapped to something with an $a$, but there is only one such sequence, namely the constant sequence $a$ (since all other sequences are mapped to the constant sequence $b$). The preimage is not open since it is an infinite product of the opens $\left\{a\right\}$, this is not open since by definition of the product topology we only allow finitely many opens different from $A$ itself.
Comment: What do you mean with $\prod_{-\infty}^{\infty}a$?
Comment: An element of $A^\mathbb{Z}$ under the identification $A^\mathbb{Z}$ with $\prod_\mathbb{Z}{A}$
Comment: Then I do not understand the description of the function. An element is imaged to itself and anything else to another element?
Comment: Sry, I should add: it means the string with constant $a$, ie the function $\mathbb{Z}\to A$ picking out $a$ for every $z\in\mathbb{Z}$
Comment: A function from $g:\mathbb{Z}\rightarrow A$ can be represented as a two-sided sequence. Hence $g$ can be written as $g(i)_{i\in \mathbb{Z}}$ or equivalently $\prod_{i=-\infty}^{\infty} g(i)$. Thus $\prod_{-\infty}^{\infty} a$ denotes the constant sequence $a$. Any other sequence is mapped to the constant sequence $b$.
Comment: Okay, but I do not see (1.) Why $f^{-1}(\prod_{i=-\infty}^{\infty}X_i)$ is $\prod_{i=-\infty}^{\infty}a$ and, moreover, why is this pre-image not open?
Comment: Consider the cylinder sets $[a_m,\ldots,a_n]:=\left\{x\in A^{\mathbb{Z}}: x_j=a_j~\forall m\leq j\leq n\right\}$ with $a_j\in A, m\leq n$. These sets form a base of the product topology and are clopen. I think the cylinder sets also form a base for the closed subsets of $X=A^{\mathbb{Z}}$. - To show that a function $f\colon X\to X$ is continuous, it should be enough to show that the pre-image of a cylinder set is closed, i.e. can be expressed as an intersection of cylinder sets.
Comment: Now, consider any cylinder set for your example. For example $[a]_0$. This has pre-image $\left\{a\right\}^{\mathbb{Z}}$. But why not writing this as $\bigcap_{m\geq 1}[a_{-m},\ldots,a_m]$ with $[a_{-m},\ldots,a_m]=(a,a,\ldots,a)$ for each $m\geq 1$? So isn't it true that the pre-image of each cylinder set is closed? .
Comment: No, this is not true. You showed that the preimage of $[a]_0$ is closed, but you didn't show that the preimage of any closed is closed (which you need to do if you want to argue that $f$ is continuous).
Answer: Note that $X = A^{\mathbb Z}$ is Hausdorff but not discrete.  So there is a point $p \in X$ such that the singleton $\{p\}$ is not an open set.  Choose a second point $q \ne p$.  Define $f : X \to X$ by
$$
f(p) = q,\qquad\text{and}\qquad f(x) = p \text{ for all $x \ne p$}.
$$
Then $U = X \setminus \{p\}$ is open, but $f^{-1}(U) = \{p\}$ is not open.
Comment: Is it really Hausdorff?
Comment: Why not try to prove that yourself?
Comment: As far as I know, the cylinder sets $[a_{-n},\ldots,a_n]$ generate the product- topology. Moreover, A^Z is compact and as you say, Hausdorff. Then the pre-image of a cylinder set (which are closed and open), should be a subset of a cylinder set and hence closed since a cylinder set is compact (?). So up to this the function is continuous.... thats why  i am confused to hear that not each function f is continuous.
Comment: ??? a subset of a cylinder set is closed ???  I doubt it.
Comment: Please see the two last comments which I wrote below the other answer.


Samba permissions being ignored

Question: I have defined the following share in smb.conf
[development_server]
    comment = Development directories
    path = /sites
    writeable = yes
    valid users = @dev
    guest ok = no
    directory mask = 0775
    create mask = 0775

The problem is that whenever I create a file within windows the permissions of that file are set as 764 instead of being set as 755. Directories however are set correctly with 775. I am confused. I tried setting the following:
[global]
    unix extensions = yes

But this did not help either.
Answer: The problem turned out to be the security mode settings within my configuration (or lack there of). The following smb.conf configuration is now working for me and all users within my security group "dev" now have 775 for all files they create within the share:
[development_server]
    comment = Development directories
    path = /sites
    writeable = yes
    valid users = @dev
    guest ok = no

    create mask = 0775
    force create mode = 0775
    security mask = 0775
    force security mode = 0775

    directory mask = 0775
    force directory mode = 0775
    directory security mask = 0775
    force directory security mode = 0775

I found this solution while digging through askubuntu
Comment: These configurations are deprecated "security mask, force security mode, directory security mask, force directory security mode"
Answer: create mask can only be used to prevent a permission bit to be set, as the mask is bitwise ANDed with the bits the client tried to set. If the mask is set to 7, but the client tries something less, e.g. 6, the client "wins" as 0 AND 1 for the execute bit is 0.
force create mode works the other way around, it will bitwise OR the mode to what the client tries to set, so if you set a 7 here, every bit will end up  with x OR 1, which is always 1.
To force the value 0775 regardless of what the client tries to set, you have to combine the two:
create mask = 0770   (0000 would also work)
force create mode = 0775

See the documentation.
Comment: after setting create mask = 0770 and force create mask = 0775 my permissions then become 760 on newly created files
Answer: Check obey PAM restrictions parameter. If enabled Samba will create files with umask restriction for given user.
Answer: A word of warning on testing this problem:
After suffering the same issue I discovered that, in my case at least, it was conditional;

when I create a file in the samba share using context-menu new-file ('New Text File.txt') it does not set the group-write bit on that file (0750)
when I create a new file using context-menu new-file and change its name before pressing enter it does set the group-write bit on that file! (0770)

My solution was the one @niziak warned about.
Do not use obey PAM restrictions (defaults to no).
Comment: I have double-checked this with Windows 10 as a client of a Samba-hosted AD domain (version 4.17.8 on Debian Bookworm), and no matter how this is done, the permissions are set to `drwxrwx---` for directories and `-rw-rw----` for regular files no matter how `create mask` or `directory mask` are set (in my case it's 0640 for the former and 0750 for the latter) and independent of `obey pam restrictions` (I've checked with both settings). The permission bits for world-access are correctly cleared, though.

Samba permissions being ignored


Finding Velocity of $1$-D Two Fluid Steady Flow

Question:
In the absence of surface tension, two incompressible viscous fluids are conned between a pair of parallel flat plates $y = -h$ and $y = h$. The region $-h<y<0$ is occupied with a fluid of density $\rho_1$ and viscosity $\mu_1$. The region $0<y<h$ is occupied with a fluid of density $\rho_2$ and viscosity $\mu_2$. A steady fully developed flow is set up with the lower plate $(y = -h)$ fixed
  and the upper plate $(y = h)$ moving with a constant velocity $U_0$ parallel to
  the x-axis. Prove that the velocity distribution in the two fluids is:
  $$\boldsymbol{u} = u(y)\underline{\hat\imath}\quad\text{where}\quad u(y) =\left\{
\begin{array}{11}
\frac{\mu_2}{(\mu_1 + \mu_2)}U_0(1+\frac{y}{h})\quad-h\le y\le0\quad(1)\\
\frac{\mu_1}{(\mu_1 + \mu_2)}U_0(\frac{\mu_2}{\mu_1}+\frac{y}{h})\quad\,\,\,\,0\le y\le h\quad(2)\\
\end{array}
\right.$$

I write the problem out:
$$\boldsymbol{u} = u(y)\underline{\hat\imath} =\left\{
\begin{array}{11}
u_2(y)\underline{\hat\imath}\quad\,\,\,\,\,\,\,0\le y\le h\quad(1)\\
u_2(y)\underline{\hat\imath}\quad-h\le y\le 0\quad(1)\\
\end{array}
\right.$$
I have the boundary conditions:
$$y=-h,\quad u=0\\
y=h,\quad u=U_0$$
I am not given a pressure gradient so I assume $p=p_0$. I check continuity holds:
$$\nabla\cdot\boldsymbol{u} = \frac{\partial u}{\partial x} = 0.$$
I then use N-S equations:
$$\frac{\partial u}{\partial t} + (\boldsymbol{u}\cdot\nabla)\boldsymbol{u} = -\frac{1}{\rho}\frac{\partial p}{\partial x} + \boldsymbol{X} + \nu\nabla^2u$$
The body force $\boldsymbol{X}=0$ and $\frac{\partial u}{\partial t}=0$ because steady flow. This then comes down to:
$$u\frac{\partial u}{\partial x} + v\frac{\partial u}{\partial y} = -\frac{1}{\rho}\frac{\partial p}{\partial x} + \nu\left(\frac{\partial^2 u}{\partial x^2} + \frac{\partial^2 u}{\partial y^2}\right)$$
Here, both $\frac{\partial u}{\partial x}$ and $v$ are $0$ so the LHS $=0$. And I think that the pressure is $p=p_0$ so that makes $\frac{\partial p}{\partial x} = 0$ leaving:
$$\frac{\mu_2}{\rho_2}\frac{\partial^2 u_2}{\partial y^2} = 0,\quad\frac{\mu_1}{\rho_1}\frac{\partial^2 u_1}{\partial y^2} = 0$$
Answer: For fully developed, steady, unidirectional flow, the velocity component $u$ does not depend on $x$ and $v=0$.  The flow is driven by the motion of the upper plate, so you can assume the pressure is constant.  In this case, the Navier-Stokes equations reduce to
$$\frac{\partial^2u_1}{\partial y^2} = 0, \,\,\,\frac{\partial^2u_2}{\partial y^2} = 0$$
where $u = u_1$ for $-h \leqslant y \leqslant 0$ and $u = u_2$ for $0 \leqslant y \leqslant h$.  Integrating twice we obtain,
$$u_1 = Ay +B, \,\,\, u_2 = Cy +D.$$
The natural boundary conditions are used to determine the constants $A,\, B,\, C,\, D$.
We require no-slip at solid surfaces
$$\tag{1}u_1(-h) = 0,$$
$$\tag{2}u_2(h) = U_0,$$
and continuity of velocity and stress at the interface:
$$\tag{3}u_1(0) = u_2(0), $$
$$\tag{4}\mu_1 \left.\frac{\partial u_1}{\partial y}\right|_{y=0} = \mu_2 \left.\frac{\partial u_2}{\partial y}\right|_{y=0}$$
Applying these conditions we get
$$\qquad \,\,\,\,\,\,(1) \implies -Ah + B = 0\\ \qquad \,\,\,\,\,\,(2) \implies Ch + D = U_0 \\ (3) \implies B = D \\ \quad \,\,\,\,\,(4) \implies \mu_1A = \mu_2 C$$
From (1) and (3) we get $D = B = Ah$, and from (4) we get $C = \mu_1A/\mu_2$ leading to
$$u_1 = Ay + Ah =Ah\left(1 + \frac{y}{h}\right), \\ u_2 = \frac{A\mu_1}{\mu_2}y + Ah =\frac{\mu_1}{\mu_2}Ah\left( \frac{\mu_2}{\mu_1} + \frac{y}{h}\right) $$
From (4) we get $U_0 = Ch +D = (\mu_1/\mu_2)Ah +Ah = Ah(1 + \mu_1/\mu_2)$ leading to
$$Ah = \frac{\mu_2 U_0}{\mu_1 + \mu_2},$$
and
$$u_1 = \frac{\mu_2 U_0}{\mu_1 + \mu_2}\left(1 + \frac{y}{h}\right),  \\ u_2 = \frac{\mu_1 U_0}{\mu_1 + \mu_2}\left( \frac{\mu_2}{\mu_1} + \frac{y}{h}\right)$$
(At the start, a clue that inertial terms and the pressure gradient are negligible is the absence of the densities $\rho_1$ and $\rho_2$ in the answer given to you.)
Comment: in you're first line you have what i have but without $\mu_2/\rho_2$ etc. Why is this?
Comment: using the conditions I have: $$0 = -Ah + B,\quad U_0 = Ch + D$$ But how do I determine these?
Comment: Divide both sides by the nonzero constant $\mu_2/\rho_2$ and you get what I have.  There are four boundary conditions including the two at $y=0$ to solve for the four constants.  Does that make it clear or should I add some more.
Comment: $\frac{\mu}{\rho} \frac{\partial^2u}{\partial y^2} = 0 \implies  \frac{\partial^2u}{\partial y^2} = 0$.  I finished for you.  Were you really unable to do the algebra for the constants or was there some other confusion?
Comment: I do just get lost in the algebra and can't see the subtle connections. Like after you have those 4 equations, seeing that to get $Ay$ I just need to do $Ah\cdot \frac {y}{h}$ can just go right over my head. And then going back to $U_0$ to find the fraction equal to $Ah$ I just can't see it sometimes. But you've helped clarify me that what I was thinking was good. I think and try for so long and end up questioning myself with how can this not be the right way? And it is but I'm not reading inbetween the lines
Comment: You were on the right track. You incorrectly reduced NS to equations involving the second partials with respect to $x$ when it should have been $y$.  Perhaps that was a typo, but I'm sure you now get that fully developed flow means no dependence on the coordinate in the direction of velocity.  I used some shortcuts for the algebra, so you should practice solving in any way you see fit.
Comment: Oh dear, yes that was a typo. Yes the velocity only changes in the y direction. But yes it is without a doubt very helpful. I feel I would struggle much more if I wasn't able to reach out to a mathematical community like this.


Showing that a function defines a probability distribution over a sample space

Question: Let $\Omega_n = \{0, 1\}^n$, $s = X_1X_2\dots X_n$ a binary string of length $n$ with $X_i \in \{0, 1\}$ and $k(s) = \sum_{i = 1}^nX_i$. Let $p \in (0, 1)$, and define $\Pr(s) = p^{k(s)}(1 - p)^{n - k(s)}$. I want to show that the defined function $\Pr$ defines a probability distribution over $\Omega$, i.e. $\sum_{s \in \Omega} \Pr(s) = 1$, and $\forall s \in \Omega: \Pr(s) \geq 0$. The second property is trivially true as both terms in the product $p^{k(s)}(1 - p)^{n - k(s)}$ are non-negative. However the first property seems trickier. We can surely expand the sum with the help of the binomial theorem, $$\sum_{s \in \Omega} \Pr(s) = \sum_{s \in \Omega}p^{k(s)}(1 - p)^{n - k(s)} = \sum_{s \in \Omega} p^{k(s)} \sum_{i = 0}^{n - k(s)}{n - k(s) \choose i}(-p)^i,$$ but how can we argue that the sum equals one?
Answer: We have $$\sum_{s\in\Omega}p^{k(s)}(1-p)^{n-k(s)}=(1-p)^n\sum_{s\in\Omega}\left(\frac p{1-p}\right)^{k(s)}$$  Since there are $\binom nk$ bit strings with $k$ one bits we have
$$\begin{align}
(1-p)^n\sum_{s\in\Omega}\left(\frac p{1-p}\right)^{k(s)}&=(1-p)^n\sum_{k=0}^n\binom nk\left(\frac p{1-p}\right)^k\\
&=(1-p)^n\left(1+\frac p{1-p}\right)^n\\
&=(1-p+p)^n=1
\end{align}$$
Answer: For $k=0,1,2,\dots, n$ let $\Omega_k:=\{s\in\{0,1\}^n\mid k(s)=k\}$.
Then $|\Omega_k|=\binom{n}k$ so that: $$\sum_{s\in\Omega}\Pr(s)=\sum_{k=0}^n\sum_{s\in\Omega_k}\Pr(s)=\sum_{k=0}^n\binom{n}kp^k(1-p)^{n-k}=(p+(1-p))^n=1^n=1$$


Use base function but only with specific class

Question: Names are getting hard to come by these days.  It seems with additional packages we'll need to eventually use names like a_function_to_find_the_correlation_of_a_data_set_but_slightly_different.
My question is as follows:
How can one use the name of a base function (cor for example) for use in a package as a function name that operates on a specific class and if it is not of that class then the original use of cor from the base stats package is assumed?
Here is an example:
cor(mtcars[1:4, 1:4])

## > cor(mtcars[1:4, 1:4])
##             mpg        cyl       disp         hp
## mpg   1.0000000 -0.9753429 -0.4962289 -0.9753429
## cyl  -0.9753429  1.0000000  0.6755988  1.0000000
## disp -0.4962289  0.6755988  1.0000000  0.6755988
## hp   -0.9753429  1.0000000  0.6755988  1.0000000

cor <-
function (x, ...) {
    UseMethod("cor")
}

dat <- "I wish robots would disappear."
class(dat) <- c("whammy_robots", class(dat))

cor.whammy_robots <- function(x, ...) {
    gsub("robots", "", x)
}

cor(dat)

## > cor(dat)
## [1] "I wish  would disappear."
## attr(,"class")
## [1] "whammy_robots" "character"

cor(mtcars[1:4, 1:4])

## > cor(mtcars[1:4, 1:4])
## Error in UseMethod("cor") :
##   no applicable method for 'cor' applied to an object of class "data.frame"

Is there a way to say hey if the object isn't of this class (whammy.robots for instance) then behave as you typically do cor?
I assume I could make specific new methods fucntions like:
cor.data.frame <- function(x, ...) {
   stats::cor(x, ...)
}

and
cor.matrix <- function(x, ...) {
   stats::cor(x, ...)
}

but this gets convoluted fast.
Comment: That's what default methods are for... `cor.default <- stats::cor` (not to say whether masking a base-ish package function is a good idea or not).
Comment: Ahh gotcha I think Josh, let me play around.
Comment: @Josh can you add that as an answer?
Answer: Leaving aside the point that what you want to do might not be a good idea...
You don't have to define a method for every possible class.  That's what default methods are for.
> cor.default <- stats::cor
> cor(mtcars[1:4, 1:4])
            mpg        cyl       disp         hp
mpg   1.0000000 -0.9753429 -0.4962289 -0.9753429
cyl  -0.9753429  1.0000000  0.6755988  1.0000000
disp -0.4962289  0.6755988  1.0000000  0.6755988
hp   -0.9753429  1.0000000  0.6755988  1.0000000

Comment: sometimes it makes sense if you are using your function in a very similar context but needs a slight tweak.  Thank about a `tm::TermDocumentMatrix`, let's say is named `tdm`.  `cor(tdm)` won't work but it may be very handy to have a `cor` function/method that will use `as.matrix` first.  I agree this needs to be done thoughtfully and with care but can be a good thing as you're building off of the semantics of the base function.  Plus Hadley does it with `filter` in dplyr so it must be ok :-)


I have a recursively defined function, and another function involving powers of a matrix. How can I show that they are equal?

Question: The problem is

Let $A$ be the $n \times n$ adjacency matrix of a graph $G=(V,E)$ on $n$ vertices, i.e. $A=(a_{ij})$ and
  $$a_{ij}=\begin{cases}
1 & ij\in E  \\ 0 & ij\notin E
\end{cases}$$ Show that the $i,j$ entry of $A^k$ is the number of $i-j$ walks in $G$ that use exactly $k$ edges.

I'm almost done but I don't quite believe my solution. Here's what I have.

Let $w_k(i,j)$ be the number of $i-j$ walks of length $k$. Clearly, $$w_{1}(i,j)=\begin{cases}
1 & ij\in E  \\ 0 & ij\notin E
\end{cases}$$
  The number of $i-j$ walks of length $k$ equal to the number of walks of length $k-1$ from $i$ to a vertex in $N(j)$ where $N(j)$ is the set of vertices adjacent to $j$, so we have $$w_k(i,j)=\sum_{x \in N(j)}w_{k-1}(i,x)$$
  Now,, $[A^k]_{ij}=[A^{k-1}A]_{ij}=[A^{k-1}]_i^T [A]_j$, where the subscripts denote columns of the matrix in brackets (since $A$ is symmetric and hence powers thereof are also symmetric). We can write this as $$[A^k]_{ij}=\sum_{l=1}^n[A^{k-1}]_{il}[A]_{lj}$$
And by the definition of $A$, this is equivalent to $$[A^k]_{ij}=\sum_{x\in N(j)}[A^{k-1}]_{ix}$$

Obviously these recursive definitions look very similar and I can't decide if I am done or not. How can I show that these are in fact are the exact same function?
Answer: You have the right idea, but you've not really made it clear. What you want to do is show by inductionn on $k$ that $w_k(i,j)=[A^k]_{ij}$ for all $i,j\in\{1,\ldots,n\}$. This is clearly the case for $k=1$. If $k>1$, and if it holds for $k-1$, then
$$\begin{align*}
w_k(i,j)&=\sum_{\ell\in N(j)}w_{k-1}(i,\ell)\\
&=\sum_{\ell\in N(j)}[A^{k-1}]_{i\ell}&\text{induction hypothesis}\\
&=\sum_{\ell=1}^n[A^{k-1}]_{i\ell}[A]_{\ell j}&\text{since }[A]_{\ell j}=\begin{cases}1,&\ell\in N(j)\\0,&\ell\notin N(j)\end{cases}\\
&=[A^k]_{ij}\;,
\end{align*}$$
and we're home free.
Comment: right, I did write that part. My question is more about the implicit assertion that $A^l=w_l$, i.e. raising $A$ to a power is the same as applying $w$ $l$ times.
Comment: @crf: Now that I look more closely, I see quite a bit more that you really ought to have said (and that I mentally filled in without realizing that I was doing so). Give me a few minutes to expand my answer.
Comment: @crf: See how this version looks.
Comment: Awesome. I was thinking that maybe there was some argument that could me made that matrix multiplication is like applying the same function over and over again and so those are actually the same thing, but I don't know if that works. This works perfectly though.
Comment: @crf: I suspect (without having thought it through) that anything along those lines would in the end come down to this or something very similar anyway.


limit of complex line integral over a uniformly convergent sequence of curves

Question: suppose $f:\Omega\to\mathbb C$ is continuous,  $\Omega\subset\mathbb C$  is open and connected, $\gamma_{n}:[0,1]\to\mathbb Ω$  is a sequence of continuous curves that converges uniformly to $\gamma:[0,1]\to\mathbb Ω$
I've been asked to prove that:
$$\lim_{n\to \infty}\int_{\gamma_{n}}f(z)dz=\int_{\gamma}f(z)dz$$
I'm stuck.
Thanks in advance
Comment: Aren't the curves given to be smooth or some other condition about being differentiable?
Answer: Hint: A stronger hypothesis that each curve of the sequence is smooth is needed. Now about an approach to get a solution. You can use the fact that $\gamma_{n}(t)=f_n(t)+ig_n(t)$ where $f_n , g_n$  are uniformly convergent sequences and converge to  $\gamma(t)=f(t)+ig(t)$for $t\in [0,1]$ . Then make the substitution for the standard contour integral into a real one and using the fact that the convergence is uniform you can pass the limit inside the integrand. Be careful though because some derivatives will emerge so you need to use the uniform convergence hypothesis again.


AngularJs & Ionic : Stop/Restart $timeout when change and return to view

Question: I have a View that is updated after 1 minute, I stop the timer after before leaving this view, and all is OK.
After returning to the current view the timer don't restart again.
This is the code of the controller of this view:
<code>.controller('IndexCtrl', function($scope, $timeout, RestService) {
    var updateN = 60*1000;
    $scope.test = "View 1 - Update";
    var update = function update() {
         timer = $timeout(update, updateN);
         /** make a http call to Rest API service and get data **/
        RestService.getdata(function(data) {;
             $scope.items = data.slice(0,2);
         });
    }();

   /** Stop the timer before leave the view**/
    $scope.$on('$ionicView.beforeLeave', function(){
   $timeout.cancel(timer);
      //alert("Before Leave");
   });

   /** Restart timer **/
    $scope.$on('$ionicView.enter', function(){
    $timeout(update, updateN);
      //alert("Enter");
   });
})

.controller('ViewCtrl2', function($scope) {

  $scope.test = "View 2";

});
</code>
Answer: I resolve the problem,
There is not a problem with the cache, but with the function update that is not called after I re-enter on the page.
I move the update function inside the $ionicView.enter :
The corrected code is:
<code>   $scope.$on('$ionicView.beforeLeave', function(){
      //updateN=12000000;
      $timeout.cancel(timer);
      //alert("Leave");
   });

  $scope.$on('$ionicView.enter', function(){
      //updateN=12000000;
    var update = function update() {
    timer = $timeout(update, updateN);
    RestService.getdata(function(data) {
        //console.log(tani);
        //$scope.items = data;
        $scope.items = data.slice(0,2);
    });
   }();
   });
</code>
Comment: That was the problem. You can always use the angular service [$interval](https://docs.angularjs.org/api/ng/service/$interval).
Answer: When you go back to current view, it comes from the cache, so the controller does not work again. You can disable caching in the config section of your app by adding this line of code :
<code>$ionicConfigProvider.views.maxCache(0);
</code>
or you can disable cache on a specific view in the routing part by addding
cache : false property.
More information here and here
Comment: I already have set cache false to the current view:

On the Index template I have set :

 ........
Comment: Did you try the .config version of disabling cache?
Answer: In your code your controller function does not call on change of view. call $timeout function outside of var update function. Each time view loads it call its controller and call anonymous or self executing functions in their scope.
<code>.controller('IndexCtrl', function($scope, $timeout, RestService) {
var updateN = 60 * 1000;
$scope.test = "View 1 - Update";
var update = function update() {
    var timer = $timeout(update, updateN);
    /** make a http call to Rest API service and get data **/
    RestService.getdata(function(data) {;
        $scope.items = data.slice(0, 2);
    });
}();

/** Stop the timer before leave the view**/
$scope.$on('$ionicView.beforeLeave', function() {
    $timeout.cancel(timer);
    //alert("Before Leave");
});

/** Restart timer **/
$scope.$on('$ionicView.enter', function() {

    timer()
});
</code>
})
.controller('ViewCtrl2', function($scope) {
<code>$scope.test = "View 2";
</code>
});


Conditional Probability using an urn.

Question: An urn contains $5$ white balls and $6$ black balls. $3$ balls are drawn sequentially without replacement. What are the probabilities...
a. $P(\text{2nd is black} | \text{1st is white})$?
For this one I did the
$$ P(\text{1st is white})=\frac{5}{11} , $$
and
$$ P(\text{second is black}) = \frac{3}{11}*\frac{3}{11} $$
(that is the probability of WB and BB added together). I multiplied the probability of
$$ \frac{P(\text{2nd black} \cap \text{1st white})}{P(\text{1st is white})} , $$
for this I got
$$ \frac{\frac{5}{11}*\frac{3}{11}}{\frac{5}{11}} = \frac{3}{11} . $$
However since this is without replacement I did not think that the answer could be independent, some feedback would help. Alright so I have this figured out that it should be $\frac{6}{10}$.
b. If I am looking now for $P(\text{3rd is black} | \text{1st is white and 2nd is black})$, I ended up with
$$ \frac{\frac{5}{9}*\frac{3}{11}}{\frac{3}{11}} , $$
this is again an independent answer is this correct?
Comment: "(that is the probability of WB and BB added together)" should actually involve *adding* rather than multiplication.
Comment: This is a bit hard to read.  Given that the first is white, there are then $4$ White balls and $6$ black balls left in the bin. Hence the conditional probability that the second is Black is $\frac 6{10}$.
Comment: Yes I am new and struggling with the notation in maths tax, so sorry. I see what you are saying now. I have asked another question if you care to look at this one. Thank you for the help!
Comment: But, try to write readable expressions.  Nobody can follow your iterated divisions.   In any case, if you have seen one white and one black, that leaves four white and five black so the answer would be $\frac 59$.
Answer: There's no need to use any formulas here, just look at what happens when you follow the conditions and remove the relevant balls from the urn step by step.
If we start with $5$ white balls and $6$ black balls, then we're given that the first ball drawn is white, then after that first draw, $6$ black balls remain and $5-1=4$ white balls remain. So, we have $6$ black balls out of $10$ total balls, and the answer to the first question is
$$ P[\text{2nd is black} | \text{1st is white}] = \frac{6}{10} . $$
For the second question, we're given that the first is white and the second is black. So, after these two draws, we know that $5-1=4$ white balls remain and $6-1=5$ black balls remain. Out of a total of $9$ remaining balls, $5$ are black, so we have
$$ P[\text{3rd is black} | \text{1st is white and 2nd is black}] = \frac{5}{9} . $$
Answer: Using the notation $B_n$ to represent the events "the $n$-th ball is black", and $W_n$ likewise for white balls.
$$\mathsf P(W_1)=\dfrac{5}{11}\\\mathsf P(B_2)=\dfrac 6{11}$$
Reason: each individual ball has the same chance to be the second one drawn there are six black balls among the eleven.

(that is the probability of WB and BB added together).

That is true, but for some reason you multiplied.  You should add.
$$\begin{align}\mathsf P(B_2)&=\mathsf P(W_1\cap B_2)+\mathsf P(B_1\cap B_2)\\[1ex] &=\mathsf P(W_1)\cdot\mathsf P(B_2\mid W_1)+\mathsf P(B_1)\cdot\mathsf P(B_2\mid B_1)\\[1ex]&=\dfrac{5}{11}\dfrac{6}{10}+\dfrac{6}{11}\dfrac{5}{10}\\[1ex]&=\dfrac 6{11}\end{align}$$
Here, $\mathsf P(B_2\mid W_1)$ is evaluated as the probability for drawing one from the $6$ black balls when selecting one from the $10$ balls remaining after one white ball has been removed.

I multiplied the probability of
$$ \frac{P(\text{2nd black} \cap \text{1st white})}{P(\text{1st is white})} = \frac{\frac{5}{11}*\frac{3}{11}}{\frac{5}{11}} \\= \frac{3}{11} .
 $$

You had already found  $\mathsf P(\text{1st white$\cap$ 2nd black})$ to be just $3/11$.  So you wanted:$$\mathsf P(B_2\mid W_1)=\dfrac{\mathsf P(W_1\cap B_2)}{\mathsf P(W_1)}=\dfrac{3/11}{5/11}=\dfrac{3}{5}$$
Which, again, you had already evaluated without recognising it.
Answer: I'm not sure what you did, but
P(2 is B|1 is W) = P(pick B among 4W6B) = 6/10
Answer: a. P(second is black|first is white)=P(black ball out of 4 white 6 black)=6/10
b. P(third is black|1st is white and 2nd is black)=P(black ball out of 4 white and 5 black)=5/9

Conditional Probability using an urn.


Conversor de decimal para binário em C

Question: Estou fazendo um código em C para um trabalho de faculdade com o objetivo de converter um número decimal para binário. Porém quando o programa executa, ele sempre imprime 00000000, não importando qual número eu coloque. Alguém saberia dizer qual é o erro? Segue o código:
<code>#include <stdio.h>
#include <stdlib.h>

int main() {

    int num;
    int bin[7];
    int aux;

    printf("Digite o número (base decimal) para ser convertido: ");
    scanf("%d", &num);

    for (aux = 7; aux >= 0; aux--) {
        if (num % 2 == 0) {
            bin[aux] = 0;
            num = num / 2;
        }
        else {
            bin[aux] = 1;
            num = num / 2;
        }
    }

    for (aux = 0; aux <= 7; aux++) {
        printf("%d", bin[aux]);
    }

    return 0;
}
</code>
Comment: Qual seria a lógica que você utilizou na linha `num = (num / 2) - 0.5;`? Esta subtração de 0.5 não faz muito sentido (lembrando que a variável é do tipo `int`, portanto, quando um valor ímpar é dividido por dois, o resultado é arredondado para baixo; por exemplo, 5/2 = 2).
Comment: @JeffersonQuesado Não é duplicata por causa da recursão. O caso aqui é mais fechar como um problema que não pode ser reproduzido. Testei o código aqui e funcionou. O Woss há mais de um ano atrás também testou e também funcionou.
Comment: Precisa funcionar para números negativos?
Comment: Verdade, consertei essa parte, mas o problema continua. Não precisa pra números negativos
Comment: https://repl.it/HUEA/0 aqui funcionou perfeitamente. Como está testando?
Comment: Fiz no Dev-C++... provavelmente é problema do compilador então
Comment: Relacionado: https://pt.stackoverflow.com/q/286742/64969
Comment: Possível duplicata de [Como obter a representação de um número inteiro positivo em binário, usando recursão?](https://pt.stackoverflow.com/questions/267758/como-obter-a-representa%c3%a7%c3%a3o-de-um-n%c3%bamero-inteiro-positivo-em-bin%c3%a1rio-usando-recu)
Comment: @JeffersonQuesado É mais próximo da pergunta que você relacionou em abril deste ano.
Answer: Não consegui reproduzir o erro reportado, mas tem um erro na declaração do array "bin", que pela sua lógica precisa ter 8 elementos. Fora isso, não parece ter nada errado.
<code>#include <stdio.h>
#include <stdlib.h>

int main()
{
   int num;
   int bin[8]; // <---------------
   int aux;

   printf("Digite o número (base decimal) para ser convertido: ");
   scanf("%d", &num);

   for (aux = 7; aux >= 0; aux--)
   {
      if (num % 2 == 0)
         bin[aux] = 0;
      else
         bin[aux] = 1;
      num = num / 2;
   }

   for (aux = 0; aux < 8; aux++)
       printf("%d", bin[aux]);

   printf("\n");

   return 0;
}
</code>

Conversor de decimal para binário em C


Balanced Mono Output through Software on Stereo Jack Output

Question: I have a Focusrite Scarlett 18i20. The USB interface has 4 balanced mono outputs and 2 unbalanced stereo headphone outputs.
I want to output a mono balanced signal on the unbalanced stereo headphone output.
Is there software to generate a balanced signal on two channels? I can then route those two to L and R of the stereo jack and should have a balanced mono output. Or is there a flaw in this approach?
Thanks!
Comment: I think the major flaw is in thinking a line out really needs to be balanced. Sure, some line outs, especially if you're running to huge internally-amped monitoring, can benefit from it in noisy environments, but you don't really need it for anything else at those levels.
Comment: Thanks for your answer! Wouldn't it be best practice to use a balanced signal when you run long distances, say more than 10 meters?
Comment: 10m, the length of a decent guitar lead… nope, I wouldn't bother balancing one of those & certainly not output level signals. I can't think of any studio I've ever worked in that used balanced line-level, only mic. I've seen patch panels with TRS jacks, but they tend to be multi-purpose, can push a guitar one way, headphones the other, without being too fussy about which socket to use.
Comment: thanks for the helpful examples. at what length would you say one should start thinking about switching to balanced cables for line-level signals? it probably also depends on the environment?
Comment: Stage to FoH, which is an area I've never really worked in. Always been a studio engineer, occasionally helping out with live, but I never did the rigging.
Answer: If you just output a signal on the left headphone channel and keep the right channel at zero, you have a balanced signal.  Balancing really is about having the same impedance on both lines and evaluating the differential at the receiving side.  Many balanced outputs are done in that manner (rooting the voltage-only signal and signal ground through a matched resistor pair for hot/cold) rather than using an inverted signal for the return: this has the advantage that you don't have ±6dB changes when using unbalanced cables/targets that short the cold line.
Comment: i don't have the electronics background to analyse this properly, but to me that ends up with a huge DC offset I can't think around.
Comment: Nice! I clearly haven't tinkered enough with electronics, because I could only think of the plus/minus thing that was explained in a text book 30 years ago. :)  (A+noise)-(-A+noise)=2A, but (A+noise)-(0+noise)=A, so you still get A without noise. Or maybe this "hack" was explained there and I just remembered half of what was said in the book.
Comment: Thanks a lot for the answer. I can follow the math that leads to A or 2A, but how does the receiving side know, which method was applied? And if by default 2A is expected, wouldn't this result in 1/2 A = 0.5 A ? This may be the DC offset Tetsujin refers to?
Comment: @tetsujin I think the way around is given by the decoupling capacitors which are usually located on inputs and outputs of audio systems (and responsible for the pop on powering on as they equilibriate). Their main goal is to remove any DC component of the signal so it is likely that this DC offset won't be propagated anywhere...
Comment: I was only looking at it as a math equation. Maybe a question or search on Electrical Engineering is in order https://electronics.stackexchange.com/
Comment: Any disadvantage of this approach?  It's standard to send an inverted signal on the second channel rather than silence, why is that standard?


ASP.NET membership roles - event management

Question: I'm working on a project for an events site. I want to create it so that users can create an event and they become the admin for only that event, and they can authorise others as fellow admins (FB style), meanwhile they are only a user for. Is it possible to use the existing roles tools built into .NET to do this?
Thanks
Comment: Why don't you create your own table for it. [eventId, userId]
Comment: You could do it by creating roles on the fly and making everyone able to administer some of the roles, but you'll likely wind up fighting the system. Better to do as Hatsjoem suggested and save the owner of each event with the event and using another table to grant access to the events for additional users.
Answer: The comments provided are pretty useful (create your own table for it\creating roles on the fly).  In short, the functionality you are looking for is not currently available in the existing Universal Role Provider packaged with .NET.  However, the URP is intended to only be a starting framework for you to work with\edit as you see fit.  I would use a combination of these 2 suggestions, using the built in role provider tables to generate roles on the fly, and use a custom table to manage that hierarchy.
Hope this helps, and welcome to Stack Overflow!


Alinhamento de campos HTML

Question: Tenho um formulário Bootstrap para um landing page.
Quero colocar os campos de data inicial e data final um ao lado do outro, sem quebrar meu responsivo.

        Período

                        Data inicial
                        <input type="date" class="form-control"
                               placeholder="Período inicial">

                        Data final
                        <input type="date" class="form-control"
                               placeholder="Período final">

Comment: Elabore: "_sem quebrar meu responsivo_".
Answer: Acho que seria isso que você queria, apenas acrescentei um id='final' na sua div do segundo campo e após, um CSS para formatação deles lado a lado.

Fiddle de exemplo

#inicial {float: left; width: auto;}
#final {float: left; width: auto;}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

        Período

                        Data inicial
                        <input type="date" class="form-control"
                               placeholder="Período inicial">

                        Data final
                        <input type="date" class="form-control"
                               placeholder="Período final">

Answer: Tente dessa maneira:

                Data Inicial
                <input type="date" class="form-control" placeholder="Período inicial">

                Data Final
                <input type="date" class="form-control" placeholder="Período final">

Comment: @MarcosHenzel Correto. Tens razão.
Comment: Acho que se colocar uma formatação `CSS` pra ficar lado a lado, aí sua resposta fica correta, pois assim fica um abaixo do outro.

Alinhamento de campos HTML


How can I update the time from chosen timezone every minute on my webpage?

Question: I have a jquery function that uses moment.js to calculate time in different timezone based on the clock in the client's system:
function updateTime(){
                var chicago = moment.tz("America/Chicago").format('h:mm:ss A');
               $('#time').html( chicago +", ");
            };

            moment.tz.add('America/Chicago|CST CDT|60 50|01010101010101010101010|1BQU0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0');

            updateTime();
            setInterval(function(){
               updateTime();
            },1000);

It works pretty nice, however when user changes his system clock, then the momentjs shows incorrect time. I figured out I can fetch timestamp from the server (by php) and use it as a start time for updating time on client's webpage. I tried to write a script as follows:
function updateTimeBasedOnServer(){
                var timestamp = 1443618723;
                var Chicago = new Date(timestamp);
                var dateString = Chicago.format('h:mm:ss A');
               $('#time2').html( dateString +", ");
            };

            updateTimeBasedOnServer();
            setInterval(function(){
               updateTimeBasedOnServer();
            },1000);

But it doesn't work. I want to have the same result as after running the first script, but with only the difference that it works independently from the user's clock in his system. How can I do that?
Here is my fiddle:
http://jsfiddle.net/b8o5cvdz/9/
Answer: There is an error here:
function updateTimeBasedOnServer(){
            var timestamp = 1443618723;
            var Chicago = new Date(timestamp); // Here you create a Date object
            var dateString = Chicago.format('h:mm:ss A'); // a Date object does not have a 'format' method. A moment.js object has it.
           $('#time2').html( dateString +", ");
};

To fix it, use a moment.js object:
function updateTimeBasedOnServer() {
    var timestamp = 1443618723;
    var Chicago = moment(timestamp); // <- Here I create a moment.js object from the time stamp
    var dateString = Chicago.format('h:mm:ss A');
    $('#time2').html(dateString + ", ");
};

Here you can find a JSFiddle with the working code.
To answer you second question in the comment:

Thanks, one more thing - the 2nd date does not refresh every second -
  is there a way of fixing it?

You should not hard code the timestamp value (1443618723) inside the updateTimeBasedOnServer() because at every call it will use that value. For this reason you do not see the time change.
To fix it, move the timestamp outside the method:
function updateTimeBasedOnServer(timestamp) { // Take in input the timestamp
    var Chicago = moment(timestamp);
    var dateString = Chicago.format('h:mm:ss A');
    $('#time2').html(dateString + ", ");
};

var timestamp = 1443618723;
updateTimeBasedOnServer(timestamp);
setInterval(function () {
    timestamp += 1000; // Increment the timestamp at every call.
    updateTimeBasedOnServer(timestamp);
}, 1000);

Se the JSFiddle with the updated code.
Comment: It does not update because every seconds it calls the `updateTimeBasedOnServer` method and use always the value as `1443618723 ` as `timestamp`. You cannot hardcode it in the method.
Comment: Thanks, one more thing - the 2nd date does not refresh every second - is there a way of fixing it?
Comment: oh yeah, I see it, thanks! :) one more thing - can I use it as a start time and then append seconds, so that I don't need to make an ajax call to my php script?
Comment: Yes, you can do it, after you have the correct base time from the server you can increment it locally without call the server every time.
Answer: You need to use .toTimeString() or similar on the Date object, not .format
function updateTimeBasedOnServer(){
            var timestamp = 1443618723;
            var Chicago = new Date(timestamp);
            var dateString = Chicago.toTimeString();
           $('#time2').html( dateString +", ");
        };

Updated fiddle
Comment: thanks - one quetion - is it ok to create a new date object every second? Is it efficient?


What happens if a player who has been cautioned during the match gets a second yellow card while kicks from the penalty mark are being taken?

Question: I know you could be tempted to say that the player must be sent-off, but Law 12 says the following (Law 12.3):

A player, substitute or substituted player who commits any of the following offences is sent off:(...) receiving a second caution in the same match

The point is, kicks from the penalty mark are not part of the match. This was written quite clearly in the old Laws of the Game (from the 2012 LoTG):

The kicks from the penalty mark are not part of the match

But this is actually still true even if the same passage is worded differently in the current Laws (Law 10.3):

Kicks from the penalty mark are taken after the match has ended

Therefore, according to the rules, the player cannot be sent off because he has not received more than one yellow card during the same match. Does it mean the referee will only be able to show the player a yellow card and report the misconduct to the appropriate authorities, but without being able to actually send him off?
Answer: A semantic reading suggests this is the case, however one should not interpret the Laws of the Game in a manner that produces an absurd result.
Practical Guidelines for Match Officials [pdf], p. 2:

Referees are expected to use common sense and to apply the 'spirit of the game' when applying the Laws of the Game

Interpreting the word in as during, rather than before, during and after in the sending-off offence receiving a second caution in the same match could produce a number of strange results:

A player receiving a second caution for dissent when the referee is leaving the field of play could not be sent-off (and receive a subsequent suspension for being sent-off).
In your example and hypothetical interpretation, the player commits a second cautionable offence and isn't sent-off. If this was the case, what's to stop them continually committing cautionable offences with no consequences - e.g. goading opponents, dissenting decisions, being generally uncooperative?
Related to the above point, if a goalkeeper infringement causes a penalty kick to be retaken, the goalkeeper is cautioned for unsporting behaviour (in the past this caution would occur after persistent offences only). If goalkeepers weren't sent-off for a second caution on this point, this would create a perverse incentive for goalkeepers to infringe without consequence.
Answer: Had the same question myself and took a dive into the LOTG. Found this in Law 10 FAQs on the IFAB website:

Question: 'A player is cautioned (yellow card, YC) during extra time.
After the match has ended, the same player receives a YC during kicks
from the penalty mark. What is the referee's decision?'
Answer: 'Warnings and cautions (YCs) issued during the match
(including during extra time) are not carried forward into kicks from
the penalty mark (KFPM). A player who receives a YC during both the
match and the KFPM is not sent off.  The two separate cautions are
reported to the appropriate authorities.'

So, to answer the question, a player who has been cautioned during the match and receives a second caution during kicks from the penalty mark (KFPM) can continue to participate in KFPM, unless they receive a further caution during the KFPM (in which case they would be sent off).
https://www.theifab.com/laws/latest/determining-the-outcome-of-a-match/#kicks-from-the-penalty-mark
Answer: A yellow card during Kicks from the Penalty Spot does not relate to the yellow card during regular time. Thus the goalie can continue.
Re player sent off during Kicks from the Penalty Spot. The other team does not reduce its number of players. The reduction only refers to number of players during regulation time. If a player on Team A is injured and cannot be substituted anymore during regulation time, then Team B must remove one of its players for the Kicks from the Penalty Spot.
Comment: This is directly contradictory to the LOTG and is totally incorrect. Law 12.3: a player must be sent off for receiving a second caution in the same match. Law 10.3: reduction of numbers to balance teams occurs at any time as necessary, before or during KFTPM.


How can I return a different number of results per page for a view if a user is accessing the site with a mobile device?

Question: I have a large number of views that show member profiles.  Right now, I only show 8 members per page, because on a mobile device it takes a very long time to scroll.
However, for the desktop, I could easily show 20 members per page.
Since there are a large number of views, I don't want to do this if I have to duplicate all of them and change the pager settings.  Is there another way to return a different number of results per page if the user is on a mobile device?
Comment: I just realised I asked [a very similar question](http://drupal.stackexchange.com/questions/50850/managing-blocks-in-a-responsive-theme) a while back. If I remember rightly you're on Pantheon? I haven't found a sustainable way to do this yet with their enterprise package (to be fair to them I haven't gone down every possible avenue so it may well be possible)
Comment: Yes, good point-- I'm on Pantheon, so the solution has to work on Varnish too.
Answer: You could use Browscap module along with Browscap Block which would add the visibility of blocks depending on device. Next you could add two blocks one for Normal screen and one for mobile devices.

Browscap Block
Browscap Block adds visibility options to block configuration settings
  to allow you hide or show blocks in mobile devices.

If you do not want to create multiple views then you could use the browscap function in your template file to detect the browser and then restrict the number of items displayed. The function would be browscap_get_browser()
This could either be done in hook_views_pre_build function or with in the Style output template file where it loops through the $rows array. you could restrict it the number to 8 depending on the device by exiting the loop once you reach the required count.
Comment: Without resorting to AJAX/ESI this is about the best you can get, although basing content on the UA string can be a bit hit and miss. You also need to give careful consideration to how you manage this, so you don't end up penalised in SERPs for showing different content to different users (your intentions are obviously harmless but there's no intuitive way for Google et al to know that), and so that all your content actually gets indexed. If your site's behind a reverse proxy it'll probably require some extra configuration on that server too
Comment: I am pretty sure it is too late in the template logic to alter view paging.
Answer: Personally, I would use something like Views Infinite Scroll instead of messing with the pager.  This would be better for most users in all cases.
However, you can use the Mobile Detect module inside a hook_views_pre_build().  Something like this (untested)
function mymodule_views_pre_build (&$view) {
  $detect = mobile_detect_get_object();
  $is_mobile = $detect->isMobile();
  $is_tablet = $detect->isTablet();

  if ($is_mobile && !$is_tablet) {
    $view->pager["items_per_page"] = 8;
  }
  else {
    $view->pager["items_per_page"] = 20;
  }
}

This would affect all views.  dpm() the $view object to see how you would use it to add logic to limit to particular views and/or displays.
However, adding logic like this really complicates the cachability of pages using the normal methods.  The Mobile Detect module has a submodule that adds some ctools selection and access rules.  Using this, you could have view panes for device types, and then leverage Page Manager for caching.
Disclosure: I am the author of the Mobile Detect module.
Comment: @nathan6137 Doubtful.  The module has some caching issues right now, similar to anything that modified behavior based on UA.
Comment: I had originally avoided Views Infinite Scroll because it does not work with the iPhone and there is no consistently working patch (https://drupal.org/node/1180962).  However, I was able to get Views Load More (https://drupal.org/project/views_load_more) with Waypoints to provide infinite scroll instead.
Comment: @PatrickKenny The patched version of the jQuery plugin works for me.  Oddly enough, I have never gotten Views Load More + Waypoints to do infinite scrolling.
Comment: The current release of Views Load More requires a patch (https://drupal.org/node/1889300) for infinite scrolling to work.  Also, you have to turn on both "Use AJAX" (general views setting) and "Use infinite scrolling" (pager setting) in the options; this is not documented (I added a request for at least putting that info in the README, but who knows when it will be acted upon).
Comment: Would this work with boost enabled?
Answer: For those that find this like i did, I am running drupal 10, look into Responsive Views Pager
It is simple with all the settings in the pager part of the view.


for loop in Shiny htmlOutput does not execute in order

Question: This is a really strange behaviour for using loop inside a Shiny htmlOutput. What I've been trying to do is very simple, execute a Javascript code (console.log) from the Shiny htmlOuput and print the loop number to the console. See code below:
<code>library(shiny)
ui <- fluidPage(
  actionButton("goButton", "Go!"),
  mainPanel(htmlOutput("result"))
)
server<-  function(input, output) {
  observeEvent(input$goButton,{
    output$result <- renderUI({
      html_output_list <- lapply(1:50, function(j) {
        htmlname <- paste("html", j, sep="")
        htmlOutput(htmlname)
      })
      # Convert the list to a tagList - this is necessary for the list of items
      # to display properly.
      do.call(tagList, html_output_list)
    })
    lapply(1:14, function(i){
        htmlname <- paste("html", i, sep="")
        output[[htmlname]] <- reactive({
          paste('<script>number=',
                            i,
                            ';console.log(number);</script>')
          })
        })
    })
}
shinyApp(ui = ui, server = server)
</code>
By clicking the go button, the result should be an ordered sequence number from 1 to 14 (as the number i loops from 1 to 14), but the actual outcome is 14,1,2,...,13. Try the range of i from 1:20 will generate a sequence as (14,15,16,17,18,1,19,2,3,4,5,6,7,8,20,9,10,11,12,13). Could anyone explain what's going on here? How come it does not follow the order? Obviously it's neither a random order.
Answer: Maybe this could help:
app:R
<code>   library(shiny)
    library(shinyjs)
    ui <- tagList(
            useShinyjs(),
            fluidPage(
            actionButton("goButton", "Go!"),
            mainPanel(
                     uiOutput("result")
    )))
    server<-  function(input, output) {

            observeEvent(input$goButton, {
                lapply(1:50, function(j){

                        shinyjs::logjs(paste('number=', j))
                    })

            })

    }
    shinyApp(ui = ui, server = server)
</code>
Comment: This may give the right answer, but it is slightly different from my purpose. You finished the loop by assigning the Javascript to an array (x) before output. Is it possible to output inside the loop? My code is to achieve this, but the execution does not follow the right order. Thanks.
Comment: Try with the shinyjs package, with the logjs function. Check the modified answer.


Is there a simple rule for interpretation of Interactions (and their directions) in binary logistic regression?

Question: I have a binary logistic regression with Y (a disease) and 5 independent variables (and some of their 2-sided interactions which did not cause multicollinearity). All of my single IVs significantly predict Y:

A: positive beta for males (males are more likely to get affected)
B: a positive beta (older people are more likely to be affected)
C (yes/no): a positive beta for smoking (smokers are more likely to be affected)
D (continuous): a positive beta (more traumatic patients are more likely to have disease)
E (yes/no): a Negative beta for treatment (treated cases were less likely to have diseases).

Now 4 interactions are significant and I want to interpret them. I know I should state that in a significant interaction, I should say that the effect of variable A on Y differed for B(1) and B(2). For example the effect of age on disease differed in males and females. But I don't know in which class (males or females), it was greater, and I don't know how to determine it.
The significant interactions and their direction of betas are as follows:

4 by 3:   positive beta
4 by 5: positive beta
1 by 2:       Negative beta
3 by 2:      Negative beta

I would appreciate if you could kindly guide me. I searched for this issue but the discussions on the web are all sophisticated (e.g. this one) and beyond me. I just want to know is there a simple rule to determine the direction of interaction [i.e., "is A's effect on Y greater in B(1) or B(2)?"], given the directions of the coefficients of the involved variables (A and B) and the coefficient of the interaction itself (A*B)? (B(1) and B(2) are the levels of binary variables (man or woman) or extreme ends in continuous variables ([young and old], [easy or difficult])
Many thanks in advance.
Comment: I believe this is a completely independent question compared to what is referred to, and marking it as a "duplicate" is misleading, IMHO. The reason is the style and concern of this question which totally differs from the other one. This one concerns in a general way with the direction of the interactions, while the other question is a technical question regarding a specific problem. The other one also uses R code to show the problem, while this one is of global generalizability, not only to R users but to anyone interested in stats or science or academia.
So linking this to that is irrelevant
Answer: A positive interaction effect between A and B means that when A increases, the effect (in this case log odds ratio) of B increases. A negative interaction effect means that when A increases, the effect of B decreases.
When interpreting the results, I often find it easiest to work in the odds metric rather than the log(odds) metric. I tend to start with the baseline odds just to refresh my (and my audience's) memory on what odds are, then continue to interpret the odds ratios of the main effects (odds ratios are literary that: ratios of odds), and then go on to the interaction effects, which in logistic regression are ratios of odds ratios. A complete example is given in my answer to Interpreting interaction terms in logit regression with categorical variables
Comment: Thanks a lot Maarten for your informative reply. I am a little bit familiar with OR and Beta as log(OR), but am curious how to use ORs, instead, to interpret interactions.

This sentence was awesome "A positive interaction effect between A and B means ..." but i still have a question:

Even if the effect of A itself is negative and B is positive, again that sentence applies to this situation? ("a negative interaction still shows that with decrease in A, the effect of B decreases? or since now the effect of A is negative, this sentence should be reversed?")
Comment: no, the original sentence remains valid regardless of the sign of the main effect. The answer I linked to above gives an example of exactly that case.
Comment: TRhanks a lot Maaten :) I would upvote your kind reply as soon as I gain enough points to qualify to vote (not that you care, of course!) :)
Answer: I'm not familiar with binary logistic regression, but in interaction effects in general, the way you understand them is by plotting (usually means, perhaps different in this case?).  That will allow you to see the relationship between different levels and state the interaction effect specifically.
Comment: Thanks Krysta. According to those sources I read on the net, interactions in logistic regression appear a little bit different, and also harder. But I will try to plot them, if I can.
Comment: But I am still looking for some rules of thumb to tell effect of A is greater in B(1) or B(2). That could facilitate my interpretation.
Comment: You probably already found this, but just in case not, there's good stuff here: http://www.ats.ucla.edu/stat/stata/seminars/interaction_sem/interaction_sem.htm
Comment: lol yes this is the one example I linked to in this page! :) but thanks anyhow.
Comment: Darnit! Good luck finding simpler info--you're right, there doesn't seem to be much simple out there on the topic.  The fact that there is a book all about (and called, in fact) Interaction Effects in Logistic Regression suggests that simple may not be in the cards!
Comment: lol yeah some sites say interpretation of interactions in logistic regression is unlike linear regression tricky and difficult.


Custom Block Class with custom Template, cache issue

Question: I need add a custom block in my website, this block must show some users values (from customs fields).
I can show all user variables I want but if a user value change for some reason, I must clear all caches for get the news values from the page where is showed my custom block.
I checked the drupal 8 cache API and try find some example, but I don't find how I do for my variables aren't cached. (or cached but refresh when datas user change)
My code is very simple, I have this hook theme (in my .module) :
function main_menu_theme($existing, $type, $theme, $path)
{
  $theme=array();
  $theme['block__main_menu_quick_stat_block'] = array(
    'base hook' => 'block',
    // 'render element' => 'block', // I tried with and without this line..
  );
  return $theme;
}

This is the build method from my Block Class:
class MainMenuQuickStatBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $build = [];

    // Get the currect Drupal User
    $user = _getCurrentUser();

//I tried this...
//  $build['main_menu_quick_stat_block'] = array(
//    '#one' => $user->customfieldone->value,
//    '#two' => $user->customfieldtwo->value,
//  );
//  return $build;

//I tried this...
//    return array(
//      'main_menu_quick_stat_block' => array(
//        '#cache' => array('max-age' => 0),
//        '#one' => $user->customfieldone->value,
//        '#two' => $user->customfieldtwo->value,
//      ),
//    );

//Last try..
    return array(
        '#one' => $user->customfieldone->value,
        '#two' => $user->customfieldtwo->value,
        '#cache' => [
          'max-age' => 0,
          // 'contexts' => ['user',], // I tried this
          // 'contexts' => 'user', // I tried this
        ],
    );
  }
}

For my custom template, I copied the default block.html.twig template from the theme directory.
I can show variables "one" and "two" from the webpage thanks to the custom template. But impossible to configure theses variables for they become uncacheable !
I also try with cache tags but no success..

EDIT 1 (after 4k4 detailed answer !)
This is my last try :
From my custom Block Class :
class MainMenuQuickStatBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $build = [];
    $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

    //$user = \Drupal::currentUser(); // If I use this way, I get this error in the "'tags' => $user->getCacheTags()," below : "Error: Call to undefined method Drupal\Core\Session\AccountProxy::getCacheTags() in Drupal\main_menu\Plugin\Block\MainMenuQuickStatBlock->build() (line 52 of modules/custom/main_menu/src/Plugin/Block/MainMenuQuickStatBlock.php)."

    $var1 = $user->field_field1->value; //If a log var1, I get a value here ($var1 = 7 by example)
    $var2 = 42; //its a test

    return [
        '#theme' => 'block__main_menu_quick_stat_block',
        '#test' => 42,
        '#var1' => $var1,
        '#cache' => [
          'contexts' => ['user'],
          'tags' => $user->getCacheTags(),
        ],
    ];
  }
}

From my .module file :
...
function main_menu_theme($existing, $type, $theme, $path)
{
  $theme=array();
  $theme['block__main_menu_quick_stat_block'] = array(
    'variables' => [
      'var1' => NULL,
      'test' => NULL,
    ],
  );

  return $theme;
}

I cleared caches (drush cr)
My custom template block is called when I load the page, but variables 'var1' and 'test' are null. Below, I log variables array with "{{ kint() }}" in my custom template :

I'm going to find drupal guide for know why my vars are null...
Answer: The problem is not your choice of cache parameters. If you set cache max-age to 0 you don't need any other cache setting to disable the cache.
The problem is how you use the block template. You probably render only the single variables you've added and not the default {{ content }} variable. This is the reason the cache info gets lost.
Better use a custom twig template for the custom variables:
hook_theme() in mymodule.module:
function mymodule_theme($existing, $type, $theme, $path) {
  return [
    'mytemplate' => [
      'variables' => [
        'var1' => NULL,
        'var2' => NULL,
      ],
    ],
  ];
}

build() in block class:
  public function build() {

    $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
    $var1 = $user->field_field1->value;
    $var2 = $user->field_field2->value;

    return [
      '#theme' => 'mytemplate',
      '#var1' => $var1,
      '#var2' => $var2,
      '#cache' => [
        'contexts' =>  ['user'],
        'tags' => $user->getCacheTags(),
      ],
    ];
  };

mytemplate.html.twig:

Additional user info

Field 1: {{ var1 }}

Field 2: {{ var2 }}

The template mytemplate will be nested inside of the block template, which then, if you change it back to default, can merge the cache data to the block level and page elements on higher levels.
Comment: remove `block__` from the template name: `main_menu_quick_stat_block` - about the user, that's a good point in your code, we need to load the full user entity
Comment: You can implement `getCacheTags()` and `getCacheContexts()`in your block plugin. But if you return in `build()` a render array, what you usually do in a block plugin, you don't need to merge the cache info yourself, this is done by drupal automatically.
Comment: Thanks for your detailed answer :) (+1) I tried your code but I get an issue..I updated my main post
Comment: First, I remove 'block__' from the '#theme' property in the custom Block Class, nothing changed..Then I removed 'block__' from the hook _theme and in my custom template and....Its works ! its marvelous haha :D As you said, the problem was the block 'context' use in my code. Just for curiosity, if I wanted keeps this block 'context', how can I did manage the cache of my block ? It's impossible ? Thanks you again :)
Answer: What you have should work by disabling cache completely.
'tags' => $user->getCacheTags() would allow you to invalidate, and while you want that too, it still means the block will by default be cached for the first user that accesses it. So what you additionally need is 'contexts'] => ['user'] to indicate that each user needs his own cache.
You could also implement the methods getCacheTags(), getCacheMaxAge() and getCacheContexts() on the block But that shouldn't change anything.
PS: Do not define global functions like _getCurrentUser(), always prefix with a module like main_menu_get_current_user() or make them part of your class (e.g. with a trait if you want to re-use)
Comment: I tried with 'user' context (I added "'contexts' => ['user',],", I updated my first post), but its still not work.. I don't understand why 'max-age' to 0 also doesn't work, I think I missed something somewhere.. but what ? x) the "_getCurrentUser()" function is a quick example for explain I get the current user :) Can you provide me a very simple example where user data is used in a custom block Class and called from a template and with no need clear cache when the user data is updated ?


How can I make web scraping of a field more difficult?

Question: I have a text field that I get with <?php print render ($content['field'][0]['#markup']); ?> in node.tpl. I'd like to somehow make loading the markup require a click, and deselecting it to put the placeholder markup back. It's a select dropdown if it matters.
I thought javascript might work, to test if scripts worked in node.tpl I tried
var test ="<?php print render ($content['field'][0]['#markup']);?>";
document.write(test);

but it loaded the markup for every node on the page in one line. My php/js skills are weak so I'm hoping there's a module that might help me. I'm open to any suggestions though.
Answer: You can try to do something like this:

Your Placeholder

Comment: I think something like this may work. It didn't with this field, it's a full html text field with a  in it though. Does .text support that?
Comment: forgot to write @
Comment: No, `text()` doesn't render HTML tags, it will show HTML tags as text, so in that case change every `.text` with `.html`...there is an example so you can see the difference between `text()` and `html()`: http://jsfiddle.net/hossain/sUTVg/


/search-results page returns 404 if no query parameter is present

Question: I have inherited a Drupal site with a node that uses /search-results as path alias.
The page works fine if I use https://example.com/search-results?keys=test or https://example.com/search-results?keys, but it returns a 404 error if I use https://example.com/search-results.
Any thoughts on where to begin?
Answer: How do you process the parameter? Is there a module to look at it? or you do it in your .theme hooks?
In any case you wanna try to set a default respose for the function you are using to process that key parameter.
Comment: That is a very good question. I've checked the .theme and didn't see anything.
There is a search api module installed which I am not familiar with.
The search form (on all pages) has an action for '/search-result', on that page, it says it is for an override of main view template and it uses 'exposed.keys' with comment: "exposed: Exposed widget form/info to display."
From there, i cannot see why this page would end up with a 404 error if that query parameter is not included.
Comment: Did you know if ther's a view named `search-results` or something like that?
Comment: this is what i can see:

there is a template in the theme named: page--search-result.html.twig
it contains an embed view (set in the .theme file) named views-view--search-content.html.twig.
if that embedded view is commented out in the page--search-result.html.twig the page will load (obviously without any results)
as soon as it is added back in, the 404 occurs even if nothing is on that embedded page.
Comment: it looks like it is using a built in filter Views->Search Content -> FILTER CRITERIA Configure filter criterion: Search: Fulltext search has 'keys' as the Filter identifier
Comment: In this configuration, did you see any `CONTEXTUAL FILTERS` under the `ADVANCED` tab?


What is the simplest way to compute the lowest integer greater or equal than a / b?

Question: r, a and b are integers.
I need the cheapest computation since in a critical part of the code.
I found :
r = (a / b) + (((a % b) != 0) ? 1 : 0);
if b is a power of 2, then a / b can be replaced with a >> log2(b)
and a % b with a & (b-1) which should save a lot of computation time.
Do you know any better solution ?
Comment: Is this really a bottle-neck?
Comment: Why not take him at his word? He says it's a bottleneck. He bothered to write up a question about it.
Comment: What's the relevance of it being a bottleneck or not? Are you going to answer only if it's a bottleneck? That's silly.
Comment: But for the sake of other people who might learn from the responses, it makes sense to answer as if it were a bottleneck so everyone can learn. This question is a great example of how a messy expression is actually doing something so simple that it can be made clear and efficient simultaneously, as Daniel showed.
Comment: This is pretty ugly, but relatively straightforward when you understand what it's doing, and probably not all that slow.  Any efforts to optimize by bit shifting when b is a power of 2, etc...unless you have a good reason to believe that's really going to be the case a *lot* of the time, I think you're going to slow things down with tests that aren't going to be true most of the time, and you'll have to do the "long" work anyway.
Comment: It's not silly.  Many times when things look a bit confusing, asking for more information can help...they may think it's a bottleneck because of reason A, but also B, and someone may point out that B grossly overshadows A, so it can be safely ignored, etc.  People are asking if it's really a bottleneck because they don't want to spend a lot of time answering a question that isn't going to solve the underlying problem.
Comment: @Nosredna: True...good point.
Comment: @Beska, having said that, dilig0's comments to the responses don't exactly make the case for authenticity, do they?
Comment: @Nosredna: not so much, no.  I'm rather beginning to feel like someone is yanking our respective chains.
Comment: @Nosredna: I don't know where he's coming from. Without proper information getting to the proper answer is hard. I wouldn't call the question especially fleshy, so maybe he's made super-rigorous tests on the code, or he's just taking a shot in the dark. Like I said, no way to know without asking is there?
Answer: val r = (a + b - 1) / b

For example:
scala> for(a <- 1 to 10; b <- 1 to a) println("a: "+a+"\tb: "+b+"\tr: "+((a+b-1)/b))
a: 1    b: 1    r: 1
a: 2    b: 1    r: 2
a: 2    b: 2    r: 1
a: 3    b: 1    r: 3
a: 3    b: 2    r: 2
a: 3    b: 3    r: 1
a: 4    b: 1    r: 4
a: 4    b: 2    r: 2
a: 4    b: 3    r: 2
a: 4    b: 4    r: 1
a: 5    b: 1    r: 5
a: 5    b: 2    r: 3
a: 5    b: 3    r: 2
a: 5    b: 4    r: 2
a: 5    b: 5    r: 1
a: 6    b: 1    r: 6
a: 6    b: 2    r: 3
a: 6    b: 3    r: 2
a: 6    b: 4    r: 2
a: 6    b: 5    r: 2
a: 6    b: 6    r: 1
a: 7    b: 1    r: 7
a: 7    b: 2    r: 4
a: 7    b: 3    r: 3
a: 7    b: 4    r: 2
a: 7    b: 5    r: 2
a: 7    b: 6    r: 2
a: 7    b: 7    r: 1
a: 8    b: 1    r: 8
a: 8    b: 2    r: 4
a: 8    b: 3    r: 3
a: 8    b: 4    r: 2
a: 8    b: 5    r: 2
a: 8    b: 6    r: 2
a: 8    b: 7    r: 2
a: 8    b: 8    r: 1
a: 9    b: 1    r: 9
a: 9    b: 2    r: 5
a: 9    b: 3    r: 3
a: 9    b: 4    r: 3
a: 9    b: 5    r: 2
a: 9    b: 6    r: 2
a: 9    b: 7    r: 2
a: 9    b: 8    r: 2
a: 9    b: 9    r: 1
a: 10   b: 1    r: 10
a: 10   b: 2    r: 5
a: 10   b: 3    r: 4
a: 10   b: 4    r: 3
a: 10   b: 5    r: 2
a: 10   b: 6    r: 2
a: 10   b: 7    r: 2
a: 10   b: 8    r: 2
a: 10   b: 9    r: 2
a: 10   b: 10   r: 1

This does assume a and b are positive. If either are negative, it depends on whether the division is symmetric or floored (modern languages and platforms are symmetric), and the signal of a and b.
If a*b >= 0, then the formula works as given. If the division is symmetric and a*b < 0, then a / b gives the correct answer.
Comment: Good call, wouldn't have thought of doing it that way
Comment: For some reason, I have written this code many, many times. The trick is that `(b - 1) / b` is equal to `0`, so it won't change the result unless `a % b > 0`.
Comment: Fantastic.  Very elegant.  I'm impressed.
Comment: and a great demonstration over why improving the algorithm wins over optimising what is there provides such huge wins :)
Comment: To me that's the essence of optimization. You look at the inputs and the outputs and try to find the best way (whatever best may mean in the situation) from _here_ to _there_.
Comment: Be aware that this doesn't work for negative numbers, because / usually truncates towards zero.
Comment: @starblue, by "doesn't work," do you mean it behaves differently than the code given in the question?
Comment: If b is a constant as stated in a comment to one of the other answers, and also a power of 2, then the divide should be converted to a bit shift by any intelligent compiler. I imagine that's the answer to the 'game' that you were looking for?
Answer: In the title you ask about the "simplest" - yet the question alludes to the most "effective". Which one do you need?  In practice the simplest doesn't always equate to the most effective.
So if you need the simplest method, you should probably be using your language's ceiling function (usually called ceil), if you need the most efficient - that really depends a lot on the processor you're using (whether it implements division in hardware and other such factors)
Also, I'm a little skeptical about the performance of log2 - but I may be wrong.. However one thing is pretty clear: optimizing for the sake of optimizing is almost always not a good idea.
Comment: In this case the optimization (as Daniel showed) is also clearer code.
Comment: Indeed, the most effective is not always the simplest,
and log2 is definitely NOT an efficient function (actually b is a constant in my specific case)

But you did not play this little game ;-)
Comment: BTW, "effective" does not mean "efficient". It only means something that works (something that produces a notable effect).
Answer: What about:
(a - 1) / b + 1;

Obviously you have to watch yourself if a might be 0 or less. Negative numbers don't necessarily divide the way you expect, it depends on language and implementation.
Answer: modulo can be implemented a % n = a - (n * (a / n);
So taking that into account you could re-write as
const int div = a / b;
r = div + (((a - (n * div)) != 0) ? 1 : 0 );

which will be marginally faster as you only do one div instead of 2.
Edit:  If b is a constant then you can actually remove the divide completely and replace it with a multiply by a "magic number" (relevant to the constant divisor) that will be a small amount faster again.  Then again the compiler WILL make this optimisation anyway with a constant divisor.
Comment: What are you talking about dilig0?
Comment: It might be marginally faster. With a decent compiler, on a processor with an integer division op that calculates quotient and remainder, only one div will be done either way.
Comment: Man...better have a good comment in your code when you drop those lines in!
Comment: I was thinking something similar. Some algorithms compute both "/" and "%" at the same time.
Comment: Come to think of it, in cases with a "good" division op, this might end up slower than the questioner's code, because it introduces a multiply.
Comment: Finally someone who wants to play :)
All the other ones skipped that contest ;-)
I will wait a bit for someone giving a better solution, but your answer is the best candidate for being accepted.
Comment: Dilig0: have you checked the top rated answer?  I appreciate Goz's work here, but the top rated answer is less code and faster.
Comment: @dilig0: yep, "play" what? StackOverflow is a not a programming contest site.
Comment: Beska has a great point.  I wrote my response while my wife was waiting for me outside the office.  I didn't really think about the problem.  Sure I've given a good optimisation for the modulo operation but Daniel's suggestion is an algorithmic optimisation that makes my minor speed up (as pointed out, provided the compiler doesn't spot it anyway) pale into insiginifance.
Answer: This may or may not be suitable for what you're looking for, but most (if not all) languages provide access to a mathematical ceiling function. For example, in C#, writing Math.Ceiling(5/2) yields 3.
Comment: well, the function is Math.Ceiling for one... My guess is he's trying to keep it to integer division, but who knows...
Comment: even javascript has it :-)  "Math.ceil(5/2)"
Comment: Floating point math is usually slower than integer, especially if the parameters are integers and need to be converted.
Answer: Since no language was specified, I'm going to write a solution in ANS Forth as well...
: div ( a b -- r)
  FM/MOD     \ a b -- q rest
  IF 1+ THEN \ q rest -- r
;

Answer: If you are on a desktop, try floating point numbers and round them. But I doubt that you can find anything that is more cheap than two int devisions plus an add.
The only other option is the DIVMOD operator which some CPUs support. It will give you both the division and the rest in a single call.


Implementing open collector and 'z' data type

Question: I want to implement open collector protocol. When I try to set inout type port to 'Z' value, which is pulled up, it just continue to hold its previous value. To elucidate, I have just written the following VHDL code which first set o_sample_trig to 0 then set to to 'z' ( high impedance) state, since the o_sample_trig pin is pulled up it should immediately go to '1' state, but instead continue sending '0'! please advise me.
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
--********************************************
entity TopLvl is
port(
    clk,reset : in std_logic;
    max_tick: out std_logic;
    o_sample_trig: inout std_logic
    );
 end TopLvl;
 --***************************************************
architecture Behavioral of TopLvl is
signal timer1_reg,timer1_next : integer range 0 to 23999999:=0;
 attribute PULLUP: string;
 attribute PULLUP of o_sample_trig : signal is "TRUE";

begin

process ( clk ,reset)
begin
        if(reset ='1') then
            timer1_reg <= 0;
        elsif ( clk'event and clk='1' ) then
             timer1_reg <= timer1_next;
        end if;
end process;

 --**************************************************
  process ( clk ,timer1_reg)
  begin

            Timer1_next <= timer1_reg+1;

        if (timer1_reg >= 100 and timer1_reg < 150)  or (timer1_reg >= 200 and timer1_reg < 225) or (timer1_reg = 300) then
            o_sample_trig<='0';
        elsif (timer1_reg >= 150 and timer1_reg < 200) or (timer1_reg >= 225 and timer1_reg < 300) or (timer1_reg >= 400) then
            o_sample_trig<='Z';
        end if;
        if (timer1_reg >= 151 and timer1_reg < 199 and o_sample_trig = '1') then
            max_tick<= '1';
        end if;

end process;

end Behavioral;

Comment: The sensitivity list is incomplete in the second process. I don't see any reason to include `clk` in the sensitivity list and `o_sample_trig` is missing from the sensitivity list.
Comment: no, it is not the problem. :(
Answer: First re-read the post about pull-ups.   It is half of your solution.
Second, your logic about max_tick is wrong.   You need to handle 'H' as well as 1 and have an assignment for 0.
    if (timer1_reg >= 151 and timer1_reg < 199 and to_x01(o_sample_trig) = '1') then
        max_tick <= '1';
    else
        max_tick <= '0';
    end if;

Comment: it is not what I wanted to do, I want to send 0 through o_sample_trig port during timer1_reg >= 100 and timer1_reg < 150 interval, then receive input from the same port during timer1_reg >= 150 and timer1_reg < 200 interval. I do not want to trigger max_tick . I just mentioned max_tick  in order to synthesis tool not omit this port. and I have read pull up that is what I conceive from it please advise.
Comment: I already answered this question myself, the problem was the way I configure tristate buffer
Comment: If you leave your max_tick logic as it is, it starts at 'X' (which in some technologies can be a 1) and then later is assigned to a 1.   It is never 0.  Hence, it is not the sort of hardware most of us would ever expect to use or allow in a review.
Answer: You need to model the pull-up resistor.  In your test bench, assign 'H' (driving a weak one) to your tri-state signal:
o_sample_trig <= 'H';

You also probably need to fix your second process and add a conditional for the clock signal.  What you have might simulate, but it likely won't synthesize into hardware.
Comment: according to pedroni's book, 'H' will be synthesized as '1'. It  did not work.
Comment: I think Charles's suggestion is that if you have a open-collector, then there must be a pull-up somewhere - such as the board, the IO cell, or the testbench.   None the less, this must be modeled to be able to simulate.   Hence, as Charles suggested, perhaps you need to have it in your testbench?   Since the testbench is not synthesized, this will be fine, but also see below as this is only half of the solution
Comment: I do not attempt to design circuit for simulation at all. what I want is that I want to know why inout port not receiving input in the real world! and yes surly I tried to use physical pull up. besides 'H' state is defined to be used in simulation only.
Comment: I already answered this question my self, the problem was the way I configure tristate buffer
Comment: If max tick is not part of your concern, then post a minimal complete example for review here that does not include it.
Answer: according to Pedroni's book you cannot use a in/out port in that way and you should configure Tristate buffer in the following way:
1 ------------------------------
2 LIBRARY ieee;
3 USE ieee.std_logic_1164.all;
4 ------------------------------
5 ENTITY bidir IS
6 PORT (a, b: IN STD_LOGIC;
7 c: INOUT STD_LOGIC;
8 d: OUT STD_LOGIC);
9 END ENTITY;
10 ------------------------------
11 ARCHITECTURE arch1 OF bidir IS
12 BEGIN
13 c <= a WHEN b='1' ELSE 'Z';
14 d <= c;
15 END ARCHITECTURE;
16 ------------------------------
17 ARCHITECTURE arch2 OF bidir IS
18 BEGIN
19 PROCESS (a, b)
20 BEGIN
21 d <= c;
22 IF (b='1') THEN c <= a;
23 ELSE c <= 'Z';
24 END IF;
25 END PROCESS;
26 END ARCHITECTURE;
27 ------------------------------

using above code I managed to actually synthesize a tristate buffer.


Switching between view controllers

Question: I have three view controllers.  I used the flipsideproject template and then added another view controller.
There is a button on the first view controller that goes to the second view controller.  There is a button on the second view controller that goes back to the first one.  When switching between the first and second, those buttons always work.
It is the same situation with the second and third view controller.  When I try to transfer between the first to second to third and then back to first, it does not work.
(1-->2-->3-->2-/->1) My poorly drawn diagram depicts the situation.
I had all of the back buttons connected to the back IBAction, which I thought was the problem.  I then made another IBAction, but it has not fixed the problem.
1st view controller = MainViewController
2nd VC = FlipSideViewController
3rd VC = ChooseAlarmSound
This is for going 2->1 (this is the problem I think. It sometimes works)
<code>- (IBAction)done:(id)sender
{
   [self.delegate flipsideViewControllerDidFinish:self];
}
</code>
This is for going 2->3
<code>- (IBAction)chooseSound:(id)sender
{
    ChooseAlarmSound *controller = [[[ChooseAlarmSound alloc] initWithNibName:@"ChooseAlarmSound" bundle:nil] autorelease];
    controller.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentModalViewController:controller animated:YES];
}
</code>
This is for going 3->2
<code>- (IBAction)goBack:(id)sender
{
    FlipsideViewController *controller = [[[FlipsideViewController alloc] initWithNibName:@"FlipsideViewController" bundle:nil] autorelease];
    controller.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentModalViewController:controller animated:YES];
}
</code>
Comment: You include in your question by pasting it in to the question, then selecting it and pressing the {} button at the top of the edit box, or pressing command-K, or indenting by 4 spaces, or enclosing words in backticks : `. I've put your code from the comments in.
Comment: Can you show The code that you go from 3rd to 1st?
Comment: I never go from 3rd to first.  Thats whats weird.  I always go from 1->2, 2->3, 3->2,  and I can't go 2->1 after I have opened 3.  I can if I haven't opened 3.  Ill post the code.  One sec.
Comment: 1st view controller = MainViewController
2nd VC = FlipSideViewController
3rd VC = ChooseAlarmSound

This is for going 2->1 (this is the problem I think.  It sometimes works)
- (IBAction)done:(id)sender
{
    [self.delegate flipsideViewControllerDidFinish:self];
}

This is for going 2->3
- (IBAction)chooseSound:(id)sender
{
    ChooseAlarmSound *controller = [[[ChooseAlarmSound alloc] initWithNibName:@"ChooseAlarmSound" bundle:nil] autorelease];
    controller.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentModalViewController:controller animated:YES];
}
Comment: This is for going 3->2

- (IBAction)goBack:(id)sender
{
    FlipsideViewController *controller = [[[FlipsideViewController alloc] initWithNibName:@"FlipsideViewController" bundle:nil] autorelease];
    controller.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentModalViewController:controller animated:YES];
}
Comment: @jrturton: Good job of formatting.  I was trying to do it while using a mobile device.  But not as easy and I saw you made the change.
Comment: Yes, nicely formatted questions go out the window when posting from your phone, don't they? I feel your pain.
Comment: Thankyou for the help jrturton.  I will do that in the future.
Answer: You presented your 3rd VC (going from 2 to 3) using modalviewcontroller.  But then you tried to go back to 2nd VC (from 3rd to 2nd) using another modalVC.  That will not let you go back to the previous instance of 2nd VC.  You need to use dismissmodalviewcontrolleranimated method to do this.  Checkout Apple website on modalviewcontroller class reference for detail info on this.
Comment: I have no trouble going from 2->3 and 3->2.  Its only when I visit the third and then try to go back to the first (1>2>3>2--/-->1).
Comment: Can you do this test for me before I can further assist you:
On VC2, create an instance variable say an NSString, then assign some text to it.  Then move from 2->3.  And then move back from 3->2.  Now find out if that instance variable string still hold the text that you assigned to it before.
Comment: Almost forgot an important detail in my previous message.  By "assign" I meant to use a UITextField to get the input from you dynamically during running time and then assigning to that NSString.
Comment: It doesn't save.  (when typing on 2, then moving to 3, and then going back to 2)
Comment: That confirmed on my first explanation.  I would go ahead and replace your code in goBack method with this line (as also suggested by Darren's):
[self dismissModalViewControllerAnimated:YES]
Comment: If my answer solved your problem, would you select it as your answer by clicking on the check mark.
Answer: As suggested by user523234, all you need to do is call
<code>[self dismissModalViewControllerAnimated:YES]
</code>
in the
<code>- (IBAction)goBack:(id)sender
</code>
method of the 3rd view controller, instead of what you're doing, which is creating another instance of the 2nd view controller and presenting it.
The reason it's not working now, is because when you press the done button in the 2nd view controller it calls
<code> - (IBAction)done:(id)sender
{
   [self.delegate flipsideViewControllerDidFinish:self];
}
</code>
which is sending a message the 2nd view controller's delegate, which you haven't set in the case where you're going from 3->2.

Switching between view controllers


How can I maintain interest with a repeating bassline?

Question: If it helps, this is my bassline(opening the piece as the melody of a chorale), for a classical orchestra plus trombones and piano.

This bassline has to repeat for the entirety of the piece, with the possible exception of a coda. I've composed 6 variations at this point, and the repetition is notable. How does one mask the repetition? Brahms does this in the finale of his last symphony to great effect, but I have some difficulty analyzing his techniques and I find it exhausting to analyze orchestra scores. The harmony is limited, but I can still use rhythmic, melodic, and textural variation. Are there any concrete techniques to this form to mask the repetition?
Comment: Pachelbel's Canon in D repeats its baseline throughout, yet is immensely popular.
Comment: @It'sHEDLEY Firstly, that piece is much shorter(with less variations) than I intend mine to be. Secondly, do you know how many people are driven insane by Canon in D?
Comment: Imagine soloing on a repeated bassline and you should get some ideas. Feel free to **reharmonize** some variations.
Answer: The object of some of this sort of writing is to keep something going all through, as, for example, the snare in Bolero. It's the constant against the rest of the piece changing. Ostinato.
But - if you want it to change but stay the same, various options are available.
Alter the length of each note - even down to staccato.
Change the volume of each note, either playing pp, ff, or cresc., - decresc. for a couple of 'verses'.
Double up so each note is half as long, but played twice. Or thrice in 3/4 time.
Play the note so it starts a quaver early, sort of shifting the beat sooner.
Delaying the note, so there's a quaver rest before it's played.
Play two instead of one - note, octave above, note, in each bar.
Move that eight bar motif around to other instruments - a really nice idea, used many times already, kind of 'trading eights', or 'passing the baton'(sic).
By using these in combination, there are many, many variations available!
Comment: I'm trying to keep something all the way through without making it boring. A lot of pieces like that, even by great composers(like Bolero, or Canon in D), get some hammering at for being repetitive and boring. But, my previously mentioned Brahms movement lasts more than 9 minutes, and is anything but boring. Bach's Goldberg Variations, and his famous Chaconne in Dm, follow the same formula, and you get (REDACTED) by the Bach police if you call either of them boring, or so much as say anything about them that isn't superlative-filled praise. What did Bach and Brahms do that Ravel and...
Comment: ...Pachelbel didn't? This is my first piece that actually has a(low, but non-zero) chance of being performed, and killing the audience with boredom isn't a good move for a first premiere.
Comment: Another idea is to arrange your variations in increasing order of complexity (and hopefully interest). You can also (if allowed by the terms of the composition) change the harmony but keep the bass note the same.
Answer: Brahms does in fact not just keep repeating the Bass line in the fourth movement of his fourth symphony. You might want to check out ciaconnas and passacaglias that keep to the bass line more strictly, e.g. Bach's organ passacaglia in c minor.
You have a handful of options to vary the bass itself. You can change the rhythm, the dynamics, the orchestration, you might even feature the line in a different orchestral voice. But the rest has to come from the other voices. Even though the bass is the same you want to avoid a feeling of uniformity and repetition. You want to evoke different characters, different harmonic interpretations of the same bass line, different rhythmic interpretations and such. This means that optimally you'd compose your base line in such a way that you can do these things! So optimally you'd want your baseline to allow for lots of interesting harmonic progressions.
Really importantly the rest of your voices should be interesting enough to distract from the repeated bass line. But also the bass line should be something that is interesting enough to warrant hearing it more than once. If your bass line is boring on the third time you hear it isolated, it will probably not be well suited for basing a whole piece on the repetition of it.
Again, if you want to learn about these kind of things, you'd best study pieces where this is a principal design choice by composer who really had experience doing this, so baroque and renaissance ciaconnas and passacaglias.
Comment: I've heard from several sources that the Brahms movement IS a Chaconne/Passacaglia. Namely these: https://houstonsymphony.org/brahms-symphony-4/  https://www.youtube.com/watch?v=PxyyVVphogo      https://archive.schillerinstitute.com/fid_97-01/984_sub_moral_appen_PDFs/chapter8.PDF
Comment: The first six variations are pretty bare-boned, maybe that was my problem. I was more attempting a Beethoven style-variation, where each variation gets progressively more complex.
Comment: @OprenStein Yes, the last movement of Brahms 4th **is** considered a ciaconna or a passacaglia by some. It is definitely composed as a variation movement, and it has quite a few variations that feature the theme in the bass. But still Brahms is not strictly sticking to this theme, especially in the middle variations.
Comment: Look at the Brahms, the Pachelbel.  The bass lines aren't interesting, but they're STRONG.
Comment: @Laurence Well, you can call it that if you want.