stream wrapper public /private not found Error

Question: Configuration : WAMP on windows drupal 7
I have tried using
$image = file_get_contents('E:\Team_Install\wamp\www\rootfolder\sites\all\modules\my_module\errorwinmobilesdk.jpg');
$file = file_save_data($image, 'public://',FILE_EXISTS_REPLACE);

I can see the result after first line file_get_contents but on file_save_data I get that destination folder invalid error
Another method I had tried was  $file = file_copy($source, $dest);
here also it says $dest does not exists
Wrapper folder permission and path are check thorughly they are working when I add an image using media_gallery module as it saves to public gallery or creates a new article with image, when I try to add from code it breaks and start showing message

The data could not be saved because the destination public is
  invalid. This may be caused by improper use of file_save_data() or a
  missing stream wrapper.

Please help I am new to drupal and stuck at this.
Thanks in advance
Comment: The 2nd param to `file_save_data` needs to be a stream wrapper path, e,g, `public://` instead of `public`
Comment: sry code was edited to try different version i did not corrected back , i had already tried with both "public://" or 'public' or event the complete path none worked , just corrected it
Comment: It's difficult to say exactly what's causing the problem without access to the file system - the best advice I can give is to start at [`field_valid_uri()`](https://api.drupal.org/api/drupal/includes%21file.inc/function/file_valid_uri/7) (called from `file_save_data()`) and work your way down until you find out exactly what Drupal's objecting to
Comment: i have tried to drill down to code started from file_valid_uri() till  $wrappers = file_get_stream_wrappers(); file_get_stream_wrappers are returning blank array any idea as to whta can be the reason
Comment: "$image = file_get_contents('root\sites\all\modules\my_module\errorwinmobilesdk.jpg');
$directory = 'public://' ;
$result = file_valid_uri($directory);
$uri_scheme = file_uri_scheme($directory);
print_r( $uri_scheme);
if (empty($uri_scheme) || !file_stream_wrapper_valid_scheme($uri_scheme)) {
echo  'file_stream_wrapper_scheme FALSE';
}
$class = file_stream_wrapper_get_class($uri_scheme);
print_r('$class' . $class);
if (class_exists($class)) {
echo 'class_exists';
}
$wrappers = file_get_stream_wrappers();
print_r('$wrappers  ' . $wrappers );
echo ''; print_r($wrappers); echo '';
Comment: Print output  edited some print statement to adjust in the comment as there is limit "public://
public
file_stream_wrapper_valid_scheme FALSE
$class ...................class_exists FALSE
$wrappers Array...............
Array
(
)
"
Answer: I had this problem too after some coding with file_save_data. And i solve it after clearing the cache and resaving the path in the file system configuration at admin/config/media/file-system.
My problem comes from an add field of file type, programmatically in an update.


Write the polynomial of degree $4$ with $x$ intercepts of $(\frac{1}{2},0), (6,0)$ and $(-2,0)$ and $y$ intercept of $(0,18)$.

Question: Write the polynomial of degree $4$ with $x$ intercepts of $(\frac{1}{2},0), (6,0) $ and $ (-2,0)$ and $y$ intercept of $(0,18)$.
The root ($\frac{1}{2},0)$ has multiplicity $2$.
I am to write the factored form of the polynomial with the above information. I get:
$f(x)=-6\big(x-\frac{1}{2}\big)^2(x+2)(x-6)$
Whereas the provided solution is:
$f(x)=-\frac{3}{2}(2x-1)^2(x+2)(x-6)$
Here's my working:
Write out in factored form:
$f(x) = a\big(x-\frac{1}{2}\big)^2(x+2)(x-6)$
I know that $f(0)=18$ so:
$$18 = a\big(-\frac{1}{2}\big)^2(2)(-6)$$
$$18 = a\big(\frac{1}{4}\big)(2)(-6)$$
$$18 = -3a$$
$$a = -6$$
Thus my answer:
$f(x)=-6\big(x-\frac{1}{2}\big)^2(x+2)(x-6)$
Where did I go wrong and how can I arrive at:
$f(x)=-\frac{3}{2}(2x-1)^2(x+2)(x-6)$ ?
Answer: Both forms are equivalent:
$$
-6(x-\frac{1}{2})^2(x+2)(x-6)\\
=-\frac{3}{2}\cdot 2^2(x-\frac{1}{2})^2(x+2)(x-6)\\
=-\frac{3}{2}(2(x-\frac{1}{2}))^2(x+2)(x-6)\\
=-\frac{3}{2}(2x-1)^2(x+2)(x-6)
$$
Answer: $$\Big(x-\dfrac{1}{2}\Big)^2 = \Big(\color{red}{\frac{1}{2}}\Big(2x-1\Big)\Big)^2=\color{red}{\frac{1}{4}}\Big(2x-1\Big)^2$$
Answer: You didn't go wrong anywhere.
$-6(x-\frac{1}{2})^2(x+2)(x-6) = -\frac{3}{2}(2x-1)^2(x+2)(x-6)$
That is because
$-6(x- \frac 1{2})^2 = -6(\frac 12[2x-1])^2= -6\cdot (\frac 12)^2(2x-1)^2 = -6\cdot \frac 14(2x-1) = -\frac 32(2x-1)$.
Is there some rule that that says fractions in the $(ax + b)$ parts are frowned upon?
If so, if you get $(x + \frac ab)^k$ and can replace it with $(\frac 1b)^k(bx + a)^k$ but I don't see why you should have to.
(In fact, I much prefer your notation as it directly indicates the roots and solutions... and indicates what the leading coeficient will actually be when expanded out.  And what the heck kind of sense does removing a horrifying offensive fraction from one area make if you are just going to have to put an equally offensive fraction somewhere else?)
But.... weren't you supposed to expand this out? So far as I can tell neither answer has done that.  If you expand it out, you will see both answers are exactly the same.
Comment: Well.... if you double everthing, you have to divide everything by two to even it out.  $x - \frac 12 \ne 2x -1$ but $x-\frac 12 = \frac 12*2*(x-\frac 12)= \frac 12(2x - 1)$.  And when we square it we get $(x-\frac 12)^2 = [\frac 12(2x -1)]^2 = [\frac 1 2]^2 \cdot [(2x-1)^2]$ so we have to squar the $\frac 12$ to get $\frac 14$.  And when we multiply our leading coefficient of $-6$ byt $\frac 14$ then $-6\times \frac 14 = -\frac 32$.  That's all.
Comment: Or working backwards....  $-6 (x-\frac 12)^2 = -\frac 32\times 4(x-\frac 12)^2 = -\frac 32[4(x-\frac 12)^2]=-\frac 32 [2^2(x-\frac 12)^2]=-\frac 32[2(x-\frac 12)]^2=-\frac 32[2x-1]^2$.
Comment: ... or forward.... $-6(x-\frac 12)^2 = -6(\frac 12(2x -1))^2 = -6[(\frac 12)^2(2x-1)^2]=-6*\frac 14(2x-1)^2 = -\frac 32(2x-1)^2$
Comment: Thanks for the info here. I see that in the first factor, I can get rid of the fraction x-1/2 by doubling everything within the parenthesis to get (2x-1). WHat I don't get is what to do with the power term and how -3/2 was arrived at?
Comment: It shouldn't be a hard concept:  $(x - \frac ab)^k = [\frac 1b(bx - a)]^k = \frac 1{b^k}(bx-a)^k$.  That should be a a familiar concept.
Comment: This is great! Thanks


Explicit test of within-group variance to among-group variance?

Question: Is there a way to test if the variance among groups is equal to the variance within groups, and if not, which variance is larger?
Answers on related posts all seem to point to either an F-test or a Levene's Test, but those aren't really making the comparison that I'm looking for. F tests use the ratio of variances to test for the homogeneity of means, but I'm interested in explicitly testing whether the variance within groups is larger/smaller/equal to the variance among groups. Similarly, I'm not interested in testing whether or not the within-group variance is homogeneous among groups (with Levene's Test or one of the alternatives).
My only thought is that a mixed model, with a random effect for group, gives an estimate of the variance among groups, while the combination of fixed effects and residual variance comprises the within-group variation. But it doesn't actually directly compare the two.
Answer: This is the definition of a variance ratio test, usually accomplished with the F test (less commonly, chi square). And, your use case of testing between and within groups variances IS the ANOVA F test


Python Binary Converter

Question: I am new to python and trying to write a binary converter. I want to know if there is a way to check if a value entered is 0 or 1.
Example:
binary = userinput

check to see if the 8 bit numbers entered by the user are all binary numbers.
Comment: What did you tried so far?
Comment: `value == 0`??? `value == 1`?
Answer: Try this one:
bin_str = raw_input('Enter a binary number: ')

try:
    bin_num = int(bin_str, 2)
    print "Valid binary number entered. - " + bin_str
except ValueError:
    print "Invalid number entered."

Hope that's what you are looking for.
Answer: You can use a conditional statement while looping through all digits of the user input value to check if it's equal to 0 or 1.
Ex.:
num = str(input("Insert binary number: "))

for n in num:
    if n == "0" or n == "1":
        print(n, "is a binary digit!")
    else:
        print(n, "is not a binary digit!")

Code Output:
>>> Insert binary number: 12010104

>>> 1 is a binary digit!
>>> 2 is not a binary digit!
>>> 0 is a binary digit!
>>> 1 is a binary digit!
>>> 0 is a binary digit!
>>> 1 is a binary digit!
>>> 0 is a binary digit!
>>> 4 is not a binary digit!

Now you should ask the user for input until they give a valid response, that in your case, is a user input with 8 digits.
Answer: Another option, presuming that you don't want to actually create an integer and use the exception handling mechanism:
all(bit in {"0","1"} for bit in userinput)

Comment: or `{"0","1"}.issubset(userinput)` if you really want to use sets.

Python Binary Converter


How to add checkbox to subscribe newsletter in webform

