Accessing Drupal 6 data using Drupal 7 entities

Question: I have a project where we have a legacy system built in Drupal 6 that has been heavily customized, with much of the data stored in custom tables.  We are currently planning a D6 to D7 upgrade, but we have an immediate need to access that data in a Drupal 7 instance, leaving the D6 site intact for now.
I would like to access that data using Drupal Entities and wrap each D6 table in a Drupal 7 Entity; however I'm having trouble making that work since the underlying assumption with the Entity API is that the data is stored in the local database, and this database is remote.  We can access the database directly from the Drupal 7 instance, and I have the database credentials loaded in settings.php.  I can query the data using Database::getConnection('default', 'legacy')->select(), so I know my connection is good; however I have no idea how to go about structuring an Entity class so that I can leverage EFQ, Views, etc. on this data.
I looked at Remote Entity API, but I"m not dealing with a RESTful service here, I have a direct connection to the D6 database.
Any assistance or hints would be greatly appreciated.  I've worn Google out.
Comment: Lisa, the question "Any assistance or hints" is a bit broad, but you can override an entities load function to fetch the data from anywhere you want, including a second database with custom content. I'd be happy to discuss the topic further in the [chat](http://chat.stackexchange.com/rooms/327/drupal-answers)
Comment: Drupal 6 and Drupal 7 data is heavily incompatible. Either you will have to practically rewrite entities from the ground up, or give up this idea, and follow classic solutions: 1) Migrate content to new site or 2) Start RESTful server on Drupal 6, and let it continue to handle your data.
Comment: @Mołot Luckily enough, someone's already done it
Comment: @Clive OP already said "I looked at Remote Entity API, but"
Answer: As I understand it you're discounting the Remote Entity API module because you don't have a RESTful service...
The module actually relies on the Web Service Clients module, which provides that REST service for you:

Parallel to the Services module, the Clients module provides the ability to implement pluggable clients to external web services, including external Drupal sites running the Services module, the main use case being connecting to other Drupal installs via the Services module with either the REST or XMLRPC server.
Clients module allows you to create connections to remote services with an admin UI. These handle fetching a result from a remote service. Different types of connection are provided for different types of services. There is a Drupal client connection type for different versions of Services (5.x-0.92, 6.x-2.x, 7.x-3.x), hence Clients can be used to connect to sites with different versions of Drupal.

Emphasis mine.
Comment: Yeah you may well be right, I could easily have got that wrong. But as your first comment on the question rightly alludes to, to make this happen you need some sort of translation layer between D6 and D7 data. REST feels like an infinitely better option than actually coding that layer as D6 CCK -> D7 fields
Comment: OP already said "I looked at Remote Entity API, but". Seems she already tried this solution and does not want it; prefers direct database connection.
Comment: @Mołot _but I"m not dealing with a RESTful service here, I have a direct connection to the D6 database._ suggests to me the OP is discounting solutions on false information - using this module you have an implicit RESTful connection. Unless there's another hidden gem of a module which magically exposes remote db connections as local ones, the only alternative I can think of is "write it from scratch".
Comment: Oh, if you're right, then good. I understood it more like she wanted to discard soon-unsupported d6 and use it's DB directly with 7.
Comment: Explain to me why I would need the Clients module.  I'm not dealing with a REST api, I have a direct database connection.  I simply want to query the remote legacy database instead of the local database.  Right now the legacy system continues to live and is being used on a daily basis, so migrating the data to D7 is not currently an option.  So, I'm failing to see where the Clients module has any role here, please enlighten me.  I can use the Database functions in Drupal 7 to do this, but I would prefer to leverage the Entity API if possible so that I can in turn leverage Views.
Comment: Also, D6 REST is not an option -- it's unsupported and has too many security issues associated with it at this time.
Comment: The clients module **provides a REST API for your Drupal 6 site**, that's why you would need it. I'm offering this to you as an alternative to the gut-wrenching amount of code you'd have to write if you want to expose the entity system to a remote database, which it was never intended to do. There's a good reason you haven't been able to find alternative suggestions with Google - it's a difficult and laborious feature to implement.
Comment: And that's just if you're going from Drupal 7 -> Drupal 7. What you're asking for is a fully-fledged, on-the-fly, translation layer from D6 data to D7 entity API, exposed over a remote database connection, with full API support. It's just not going to happen. Standardising your data into REST, though, which makes it version-agnostic, is distinctly possible. Hence this answer.
Comment: Lisa, I'm not trying to argue with you here - I'm telling you what solutions are available to you that don't involve writing a lot of code. Yes, there are other issues you'll need to overcome if you want to achieve this very advanced functionality, I'm just giving you, and anyone else who's trying to do this, one of the options. You don't have to do it this way, I'm not trying to force you to. But it would hardly be in the interests of our community for this question not be answered just because you don't want to implement it this way, when it's a viable solution to your problem.
Comment: From the documentation on the Clients module, you have to implement Services on the D6 site in order for the Clients module to actually with the D6 site to provide the REST API as you referenced.  https://www.drupal.org/node/2012982 and https://www.drupal.org/node/2125265 make D6 Services NOT a viable option due to security implications, as I had mentioned earlier, so the suggested solution of using Remote Entity API and Clients is not an option -- we will not be implementing Services on the D6 site.
Comment: Not quite, it's an option you _won't consider_. It's still a viable solution to the posed problem. But, like I said, I'm just trying to help you understand quite how mammoth a task you're trying to take on here, and offer an alternative way to get the results. Ignoring this option is perfectly fine, perhaps it will be sufficient for somebody else in future, though.
Comment: @LisaRidley Read [this](http://www.wunderkraut.com/blog/remote-entities-in-drupal-7/2012-10-25), it explains why remote entities are so hard to implement in D7, and why you can't have access to the full API when using them. All you need to do is substitute the 'web service' part of their solution with your translation layer of D6 -> D7 entity/field data, and you have everything you need
Answer: If it was me I would properly migrate the data from the old database into Drupal 7.
I would plan out the entities in the new site that will take the data from the old site. They may be nodes, custom entities, data module tables, users, taxonomy terms, etc.
Then I would migrate the data from the old database into those native Drupal 7 entities.
Then I would completely do away with the old legacy database.
By hanging on to the old database and somehow hacking it into your new website you are adding much unnecessary complexity and it will likely cause you lots of headaches in future.
As for the migration, I would use the Migrate module, the Migrate extras module and depending on your needs maybe the Drupal-to-Drupal data migration module.
The migrate module is fairly complex and has a bit of a learning curve but is very powerful. It follows consistent patterns though so once you've learned it it's not so scary.


Display additional fields from included content with Entity Reference field

Question: I'm building a site in Drupal 8 using a content type for products, and I want to show for each product, some "Related Products" that are set in an entity reference field called field_related_products.
Each related product wants to show the title and link (as the field works by standard), but also include the product image and price (defined in fields against each piece of content).
Is there a way to alter the output of the field to do this?
I've seen also that views might be a route to take, but can't seem to get contextual filters to work - the closest I've come is displaying all content that is included as a "related product" throughout the site, which feels a large portion of the way there, but whatever combination I try with contextual filters/default values, it just seems to remove all my results.
Thanks for any advice.
Answer: You can achieve this by setting a view mode (recommended: Teaser) in the node display for the entity reference field at /admin/structure/types/manage/[CONTENT_TYPE]/display, and then adding the price and picture fields to the Teaser display of the referenced entity.
If the referenced entity is also a node then it would have a similar path of /admin/structure/types/manage/[OTHER_CONTENT_TYPE]/display/teaser. The path would be different if it is not a node, but should be easily found for most custom entities through the UI under the commonly named entity page 'Manage Displays'. Once there view modes can be selected at the top of the page for editing them.


Anyone know how to make an entire form disappear on a jsp page?

Question:
ID Lookup

<FORM ACTION="index.jsp" METHOD="POST">

Please enter your User ID:

<INPUT TYPE="TEXT" NAME="userIDTextBox">

<INPUT TYPE="SUBMIT" value="Submit">
<%
    String userID = request.getParameter("userIDTextBox");

%>
</FORM>

I'm a beginner and this is my form on my jsp page. What I want to do is have the form disappear after submitting. Can anyone help me please? Or give some tips?
Comment: Which materials did you use to start learning HTML and JSP? The presence of those uppercased HTML tag/attribute format, the since 1998 deprecated `align` attribute, and the old school JSP *scriptlet* suggests that it's more than a decade old. This is not right. I strongly recommend to catch up with most recent materials. A good starting point is our tag wiki page. Hover the `[jsp]` tag which you put on the question until a black box shows up and then click therein the *info* link.
Comment: As to your concrete question, just conditionally print HTML using an `if` block (or tag, if you want to be modern). If the condition in the `if` block/tag is not matched, then its body won't be executed. Makes sense, right?
Answer: After Reading your requirement all I understand is you are trying to read parameter "userIDTextBox" from one page and need to display the value to some other page. And You are trying to achieve the same in one page.
Rather have two separate pages..

First with Form and required text field
Other to display the value
Define servlet and servlet-mapping configuration in web.xml

That is the valid way to do it. Hope it may help
Answer: Give your form an ID, then use a javascript command to get your form element and set its visibility.
var myform = document.getElementById('myForm');
myform.style.visibility="hidden";

Now you just need to handle a javascript event and run that.


Is $|\frac{y}{x^2}|\exp(- |\frac{y}{x^2}|)$ continuous?

Question: Let $q: \mathbb{R}^2 \to\mathbb{R}$ such that
$$
q(x,y):=\begin{cases}\left|\frac{y}{x^2}\right|\exp\left(-\left|\frac{y}{x^2}\right|\right),&\text{ for }x\neq 0\\0,&\text{ for }x=0\end{cases}
$$
Can I say that for all $x$ and $y$ and for all $\epsilon>0$, there exists $\delta>0$ such that if $|q(x,y)−c|<δ$, then $|q(x,y)−q(c)|<ϵ$. So since $\exp$ is defined everywhere on $\Bbb R$, let $c \in \Bbb R$ and let $\epsilon>0$. But how do I find a corresponding $\delta>0$? Or is that already totally wrong?
Answer: Let us study the continuity of the function at the origin. For the function to be continuous there,
the limit $$ \lim_{(x,y)\to (0,0)} \left|\frac{y}{x^2}\right|\exp\left(-\left|\frac{y}{x^2}\right|\right)  $$
should exist and be equal to $q(0,0) = 0$.
For the limit to exist, the function should approach the same value along any curve converging to the origin. However, if you consider the curve $(t,t^2)$, you see that, as $t\to 0$,
$$ q(t, t^2) = \left|\frac{t^2}{t^2}\right|\exp\left(-\left|\frac{t^2}{t^2}\right|\right) = \exp(-1) \not\to 0. $$
Hence the function is discontinuous at the origin.
Comment: This shows that the function is not continuous at the origin, as the limit as $(x,y)\to (0,0)$ does not even exist. EDIT: @saulspatz Ahh, now I see what you mean, I shall edit.
Comment: @saulspatz I have edited. Thanks for commenting, I agree that the first line was misleading before.


Bending with the "super light" strings

Question: I know bending technique is problematic with nylon strings. One has to pull them far to achieve the desired pitch change.
Is it the same with "super light" electric guitar strings which have tension rating similar to the nylon ones? E.g. D'Addario EXL130 or EXL120? Or do they work pretty much the same as the normal tension steel strings in this regard?
Answer: The only changes I've seen in electric guitar bending by string guage are the obvious one that it's harder to bend thicker strings (and easier to bend thinner ones), and the not-so-obvious one that if you switch to a wound G string from an unwound G string, you'll find the wound G string doesn't change in pitch as much with same amount of bending displacement. Basically you can't bend a wound G string as well.
That last point becomes a factor when you move up to string sets that have .012 guage high E strings and thicker. There are definitely 12s that are available with either wound or unwound G strings.
For lighter guage strings (8s are as light as I've gone - EXL 130 are 8s), I haven't found they don't change pitch as much. Definitely 9s (EXL 120) bend just like 10s, 11s, and 12s only with less force required.

Bending with the "super light" strings


How to return new model return in response response?

Question: In  laravel8/inertia/vue3 app creating model I set mode of the form in "add" mode and I try when new model is created return
it in responce , like :
$role = Role::create([
'name'       => $request->name,
'guard_name' => 'web',
]);
return back ()->with('data', [
    'role' => $role,
]);

But I can not get this new model on client part with code :
this.form.post(this.route('admin.roles.store'), {
    preserveScroll: true,
    onSuccess: (resp) => {
        console.log('resp::')
        console.log(resp)
        Toast.fire({
            icon: 'success',
            title: 'New role created!'
        })
    },

In browser I do not see model returned from control : https://prnt.sc/1xxhS-EOHLSh
How can I do this ?
Thanks!
Answer: I think you misunderstood some things:
First: When you use ->with, you're putting that data in a session flash. You're not returning it to the client. And putting the result into the flash probably isn't what you want.
return back ()->with('data', [
    'role' => $role
]);

Second: If you intend to use onSuccess on the client side to deal with the response, you can't return back(). You need to send an actual response to the client in a traditional AJAX way like this:
return [
   'data' => $role
];

Third: I would encourage you to avoid using onSuccess and returning JSON like described above, since this kind of defeats the purpose of Inertia and I believe it's provided more like an escape hatch for situations where you can't do things "the Inertia way".
Comment: If you stay on the same page, just "return back();". Otherwise redirect to another page which will take care of showing the roles... If you want to do something like toast notifications, you can "return back()->with('toast', 'Message here')" and then handle the toast in the session on the HandleInertiaRequest middleware.
Comment: What can be "the Inertia way" here without onSuccess ?
Comment: Thanks! it helped, but how can I with message to send also message_type(success/failure) ?


How to replicate large well powered mixed effects model with a smaller sample?

Question: Some edits made...
I have a dataset which other researchers have used mixed effects modelling with to come up with a nice set of associations. I also have a much smaller dataset which is the same variables but from a different country. The first dataset is plenty powerful enough (350 individuals from 30 locations) but the second dataset is not very powerful at all (70 individuals from 15 locations).
Is there some way to take what I know about the first data set and use it to boost the power of the second dataset? I've pooled all the data and analysed it and replicated the results, but I fear that is because the first dataset is just swamping the second one. So far I've come up with:
1) Analyse first dataset, then pool, analyse again, and compare AIC to see if it gets worse (seems a bit crude).
2) Analyse both datasets using a dummy variable for first/ second dataset (they're from different countries). This seems like a good idea but I'm not convinced it would eliminate the whole problem of the first swamping the second.
3) It sounds a bit like Bayesian statistics, but I don't know the first thing about Bayesian statistics, so if it is this then I'd better hit the library.
Any and all help as ever gratefully received!
Clarifications:
1) dependent variable same for both countries
2) oh dear, not sure I understand this question. All the variables are the same, so I have a list of their data, with a country code, and then the same variables again, with a different country code. All observations are individuals clustered in wards clustered in countries. Does this answer?
3) Really I'm just trying to replicate the significant linear associations which they found (or, I guess, highlight where they are different). So e.g. they found that size of ward improved outcomes, we would like to replicate that, along with some other associations.
Comment: Some points to clarify: 1. Is your dependent variable the same for both countries?  2. How did you pool both country data? 3. What type of the conclusions you are trying to make? My general observation is that if you pool both countries, you must assume that the same association applies in both of them. This usually is quite strong assumption. If it holds, then simply adding country specific variables to your pooled analysis might be enough.
Answer: Sounds like what you want is a hierarchical model: you would have a country-level effect, and nested within that would be a location-level effect. I've only ever skimmed through it, but the Gelman and Hill book seems to be quite highly regarded in this area:
http://www.stat.columbia.edu/~gelman/arm/
As for whether this sounds Bayesian: this is one area where the distinction between Bayesian and non-Bayesian techniques becomes very blurred. Personally, I find it easier to think of these models in Bayesian terms, because then you don't need to get bogged down in making the distinction between fixed and random effects.


