path of light in disc where speed varies according to distance from boundary

Question: I'm struggling to answer one of the problems in the book Notes on Geometry by Elmer Rees. The question is as follows:

Consider a disc $D^2$ made of a material such that the speed of light
  at a point $p$ is proportional to the Euclidean distance of $p$ from
  the boundary. Prove that the light rays are the hyperbolic lines of
  the Poincaré model.

After trying to solve this using purely mathematical ideas (the book is a classic mathematical geometry graduate text), I found the only way to proceed was by using a Snell's Law (a law of physics and so not in the book). This makes me nervous that I'm perhaps missing the point!
However this does allow me to relate $r$ (the general distance of $p$ from the centre of the disc O, $k$ (the distance of $p$ from O when the light is travelling parallel to the boundary) and the general angle $\theta$ between Op and the direction of motion. The relationship I have derived is:
$$1-r = (1-k)\sin\theta$$
Which looks really promising since then $\theta=\pi/2$ when $r=k$ and $\theta=0$ or $\pi$ when $r=1$, as required for a circular path (i.e. hyperbolic lines of Poincaré model). However I still can't show the path of the light is actually circular.
So I have a few questions:

Am I using the right approach, or is there a better way that avoids Snell's Law?
If my approach is correct, is my equation relating $r$ and $\theta$ correct?
If this is right, how can I show the motion is along a circular path?

Many thanks in advance!
Comment: I think Snell's Law follows from either of the following: light takes the fastest path between two points; or the path is orthogonal to the family of level curves of the function that gives the minimum time to each point.
Answer: I think I have found the right solution: I thus deleted my previous answer to avoid any possible confusion.
To compute the light path, we can take advantage of Fermat's principle: among all paths, light chooses the one that takes the minimum amount of time. In polar coordinates $(r,\theta)$ the line elements is $ ds=\sqrt{dr^2+r^2d\theta^2}$ and the speed of light inside the unit disk is $v=\alpha(1-r)$, where $\alpha$ is some positive constant.
If $k$ is the minimum distance of the light ray from the center, the path must be symmetric with respect to the point nearest to the center and the time light takes to travel from that point to the boundary of the disc is:
$$
T=\int_{path}{ds\over v}=\int_k^1{\sqrt{1+r^2\dot\theta^2}\over\alpha(1-r)}dr,
$$
where I set $\dot\theta=d\theta/dr$.
Unfortunately, this integral diverges: this might be a signal that the model proposed in that book is not realistic, or that there was some misprint.
We can however circumvent this problem by integrating up to $1-\epsilon$ (with $\epsilon>0$), finding the solution and letting then $\epsilon\to0$. To find the function $\theta(r)$ giving minimum time we must solve Euler-Lagrange equation, which doesn't depend on $\epsilon$ and can be written as:
$$
{d\over dr}{\partial\over\partial \dot\theta}
\left({\sqrt{1+r^2\dot\theta^2}\over\alpha(1-r)}\right)=0,
$$
that is:
$$
{r^2\over 1-r}{\dot\theta\over\sqrt{1+r^2\dot\theta^2}}=a,
$$
where $a$ is a constant which depends on boundary conditions. We can safely choose that half of the path where $\dot\theta\ge0$ (which entails $a\ge0$), square the above equation and solve for $\dot\theta$:
$$
\dot\theta={a\over r}{1-r\over \sqrt{r^2-a^2(1-r)^2}}.
$$
We can find $a$ by noticing that at $r=k$ we have $dr/d\theta=1/\dot\theta=0$. That entails $k^2-a^2(1-k)^2=0$, that is: $a=k/(1-k)$. Substituting that into the above equation we finally get:
$$
\tag{*}
\dot\theta={k\over r}{1-r\over\sqrt{(r-k)(r+k-2kr)}}.
$$
It is convenient to choose the reference frame so that $\theta(k)=0$. We can then readily integrate $(*)$ to find $\theta(r)$:
$$
\tag{**}
\theta(r)=\int_k^r{k\over x}{1-x\over\sqrt{(x-k)(x+k-2kx)}}\,dx.
$$
The result can be written in closed form: I computed it with Mathematica but haven't been able to cast it yet in a real simple form.
What matters, however, is that this result is not "a hyperbolic line of the Poincaré model", i.e. a circle perpendicular to the boundary of the unit disk. For a point on such a circle on can easily derive that its polar coordinates obey:
$$
\theta_{circ}=\arccos\left({k\over r}\cdot{1+r^2\over1+k^2}\right),
$$
which gives:
$$
\dot\theta_{circ}={k\over r}{1-r^2\over\sqrt{(r^2-k^2)(1-k^2r^2)}}.
$$
This is different from equation $(*)$ found above and one can check that the integrand appearing in the expression for $T$ is indeed smaller using $(*)$ than using the expression above.
One can see below some plots of the light paths given by solution $(**)$, for different values of $k$.

EDIT.
As noted by David K in a comment below, taking $v=\alpha(1-r^2)$ and repeating the same steps as above, from the Euler-Lagrange equation one gets an expression for $\dot\theta(r)$ which is the same as that for $\dot\theta_{circ}$ above. In that case, then, one actually finds as solution an arc of a circle, perpendicular to the boundary of the unit disk. This is then probably the form which was intended in the book.
Comment: Two things: first, I couldn't find any error in your calculations; second, I now have an independent hand-wavy  intuitive reason to think the exercise's claim is wrong. I think the speed should have been given as $1-r^2$ rather than $1-r.$
Comment: Interesting. This graph of the light paths is at least qualitatively consistent with the physics (namely, the radius of curvature is always toward the slower part of the disk). I wonder how the exercise was actually intended to be done and whether there is a subtle error in it. The fact that it takes infinite time to reach the boundary may already have been recognized in that method; it merely claims that the paths are the hyperbolic lines, not that any path can be completed in finite time. So if the exercise is wrong it is probably some other error.
Comment: You are right: I repeated the same reasoning with $v=\alpha(1-r^2)$ and one gets for $\dot\theta$ the same expression given above for $\dot\theta_{circ}$. I'll add that to the answer.
Answer: Snell's law as it is initially taught in high school physics applies to a ray of light passing through a single boundary between two uniform transmission media.
There are only two speeds of light in this scenario, one on each side of the boundary.
Now consider two vectors normal (perpendicular) to the boundary between the media,
one pointing into the medium with the higher speed and one into the medium with the slower speed.
Notice that when the ray of light passes through a boundary between the media,
it is always deflected toward the normal vector pointing into the slow medium,
and away from the normal vector pointing into the fast medium.
If you have multiple transmission media layered so that the boundaries between media are a set of parallel planes, then you can easily extend Snell's law (by induction on the number of boundaries, if you like) to show that the sine of the incidence or refraction angle on one side of any boundary is proportional to the speed of light on that side of that boundary.
You can even extend this idea to a medium in which the speed of light varies continuously, provided that the places where the speed is $v_1$ all lie in a plane, the places where the speed is $v_2$ all lie in a plane, and those two planes are parallel for any speeds $v_1$ and $v_2.$
To apply the idea of the previous paragraph in two dimensions, you need parallel straight lines instead of parallel planes.

But that is not what you have. If the speed of light is $v_1$ at some point $p_1$ on the disk, the set of all points where the speed is $v_1$ forms a circle.
Multiple speeds gives you a set of concentric circles.
The interaction of light with an infinite number of concentric circles is hard to visualize, so let's discretize the system for the time being
by dividing the disk into concentric annular rings, each one having
the same small width $\Delta r$.
The figure below shows the two circular boundaries that separate three of those rings.

This actually shows just a small arc of each circle so that we can enlarge the figure enough to fit some labels between the two boundaries.
Suppose the radius of the inner circle in this figure (the arc through $A$) is $r$;
then the speed of light in the ring inside $A$ is $(1 - r + \Delta r)c,$
the speed of light between $A$ and $B$ is $(1 - r)c,$ and the speed of light outside $B$ is $(1 - r - \Delta r)c,$ where $c$ is the speed of light at the center of the disk.
Now you can use Snell's Law to compare $\theta_1$ with $\theta_2$ or to compare $\theta_3$ with $\theta_4.$
But notice that $\theta_3 \neq \theta_2$; in fact,
$\theta_3 = \theta_2 - \Delta \phi,$ where $\Delta \phi$ is the angle between the radii from the center of the disk to $A$ and to $B.$
Therefore you cannot rely on Snell's Law alone to compare $\theta_1$ with $\theta_4.$
If a ray of light travels along the path shown in red from the ring inside $A$
to the ring outside $B,$ the angles of incidence/refraction decrease not only because of Snell's Law, but also because the vectors normal to the boundaries that the ray crosses are not parallel.
The curvature of a differentiable curve is the rate at which the direction changes relative to the rate at which we travel along the curve.
Note that "direction" is not the angle the curve makes as it crosses a radial line of some system of polar coordinates; the change in direction should be independent of any particular system of coordinates, but you can measure it by observing the change in angle between the tangent line and a fixed line (e.g. the $x$ axis of some coordinate system).
The path in the figure is not differentiable so we cannot speak of its curvature, but it has a corresponding property: starting at $A$ the path goes in one direction toward $B$; it travels a distance $\Delta s,$ and then it changes direction by the amount $\theta_4 - \theta_3$ (a negative number, indicating a rightward turn).
If we reduce $\Delta r$ so that we have more rings,
as $\Delta r$ goes to zero we should approach the shape of the path of the light across the disk when the speed varies continuously,
and $(\Delta s)/\lvert \theta_4 - \theta_3\rvert$ should approach the radius of curvature at each point along the curve.
The goal would be to show that on a single path, that limit is constant over the entire path.
I don't have a solution yet, but I think what I wrote at least gives some hope that the exercise you were given is correct.
If instead we assumed (incorrectly) that
$$ \frac{\sin\theta_4}{\sin\theta_2} = \frac{1 - r - \Delta r}{1 - r} $$
(notice how this compares an angle at $A$ with an angle at $B$),
we would get results like the ones already found in another answer,
which are not lines of the hyperbolic geometry of a Poincaré disk,
thereby disproving the thing you were asked to prove.

Some additional, possibly random thoughts (since I still do not have a complete answer):
There is quite a lot written about the Poincaré disk on this site:
https://math.stackexchange.com/search?tab=relevance&q=poincare%20disk
I think you have assumed your disk $D^2$ is a unit disk.
If we take a point $P$ inside the unit disk and invert it through the unit circle, we get a point $P'$ on the same radial ray such that
$\lvert OP\rvert\lvert OP'\rvert = 1.$
Then every circle through $P$ and $P'$ is a line of the Poincaré model.
This set of circles is the elliptic pencil of a set of
Apollonian circles,
the unit circle belongs to the hyperbolic pencil of the same set of Apollonian circles.
Elsewhere in the various questions on the Poincaré disk I see that a circle around $P$ in the Poincaré model (a set of points all at an equal distance from $P$) is also a circle in the Euclidean metric, but with a center other than $P.$
Assuming your exercise is correctly put, I believe the
the set of circles around $P$ (according to the Poincaré model)
should be part of the hyperbolic pencil of the set of Apollonian circles described above,
and they should correspond to the wave fronts of a disturbance that starts at $P$ and propagates at the speed of light (as defined in your exercise) in all directions.
If you can show that the hyperbolic pencil around $P$ (or at least the part inside the unit disk) is the set of Poincaré circles about $P$,
then the elliptic pencil through $P$ (which is orthogonal to the hyperbolic pencil) would be the set of fastest paths from $P$ to any point, and therefore would be the paths of rays of light starting at $P.$
The speed of light defined by your exercise induces a distance metric defined by the time it takes light to travel from one point to another.
For an arbitrary point $P$ there is a Möbius transformation that preserves the unit circle but takes the origin to $P.$
If that transformation preserves the metric induced by the speed of light (does it?) then it takes the circles around the origin to the Poincaré circles about $P.$ Are those circles the hyperbolic pencil around $P$?

Update: It occurs to me that the Poincaré model of the unit disk implies that we can measure distances between points by integrating a distance metric along paths between the points.
By several hand-wavy leaps I come to the idea that the metric is chosen so that its geodesics are the hyperbolic lines of the Poincaré model,
and that if the speed of light is defined so that it is constant with respect to that metric, it will follow those geodesic paths.
If the speed of light is not constant with respect to that metric then in some cases it will be refracted and will depart from a hyperbolic line.
By a further leap (based on reading
Distance in the Poincare Disk model of hyperbolic geometry
and these course notes) I come to the idea that the metric should be proportional to $\frac1{1-r^2}$ where $r$ is the distance from the center,
and therefore the speed of light should be proportional to $1-r^2$
if we want light to follow the hyperbolic lines.
Since the exercise says the speed of light is proportional to $1 - r$ rather than $1-r^2,$ it seems credible that the light will not follow hyperbolic lines in all cases.
If the path of the light stays near the edge of the disk, however, its speed will be almost proportional to $1 - r^2$ (since the relative error of the missing factor $1 + r$ is small), producing a path that almost follows a hyperbolic line.
So if we plot several paths as in Aretino's answer, the ones near the edge of the disk should be almost circular (which they appear to be).
Taking this together with the calculations in Aretino's answer,
I'm inclined to agree that the exercise is incorrect.
Comment: You are right: the law to apply in this general case is mentioned here: https://physics.stackexchange.com/questions/43711/optics-derivation-of-vec-nablan-fracdn-hatuds (see also the answers).
Comment: @Aretino I'm glad we're on the same page. I just wish I knew how the problem ultimately can be solved. I hope I do eventually.
Comment: @David K, Aretino - thank you both for your help in trying to solve this problem! It follows a chapter on hyperbolic geometry in Rees' book, so surprising if we have to use formulas from physics that are not in the book. I wonder if there is a purely mathematical solution. But anyway, thank you both again, I really appreciate the help!
Comment: Thanks to the help provided, I have an idea of how to solve the problem. However, there is a critical detail that I still need help with, and if unlucky it may mean my idea won't work! As @DavidK pointed out, we can't apply Snell's Law where the lines of constant refractive index are not straight lines. So using a Möbius transformation (which preserves circles) from the disc to the upper half plane which flattens the concentric circles around O to horizontal lines in the upper half plane, we now can use Snell's Law. And here I can show circular paths! But is there such a Möbius transformation?
Comment: As I recall from my reading while gathering the "random thoughts", there is such a transformation. Of course you get higher speeds this way: the transit time between two horizontal lines has to be the same as the time between the concentric circles they were mapped from, which are generally much closer together. But you _can_ apply Snell's Law then without needing to do any weird jiggery-pokery to account for turning of the normal vector.
Comment: @DavidK I've just posted a new answer: please let me know your opinion.


Best implementation for a callback method to update multiple fields

Question: I am developing a mobile application (BlackBerry) with Java that makes use of the Google Translate API.  I have it set up so that a user can specify a language before logging in, and then once they log in, I have wrappers around every piece of text displayed to screen which will translate the text based on the language chosen.
My problem is that multiple things need to be translated on a given screen.  Therefore, I have to access the Google Translate API multiple times per screen.  To do this, I open an HTTPConnection on a new thread.  So I pass my Screen Interface to the Translator class, and then the Translator class will call my callback methods for that Screen (requestSucceeded() or requestFailed()).
Now, lets say I translate both the Screen title and the Screen body text.  That's two separate HTTPConnections.  So when the title is translated, I want my requestSucceeded() method to setText on my title LabelField.  When the body text is translated, I want my requestSucceeded() method to setText on my body LabelField.
What is the best way to have my requestSucceeded() method differentiate between different fields to be updated?  Currently, I am passing to the Translator two things (via a String[] array): The text to be translated and a "cookie" describing the item being translated.  I then use if statements in my requestSucceeded() callback method to update the appropriate field based on the "cookie" (which the Translator will send back along with the translated text).
I feel like there has to be a better way to do all of this. Does anyone have any suggestions?
Thanks!
Comment: Your approach sounds reasonable. Don't try and be too clever. Use the simplest solution that works.
Answer: First, I suggest you read up on the Command Pattern.  It is basically a design approach that can be used towards encapsulating each of your translation requests in an object that knows how to handle the results.  I then suggest having a collection that these commands can be inserted into, and that your translation thread can get its input from.  This way, you could (depending on how the API works) process a batch of translation requests on the same HTTP connection.


Improper integral to infinite sum and proper integral.

Question: I saw this in a proof (by sos440) from another question, but as I don't have 50 reputation I wasn't able to comment to ask about a particular step in the proof.
\begin{align}
\frac{\alpha}{2}PV\int_{-\infty}^{\infty}\frac{\log\cos^2x}{(\alpha\beta)^2-x^2}dx
&=\frac{\alpha}{2}\sum_{n = -\infty}^{\infty}PV\int_{\Large-\frac{\pi}{2}}^{\Large\frac{\pi}{2}}{\frac{\log \cos^2{x}}{(\alpha\beta)^2 - (x+n\pi)^2}}dx
\end{align}
I'm not sure how the sum is produced from the integral. If someone could point me in the right direction that would be great. Thanks!
From this question: How to find PV $\int_0^\infty \frac{\log \cos^2 \alpha x}{\beta^2-x^2} \, \mathrm dx=\alpha \pi$
Comment: I give you $15$ reputation then.
Answer: All there is to the above expansion is an exploitation of the fact that $\log{\cos^2{x}}$ is periodic with period $\pi$.  That means we can split the real line into an infinite set of intervals
$$\left [ -\frac{\pi}{2} + n \pi , \frac{\pi}{2} + n \pi \right ) $$
for all $n \in \mathbb{Z}$.  Then
$$\int_{-\infty}^{\infty} dx \frac{\log{\cos^2{x}}}{(\alpha \beta)^2-x^2} = \sum_{n=-\infty}^{\infty} \int_{-\pi/2}^{\pi/2} dx \frac{\log{\cos^2{\left (x+n \pi \right )}}}{(\alpha \beta)^2-\left (x+n \pi \right )^2}$$
Applying the periodicity of $\log{\cos^2{x}}$ produces the desired result.


Linux como Remover Linhas Duplicadas

Question: Qual comando do terminal Linux para remover linhas duplicadas
de um arquivo.txt?
Answer: a minha favorita seria:
cat arquivo.txt | sort | uniq >  novo-arquivo.txt

mas isto vai reordenar as linhas. Sem alterarar a ordem:
cat arquivo.txt | uniq >  novo-arquivo.txt

Comment: É essa mesmo que eu preciso
  --> cat arquivo.txt | sort | uniq >  novo-arquivo.txt

Obrigado

Linux como Remover Linhas Duplicadas


Trigger para sistema de imovel

Question: Pessoal estou desenvolvendo um sistema de imóvel e preciso que a cada cinco minutos o banco leia a informação do imóvel, processe e descriptografe a informação, envie uma confirmação de processamento e descarte a informação.
Estou pensando em fazer alguma trigger, mas não sei como liberar ela a cada 5 minutos, alguém pode me dar uma luz? (Desculpe a falta de tecnicidade, ainda estou começando)
Comment: Você pode usar `SQL Server Job`.
Answer: Como você está pensando em executar uma ação no banco de tempo em tempo, vejo que a melhor opção seja utilizar "events"
<code>Create event teste //bome
On schedule
Every 1 week //aqui é o intervalo
Do
NomeDaTrigger;
</code>
Com esse evento vc criar campo, deleta, executa procedures e triggers, de tempos e tempos pré definidos.

Trigger para sistema de imovel


iPhone PDF creation text inverting issue

Question: i am creating an iphone app for creating pdf. I am using the following code:
    [self drawRect:CGRectMake(0, 0, 100, 20 )text:@"last Name"xVal:10 yVal:-30 len:9];
    [self drawRect:CGRectMake(0, 0, 100, 20 )text:@"First Name"xVal:180 yVal:30 len:10];
    [self drawRect:CGRectMake(0, 0, 100, 20 )text:@"Middle Name"xVal:330 yVal:-30 len:11];

    + (void) drawRect:(CGRect)rect text:(NSString *)string xVal:(int)x yVal:(int)y len:(int)length{
        CGContextRef theContext = UIGraphicsGetCurrentContext();
        CGRect viewBounds = rect;
        CGContextTranslateCTM(theContext, 0, viewBounds.size.height);
        CGContextScaleCTM(theContext, 1, -1);
        // Draw the text using the MyDrawText function
        MyDrawText(theContext, viewBounds,string, x, y,length);
    }
void MyDrawText (CGContextRef myContext, CGRect contextRect, NSString *textToDraw, int x, int y, int len){
    float w, h;
    w = contextRect.size.width;
    h = contextRect.size.height;
    CGAffineTransform myTextTransform;

    CGContextSelectFont (myContext,"Helvetica-Bold", h, kCGEncodingMacRoman);

    CGContextSetCharacterSpacing (myContext, 3);
    CGContextSetTextDrawingMode (myContext, kCGTextFill);
    CGContextSetRGBFillColor(myContext, 0, 0, 0, 1);

    CGContextSetRGBStrokeColor (myContext, 0, 0, 0, 0);
    myTextTransform = CGAffineTransformMakeRotation(0.0);
    CGContextSetTextMatrix (myContext, myTextTransform);
    const char *str = [textToDraw UTF8String];
    CGContextShowTextAtPoint (myContext, x, y,str, len);
}

When I use this code I am getting the output like, first and third word is fine but the second one is coming like inverted (head down). Why so? Any idea?
Answer: The issue was with CGContextRef theContext = UIGraphicsGetCurrentContext();, when each time the function calls, the CGContext taking the last state, that's why getting the inverting output. So, i added,
CGContextRef theContext = UIGraphicsGetCurrentContext();
CGContextSaveGState(theContext);
//code to draw....
CGContextRestoreGState(theContext);

this solved the issue. Thanks :)
Answer: Core Graphics considers Bottom-Left corner as the origin for drawing.(In UIKit its Top-Left).
Here in your method call for second string you are providing yVal as 30 and other values as -30.
Thanks,
Comment: yVal just changing the position in Y axis. That is not controlling the inverting nature of the text. I changed that to 30, still no change but the position has been changed.