Question: I'm using D7, and I want to create a newsletter subscribing page with simplenews module.
Other than email column, I want to have fields like name, address, contact number, select field (checkbox) in the form, like in the link below
http://bsgproperty.com/registration_form.php
However, I found that simplenews is hard to add in fields, so I decided to use webform to create fields and add in a checkbox to subscribe newsletter.
I had successfully created a checkbox, but how can I link this checkbox to newsletter module?
I want the email address entered in webform to be added in newsletter subscriber list after users check the checkbox and submit.
Is there anyway to do this?
Answer: If you want to add a checkbox field using the Webform module...
Choose the "Select options" type, enter the value and label, then choose the "Multiple"  setting (even if you just want one checkbox to appear), and make sure "Listbox" option is not on.
Comment: but how should I link this to newsletter module? As I want after user check the checkbox and submit, email entered in the form will be added into newsletter subscriber list.
Comment: Which newsletter module are you using? Most come with their own subscribe forms.
Comment: I'm using simplenews. It provides a subscribe block with email address, but I need to setup extra fields like phone number, address, etc in the form.
Answer: If writing a custom module is an option, and you need to do a custom integration of Webform with another module, you can:

Implement the form_alter hook to add a new submit handler to the webform client form.
On the submit handler do any actions to subscribe your user (or any other actions you need to do). Read the code in the newsletter number to learn how to register a new subscriber; it shouldn't be too hard.

Here is a gist with a bit of example code and comments:
https://gist.github.com/noel-rivas/6fc0de57b31ca8c6885db06c92bffab0
This is an old question, and this is a very generic answer of how to use webform submitted data to accomplish some other action, but it might be helpful to you, or others.


requireNotNull vs sure operator !! in Kotlin

Question: We have a Kotlin based application and recently we added third party code quality tools (Detekt in Codacy). However, we started facing UnsafeCallOnNullableType errors.
We found that approach viable to use is to add requireNotNull checks on all parameter which maybe null. Currently, we are using sure operator (!!)
Do we have any specific reason or convention to chose one over the other. As far as I see, both will throw an Exception and will block the execution flow, except one will throw IllegalArgumentException while the other will throw NullPointerException.
Comment: Found answer from kotlin team. https://discuss.kotlinlang.org/t/requirenotnull-or/1562/2
Answer: requireNotNull, assuming you're referring to Objects#requireNonNull, is a Java method that is equivalent to !!, but with a different exception.
You didn't add any code, so it's slightly hard to help you debug. You mentioned third party code quality tools, but not which. I randomly stumbled over this GH issue that matches the error you're having. It's also the only thing I can find that would at any point use that exact error. I might have missed some, but it's the one that covers the top Google hits, so I'm going to go off that.
If you are using Detekt, this is a reported bug. Using !! is even suggested by IntelliJ.
However, you can do it another way.
Yes, using Objects#requireNonNull is one option. There is a second one though, and that's using the null-safe operator, as m0skit0 mentioned.
The reason this works is because if anything called is null, the final result is null. I.e. this:
instance.nonNullType.nullable?.nullableChild?.someOtherNullableChild

If any of the nullable ones are null, the final result is null, and none of the others are called.
Now, considering this is likely a bug in Detect, this seems like the easiest workaround for now:
whatever.calls.you?.make?.to?.the?.database ?: throw NullPointerException("Something is null");

It also keeps the variable non-null, which means you don't need null-safe calls later. The elvis operator checks if anything is null, then throws an exception. Alternatively, you can just use Objects#requireNotNull:
Objects.requireNonNull(whatever.calls.you.make.to.the.database)

If you really need to validate every single step, you'll just need to keep null checks everywhere
TL;DR:
!! and requireNotNull are effectively identical in how they work, except requireNotNull is a method call and !! compiles to an if-statement:
if(whatever == null) {
    Intrinsics.throwNpe();
}

The reason !! triggers UnsafeCallOnNullableType is because of a (probable) bug in Detekt. Both of the options are syntactic sugar for the same thing, though: if the variable is null, throw an NPE.
Comment: Codacy is the tool we have integrated with GitHub repository. Its not code specific but triggers error wherever we used !!. Though, our code runs successfully, if we ignore Codacy. Yeah, we indeed use Detekt. Didn't realize, its a bug. Definitely, the tool wanted to change all ours !! to requireNotNull :) Thanks!!
Answer: As you mentioned, requireNotNull() throws IllegalArgumentException and !! throws NullPointerException. That could be helpful if you want to differentiate between defensive code added by your devs versus undefended code (by using !! is isn't immediately obvious).
However, the bigger benefit of using requireNotNull() is using the function that takes the lazyMessage argument. This way your devs can add more meaningful messages to the exception, which could help in debugging
Answer: In my experience the best practice when a value is nullable is to use ?  and ?: operators and provide an alternative (if available) when the value is null, for example:
settings?.getValue("some-setting") ?: defaultValue

Note that this expression will return defaultValue when either settings or getValue return null.
It is best to try to avoid using !! operator at all since this basically defeats any protection against nulls. When this is not possible, I would throw a more comprehensive exception instead of relying on generic exceptions like IAE or NPE, for example:
settings?.getValue("some-setting") ?: throw SettingNotFound("Descriptive message")

Comment: In my case, its more like object.property!! This is so because property in my requirements can be null. We know the cases where this can be null and therefore when pulling value from store or DB, we add !! to validate this should never be null during those cases. Using elvis operator, will not ensure if its null and we still have to manually add null checks and throw exception if value is not there.
Comment: Then the property should be declared as non-nullable and add the null checking when pulling this property from store/DB and act accordingly, i.e. throwing a more comprehensive exception than NPE (it is never a good idea to catch a `RuntimeException`).


Automatically computed torque actuation of a revolute joint block error?

Question: Im simulating a swing door with generator using Simscape/Simulink. I imagine there is only one input for system which is the force at the knob needed to open the door, so all revolute joints have their torque actuation set to automatically computed. However, im getting an error saying:
"In the dynamically coupled component containing Revolute Joint 'SDL/SwingMotion', there are more joint primitive degrees of freedom with automatically computed force or torque (4) than with motion from inputs (0). In general, the equations of motion do not have a unique solution. Solve this problem by increasing the number of joint primitives with motion from inputs or reducing the number of joint primitives with automatically computed force or torque. Resolve this issue in order to simulate the model."
The animation works fine if i set the torque actuation of all 4 revolute joints to none, but the torque produced by the force wont be transfered this way and the generator shaft wont have any torque. However, I am able to measure the output RPM (angular velocity of generator shaft). I dont quite understand the error. Why do the revolute block treats the degree of motion of other revolute blocks as its own? How do i resolve this?
Block Diagram can be seen here.

The Assembly looks like this:

Any help is much appreciated!
Answer: For a revolute joint there are three options:

Let the revolute joint just act as a hinge, no torque can be exerted from base to follower and vice versa
Provide torque and calculate motion from the torque. This is called forward dynamics, motion is determined from torque.
Provide motion and calculate torque from the motion. This is called inverse dynamics, torque is determined from motion.

So you have to select either one of the option. If you select torque automatically computed, then you need to provide the motion which it has to follow. If you don't need to follow a provided motion, than no torque is needed.
If you set torque computed to 'none', then there is no torque that can be exerted from the base to the follower and vice versa, that is the idea of a Degree of Freedom.
It seems as if you want the Base and the Follower to be somewhat rigidly connected and follow the same motion. Than you can consider using the Rigid Transform block, which is just a rigid link in which you can define a translation or rotation offset.
EDIT
What you were effectively doing was combining forward and inverse dynamics. You put a force on the doorknob, let Simulink calculate the motion (up till now forward dynamics) then you desire the torque on the GenShaft from the motion it is doing, which is inverse dynamics. That does not work.
A better way to check the torque on the GenShaft is to, for instance, desire a certain door hinge angular velocity, put a proportional controller on it, and check the required torque. Notice that with no friction modeled in the hinge the required torque will go to zero.
So if you set all torque computed to 'none' except for the GenShaft, set this to provided by input. Then put a proportional controller on the angular velocity of the door hinge. You can then check the torque needed.
Updated model
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/219376/discussion-on-answer-by-nathan-automatically-computed-torque-actuation-of-a-revo).


What is the mathematical model for simulating flanger?