Get all the text fields type and alter value after save

Question: I'm trying to alter the value of entity text fields upon node save, even the custom-made fields
so far I've managed to do that with the title and default body field but not with a custom field, I'm trying to target any field that might be a text field, here's my code:
function MODULENAME_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  $replacement_pattern = array("/a/", "/b/");
  $replacement = array("c", "d");

  /* Check whether it's a node */
  if ($entity instanceof \Drupal\node\NodeInterface) {
    // Node title
    $nodeTitle = $entity->getTitle();
    $entity->setTitle(preg_replace($replacement_pattern, $replacement , $nodeTitle));

    // Body main
    if(!empty($entity->body->value)) {
      $entity->body->value = preg_replace($replacement_pattern, $replacement , $entity->body->value);
    }

    // Body Summary
    if(!empty($entity->body->summary)) {
      $entity->body->summary = preg_replace($replacement_pattern, $replacement , $entity->body->summary);
    }
  }
}

Comment: see https://drupal.stackexchange.com/questions/213969/how-to-get-all-fields-of-specific-fieldtype
Comment: Thanks for the reference, still struggling though :(
Answer: Another approach by checking field name. I think this will get you the "custom" field part, but not the "all" fields part:
MYMODULE.module:
use Drupal\Core\Entity\EntityInterface;

function MYMODULE_node_presave(EntityInterface $entity) {
  if ($entity->hasField('field_name')) {
    $entity->get('field_name')->value = preg_replace(
      $toReplace,
      $newText,
      $entity->get('field_name')->value
    );
  }
}

But this only checks for fields of that name. I am also looking for a way to alter the value of a ckeditor/text field by testing field type instead of field name.
I would have hoped setting the field name value to something like text_long would have worked. This is a base field hook suggestion, but I am not having any luck at this time.
To add to the use case, it would be nice to alter ckeditor/text fields whether attached directly to the node, or via a Paragraph type.
The answer in the comment link above is helpful, but I have not succeeded in implementation.


Is there a difference between using $\alpha \cup \{\alpha\}$ and $\mathscr{P}(\alpha)$ in constructing ordinals in the cumulative hierarchy of sets?

Question: In constructing the sets in the cumulative hierarchy from the empty set, why is the power set operation even needed?
Let $V_{0} = \emptyset$, and inductively define $V_{\alpha+1} = V_{\alpha} \cup \{V_{\alpha}\}$. By using the union operator we can keep on constructing larger and larger sets. Why do we even need the power set operator here?
Comment: Yes, you can build *a* cumulative hierarchy this way (cf. https://en.wikipedia.org/wiki/Cumulative_hierarchy), but by changing the recipe it is no longer *the* cumulative hierarchy as introduced by von Neumann/Zermelo
Answer: This way you only get the ordinals. Note that the construction only yields sets which are transitive and all of their elements are transitive.
But not all sets are ordinals, not all sets are even sets of ordinals. Even if every set is equipotent to an ordinal (assuming choice, anyway).
Comment: So in some sense, the power set operator is more powerful?
Comment: Well... Obviously. Just look at Cantor's theorem.


Distribution of the $90$th percentile of a geometric brownian motion simulation

Question: I have run a simulation of a geometric brownian motion. The simulation runs from $t=0$ to $T=1000$. I generate $10000$ paths. For every moment for $t=1,2,3,\ldots, 100$ I calculate the $90$th percentile of the simulated paths. When I plot these points, depending on the used parameters, the curve that is produced is concave or convex. Please check the figure for an example.
When $\sigma$ is large relative to $\mu$, the curve of the $90$th percentile is concave (as above), and when $\sigma$ is small relative to $\mu$ the curve is convex. Is there any analytic formula for the distribution of percentiles of the GBM between two time instances? Also, is there an analytic or heuristic way to predict the shape of the 90th percentile (or any other percentile)? Thanks for the help.
Comment: This curve obviously is neither concave nor convex in any [standard sense](https://en.wikipedia.org/wiki/Convex_function), so what do you mean by these terms?
Comment: One thing to note is that for tail probabilities such 90th percentile, you usually need more simulations than for central tendencies (few simulations actually contribute to the 90th percentile).
Answer: The GBM's distribution at any given point is $$\ln x_t= \mathcal N(\mu t,t\sigma^2)$$
Hence the 90th percentile would be $$g(t)=\exp\left(\Phi^{-1}(\mu t,t\sigma^2,0.9)\right)=\exp\left(\mu t +\sqrt t \sigma \Phi^{-1}(0.9)\right)$$ where $\Phi^{-1}()$ is the normal or standard normal inverse CDF. This curve is certainly concave and smooth for any $\mu$ and $\sigma^2$.
Consider the second derivative: $$g''(t)=\left(\left(\mu+\frac 1 2 \sigma \Phi^{-1}(0.9)t^{-1/2}\right)g(t)\right)'=\\
\left(-\frac 1 4 \sigma\Phi^{-1}(0.9) t^{-3/2}+\mu+\frac 1 2 \sigma \Phi^{-1}(0.9)t^{-1/2}\right)g(t)=\\
\left(\frac 1 4\sigma \Phi^{-1}(0.9)(2- 1/t)t^{-1/2}+\mu\right)g(t)
$$
Since $g(t)>0$, the $g''(t)>0$ only when the following holds:
$$\frac 1 4\sigma \Phi^{-1}(0.9)(2- 1/t)t^{-1/2}+\mu>0$$
In other words this is the condition of convexity. It can be shown that it holds at sufficiently large $t$. So, the true percentile is concave at small $t$, and convex at large $t$.
You can see why this happens intuitively. At small $t$ the exponent is close to linear $e^x\sim 1+x$. Hence the only source of nonlinearity comes from the square root of time term in $g(t)$, which is concave. When $t$ is sufficiently large, the exponent, which is convex, starts to dominate and the percentile curve becomes convex.
The reason why you think that the entire curve switches convexity is due to imprecision of your Monte Carlo simulation. For instance, what appears to you as switching between convexity and concavity could be that you are in a sense looking at different parts of the curve. When you're playing with $\mu$ and $\sigma$ you're effectively changing the scale of your plot on $t$ axis. So, sometimes that inflection point can be to the right and sometimes to the left of you plot.
Now, your curve is an empirical 90th percentile, and it's a random curve as such. It will not have a derivative at any point in an ordinary sense, like @whuber mentioned. Hence, in an ordinary sense, i.e. second derivative's sign, it cannot be concave or convex. You'd have to define some measure of convexity for a random curve that doesn't have derivatives in order to judge whether your curve is concave or convex. Obviously, your measure should reconcile with the result I gave you based on theoretical properties of the percentile of GBM. Otherwise, it will not be a sensible measure, if it's not working even in a tractable case where the analytical solution is known.
Answer: I am a little unclear on what the graph is.  You mention calculating 100 moments, but I presume this is the 90th percentile boundary for the value of the path.  ALso, i presume this is the upper 90th percentile boundary; assumedly there is a lower 90th to go with it?
If I understand what you are doing right, the shape just shows which term is dominating.  If $\mu$ (the drift) is large and the volatility is really close to zero, it should look like $e^{rt}$ since there is exponential growth.  But, if $\mu$ is zero,and $\sigma$ is a realistic number, what you mwould see is the bounds growing as $\sqrt t$.
Comment: Hi, you understand it right, sorry if it is unclear. I understand that it depends on the relative strength of drift and volatility, I just would like to know if there is a way to quantify this, thanks.
Comment: The solution to the SDE for GBM is one that has a closed-form, exact solution.  In other words, we can specify the distribution $P_t$ (usually this occurs in finance, and Price is the variable of focus) for all $t>t_0$.  Since that gives you the mean and variance (and thus SD) at all times t, it should be easy to solve for the 90% bound.  Think of it this way: the 95% bound is at just about the mean plus 2 x SD.
Comment: there's no upper or lower 90th percentile. there's 10th percentile, if that's what you meant


If $1+x+x^2+\cdots+x^{y-1}$ is a prime number then how prove that y is also a prime number?

Question: If $1+x+x^2+\cdots+x^{y-1}$ is a prime number then how prove that $y$ is also a prime number?
$x$ and $y$ are natural numbers
Answer: No, it's simpler than that. Suppose $y$ is composite, $y=ab$. Then
$$ 1+x+x^2+\cdots+x^{ab-1} = (1+x+x^2+\cdots+x^{b-1})(1+x^b+x^{2b}+\cdots +x^{(a-1)b}) $$
and therefore the value of the LHS is composite too.


How random variable $Y$ following geometric distribution in the following situation

Question: I have a random variable, $X$ which follows exponential distribution with parameter $\lambda$. Then, define $Y=k$ for some $a$ greater than zero such that:
         $ka \leq X \leq (k+1)a$.
Now, my question is how can $Y$ follow geometric distribution. I am not able to understand why but book give me the answer that this $Y$ random variable will follow geometric distribution taking values $y=0,1,..$. Any help would be appreciated.
Answer: Hints:

Pick a positive number $a$. Go on, it is not hard, and there are no rules as to which number you pick, as long as it is positive.  Can't think of one? Use the last four digits of your mobile phone number with a decimal point between the first two and the last two digits.
Pick a nonnegative integer $k$. Again, just pick one number, it doesn't matter which one as long as it is nonnegative and an integer.
Now you have $k$ and $a$ and so can compute $ka$ and $(k+1)a$.  So, since $X$ is an exponential random variable with parameter $\lambda$, can you calculate the probability that $X$ takes on values between $ka$ and $(k+1)a$? Subhint: unlike the previous stuff, you will not be getting a numerical answer but rather a function of $\lambda$ which I hope will work out to be something that you can express in the form $p(1-p)^{k}$ for suitable choice of $p$; that is, you need to choose a function of $\lambda$, call it $g(\lambda)$ and say that if you set $p=g(\lambda)$, then you can write $$P\{ka \leq X < (k+1)a\} = p(1-p)^k.$$ This is the part that requires some thinking as to how to define $p$.
Your answer above is the probability that $Y$ takes on value $k$ where  $k$ is a nonnegative integer. So the general formula is
$$P\{Y = k\} = p(1-p)^k, k = 0, 1, 2, \ldots$$
Compare your answer to the second of the two forms of the geometric distribution shown in Wikipedia.


function calls in template arguments

Question: I'm struggling with the following situation.
#include "systemc.h"

template<int maxval>
class Foo {
  /* Error: calls to constructors and functions cannot be part of a constant expression */
  sc_uint<int(log2(double(maxval)))> a;
  ...
};

int main() {

  Foo<10> foo;
  ...
  return 0;
}

As you can observe above, the templated class 'Foo' has the template parameter 'maxval'. 'Foo' also holds a member, again a templated class, that uses the template parameter 'maxval' together with the function 'log2' in its template arguments for instantiation.
However, the depicted code will not work since e.g. function calls cannot be part of constant expressions.
Do you see any possibility to evaluate e.g. log2(maxval) during compile time and to use the result for further template arguments inside 'Foo'?
Thanks for your help.
(I'm using GCC 4.1.2)
Answer: Templates expect compile-time values. The log2 function would need to be constexpr for this to work (which it isn't).
You'd have to define your own constexpr function. In the case of a logarithm function to the base 2 it can work if you need an integer (cutting off the floating point part):
constexpr int log2(int number, int acc = 0) {
    return number <= 1 ? acc : log2(number / 2, acc + 1);
}

Edit:
I did not notice that the question asked for GCC 4.1, which does not support constexpr. While you should try to upgrade if that option is available to you, you can also go for a template-based solution, as proposed in @Florian's answer.
Edit 2:
In case you do not want to rely on Boost, here is a simple template-based implementation you could use:
template<int V>
struct log2 {
    static int const value = 1 + log2<V/2>::value;
};

template<>
struct log2<0> {};

template<>
struct log2<1> {
    static int const value = 0;
};

Then you'd use it as log2<13>::value, which would result in 3.
Yet another edit:
The constexpr implementation above will return 0 for 0 and negative numbers, which is a mistake. The logarithm is not defined for zero or negative values (in the real domain), so the function can be adjusted to throw an error (since it's getting a bit unreadable, I added some line breaks for formatting):
constexpr int log2(int number, int acc = 0) {
    return number <= 0
        ? throw std::logic_error{"Logarithm of zero or negative number not allowed."}
        : number == 1
            ? acc
            : log2(number / 2, acc + 1);
}

Comment: GCC 4.1 is way older than constexpr support.
Comment: @chessat2002 You need to compile with `-std=c++11` or `-std=c++14` to get `constexpr` support in GCC.
Comment: Make the arguments unsigned (The second solution will not terminate using a negative value)
Comment: Good point, sorry, didn't notice that. You'd either need to update your compiler (which you should definitely do, if you have the option, because 4.1 is very old and does not support many new features), or use @Florian's solution. I'll update the answer to reflect that.
Comment: @ Stjepan: Thanks a lot for your proposals! I think I have to go with the template-based solution since 'constexpr' does not work out for me, even with GCC5.2.0
Comment: @ Holt: Perfect! Now, both solutions work, amazing help guys :)
Comment: I had it `unsigned` originally, but I changed it to `int` only to match @chessat2002 's original code, where he also uses `int` as the parameter type. `unsigned` would probably be the semantically sound thing to do, although it's not a problem with the current implementation. `log2::value` for negative values of `x` would keep integrally dividing by 2 until it reaches 0, and `log2<0>` does not have a value member, i.e. you'd be getting a compiler error.

function calls in template arguments


Why there is no sign of logic symbols in mathematical texts?

Question: Either in undergraduate or graduate textbooks on Mathematics (Real/Complex Analysis, General Topology, Differential Geometry, ...), I never saw symbols $\Rightarrow$, $\iff$, $\forall$, $\exists$, etc. Instead, I just see their "read as" or explanation such as "if ... then ...", "if and only if", "for all", "there exists", etc. Before I started to study mathematics, I thought I would see a lot of logical symbols, but I didn't see any (even once!) even in the proofs. Why is that so? If they are for mathematical use and they take less space in texts, why are there none of them in mathematical textbooks?
Comment: @pyrazolam that seems an odd way to put it. The *most* formal proofs are all symbols. We choose to not use them because humans are not computers.
Comment: They are mostly seen in "shorthand" mathematics and are considered informal when written in a textbook. When you write a formal proof, for example, you don't use such symbols. Instead, you would actually write the words out to make the proof more "elegant" in a sense.
Comment: Why does no one want to admit that it's because mathematical symbols are harder to read and don't necessarily convey any more information than plain English?
Comment: Just for fun: once upon a time, mathematical symbols used to be harder to print than standard characters. I studied on many textbooks where symbols were hand-written! Nowadays TeX makes it all so easy.
Comment: Another issue is that logical symbols are actually harder to use. Most occurrences I've seen of students (or others, including me) using them result in proofs that are actually incorrect (implication instead of equivalence, bad quantification...)
Comment: I think this is a very interesting question; I used to try to write everything as purely symbolically as possible, supposing that it would lead to greater fluency, and that at some stage the symbolic form would become clearer to me than the verbal form, but in practice it did not work very well. I still like a fairly high density of symbols, but natural language has many tricks and subtleties that help create a mental framework in which to grasp an assertion, while there seems to be a cut-off point beyond which a symbolic formulation only gets across with a great deal of effort.
Comment: Actually, you are joking right? I was falling for it, right?
Comment: Personally I use them all the time when working on a proof; I find that it helps me think more clearly and helps me avoid any gaps in my logic. However after I have constructed a concrete proof symbolically, I rewrite it in words to clarify any questions that may arise and emphasise the structure of the proof. I have also found that working on proofs symbolically helps me understand definitions, theorems and their applications a lot better.
Comment: @MKR The "logical" version of you saying you washed your hand doesn't make any sense to me – even when knowing it should express you having washed your hands. Saying "$∃t_1 \colon f(t_1) → ∞$" doesn't make any sense. Also I think that should rather read "$∃t_2 > t_1$" instead of "$∃t_2 ≥ 0$" (If $t_2$ should be the time when you wash your hands). Also there's more *and* less to washing hands that getting rid of bacteria. Bottomline: The second version is definitely *not* more elegant than the first one, in fact it's absolutely awful.
Comment: *generally*, Logical symbols are only used when talking *about* Logic: (mathematical logic, metamathematics, set theory, foundations, etc.).  There are a variety of reasons for doing this, most having to do with readability and comprehension.  For example, using symbols only for the *subject* expressions and using text for the logical/meta expressions minimizes the chance of confusing the two.
Comment: @AlphaE: Just because two sentences mean the same thing and just because you can understand both of their meanings, that doesn't mean they require the same amount of brainpower to parse.
Comment: @FireGarden: Er, don't get too excited with the strawman... I was referring to mathematical symbols under the (obvious) consideration of this question, not to all symbols that have ever existed in all of mathematics as a whole. I'm asking why no one wants to admit that the use of symbols *in such contexts* actually make things harder to read and understand. Everyone seems to go on tangents with reasons like elegance or difficulty of printing or whatever, when in fact it's clearly about ease of parsing for the human reader.
Comment: @ThomasAndrews Is that true though. Maybe if we're talking "formal" in a formal logic sense then yes. But can you say proofs in every math discipline are more "formal" if they involve logical symbols? Aren't they still "formal" proofs no matter how we write it, as long as the way they're written/elucidated is correct? Or maybe the question is should formal logic be interpreted as to encompass everything.
Answer: Many mathematicians, and I want to be in that number, believe that

Let us fix any $\epsilon>0$. It follows from the assumptions that there exists a positive number $\delta$ with the property that $1/x<\epsilon$ whenever $x>\delta$

is more elegant than

$(\forall \epsilon>0)(\exists \delta>0)(\forall x)(x > \delta \Rightarrow 1/x<\epsilon)$.

Book authors often want to write good books, carefully written, elegant and pleasant to read. Book authors often think of themselves as artists, or professional writers: if, as others said in their answers, good English grants both style and scientific quality to a book, why not use it?
Comment: Wow. I've always found the second (symbol) version more elegant. In my opinion you can see at a glance what is going on, which quantor comes first , what implies what etc. For example, in the word-y version I find it extremely ugly that the "whenever" part comes last (whereas in the symbol version the epsilon-inequality comes last). Sometimes even "for all x" is pushed to the end of the sentence so that I find it hard to parse which symbols would have logical precedence.
Comment: Following my own answer, and somewhat sarcastically - why stop there? Perhaps it is more elegant to say "Let us fix any epsilon greater than zero. It follows from the assumptions that there exists a positive number delta with the property that one divided by the thing is lesser than epsilon whenever the thing is greater than delta."? (And I even lost some of my punch here because the statement is very simple. What if it involved more complex concepts and equations?)
Comment: To be honest, I always considered the latter to be much more elegant _and_ easier to understand. I don't like it when too many extraneous words clutter my field of vision, they're distracting and an undue burden on my cpu.
Comment: @MKR Do you means "by words"? If this is your question, then yes: most journals do not like logical symbols at all. If you insert $\forall$, $\exists$, $\iff$, it is highly probable that editors will replace them by english words.
British journals even correct each occurence of american spelling, but logical symbols are generally considered to be a blackboard shorthand.
Comment: But the two phrasings don't mean the same thing. The former includes an imperative ("Let us fix any $\varepsilon >0$.") while the latter is purely declarative.
Comment: @Chris: well, IMO it's sensible enough to just say "it follows from the assumptions that all $x$ above some $\delta$ fulfill $1/x < \epsilon$", without explicitly quantifying the $\delta$ into existance. Though indeed that obscures the order of quantors even more.
Comment: @ThomasAndrews Here in Italy most classical books in mathematics used to be written in a very literary way. I know that english is a more straightforward language if compared to latin languages... My books were full of sentences like "Fissiamo arbitrariamente un numero $\epsilon>0$" (Let us arbitrarily fix a number $\epsilon>0$)!
Comment: Yes. Thank you very much. Actually, so I did think all wrong, i.e. journals do not like words at all because logical symbols are more mathematical!
Comment: @goblin It seems to me that the imperative doesn't change the mathematical meaning. If we begin a theorem by saying "Let $\epsilon$ be any positive number" or by saying "For any $\epsilon >0$", I understand the same mathematical idea...
Comment: What is this '_it follows from the assumptions_' doing? It seems to be another difference between the statements. The verbal formulation also refers (a bit vaguely) to a '_number_', while the symbolic version does not specify the universe at all. I feel also that the rather trivial statement about $1/x$ - unless that is specially defined - is a less satisfactory example than one about $f(x)$.
Comment: I like the gist of this answer, but nobody would write that first sentence. In the first text, when talking about "any" $\epsilon$ we rarely talk about fixing it. And the start of the second sentence "It follows from the assumptions that," is completely redundant in a proof.
Comment: what about research papers? is it acceptable for publish if someone writes in first-type of writing that you mentioned? Thank you
Comment: i agree that the latter style represents the epitome of mathematical elegance. that is: simplified. reduced. swift. precise. mathematics unfettered by language. like a pure thought. it contains all it needs and nothing more. each symbol has exactly one purpose, represents one thing, and nothing is superfluous. it's not a novella, but a didactive statement of fact. i might present it as a figure accompanied by a more comprehensive written description & dialectic exposition.
Comment: I agree with the spirit of this Answer, but would like to point out that the latter option is being presented *unnecessarily* clunkily: I would simply write it very readably as $$\forall \epsilon{>}0\:\;\exists \delta{>}0\:\;  \forall x{>}\delta \quad\frac1x<\epsilon.$$
Answer: Certain symbols are best used only in certain cases.
The most common place where such symbols are used, at least when not talking about the topic of logic, is likely on a blackboard. That's because they are used in addition with the spoken word. Then the symbols are an abbreviated language.
For example, the "therefore" symbol does not have any formal usage in mathematical logic, and I've hardly ever seen it in print, but it is great for a blackboard argument because the professor accompanies it with he spoken word, "therefore."
Logic symbols for print exist because sometimes we want to reason about logic itself.
Comment: Oddly enough, I've never seen the therefore symbol on a blackboard, but it seemed _very_ common in textbooks of a certain age (particularly classical geometry texts).
Comment: Brilliant answer! Thank you very much. First time I saw them on a lecture.
Comment: Is the therefore symbol a strictly mathematical symbol? AFAIK Tolkien uses it at least twice in one of his letters, and I wouldn't count him as a mathematician...
Comment: Why the edit to remove "we" from "Logic symbols for print exist because sometimes we want to reason about logic itself"? Seems grammatically incorrect now. Can I rollback?
Comment: Not sure - I don't recall making the edit. @6005
Comment: Hey guys, I screwed up the edit. I changed the mobile Wiki link to a regular link, which is only a 2-character edit. SE requires 6 chars per edit, so I tacked on those f's, intending to delete them in a subsequent edit. Could someone fix this please?
Comment: @Bakuriu: The fact that Tolkien uses three dots (to represent _a_ in formal writing, says LOTR Appendix E/II/(i)/_vowels_) has no bearing on whether '∴' is a "genuine" or useful mathematical symbol. Its meaning as opposed to '⇒' is clear enough; whether you use it is more a matter of convention. The glyph '∴' (U+2234) seems not to be present in many fonts, though [Gentium Plus](https://en.wikipedia.org/wiki/Gentium) has it.
Answer: The famous topologist James Munkres requires students in his MIT courses follow  these guidelines on good mathematical style. Rule (7) reads

Don't use logical symbols at all. The symbols $\exists, \ni, \forall, \exists !, \vee, \wedge $ as well as the abbreviations s.t., w.r.t., are to be avoided in mathematical writing. In papers in logic, these symbols constitute part of the subject matter and are completely appropriate. In informal mathematical discourse, on blackboard or paper, they are often used as "parts of speech", in a sort of mathematical shorthand. However, they are not allowed by editors in formal mathematical writing.
Just as you wouldn't submit a history paper that is written partly in secretarial shorthand, don't submit a math paper written partly in mathematical shorthand!

Rule (8) adds

One exception is the use of the symbols $\Rightarrow$ (implies) and $\Leftarrow$ (is implied by) and $\Leftrightarrow$ (is equivalent to). One of course does not use these symbols as word-substitutes, any more than one uses $<$ or $+$ or $\cap$ as word-substitutes [e.g., "Consider the set of all numbers $< 1$" or "Consider the $\cap$ of the sets $A$ and $B$"].
But usage is allowed in phrases such as: "We show that (a) $\Rightarrow$ (b) $\Rightarrow$ (c)," or "To show (a) and (b) are equivalent, it suffices to show that (a) $\Rightarrow$ (b) and (b) $\Rightarrow$ (a)".
There is a reason why editors (at least those who are also mathematicians) enforce rule (7) strictly. Most mathematical readers find sentences in which this rule is violated quite unreadable, just as they find secretarial shorthand unreadable. They translate the sentence into the English language (or German, or French, or ...) mentally, before attempting to understand it. ...

Yes!
Comment: I like that "editors enforce rule 7 strictly", except that they don't. By the argument of rule 7 there's absolutely no reason not to write "it suffices to show that (a) implies (b) and (b) implies (a)". But we don't because, well, it's just not what we do, a bit of secretarial shorthand is fine really ;-)
Comment: Thanks a lot. Very informative.
Comment: I can certainly imagine that, according to the guidelines you quote, most mathematicians cannot immediately grasp this quote "_from a well-known text, verbatim_": "Let $ f:[0,\Omega) \to [0,\Omega) $ be s.t. $ f(\alpha) < \alpha $ for all $ \alpha \geq $ some $ \alpha_0 $. Then $ \exists \beta_0 \forall \beta \exists \alpha \geq \beta : f(x) \leq \beta_0 $.", but it is also a rather inelegant mixture of words and symbols and seems not quite right: should $x$ be $\alpha$? If one wishes to argue that some degree of symbolism is useful, perhaps this provides an upper limit (appropriately!).
Comment: The part of Rule 7 about papers on (formal) logic deserves clarification.  Such a paper, for the most part, will be written in "meta-language" (ordinary mathematical English).  It will talk about (and contain examples or schemas of) syntactic objects such as formulas using an "object language" which will be extremely precisely defined.
Comment: (continued comment) If the object language ever contains two symbols for a (say) disjunction, you can be sure that they have non-overlapping meanings, as well as each of them being distinct from the meta-language disjunction expressed as an "or", an "except if", or whatever other English phrase will best combine the intended disjunctive meaning with the desired flow of the argument throughout the paper.  An extra reason to keep the style distinction which is otherwise the same as in any other research area.
Comment: What is s.t. shorthand for?
Answer: I have to disagree with many of the answers here. There is a theme here that "humans are not computers, so it's easier for them to read words than symbols". But why stop at logical symbols? There are many symbols we do use in math in lieu of words. In earlier times, an equation like $x^3+3x=2$ would be written as "the thing cubed plus three times the thing equals two". Perhaps we should all go back to that?
Of course not. Mathematical symbols are here to make our lives easier, not harder - they do so by expressing ideas in a concise and easy-to-work-with form.
The question was also asked if we would like to read a proof that has no words and only symbols. But that is a strawman since nobody was suggesting this - instead, we wish to use a mixture of words and symbols according to what makes sense in the context, and that logical symbols will not be singled out for avoidance.
I can only speculate that the real reason behind this is that logic is, on one hand, ubiquitous in math, and on the other hand, formal mathematical logic was developed much later than algebra. So by the time mathematicians realized they actually can use symbols for logic, it has been widespread to use words for logical connectives, and symbols for the domain-specific subject matter.
And of course, traditions are hard to change - once everyone is used to one way, it's harder for them to parse statements written another way, and they find the traditional way prudent, so they continue the tradition in their own writing, enforce it in their journals, etc., and perpetuate the tradition. But it is important to understand that there is no real reason to eschew logical symbols - it's just a continuation of a tradition that resulted from a historical accident.
PS. $\forall$ and $\exists$ are rare in non-logic texts, but I do see $\implies$ and the like occasionally.
Comment: @ZevChonoles: Read the answer again - I'm not making that dichotomy, I've very clearly stated that the choice of words vs. symbols depends on context. I just object to "logical symbols are bad unconditionally, all other symbols are good". Also: Did you downvote? And if not, can the one who did explain his reasoning?
Comment: Perhaps you're making a false dichotomy, and the utility of symbols as compared with that of words actually depends on context?
Answer: Proofs in textbooks are supposed to be readable for humans.
Using logical symbols can make proofs significantly shorter but also significantly more confusing.
The proofs written in natural language with actual words and sentences are much faster to read.
Moreover, with words you can explain ideas, not just state truths.
Mathematics is not only about finding all the true statements.
Textbooks and shorter mathematical texts tell a story, and stories are hard to tell in symbols only.
A proof in words can also be difficult to understand if it never explains why things are done the way they are.
If you only use symbols, you don't even have the chance to explain.
A symbolic proof explained in words might work, but I find non-symbolic logic often easiest to follow in a proof.
Make a test if you will:
Take a proof that is approximately one page long.
Convert it to logical symbols so that no English word remains and give it to a friend to read.
Can they understand what is going on?
Some things are better written in symbols, some in words, and the position of the borderline is a matter of taste.
I believe most people would agree that writing mathematics with symbols only or without symbols of any kind is not a good idea.
Comment: To formalize when actually needed -- e.g., in logic, or for formal proofs.
Comment: @MKR, sometimes the logical symbols can be convenient shorthand notation, but they should be used sparingly. They can also be a good tool for getting a grasp of formal logic. Some teaching experience shows that students are *much* better at reading mathematics stated in natural language than in purely symbolic expressions. Mathematics can be done without the logical symbols.
Comment: @JoonasIlmavirta: That is very interesting: are you saying that you have seen studies that demonstrate this, or is this your own experience? If the former, do you have a link, and could you work this into your answer? And have you seen studies as to how far it is possible to develop proficiency in a more symbolic style, what limits there are, what constructs cause problems?
Comment: Take a proof that is approximately one page long. Convert it to English words so that no symbol remains and give it to a friend to read. Can they understand what is going on? Probably not, and my point is - symbols are used everywhere to express ideas more clearly. Even if true that logical symbols, specifically, are so difficult to understand that they should never ever be used, this is only because we are not used to working with them, not because of any objective reason.
Comment: @MeniRosenfeld, that is true but there is still a difference. A (good) proof in words *explains* instead of only stating. Explaining ideas and choosing words well can do wonders to understanding. A proof in words conveys more. The logical part could admittedly be done in symbols only, but it still benefits from explanation.
Comment: Words are great, no doubt about that. Symbols are also great. Wisely choosing whether to use a word or a symbol is great. But how come for pretty much everything else we have a choice of using a word or a symbol (e.g., you'll find in the literature both "$T$ is a linear map from $V$ to $W$" and "$T \in \mathrm{Hom}(V,W)$"), but we are never "allowed" to use logical symbols? That's what the question was asking, and I don't feel you've given a compelling explanation so far. Using a logical symbol for a statement in a proof certainly does not preclude explaining things with words.
Comment: Someone new to English may consider logical symbols easier to read than English, even if they are harder than her own native language.
Comment: So why there exist logical symbols?
Comment: @PJTraill, this is certainly something worth studying, but this is only based on my experience and that of some colleagues. In my experience some students even fail to see purely symbolic logical statements as meaningful statements (that mean something, that could be turned into words, that is possibly true or false etc.); instead, they become strings of alien symbols that one can formally manipulate. Formal manipulation without understanding is not a good path. I would be most interested in seeing studies about this.
Comment: @PJTraill, your question inspired me to ask this question at the SE site dedicated to mathematics education: http://matheducators.stackexchange.com/q/8422/2074
Comment: @MeniRosenfeld, sometimes words are better, sometimes symbols. Some things are best written in symbols (like manipulating functions using formulas for them) and a small amount of symbols is ok almost anywhere. Short symbolic logical expressions are readable, but longer ones are not (according to experience). Human readability is the key point in my answer, but of course some humans may disagree with me. I have yet to encounter anyone who tells me that they find logic easier to read in symbols than in words.
Answer: (This is a non-standard answer.)
Suppose we wish to prove a theorem of the form:
$$\varphi_0,\ldots,\varphi_{n-1} \vdash \psi$$
(See here for notation.)
There's basically two ways to go about this:

In the deductive paradigm, we start by writing down the premises (the $\varphi$'s), and then proceed to use inference methods to write down further formulae. We're done only if we can write $\psi$ on our page without breaking the rules.
In the algebraic paradigm, inference methods are instead used to manipulate the whole judgement $\varphi_0,\ldots,\varphi_{n-1} \vdash \psi.$ We're done if we can manipulate it so that it says something trivial, like $\alpha \vdash \alpha$, without breaking the rules.

For instance, to prove a trigonometric identity, a high school teacher will often begin by writing down the identity to be proved, say $\tan^2 \theta + 1 = \sec^2 \theta$, and then begin manipulating it. The proof is complete only once the identity to be proved has been transformed to the point where it says something that is already know to be true, like $\cos^2 \theta + \sin^2 \theta = 1$. This is the algebraic paradigm in action.
However, the deductive paradigm is currently dominant; pick up any serious mathematics text, and everything you see will be deductive. This is because the deductive paradigm allows us to write less. Therefore, if we're creating a "static" proof, like a blackboard proof, or a paragraph in a mathematics article (or book), we're essentially forced to use the deductive paradigm. Otherwise, our 1-paragraph proof might end up spanning 5 pages!
So to answer your question: if a book is using the deductive paradigm (and they all are), then there isn't much benefit in using logical notation like $\wedge,\rightarrow$ etc. since we're not going to be manipulating any formulae or judgements directly. This, in my opinion, is the true reason that you rarely see such symbols, although few (if any) authors would explain their choice in this way.
Its worth noting that, if we're interested in slideshow proofs that are presented on a computer, then suddenly the algebraic paradigm suddenly becomes a lot more user-friendly. In this case, the use of logical symbols like $\wedge,\rightarrow$ becomes indispensable, because only by using such symbols do we get rigorous and terse mathematical formulae that are easy to manipulate algebraically.
Comment: I *demand* to know why my answer was downvoted.
Comment: I have upvoted :)
Comment: Certainly my courses in logic used the deductive paradigm. We defined $\alpha \vdash \beta$ in terms of the existence of a proof containing axioms, the premis(es) $\alpha$, and inferences, and terminating in $\beta$. We didn't define it in terms of algebraic manipulations of the whole statement $\alpha \vdash \beta$. Whereas (still in logic courses this is) we'd algebraically manipulate $\alpha \Rightarrow \beta$, and switch between the two paradigms using the theorem that $\alpha \vdash \beta$ if and only if $\vdash \alpha \Rightarrow \beta$
Comment: Because you yourself state it is non-standard, perhaps? ;-)
Comment: @vonbrand, well I would claim that non-standard answers are more likely to be incorrect. But I would also claim that *if* they're correct, then they're doubly valuable.
Answer: As a programmer, I find the purpose of these symbols the same as for programming languages - to keep the structure of the code readable and maintainable. As you say, these symbols make the texts significantly shorter, and, in my opinion, I would find short readable proof more interesting than long readable English-words-only proof, where I would sooner or later get lost in the text.
Another problem is different interpretation. English "or" or other connectors sometimes don't exactly follow their mathematical definition, and that can be a problem, especially when translating to other languages. To a mathematician, a simple "∨" should always be clear and free of any different interpretations. I find this more useful than trying to specify which of the 20 meanings of "or" you mean. Symbols also make the text much more readable for non-English mathematicians.
However, I don't want to encourage you to change all connectors to symbols. Only do so when the statement itself has mathematical meaning, like being part of a proof describing properties of various mathematical objects or similar. When you can write the whole statement in mathematical symbols, do it.
Answer: Note: OPs question addresses one of many important aspects which an author of a mathematical text(book) has to consider and it should be seen in a wider context around the question:
What is the essence of writing a mathematical book?
I highly appreciate the following $50$ year old answer:

P. R. Halmos: The basic problem in writing mathematics is the same as in writing biology, writing a novel, or writing directions for assembling a harpsichord: the problem is to communicate an idea. To do so, and to do it clearly, you must have something to say, and you must have someone to say it to, you must organize what you want to say, and you must arrange it in the order you want it said in, you must write it, rewrite it, and re-rewrite it several times, and you must be willing to think hard about and work hard on mechanical details such as diction, notation, and punctuation. That' s all there is to it.

So, the main theme is to communicate an idea.
In order to do so we have besides other things take care about diction, notation, and punctuation. But, there may also be subtle (and less subtle) differences to whom this idea should be communicated.

P. R. Halmos: The second principle of good writing is to write for someone. When you decide to write something, ask yourself who it is that you want to reach. Are you writing a diary note to be read by yourself only, a letter to a friend, a research announcement for specialists, or a textbook for undergraduates? The problems are much the same in any case; what varies is the amount of motivation you need to put in, the extent of informality you may allow yourself, the fussiness of the detail that is necessary, and the number of times things have to be repeated. All writing is influenced by the audience, but, given the audience, an author's problem is to communicate with it as best he can.

So, the contents and the way to present contents will usually differ depending on the audience. We should keep in mind, that the amount of motiviation and the extent of informality are key ingredients of good mathematical books, although these aspects are typically beyond the symbolism we use in mathematics.
But, what about the usage of logical symbols?

P. R. Halmos: Here is a sample :
"Prove that any complex number is the product of a non-negative number and a number of modulus $1$."
...
One way to recast the sample sentence of the preceding paragraph is to establish the convention that all "individual variables" range over the set of complex numbers and then write something like
  $$\forall z\exists p\exists u [(p=|p|) \wedge (|u|=1) \wedge (z=pu)]. $$
I recommend against it. The symbolism of formal logic is indispensable in the discussion of the logic of mathematics, but used as a means of transmitting ideas from one mortal to another it becomes a cumbersome code. The author had to code his thoughts in it (I deny that anybody thinks in terms of $\exists, \forall, \wedge$, and the like), and the reader has to decode what the author wrote ; both steps are a waste of time and an obstruction to understanding. Symbolic presentation, in the sense of either the modern logician or the classical epsilontist, is something that machines can write and few but machines can read.

Note: This article written by one of the great provides many more guidelines. It has the somewhat cheeky  title How to write Mathematics and guarantees highly instructive amusement.
I like to finish my answer with his guideline $15:$ Resist symbols

P.R. Halmos: Everything said about words applies, mutatis mutandis, to the even smaller units of mathematical writing, the mathematical symbols. The best notation is no notation; whenever it is possible to avoid the use of a complicated alphabetic apparatus, avoid it. A good attitude to the preparation of written mathematical exposition is to pretend that it is spoken. Pretend that you are explaining the subject to a friend on a long walk in the woods, with no paper available; fall back on symbolism only when it is really necessary.
Comment: Every mathematician should read *How to write mathematics* ... and apply it to their own writing.
Comment: @J.-E.Pin: I agree in both aspects.
Answer: Since "no sign of logic symbols in mathematics texts" is exaggerated, we assume this phrase is replaced by "so little use of logic symbols in most mathematics texts".  The answer to the question is: (a) dogmatism, (b) various myths, (c) the state of development of symbolic logic.  Let's expand.
(a) Dogmatism: the failure to recognize that different people benefit from different means of expression. For one's own use, one may choose what suits best. When writing for others, looking for a balance that suits the audience helps understanding. This obviously depends on (c).  Prohibiting logic symbols (John Munkres) is dogmatic and stifles progress regarding (c).
(b) Myth 0: logic symbols are for logic texts only.  If logic texts fail to produce notations that are useful for the remainder of mathematics, their usefulness is limited.  Fortunately, the situation is not that bleak.
Myth 1: symbolism is for computers.  In fact, programming languages use just ASCII.  Symbolism was developed by and for humans long before computing machines existed.
(c) The state of development of symbolic logic.  In algebra, development of symbolism started with Diophantus nearly 2000 years ago and reached its current form about 300 years ago.  Using symbols as mere secretarial shorthand is called syncopation, and has no advantages for reasoning.  However, mature symbolism also has well-designed rules such that the shape of the expressions provides guidance in reasoning. In analysis/calculus, for instance, the shape of expressions often helps deciding the next step in the symbolic calculation of an integral.  Books such Gries and Schneider's (see Google) show how symbolic logic can provide similar advantages for routine reasoning in all branches of mathematics.  Of course, this is a development of recent decades and is constantly improving.  As already said, forcing (or even encouraging) students to avoid logic symbols is anathema to learning.
Answer: All my math related university textbooks made large use of logic symbols.
The worst ones were actually almost only logic symbols, which is not bad per se, but as someone noted symbols only state things, a little writing in a less formal language (note: implying math symbols are a language) can help understand.
Conclusion: best is to state with symbols and then help understand by explaining stuff with words.
@ThomasAndrews
There is a huge problem with this statement you made:
"The most formal proofs are all symbols. We choose to not use them because humans are not computers".
Math symbols are a LANGUAGE, specifically one where every "word" (symbol) has a very precise meaning (not like other human languages, where you can have a word have different meanings in the same context - e.g. inclusive and exclusive "or").
Some symbols can have different meanings in different contextes, but that is fine as the context makes the meaning well defined (it happens in other human languages too).
A symbol express a concept, sometimes a concept is expressed in more than one word in a language and a proper 1 (word) to 1 (word) mapping does not exist (= is read "is equal to" in english, but it is only 1 word in italian). Perfectly normal if you ever studied a foreign language, so nobody should have an issue with this.
The issue with symbols is not that they are not human readable, the issue is that they are a language most of us never became proficient (enough) in.
The very first thing you need to learn when studying new languages is to stop thinking in the old one: it is not a matter of being computers, it is a matter of not being bad at other languages (math or any other "human" languages).
Once again, the issue with the symbol language (maybe because I am not good enough myself) it does not help to visualize the  concept so that you can really understand what it says (and I mean more than understanding the causality chain if you want). Things that help visualization are e.g. examples (pun not intended). For visualization purposes, a "normal" language is more efficient, since you do not need "precise meaning" of each word, but rather what I would define as "richness" in expressiveness - something that, thanks to being less precise, can express a concept in a less verbose manner. In this way you get the idea "fast" and can clarify it with the help of the symbolic statement (so english first, and symbols later is my preferred approach).
Comment: *"The issue with symbols is not that they are not human readable, the issue is that they are a language most of us never became proficient (enough) in. The very first thing you need to learn when studying new languages is to stop thinking in the old one..."* +1! Highly agreed!
Comment: Indeed, I'm not sure what maths books people here have. I've checked a handful above my desk and I could not find *one* without logic symbols. There's always at least one chain of equivalences using `⇔` or other and several make systematic use of a tombstone (`∎` or other). It's hard to imagine an analysis book not making abundant use of `∃` and `∀` for  points.
Answer: It depends on the texts you are reading. There are still places where the logic symbols are used frequently; of course in mathematical logic (for an MSE example see here);
some professors still encourage the use of logic symbols to shorten a proof, see the discussion here.
Comment: I find these links unconvincing: reference 1 refers to mathematical logic, where the formal notation is part of the objects being treated, rather than arguments about them; reference 2 is a broken link; reference 3 does not contain much logical notation. Can you give an example of a proof written predominantly in logical notation?
Comment: I have removed the broken link; thank you @PJTraill for a constructive criticism.
Answer: I find that symbols are only really helpful to the extent that they don't actually change the sentence. Writing "Let epsilon be..." and "Let $\varepsilon$ be..." are identical, because the collection of strokes translates to the same sentence in my head, which is also how I would naturally describe the idea to myself and others. The second form may be slightly better because the different font and unusual letter of $\varepsilon$ serve to draw visual attention to the central mathematical actor at hand, rather than blending in with the supporting dialogue. The form of conciseness that still clearly matches the reader's internal monologue is undoubtedly helpful.
The issue, I think, is when you need to "translate" logical symbols, rather than merely read them. If I say "all roots of unity have magnitude one", that's a natural sentence. "All roots of unity $z$ have $|z|=1$" is more or less the same, since the order of concepts is still the order of the natural phrasing; translating the symbols into English as I go left to right still yields a natural sentence in my head. If I go all the way and say: $$\forall z\in \mathbb{C}\ \forall n\in\mathbb{N} \ \ z^n=1\implies zz^*=1$$ this looks much less like what I wrote originally, though it's still clearly identical. In visual order it reads more like "For all complex numbers $z$ and for all natural numbers $n$, $z$ raised to the nth power being equal to one implies that the complex number times its conjugate is one". That's clearly a very muddled way of putting things. Anyone's mental reading of this sentence packages the phrasing into another form as they scan it, so you may as well just write that in the first place. Turning the symbols into reasonable sentence involves mentally rearranging them, which is extra work for both the reader and writer. In this case it's not much work, since there aren't really nested quantifiers and the individual predicates are simple, but it also doesn't get you any extra clarity either. The only thing that can happen is that you lose a reader.
As an aside, note that the phrase "roots of unity" got turned into its defining expression. In general, mathematical English can bundle detailed definitions into simple phrases that help compartmentalize both the writing and the reader's thinking appropriately. Mathematical logic is a more minimalist language, so such terms often have to be explicitly expanded everywhere they appear if you refuse to write the English phrase. That would easily turn into a nightmare if you actually stuck to it for a whole text.
Comment: I've found that when I do expand definitions fully, I get a better understanding of both the definition and its applications. It does make my proofs a bit longer but it makes sure that I am not forgetting any details or overlooking gaps in logic.
Answer: Maybe a reason that people don't like to write or read logical statements as (∀ϵ>0)(∃δ>0)(∀x)(x>δ⇒1/x<ϵ) is that the time needed to pronounce it ('in their head' while reading possibly) is large compared to the length of the statement. Namely, one would get something like this:
"For all $\epsilon$ greater than $0$ there exists a $\delta$ greater than $0$ such that, for all $x$ greater than $\delta$, 1 over $x$ is smaller than $\epsilon$."
For a short symbol as $\exists$ or $\forall$ a one-syllable word would be more suitable than "there exists a" and "for all".


help with this doubts about analysis. (usual metric)

Question: help with this doubts about analysis. (usual metric) (Please answer)
Find the set $B$ such that its derived set $B´=A$ where $A=\{\frac{1}{n},n\in \mathbb{Z^+}\}$.
is there any theorem to say that any derived set is closed? If this is so, then the problem would not have a solution.
_
I told my teacher about something that he had read that the derived set should be closed, but he told me that he was confusing the derived set with  closure set, (Could you explain this to me?)
I was thinking of the possible proof that the derived set is closed.
Theorem: $A$ is closed if and only if $A^{\prime} \subseteq A $
if $(A^{\prime})^{\prime}\subseteq A^{\prime}$ then $A^\prime$ is closed, propuse it a my teacher but, he said that it is not always true..
how proof that $(A^{\prime})^{\prime}\subseteq A^{\prime}$ for every $A$
I've already asked this exercise here, but every time I have class, I'm confused. and im sorry my English is bad.
Comment: In metric spaces, every derived set is closed. There are topological spaces in which derived sets need not be closed, but that's something to worry about later. But [if you are curious now …](https://math.stackexchange.com/questions/954578/x-tau-needs-to-be-t-1-in-order-to-guarantee-that-a-is-closed)
Answer: A derived set is the set of all limit points of the set. If $S$ be any set then $S'=\{x: x \ \text{is a limit point of } S\}.$
Derived set is closed.
Let $S'$ be the derived set of $S$. Let $x$ is a limit point of $S'$. I will show that $x\in S'$ i.e. $x$ is a limit point of $S $. Since $x$ is a limit point of $S'\implies \forall r>0,\ B(x,r)\cap S'\setminus \{x\}\neq \emptyset.$

To show: $x\in S'$ i.e. $x$ is a limit point of $S$, i.e. for every $r>0,$ $B(x,r)\cap S\setminus\{x\}\neq \emptyset$

Let $y\in B(x,r)\cap S'\setminus \{x\}$. So $d(y,x)<r$. If $y\in S$ then we are done. If $y\notin S\implies y\in S'.$ Let $s=\min\{ d(x,y),r-d(x,y) \}$, so that $s>0$. Now since, $y\in S' $ implies for the obtained $s$ we will get $B(x,s)\cap S'\setminus \{x\}$. Now check that $z\in B(x,s)\cap S\setminus\{x\}.$  Hence, $x\in S'$.
Answer: First we consider the original problem. Let's look at the elements of $B=\{n^{-1}\,|\,n\in\mathbb Z\}$ and suppose $A'=B$ for some set $A$. Let $x=\frac1n\in B.$ Now we consider the fact that for any set $A,$ we get $A\subseteq A'$ and as $x$ is a limit point, say it is the limit of the sequence $a_k$ (with each $a_k$ in $A$). Wlog every element of $a_n$ must be at most a distance  $\frac12\left(\frac1n-\frac1{n+1}\right)$ from $x$ (we can do this by the definition of a limit and by ignoring the initial part of the sequence not within this distance). Now every element $a_n$ is in $A\subseteq A'=B$ and so we find that $a_n=x$ is constant and so $B\subseteq A$. Now observe that $0=\lim_{n\to\infty}\frac1n$ is a limit point of $A$ but is not in $B$. Therefore contradiction.
Now for the other parts of the question:

In a metric space every derived set is closed. A set is closed if and only if it contains all of it's limit points (that is $A$ is closed if $A=A'$). This is straightforward to prove if your definition of a closed set is that it is the complement of an open set. The next part is that for any set $A,$ we have $(A')'=A',$ that is, you need to prove that a limit of limit points is itself a limit point.
On closure. In general the closure of a set is the smallest closed superset of it (precisely it is the intersection of all closed supersets). In a metric space this is the same as the derived set. In some general topological spaces these are not always the same. In topological spaces limits are not anywhere near as nice as they are in metric spaces and so all definitions involving limits are less nice.


Möbius transformations lines and circles

Question: I am looking for a basic outline of a proof
I know that all MT's are of the form $\frac{ax+b}{cx+d}$
For $c=0$, I know that lines/circles are preserved because translations and dilations do not change a line/circle from being a line/circle
But I am not sure how to prove this for all cases
My exam is actually tomorrow, so it would be great if someone could help me today :)
Comment: I believe I understood the question and I spent a decent amount of time writing up an extensive answer.
Comment: Due to the fact that this question was migrated from meta, when it was closed, it was locked (I think this should be fixed). I have unlocked it in case people want to vote to reopen.
Comment: Do you know that MTs preserve cross-ratio?
Comment: What are you actually trying to prove? That lines and circles are mapped to lines and circles?
Answer: Note that
$$
\dfrac{a\color{#C00000}{z}+b}{c\color{#C00000}{z}+d}=\frac ac+\frac1c\frac{bc-ad}{c\color{#C00000}{z}+d}\tag{1}
$$
is a composition of translation, dilation, and inversion $\left(z\mapsto\frac1z\right)$. Geometrically, it is easy to see that translation and dilation preserve circles and lines.

Inversion Preserves Circles Not Passing Through The Origin
If $|z-c|=r$ where $|c|\ne r$, then $\color{#C00000}{r^2}=(z-c)(\bar{z}-\bar{c})=\color{#C00000}{|z|^2+|c|^2-2\mathrm{Re}(z\bar{c})}$ and
$$
\begin{align}
&\left[\frac1z-\frac1c\left(\frac{|c|^2}{|c|^2-r^2}\right)\right]
\left[\frac1{\bar{z}}-\frac1{\bar{c}}\left(\frac{|c|^2}{|c|^2-r^2}\right)\right]\\
&=\frac1{|z|^2}+\frac1{|c|^2}\left(\frac{|c|^2}{|c|^2-r^2}\right)^2-2\mathrm{Re}\left(\frac1{z\bar{c}}\right)\left(\frac{|c|^2}{|c|^2-r^2}\right)\\
&=\frac1{|z|^2}+\frac1{|c|^2}\left(\frac{|c|^2}{|c|^2-r^2}\right)^2-\frac{\color{#C00000}{2\mathrm{Re}(z\bar{c})}}{|z|^2|c|^2}\left(\frac{|c|^2}{|c|^2-r^2}\right)\\
&=\frac1{|z|^2}+|c|^2\left(\frac1{|c|^2-r^2}\right)^2-\frac{\color{#C00000}{|z|^2+|c|^2-r^2}}{|z|^2}\left(\frac1{|c|^2-r^2}\right)\\
&=\left(\frac{r}{|c|^2-r^2}\right)^2\tag{2}
\end{align}
$$
Therefore, $\frac1z$ lies on the circle with
$$
\text{center}=\frac{\bar{c}}{|c|^2-r^2}\qquad\text{and}\qquad\text{radius}=\frac{r}{|c|^2-r^2}\tag{3}
$$

Limiting To Circles Passing Through The Origin
If we fix $c$ and let $r\to|c|$, the radius tends to $\infty$ while containing the following point:
$$
\begin{align}
\frac{\bar{c}}{|c|^2-r^2}-\frac{\bar{c}}{|c|}\frac{r}{|c|^2-r^2}
&=\frac{\bar{c}}{|c|}\frac{|c|-r}{|c|^2-r^2}\\
&=\frac{\bar{c}}{|c|}\frac1{|c|+r}\\
&\to\frac1{2c}\tag{4}
\end{align}
$$
Thus, the circle tends to a line passing through $\dfrac1{2c}$ and perpendicular to $\bar{c}$.

Lines
Since the inverse of $z\mapsto\frac1z$ is itself, we can invert the previous section to yield that a line maps to a circle passing through the origin whose center is $\dfrac1{2p}$, where $p$ is the closest point on the line to the origin.

Circles Whose Center Is The Origin And Lines Passing Through The Origin
In the previous sections, we have ignored the problems that occur when $c=0$ and $p=0$. These cases are trivial geometrically.
Comment: The inverse map maps a circle passing through the origin to a line not passing through the origin. The inverse of the inverse map is itself, so the inverse map maps a line not passing through the origin to a circle passing through the origin. How you find $p$ depends on the form in which the line is given.
Comment: Do you can give me a reference book for you answer? thanks.
Comment: Did you have a question about this answer? This topic is known as [Inversive Geometry](https://en.wikipedia.org/wiki/Inversive_geometry).
Comment: Hello, could you kindly elaborate on the Lines section? I am a little confused. I can invert the previous section how? By taking $|c|=r$? Wouldn't $|z-c|=|c|$ just give me the equation of a circle passing through the origin? How do I get $p$, which is the closest point on the line to the origin?
Answer: To begin with, if $c\neq0,$ then put $f_1(z)=z+d/c,$ $f_2(z)=1/z,$ $f_3(z)=\frac{bc-ad}{c^2}z,$ and $f_4(z)=z+a/c.$ Then $$(f_4\circ f_3\circ f_2\circ f_1)(z)=\frac{az+b}{cz+d}.$$ So, it suffices to show that each of $f_1,f_2,f_3,f_4$ maps generalized circles to generalized circles. The fact that $ad-bc\ne0$ will be essential here. The only somewhat tricky part is showing that this is true for $f_2.$ The idea is to show that lines are mapped to generalized circles through the origin and vice versa, while circles that don't pass through the origin are again mapped to circles that don't pass through the origin.
The $c=0$ case is straightforward.


Proving the Nilradical of a Commutative Ring is closed under addition.

Question:
Let $R$ denote a commutative ring and $Nil(R)$ is the ideal consisting of all nilpotent elements in $R$. I am attempting to prove that $Nil(R)$ is closed under addition.

My work so far is summarized in the following. I know that $a,b\in{Nil(R)}$ implies there exists integers $k_{1},k_{2}$ such that $a^{k_{1}}=b^{k_{2}}=0_{R}$ where $0_{R}$ is the additive identity of $R$.  To assert that $a+b\in{Nil(R)}$ is to assert the existence of an integer $k_{3}$ satisfying $(a+b)^{k_{3}}=0_{R}$, for explicit rings such as the real or complex numbers this is very straight forward and one can merely use exponent properties but I am admittedly uncertain how to go about showing the Nilradical is additively closed for an arbitrary Ring where the elements may not be numbers but objects. Any hints or helpful observations showing how to prove this would be much appreciated.
Answer: Observe that you can use Newton's Binomial Theorem because of commutativity, so take
$$(a+b)^{k_1+k_2}=\sum_{i=0}^{k_1+k_2}\binom{k_1+k_2}i a^ib^{k_1+k_2-i}$$
Now check what happens with each summand above (by the way, can you see how is it possible to take an even lower exponent in the above?)


Maximum Modulus path

Question: Consider any entire, non constant function $f:\Bbb C\to \Bbb C$. Choose any $z\in\Bbb C$ and define $m(r)\in\overline D(z,r)$, for any $r\ge 0$, with this property:
$$|f(m(r))|\ge|f(w)|\;\forall w\in \overline D(z,r)$$
I'm aware that this definition may be ambiguous, since the maximum modulus needn't be met in a single point. I'm also aware that $|m(r)-z|=r$, by the maximum modulus principle.
Questions:

Is it always possible to choose $m(r)$ in such a way that $m$ is continuous, as a function from $[0,\infty)$ to $\Bbb C$?
If/when it is the case, has this $m$ any known properties? Is there some theory about this?

EDIT: I suspect that the answer to the first question is yes, since the modulus of an entire function can't have any local maxima. But I haven't anything rigorous.
Comment: Do you want to require $m(r) \in \overline{D}(z,r)$?
Comment: Yes, I do. Thank you!
Answer: It is not always possible.
WLOG we can take $z = 0$.
That leaves me free to use $z$ as the variable for complex functions.
Consider e.g.the function $f(z) = {z}^{16}+8\,{z}^{12}+432\,{z}^{8}-640\,{z}^{4}+256$.
 (Note: small typo in the function fixed)
The maximum modulus on the circle $|z|=r$ turns out to be on the
diagonals $x = \pm y$ for $r < 1.729363340$ approximately, then abruptly switches to the $x$ and $y$ axes.
EDIT: This function is symmetric under $z \to iz$ and its absolute value is unchanged by $z \to \overline{z}$, so it suffices to consider the sector $z = r e^{i\theta}$, $0 \le \theta \le \pi/4$.  A local extremum
of $|f(z)|$ on the arc $|z|=r$ must satisfy $\text{Im}(z f'(z)/f(z)) = 0$.
The graph looks like this:

The curvy parts actually give local minima (in fact they pass through zeros of $f$).  The axes and the diagonal $x=y$ have the local maxima.
If you plot $|f(r)|/|f(r e^{i\pi/4})|$ you get this:

For $r < 1.729363340$ (approximately) this ratio is less than $1$, so the maxima are on the diagonals.  For $r > 1.729363340$ the ratio is greater than $1$ and the maxima are on the axes.

Maximum Modulus path


Target specific tab with hyperlink from other page on same website

Question: I've got a page (documents.php) that contains four tabs, the 1st tab is set as the default and opens when one browses to documents.php
I need to be able to target tabs 2, 3 and 4 directly from hyperlinks on my index.php and a JavaScript menu that appears on all pages on the site.
Example:
Tab 3 on documents.php contains "archived documents".
On Index.php I want to place a link called "Click here to go to Archived documents" and when someone clicks on it it must take them to documents.php but automatically go to Tab 3 which is "archived documents" and not go to the default 1st Tab.
Here is the coding I am using to create the Tabs and would like to only modify this at most (and not re-invent the wheel by using jQuery or other technology and re-write the tabs on this and other pages):
HTML:

General Documents

Circulars

Newsletters

Archived Documents

Javascript:

Then there's some CSS in an external style sheet that formats the Tabs, their borders, background etc.
CSS Formatting:
.tabs ul{
    list-style:none;
    display:block;
    margin:0px;
    padding:0px;
    z-index:99;
    position:relative;
}
.tabs li {
    float:left;
    display:block;
    border-top:#E5E5E5 1px solid;
    border-left:#E5E5E5 1px solid;
    border-right:#E5E5E5 1px solid;
    border-top-left-radius:4px;
    border-top-right-radius:4px;
    position:relative;
    z-index:999;
    color: #444444;
    padding: 4px 8px 4px 8px;
    margin: 0px 6px 0px 0px;
    background: #e7e7e7 url(/assets/images/common/bg.png) repeat-x;
}

.tabs li:hover {

/*If you want hover effects on tabs put your css here*/

}
.tabs li a {
    display:block;
    color:#323234;
    outline:none;
}

.tabs li.current {
    border-bottom:#DD6E27 2px solid;
    outline:none;
}

.tab-content {
    display:none;
    clear:both;
    min-height: 120px;
    border-top-left-radius:0px;
    border-top-right-radius:4px;
    border-bottom-left-radius:4px;
    border-bottom-right-radius:4px;
    color:#444444;
      background:#fefefe url(/assets/images/common/bg.png) repeat-x;
    border: 1px solid #E5E5E5;
    overflow:hidden;
    padding:15px;
}

.tab-content:first-child {
    display: block;
}

Answer: Pass the # value url like http://example.com#tabs3 .Then use like this in your document ready.
$(document).ready(function(){
  var hash = window.location.hash;
  $('#'+ hash).addClass("current");

 $(".tabs li").click(function() {
  $(this).parent().parent().find(".tab-content").hide();
  var selected_tab = $(this).find("a").attr("href");
  $(selected_tab).fadeIn();
  $(this).parent().find("li").removeClass('current');
  $(this).addClass("current");
  return false;
  });

});

Comment: Hi Sibiraj PR, Thanks for the comment - to confirm: on my index.php I will link the "click here to go to archived docs" to http://documents.php#tab3 and then to make it work I need to add the above two lines to the existing javascript (or does the above 2 lines of javascript code need to replace existing code in my javascript ? Thanks, Reinhard.
Comment: Hi Sibiraj PR, Thanks again for the update. I have tried this, but the moment I add the two additional lines of code in the JavaScript namely `var hash = window.location.hash;` and `$('#'+ hash).addClass("current");` then the link format  **http://documents.php#tabs3** you suggested from my index.php still takes me to the default Tab 1 on documents.php, if I then click on Tab 2, 3 and 4 they do not work any longer (content stays on Tab1). There might be something else missing I guess. Thanks for any further help.
Comment: Good day Sibiraj PR, Sorry, but when I add your suggested changes then the content of the four tabs dissapear and does not show at all. I've made a jsfiddle with exactly the code I am using, would you mind please having a look here http://jsfiddle.net/rrensburg/fLDfy/3/ and see if you add your modified code (JavaScript and HTML) why is then "breaks" the TAB Content please? Thank a lot, Reinhard.
Comment: Hi there Sibiraj PR. I have now copied the new code from the jsfiddle above back into my live site, if one is now on "documents.php" you can click the four tabs and they work again (shows content of tabs fine when clicked) - but still if targeted from index.php it does not target any tabs and ends up at the default tab (tab1), also not "selecting" it (not underlining the tab itself). The URL I tried on index.php was both documents.php#tab3 and documents.php#ttab3 and in both instances one ends up on docuemnts.php at tab1's content. Thanks for assistance iwth the last piece of the puzzle :)
Comment: Hi Sibiraj PR, Just wanted to touch base and see if you've maybe had time to look at the latest comment please. Thanks a lot, Reinhard


Minute hand and hour hand interchange

Question: A person who left home between $4$ p.m. and $5$ p.m. returned between $5$ p.m.
and $6$ p.m. and found that the hands of his watch has exactly changed places. When
did he go out?
My attempt: The dial of a clock is divided into $60$ equal divisions. In one hour, the minute
hand makes one complete revolution, i.e., it moves through $60$ divisions and the hour
hand moves through $5$ divisions.
Suppose, when the man went out, the hour hand was $x$ divisions ahead of the point
labeled $12$ on the dial, where $20 < x < 25$ (as he went out between $4$ p.m. and $5$ p.m.).
Also suppose, when the man returned, the hour hand was $y$ divisions ahead of zero
mark and $25 < y < 30$.
Since the minute hand and hour hand exactly interchanged places during the interval
that the man was out, the minute hand was at y when he went out and at $x$ when he
returned.
Since the minute hand moves $12$ times as fast as the hour hand, we can say that the angle that the minute hand sweeps will be $12$ times that swept by the hour hand. But, I am not able to express this in terms of $x$ and $y$.
Any constructive hint is appreciated.
Comment: I think I would formulate the problem as $h_1=4+x$, $m_1=12x$, $h_2=5+y$, $m_2=12y$.
Comment: Can you please tell me what should be done after that.
Comment: $h_1$ is the position of the hour hand when he left home, and $m_2$ is the position of the minute hand when he came back. What do we know about these?
Comment: We know that as the time for which minute hand and hour hand move is same , the angle they traverse will be in ratio of their speeds...
Comment: I just meant that the position of the hour hand when he left is the same as the position of the minute hand when he came back.
Comment: Yes that is true
Comment: You could just solve the system: $4+x=12y$ and $5+y=12x$.
Answer: Between the time you go out and the time you return, the hour hand describes the minor arc between the original positions of the hands, and the minute hand describes the major arc. So the total angle of rotation of the two hands together is one full revolution.
At the same time, we know the minute hand must have turned 12 times more than the hour hand. So the gap between the two hands when you go out is $1/13$ of a revolution.
Now assume the time you leave is $4 + x$ hours, where $0 < x < 1$. At that time the position of the minute hand, in relation to the top of the dial, is $x$ revolutions. The position of the hour hand is $(4 + x)/12$ revolutions. So we have
$$x - (4 + x)/12 = 1/13.$$
The solution of this equation is $x = 64/143$.
So the time you leave is $26\frac{122}{143}$ minutes past four o'clock.
Answer: HINT:
Let's consider a time as a number between $0$ and $12$.
At time $x=$ the position of the hour hand, the position of the minute hand equals $12 \{x\}$, where $\{x\}$ is the fractional part of $x$. If $x = a_0. a_1 a_2 \ldots_{(12)}$ written in base $12$, then $12\{x\}= a_1.a_2 a_3 \ldots_{(12)}$.
Let $x$, $y$ be the departure, and arrival times. Then we have the system
$$
y= 12\{x\}\\
x = 12\{y\}
$$
and the conditions $4\le x\le 5$, $5\le y \le 6$. We conclude that in base $12$ we have
$$ x= 4.5454\ldots_{(12)} \\
y = 5.4545\ldots_{(12)}$$
Comment: This answer is amazing!
Comment: @Mike, amazing answers deserve upvoted.
Comment: @Joe When I try to vote, I get this message: "Join Mathematics Stack Exchange to start earning reputation and unlocking new privileges like voting and commenting." So it's up to the registered members to vote. I haven't "unlocked" that "privilege." For some reason, I'm being allowed to comment, but when the site creators realize their mistake, I'm sure I'll get in trouble for usurping this privilege.
Comment: @Mike, I don't know why you received that message. You are a user: user 963216. You should only need a reputation $\ge 15$ to upvote, and your reputation is currently 126.
Comment: @Joe It's all right. Joe, have a look at the map [here.](https://ygdp.yale.edu/phenomena/needs-washed) I'm from one of the light areas. Are you from one of the dark areas?
Comment: @Mike, One of the darkest.

Minute hand and hour hand interchange


Pulling Possible Select Values From A Field (Drupal 7)

Question: I have been looking if there is a function that return all the possible values for a field. I have a select field that is a Node Ref. So, function list_allowed_values() is out of the question. Because, list_allowed_values() is not compatible with Node Ref. Does anyone know a function to get all the possible Node Ref for a field?
Or do have to code my own function?
Thanks,
Nate
Comment: please post your answer separately
Answer: Ok, I did some digger on google. ychaugule made a nice function for this problem. Here is the post.
Also, reference to the information here:
"But the above code will only work for select list, not for node reference or other types of references. _field_allowed_values() function is a custom function which returns allowed values of reference type field. The function returns allowed values for node reference and term reference field and can be extended to get allowed values of other reference fields as well. - See more at: http://yogeshchaugule.com/blog/2013/get-allowed-values-select-list-field#sthash.xnf89Cgn.dpuf"
<code><?php
function _field_allowed_values($field_name) {
      // retrieve field configurations from DB.
  $allowed_values = array();
  $query = db_select('field_config');
  $query->condition('field_name',$field_name)
  ->fields('field_config',array('type', 'data'));

  $result = $query->execute()->fetchAssoc();

// Allowed references type
  $ref_type = array(
    'node_reference',
    'taxonomy_term_reference',
    );

  $field_config = unserialize($result['data']);
  if (in_array($result['type'], $ref_type)) {
    if ($result['type'] == 'node_reference') {
      $node_types = array_filter($field_config['settings']['referenceable_types']);

      $query = db_select('node');
      $query->condition('type', $node_types, 'in')
      ->condition('status', 1)
      ->fields('node', array('nid', 'title'));
      $allowed_values = $query->execute()->fetchAllKeyed(0, 1);
    }
    elseif ($result['type'] == 'taxonomy_term_reference') {
      $allowed_values = taxonomy_allowed_values($field_config);
    }
  }
  else {
    $allowed_values_raw = unserialize($result['data']);
    $allowed_values = (!empty($allowed_values_raw['settings']['allowed_values']) ? $allowed_values_raw['settings']['allowed_values'] : array());
  }
  return

  $allowed_values;
}

$field = _field_allowed_values('FIELD_NAME');
</code>
Comment: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes.
Comment: I updated the answer as requested.