PubNub PHP SDK encountering class error when installing and configuring (Use case real-time map)

Question: Hello guys I am trying to get pubnub PHP SDK to work. Followed the guide on https://www.pubnub.com/docs/php/pubnub-php-sdk but I kept encountering the following issue:

Uncaught Error: Class 'Pubnub\Pubnub'. Can anyone assist me on it.

P.S.
I am intending to build a map that tracks assets in real-time but the resources that I was given for this project is extremely limited in scope and after reading pubnub documentation and guide it seems viable but since I am currently encountering unexpected error, I am wondering is it possible that there is alternative solution for asset tracking in real-time? My understanding is that

Asset has to output longitude and latitude
Data will goes through a stream processor
Stream Processor output and store the data
Front End Map will display the location

I am using MySQL, CPANEL (Non-root user), prototype is build using web technologies JS,HTML5 CSS3 and wrapped using cordova.
Comment: What is your question? "Uncaught Error" is (at least for me) not enough information
Comment: The "thing" that is emitting the location is likely a mobile device, right? So you would be using iOS or Android PubNub SDK to emit it. Or are you using device like RaspberryPi or Arduino and using PHP on it? The issue you are having though sounds like development environment configuration issue. [PubNub EON framework](https://github.com/pubnub/eon-map) is a great solution for you, too.
Answer: Hey thanks for all your feedback! I manage to find an alternate API (Pusher) that works (It has proper documentation too)


Passing value of a variable to another variable

Question: I'm trying to make a function that will output fibonacci numbers. This is the code:
#!/bin/bash
a1=0;
a2=1;
echo "Vnesi n"
read n
echo $a1
echo $a2
for ((i = 1; i <= $n; i++)) do
    a3=$(($a1+$a2))
    echo $a3
    $a1=$a2
    $a2=$a3
done

When I run it, it gets to to line 10 (echo $a3) and then outputs an error:
1
0
1
1
./fib.sh: line 11: 0=1: command not found
./fib.sh: line 12: 1=1: command not found

Basically what I'm trying to do is to pass value from a2 to a1 and value from a3 to a2. What am I doing wrong here?
Answer: Your first variable assignments are correct:
a1=0
a2=1

The second ones incorrectly prefix the left-hand side with a dollar sign:
$a1=$a2   # Should be a1=$a2
$a2=$a3   # Should be a2=$a3

Answer: replace
    $a1=$a2
    $a2=$a3

with
    a1=$a2
    a2=$a3

Answer: a1=$a2
not $a1
otherwise the left side is evaluated and the value (0 or whatever) is used


Drupal 7 "undefined function" fatal error; from FTP error

Question: One of the guys here deleted a module folder, in error, from drupal 7 site using FTP (I know but it was a mistake).
the Commerce module was deleted. Now can not access the site at all as we are getting a fatal error
Fatal error: Call to undefined function commerce_pricing_attributes_property_info_callback() in /var/www/sites/all/modules/contrib/entity/modules/field.info.inc on line 30
Anyone know how to correct it?
line 30 is
    $callback($info, $entity_type, $field, $instance, $field_type);
The function in question is below
function entity_metadata_field_entity_property_info() {
  $info = array();
  // Loop over all field instances and add them as property.
  foreach (field_info_fields() as $field_name => $field) {
    $field += array('bundles' => array());
    if ($field_type = field_info_field_types($field['type'])) {
      // Add in our default callback as the first one.
      $field_type += array('property_callbacks' => array());
      array_unshift($field_type['property_callbacks'], 'entity_metadata_field_default_property_callback');

      foreach ($field['bundles'] as $entity_type => $bundles) {
        foreach ($bundles as $bundle) {
          $instance = field_info_instance($entity_type, $field_name, $bundle);

          if ($instance && empty($instance['deleted'])) {
            foreach ($field_type['property_callbacks'] as $callback) {
              $callback($info, $entity_type, $field, $instance, $field_type);
            }
          }
        }
      }
    }
  }
  return $info;

Comment: Can't you just upload Commerce module back, using FTP, just like it was deleted?
Comment: Nope, put them back and nothing, rebooted server, flushed caches and still the screen only shows this error.
I can not access the admin screen from the web page, can only access everything now through the server terminal
Comment: New error from
commerce_pricing_attributes_property_info_callback() -
to -
commerce_price_property_info_callback()......

regardless of resolving this or not. Thanks guys, I am always amazed by the amount of time that people take, to help others that they don't even know
Comment: Apologies, already did that
Comment: And it did not help?
Comment: Disable commerce related modules from database.. Do take DB Backup before doing any changes... For more info https://drupal.org/node/157632
Comment: Thanks all:
I don't have the rep points to answer this officially yet.
I figured it out, based on the above assistance. There was one final blocker and that was the field.info.inc file itself. Once I did all the steps above and removed this file everything worked perfectly.
Answer: If you have a backup this is the time to use it.
If not you should:

Put your Site in maintenance mode from command line: https://drupal.org/node/590468 or by using Drush: drush vset maintenance_mode 1
Replace the deleted module with exactly the same version in exactly the same place.
Run update.php either from drush: drush updb or command line: https://drupal.org/upgrade/running-update-php
All should be fine.

Please report back if this works or if another solution is found
Comment: I've done the second option and no luck so will just go with a backup. I was trying to avoid it as the work done back to that point was good progress. Ce la vie
Comment: Doing it whilst in maintenance mode **does** make a difference to how the database reacts to changes to the modules so it is worth performing the steps in the order proposed in the answer. Good Luck


Validate APN push token

Question: I have a server side java application which send bulk push messages to apple server. Recently i'm getting multiple SSLSocketException: Connection closed by remote host OR SSLSocketException: Broken pipe expcetions.
I understand that in case i'm sending invalid tokens, apple forcefully closes the connection. I also have a feedback loop, but the failing tokens never appear on feedback loop since they are not even accepted by apple.
Is there any algorithm or method to know, why the device token is "invalid" ?
Answer: Why the device token is invalid?
Assuming you got all your device tokens from Apple and didn't create dummy tokens, the most likely cause for invalid tokens is a DB that has both production tokens and sandbox tokens.
How to find which tokens are invalid :
You should use the enhanced APN format, in which you specify the message ID. After each message you send to Apple, you should try reading from the socket after setting the timeout to a large enough value. Apple will send you error responses for the invalid tokens, which specify the message ID. This will let you find the invalid tokens and remove them from your DB.
Note that you should only use this method (reading responses after each message with a long timeout) in order to clean your DB. After your DB is clean from invalid tokens you don't want to use it, since it will make the notifications delivery very slow.

Validate APN push token


Shall we call this relation an "isomorphism"?

Question: This is a short question:
Assume the values: $\mathbf{True}$, $\mathbf{False}$
and the logic symbols: $\land,\lor$
Is $\mathbf{True}$, $\mathbf{False}$ under $\land,\lor \,$ isomorphic to $\boldsymbol{0},\boldsymbol{1}$ under $\cdot, +$?
Can you explain why or why not?
Comment: $\{0,1\}$ is not closed under "normal" addition: $1+1=2\notin\{0,1\}$
Comment: But $\{F,T\}$ under $\land$ and $\lor$ _is_ isomorphic to the integers modulo 2 under $xy$ and $x+y-xy$. (Since the integers modulo 2 form a field, this correspondence makes _linear algebra_ techniques applicable to some Boolean problems).
Comment: ... and perhaps with $x\cdot y=\min(x,y)$ and $x+y=\max(x,y)$.
Answer: In addition to drhab's comment, even if we use addition mod $2$, there is no isomorphism between the two systems.  $x+x=0$ for all $x=0,1$ in modulo $2$, so $x+x$ is a constant function.   But $x\wedge x=x$ and $x\vee x=x$ for $x=\mathbf{True},\mathbf{False}$, so both $x\wedge x$ and $x\vee x$ are not constant functions.
What you can do is show that $\{\mathbf{True},\mathbf{False}\}$ along with $\wedge$ is isomorphic to $\{0,1\}$ with $\cdot$.  I take the map $f:\{\mathbf{True},\mathbf{False}\}\to\{0,1\}$ with $f(\mathbf{True})=1$ and $f(\mathbf{False})=0$.  So, $$f(x\wedge y)=f(x)\cdot f(y).$$
Similarly,  you can show that $\{\mathbf{True},\mathbf{False}\}$ along with $\vee$ is isomorphic to $\{0,1\}$ with $\cdot$.  I take the map $g:\{\mathbf{True},\mathbf{False}\}\to\{0,1\}$ with $f(\mathbf{True})=0$ and $f(\mathbf{False})=1$.  So, $$g(x\vee y)=g(x)\cdot g(y).$$


Logic on Node Add Page for Specific Content Type

Question: I created a new content type in Drupal 7 and I want to make a template to customize the node add page for that content type. I want to be able to check if the user is authenticated with Facebook before they can use the node add form. If user is not authenticated then I will show them a paragraph explaining that they need to authenticate via facebook before they can use this form. I want them to always see the form link but they can only use the form if they are authenticated to facebook. I just don't know where to put it. Is it possible to make a template file specifically for that node add page so that I can include my logic?
Comment: ... and what do you want to do if the user is not FB-authenticated? More information is needed; you're just repeating what you've mentioned in the comment. Don't be shy and write an essay :)
Comment: Lol ok. How's that?
Comment: Better and I've updated my answer :)
Answer: Hiding options such as publishing and URL aliases is accomplished through the use of user roles and permissions. Visit /admin/people/permissions on your site to see what I mean. Enable the help module for more (contextual) assistance.
If you want to perform additional modification beyond basic access control, then, seeing as to how you are attempting to customise a form, you would need to implement a Drupal hook named hook_form_alter(). You will need to do this in a custom module - if you haven't done this before, it's a lot easier than it sounds :)
There should be plenty of information and guides on SE, d.o as well as Google on how to use this hook to modify forms. But the one reference that you definitely need to be aware of is the Form API reference.
Since you want links to the node-add form to be visible, rather than controlling access to the page based on the FB-authentication status, you can check the status during the form_alter and either add a message and disable the form, or as is usually done, set an error message or notice (using drupal_set_message()) and redirect them to a page where they can log in via FB; the message/notice will be displayed at the destination.
Comment: I see what you mean. However, I still need to add some additional logic to that add content type page. Is what I am trying to do possible?
Comment: I have updated my answer with more information. You can also attempt to modify the _markup_ of the entire page via a template file. But it is usually unnecessary as you can perform most of the nudges via the form_alter. You can also modify the structure of form elements if need be via .tpl files. But again, in most cases it is unnecessary.
Comment: The logic i want to edit is not specific to the form itself. I want to show a menu link for this content type but I want to check if user is authenticated to facebook when they click it. Which is why i want to add my logic to the node/add but only for that specific content page. Make sense? Making i'm going about this all wrong.
Comment: If that's the case, please improve your question with lots of detail stating exactly what it is that you are looking to do.
Comment: OK everything you're saying makes perfect sense and it sounds like the way to go. Just need some clarification on how to make a custom module work specifically for this. Do I just make a custom module and then call it manually? If so where would I call it manually from? Or should I just hardcode the form id in my custom module?
Comment: Read the docs. Create the module. Add your hook. Add your logic. Check. Debug. Rinse. Repeat. Drupal core and other modules have plenty of examples of hook_form_alter in action. The api.drupal.org links that I've provided are also invaluable. Search SE for any other questions that you might have - they have very likely already been answered :)
Comment: Sounds like fun. Technically i don't have to make a module right? I can just add my hook in template.php.
Comment: No, form_alter is a modular hook and will need to be placed in a module.
Comment: @coleopterist `hook_form_alter()` is invoked for themes too :) _The call order is as follows: all existing form alter functions are called for module A, then all for module B, etc., followed by all for any base theme(s), and finally for the theme itself._
Comment: I did not know that. Interesting and a little unsettling. Thanks :)