Question: Assuming the trigonometric functions use radians, a basic constant tone is represented by s(t) = a * sin(2πf). How do I use s(t) to simulate flanging? I've tried (s(t) + s(0.999t) / 2, (s(t) + s(t + 0.001sin(2πt)), etc. with varying levels of closeness. I've gotten robot-like sounds. I've gotten dissonance. I've gotten waving dissonance. I understand how flanging is done with tapes. I just don't know how to digitally simulate it.
Answer: A flanger is just a time-modulated, scaled version of the signal added back to the original signal.  Whether the signal is a single tone or not, the equation is s_out( t) = s(t) + g*s( t-d(t) )  where g is the gain applied to the added signal, and d(t) could, in principle be any periodic delay function, but is often just sinusoidal: d(t) = c*[sin( 2*pi*m*t)+1]/2 where c the the maximum amount of delay, usually less than 20ms, and m is the period of the modulation (in cycles per second) this could range from many tens of Hz down to much less than 1 Hz.  (there's a +1 to ensure that the amount of delay is always positive.)


Cisco AnyConnect weird interaction with ethernet (DNS?)

Question: We use Cisco AnyConnect Secure Mobility Client (Version 4.7.01076) at our company. Often in the morning after starting the AnyConnect client, I get a weird state with DNS on my setup. The most user visible effect (symptom) is the ping command:

The other less visible effects is that I cannot access the shared netword drives.
I eventually found a workaround, where I physically unplug the ethernet cable from the docking station (ThinkPad/Lenovo), wait for Wifi to connect, AnyConnect client would then reconnect over Wifi. At this point if I replug physically the ethernet cable, then everything is back in shape:

My very first issue is to properly define the issue (what is the actual bug?) I am having (in order to formulate it, or escalate it). How can I diagnose the bogus state I have when I first start AnyConnect (is it even related to DNS setup at all) ?

Update: I am a simple user (admin of my machine). I am guessing something is bogus, but I'd like to understand the magic behind unplug/replug ethernet cable (what details actually changed: dns, routes ... ?).

Update2: Here is my preference page:
Comment: Are you the router admin? this look like a simple LAN access restriction set inside the connection policy, which block LAN access and force your computer to talk to only corporate ressource
Answer: Make sure you've toggled "Enable automatic VPN reconnect:
Comment: thanks for the help, but it seems I do not have access to this setting in my version.
Comment: Try activating the two empty checkboxes (top two options) in your settings page?


session value is not update in the jsp page but update in after a page reload

Question: I called my servlet from Jsp file and here my servlet (i am setting a session name, value) which is used to output data in a div tag of same jsp page who called servlet.
i am using that session value as a hidden field in the form submit to jquery, but here, the updated session value is not reached in jquery??
Any solution for the same??
and yes, the jquery fetches the updated session value, if i reload the page before submitting the page..
code
servlet file:
HttpSession session = request.getSession(true);
       session.setAttribute("totalpurchase", total);

jsp file:
<form method="post" action="" onclick="check()">
            <input type="hidden" value="${sessionScope.totalpurchase}" id="totalpurchase">
</form>

Comment: Can you please give code snippet?
Comment: yes, but i am trying things from my side. and thats why code gets a bit changed..
Comment: Below link may help you understand relation between session and sessionScope:
http://stackoverflow.com/questions/3345180/which-scope-application-servletcontext-httpsession-will-el-use-for-interpret

Please confirm both sessions on page and servlet are same. and then proceed.
Comment: What else are you doing in Servlet? How you are coming back to JSP from Servlet? Do you want to update the div value without refreshing the page?
Comment: @user3657302 : yes both sessions are same..
Comment: @Braj : Actually nothing just simply putting things in the cart's div tag and creating the totalpurchase amount as in the session, to use it in the jsp page ..
Comment: I would suggest go with scriptlet and print values on console to confirm it is being added. Add SOPs just after adding to session with timestamp in SOP and inside JSP.
Compare both values, on first load and on refresh. If you will print value from session, then you will get total 4 values along with timestamp, you will come to know when those values were isnide session and when those are lost.
Comment: i checked the same. session.getAtribute("totalpurchase") is working on servlet page with updated value, but its scriptlet version is not responding in jsp page and it only responds using ${sessionScope.totalpurchase} with previous value, but after a page refresh it gets the updated new value and show it..
Answer: session and sessionScope are two different objects. You can read about it on this page.
One way is directly using ${totalpurchase}. This has limitation that no other attribute similarly named is not been used.
Comment: `${sessionScope.totalpurchase}` is the correct way to get the attribute from session scope. `${session.totalpurchase}` is incorrect. Read the link that you have shared in your post.


Using $\epsilon-\delta$ to prove that a limit is not a specific number

Question: I want to use $\epsilon-\delta$ formulation to prove that $\lim_{x\to 1 } 2x+3 \neq 6$.
I know that I need to show that there exists an $\epsilon>0$ such that for every $\delta>0$ there exists $x\in \mathbb{R}$ such that $0<\left| x-1 \right| <\delta$ but $|2x-3|\geq \varepsilon$.
Will someone please guide me through the process?
Thanks a lot in advance
Comment: What happens for $x=1$ ? :-)
Comment: My first approach would be to show
$
\lim_{x\to 1} 2x+3=5.
$
Knowing that limits are unique (if they exist) in $\mathbb{R}$ with the standard topology then shows that  $
\lim_{x\to 1} 2x+3\not= 6.
$
Comment: How about trying something like $x=1 + \min(\frac1{10},\frac{\delta}{2})$ so $0<\left| x-1 \right| <\delta$  and $ |2x-3|\geq \frac45$
Answer: You have a mistake in your definition.
The formal definition stats :

If for every number $ε>0$ there is some number $δ>0$ such that if :
$$|x - α| < δ $$
then
$$|f(x) - L| < ε$$
where $L= \lim_{x\to a} f(x)$.

So, for your exercise, $L=\lim_{x\to 1}f(x)=\lim_{x\to 1} (2x+3) =5$
Which translates to :
$$|x-1| < δ$$
$$|(2x+3) - 5|<ε$$
Take a look into the second expression :
$$|(2x+3)-5|<ε \Rightarrow |2x -2|<ε \Rightarrow |x-1|<\frac{ε}{2}$$
So in order to make sure that $|f(x)−5|<ϵ$, it is enough to require that $|x−1|<\frac{ε}{2}$.
Thus we can select $δ = ε/2$.
Then $δ>0$, and if $0<|x-1|<δ$, then it will follow that $|f(x)-5|<2δ=ε$
Thus, for all $\epsilon\gt 0$ there exists a $\delta\gt 0$ (namely, $\delta=\epsilon$) with the property that if $0\lt |x-1|\lt \delta$, then $|f(x)-5|\lt \epsilon$. This proves that $\lim\limits_{x\to 1}f(x) = 5\neq 6$, as desired, because limits are unique in $\mathbb R$, if they exist.
Answer: You want to find a way of making sure that the distance between $2x+3$ and $6$ is large for $x$ close enough to $1$.
Try making $2x+3\lt 5.5$, which would mean you could make $\epsilon = 0.5$.
Comment: Thanks a lot !!!
Answer: This problem is teaching you the negation of "for every $\epsilon > 0$ there exists a $\delta > 0$ such that ... "
So pick $\epsilon = 0.1$.  Now you need to show there's no possible $\delta$ such that, for all $x \in (1-\delta , 1 + \delta)$, $f(x)=2x+3 \in (5.9, 6.1)$. Well big values of $\delta$ will include values of $f(x)$ that are far away from 6, and small such values will never let $f(x)$ get near 6.
Comment: Thanks a lot !!!


How do I display my germination rates? Is it count data? Not sure!

Question: I have 4 treatments, each with 5 Petri dishes (so total 20), and each Petri dish has 25 seeds in it. I am looking to discuss how many seeds have germinated. Should I get the mean germination of each treatment and then discuss it as a percentage of 25 seeds? So if in the root treatment, 4,4,6,6,0 germinate, so my mean is an average of 5 seeds out of 25, how do I best display/discuss this?

<code>> ARpetri<-read.table(file.choose(),header=TRUE)
> attach(ARpetri)
> names(ARpetri)
[1] "Distilled" "Marigold"  "Mixed"     "Root"
> ARpetri
  Distilled Marigold Mixed Root
1         2        1     1    5
2         2        1     0    3
3         3        0     0    3
4         3        1     0    4
5         0        1     1    1
</code>

the counts on each row do not belong together, just the columns and the first column is excel generated and not my own. I hope that helps clarify. Many thanks for all the advice and I will definitely check out the R mailing list as suggested. Any recommendations for where I can look up how to create the plot pictured above? I think it would be useful to re-create with my other counts and "eyeball" the data. Thanks all!
Comment: "How many seeds germinated" is a count... how did you know how many there were? By counting them.
Comment: https://en.wikipedia.org/wiki/Generalized_linear_model
Comment: Could you have a fraction of a seed germinate??
Answer: Your outcome is discrete insofar as the response can only assume values 0/25 (1/25) 25/25 or 0(0.04)1 or 0(4)100%, but in principle your rate is a probability. Had you used 250, 2500, ... seeds your response would have been more and more finely measured and it's fruitful (pun intended) to think that you're modelling a quantity on a continuous scale.
Tukey called numbers like 4/25 counted fractions, not that anyone really needs a special name.
GLM software that I know of will handle this properly as a model with binomial link and total 25. Display is not a problem as you have 20 counts which can be shown directly on a single graph with both count and probability or percent scales.
If you post the data, example analyses are likely to follow.
EDIT Some small questions remain about the data, but on the assumption that the row identifiers just arbitrarily label replicates, and have no other meaning, then this kind of plot shows all the information in the data. The horizontal lines show means.
Note that my software sorts Distilled Marigold Mixed Root alphabetically but it could be that there is a more meaningful order. I am not a plant scientist and in any case I guess that it needs the OP to explain here.
Comment: +1. There *always* are meaningful sequences that can be inferred from the data: order the groups by median, maximum, or variance, for instance. That's one no-cost way to add information to a graphic: it communicates more without costing any more ink.
Comment: Sure, and I would order by mean if these were my data and there was no reason otherwise. I am asking to hear from the OP whether there is a natural order.
Comment: Hi, I would probably go for mean as well but mostly because I am not fully versed in R and statistical models. The order of the treatments (distilled, marigold etc) doesn't matter in so far as the treatment is concerned. So would definitely need to order them in terms of a measure such as mean, which would visually be far more meaningful. Very appreciative of all the comments and any feedback on better content is appreciated as well as I am new to this community.
Comment: Just a quick point about the data: the column to the far left (1,2,3,4,5) is not included, it appeared in R when I attached the data that was in tabs delimited format after I added it to excel. So they are excel's row numbers.
Comment: Using R or anything else is immaterial here, as is my use of Stata: CV is not focused on which software or which code to use or how to use it. The  identifier was read as such by me. What you're leaving unclear is whether the identifiers identify plots or containers or other groups, e.g. whether the values in the  first row (observation) are linked in some sense. Please consider the graph redrawn so that treatments are ordered by mean.
Comment: Hi Nick, the first row (observation) are not linked. I'm confused about how you made that graph. Is that ok to ask about or not a question for this space?
Comment: It's using my own Stata program `stripplot`.But it's essentially a scatter plot with annotations, with the horizontal axis being based on treatment and rank order of response. R people are always telling me that R graphics are superior, so it should be trivial in R except I am not the person to ask how.