how do I improve my muscle memory for accordion

Question: I have been playing accordion for 8-9 months and one of the difficulties I am currently encountering is playing the bass/buttons as because I can't see them at all unless using a mirror (even then the help they provide is limited) it's not quite as easy as "oh I need to press that" I hear that the way to do something without looking is called muscle memory (correct me if im wrong) and hear that in order to build muscle memory I need to repeat something again and again with as little error as possible. is this correct? at the moment I'm learning despacito and it seems when everything goes well it sounds great (in my own opinon lol) however sometimes I will make the same mistake repeatedly and so as said I'm unsure as to what I have to do to be able to do these things.
thanks
Comment: Switch to banjo :-)    (hey, at least I didn't suggest the viola!)
Answer: Just a suggestion from a non-accordion-playing musician.  Yes, muscular memory sounds right to me.
I would suggest that you break it down - pick an easy key (say C maj?) and acquaint your bass playing fingers with the C, G and F buttons.  Play as many simple pieces as you can that use those three notes/chords.  Firstly just play the bass, then eventually add the other hand.  After a while, you will find that those bass notes are easy to find.  Once there, go to another key (say G maj?)  Do the same - G, D and C buttons (you already know C, so it's good positive reinforcement).  This way, you can slowly but surely build up your muscular memory of all the bass notes.
Answer: The key to muscle memory is to create an automatic pathway traveling down the nerves from the brain to the fingers. The movement must be done accurately over and over. To ensure accuracy, the movement must be broken up into small bits and done extremely slowly. After the movement can be done slowly "without thought", then the speed can be increased incrementally. Increase the tempo by tiny amounts at a time and only increase as the accuracy remains. As soon as a mistake is made, you know you're going too fast. Slow back down a little and do it again. Don't expect this to happen in one practice session. Build up over time.
As Jomiddnz suggested, start with one key. Get used to where the buttons are located in reference to each other. When playing slowly, take the time to really feel the distance. How much do your hands stretch? How far apart are your fingers? Do you move up to the right or down to the left (or whatever the movements are for accordion.) The idea is to be mindful about every motion.
I use this technique when practicing piano and even used it today when I was getting everything right except for stumbling in one or two measures. I slowed those measures right down and got to work.  I am an excellent sight-reader, and the reason is because of muscle memory. I am terrible at memorizing songs, but I have the piano keyboard memorized. I can play it blindfolded if I know the song because I can feel where every single key is in relation to my body. So when I am sight-reading a piece, my mind can translate those notes into hand and finger positions on the keyboard. It really works, but there's not shortcut.
Answer: In addition to what the other folks said, concentrating on one hand at a time helps. In particular, I found learning the left-hand-only songs in "Melodic Adventures in Bass-Land" to be useful.


Why conditional breakpoint doesn't work in some address in ollydbg?

Question: I use ollydbg with a 64bit program, in some address the conditional bp work like normal bp,for example
LEA RDX,[REL 7FF7_8127B320]
MOV RCX,QWORD PTR [RSI+3D0]
CALL 00007FF7_80805210

inside of 00007FF7_80805210
MOV QWORD PTR [RSP+8],RBX
PUSH RDI
SUB RSP,20
MOV RAX,RDX
MOV R11,R9
.
.
.

After I set the conditional bp with R9==5 at MOV R11,R9,then it break with R9 == 10 or other value just like a normal bp.
It happens in the whole address inside the call,but if i set conditional bp at outside like MOV RCX,QWORD PTR [RSI+3D0] with [RSI+3D0]==19DB0258BD0 or RSI==19D_730D6DB0 it work.
I try R9 == 00000005 or R9 == 00000000_00000020 or R9 == 12345678 and other address inside the call but all fails,the conditional bp all work like a normal bp break when execute to the line.
Comment: The tag says that ollydbg is a **32-bit** debugger, if that is relevant.
Comment: @WeatherVane  The tag says OllyDbg is a Ring3, "Win32" debugger,I think the "32" is just  a name.
Answer: Because OllyDbg64 is incomplete/frozen version. Try x64dbg.


Test to measure statistical significance of z-scores?

Question: I'm a med student with an interest in maths/stats.
I'm looking for a quantitative analysis of a teamwork model (how people change in a team environment). The data is in two sets, before and after. Both sets have a mean of 35 (they are supposed to have the same total and mean). However one has an SD of 8.15 and the other has an SD of 4.89. Just wondering if there was a way to see if these are statistically significant (using SDs or z-scores)?
Just a basic explanation would be great.
Thanks,
MG
Comment: Do you just want to test if the SD's differ? You could use Levene's test.
Answer: You have a couple of options for tests of your two samples to define the significance of the difference.  One of the major factors in these tests is the sample size.  (For example, conducting the tests with 7 samples yields very different results than data with the same means and standard deviations but with 200 samples.)
If the data is Gaussian, then the $F$-test for Equality of Two Variances would be the most sensitive, simple, and appropriate method.
Levene's Test tends to be the most robust as it calculates the distances from the median to each data point (instead of the mean).  The test is easy to implement, even in a basic spreadsheet environment, and is included in most statistical packages.
The Bartlett's Test has results which tend to lie between the $F$-test and Levene's test.  The Minitab website, which provides help beyond the scope of their proprietary software, notes some issue with Bartlett's Test and that the user may wish to exercise caution when using the same test from other software applications.
The $\chi^2$ test can also be used in most software and is similar to the $F$-test.
A Quantile-Quantile plot is a simple graphical method which would be easy to conduct in this instance where the number of observations remain the same for both groups.
A less common solution would be the bihistogram, which can be implemented in R.  The bihistogram plots the histograms of the two datasets "back to back" as it were and helps to graphically portray the difference and similarities between two samples.


How to print out information about Task Scheduler in powershell script?

Question: I am trying to print out information from the Task Scheduler from the local computer in a PowerShell script so other users can print out this information as well and not have to access the Task Scheduler. I need the script to print out

name,
status,
triggers,
next run time,
last run time,
last run result,
author,
created.

I can print out the information about the name, next run time, and last run time, but the rest won't print out when I run the script.
I have already got a little start on my script and got the fields down.
$schedule = new-object -com("Schedule.Service")
$schedule.connect()
$tasks = $schedule.getfolder("\").gettasks(0)

$tasks | select Name,Status,Triggers,NextRunTime,LastRunTime,LastRunResult,Author,Created | ft

foreach ($t in $tasks)
{
foreach ($a in $t.Actions)
{
$a.Path
}
}

Any help or suggestions would be appreciated.
Below is a screenshot with what i am looking for and what fields arent printing out data:
Comment: It's blank b/c it's not available in the object. If you run `$Tasks | Get-Member` what do you get?
Comment: Look at what `$tasks` contains. It doesn't have all that you want to output: `Name`, `Path`, `State`, `Enabled`, `LastRunTime`, `LastTaskResult`, `NumberOfMissedRuns`, `NextRunTime`, `Definition`, `Xml`.
Comment: I've updated my answer. Still doesn't have what you need?
Comment: i see now with the get-members command. i didnt realize i wasnt calling the specific fields i was looking for data in. I am new to powershell scripting and thought it was a pre-determined field that all i had to do was call on it. So with the get-member command, in order for me to grab author, created, and what ever else i need...i need to specific those in my $task variable?
Comment: by specifying "those" i mean for example : i need triggers so i do a:  `get.Triggers`  to pull the triggers for that task?
Comment: @BigHomie sorry forgot to tag you in my question above
Answer: Server 2012 R2 and Windows 8.1 have Task Scheduler cmdlets, and this module can be copied and used on a Windows 7 machine, presumably it probably needs the latest .NET and the Windows Management Framework as well. I'm able to disable and re-enable scheduled tasks, as well as display task information. Currently I don't know of built-in cmdlets that give me this information or allow this control.
To list all the scheduled tasks on the machine:
Get-ScheduledTask

You can get the following members from the task sequence object:
PS C:\BigHomie> $A = Get-ScheduledTask | select -First 1

PS C:\BigHomie> $A

       TypeName: Microsoft.Management.Infrastructure.CimInstance#Root/Microsoft/Windows/TaskScheduler/MSFT_ScheduledTask

Name                      MemberType     Definition
----                      ----------     ----------
Clone                     Method         System.Object ICloneable.Clone()
Dispose                   Method         void Dispose(), void IDisposable.Dispose()
Equals                    Method         bool Equals(System.Object obj)
GetCimSessionComputerName Method         string GetCimSessionComputerName()
GetCimSessionInstanceId   Method         guid GetCimSessionInstanceId()
GetHashCode               Method         int GetHashCode()
GetObjectData             Method         void GetObjectData(System.Runtime.Serialization.SerializationInfo info, Sys...
GetType                   Method         type GetType()
ToString                  Method         string ToString()
Actions                   Property       CimInstance#InstanceArray Actions {get;set;}
Author                    Property       string Author {get;set;}
Date                      Property       string Date {get;set;}
Description               Property       string Description {get;set;}
Documentation             Property       string Documentation {get;set;}
Principal                 Property       CimInstance#Instance Principal {get;set;}
PSComputerName            Property       string PSComputerName {get;}
SecurityDescriptor        Property       string SecurityDescriptor {get;set;}
Settings                  Property       CimInstance#Instance Settings {get;set;}
Source                    Property       string Source {get;set;}
TaskName                  Property       string TaskName {get;}
TaskPath                  Property       string TaskPath {get;}
Triggers                  Property       CimInstance#InstanceArray Triggers {get;set;}
URI                       Property       string URI {get;}
Version                   Property       string Version {get;set;}
State                     ScriptProperty System.Object State {get=[Microsoft.PowerShell.Cmdletization.GeneratedTypes...

PS C:\BigHomie> $A.Triggers

Enabled            : True
EndBoundary        :
ExecutionTimeLimit :
Id                 :
Repetition         : MSFT_TaskRepetitionPattern
StartBoundary      :
PSComputerName     :

Comment: Reason I'm asking is because I ran it on 2012R2 and it behaves totally different than what you've depicted in your post.
Comment: @slybloty yugh, what I'm using is actually a [separate module from pre W8 days](http://blog.powershell.no/2012/05/28/working-with-scheduled-tasks-from-windows-powershell/). Well, this is embarrassing, but that's what happens when you leave a project for several months and pick it up b/c someone asked a question on SF ;)  I'll be editing this answer, but the good news is the 2k12 module actually gives *more* information, and the `-Recurse` parameter isn't needed. OP Should ideally use that instead of reinventing the wheel.
Comment: thank you for your response but i am looking more into the service "Task Scheduler" and the current tasks that are in the "Task Scheduler" service. I'll add a screen shot shortly to show what i need help with!
Comment: Jimmyboy, how's that different than what I've given you?
Comment: Are you using certain modules which don't run as default?
Comment: @slybloty the task scheduler module isn't installed in Windows 7 by default. OP didn't indicate which OS he was using, so I was covering all bases.
Answer: This could be cleaned up a bit (i.e. mapping LastRunResult codes).  Let me know if you need help.  Triggers are a bit more difficult since I don't think the plain English representation you see when viewing a task in the GUI exists in the COM object.  I believe it would have to be built from the TriggerCollection stored in RegisteredTask.Definition.Triggers
$sched = New-Object -Com "Schedule.Service"
$sched.Connect()
$out = @()
$sched.GetFolder("\").GetTasks(0) | % {
    $xml = [xml]$_.xml
    $out += New-Object psobject -Property @{
        "Name" = $_.Name
        "Status" = switch($_.State) {0 {"Unknown"} 1 {"Disabled"} 2 {"Queued"} 3 {"Ready"} 4 {"Running"}}
        "NextRunTime" = $_.NextRunTime
        "LastRunTime" = $_.LastRunTime
        "LastRunResult" = $_.LastTaskResult
        "Author" = $xml.Task.Principals.Principal.UserId
        "Created" = $xml.Task.RegistrationInfo.Date
    }
}

$out | fl Name,Status,NextRuNTime,LastRunTime,LastRunResult,Author,Created

Comment: Sure, `invoke-command -ComputerName REMOTEPC -ScriptBlock { --Paste Entire Script Block Here-- }`
Comment: How do i use this to connect remotly to another server? (i am still on the same domain) use the invoke-command?
Comment: This did exactly what i needed, only with the exception that triggers doesnt get called but i can research that some more and find something about that. Thank you very much!
Comment: I added the following under "Status": "Actions" = ($xml.Task.Actions.Exec | % { "$($_.Command) $($_.Arguments)" }) -join "`n"
In the $out statement, how do I only show those Actions that are not blank?
Comment: You could do something like `foreach ($o in $out) {$o.PSObject.Properties | ?{$_.Value -ne $null} | ft Name,Value}` to only list properties that aren't null.  Output looks a bit funky, but it should work.


Should I buy a new guitar or fix my current one?

Question: I have a 2004 Epiphone G400 Gothic. I bought it used in 2011. The person I bought it from sold it to me with fretbuzz. I haven't minded it so I chose not to repair it. But now that I've been playing for several years, I would like to play without worrying about the buzz. The neck's action definitely needs to be reset, and I don't know how to properly do it. I also think some of the wiring inside needs to be addressed (I don't think it's grounded properly) since sometimes I get horrible feedback for what seems like no reason.
So the guitar is old and has seen better days no doubt. My question is is it worth it to get all these repairs done or just save for a new guitar? I love my G400, it's my first guitar. But I think it's time I got something new, or at least fixed what's wrong with my current instrument. I'm no music prodigy, just a hobbyist.
If I did buy a new guitar I'd probably get an ESP, either their Eclipse line or the LTC EC line.
Comment: You are considering scrapping it. Why not get another for your main guitar, and gently work on the old one. Chances are you won't wreck it, and you'll learn how to adjust on the job. Worst case scenario, you *may* wreck it, but that's what could happen anyway. Or - find another one in a state, and work on that, for the experience. Which, believe me, is invaluable.
Comment: There are so many videos online about how to do a proper set up.  It doesn't take much tools.  I would draw the line at doing fret work unless you don't care about damaging beyond repair.  It sounds like you want a new guitar anyway, though.  That's what I would do
Answer: Do a cost/benefit analysis starting with the actual costs. So the cost of a new G400 (or the ESP from a quick search) is about $400, right?
So now you need to find out how much it will cost to fix your current guitar. See if you can take it in for a quote. It might be a simple as doing a setup, but it could also be something like the frets or the nut. If you need a fret job on it that will definitely increase the cost a bit. If there are wiring issues, those are usually a relatively inexpensive repair, but that will add to the total cost. So try to get a quote.
Once you know what it will actually cost to fix it, it will be a lot easier to make the decision. For instance if it was more than $400 (it won't be though) that would make it pretty clear that it's not worth fixing. But you might find that they say it only needs a setup and the price might be worth it to you.
But that's pretty hard to determine until you know precisely what needs fixed.
Answer: I've owned Epiphones and played ESP (My wife has an inexpensive LTD).  I have been quite impressed by the ESP models I've played and I cannot say the same for Epiphone.  All guitars will need work, they are all an investment regardless of the initial cost.  They should be checked at least every year and adjusted.  After a few years of playing they will need fret dressing and eventually new frets.  this starts to get expensive but it is the reality of the situation.  My point(s) is (are) this, (1) don't think that if a guitar is not working it's time for a new one, (2) don't think a new one will be problem free.  A buzz can be fixed with an easy tweak!  And the fact is that many brand spanking new guitars buzz because they are not set up properly or have slipped at the store.  To me it seems like a 50/50 crap shoot.  Take you ax in to a store willing to do an evaluation and a free estimate.  If they say 75$ set up will correct the buzz do it.  They may say you need new frets (250$).  That may not be worth it but you NEW ESP WILL EVENTUALLY NEED IT, all guitars need it.  My question would be, how do these two models compare in reviews.
Comment: Fret dressing after a few years? My main guitar has done thousands of gigs in the last forty years, and hardly gets 'work' to re-set, apart from new strings. And none of my guitars - several from the '60s, need anything like you portray here.
Comment: Depends on how much you play, how hard you play (techniques wise), and how well you keep them in the winter.  All of my guitars have needed minor fret work over time, every 15 years or so.  And I have a light touch.  Price varies greatly from city to city.


Program will not run completely through code (no errors) Python 2.7.15

Question: I am very new to programming (as in a few weeks ago - sorry in advance for any ignorant coding!) but I am trying to run a function defined and user input code that finds the minimum of 3 integers. It will properly ask for the 3 integers, but then returns nothing after that even though I have the minimum function written.
My code:
Comment: Please add your code to the question rather than just a picture of your code
Comment: okay thanks! @G.Anderson
Comment: What do you expect the code to do? You don't do anything with the values you return. Did you perhaps want to print in your `get_minimum` function instead of returning?
Comment: yes thank you! @DavidG
Answer: You coded your program a bit awkwardly. However, that aside, you can get your method to output by using the print statement as opposed to the return.
Otherwise, when you return something from a function you need to assign what is returned to some variable(s).
For example:
def getter():
     return "Hello, world"

r = getter()

print r

Output:
Hello, world

So, return "Hello, world" will assign "Hello, world" to r. However, nothing will be shown in your terminal. In order for it to be shown in your terminal, you would have to use the print statement.
And just as a side note, it is best to paste your code in as opposed to attaching pictures.
Answer: You don't need globals since you are also returning the entered values. But you must save them on returning from get_integers. After that, you can simply use the min function to get the minimum value in a list:
def get_integers():
    N1 = int(input("Enter an integer: "))
    N2 = int(input("Enter an integer: "))
    N3 = int(input("Enter an integer: "))
    return N1,N2,N3

def get_minimum(*values):
    print ("The minimum is {:d}".format(min(list(values))))

a,b,c = get_integers()
get_minimum(a,b,c)


How to interpret the result of Forecast in R

Question: I am working on Daily time series forecasting starts from 1-1-2016 to 31-08-2018, For such long series I have used below approach to forecasting for next 30 days.
x<-msts(x1,start = c(2016,1,1),seasonal.periods = c(7,365))
fc<-auto.arima(x,D=1)
fit<-forecast(fc,h=30)
plot(fit)
summary(fit)

Where I am getting the desiered results as expected...

Forecast method: ARIMA(1,1,1)(0,1,0)[365]

Model Information:
Series: x
ARIMA(1,1,1)(0,1,0)[365]

Coefficients:
         ar1      ma1
      0.3771  -0.9760
s.e.  0.0411   0.0123

sigma^2 estimated as 164061:  log likelihood=-4516.73
AIC=9039.46   AICc=9039.5   BIC=9052.69

Error measures:
                   ME     RMSE      MAE       MPE     MAPE      MASE        ACF1
Training set 9.542325 319.4919 176.8696 -19.14952 39.12223 0.5240848 -0.01867405

Forecasts:
          Point Forecast      Lo 80     Hi 80       Lo 95    Hi 95
2018.6685       774.3854  255.29962 1293.4711  -19.487785 1568.259
2018.6712       957.2433  397.95021 1516.5364  101.878323 1812.608
2018.6740       950.2112  383.56386 1516.8586   83.598862 1816.824
2018.6767       871.5679  302.99223 1440.1435    2.006462 1741.129
2018.6795       765.9185  196.54592 1335.2911 -104.861727 1636.699
2018.6822       887.0847  317.21373 1456.9556   15.542277 1758.627
2018.6849      1395.4100  825.13533 1965.6847  523.250138 2267.570
2018.6877       966.2870  395.64171 1536.9323   93.560353 1839.014
2018.6904       880.2844  309.28081 1451.2879    7.009791 1753.559
2018.6932       794.0757  222.71863 1365.4329  -79.739560 1667.891
2018.6959       707.7894  136.08066 1279.4982 -166.563686 1582.143
2018.6986      1153.8072  581.74759 1725.8668  278.917525 2028.697
2018.7014      1021.8139  449.40391 1594.2238  146.388382 1897.239
2018.7041      1828.8164 1256.05638 2401.5764  952.855537 2704.777
2018.7068       884.8173  311.70752 1457.9272    8.321500 1761.313
2018.7096       888.1510  314.69163 1461.6105   11.120549 1765.182
2018.7123       891.4845  317.67573 1465.2933   13.919708 1769.049
2018.7151       894.8179  320.65996 1468.9758   16.719111 1772.917
2018.7178       694.8179  120.31104 1269.3248 -183.814526 1573.450
2018.7205       779.8179  204.96232 1354.6735  -99.347850 1658.984
2018.7233       816.8179  241.61381 1392.0220  -62.880856 1696.517
2018.7260       716.8179  141.26551 1292.3703 -163.413540 1597.049
2018.7288       812.8179  236.91741 1388.7184  -67.945903 1693.582
2018.7315       908.8179  332.56953 1485.0663   27.522055 1790.114
2018.7342      1004.8179  428.22186 1581.4140  122.990335 1886.646
2018.7370       792.8179  215.87439 1369.7615  -89.541065 1675.177
2018.7397       605.8179   28.52714 1183.1087 -277.072146 1488.708
2018.7425       842.8179  265.18009 1420.4558  -40.602907 1726.239
2018.7452      1004.8179  426.83325 1582.8026  120.866651 1888.769
2018.7479       303.8179 -274.51338  882.1492 -580.663474 1188.299

My Questions are as below
1.How to interpret 2018.6685 etc in forecast results
2.How to reduce errors(MAPE).
Answer: You're defining two seasonalities in your series:
x<-msts(x1,start = c(2016,1,1),seasonal.periods = c(7,365))

But you are using auto.arima, which can handle at most one seasonality.
Try TBATS, BSTS or FB Prophet, the models used in those packages can handle multiple seasonalities.
Answer: 1) .6685 * 365 = 244; .6712 * 365 = 245. These are your days of the year, but expressed as fractions. So it's .6685 through the 2018 year.
2) There's not an easy, simple answer to this. You're already using auto.arima, so you're less likely to reduce errors by tuning arima. You could try the ets function from the forecast package and that will pick an optimized exponential smoothing model. There are many other time series methods as well.
Are there other regressors you could add (like events or holidays or level shifts)? Can you do more aggregation of your data (either in some kind of categorical hierarchy or by time)? These are all things that could help you capture more signal and lead to lower forecast error.
Answer: To reduce your large error variance you might want to look at Understand order of time series as it details how to combine arima and latent deterministic predictor series. Simple method of forecasting number of guests given current and historical data might also help.


O ícone da notificação modifica com app fechado

Question: Quando o App esta aberto o ícone aparece normal, agora quando o app não esta aberto aparece apenas um circulo no lugar do ícone. Tenho um sistema em Swing que quando o usuário faz uma certa ação é enviado uma notificação.
Código que fica no sistema em Swing
<code>    public void enviaNotificacaoDenunciaFcm(String tkn, String corpo) {
    try {

        URL url = new URL("https://fcm.googleapis.com/fcm/send");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Authorization", "key=chave do fcm");
        conn.setRequestProperty("Content-Type", "application/json");

        JSONObject json = new JSONObject();

        json.put("to", tkn);

        JSONObject info = new JSONObject();
        info.put("title", "Secretaria do Meio Ambiente");   // Notification title
        info.put("body", corpo); // Notification body
        info.put("color", "blue");

        json.put("notification", info);

        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(json.toString());
        wr.flush();
        conn.getInputStream();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        JOptionPane.showMessageDialog(this, "Erro ao enviar notificação!\n" + e, "Erro", JOptionPane.ERROR_MESSAGE);
        atualizaTabela();
        desabilitaBotoes();
        desabilitaCampos();
        limpaCampos();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        JOptionPane.showMessageDialog(this, "Erro ao enviar notificação!\n" + e, "Erro", JOptionPane.ERROR_MESSAGE);
    }

    // return null;
}
</code>
Comment: não sei o motivo do negativo já que expliquei tudo direitinho.
Answer: basta colocar o codigo abaixo no AndroidManifest.xml, conforme o:  https://vike.io/pt/408790/
<code> <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@drawable/ic_stat_name" />
        <meta-data android:name="com.google.firebase.messaging.default_notification_color"
            android:resource="@color/blue_dark" />
</code>


How to make content inside DataGridCell scrollable?

Question: I tried to make cell scrollable with a fixed maximum height, it doesn't really work and the content inside pretty much is not visible. Here's the code on the main page:
<DataGridTemplateColumn Header="Reported" Width="*" ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.CanContentScroll="True">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <ItemsControl ItemsSource="{Binding Reported}" ScrollViewer.CanContentScroll="True"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

And here's the code from ResourceDictionary:

</Style>

</Style>

As you can see I've tried  adding this feature in every possible way and it didn't work. Everything else works fine.
Answer: The ItemsControl doesn't have scrolling capabilities. You need to add them yourself:
<DataGridTemplateColumn Header="Reported" Width="*">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <ScrollViewer VerticalScrollBarVisibility="Auto"
                          HorizontalScrollBarVisibility="Auto"
                          CanContentScroll="True">
                <ItemsControl ItemsSource="{Binding Reported}" />
            </ScrollViewer>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

Though you should be aware the ItemsControl is not optimized out of the box as it doesn't have virtualization by default like the ListBox and will lag if you try to display lots of items.
Comment: You're welcome. The whole list can't be selected because the ListBox have its own selector. I'm pretty sure you could deactivate it somehow (never had that particular case, so I'm just guessing at that point). Otherwise, you can stay with the ItemsControl and implement virtualisation. You can check how to do it here : https://stackoverflow.com/questions/2783845/virtualizing-an-itemscontrol
Comment: Thanks for the advice, as well as the answer. Is there any disadvantage with using ListBox, I can see the whole list can't be selected, will that cause any problems in the future?


stack image using index into loops in R

Question: I have 273 images in a folder and I would like to paste it into a matrix. I loaded the images using list.files and I created 2 loops for row and column of the matrix.
folder <- "C:/Users/Desktop/image"
jpeg <- list.files(folder, full.names=TRUE)

#Size matrix
Number_R <- 13
Number_C <- 21
#create empty matrix
matrix <- matrix(, nrow = Number_R, ncol = Number_C)
total <- Number_R * Number_C

#i for row
#j for col
ind <- 0

for (i in (1:(Number_R))) {
  for (j in (1:(Number_C))) {
    ind <- ind+1
    l <-stack(ind)
    img_array <- as.array(l)
    }
  }

The problem is how to use the function stack in this case (if it is the right way)? For each iteration I would like to stack the image, l, that I loaded thanks to the function  "list.files". Finally I will have row 1/column 1 image 1; line 1/col 2 image 2; line 2/col 1 image 24; etc
I created an index name "ind" but I cannot use it with stack function.
Answer: Perhaps you can do
library(raster)
f <- list.files()
s <- stack(f)
m <- as.matrix(s)

stack image using index into loops in R


Simple REST service using Spring MVC, problems with configuration

Question: I'm trying to add a simple REST service to a default Spring MVC Template project created using the SpringSource Tool Suite (STS) and Eclipse. The REST service I want to expose is basically a utility that's not tied to any model. The input is a string and I want it to return the string reversed. The code part is easy, but the configuration is not. Below are my relevant files.
I don't really understand why this doesn't work, but when I type in the URL http://localhost:8080/projectName/restfultest/stringreverser/testString I get the error message
    No mapping found for HTTP request with URI [/projectName/restfultest/stringreverser/] in DispatcherServlet with name 'restfulServlet'
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/root-context.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>restfulServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/restfulServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>restfulServlet</servlet-name>
        <url-pattern>/restfultest/*</url-pattern>
    </servlet-mapping>

</web-app>

servlet-context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <annotation-driven />

    <context:component-scan base-package="com.sample.pkg" />

</beans:beans>

RestfulService.java
package com.sample.pkg;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping(value = "/stringreverser")
public class RestfulService {

    @RequestMapping(value="/{id}", method=RequestMethod.GET)
    public String reverseId(@PathVariable("id") String id) {
        String reversed = "";
        for (int i = id.length() - 1; i <= 0; --i) {
            reversed += id.charAt(i);
        }

        return reversed;
    }
}

Thanks in advance for any help!
-Joe
Comment: Did you try `http://localhost:8080/restfultest/stringreverser/testString` ?
Comment: just try without the "projectName" part in your URL.
Comment: Tried that, but the server gave me a 404 error without any details from the console. It's the same error I would get if I tried http://localhost:8080/foo/bar
Answer: First off, you reversal function is incorrect
for (int i = id.length() - 1; i <= 0; --i) {...}

It will never go in, as you expect i to be less than or equal to 0 on start.
Second of all, here's some good news

Here is a working controller
@Controller
@RequestMapping( value="/stringreverser" )
public class HomeController {

    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

    @RequestMapping( value="/{id}", method=RequestMethod.GET )
    public String reverseId( @PathVariable String id, Model model ) {

        StringBuilder reversed = new StringBuilder();
        for ( int i = id.length() - 1; i >= 0; i-- ) {
            reversed.append( id.charAt( i ) );
        }

        logger.debug( "\n\t [" + id + "] reversed ==> " + reversed.toString() );

        model.addAttribute( "originalId", id );
        model.addAttribute( "reversedId", reversed.toString() );

        return "home";
    }
}

Controller name is HomeController, since I used a templated Spring MVC app that you can create in two clicks with Spring Tool Suite:

File => New => Spring Template Project
Choose "Spring MVC Project", enter project name, top level package ( e.g. org.guru.xyz ), click Next
You have yourself a brand new "Spring MVC" project
In order to deploy it, right click on your project ( on the left hand side ), go to "Run As" => "Run On Server"
This will deploy it to Tomcat and open a "localhost:8080/somemvc/" where you would see "Hello world!"

But the way, it'll already have a, missing from your code above, view resolver and a home.jsp, that you see rendered on the picture above.
Here is the home.jsp

   <title>Mean ID Reverser</title>

 Mean ID Reverser

  I just reversed your ID "${originalId}" => "${reversedId}"

And
<url-pattern>/restfultest/*</url-pattern> in web.xml works just fine.

JSON Woodoo
In order to return it as JJ (Just JSON), there are just two things you need to do:
Add a Jackson Mapper dependency
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.2</version>
</dependency>

Change a return type to @ResponseBody Object
@RequestMapping( value="/{id}", method=RequestMethod.GET )
public @ResponseBody Object reverseIdJson(@PathVariable String id) {
    return new ReverserResult( id );
}

I included an object ReversalResult instead of a simple String in order to demonstrate a transparent Jackson Mapper magic, and to see that it is truly a JSON response that comes back:

where a ReversalResult has two fields, a reverseString static method, and it reverses a String in a constructor:
    private String original;
    private String reversed;

    public ReverserResult( String reverseMe ) {
        this.original = reverseMe;
        this.reversed = reverseString( reverseMe );
    }

This of course would just be a stand alone function, but again, I wanted to show the Object with 1+ fields to come back as JSON.
Comment: I saw the view resolver section that was in there for the sample application, but I wasn't sure if it was necessary in my situation. I don't have a stringreverser.jsp page inside of the WEB-INF directory, but I want the reverseId() function to be called on whatever string is provided by the URL. Do I need a viewResolver anyway? Also, I tried adding the mvc: part to annotation-driven but eclipse complained about 'The prefix "mvc" for element "mvc:annotation-driven" is not bound." It didn't complain without the mvc part so I assumed it was able to find that configuration option.
Comment: in order to get `` to work, you have to add XML schema (`xmlns:mvc="http://www.springframework.org/schema/mvc"` and friends), see this [example](http://stackoverflow.com/questions/6001593/mvcannotation-driven-is-not-bound) on the simple config. Yes, I would leave a view resolver there.
Comment: I do not think that the missing namespace is an issue, as he has defined mvc namespace to be his default namespace.
Comment: @nicholas.hauschild, good catch, I see that. Then I have another little thing to try ( besides the view resolver => keep it there ) => Remove the `*` in `/restfultest/*`.
Comment: Okay, so I left the viewResolver in there. Taking the * out of the url-pattern seems to have the effect of only matching projectName/restfultest/, giving me the same warning output as before (No mapping found for HTTP request ...). Anything else gives me a 404 page with no warning printed out. It would seem to me like the regex is working fine with the *, but something is missing from the configuration.
Comment: remove the class level `@RequestMapping`, I edited the answer.
Comment: @tolitius you are a gentleman and a scholar. I believe my biggest issue was that my reverseId method wasn't taking in a model as the second argument. If I modified the resolver could I have this return a JSON formatted string instead of home.jsp?
Answer: @tolitius is right, but there's another issue which is that you're not telling it which view to use. If a @RequestMapping method returns a String, Spring expects that String to be the name of a view. You can annotate the method with @ResponseBody if you want the return value to be the response but you're then leaving it for Spring to decide what to do with it.
Comment: Makes sense. I'm still having the same mapping issues so afaik it's not even attempting to call my service.


How to get data from a JSON file using Azure functions and C# which is in Blob storage and Storing JSON data as columns in Azure table storage

Question: How to get data from a JSON file (filename.json) using Azure functions and C# which is in Blob storage and Storing JSON data as columns in Azure table storage. My function app will be triggered when a json file has been placed in the path. So basically, there will be a JSON file with multiple records (tuple) in Blob Storage of ADLS Gen2 and I have to upload that to Table storage.
I have barely ever written code in C# before, any help with an elaborate description and explanation would be greatly appreciated.
I am also fairly new to Azure, so if anyone has a better suggestion on how to achieve what I am trying to do (that is maybe using a different trigger or different binders), I would gladly appreciate it.
Answer: You need to create a function with Azure Blob storage trigger and output binding of azure table storage
uploading a file in your blob storage will trigger your function and you can then do any work needed to parse your json and push it to the table.
you can have a look at the links, get your blob trigger working and firing your function, then add to your function to include the output binding.
if you get stuck you can always update your question with the code thats giving you an issue.
one more link for getting started with c# functions in azure.


Load GLTF file that is not located in Public folder

Question: I found a problem that I cannot load GLTF files into a scene if I cannot place them in the Public folder in my React application. For example, I have MyPVPanel.gltf, and I want to load it in react app or in my npm library, or I always to be with my react components.

My questions are:

Is this possible to import assets from a specific folder if you develop an npm package. Do packages have something like /public or /assets?
Can I configure my own package to have such a folder with static assets?
How to load GLTF files without a public folder. For example, we can import .png files without problems in react application.
Answer: So there is a thing named data URI. You can convert small files in that format(which is basically a base64 encoded string with some metadata at the beginning of it).

data:[<mediatype>][;base64],<data>

In my case [<mediatype>] is data:application/octet-stream.

So if you want to load small file from specific folder in you application, first of all rename your .gltf file into .json. And after importing and converting it into base64 code you can load it using GLTFLoader from three.js library.

Here is a code example:
import myGLTF from './MyPVPanel.json';

import {GLTFLoader} from "three/examples/jsm/loaders/GLTFLoader";
import myGLTF from "./MyPVPanel.json";

const loader = new GLTFLoader();

const stringGLTF = JSON.stringify(myGLTF) // convert Object to a String
const base64EncodedGLTF = btoa(stringGLTF) // Base64 encode the String

//First part is: 'data:application/octet-stream;base64,'
const resultingDataURI = `data:application/octet-stream;base64,${base64EncodedGLTF}`;

loader.load(
  resultingDataURI,
  (gltf: any) => {
    console.log('Loaded!!!');
    this.scene.add(gltf.scene)
  },
  () => {},
  (e: any) => console.error(e)
);
}}>Load</button>

Comment: Note that base64 encoding can be very inefficient, and a JSON glTF file will include either external references or embedded base64 data already, meaning your mesh data might be double-encoded for double inefficiency.  Perhaps base64 encoding a *.glb file would be slightly better?


What's the conditional probability of a word based on the previous word in a text for each word

Question: I'm kind of lost on this.
Let's say we have a long text, something like 800 words. Some repeated, some not.
Based on the previous word(I'm guessing that means if we know the previous word) what's the conditional probability of the next word?
Using: $P(A|B) = P(AB)/P(B)$
I've been thinking, that P(AB) is how many times a combination of words was used in a text, and P(B) tells me how many times the previous word in each combination of words has been used.
To put this into perspective and a smaller example.
Let's say we have this:

A small dog jumped over the fence. The dog used its small paws to jump over the fence. The fence was no challenge.

Let's ignore if the sentence is grammatically correct. What are the conditional probabilities of each word, if we know the previous word?
There are 22 words in this example.
Using my logic:
$$P(small|a) = P("a\; small") / P(a) = ("1/22") / ("1/22") = 1 $$
This is obviously very wrong. Or is it ? I'm honestly torn between: We've analyzed the text and obviously every time there was the word a it was followed by small. Therefore we can safely assume with 100% certainty.
However, knowing myself, every time I've reached conclusions like these I was very wrong and since I'm currently ahead of my school work I have no one to discuss this over and I would appreciate any help or ideas you may throw at me.
Answer: Let $X_n$ denote the $n$-th word. Then in your simple model (technically speaking, assuing we're using a Markov chain) then for words $x,y$
$$P(X_{n+1} = y | X_n = x) = \frac{\#\{\text{occurences of } x \text{ followed by } y\} }{\#\{\text{occurences of } x \}},
$$
In your example since there is only one occurence of "a small", and also only one occurence of the word "a", we have
$$P(X_{n+1} = \text{"small"} \, | \, X_{n} = \text{"a"} ) = \frac11 = 1.
$$
Suppose instead we were using the sentence "a small man had a llama, but the tall woman had a small alpaca.". Then in this context, the generic formula above gives:
$$P(X_{n+1} = \text{"small"} \, | \, X_{n} = \text{"a"} ) = \frac{2}{3}.
$$
Unlike the original poster's solution, this does not depend on the total length of the sentence for the calculation (in this case $14$ words), but only the relative frequency of the pair "a small", to the single word "a".
Update. The case that the sentence ends in $x$
In the model described above, it is possible that $\sum_y P(X_{n+1} = y \, | \, X_n = x) < 1$, which occurs in the case that the sentence ends in the word $x$.
Consider for instance the sentence: "a small man had a llama called a". In this case our calculation gives:
$$P(X_{n+1} = \text{"small"} \, | \, X_{n} = \text{"a"} ) = P(X_{n+1} = \text{"llama"} \, | \, X_{n} = \text{"a"} )= \frac{1}{3}.
$$
but there are no other words that follow "a" in the passage. This is because we also have the probability of $1/3$ that "a" is not followed by another word. In the contexts of Markov chains this is known as an absorbing state.
Suppose we want to rule out this case, then the suitable formula is:
$$P(X_{n+1} = y | X_n = x) = \frac{\#\{\text{occurences of } x \text{ followed by } y\} }{\#\{\text{occurences of } x \text{ followed by another word}\}},
$$
In the last example ("a small man had a llama called a"), the denominator is now equal to 2 (since we ignore the last a), and we get the expected probability of $1/2$ that "a" is followed by "small".
Update. Why this disagrees with the original poster, and @Thomas Pastor
In the original post it is suggested that
$$P(\text{"a"}) = 1/22$$
because there are $22$ words, and $a$ appears once. However, it is also suggested that
$$P(\text{"a small"}) = 1/22$$
presumably for the same logic that there are $22$ words and "a small" appears once. However this should be counted in pairs of successive words, of which there are only 21, so this would be:
$$P(\text{"a small"}) = 1/21$$
With this `correction', the original poster's method would give:
$$P(\text{"a small"}\,|\, \text{"a"} ) = \frac{22}{21} > 1,$$
which is clearly not possible.
This was then formalized in the post of @Thomas Pastor as:
\begin{align*}
P(X_{n+1} = y \, | X_n =x) & = \frac{P(X_n = x,\, X_{n+1} =y )}{P(X_n = x)} \\
& = \frac{\#\{\text{occurrences of x followed by y}\}  \#\{\text{words}\}}{
\#\{\text{occurrences of x}\}  \#\{\text{pairs of words}\}}
\end{align*}
The issue with this formula is that it does not account for the case that $x$ may be the last word of the sentence. In particular, note that if we sum this formula over all words $y$, we get:
\begin{align*}
\sum_{y} P(X_{n+1} = y \, | \, X_n = x) & =
\sum_y \frac{\#\{\text{occ. of x followed by y}\}  \#\{\text{words}\}}{
\#\{\text{occ. of x}\}  \#\{\text{pairs of words}\}} \\
& =\frac{ \#\{\text{words}\}}{
\#\{\text{occ. of x}\}  \#\{\text{pairs of words}\}}
\sum_y \#\{\text{occ. of x followed by y}\} \\
\end{align*}
If it is the case that $x$ is not the last word in the sentence, then the summation on the right hand side is equal to $\#\{\text{occ. of x}\}$ from which we would get:
\begin{align*}
\sum_{y} P(X_{n+1} = y \, | \, X_n = x) & =
\frac{ \#\{\text{words}\}}{\#\{\text{pairs of words}\}} \\
& > 1.
\end{align*}
So the discrepancy is caused by how to handle the special case of the last word.
Comment: Except the Markov chain concept, your probability formula is identical to what the OP has done.
Comment: @ThomasPastor, see my update above. I disagree that this is equivalent to the original poster's model.
Comment: Oh so we're just taking into consideration the occurences of xy and x? Is it really irrelevant the size of the whole text?  How come we're using P(X) and not P(Y) as the conditional probability formula would suggest?
Comment: The length of the text will have an impact: but only as it makes occurrences of the word "a" more likely, and (if real text) less likely that it would be followed by "small". On your second comment: I'm not sure I understand what you mean about using $P(X)$ not $P(Y)$. Perhaps this is just that we are using different notation? We are dividing the number of occurrences of both words "a small" by the number of occurrences of the first word "a".
Comment: @owen88 Using which definition of Markov chain that you have this formula based on ONLY the number of occurence if you **consider the sample size of numerator and denomator are different** ?

$$P(X_{n+1} = y | X_n = x) = \frac{\#\{\text{occurences of } x \text{ followed by } y\} }{\#\{\text{occurences of } x \}}$$

The model which is called Markov chain is defined by the defintion

$$P[X_{n+1} = y | X_n = x, X_{n-1}=z, X_{n-2}=t, ...] = P[X_{n+1} = y | X_n = x])$$
Comment: and by using Bayesian conditional probability
$$P[X_{n+1} = y | X_n = x]) = \frac{P[X_{n+1} = y \textrm{ AND } X_n = x])}{P[X_n = x]}$$

This is what the OP has used.

And by taking the definition of empirical probability

$$P[X_{n+1} = y \textrm{ AND } X_n = x]) = \frac{\#\{\text{occurences of } x \text{ followed by } y\}}{\textrm{#pairs of successive words}}$$

$$P[X_n = x] = \frac{\#\{\text{occurences of } x \}}{\textrm{#words}}$$
Comment: As I put in my (edited) post, yesterday: this does not give the same number, since $\#\{\text{pairs of successive words}\} \neq \#\{\text{words}\}$. In particular, when you sum over all options $y$, you would need (for this to be a probability measure): $\sum_y P(X_{n+1} = y \, | X_n = x) = 1$, however your formula gives $N/(N-1)$, where $N$ is the total number of words.
Comment: @owen88 of course it does not work because of the way you calculate the probability of the pair of words. Indeed, if "a small" happens at $x_n$ and $x_{n+1}$, the probability "a small" happens at $x_{n+1}$ and $x_{n+2}$ is 0. The events are not independent. The formula of the author of the question is ok, just the application is wrong.
Comment: This still does not explain why the formula as you / poster stated adds to greater than 1, which is not anything to do with independence: it violates the law of total probability. I have explained in the post that this is due to handling the final word of the sentence.
Comment: @owen88 because when you (and the author) derive the probabilites by counting the number of occurence is correct is only when the sample size is large and the occurence are independent. Both of you calculated wrong numbers then unsurprisingly the final result was wrong. Think about this, if in your sentence whenever we see "a", we are sure to have "a small", are the probability of "a" and "small" still identical, and is the probability of "a" is still the number of occurence divided by the length of the sentence ?
Comment: @Thomas Pastor, I still don't understand your reasoning for saying the answer is wrong. If you mean "in the real world, the probability that the word " a" is followed by "small"", then you are correct: the estimate here is clearly wrong. However, based on a mathematical model, and the information available, this is a standard approach assuming a Markov structure...
Comment: ... If you have the time, I'd be interested to see a detailed explanation of why you think the solution I provide is wrong, why you think it is equivalent, and an example making it clear that it is incorrect. Also, I'd be interested in seeing an example of how you would calculate this probability... All of which is too  much for the size of comments!
Answer: What is your question ?
What you are doing is Empirical distribution and it converges to the real distribution when your sample size is large enough. You got the "seems wrong" result because your sentence is short.


How to allow user to insert grammatical equation with checking some rule in textbox

Question: I dont want evaluation. I want validation of equatioin at html side.
I want to allow user to enter this type equation in textbox with validation:
400 - IF(age > 32, 6, 4) +10

where age is fix string, there will be other fix string lile weight, birthdate etc....
So is there way to validate this custom equation as user enter text,
Is there any jquery plugin?
I know  here IF() is custom equation, so i must have to make custom cset of rule.
I just want some suggestion or plugin that how can i do it?
Any help would be helpful for me.
Comment: Do you mean `eval()`?
Comment: @doveyg  Just validation from html side.
Comment: In that case you want some rather complex regex. What have you tried? post examples and [JsFiddle](http://jsfiddle.net/)
Comment: Make a parser. [PEG.js](http://pegjs.org/) is good.
Answer: You could store the variables as actual variables and then do an eval call on the string from the input- like so:
var age = 10;
eval("20-age"); // returns 10

Note that dependending on what you're going to use this for, this might be a real security risk and if you're going to save the input anywhere you'd obviously need to validate and sanitize the input on the server side.
Comment: @sebbzzz: "How you'd achieve that" - as I said in question comments, and as expressions are normally evaluated by any programming language: you make a parser. Your answer is okay now with the disclaimer added; if OP decides the security cannot be compromised, it's fine.
Comment: Sure. Textbook scriping vulnerability.
Comment: Whats the worse you can do? Javascript is client side, The user wont be able to effect anything server side.
Comment: Well, it is. But it really depends on what the expression is going to be used for. The question actually want's to execute a user defined expression and I'm not sure how you'd achieve that if not going with an approach like this
Comment: @doveyg: "What's the worse you can do?" As a trivial example, say you allow sharing of expressions with other users; the expression could be stored on a server, and evaluated by someone else. Then an attacker could craft an expression that would steal private information (CSRF token or something) and send it to the attacker's drop. Maybe OP's app won't allow for something like that; maybe it does. Are you a gambler?
Comment: @Amadan: If its going into a database, I would assume the protection/validation would lie at that level. Prevent users from inputting malicious code.


What is a representative sample?

Question: I understand the rationale that underpins representative sampling (i.e. to avoid bias so that the sample 'broadly' represents the target population).
Suppose the size of the target population is 600 and the population comprises of four types of units as follows:

100 white units
250 black units
50 green units
200 yellow units

Questions

What would be a representative sample (overall and subgroup) in this case?
Is the sample in (1) appropriate for only descriptive analysis or inferential analysis or both?
If you have a representative sample, is a priori power analysis needed?
Comment: At least part of the answer will depend on whether you wish only to identify the relative proportions, or if you wish to ask questions/take measures of the individual units and try to determine if the results are significantly different based on unit colour. For the latter, multidimensional cell sizes can influence the minimum sample numbers.
Comment: Be careful with a term "representative sample". Kruskal and Mosteller (1979a, 1979b and 1979c) give nine different meanings of the term. See http://stats.stackexchange.com/a/43044/3330 for the references.
Answer: One. Any sample for which every population member has a known, non-zero (but not necessarily equal) probability of being selected.  So long as you know the probability, you can use post-stratification weighting to help your inference to population.
Two. Both.  Arguably, descriptive analysis is a special case of inferential analysis anyway.
An interesting additional distinction is between inference about a finite population (your 600 units) and a more metaphysical infinite size "data generating process" of which even the 600 units in the population are just a sample.  In either case, you will be able to analyse it with the sample generated in response to question 1, but the techniques will differ slightly, particularly with regard to what is called the "finite population correction".
Three. No.  But any inference you do should certainly do power analysis at some stage.  It could be useful to do power analysis before determining the sample size, but this is difficult if you don't know the probability distribution of the variables of interest.  Often, sample sizes in my experience are chosen with the aim of a 95% confidence interval for a particular parameter estimated from the resulting sample being within a particular range set by the key stakeholders.  This is a form of power analysis and is very helpful to do before setting the sample size.  But not essential if you are prepared to just live with what you get.
Answer: Adding to @PeterEllis excellent reply, there are many types of sample that are representative, and they each have strengths and weaknesses. However, a good start is simple random sampling without replacement. This would entail randomly choosing numbers between 1 and 600 and using the corresponding units in your sample.
However, other methods might be better, depending on what you are trying to do.

What is a representative sample?


Lower bound on clique number

Question: What is the smallest clique number (that is maximum clique size) possible for a graph with n vertices and m edges? I was thinking of using Turan's theorem, but that just tells us an upper bound on the number of edges given the clique number. I've been stuck on this for days, and could use some help.
Comment: Is this homework? If so, please tag appropriately.
Comment: not homework, but rather an exercise on one of those programming challenge sites
Comment: So you're passing the challenge on to SO?
Comment: only because i think its an interesting problem and i would like to finally know the answer
Comment: fair enough. what's the site where this question was originally posed?
Comment: Does "a graph" mean you have a fixed graph, or are you looking for an extreme example graph?
Answer: I don't believe this question has a simple answer (as is often the case with Ramsey-esque problems), but here is an approach to get you started (I'm assuming this is homework and so I won't try to work it all the way out).
Assume the graph is connected (without this assumption, the problem only gets harder). Let k be the smallest clique number possible. The extreme cases are:

If n = m-1 (equivalently, the graph is a tree), then k=2.
If m = (n choose 2) (equivalently, the graph is complete), then k=n.

From this one might reasonably infer that as m increases relative to n, k should also increase. Go with this idea and see where it takes you.

I worked out the numbers for small n,m and the results are not in OEIS, though possibly I made a computational error (please let me know if you find one). Here are the numbers:
n\m | 0 1 2 3 4 5 6 7 8 9 10
---------------------------
 1  | 1 - - - - - - - - - -
 2  | - 2 - - - - - - - - -
 3  | - - 2 3 - - - - - - -
 4  | - - - 2 2 3 4 - - - -
 5  | - - - - 2 2 2 3 3 4 5
 6  | - - - - - 2 2 2 2 2 3

Again, I'm assuming connected (at least n-1 edges) and no loops (at most (n choose 2) edges).

Lower bound on clique number