How to prevent auto rotation like the iPhone photo app does?

Question: I want to prevent a UICollectionViewController from auto rotation when there's a finger on the screen. The finger could move, the device could rotate, but the UICollectionViewController shouldn't rotate whenever the finger is still on screen.
And the UICollectionViewController should rotate immediately when the finger left the screen. As the iPhone photo app does.
Question:

How to detect touch?
I overwrite the touchBegan:withEvent: etc. in UICollectionView subclass. But when the UICollectionView start scrolling, it calls touchCanceled:withEvent: method.
If I start scrolling the UICollectionView earlier, the touchBegan:withEvent: does even not fired.
How to prevent auto rotation temporarily?
I overwrite the shouldAutorotate in my view controller to prevent rotation. But when the finger left the screen, the UICollectionView can't rotate immediately.
Comment: Du you mean fix Device Orrientation
Comment: I wanna disable rotation temporarily when there's a finger touch.
Answer: For detecting the touch event, I would recommend using a UIGestureRecognizer rather than overriding the UICollectionViewController's touch events. That way you can be notified of the touch event without interfering with the existing event handling.
You will probably need two custom UIGestureRecognizer classes to implement this, since I don't think UITapGestureRecognizer will meet your needs. You can have one UIGestureRecognizer notify you of finger down events and another notify you when the finger is lifted.
For preventing auto rotation, override shouldAutorotate as you have already done. When your gesture recognizer detects that the finger has been lifted, call [UIViewController attemptRotationToDeviceOrientation] to tell iOS to rotate the UI to the current orientation. (Obviously make sure that shouldAutorotate will now return YES before calling that.)
Comment: Your idea may work. But it needs to implement two custom UIGestureRecognizer. I will try sometime.
Answer: Try this code, please:
@interface BlockAutorotateViewController ()

@property (nonatomic, strong) UILongPressGestureRecognizer *longPressGestureRecognizer;
@property (nonatomic, strong) UISwipeGestureRecognizer *swipeGestureRecognizer;
@property (nonatomic, assign, getter = isPressed) BOOL pressed;

@end

@implementation BlockAutorotateViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.pressed = NO;

    self.longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(myLongPressAction:)];
    self.longPressGestureRecognizer.minimumPressDuration = 0;
    [self.view addGestureRecognizer:self.longPressGestureRecognizer];

    self.swipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(mySwipeAction:)];
    [self.view addGestureRecognizer:self.swipeGestureRecognizer];

}

- (void)myLongPressAction:(id)sender
{
    if ((self.longPressGestureRecognizer.state == UIGestureRecognizerStateEnded) || (self.longPressGestureRecognizer.state == UIGestureRecognizerStateChanged))  {
        self.pressed = YES;
    }
    else if (self.longPressGestureRecognizer.state == UIGestureRecognizerStateBegan) {
        self.pressed = NO;
        [UIViewController attemptRotationToDeviceOrientation];
    }
    else {
        self.pressed = NO;
    }
}

- (void)mySwipeAction:(id)sender
{
    if ((self.swipeGestureRecognizer.state == UIGestureRecognizerStateBegan) || (self.longPressGestureRecognizer.state == UIGestureRecognizerStateChanged))  {
        self.pressed = YES;
    }
    else if (self.longPressGestureRecognizer.state == UIGestureRecognizerStateEnded) {
        self.pressed = NO;
        [UIViewController attemptRotationToDeviceOrientation];
    }
    else {
        self.pressed = NO;
    }
}

- (BOOL)shouldAutorotate
{
    return (self.isPressed ? NO : YES);
}

@end

Comment: @smilingpoplar, which one would you use for this desired feature? Have you tested example above?
Comment: I have tried your code. It doesn't work if I move the finger first, and then rotate the device. In this case, the view shouldn't rotate.
Comment: You have tried without UIGestureRecognizerStateChanged in first if sentence, of course?
Comment: I tried your new code. Your could test like this: quickly tap and swipe on the view, then rotate device.
Comment: Don't get me wrong, but you should test this above all, right? :) I'm trying to help you. Also, take some time and study gesture recognisers, it will be easier for you to go further on proposed code. Purpose of this site is not getting free snippets, but collaborate. I'd also advise you to make more clear requests, you will get this many times here. Just a friendly advice.
Comment: Well, I add `self.longPressGestureRecognizer.minimumPressDuration = 0;`, it seems to work :)
Comment: You see, it's going when collaborate. Yes, minimumPressDuration is a vital one :)


Why is gmpy2 so slow at complex exponentiation?

Question: I was using complex numbers in gmpy2 and noticed that it was slow. I narrowed it down the exponentiation operator. At first I thought it was just because it was complex. But then I compared it to mpmath which uses gmpy2 and it was so much faster:
# tested using gmpy2 2.0.8, mpmath 1.1.0, python 3.8.5
>>> import timeit
>>> setup = '''
import gmpy2 as gm
import mpmath

a1 = gm.mpc(-12.5, 34.125)
a2 = gm.mpc(17, -45.875)

b1 = mpmath.mpc(-12.5, 34.125)
b2 = mpmath.mpc(17, -45.875)
'''

# using gmpy2
>>> timeit.timeit('a1 ** a2', setup)
87.13848301399992
>>> timeit.timeit('a1 ** 2', setup)
40.478690218
>>> timeit.timeit('pow(a1, 2)', setup)
40.70392542999991

# using mpmath
>>> timeit.timeit('b1 ** b2', setup)
51.799312732999965
>>> timeit.timeit('b1 ** 2', setup)
4.239320562999978
>>> timeit.timeit('pow(b1, 2)', setup)
4.293315565000057

# multiplication comparison
>>> timeit.timeit('a1 * a1', setup)
0.9900801109999975  # gmpy2
>>> timeit.timeit('b1 * b1', setup)
4.711916033999955  # mpmath

Pure complex exponentiation is incredibly slow, but mpmath is still some 40% faster than gmpy2. Since mpmath is Python I figured it would be much slower but that's clearly not the case. How is gmpy2 so slow here?
Comment: `mpmath` will attempt to use `gmpy2` or `gmpy` to replace Python's built in integer type. `mpmath` does not call the `mpfr` or `mpc` related functions in `gmpy2`/`gmpy`. I'll look at in more detail later.
Comment: Are you sure `mpmath` is using `gmpy2`? The docs say `mpmath`'ll use `gmpy` if available, without mentioning `gmpy2` (could just be an oversight, one project sprang from the other). I don't know how much effort they've put into keeping up with the gmpy/gmpy2 releases, and they might not work with `gmpy2` given it presumably had some breaking changes in the 2.0 release.
Comment: Could you please check and paste version of python, gmpy2, ,mpmath. Also please check if all C-libraries, that [gmpy2 depends](https://gmpy2.readthedocs.io/en/latest/intro.html#requirements) are properly compiled and installed. The results you have for single operation are **terribly** slow for both libraries,  I guess the issue is with C-libraries that works under the hood.
Comment: Sorry, I did not notice versions are already there. Still I think you should check e.g. if `libmpfr` and `libmpfr-dev` (assuming its debian or similar, or equivalent appropriate for your OS) is properly installed and works properly
Comment: @ShadowRanger `mpmath.libmp.BACKEND` says `gmpy` even though gmpy is not installed - mpmath will also [try to import](https://stackoverflow.com/a/26553032/1846249) `gmpy2` first.
Comment: @running.t gmpy2 was installed from a complied wheel file from [this site](https://www.lfd.uci.edu/~gohlke/pythonlibs/#gmpy) as I am on Windows.
Answer: Disclaimer: I maintain gmpy2.
I was curious about the cause(s) of the differences. I ran four different tests.
# Reference test on Windows 10 that used the same gmpy2
# binaries.

>>> timeit.timeit('a1 ** a2', setup)
60.565931600000006
>>> timeit.timeit('a1 ** 2', setup)
25.686232700000005
>>> timeit.timeit('pow(a1, 2)', setup)
25.684606899999977
>>> timeit.timeit('b1 ** b2', setup)
35.29716189999999
>>> timeit.timeit('b1 ** 2', setup)
2.6226074000000494
>>> timeit.timeit('pow(b1, 2)', setup)
2.6126720999999975
>>>
>>> import gmpy2
>>> gmpy2.version()
'2.0.8'
>>> gmpy2.mp_version()
'MPIR 2.7.2'
>>> gmpy2.mpfr_version()
'MPFR 3.1.4'
>>> gmpy2.mpc_version()
'MPC 1.0.3'
>>>

The results are similar to those in the question. I printed the versions of the underlying libraries.
# Test using WSL with latest Ubuntu version. Same physical
# system as above.

>>> timeit.timeit('a1 ** a2', setup)
31.21574370000002
>>> timeit.timeit('a1 ** 2', setup)
2.3873958000000357
>>> timeit.timeit('pow(a1, 2)', setup)
2.3556844999999953
>>> timeit.timeit('b1 ** b2', setup)
36.35650579999998
>>> timeit.timeit('b1 ** 2', setup)
2.4482329999999592
>>> timeit.timeit('pow(b1, 2)', setup)
2.431874800000003
>>>
>>> import gmpy2
>>> gmpy2.version()
'2.1.0b3'
>>> gmpy2.mp_version()
'GMP 6.2.0'
>>> gmpy2.mpfr_version()
'MPFR 4.0.2'
>>> gmpy2.mpc_version()
'MPC 1.1.0'
>>>

I chose WSL because it is easy to install on Windows 10. gmpy2 and mpmath were installed using sudo apt install python3-gmpy2 and sudo apt install python3-mpmath. gmpy2 is slightly faster than mpmath.
# Test using Hyper-V virtual machine under Windows Server 2016.
# Different physical system but identical specifications.

>>> timeit.timeit('a1 ** a2', setup)
27.467059508984676
>>> timeit.timeit('a1 ** 2', setup)
2.171035467006732
>>> timeit.timeit('pow(a1, 2)', setup)
2.193065536994254
>>> timeit.timeit('b1 ** b2', setup)
31.870763173996238
>>> timeit.timeit('b1 ** 2', setup)
2.019194034015527
>>> timeit.timeit('pow(b1, 2)', setup)
2.0843256690131966
>>>
>>> import gmpy2
>>> gmpy2.version()
'2.1.0b5'
>>> gmpy2.mp_version()
'GMP 6.2.0'
>>> gmpy2.mpfr_version()
'MPFR 4.0.2'
>>> gmpy2.mpc_version()
'MPC 1.1.0'
>>>

I used the latest beta release for the previous test. The results are identical with the Ubuntu version. Overall, slightly faster that WSL.
# Same as above but using gmpy2 2.0.8 instead of 2.1.0b5.

>>> timeit.timeit('a1 ** a2', setup)
23.692542312986916
>>> timeit.timeit('a1 ** 2', setup)
9.208024947001832
>>> timeit.timeit('pow(a1, 2)', setup)
9.388882965984521
>>> timeit.timeit('b1 ** b2', setup)
32.078784318000544
>>> timeit.timeit('b1 ** 2', setup)
2.027712993003661
>>> timeit.timeit('pow(b1, 2)', setup)
2.123160599003313
>>>
>>> import gmpy2
>>> gmpy2.version()
'2.0.8'
>>> gmpy2.mp_version()
'GMP 6.2.0'
>>> gmpy2.mpfr_version()
'MPFR 4.0.2'
>>> gmpy2.mpc_version()
'MPC 1.1.0'
>>>

The last two test show the difference between the 2.0.8 and 2.1.0 versions. I made significant changes to the argument handling. mpc ** int is much faster but mpc ** mpc is slightly slower. (I think I can fix that regression...)
The Windows binaries are using old versions of the underlying libraries. I am working towards Windows binaries based on the latest versions of GMP, MPFR, and MPC compiled with the mingw-w64 compilers. The GCC compiler will allow GMP to automatically select the proper code path for different CPUs.
Update 1
I've optimized mpc ** mpc and mpc ** int. The performance regression for mpc ** mpc has been fixed and mpc ** int is even faster.
Comment: So ultimately, it's slow because it's outdated. When might the `2.1.0` version be out? Unrelated: the Windows version (the compiled wheel from [here](https://www.lfd.uci.edu/~gohlke/pythonlibs/#gmpy) at least) also crashes Python when `.conjugate` is called on an `mpc`.
Comment: I managed to get a running binary. It is about 25% faster but the WSL/Linux versions are faster. I haven' done any detailed testing so its not ready for release but I'm getting closer.


How far can a player throwing a soccer ball inbounds run along the sideline?

Question: Watching Bundesliga or Premier League from time to time I will see a player inbounding the ball, and running along the sideline.  There does not seem to be a restriction, but surely there must be.
What restricts the movement of a player inbounding the ball in football (soccer)?
For more information: (and apologies, YouTube does not seem to have very many videos of player tossing the ball in).  What I am talking about is when the ball is played out of bounds along the sidelines.  The ensuing play has one player take the ball and toss it over his head into play.  It seems this player can run boundlessly along the sideline before tossing it in.
Comment: Sounds like you're talking about a throw-in. They can go until the ref says stop. 5 meters +/- are usually acceptable.
Answer: Law 15 - The Throw-in states:

At the moment of delivering the ball, the thrower must: [...] throw the ball with both hands from behind and over the head from the point where it left the field of play

so in theory it should be at the exact point the ball left the pitch. In practice, players will be given a certain (non-defined) amount of leeway, particularly if doing so enables the game to be restarted more quickly and does not result in their team gaining an advantage.
Comment: And referrees allow this to be widely abused almost evrywhere. Watch any football match in any of the English leagues including the Premiership and players steal huge amounts of ground with impunity, in this way. And it has been widely evident at this world cup. Only rarely do you see a referee or a linesman pull a player back and make him take the throw from where the ball went out of play.


Does Java optimize new HashSet(someHashSet).contains() to be O(1)?

Question: This class is an example of where the issue arises:
public class ContainsSet {
    private static HashSet<E> myHashSet;

    [...]

    public static Set<E> getMyHashSet() {
        return new HashSet<E>(myHashSet);
    }

    public static boolean doesMyHashSetContain(E e) {
        return myHashSet.contains(e);
    }
}

Now imagine two possible functions:
boolean method1() {
    return ContainsSet.getMyHashSet().contains(someE);
}
boolean method2() {
    return ContainsSet.doesMyHashSetContain(someE);
}

Now is my question whether or not method 1 will have the same time complexity after Java optimization as method 2.
(I used HashSet instead of just Set to emphasize that myHashSet.contains(someE) has complexity O(1).)
Without optimization it would not. Although .contains() has complexity O(1), the new HashSet<E>(myHashSet) has complexity O(n), which would give method 1 a complexity of O(n) + O(1) = O(n), which is horrible compared to the beloved O(1).
The reason why I this issue is imported is because I am teached not to return lists or sets if you will not allow an external class to change the contents of it. Returning a copy is an obvious solution, but it can be really time-consuming.
Comment: `new HashSet(anotherHashSet).contains()` == `anotherHashSet.contains()`
Comment: Use an immutable `Set` (such as Guava's [`ImmutableSet`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/collect/ImmutableSet.html)) and you won't have to return a copy at all.
Comment: Set is just an interface, the class implementing it is (in your case) HashSet so there's no difference
Comment: Sure? Besides, you call the `.contains()` on a return value of a method. So they are in different files. So at compile time, your equation does not hold.
Are you sure it will always be so?
Comment: @GuilhermeTorresCastro True, but I tend to be as general as possible with variable declarations and return types. Normally I will always type `Set mySet = new HashSet()`, but I always used HashSet here to be specific.
Comment: @FrankPavageau Of course, I do want it to be mutable from within it's own class.
Comment: @StevenRoose You can still create a new, modified instance of the `Set`  to replace the previous one, it's not incompatible. Of course, the cost depends on the ratio of reads and writes.
Answer: No, javac does not (and cannot) optimize this away. It's required to emit the byte code you describe in your source to this level. And the JVM will not be nearly intelligent enough to optimize this away. It's way too likely to have side effects to prove.
Don't return a copy of the HashSet if you want immutability. Wrap it in an unmodifiable wrapper: Collections.unmodifiableSet(myHashSet)
Comment: If the caller wants a mutable copy it can always call `new HashSet()` itself.
Comment: I assumed it was not possible at compile time, but I thought maybe at runtime it was. At runtime you can see all instructions chronologically so it would be more obviously visible that the optimization is possible.
Comment: I don't necessarily want immutability, I only want the set from my class to be immutable. But if the caller wants to play with the set, I'd want him to be free to do so. But for this purpose I will probably use your solution and document the fact that it's an immutable set.
Comment: @StevenRoose But the instructions will be doing something (comparing hashCodes, creating `Map.Entry`s, etc.) and could not be eliminated.
Comment: If you clearly specify that your method returns an immutable collection, the caller knows exactly what he can and cannot do. If he needs to modify the collection for his own purposes, he can just as easily take a copy (and will be greeted by an `UnsupportedOperationException` if he fails to do so). This seems reasonable to me in the common scenario where reads are more frequent than writes.
Answer: What can I say here but that creating a new HashSet and populating it via the constructor is expensive!
Java will not "optimize away" this work: Even though you and I know it would give the same result as "passing through" the contains() call, java can not know this.
Answer: No. That is beyond optimization. You returned a new object and you could use it in somewhere else, Java is not supposed to omit it. A new HashSet will be created.
This is not a good practice to return a copy. It's not only time consuming but also space consuming. As Sean said, you can wrap with unmodifiableSet or you can wrap it in your own class.
You can try this:
public static Set<E> getMyHashSet() {
    return Collection.unmodifiableSortedSet(myHashSet);
}

Note: use that method will return a view of your set, not a copy.


aws vpc subnet design

Question: I'm asked to update our current aws vpc environment, our current vpc cidr is 172.30.0.0/24,
below are subnets and avilability zones:

172.30.0.0/26    - public1  - az1
172.30.0.128/26  - private1 - az1
172.30.0.64/26   - public2  - az2
172.30.0.192/26  - private2 - az3

I'm not able to recreate the vpc because some other services have been deployed to them,
as you can see, in az2 and az3, there are only one subnet, and I want to add one subnet in az2 and az3
But I don't know how can I split it, could you please give some idea
Comment: You can't split a subnet if it has any resources in it.
Comment: I want add new subnet, do you know how to set the cidr for new subnet in the 2 az?
Comment: I'm not sure what is the issue. Go to AWS console, VPC and add new subnet to it.
Comment: You can have multiple subnets in each Availability Zone. What did you try and what problem are you facing?
Comment: thanks @JohnRotenstein, since I'm not familiar with vpc subnet part, the problem is the new cidr block, I don't know wha't the value of cidr_block for new subnet, like can I use `172.30.1.64/26` for new subnet at az2?
Answer:
can I use 172.30.1.64/26 for new subnet at az2

Sadly, you can't, as your VPC cidr is 172.30.0.0/24. Since you can't delete any of your current subnets, I think the best way is to add new cidr to your VPC. You can add 172.30.1.0/24, and then you will be able to create 172.30.1.64/26 subnet.
Answer: Using a CIDR calculator:
Your VPC 172.30.0.0/24 goes from 172.30.0.0 to 172.30.0.255:

Subnet 172.30.0.0/26 goes from 172.30.0.0 to 172.30.0.63
Subnet 172.30.0.64/26 goes from 172.30.0.64 to 220.127.116.11
Subnet 172.30.0.128/26 goes from 172.30.0.128 to 220.127.116.11
Subnet 172.30.0.192/26 goes from 172.30.0.192 to 184.108.40.206

Therefore, the VPC range is full!

aws vpc subnet design


Computing the median of a nc file with nco

Question: As the title indicates, I want to compute the median of a .nc file named sfcWind_1999.nc. On each grid point (lat/lon combination) I want to compute the median in the time dimension. Is there any nco attribute that does this?
Comment: Does the solution have to be with NCO?  CDO has a percentile function that can calculate the median.
Answer: The median is the 50th percentile, so you can use the percentile function in CDO to do this:
cdo timpctl,50 in.nc -timmin in.nc -timmax in.nc median.nc

The function needs to know the data bounding values to calculate the histogram, hence the piped min and max commands.
Answer: As described in the manual, NCO can report the median of a single variable, but not, in one step, all variables in the file. So you would have to create the loop over variables yourself, either in Bash or in ncap2 directly.
ncap2 -O -v -s "foo=gsl_stats_median_from_sorted_data(var_nm.sort());print(foo)" in.nc out.nc

or
ncmdn var_nm in.nc


How to use boxplots to find the point where values are more likely to come from different conditions?

Question: I have plotted some data using box plots.
I am comparing Condition 1 (left) and Condition 2 (Right) values. My aim is to find a point at which we make a decision where the value changes from point Condition 1 to Condition 2.
Will this conclusion make sense, if I say if I do the experiment again and get any value than the median of Condition 1, then it is likely that the value will be of Condition 2?
Or is there any other way which I can represent this data  to to get conclusion that if I get random value I can say if it is from condition 1 or condition 2?
Data presented as code for R input:
Cond.1 <- c(2.9, 3.0, 3.1, 3.1, 3.1, 3.3, 3.3, 3.4, 3.4, 3.4, 3.5, 3.5, 3.6, 3.7, 3.7,
            3.8, 3.8, 3.8, 3.8, 3.9, 4.0, 4.0, 4.1, 4.1, 4.2, 4.4, 4.5, 4.5, 4.5, 4.6,
            4.6, 4.6, 4.7, 4.8, 4.9, 4.9, 5.5, 5.5, 5.7)
Cond.2 <- c(2.3, 2.4, 2.6, 3.1, 3.7, 3.7, 3.8, 4.0, 4.2, 4.8, 4.9, 5.5, 5.5, 5.5, 5.7,
            5.8, 5.9, 5.9, 6.0, 6.0, 6.1, 6.1, 6.3, 6.5, 6.7, 6.8, 6.9, 7.1, 7.1, 7.1,
            7.2, 7.2, 7.4, 7.5, 7.6, 7.6, 10, 10.1, 12.5)

Each condition has 39 values.
Answer:
Here is one of many possibilities. Back in 1979, Emanuel Parzen suggested hybridising the quantile plot and the box plot. Some references are given below. Clearly, the box of the box plot shows median and quartiles, which are just key quantiles. Showing all of the data, namely all the quantiles or order statistics, is entirely possible, at least with a small number of groups (as in this thread) and a small or moderate number of observations (as in this thread too). In fact the design extends quite well to larger sample sizes. Outliers, granularity, ties, grouping and gaps (whichever way you want to think about such features) are always evident as well as general level, spread and shape. The graph is not subject to artefacts or side-effects of arbitrary rules of thumb such as what is or is not within 1.5 IQR of the nearer quartile. Conversely, it may offer too much detail for some tastes, but faced with a less than ideal graph one just moves on.
It is reasonable to point out that quantile plots are just cumulative distribution plots with axes reversed, although they are more often shown as point patterns than as connected lines.
Cox (2012) reported one Stata implementation and his stripplot (Stata users can download from SSC) offers another. Implementation should be trivial in any major statistical or mathematical software.
I think this kind of display offers much more detail than a conventional box plot, which here does not fully exploit the space available. A conventional box plot can be helpful for 10-100 groups or variables, where some severe reduction of the data may be needed, but it throws out possibly interesting fine structure for the common few-group or few-variable case.
Another key virtue of this graph is that it echoes the elementary but fundamental fact that just as half the values are inside the box, so also half the values are outside the box (and often the most interesting or more important half). I've seen even experienced statistical people misled by the stark contrast between fat box and thin whiskers. The classic illustration of this is any U-shaped distribution or any distribution with two big clumps of approximately equal size. The box will then be long and fat and the whiskers short and thin. People often miss the fact that such whiskers  are hiding the highest densities. Tukey (1977) gave an example of this with Rayleigh's data.
In this case and in many others logarithmic scale is used. In principle, the quantile-box plot is easily compatible with any monotonic transformation, as the transform of the quantiles is identical to the quantiles of the transformed values. (There is some small print qualifying that, arising because median and quartiles may be be produced by averaging of adjacent order statistics, which doesn't usually bite.)
I don't offer herewith any kind of graphical substitute for a significance test. This is an exploratory device.
Cox, N.J. 2012. Axis practice, or what goes where on a graph.
Stata Journal 12(3): 549-561. .pdf accessible here
Parzen, E. 1979a.
Nonparametric statistical data modeling.
Journal, American Statistical Association 74: 105-121.
Parzen, E. 1979b.
A density-quantile function perspective on robust estimation.
In Launer, R.L. and G.N. Wilkinson (Eds) Robustness in statistics.
New York: Academic Press, 237-258.
Parzen, E. 1982.
Data modeling using quantile and density-quantile functions.
In Tiago de Oliveira, J. and Epstein, B. (Eds)
Some recent advances in statistics. London: Academic Press,
23-52.
Tukey, J.W.
Exploratory Data Analysis.
Reading, MA: Addison-Wesley.
Comment: can we reproduce the analysis (i.e., the plot) that you created? (can you include the code if you have plotted in R or similar software)
Comment: The plot was produced with `stripplot` in Stata. I don't know if you consider that "similar to" R.  @Glen_b evidently used R for the same kind of plot in his answer to http://stats.stackexchange.com/questions/114744/how-to-present-box-plot-with-an-extreme-outlier
Answer: @NickCox has presented a good way to visualize your data.  I take it you want to find a rule for deciding when to classify a value as condition1 vs condition2.
In an earlier version of your question, you wondered if you should call any value greater than the median of condition1 as a member of condition2.  This is not a good rule to use.  Note that by definition, $50\%$ of a distribution is above the median.  Therefore, you will necessarily misclassify $50\%$ of true condition1 members.  Based on your data, I gather you will also misclassify $18\%$ of your true condition2 members.
A way to think through the value of a rule like yours is to form a confusion matrix.  In R, you can use ?confusionMatrix in the caret package.  Here is an example using your data and your suggested rule:
library(caret)

dat  = stack(list(cond1=Cond.1, cond2=Cond.2))
pred = ifelse(dat$values>median(Cond.1), "cond2", "cond1")
confusionMatrix(pred, dat$ind)
# Confusion Matrix and Statistics
#
#           Reference
# Prediction cond1 cond2
#      cond1    20     7
#      cond2    19    32
#
#                Accuracy : 0.6667
# ...
#
#             Sensitivity : 0.5128
#             Specificity : 0.8205
#          Pos Pred Value : 0.7407
#          Neg Pred Value : 0.6275
#              Prevalence : 0.5000
#          Detection Rate : 0.2564
#    Detection Prevalence : 0.3462
#       Balanced Accuracy : 0.6667

I bet we can do better.
A natural approach is to use a CART (decision tree) model, which (when there is only one variable) simply finds the optimal split.  In R, you can do that with ?ctree from the party package.
library(party)

cart.model = ctree(ind~values, dat)
windows()
  plot(cart.model)

You can see that the model will call a value "condition1" if it is $\le5.7$, and "condition2" otherwise (note that the median of condition1 is $3.9$).  Here is the confusion matrix:
confusionMatrix(predict(cart.model), dat$ind)
# Confusion Matrix and Statistics
#
#           Reference
# Prediction cond1 cond2
#      cond1    39    15
#      cond2     0    24
#
#                Accuracy : 0.8077
# ...
#
#             Sensitivity : 1.0000
#             Specificity : 0.6154
#          Pos Pred Value : 0.7222
#          Neg Pred Value : 1.0000
#              Prevalence : 0.5000
#          Detection Rate : 0.5000
#    Detection Prevalence : 0.6923
#       Balanced Accuracy : 0.8077

This rule yields an accuracy of $0.8077$, instead of $0.6667$.  From the plot and the confusion matrix, you can see that true condition1 members are never misclassified as condition2.  This falls out of optimizing the accuracy of the rule and the assumption that both types of misclassification are equally bad; you can tweak the model fitting process if that isn't true.

On the other hand, I would be remiss if I didn't point out that a classifier necessarily throws away a lot of information and is typically suboptimal (unless you really need classifications).  You may want to model the data so that you can get the probability a value will be a member of condition2.  Logistic regression is the natural choice here.  Note that because your condition2 is much more spread out than condition1, I added a squared term to allow for a curvilinear fit:
lr.model = glm(ind~values+I(values^2), dat, family="binomial")
lr.preds = predict(lr.model, type="response")
ord      = order(dat$values)
dat      = dat[ord,]
lr.preds = lr.preds[ord]

windows()
  with(dat, plot(values, ifelse(ind=="cond2",1,0),
                 ylab="predicted probability of condition2"))
  lines(dat$values, lr.preds)

This is clearly giving you more, and better, information.  It is not recommended that you throw away the extra information in your predicted probabilities and dichotomize them into classifications, but for the sake of comparison with the rules above, I can show you the confusion matrix that comes from doing so with your logistic regression model:
lr.class = ifelse(lr.preds<.5, "cond1", "cond2")
confusionMatrix(lr.class, dat$ind)
# Confusion Matrix and Statistics
#
#           Reference
# Prediction cond1 cond2
#     cond1    36     8
#     cond2     3    31
#
#                Accuracy : 0.859
# ...
#
#             Sensitivity : 0.9231
#             Specificity : 0.7949
#          Pos Pred Value : 0.8182
#          Neg Pred Value : 0.9118
#              Prevalence : 0.5000
#          Detection Rate : 0.4615
#    Detection Prevalence : 0.5641
#       Balanced Accuracy : 0.8590

The accuracy is now $0.859$, instead of $0.8077$.
Comment: @gung That is great response, I just not understand the last probability graph i.e "predicted probability of condition2". Can you please tell me about it
Comment: @Umar, it's just a plot of your data & the predictions from the logistic regression model. If you're not familiar w/ LR, it finds the predicted probability that the response is condition2 for each possible input value. You can read more about LR in the threads tagged under [tag:logistic]; some of my answers that might help you would be [1](http://stats.stackexchange.com/a/30909/7290), [2](http://stats.stackexchange.com/a/34638/7290), & [3](http://stats.stackexchange.com/a/86375/7290).
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/94248/discussion-on-answer-by-gung-how-to-use-boxplots-to-find-the-point-where-values).


Como medir o tempo de execução de uma função com precisão em C++

Question: Estou realizando um trabalho da faculdade e preciso medir o tempo de execução de uma função recursiva, porém quando eu faço a medição em nanosegundos a maior parte dos meus dados volta zerado.
Teria alguma forma de fazer uma medição mais precisa em C++ ? Em anexo está como fiz utilizando a biblioteca chrono:
auto t1 = chrono::high_resolution_clock::now();
resultado = fiboRec(n);
auto t2 = chrono::high_resolution_clock::now();
auto duration = chrono::duration_cast<chrono::nanoseconds>( t2 - t1 ).count();
cout << "O numero de Fibonacci na posicao " << n << " eh "<< resultado;
cout << "O tempo gasto foi de " << duration << " nanosegundos" << endl;

Alguns dos resultados obtidos foram os seguintes:
O numero de Fibonacci na posicao 20 eh 6765 O tempo gasto foi de 0 nanosegundos
O numero de Fibonacci na posicao 20 eh 6765 O tempo gasto foi de 1000000 nanosegundos
O numero de Fibonacci na posicao 22 eh 17711 O tempo gasto foi de 0 nanosegundos
O numero de Fibonacci na posicao 24 eh 46368 O tempo gasto foi de 999800 nanosegundos
O numero de Fibonacci na posicao 26 eh 121393 O tempo gasto foi de 0 nanosegundos
O numero de Fibonacci na posicao 28 eh 317811 O tempo gasto foi de 1998600 nanosegundos

Comment: Outra coisa que o seu experimento de performance não está levando em consideração são fatores aleatórios. Num sistema multi-processado, cada núcleo de processamento só pode executar uma thread de cada vez. Isso significa que, caso o núcleo que estivesse processando o seu programa seja desviado para outra atividade (e isso é comum, evita que o outro processo "morra de fome"), o tempo em que o núcleo de processamento passou executando o _outro programa_ vai ser levado em consideração na sua contagem. Sem falar de flutuações aleatórias também não estão sendo descartadas...
Comment: Uma das maneiras mais comuns de se descartar essas flutuações do experimento que você não tem pleno controle é rodá-lo diversas e diversas vezes e obter uma média. Está linkado no meu segundo comentário coisas sobre o assunto. É importante ler a pergunta que eu disse ser relacionada e, também, os links dentro dela para se ter uma ideia melhor de onde você está caminhando ao testar performance
Comment: Já chegou a se questionar se realmente o processamento não é rápido o suficiente para não ser detectado no intervalo de tempo perceptível para a versão da biblioteca `chrono` compilada na sua máquina? Por exemplo, qual o valor de `n` para a verificação?
Comment: Relacionado: https://pt.stackoverflow.com/q/258476/64969
Comment: não sei se entendi bem, mas ai vai a saida que eu recebo do programa para alguns valores
O numero de Fibonacci na posicao 20 eh 6765 O tempo gasto foi de 0 nanosegundos O numero de Fibonacci na posicao 20 eh 6765 O tempo gasto foi de 1000000 nanosegundos
O numero de Fibonacci na posicao 22 eh 17711 O tempo gasto foi de 0 nanosegundos
O numero de Fibonacci na posicao 24 eh 46368 O tempo gasto foi de 999800 nanosegundos
O numero de Fibonacci na posicao 26 eh 121393 O tempo gasto foi de 0 nanosegundos
O numero de Fibonacci na posicao 28 eh 317811 O tempo gasto foi de 1998600 nanosegundos
Comment: um problema possivel pode ser que meu computador esta salvando a respota e isso esta afetando o tempo em que ele leva para calcular, mas não sei como resolver isso
Comment: Não há como o computador estar guardando os dados do retorno da função. Nesse caso aqui não é cache de uma resposta http. Ele só faria isso de por acaso você tivesse ensinado
Comment: Para tempos tão pequenos geralmente o *throughput* (número de operações em uma certa quantidade de tempo) é mais importante do que o tempo de cada operação individual. O *throughput* também te dá uma boa noção da média dos temos individuais (basta dividir a quantidade de tempo pela quantidade de operações). Nesse sentido vale a pena usar uma biblioteca como [Google benchmark](https://github.com/google/benchmark) para calcular o *throughput* e evitar boa parte das armadilhas mencionadas pelo Jefferson Quesado.
Answer: Se você estiver compilando para windows pode tentar o QueryPerformanceCounter, mas não acredito que consiga uma melhora tão significativa.
Então a melhor opção é executar a função N vezes e tirar uma média.
*obs: os numeros nunca vão ser absolutos, vão ser relativos a presença de outros processos disputando a RAM e o clock da CPU, que ira aumentar/diminuir de acordo com uso.


Post on a Facebook wall as Page, not as user

Question: Is it possible to post on a Facebook wall as application and not as user? As far as I understand an application is not a valid user for Facebook, but there are numerous comments about posting as Page and not as User or Application.
How can I do it using PHP Facebook API?
Answer: You need the publish_stream,manage_pages permissions. The code is something like:
<?php
// This code is just a snippet of the example.php script
// from the PHP-SDK <https://github.com/facebook/facebook-php-sdk/blob/master/examples/example.php>
require '../src/facebook.php';

// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
  'appId'  => 'app_id',
  'secret' => 'app_secret',
));

// Get User ID
$user = $facebook->getUser();

if ($user) {
  try {
    $page_id = 'page_id';
    $page_info = $facebook->api("/$page_id?fields=access_token");
    if( !empty($page_info['access_token']) ) {
        $args = array(
            'access_token'  => $page_info['access_token'],
            'message'       => "I'm a Page!"
        );
        $post_id = $facebook->api("/$page_id/feed","post",$args);
    } else {
        $permissions = $facebook->api("/me/permissions");
        if( !array_key_exists('publish_stream', $permissions['data'][0]) ||
            !array_key_exists('manage_pages', $permissions['data'][0])) {
            // We don't have one of the permissions
            // Alert the admin or ask for the permission!
            header( "Location: " . $facebook->getLoginUrl(array("scope" => "publish_stream, manage_pages")) );
        }

    }
  } catch (FacebookApiException $e) {
    error_log($e);
    $user = null;
  }
}

// Login or logout url will be needed depending on current user state.
if ($user) {
  $logoutUrl = $facebook->getLogoutUrl();
} else {
  $loginUrl = $facebook->getLoginUrl(array('scope'=>'manage_pages,publish_stream'));
}

// ... rest of your code
?>

I've written and in-depth tutorial about this: How To: Post On Facebook Page As Page Not As Admin User Using PHP-SDK
Comment: You should probably add the `offline_access` permission as well!
Comment: This still needs a user to be logged in to Facebook, right? I receive "An active access token must be used to query information about the current user." error :/ I can't tell: "Hey, Application, make a post to that wall!"? :]
Comment: @WASD42: As you can see `/me/accounts` here you need the admin of the page so that you can get from his `accounts` the page `access_token` to use it.
Comment: @vinzenzweber indeed if he doesn't want to be logged in every time then he needs *his* `access_token` to get the page's one before he can post.
Answer: You must first have a user authorize via facebook connect, and request the manage_pages permission as a part of this request.  You can use this permission to obtain a token and secret for the page in question. You then use those to authorize requests as opposed to the token/secret you received for the user.
Check out the "Page Login" section of this page for some additional info:
http://developers.facebook.com/docs/authentication/
Comment: It is necessary that the message was signed as belonging to the application (or any Facebook page), rather than the Facebook user. Imagine the following situation:

1. Application's user (not Facebook's!) perform some action in it;

2. Application adds a message about what just happened on its own Facebook wall or page.

Strictly speaking, user of application is not required to be registered on Facebook. It is only necessary that the application in Facebook had an ability to post messages on application's wall AND as application as author.


Dealing with the pages of a website in my application

Question: I have 2 pages written in JSP the first page contains:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>

Hello World!

         Page1
         Page2
         Page3

the second page should take the content of the website specified in the href attribute and
process these content then display the page with my modification ( my modification will be highlight specific words)
First, I do not know how to pass href value from one page to the second page? because I will not use form..
Second, after I pass the value of href (which is website page)How can I get the content of that page ?
Finally, How can I display the page of the website with my modification?
I used JQuery before to highlight specific words in the same document that contains the Jquery script. But when it comes to having just the link and dealing with document that is far from my application I do not know How?
Please help and thanks in advance
Answer:
First, I do not know how to pass href value from one page to the second page? because I will not use form..

That will not achieve what you are trying to achieve.
Assuming that you are doing this without a plugin, what you actually need do is write a relay servlet that will read pages from this other site, insert stuff into them and return the resulting HTML to the user's browser.
Then you modify your existing JSP so that the hrefs look something like this:
  href="http://myrelay.com?url=http://www.site.com/page1"

with proper %-escaping added.
You then need to decide how much massaging of the HTML should be done by the relay servlet itself, and how much should be done by javascript that the relay inserts into the page.

Warnings:

This is a complicated area.  There are all sorts of potential issues with session cookies, internal links, javascript security sand-boxing, browser compatibility issues and so on.
Don't try to do the work in a JSP.


Reset Model Value On Cascaded DropDown Change

Question: I have two drop downs .One to show departments and other to show sections on change of department .

    Department

        <select id="select-department" class="form-control" name="department" ng-model="myModel.department"
                ng-options="option.name for option in departments track by option.id">
            <option value=""></option>
        </select>

        Section

            <select id="select-section" class="form-control" name="section" ng-model="myModel.section"
                    ng-options="option.name for option in sections track by option.id">
                <option value=""></option>
            </select>
            {{myModel.section}}

It works fine for me . If I change department all respective section gets updated and if I select any section respective section also gets assigned to the model . But the problem is if second time I change my department value, section drop down gets updated the model value doesn't reset to blank . It still shows the last selected value .
    var app = angular.module("mainApp", []);

angular.module("mainApp").controller("cascaded", function ($scope, $filter) {

    $scope.departments = [
    {
        id: 1, name: "Dep A"
    }, {
        id: 2, name: "Dep B"
    }, {
        id: 3, name: "Dep C"
    }];

    var sections = [
    {
        id: 1, name: "Sec A", parentId: 1
    }, {
        id: 2, name: "Sec B", parentId: 2
    }, {
        id: 3, name: "Sec C", parentId: 3
    }];

    $scope.$watch("myModel.department", function (newVal) {
        if (newVal) {
            $scope.sections = $filter("filter")(sections, { parentId: newVal.id });
        }

    });

})

I want to reset my model value when section drop down gets refreshed with new data .
Comment: Can you apply it on fiddler?
Comment: below is the fiddle link .https://jsfiddle.net/opgcxLrx/
Answer: You need to assign the sections value to your mymodel.section value
 $scope.myModel.section= $scope.sections;

Because $scope.myModel.section is does not update, when you changing the department,
Your watch event should be
  $scope.$watch("myModel.department", function (newVal) {
        if (newVal) {
            $scope.sections = $filter("filter")(sections, { parentId: newVal.id });
            **$scope.myModel.section= $scope.sections;**
        }

    });

Fiddler Demo
Comment: You have assigned the complete array of sections to section model . I am not sure about this . Can you please help me to find out the root cause why my model is not updating ..
Answer: Simply put one method in ng-change of department like:
 <select id="select-department" class="form-control" name="department" ng-model="myModel.department"
                ng-options="option.name for option in departments track by option.id" ng-change="setBlank()">
            <option value=""></option>
        </select>

And in the method setBlank() set myModel.section to blank like this:
$scope.setBlank=function(){
  $scope.myModel.section='';
}

Comment: I can not set it's value to blank as I am using the same form for edit as well . So next time user comes for edit section will be set to blank when I set the selected department  . I just want to know why respective $scope is not getting updated  with new drop down data .Why it's holding the old reference where as I have new records in my drop down . I tried to use $apply but that's not working here as it throws $digets is in progress error .


insert variable into hex string

Question: There is a hex data in client :
MESSAGE = "\x16\x01\x12\x03\x1b\x14\x30\x23\x80\x00\x03\xe8\x00\x00\x00\x00"
s.sendto(MESSAGE, (UDP_IP, UDP_PORT))

and server would show :
16 01 12 03 1b 14 30 23 80 00 03 e8 00 00 00 00

but when I want to use variable and for loop to increase the last number
for i in range(times):
     i += 1
     i = format(i, '02x')
MESSAGE = "\x16\x01\x12\x03\x1b\x14\x30\x23\x80\x00\x03\xe8\x00\x00\x00"+i
s.sendto(MESSAGE, (UDP_IP, UDP_PORT))

server would show:
16 01 12 03 1b 14 30 23 80 00 03 e8 00 00 00 30 32

The "+i" become ASCII....
So how should I do to make the server show:
16 01 12 03 1b 14 30 23 80 00 03 e8 00 00 00 01
16 01 12 03 1b 14 30 23 80 00 03 e8 00 00 00 02
16 01 12 03 1b 14 30 23 80 00 03 e8 00 00 00 03
...

Thanks!
Answer: You can use a string pattern like "\x%02x" % i.
Comment: You misunderstand the question.
Comment: `\x` is for literal hex codes, it isn't processed after formatting.
Answer: Don't format the number, just create a character with that code using the chr function.
And rather than adding 1 to i in the loop, just change the range of the loop.
for i in range(1, times+1):
    i = chr(i)
    MESSAGE = "\x16\x01\x12\x03\x1b\x14\x30\x23\x80\x00\x03\xe8\x00\x00\x00"+i
    s.sendto(MESSAGE, (UDP_IP, UDP_PORT))

insert variable into hex string


Cleaning up a lock directory with bash.

Question: after some reserch I have come across these code snipts for simple locking for a script i only want to run a single time.
    if ! mkdir /tmp/myscript.lock 2>/dev/null; then
    echo "Myscript is already running." >&2
    exit 1
fi

function finish {
  rm -r /tmp/myscript.lock
}
trap finish EXIT

So part one attempts a lock dir and exits if the directory already exists.
Second bit of code is there so that if the script crashes or exits it then cleans up the directory so the script can restart.
My question is that if the script is already running and I start a second copy it will exit due to the lock file, but in the process will delete the lock directory?
Is there a way I can insure that if the script terminated due to the lock file presence it does not delete it, but if the script exits smoothly and or crahses during exicuation it cleans up the dir?
I dont want to use any other tools I am just curious how this can be achived, and i cant seem to find any examples of both used togather.
Answer: Why do you need to use trap for cleanup. Just make sure to do cleanup at the point of exit like this:
tmpFile='/tmp/myscript.lock'

if ! mkdir "$tmpFile" 2>/dev/null; then
    echo "Myscript is already running." >&2
    exit 1
fi

echo "script is running..."
# script code starts here, sleep is just an example
sleep 20

# script complete, perform cleanup
rm -rf "$tmpFile"
echo "script completed..."

Now while this script is running all subsequent invocation of this script will exit with status=1 in the first if block without removing your lock file.
Comment: Sorry the script is a continual running script, it carries out a latency check on a server every 6 0seconds and logs the results. So the scipt should never exit. Once running at start up it will just keep looping. To this was more if the the script goes bad and crashes out that it will clean up the lock.
Comment: Thinking about it though maybe I am looking at this wrong and should jsut have cron run the script every 60 seconds. not use a loop
Comment: Yes, running this check from cron is definitely better instead of a forever running script

Cleaning up a lock directory with bash.


Rails project display development style errors in production

Question: I will deployed rails project to production mode
and then rails error showing develoment style
I change production.rb file some lines
but I dont remember what change sour code
after chagne source code showing error page development error style page
I dont know why not showing 404 Or 500 error page
this is my product.rb file content
<code># -*- encoding : utf-8 -*-
Priday::Application.configure do
  # Settings specified here will take precedence over those in config/application.rb.

  # Code is not reloaded between requests.
  config.cache_classes = false

  # Eager load code on boot. This eager loads most of Rails and
  # your application in memory, allowing both thread web servers
  # and those relying on copy on write to perform better.
  # Rake tasks automatically ignore this option for performance.
  config.eager_load = false

  # Full error reports are disabled and caching is turned on.
  config.consider_all_requests_local       = true
  config.action_controller.perform_caching = false

  # Enable Rack::Cache to put a simple HTTP cache in front of your application
  # Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
  # config.action_dispatch.rack_cache = true

  # Disable Rails's static asset server (Apache or nginx will already do this).
  config.serve_static_assets = false

  # Compress JavaScripts and CSS.
  config.assets.js_compressor = :uglifier
  # config.assets.css_compressor = :sass

  # Do not fallback to assets pipeline if a precompiled asset is missed.
  config.assets.compile = false

  # Generate digests for assets URLs.
  config.assets.digest = true

  # Version of your assets, change this if you want to expire all your assets.
  config.assets.version = '1.0'

  # Specifies the header that your server uses for sending files.
  # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
  # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx

  # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
  # config.force_ssl = true

  # Set to :debug to see everything in the log.
  config.log_level = :info

  # Prepend all log lines with the following tags.
  # config.log_tags = [ :subdomain, :uuid ]

  # Use a different logger for distributed setups.
  # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)

  # Use a different cache store in production.
  # config.cache_store = :mem_cache_store

  # Enable serving of images, stylesheets, and JavaScripts from an asset server.
  # config.action_controller.asset_host = "http://assets.example.com"

  # Precompile additional assets.
  # application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
  # config.assets.precompile += %w( search.js )

  # Ignore bad email addresses and do not raise email delivery errors.
  # Set this to true and configure the email server for immediate delivery to raise delivery errors.
  # config.action_mailer.raise_delivery_errors = false

  # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
  # the I18n.default_locale when a translation can not be found).
  config.i18n.fallbacks = true

  # Send deprecation notices to registered listeners.
  config.active_support.deprecation = :notify

  # Disable automatic flushing of the log to improve performance.
  # config.autoflush_log = false

  # Use default logging formatter so that PID and timestamp are not suppressed.
  config.log_formatter = ::Logger::Formatter.new

end
</code>
help me
Comment: create a new app and compare the production.rb files
Comment: use [git](http://git-scm.com/).
Comment: @Зелёный I using git but it so difficult to me :(
Answer: Update following lines:
<code>  # Code is not reloaded between requests.
  config.cache_classes = true

  # Eager load code on boot. This eager loads most of Rails and
  # your application in memory, allowing both thread web servers
  # and those relying on copy on write to perform better.
  # Rake tasks automatically ignore this option for performance.
  config.eager_load = true

  # Full error reports are disabled and caching is turned on.
  config.consider_all_requests_local       = false
  config.action_controller.perform_caching = true
</code>