Flash text field displaying incorrect characters

Question: I've come across a strange error with a contact details form developed with Flash CS5 Prof. My keyboard layout is set up as English (UK) and pressing shift-2 gives me an ", shift-' gives me a @ in Chrome, Notepad, Word etc. In a text field on the flash form, entering shift-2 gives me @ but shift-' gives me ". I understand this is how the US keyboard is mapped out but it is confusing to my users.
How can I change the text field so that it works correctly for my keyboard layout?
Answer: There is a known bug when using wmode="transparent" or wmode="opaque" that, in some browsers (Firefox and possibly Crome), will give these kinds of errors, defaulting to US keyboard layout. As far as I know, there is no good solution for it, only quite cumbersome workarounds. If you google for flash wmode keyboard bug you will find quite a lot of info and workarounds.
Comment: Thanks! As it happens I am using wmode="transparent" to show the asset so that makes sense. I did something similar to www0z0k and replaced the characters manually.
Answer: i didn't find a way to specify a locale in Flash, however the following code does what you want:
<code>package {
    import flash.display.Sprite;
    public class NewClass extends Sprite {
        public function NewClass() {
            addChild(new TextFieldReplacingChars());
        }
    }
}

import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.TextEvent;
import flash.events.TimerEvent;
import flash.text.TextField;
import flash.utils.Timer;

class TextFieldReplacingChars extends Sprite {
    private var tf:TextField;
    private var toReplace:Object;
    private var str1:String = '';
    private var str2:String = '';
    private var pressedKeyCount: int = 0;
    private var timer:Timer;
    public function TextFieldReplacingChars() {
        tf = new TextField();
        addChild(tf);
        tf.type = 'input';
        tf.addEventListener(TextEvent.TEXT_INPUT, ontext);
        tf.addEventListener(KeyboardEvent.KEY_DOWN, onPress);
        tf.addEventListener(KeyboardEvent.KEY_UP, onRelease);
        toReplace = new Object();
        toReplace['"'] = '@';
        toReplace['@'] = '"';
        timer = new Timer(1, 1);
        timer.addEventListener(TimerEvent.TIMER_COMPLETE, updateText);
    }

    private function onRelease(e:KeyboardEvent):void {
        pressedKeyCount -= pressedKeyCount > 0 ? 1 : 0;
    }

    private function onPress(e:KeyboardEvent):void {
        pressedKeyCount += toReplace[String.fromCharCode(e.charCode)] ? 1 : 0;
    }

    private function ontext(e:TextEvent):void {
        if (toReplace[e.text] && pressedKeyCount > 0) {
            str1 = tf.text.substring(0, tf.caretIndex) + toReplace[e.text];
            str2 = tf.text.substring(tf.caretIndex, tf.text.length);
            timer.start();
        }
    }

    private function updateText(e:TimerEvent):void {
        tf.text = str1 + str2;
        tf.setSelection(str1.length, str1.length);
    }
}
</code>
Comment: this is sort of what I did in the end - thanks for your input.


How do I integrate it?

Question: Here, how to integrate it step by step?
$$I=\int\frac{x^2+x+1}{\sqrt{x^2+2x+3}} \ dx$$
Solution:
First let's Substitute, we got
$$x^2+2x+3=t^2$$
$$\implies {x}=\sqrt{t^2-2}-1$$
$$\implies dx=\frac{t}{\sqrt{t^2-2}}dt$$
Putting this back into the Integral followed by
$$I=\int\frac{x^2+2x+3-x-2}{\sqrt{x^2+2x+3}}dx$$
$$=\int\frac{t^2-(\sqrt{t^2-2}-1)-2}{\sqrt{t^2}}dx$$
$$=\int\frac{t^2-\sqrt{t^2-2}+1-2}{t}\frac{t}{\sqrt{t^2-2}}dt$$
$$=\int\frac{t^2-2+1-\sqrt{t^2-2}}{\sqrt{t^2-2}}dt$$
$$=\int\frac{t^2-2}{\sqrt{t^2-2}}+\frac{1}{\sqrt{t^2-2}}-1dt$$
$$=\int\sqrt{t^{2}-2}+\frac{1}{\sqrt{t^{2}-2}}-1dt$$
Since we all know,
$$\int\sqrt{x^2-a^2}dx=\frac{x}{2}\sqrt{x^2-a^2}-\ln\left(\left|\sqrt{x^2-a^2}+x\right|\right)$$
and $$\int\frac{1}{\sqrt{x^2-a^2}}dx=\ln(x+\sqrt{x^2-a^2})$$
& $$a^2=(\sqrt{2})^2=2$$
Now
$$I=\frac{t}{2}\sqrt{t^2-2}-\ln(t+\sqrt{t^2-2})+\ln(t+\sqrt{t^2-2}-t+C$$
$$\implies I=\frac{t}{2}\sqrt{t^2-2}-t+C$$
$$=\frac{t}{2}\sqrt{t^2}-\frac{t}{2}\sqrt{2}-t+C$$
$$=\frac{t.t}{2}-\frac{t}{2}\sqrt{2}-t+C$$
$$=\frac{t^2-t\sqrt{2}-2t}{2}+C$$
$$=\frac{t(t-\sqrt{2}-2)}{2}+C$$
$$=\frac{(t-\sqrt{2}-2)}{2}t+C$$
Now Putting back x's value , we get,
$$I=\frac{\sqrt{x^2+2x+3}-\sqrt{2}-2}{2}\sqrt{x^2+2x+3}+C$$
$$=\frac{\sqrt{x^2+2x+1+2}-\sqrt{2}-2}{2}\sqrt{x^2+2x+3}+C$$
$$=\frac{\sqrt{(x+1)^2+2}-\sqrt{2}-2}{2}\sqrt{x^2+2x+3}+C$$
$$=\frac{(x+1)+\sqrt{2}-\sqrt{2}-2}{2}\sqrt{x^2+2x+3}+C$$
$$\implies I=\frac{x-1}{2}\sqrt{x^2+2x+3}+C$$
So , The solution is:
$$\fbox{$\int\frac{x^2+x+1}{\sqrt{x^2+2x+3}}dx=(\frac{x-1}{2})\sqrt{x^2+2x+3}+C$}$$
Comment: Hi and welcome to the site! Since this is a site that encourages and helps with learning, it is best if you show your own ideas and efforts in solving the question. Can you edit your question to add your thoughts and ideas about it? Don't worry if it's wrong - that's what we're here for. [Here](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question)'s a quick guide (if nothing else, read up the part on ["avoiding no-clue questions"](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question/27933#27933))
Comment: You made no significant edit. All you did was add "dx" to the integral. Like I already said: *it is best if you show your own ideas and efforts in solving the question*. You did not show any of your own attempts.
Comment: Also, don't get discouraged by the downvote. I downvoted the question and voted to close it because at the moment, it is not up to site standards (you have shown no work you did on your own). If you edit your question so that you show what you tried and how far you got, I will not only remove the downvote, I will add an upvote. Even if the question is closed, you can still edit it, and we will vote to reopen it.
Comment: @hasnatrbm You need to show us some work you've done. Talk about where you got stuck, what you don't understand, etc. This isn't a place to just get HW answers, you gotta put in some effort too.
Comment: Write the numerator as $(x^2+2x+3)-(x+1) -1$.
Comment: Edited it, now see
Comment: On [this site](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=&cad=rja&uact=8&ved=2ahUKEwi315zU3q71AhWHRfEDHZ9tDvMQFnoECAQQAQ&url=https%3A%2F%2Fwww.integral-calculator.com%2F&usg=AOvVaw0EjIVn1VmMoq2xzNu1PmAY), it is done as you wish. Why are you asking here?
Comment: I put some effort , now help to get rest , i mean putting back integral and simplification
Comment: I'm tempted to complete the square in the denominator to force a trig substitution. That may work.
Comment: I got this $$\frac{t^2}{\sqrt{t^{2}-2}}-1-\frac{1}{\sqrt{t^{2}-2}}$$
Comment: have you tried Rene's method?  I think the aim is to get 3 integrals.  1 easily solved by sub, and the other 2 can be solved by completing the square and making trig subs, but are then standard integrals.
Comment: @Cato yeah , i know it . But I'm comfortable with this way
Answer: Here is the full solution
First let's Substitute, we got
$$x^2+2x+3=t^2$$
$$\implies {x}=\sqrt{t^2-2}-1$$
$$\implies dx=\frac{t}{\sqrt{t^2-2}}dt$$
Putting this back into the Integral followed by
$$I=\int\frac{x^2+2x+3-x-2}{\sqrt{x^2+2x+3}}dx$$
$$=\int\frac{t^2-(\sqrt{t^2-2}-1)-2}{\sqrt{t^2}}dx$$
$$=\int\frac{t^2-\sqrt{t^2-2}+1-2}{t}\frac{t}{\sqrt{t^2-2}}dt$$
$$=\int\frac{t^2-2+1-\sqrt{t^2-2}}{\sqrt{t^2-2}}dt$$
$$=\int\frac{t^2-2}{\sqrt{t^2-2}}+\frac{1}{\sqrt{t^2-2}}-1dt$$
$$=\int\sqrt{t^{2}-2}+\frac{1}{\sqrt{t^{2}-2}}-1dt$$
Since we all know,
$$\int\sqrt{x^2-a^2}dx=\frac{x}{2}\sqrt{x^2-a^2}-\ln\left(\left|\sqrt{x^2-a^2}+x\right|\right)$$
and $$\int\frac{1}{\sqrt{x^2-a^2}}dx=\ln(x+\sqrt{x^2-a^2})$$
& $$a^2=(\sqrt{2})^2=2$$
Now
$$I=\frac{t}{2}\sqrt{t^2-2}-\ln(t+\sqrt{t^2-2})+\ln(t+\sqrt{t^2-2}-t+C$$
$$\implies I=\frac{t}{2}\sqrt{t^2-2}-t+C$$
$$=\frac{t}{2}\sqrt{t^2}-\frac{t}{2}\sqrt{2}-t+C$$
$$=\frac{t.t}{2}-\frac{t}{2}\sqrt{2}-t+C$$
$$=\frac{t^2-t\sqrt{2}-2t}{2}+C$$
$$=\frac{t(t-\sqrt{2}-2)}{2}+C$$
$$=\frac{(t-\sqrt{2}-2)}{2}t+C$$
Now Putting back x's value , we get,
$$I=\frac{\sqrt{x^2+2x+3}-\sqrt{2}-2}{2}\sqrt{x^2+2x+3}+C$$
$$=\frac{\sqrt{x^2+2x+1+2}-\sqrt{2}-2}{2}\sqrt{x^2+2x+3}+C$$
$$=\frac{\sqrt{(x+1)^2+2}-\sqrt{2}-2}{2}\sqrt{x^2+2x+3}+C$$
$$=\frac{(x+1)+\sqrt{2}-\sqrt{2}-2}{2}\sqrt{x^2+2x+3}+C$$
$$\implies I=\frac{x-1}{2}\sqrt{x^2+2x+3}+C$$
So , The solution is:
$$\fbox{$\int\frac{x^2+x+1}{\sqrt{x^2+2x+3}}dx=(\frac{x-1}{2})\sqrt{x^2+2x+3}+C$}$$
Comment: Please do not use two posts to answer one question, and then copy other users' answers to [this post of yours](https://math.stackexchange.com/questions/4355890/how-this-simplification-was-done-in-the-integral?noredirect=1).  That amounts to plagiarism.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Comment: Please do not duplicate a question with the same answer.  And do not vandalize your question.
Comment: @amwhy ok done . I'm new.

How do I integrate it?


Most powerful hypothesis test for given discrete distribution

Question: I have two discrete distributions. The second one is a simple distribution where all values from 1 to 6 (think rolling dice) have equal probability (so, that must be $\frac{1}{6}$). The first one is defined like this: $f(6) = 0.18$, $f(5) = 0.14$, $\ f(4) = f(3) = f(2) = f(1) = 0.17$. There are two observations. I need to find the most powerful test for a given significance level (0.0196, so this clearly hints at something like getting two 5s in a row, since $f(5)^2 = 0.0196$).
I only know how to apply the Neyman-Pearson Lemma. First I need to get the likelihood ratio. I can't even do this because I don't understand how to construct the joint probability mass function for the first distribution since it's not a closed-form expression. Maybe it's supposed to be a sort of a multinomial distribution? But the number of observations (2) is less than the number of possible values (6), so how would this work...
Then, I need to construct a test based on this likelihood ratio:
$$
\phi(x_1, x_2) =
\begin{cases}
1, \lambda(x_1, x_2) > c \\ 0, \lambda(x_1, x_2) < c \\ \alpha, \lambda(x_1, x_2) = c
\end{cases}
$$
And I do not have a good grasp on how to derive $\alpha$ and $c$. For $c$ I need to construct an inequality based on the likelihood ratio and use the significance level somehow, but I don't really understand how it's supposed to be done.
Answer: If you have not confused anything and the distribution corresponding to the main hypothesis is really symmetric, and the distribution corresponding to the alternative hypothesis is asymmetric, then the test will be the following.
For a single observation,
$$
\lambda(x_1)=\frac{f_2(x_1)}{f_1(x_1)}=\begin{cases}6\cdot 0.18, & x_1=6 \cr 6\cdot 0.14, & x_1=5, \cr 6\cdot 0.17, & x_1=1,2,3,4\end{cases}
$$
And for two observations we have
$$
\lambda(x_1,x_2)=\frac{f_2(x_1)f_2(x_2)}{f_1(x_1)f_1(x_2)} $$
$$=\begin{cases}36\cdot 0.18^2, & x_1=x_2=6 \cr 36\cdot 0.18\cdot 0.14, & x_1=6,x_2=5 \text{ or } x_1=5,x_2=6 \cr 36\cdot 0.14^2, & x_1=x_2=5, \cr 36\cdot 0.18\cdot 0.17, & x_1=6, x_2\in\{1,2,3,4\} \text{ or } x_2=6, x_1\in\{1,2,3,4\} \cr  36\cdot 0.17\cdot 0.14, & x_1=5, x_2\in\{1,2,3,4\} \text{ or } x_2=5, x_1\in\{1,2,3,4\}\cr 36\cdot 0.17^2, & x_1, x_2\in\{1,2,3,4\}\end{cases}
$$
The greatest value of $\lambda(x_1,x_2)$ is $36\cdot 0.18^2$ if two sixes observed. If we consider critical region as $x_1=x_2=6$, then the significance level of this MP test is
$$
\mathbb P_1 (x_1=x_2=6)=\frac{1}{36}=0.02(7) > 0.0196.
$$
So, we should consider randomized test where $\alpha$ is such that the significance level of the test is exactly $0.0196$:
$$
\mathbb P_1(\lambda(x_1,x_2)>36\cdot 0.18^2)+\alpha\cdot \mathbb P_1(\lambda(x_1,x_2)=36\cdot 0.18^2) = 0+\alpha\cdot \frac{1}{36} = 0.0196
$$
So, $\alpha=36\cdot 0.0196=0.7056$
Finally, we get most powerful test for a significance level $0.0196$
$$
\phi(x_1,x_2)=\begin{cases} 0.7056 & x_1=x_2=6\cr 0 & \text{ other cases}\end{cases}
$$
And I really sure that you swapped null and alternative hypotheses. In this case swap numerator and denominator of $\lambda(x_1,x_2)$ and you'll get that the largest value will be at $x_1=x_2=5$. If we take it as critical region then
$$
\mathbb P_1(x_1=x_2=5)=0.0196
$$
as required. Note that I swap numbers of distributions and now the first one is asymmetric. Here $\alpha$ in $\phi(x_1,x_2)$ is zero and $c$ is any number lies strictly between $\frac{1}{36\cdot 0.14^2}$ and $\frac{1}{36\cdot 0.14\cdot 0.17}$. The last value is the next greatest value of $\lambda(x_1,x_2)$.


Attempt to present  on  which is already presenting  in swift

Question: Ok so I'm adding a please wait popup for the operation that takes longer than usual in my ios app.
I have a segue from my ViewController to TabController and when I invoke it like this:
self.performSegueWithIdentifier("openMainApp", sender: self)

everything works fine.
But when I surround it with:
let alert = UIAlertController(title: nil, message: "Please wait...", preferredStyle: .Alert)

alert.view.tintColor = UIColor.blackColor()
let loadingIndicator: UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRectMake(10, 5, 50, 50)) as UIActivityIndicatorView
loadingIndicator.hidesWhenStopped = true
loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
loadingIndicator.startAnimating();

alert.view.addSubview(loadingIndicator)
presentViewController(alert, animated: true, completion: nil)

    self.performSegueWithIdentifier("openMainApp", sender: self)

dismissViewControllerAnimated(false, completion: nil)

then I'm getting a warning:
Warning: Attempt to present <app.TabController: 0x7ff6dc00bd40>
on <app.ViewController: 0x7ff6d9cf6600> which is already presenting
<UIAlertController: 0x7ff6d9d78530>

how can I skip this warning?
Answer: While the source for this warning is still a mystery to me, there is a way to skip the warning.

Delete the segue from storyboard
Give storyboard ID to your view controller, something like:

Replace
self.performSegueWithIdentifier("openMainApp", sender: self)
with
let viewController: UIViewController =
  self.storyboard!.instantiateViewControllerWithIdentifier("MainScene")
self.presentViewController(viewController, animated: true, completion: nil)

Answer: Idan's answer may work, but I would recommend using something like MBProgressHud or SVProgressHud. It looks like swift doesn't like it when you perform a segue before dismissing the alert controller because it is it's own view controller. Here is how to implement MBProgressHud. Here is how to implement SVProgressHud. If you don't want to use CocoaPods, you just download the zip file and add the .m and .h file into your project.


How should I decide how many decimal places to use in a confidence interval?

Question: My T table look up is to 3 decimal places ( or less is I am estimating for n=39 say)
Yet my margin of error can be calculated to as many decimal places as I choose.
How should I decide how many decimal places to use in the confidence interval ?
$\bar{x} \pm t_{\frac{\alpha}{2},n-1} \frac{S}{\sqrt{n}}$
Answer: It's usually more related to the number of significant figures than decimal places.
https://en.wikipedia.org/wiki/Significant_figures
A table that shows a probability to say three decimal places (common with z-tables) may have fewer than three significant figures in the tail. Many tables also only give the t-values to about 3 figures (perhaps slightly less if anything, since the t's/z's typically only range from 0 to about 3, though you may gain some of that back with suitable use of interpolation).
In your case your linked table gives t-values for specified tail areas; which is fine, the tabulated values should be accurate to 3 or 4 figures. [Unless, that is, you're after an accurate p-value, in which case, it's not much good to you. I should also add a note of caution; it doesn't hurt to double check multiple values in the table because I've found a few tables with errors.]
In the final values you report, you should generally avoid giving more significant figures than the least accurate one in the calculations performed (so if the data was available to 5 significant figures and the table to 3 significant figures, generally you wouldn't report your final interval ends to more than 3 significant figures since the answers are likely no more accurate than that, and sometimes possibly less).
However, intermediate calculations should be carried out to more figures, since premature rounding off can result in dramatic loss of accuracy. I see this particular error made very, very often and sometimes the loss of accuracy from premature rounding is substantial -- I have seen reported answers that had only about a single digit of accuracy.
In general, where you have any option, don't use tables at all, but use software calculations that typically tend to have many more figures of accuracy, though some may be based on approximations with only a few figures of accuracy, so sometimes you need to investigate what calculation was used for some implementations. Indeed some packages have not updated some of their test calculations since the late 1960s even though better approximations may have been around for decades. Sometimes the fact that the calculations only work up to some very small sample size like n=50 - with the limit coming from some early paper - is the only obvious clue that those responsible have not looked for any more recent calculations.
Comment: @whuber Indeed you can; I debated addressing that issue - I even began a paragraph on the situation with binned values - but given that the considerations involved are not normally addressed with non-mathematical beginners, I decided to avoid the details in what I realized could end up being longer than my posted answer. I appreciate you raising them though, because otherwise I could leave an incorrect impression more generally.
Comment: I wonder... .  Suppose the data have only 1 s.f. but there are lots of them, $n.$  *Assuming* you use an accurate CI procedure (that accounts for the loss of variance from the rounding or truncation), why can't you obtain both an estimate for the mean (say) and a CI with more s.f.? The increased decimal precision in those statistics should be about half the common log of $n.$ *E.g.,* a typical CI for a Normal mean based on $10^4$ single-digit data merits reporting with *at least* 3 s.f.


How to integrate trading view charting library in my website

Question: Iam  building a website for bitcoin exchange. I want to use trading view charting library I extracted it in my workspace. I want to know how to give my own datafeed. Which format should datafeed file be in (like php,js,json) ?
var _datafeed = new Datafeeds.UDFCompatibleDatafeed("http://localhost/workspace/charting");
    //var _datafeed = new Datafeeds.UDFCompatibleDatafeed("https://demo_feed.tradingview.com");

    TradingView.onready(function () {
        var widget = window.tvWidget = new TradingView.widget({
            debug: true, // uncomment this line to see Library errors and warnings in the console
            fullscreen: false,
            symbol: 'A',
            interval: 'D',
            timezone: "America/New_York",
            container_id: "tv_chart_container",
            locale: getParameterByName('lang') || "en",
            datafeed: _datafeed,
            library_path: "charting_library/",
        });
    });

In above code the charts are plotted with demo link. when I change it to my path, I get 'invalid symbol' error. Where do I specify config and symbol_info and what's their file format? Iam a total newbie. Please help .
Any suggestion to move in the right way is appreciated. I am STUCK!!
Screen shot of error message
Comment: Please tell me how to improve my question when you downvote
Answer: You should write a php file and .htaccess in a folder within charting library. htaccess should rewrite all requests to that folder to that php file. Then in that php file echo results in UDF format.
UDF format and required api calls with sample result
UPDATE: Trading view charting library is a private repository. so you need to agree to their terms to get access the library and wiki pages on github.
Comment: then link that you have given, doesn't help me anymore, becuase I could not understand that, could you please give me any code leve examples to apply that. Thanks in advance
Comment: are you sure we have to register to access the instruction on using the charts ?
Comment: @Afsanefda I had to register to access the library files from Github. Its always better to register to ask for help/ raise bugs on GitHub also.
Comment: Unfortunately I live in their restrictions area (Iran)  I asked for the repo invitation but they refused to grant me the access. Do you have the repo ? @SMJ
Answer: According with this page https://www.tradingview.com/widget/advanced-chart/ you do not need add any libraries, just to add the following references:

Two nested divs:

And set it with a script like this:

Comment: The [TradingView Widget is different from the Charting Library](https://github.com/tradingview/charting_library/wiki/Frequently-Asked-Questions#other-questions) (link requires GitHub repo membership). The widget comes with data from TradingView but doesn't have (documented) methods. The OP is asking about Charting Library, which requires supplying a data feed.
Answer: Try this one for node API, it is working well:
https://github.com/bergusman/tradingview-udf-binance-node
For front end you need tradingview's git repository access.


How to refresh a div without reloading the whole page

Question: I have an ASP.Net Core MVC project and in it I implemented a DateTime, and I need that when I click on the button it reloads the div with the new date that I inserted, but without loading the entire page, just that div.
Comment: Hi @essrrom, I have share a simple demo below. It is better for you to share your code for more efficient help.
Answer:
I need that when I click on the button it reloads the div with the new date that I inserted, but without loading the entire page, just that div.

You need use AJAX to achieve your requirement.
Here is a simple demo about how to update the div without page reloading:
View

    <input type="datetime-local" id="MyDate" />

<input type="button" onclick="ChangeDatetime()" value="Change" />
@section Scripts
{

}

Controller
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
    public string Update(DateTime MyDate)
    {
        MyDate = DateTime.Now;   //modify the datetime here
        //the browser only accepts yyyy-MM-ddThh:mm format for `datetime-local` type
        return MyDate.ToString("yyyy-MM-ddThh:mm");
    }
}


Download a file from sas token

Question: I have created a storage_account with a container named data.
In that container I have a single .zip file.
I'm generating an Account Key SAS Token with Read permission directly on the  data container :

The Blob SAS URL looks like this :
https://<STORAGE_ACCOUNT>.blob.core.windows.net/data?sp=r&st=2022-06-06T15:23:31Z&se=2022-06-06T23:23:31Z&spr=https&sv=2020-08-04&sr=c&sig=<SIGNATURE>
How am I supposed to download my zip file from that URI?
I'm always running into some Authorization error whereas I though having the link was enough and unfortunately documentation didn't help me to figure out what's wrong.
I would like to download the file from a HTTP call, not using az copy or powershell.
Answer: from your description and the URL you provided, I guess the issue is that you didn't reference the name of the zip file in the URL
so instead of
https://<STORAGE_ACCOUNT>.blob.core.windows.net/data?sp=r&st=2022-06-06T15:23:31Z&se=2022-06-06T23:23:31Z&spr=https&sv=2020-08-04&sr=c&sig=<SIGNATURE>

try
https://<STORAGE_ACCOUNT>.blob.core.windows.net/data/zipName?sp=r&st=2022-06-06T15:23:31Z&se=2022-06-06T23:23:31Z&spr=https&sv=2020-08-04&sr=c&sig=<SIGNATURE>

Comment: I can't believe that was just that ahah. Thanks !
Comment: Happy to help, if you find my answer useful, vote it up, so other people can find it easily

Download a file from sas token


Prove that $P_1P_2P_3=2rR^2$.

Question:
Let $I$ be the incentre of $\Delta ABC$ and let $P_1$, $P_2$, and $P_3$ be the circumradii of $\Delta BIC$, $\Delta CIA$, and $\Delta AIB$, respectively (i.e., $P_1 = O_1B$, $P_2 = O_2C$, $P_3=O_3A$, where $O_1$, $O_2$, and $O_3$ are circumcentres of $\Delta BIC$, $\Delta CIA$, and $\Delta AIB$, respectively).  Let the inradius of $\Delta ABC$ be $r$ and let the circumradius of $ \Delta ABC$ be $R$.
  Prove that $P_1P_2P_3=2rR^2$.
Comment: Please define all objects, even if they are introduced in the picture. (What are $O1$, $O2$, $O3$?) What are the own efforts? You may use a (central) dot in latex as `\cdot` instead of the bolder star. Indices may be accessed as `P_1` for $P_1$, etc.
Answer: In fact, $O_1,O_2,O_3$ are the second intersection points of $AI,BI,CI$ respectively and the circumcircle $(ABC)$. Thus, you may readily obtain that $$p_1=2R\sin \frac{A}{2},~~~p_2=2R\sin \frac{B}{2},~~~p_3=2R\sin \frac{A}{2}.$$
Moreover, I guess you must know the formula on the incircle radius that $$r=4R\sin\frac{A}{2}\sin\frac{B}{2}\sin\frac{C}{2}.$$
Therefore, $$p_1p_2p_3=2\cdot4R\sin\frac{A}{2}\sin\frac{B}{2}\sin\frac{C}{2}\cdot R^2=2rR^2.$$
Answer: Let $i$ denote the inversion about the incircle of the triangle $ABC$.  Write $D$, $E$, and $F$ for $i(A)$, $i(B)$, and $i(C)$, respectively.  Then, the lines $EF$, $FD$, and $DE$ are the images of the circumcircles of the triangles $BIC$, $CIA$, and $AIB$, respectively.  The point $I$ is the orthocenter of the triangle $DEF$.  Let $X$, $Y$, and $Z$ denote the feet of the altitudes from $D$, $E$, and $F$, respectively, of the triangle $DEF$.

We have $$P_1=O_1I=\frac{r^2}{2\,IX}\,,$$
and similarly,
$$P_2=O_2I=\frac{r^2}{2\,IY}\text{ and }P_3=O_3I=\frac{r^2}{2\,IZ}\,.$$
That is, to prove that $P_1\cdot P_2\cdot P_3=2\,r\,R^2$, we need to prove that
$$IX\cdot IY\cdot IZ=\frac{r^5}{16\,R^2}\,.$$
Write $\alpha:=\dfrac12\,\angle BAC$, $\beta:=\dfrac12\,\angle ABC$, and $\gamma:=\dfrac12\,\angle BCA$.  Note that $IA=\dfrac{r}{\sin(\alpha)}$. That is,
$$ID=\frac{r^2}{IA}=r\,\sin(\alpha)\,.$$
Similarly, $IE=r\,\sin(\beta)$ and $IF=r\,\sin(\gamma)$.  We have $\angle IEX=\gamma$, $\angle IFX=\alpha$, and $\angle IDX=\beta$, whence
$$IX=IE\,\sin(\gamma)=r\,\sin(\beta)\,\sin(\gamma)\,,$$
$$IY=IF\,\sin(\alpha)=r\,\sin(\gamma)\,\sin(\alpha)\,,$$
and
$$IZ=ID\,\sin(\beta)=r\,\sin(\alpha)\,\sin(\beta)\,.$$
Consequently,
$$IX\cdot IY\cdot IZ=r^3\,\sin^2(\alpha)\,\sin^2(\beta)\,\sin^2(\gamma)\,.$$
It is well known that $r=4\,R\,\sin(\alpha)\,\sin(\beta)\,\sin(\gamma)$.   Ergo,
$IX\cdot IY\cdot IZ=\dfrac{r^5}{16\,R^2}$, as required.
P.S.:  My solution is overly complicated, but I will leave it like this.  In fact, it can be proven directly (without inversion) via trigonometry that
$$P_1=O_1I=\frac{r}{2\,\sin(\beta)\,\sin(\gamma)}\,,$$
$$P_2=O_2I=\frac{r}{2\,\sin(\gamma)\,\sin(\alpha)}\,,$$
and
$$P_3=O_3I=\frac{r}{2\,\sin(\alpha)\,\sin(\beta)}\,.$$

Prove that $P_1P_2P_3=2rR^2$.


Python - Sort a list of lists but only keep last item in each sublist

Question: I have a list of items that I need to sort according to a given score I give it. The code looks something like this:
original_list = [item_1, item_2, item_3]
# ... Here I score the list in a separate function to get a score for each item ...
scored_list = [[35, item_1], [45, item_2], [1, item_3]]
scored_list.sort()
sorted_list = [item[1] for item in scored_list]

So I have a list of items, score each item, sort the list according to the score, and then remove the score variable to keep only the items.
Is this the most efficient way of doing this kind of operation, or are there simpler ways to obtain the same result?
Comment: Does this answer your question? [Sorting list based on values from another list](https://stackoverflow.com/questions/6618515/sorting-list-based-on-values-from-another-list)
Comment: https://stackoverflow.com/questions/13188476/get-the-nth-element-from-the-inner-list-of-a-list-of-lists-in-python has some pointers to this answer
Answer: Efficiency-wise I doubt you can do better. If you are concerned with the number of lines, you can move the sort to inside the comprehension:
scored_list = [[35, item_1], [45, item_2], [1, item_3]]
sorted_list = [item[1] for item in sorted(scored_list)]

But in terms of speed you'll likely not notice a difference. In fact this may be a bit slower than your approach because in-place sort() might be a bit faster as it does not need to make a copy but depending on your data that is negligible.
So I'd say your approach is perfectly fine. If you want to make it more concise, you can use sorted().
Comment: Thank you Bram, I am more for readability than minimizing number of lines at the moment so if it is the same I will keep my original code with comments. Thank you though for the answer.
Answer: That's the right way, but you can use list comprehensions:
scored_list = [i[1] for i in sorted(scored_list, key=lambda s: s[0])]

Comment: Thanks, that is nice looking!
Answer: For disentangling the scores and the items, you can use the:
the_scores, the_items = zip(*scored_list)

For efficiency, there are not much that you can do. Actually, I think that there is not something else that you can do.
Comment: Do you have any proof that that is faster than extracting the second item only with a list comprehension? It might, but I am doubtful.
Comment: This answer is about the "simpler" part. I do not have considered if it is faster or not.
Answer: You could use the key parameter in the sorted() function when you sort the array. You can pass in a lambda function that returns a list of scores using your scoring function as the key.
    def calcScore(x):
       # Calculate score here
       pass
    original_list = [item_1, item_2, item_3].
    sorted_list = sorted(original_list, key=lambda x: [calcScore(x) for x in original_list])

Comment: I doubt this is the right way to use `key`... Maybe you meant `key=calcScore`?


Configuring nginx to serve

Question: I have a rails apps hosted in my aws server and using nginx as a proxy server. In the same instance I am running an api server on port 3004. In nignx conf file I made some change so that the contents from the api server can be accessed via domain.com/api while my rails app can be access via domain.com .
When I access domain.com/api I will get a list of endpoints that I can access.But the issue is I have to access those enpoints like this domain/apicategories. It is incorrect. I have to access them like this domain/api/categories. Below is my nignx conf file
    upstream postgrest {
      server localhost:3004;
      keepalive 64;
    }

    server {
      listen 80;
      server_name localhost;

      root /home/deploy/test/current/public;

      try_files $uri/index.html $uri @app;
      location /api {
         default_type  application/json;
         proxy_hide_header Content-Location;
         add_header Content-Location  /api$upstream_http_content_location;
         proxy_set_header  Connection "";
         proxy_http_version 1.1;
         proxy_pass http://postgrest/;

   }

Comment: I guess you're missing a slash somewhere. Try adding one after "location /api" at a guess, but other places will be worth trying too. Report back results by editing your question to add more information. Your question is not as clear as it could be.
Comment: Hi Tim, thank you. I added a location /api/ in the conf file and it is working
Answer: As Tim helped you with comments, you were missing a trailing slash / in your location block.
Excerpt from NGINX Official Documentation :

If a location is defined by a prefix string that ends with the slash
  character, and requests are processed by one of proxy_pass,
  fastcgi_pass, uwsgi_pass, scgi_pass, or memcached_pass, then the
  special processing is performed. In response to a request with URI
  equal to this string, but without the trailing slash, a permanent
  redirect with the code 301 will be returned to the requested URI with
  the slash appended. If this is not desired, an exact match of the URI
  and location could be defined like this:

So these two are not equal in this case :
location /api/ {
    ...
}

IS NOT EQUAL WITH

location /api {
    ...
}

But if you want to avoid such mistakes in cases that you need to match yourDomain/api or yourDomain/api/ as full strings, you can use the following regex matching :
location ~ ^/api/?$ {
    ...
}

Tilde ~ symbol will enable regex matching, and /? will be permitting one or zero slash / symbols before the end of input.
Comment: Great that someone could answer the why, I learned something too :)
Comment: @Tim I'm glad to hear that, good luck mate.

Configuring nginx to serve


Using an Interpretation, Prove Two Equations Are Not Equivalent

Question: I have been working on this problem for hours and cant seem to understand how to go about doing it. The question is to prove that

Is not equivalent to

by giving an interpretation which is a model for one, but not for the other.
I don't see how simply switching the position of the existential quantifier makes a difference. Can someone please give me some pointers? Thank you.
Comment: To see why makes a difference think on the $\delta-\varepsilon$ definition of limit.
Comment: If you think of quantifiers more dynamically it becomes obvious why.
Comment: So we have the difference between "...exists $x$ such that for all $y$..." and "for all $y$ there exists $x$ such that..."  Consider what these statements mean if you pick a specific value for $x$ (for example).  Can you see what effect the order has?  Consider also the synonymous "... for all $y$ ..." and "... for every $y$ ..."
Comment: I am reading the first in English as "for every element w, there exists at least one element x such that for any combination of two other elements y and z, q(w,x,y,z) is true" and similarly for the second. I mentally understand the difference, but I cannot see how to create a relation q to make this matter.
Comment: Complementing abiessu's comment: let $q(w,,x,y,z)$ mean something in which $w$ and $z$ do not occur.
Answer: Hint: Let $g(w,x,y,z)$ hold if $x\lt y$, domain the reals.
Comment: Will mark as answer. Thank you for simplifying the scope of the question. I was confused by assuming that the relation must somehow incorporate all of the variables.
Comment: You can decorate it with mention of $w$ and $z$ if you really want to, by using say $(x\lt y)\land (w=z)$. But you certainly do not need to.


Good approximation for $\binom{N}{\frac{N}{2}}$

Question: $$\log_2\binom{N}{\frac{N}{2}}\approx N\log_2N - 2(N-\frac{N}{2})\log_2(N-\frac{N}{2})=N\log_2N - 2\frac{N}{2}\log_2(\frac{N}{2})$$
$$=N\log_2N - {N}{}\log_2({N}) + {N}{}=N$$
$$\implies\binom{N}{\frac{N}{2}}\approx 2^{N}$$
Is my approximation correct?
Or the following one correct?
$$\begin{align}
\log {n\choose m} & \approx (n+\tfrac{1}{2})\log n - (m+\tfrac{1}{2})\log m - (n-m+\tfrac{1}{2})\log (n-m) - \tfrac{1}{2}\log 2\pi
\end{align}$$
$$\begin{align}
\log {n\choose \frac{n}{2}} & \approx (n+\tfrac{1}{2})\log n - (\frac{n}{2}+\tfrac{1}{2})\log \frac{n}{2} - (n-\frac{n}{2}+\tfrac{1}{2})\log (n-\frac{n}{2}) - \tfrac{1}{2}\log 2\pi\end{align}$$
$$\begin{align}\approx(n+\tfrac{1}{2})\log n - (\frac{n}{2}+\tfrac{1}{2})\log \frac{n}{2} - (\frac{n}{2}+\tfrac{1}{2})\log (\frac{n}{2}) - \tfrac{1}{2}\log 2\pi\end{align}$$
$$\begin{align}=(n+\tfrac{1}{2})\log n - (n+1)\log \frac{n}{2}=(n+\tfrac{1}{2})\log n - (n+1)\log {n} + (n+1) - \tfrac{1}{2}\log 2\pi
\end{align}$$
$$\begin{align}=-\tfrac{1}{2}\log n + (n+1) - \tfrac{1}{2}\log 2\pi
\end{align}$$
$$\implies{n\choose \frac{n}{2}}\approx\frac{2^{n+1}}{\sqrt{\pi n}}$$
What is a reasonable approximation?
Comment: See http://en.wikipedia.org/wiki/Central_binomial_coefficient for some asymptotics
Comment: That's much too large.
Comment: You can't use an approximation of the log to get an approximation, because $a_n \sim b_n$ doesn't imply $e^{a_n} \sim e^{b_n}$.
Comment: Worth also looking at [Catalan Numbers](http://en.wikipedia.org/wiki/Catalan_number) approximation.
Comment: Related: https://math.stackexchange.com/questions/58560/elementary-central-binomial-coefficient-estimates
Answer: Wikipedia gives the approximation
$$\frac{2^{n+\frac12}}{\sqrt{\pi n}}$$
This comes from Stirling's formula, and the quotient of this by the binomial coefficient approaches 1 as $n\to\infty$.
Here is the article.
Comment: Always good to include a link when referencing Wikipedia.
Comment: @ThomasAndrews added. I went to the link on my computer and I'm writing the answer on my phone, which is pretty hard. Only now did I realize that I could've gone to the site on my phone and copied and pasted the link. Live and learn.


how do I call a rest server?

Question: I have a Drupal 8 site with a form that I have to submit to another server using the REST protocol.
I have the following information.

server address
server port
form data

I want to submit that information to the other server.
Is there any function I can use in Drupal 8?
Answer: Because of the new Proudly Found Elsewhere standard, Drupal doesn't have its own client.
It does however include Guzzle, a well respected library. You can use that to make your REST calls, or of course include and use another library if you wish.
You can get to the Guzzle client in a default Drupal 8 install through the http_client service:
<code>$httpClient = \Drupal::httpClient();
</code>
And the docs for Guzzle are here.

how do I call a rest server?


Unit test for method that calls other method of different class

Question: I want to unit test a method using mockito, which calls other other method of different class and that other method contain some shared preference operation .
This is the method I want to test
public boolean isPersonAvailable(Context context) {
    Person person = new Person();
    return person.loadPerson(context)!= null;
}

Here is the structure of my Person class and that Person class depends on another method of another class
class Person{
    public  Person loadPerson(Context context) {
        SharedPreferenceProvider sp = new SharedPreferenceProvider();
        sp.read(context,"any key");
        return new User;
    }
}

Here is the structure of my SharedPreferenceProvider class
class SharedPreferenceProvider{

       public  String read(Context context, String key) {
        SharedPreferences preference = context.getSharedPreferences("AppID", AppConstants.SAVE_MODE);
        return preference.getString(key, EMPTY_STRING);
    }

}

How can unit test such method which has so many dependency ?
Answer: Your problem here is that your method under test does new Person().
Basically that impacts your ability to do reasonable unit testing. You can either work around that design deficiency by using PowerMock(ito) or JMockit, or you improve your design by avoiding that call. In other words: read about dependency injection. As that would allow you to already have some Person object available. And then you could simply mock that object in advance, and have its method return whatever you need for reasonable testing.
Your code under test has only one dependency, to a Person object. Get rid of that (by enabling your code to interact with mocked Person object), and your problem is gone.
Answer: With unit-testing you try to find bugs in the isolated code.  The method isPersonAvailable, however, consists purely of interactions with other classes like Context and Person.  If there are bugs in this method, they will lie on the level of interactions with these other classes: Are you calling the right constructor of Person?  Is a return value of null from person.loadPerson really an indication that the person is not available, or is this signaled in a different way?
You will never find such interaction bugs with mocks: If you have misunderstood the way the other classes work, you will implement the mocks according to your own wrong understanding.  Therefore, a method like isPersonAvailable should be tested with integration testing rather than with unit-testing.
That said, even if it is not of much relevance for this particular method, the recommendation to learn about "dependency injection" is certainly good.  You may also find it valuable to look for "inversion of control".


PHP: Symlink in public_html cannot be accessed through browser

Question: I have tester.php file which I want to run on the browser and I have created symlink to it in my public_html folder, but still when I try to run it, its not working and gives me following error message.
Access forbidden!

You don't have permission to access the requested object. It is either read-protected or not readable by the server.

If you think this is a server error, please contact the webmaster.
Error 403
web.upc03.dev.com
Sun Apr 4 22:41:23 2010
Apache

I am not sure as to why am I getting this error message, I have check all file permissions settings and it seems to be fine.
My File permissions settings are:
lrwxrwxrwx  for tester.php

Is there something that should be done other way or is this not the proper approach ?
Answer: The FollowSymlinks option needs to be enabled for that location/directory.
Comment: How can this be enabled. Actually we just changed our development server and I just did `scp` to copy all files and folder from one dev server to another dev server. Is there any internal settings which needs to be set for the implementations. Would really appreciate if you can provide some details as am not sure how to activate it.
Comment: rachel it isn't php internal setting but apache's settings, check apache conf.


EntityFieldQuery BETWEEN condition is not working

Question: <code>$query->join('field_data_field_amountpaid', 'amt', 'n.nid = amt.entity_id and amt.field_amountpaid_value >=500 and amt.field_amountpaid_value <=5000 '); //JOIN node with Body
</code>
This is my normal query how can I call this in entity query?
I tried this way;
<code>$query->fieldCondition('field_amountpaid', 'value', array('501','5000'),'BETWEEN');
</code>
But it's not working. Any idea?
Comment: `BETWEEN` statements work fine for me in `n `EntityFieldQuery`, are you sure the data in the database is what you expect it to be?
Answer: I had the same problem than you, and was able to fix it. The real problem here is that the documentation does not provide any example.
As it was already mentioned, the BETWEEN will only work if you are using the same data types that are being stored.
In my case, the field i was searching was a date field that has a specific format. So instead of passing a timestamp i had to format that date and then pass it.
<code>//something like
start_date = (isset($_GET['startDate'])) ?  date('Y-m-d/T00:00:00',strtotime($_GET['startDate'])) : null;
        $end_date = (isset($_GET['endDate'])) ? date('Y-m-d/T00:00:00',strtotime($_GET['endDate'])) : null;

        if (isset($start_date) && isset($end_date)) {
           $query->fieldCondition('field_publication_date', 'value', array($start_date,$end_date), 'BETWEEN');
        }
</code>
Hope this helps you!
Answer: Try also different type format like this: array(501,5000).
Try also with small letters 'between'.
Make sure there is some data in that table.
Answer: <code>'BETWEEN': This operator expects $value to be an array of two literals of the same type as the column</code>.
DId you make sure that your "value" and your array types were the same?


What's the most defensive way to loop through lines in a file with Perl?

Question: I usually loop through lines in a file using the following code:
open my $fh, '<', $file or die "Could not open file $file for reading: $!\n";
while ( my $line = <$fh> ) {
  ...
}

However, in answering another question, Evan Carroll edited my answer, changing my while statement to:
while ( defined( my $line = <$fh> ) ) {
  ...
}

His rationale was that if you have a line that's 0 (it'd have to be the last line, else it would have a carriage return) then your while would exit prematurely if you used my statement ($line would be set to "0", and the return value from the assignment would thus also be "0" which gets evaluated to false). If you check for defined-ness, then you don't run into this problem. It makes perfect sense.
So I tried it. I created a textfile whose last line is 0 with no carriage return on it. I ran it through my loop and the loop did not exit prematurely.
I then thought, "Aha, maybe the value isn't actually 0, maybe there's something else there that's screwing things up!" So I used Dump() from Devel::Peek and this is what it gave me:
SV = PV(0x635088) at 0x92f0e8
  REFCNT = 1
  FLAGS = (PADMY,POK,pPOK)
  PV = 0X962600 "0"\0
  CUR = 1
  LEN = 80

That seems to tell me that the value is actually the string "0", as I get a similar result if I call Dump() on a scalar I've explicitly set to "0" (the only difference is in the LEN field -- from the file LEN is 80, whereas from the scalar LEN is 8).
So what's the deal? Why doesn't my while() loop exit prematurely if I pass it a line that's only "0" with no carriage return? Is Evan's loop actually more defensive, or does Perl do something crazy internally that means you don't need to worry about these things and while() actually only does exit when you hit eof?
Comment: This is why I wouldn't edit the meaning of someone's response (I only fix obvious typos). Add a comment instead if you think something is missing or could be improved upon.  And kudos to you for investigating the internals!
Comment: If you're looking to write defensive code, use a [tank](http://en.wikipedia.org/wiki/Tank).
Answer: Because
 while (my $line = <$fh>) { ... }

actually compiles down to
 while (defined( my $line = <$fh> ) ) { ... }

It may have been necessary in a very old version of perl, but not any more!  You can see this from running B::Deparse on your script:
>perl -MO=Deparse
open my $fh, '<', $file or die "Could not open file $file for reading: $!\n";
while ( my $line = <$fh> ) {
  ...
}

^D
die "Could not open file $file for reading: $!\n" unless open my $fh, '<', $file;
while (defined(my $line = <$fh>)) {
    do {
        die 'Unimplemented'
    };
}
- syntax OK

So you're already good to go!
Comment: @j_random_hacker, since perl5 does not have a formal language spec, the behavior of the interpreter IS the definative answer
Comment: No -1, because I agree `B::Deparse` is useful for exploring what Perl is doing when you're stumped, but IMHO using it to "answer" a question like this is not... right.  It only tells you what Perl will do in the handful of specific cases that you try it on, it doesn't tell you anything about the general conditions under which this behaviour will occur.  Only the language spec can tell you that.
Comment: @j_random_hacker: In perl's defense, perl6 puts an end to that. There's a spec and there are several independent implementations to compare with. The spec is the final word
Comment: PS, I love...absolutely LOVE how `...` is valid syntax in 5.12 and up.  LOVE it.
Comment: Oh my.  I wonder if anyone ever gets bitten in the arse by that implicit `defined`?
Comment: If anyone's really writing code that's checking if an un-chomp()ed line read from a file without a line ending evaluates to False that way, they're getting exactly what they deserve.  Perl's DWIM attitude usually gets things right.
Comment: That... is awesome. I forgot about `B::Deparse` entirely. Thanks, Robert!
Comment: @Eric: That's true (and a little sad), but ultimately not that important, since Perl does come with standard docs (perlsyn etc.) that do much the same job.  I will always prefer an answer that says, "Section X in perlfoo describes when Perl does Y" to one that says, "I tried A, B and C with `B::Deparse` and found Perl does Y for them."
Comment: @j_random_hacker: If you ever check out the Perl 5 mailing list, when discussing Perl's behavior under some condition, the usual response to a language behavior question goes something "I looked at the test cases, checked the docs, then 'looked at the C to confirm that these were right.'" :)
Comment: @Robert: Oh dear...  Lots to like about Perl, but this is a huge weakness.  Think about this: Why don't those people on the Perl 5 mailing list go any further after looking at the C source?  Why don't they have to look at the C compiler's source code to figure out what the compiler will do with Perl's source, then look at CPU gate layouts to see what the CPU will do with the binary code?  That's right, it's because C compilers and CPUs are designed to a spec!  OK, I'm done whining now :)
Comment: @j_random_hacker: I would argue that the C hackers already do that for them. :)
Comment: -1 just because Perl does this in this case on your version of Perl, it is not true in all cases and all versions. See the test cases I posted that shows it is a potential issue.
Comment: Are you kidding?  Your examples have nothing to do with this construct.  Of course there's going to be different behavior when you don't use it in a while loop.  No where in the Perl docs does it say it won't.   Calling a function that returns a line is not the same as doing a readline in a loop nor would any competent programmer assume so.  This has been Perl's behavior since at least 5.003 (see CPAN's archived perlop - the section is there) and probably much before.  That's 1996.  That's so old in Perl terms, it predates support on most OSes that exist today, including Windows.
Answer: BTW, this is covered in the I/O Operators section of perldoc perlop:

In scalar context, evaluating a filehandle in angle brackets yields the next line from that file (the newline, if any, included), or "undef" at end-of-file or on error.  When $/ is set to "undef" (sometimes known as file-slurp mode) and the file is empty, it returns '' the first time, followed by "undef" subsequently.
Ordinarily you must assign the returned value to a variable, but there is one situation where an automatic assignment happens.  If and only if the input symbol is the only thing inside the conditional of a "while" statement (even if disguised as a "for(;;)" loop), the value is automatically assigned to the global variable $_, destroying whatever was there previously.  (This may seem like an odd thing to you, but you'll use the construct in almost every Perl script you write.)  The $_ variable is not implicitly localized.  You'll have to put a "local $_;" before the loop if you want that to happen.
The following lines are equivalent:
while (defined($_ = <STDIN>)) { print; }
while ($_ = <STDIN>) { print; }
while (<STDIN>) { print; }
for (;<STDIN>;) { print; }
print while defined($_ = <STDIN>);
print while ($_ = <STDIN>);
print while <STDIN>;

This also behaves similarly, but avoids $_ :
while (my $line = <STDIN>) { print $line }

In these loop constructs, the assigned value (whether assignment is automatic or explicit) is then tested to see whether it is defined.  The defined test avoids problems where line has a string value that would be treated as false by Perl, for example a "" or a "0" with no trailing newline.  If you really mean for such values to terminate the loop, they should be tested for explicitly:
while (($_ = <STDIN>) ne '0') { ... }
while (<STDIN>) { last unless $_; ... }

In other boolean contexts, "<filehandle>" without an explicit "defined" test or comparison elicit a warning if the "use warnings" pragma or the -w command-line switch (the $^W variable) is in effect.
Comment: Good answer so I deleted mine.  But the Perl docs are misleading -- they say, "If **and only if** the input symbol is the only thing inside the conditional of a while statement" -- but later contradict the "and only if" part by showing that `while (my $line = )` also behaves the same way. Leaving us wondering about exactly which circumstances this DWIMmery will be performed in.
Comment: @j_random: Isn't the "if and only if" part referring to whether $_ is used as the location for the line read from the handle, not whether the `defined` logic is employed?
Comment: You're absolutely right, poor reading comprehension on my part.  My apologies.  I still think it wouldn't hurt to be explicit about exactly when `define` is auto-applied.  My guess is: if the loop conditional test is `` or a scalar assignment with `` on the RHS -- is that everything though?
Answer: While it is correct that the form of while (my $line=<$fh>) { ... } gets compiled to while (defined( my $line = <$fh> ) ) { ... } consider there are a variety of times when a legitimate read of the value "0" is misinterpreted if you do not have an explicit defined in the loop or testing the return of <>.
Here are several examples:
#!/usr/bin/perl
use strict; use warnings;

my $str = join "", map { "$_\n" } -10..10;
$str.="0";
my $sep='=' x 10;
my ($fh, $line);

open $fh, '<', \$str or
     die "could not open in-memory file: $!";

print "$sep Should print:\n$str\n$sep\n";

#Failure 1:
print 'while ($line=chomp_ln()) { print "$line\n"; }:',
      "\n";
while ($line=chomp_ln()) { print "$line\n"; } #fails on "0"
rewind();
print "$sep\n";

#Failure 2:
print 'while ($line=trim_ln()) { print "$line\n"; }',"\n";
while ($line=trim_ln()) { print "$line\n"; } #fails on "0"
print "$sep\n";
last_char();

#Failure 3:
# fails on last line of "0"
print 'if(my $l=<$fh>) { print "$l\n" }', "\n";
if(my $l=<$fh>) { print "$l\n" }
print "$sep\n";
last_char();

#Failure 4 and no Perl warning:
print 'print "$_\n" if <$fh>;',"\n";
print "$_\n" if <$fh>; #fails to print;
print "$sep\n";
last_char();

#Failure 5
# fails on last line of "0" with no Perl warning
print 'if($line=<$fh>) { print $line; }', "\n";
if($line=<$fh>) {
    print $line;
} else {
    print "READ ERROR: That was supposed to be the last line!\n";
}
print "BUT, line read really was: \"$line\"", "\n\n";

sub chomp_ln {
# if I have "warnings", Perl says:
#    Value of <HANDLE> construct can be "0"; test with defined()
    if($line=<$fh>) {
        chomp $line ;
        return $line;
    }
    return undef;
}

sub trim_ln {
# if I have "warnings", Perl says:
#    Value of <HANDLE> construct can be "0"; test with defined()
    if (my $line=<$fh>) {
        $line =~ s/^\s+//;
        $line =~ s/\s+$//;
        return $line;
    }
    return undef;

}

sub rewind {
    seek ($fh, 0, 0) or
        die "Cannot seek on in-memory file: $!";
}

sub last_char {
    seek($fh, -1, 2) or
       die "Cannot seek on in-memory file: $!";
}

I am not saying these are good forms of Perl! I am saying that they are possible; especially Failure 3,4 and 5. Note the failure with no Perl warning on number 4 and 5. The first two have their own issues...


android admob error changing activity with asynctask

Question: I have 2 activities (ListActivity and ContactsActivity)
Both works perfectly without Admob.
But if I have admob in ListActivity, it works perfectly but when I click a button to change to ContactsActivity (it have an AsyncTask function to get all contacts from mobile) the application exploits with this error:

If anyone can help me how to solve this problem or telling other options do.
Thanks in advance.
Comment: What's in line 98 of ContactActivity? Can you post the java code?
Comment: possible duplicate of [Getting NoClassDefFoundError: android.os.AsyncTask](http://stackoverflow.com/questions/6968744/getting-noclassdeffounderror-android-os-asynctask)
Answer: Loading of Ads might be throwing any un-handled exception. Try surrounding the ads-loading code in try-catch. Or paste the code in here.
Edit: If you are loading ads in the AsyncTask, remove it from there. Call the loading of ad after loading the contacts list.
Like:
<code> public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        new LoadContactsList();
        ...

        Method to load your ads;
    }
</code>
Answer: I can confirm that adding the following code in my initial Activity solves the problem:
<code>try {
      Class.forName("android.os.AsyncTask");
}
catch(Throwable ignore) {}
</code>


strut tags for iterating session variable

Question: I am designing a web application where i want to use maximum of struts tag on JSP page instead of java code.
In my case,
one of the action is taking input from a JSP >> fetching data from db as per input >> populating Hashmap with output beans >> Putting hashmap into session >> iterating hashmap on JSP
Why i need hashmap : On the result JSP, i am generating link having Hashmap key as a parameter. So that the next action can get bean from HashMap easily without requesting to DB or any iteration.
In Addition: Before displaying data on result JSP, i require to format some of the data. I can not format this data while populating hashmap, because this data might be required further to store back into db.
How can i do above task using logic iterator and bean:write tags?
*I don't think that creating an extra form variable would be a better approach, instead of putting result bean into session variable.
Answer: In Struts2/OGNL tags, you can access values from a map using map[key].
Reference:

Struts2 iterator tag reference and examples
Struts 2 OGNL Expression Language Example

Regarding formatting, would you able to specify exactly what you need to format?


Athletes who have won Olympic medals under the olympic flag

Question: With the Russian Track and Field team recently banned from the 2016 Rio De Janeiro Olympics, I'm wondering if any athlete has ever won medals, gold on particular, under the Olympic flag in the Winter or Summer Games.
Athletes normally compete under the flag of the country they're from, but complications can lead to an athlete competing independently under the Olympic flag.
If independents have won medals, why did they compete independently? If an athlete is of Olympic medal-winning calibre, why wouldn't any country want the athlete to compete for them?
Answer: [As of 2016]: 4 Independent Olympic athletes have won Olympic medals at the 1992 & 2016 Olympics. 3 of them were Yugoslavian (Barcelona 1992) and one from Kuwait (Rio 2016) and all the medals were in Shooting.
the medalists are:

Fehaid Al-Deehani, Gold medal in Men's double trap.
Jasna Šekarić, Silver medal in Women's 10 m air pistol.
Aranka Binder, Bronze medal in Women's 10 m air rifle.
Stevan Pletikosić, Bronze medal in Men's 50 m rifle prone.

There are many reasons why athletes will compete independently, e.g.:

Political transition
International sanctions
Suspensions
Geopolitical changes

The reason Al-Deehani compete under the Olympic flag is that the Kuwait Olympic Committee has been suspended by the International Olympic Committee due to governmental interference.
The reason the Yugoslavian medalists compete under the Olympic flag is:

The Federal Republic of Yugoslavia (Serbia and Montenegro) was under
United Nations sanctions which prevented the country from taking part
in the Olympics. However, individual Yugoslav athletes were allowed to
take part as Independent Olympic Participants.

Source: https://en.wikipedia.org/wiki/Independent_Olympians_at_the_Olympic_Games
Comment: -1. This is less information than the older answer, and is still lacking for the same reasons.
Answer: There has only been one instance where the Independent Olympians, as they are called, have won medals, which was in the 1992 Barcelona Summer Olympics, where 3 Yugoslavian athletes won medals in Shooting.
During said Olympics, athletes from the Federal Republic of Yugoslavia and Macedonia competed as Independent Olympians. Yugoslavia being under UN sanctions at the time could not participate in the Olympics, while Macedonia have yet to establish their National Olympics Committee (NOC) back then.
There have been more instances where Independent Olympians have appeared because of some issues with their home countries that prevent them from being represented in the Olympics.
Comment: @nij there aren't several dozen of cases, only 4 cases, do you have another proof for your comment?
Comment: -1: there are several (dozen) cases of medal-winners under the Olympic flag. You even reference some of the events yourself, e.g. Spanish or Italian winners in 1980. Upvote when fixed.
Comment: The proof is in your own reference. Athletes under the Olympic flag, competing as independents, have won medals. Al-Deehani and al-Rashidi are clearly listed!


In awk, can you use a pattern AND an END block together?

Question: In awk, you can perform an action for a given pattern, like:
echo foo | awk '/foo/ {print "foo"}'

or you can perform an action at the end of the input, like:
echo foo | awk 'END {print "END"}'

But it does not appear to be possible to do both, like:
# echo foo | awk '/foo/ || END {print "foo or END"}'
awk: syntax error at source line 1
 context is
    /foo/ || >>>  END <<<  {print "foo or END"}
awk: bailing out at source line 1

Is this possible?
Comment: Right, so stick that code into a function and call the function from both blocks. If it's sufficiently complex consider writing this as a proper `.awk` file and executing like `awk -f myawkscript.awk myfile.txt`
Comment: You would just put the same command in both the `/foo/` and the `END` blocks like `awk '/food/{print "foo or END"}END{print "foo or END"}` if the logic in the block is sufficiently comples then you can move it to a function and call the function from both blocks.
Comment: Understood, but if the block is long, then it's a lot of redundant code...
Comment: Forgot awk had functions.  Thanks!
Answer: No. Do this instead:
awk '
/foo/ { prtInfo() }
END   { prtInfo() }
function prtInfo() { print "foo or END" }
'

Answer: No you cannot do such a thing. The END statements are executed when the last line has been processed and similar to BEGIN they are special forms of patterns.

Overall Program Structure
An awk program is composed of pairs of the
  form:
pattern { action }

Either the pattern or the action (including the enclosing brace
  characters) can be omitted.
Patterns
A pattern is any valid expression, a range specified by two expressions separated by a comma, or one of the two special patterns BEGIN or END.
Special Patterns
The awk utility shall recognize two special patterns, BEGIN and END. Each BEGIN pattern shall be matched once and its associated action executed before the first record of input is read-except possibly by use of the getline function (see Input/Output and General Functions) in a prior BEGIN action-and before command line assignment is done. Each END pattern shall be matched once and its associated action executed after the last record of input has been read. These two patterns shall have associated actions.
BEGIN and END shall not combine with other patterns. Multiple BEGIN and END patterns shall be allowed. The actions associated with the BEGIN patterns shall be executed in the order specified in the program, as are the END actions. An END pattern can precede a BEGIN pattern in a program.
source: awk POSIX standard

The statement
/foo/ || END { action }

is thus not allowed as it combines END with another pattern.
See the answer of Ed Morton for an elegant solution.
Answer: you can try this workaround
awk '{Last=$0} END{ if( Last ~ /foo/) print "action if" }' YourFile

but it's only for last line of last file
Answer: this might be simpler
$ awk '/foo/{exit} END{print "foo or END"}'

exit will run the END block, so you don't need to repeat the statement.
Comment: Mmmm... that will ignore any lines following `foo`, surely?
Comment: Yes, of course early exit.  The question as I understand,  find a "foo" or no "foo" at the end.  If you want to find all "foo"s this is not the right approach.


Interpretation of songsterr tab

Question: Hi guys I'm looking at a tab on songsterr (Use Somebody fingerstyle) and at the 8th bar the tab indicates the playing of the open CGC strings and above it says t.h.(12) and t.h.(19).
Can anyone explain what this means?
I also need help from the 96th to the 105th bar where it requires playing on the 2nd and 6th fret. Is there any advice on how to position my fingers/what chord/technique to play this bit?
I'm relatively new to the guitar and i can get the harmonics and the rest of the song down but im having trouble with the above. Any advice is greatly appreciated
Comment: T.H. = tapped harmonics.
Comment: "open CGC strings" - open tuning? Link to what you are looking at?
Comment: @b3ko It uses CGCGCe tuning: https://www.songsterr.com/a/wsa/kings-of-leon-use-somebody-fingerstyle-tab-s88415t0
Comment: An image would be worth a thousand words here in terms of useful information.
Answer: T.H mean tapped harmonic.
t.h.(19) = use your right hand finger to tap on 19th fret.

Interpretation of songsterr tab


Large overlap between confidence intervals, although z test for difference was significant

Question: I have calculated a z test to examine the difference between two proportions. I found differences to be significant.  The formula I used was:
$$z = (p_1-p_2)/SE$$
where
$$SE = \sqrt{ p  ( 1 - p )  ( \frac{1}{n_1} + \frac{1}{n_2} ) }$$
and $n_1$ is the sample size of sample 1, $n_2$ sample size of sample 2.
I have also plotted a bar graph of my proportions with 95% confidence intervals around each of the two proportions based on this equation:
For proportion 1:
$p_1 \pm  1.96SE$
$SE =  \sqrt{p(p-1)/ n_1}$;  $n_1$: size of the sample 1
For proportion 2:
$p_2 \pm 1.96SE$
$SE =  \sqrt{p(p-1)/ n_2}$; $n_2$: size of the sample 2
I would not expect the CIs to overlap much based on significant of z test.  However, they overlap by more than 25%.   Am I using the correct formula for the confidence intervals?  If so why does there seem to be discrepancy between the results of the z test and the visual depiction of the difference
Comment: A quantitative analysis of this situation is provided at http://stats.stackexchange.com/questions/18215.  Although it's probably TMI, it definitely answers your question!
Comment: Plot the CI for the quantity you're interested in - the difference of the proportions.
Answer: Statistics is a pretty large field and it is good to invest in understanding the fundamentals before attempting to use statistics.  What you stated is a common misconception about statistics.  Individual confidence intervals make an inference about one quantity of interest.  You need a confidence interval for the difference in two such quantities.  There are many confidence intervals developed for the difference in two probabilities.  It is easy to have individual intervals overlap whereas the interval for the difference excludes zero.  The converse is not true however.  If the interval for the difference includes zero, the two individual intervals must overlap.  Note that it is not typical for the two individual intervals to be of much interest in study in which subjects are not a simple random sample from the population to which inference is desired.
Comment: Hi.  Thanks for your answer, it is helpful.  I have one more question. I will plot the CI for the difference, but I would also like to plot the individual proportions next to each other on a bar graph. People usually expect to see the 95% CI on each bar.  Is it meaningless to plot this?  If I do plot the individual CIs for each bar is there a limit for the expected to overlap (e.g. by 25%).  My CIs overlap by approx 40% but the z test still shows significance.
Comment: It is unclear why you are still concerned about the relationship between the two different types of confidence intervals.  But the answer below gives you the details.  Don't use bar charts as they give a distorted impression about the intervals.  Whether it's meaningless depends entirely on your sampling strategy.
Comment: my sampling statergy was a random sample from the population of interest.  I would like to plot a bar graph of two proportions next to each other.  People usually expect to see an confidence interval on each of the bars.  I'm simply asking whether it is meaningless to plot confidence intervals for each bar, using the formula above (for the CI for each group) - I sense that the answer is yes.  In which case why do people do this (all the time!).     Why does using bar chart distort the difference between the two proportions?
Comment: It is not meaningless but from the standpoint of helpfulness I'd put it at 0.4.  I think that it's 0.1 if the samples are not random samples from the population of interest.  Summed up, as Bill Cleveland has said, if you want to learn about a difference, show the difference.
Answer: As you can see, the standard error for the test or, equivalently, for CI of the difference, involved the term $(\frac{1}{n_1}+\frac{1}{n_2})$ where the single confidence intervals only had $\frac{1}{n_i}$. Clearly, the former is larger making the confidence interval for the difference smaller.
The other point making the CI for the difference smaller, is that the degree of freedom also becomes smaller. This in turn makes the 95%-quantiles smaller. (However, this consideration only applies to non-asymptotic tests/CIs.)
That's why overlapping confidence intervals do not imply the confidence interval of the difference to cover the $0$, whereas covering $0$ implies overlap.
Comment: if you edit again, you might want to change 'intercal' to 'interval'. I couldn't figure out what you meant for a minute.
Comment: Thank you,  I thought that it could be something to do with 'more power' for the z test because it was using N of both samples.  Is this correct?  Can i adjust my individual CIs to account for this?  So that they are more representative of the CI of the difference?


java.lang.RuntimeException: Unable to start activity ComponentInfo(tensorflow.lite.examples)

Question: I am working on this project: TensorFlow Lite image classification Android example application
GitHub link: https://github.com/tensorflow/examples/tree/master/lite/examples/image_classification/android
I run this project on my own phone (xiaomi redmi note 8) on Android Studio (not emulator)
When I run this project on Android Studio, TFL Classify applications gives the following error: application keep stopping.
Then Android Studio gives this error:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: org.tensorflow.lite.examples.classification, PID: 20798
    java.lang.RuntimeException: Unable to start activity ComponentInfo{org.tensorflow.lite.examples.classification/org.tensorflow.lite.examples.classification.ClassifierActivity}: java.lang.IllegalArgumentException: No enum constant org.tensorflow.lite.examples.classification.tflite.Classifier.Model.QUANTİZED_EFFİCİENTNET
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2984)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3119)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1839)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:201)
        at android.app.ActivityThread.main(ActivityThread.java:6864)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
     Caused by: java.lang.IllegalArgumentException: No enum constant org.tensorflow.lite.examples.classification.tflite.Classifier.Model.QUANTİZED_EFFİCİENTNET
        at java.lang.Enum.valueOf(Enum.java:258)
        at org.tensorflow.lite.examples.classification.tflite.Classifier$Model.valueOf(Classifier.java:47)
        at org.tensorflow.lite.examples.classification.CameraActivity.onCreate(CameraActivity.java:195)
        at android.app.Activity.performCreate(Activity.java:7232)
        at android.app.Activity.performCreate(Activity.java:7221)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2964)

I updated SDK version 28 to 29.0.2 but it didn't work
Answer: Remove the accents from the string QUANTİZED_EFFİCİENTNET - it should be QUANTIZED_EFFICIENTNET so it matches the corresponding enum label.
Comment: I looked inside required code but there is QUANTIZED_EFFICIENTNET ,not QUANTİZED_EFFİCİENTNET .I didnt understand this error.Project works fine on emulator
Comment: Yes you are right.I looked app->res->values->strings.xml part

'''
Quantized_Efficientnet
Float_Efficientnet
Quantized_MobileNet
Float_Mobilenet
'''
Then i changed like this

'''
QUANTIZED_EFFICIENTNET
FLOAT_EFFICIENTNET
QUANTIZED_MOBILENET
FLOAT_MOBILENET
'''
Problem is solved
Thanks for your solution


Django admin inheritance

Question: simple question: is it possible to organize all this info in one admin form only instead of 6 separated links?
i've read about django admin inheritance but there is no inheritance among the models, as shown below...so how would it work then?
models.py

# -*- coding: utf-8 -*-
from django.db import models

# Create your models here.

class User(models.Model):
 name = models.CharField(max_length=100, verbose_name='Nome Completo')
 bdate = models.CharField(max_length=10, verbose_name='Data de Nasc.')
 gender = models.CharField(max_length=15, verbose_name='Sexo')
 cpf = models.CharField(max_length=14, unique=True, verbose_name='CPF')
 oab = models.CharField(max_length=15, unique=True, verbose_name='OAB')
 phone = models.CharField(max_length=15, verbose_name='Celular')
 email = models.EmailField(max_length=50, verbose_name='E-mail')

 def __unicode__(self):
  return self.name

 class Meta:
  verbose_name = u'1.Identificação'
  verbose_name_plural = u'1.Identificação'

class Address(models.Model):
 user = models.OneToOneField(User, default=0, null=True, blank=True, verbose_name='Nome Completo')
 cep = models.CharField(max_length=15, verbose_name='CEP')
 address = models.CharField(max_length=100, verbose_name=u'Endereço')
 bairro = models.CharField(max_length=100, verbose_name='Bairro')
 city = models.CharField(max_length=100, verbose_name='Cidade')
 uf = models.CharField(max_length=50, verbose_name='Estado')

 class Meta:
  verbose_name = u'2.Endereço'
  verbose_name_plural = u'2.Endereço'

class Pretensoes(models.Model):
 user = models.OneToOneField(User, default=0, null=True, blank=True, verbose_name='Nome Completo')
 cargo = models.CharField(max_length=100, verbose_name='Cargo pretendido')
 salario = models.CharField(max_length=50, verbose_name='Salario pretendido')
 cidade1 = models.CharField(max_length=50, verbose_name='Cidade 1', default=None)
 cidade2 = models.CharField(max_length=50, verbose_name='Cidade 2', default=None)
 cidade3 = models.CharField(max_length=50, verbose_name='Cidade 3', default=None)
 cidade4 = models.CharField(max_length=50, verbose_name='Cidade 4',default=None)

 class Meta:
  verbose_name = u'3.Pretensões'
  verbose_name_plural = u'3.Pretensões'

class Graduation(models.Model):
 user = models.OneToOneField(User, default=0, null=True, blank=True, verbose_name='Nome Completo')
 scholarity = models.CharField(max_length=50, verbose_name='Escolaridade')
 course = models.CharField(max_length=100, verbose_name=u'Área/Curso')
 school = models.CharField(max_length=100, verbose_name=u'Instituição')
 year = models.CharField(max_length=4, verbose_name=u'Ano de conclusão')
 others = models.CharField(max_length=300, verbose_name='Outros')
 msword = models.CharField(max_length=50, verbose_name='Word')
 msexcel = models.CharField(max_length=50, verbose_name='Excel')
 msinternet = models.CharField(max_length=50, verbose_name='Internet')

 class Meta:
  verbose_name = u'4.Escolaridade'
  verbose_name_plural = u'4.Escolaridade'

class Professional(models.Model):
 user = models.ForeignKey(User, default=0, null=True, blank=True, verbose_name='Nome Completo')
 company = models.CharField(max_length=100, verbose_name='Empresa')
 start = models.CharField(max_length=10, verbose_name=u'Mês de entrada')
 end = models.CharField(max_length=10, verbose_name=u'Mês de saída')
 p_city = models.CharField(max_length=100, verbose_name='Cidade')
 p_phone = models.CharField(max_length=15, verbose_name='Telefone')
 functions = models.CharField(max_length=300, verbose_name=u'Funções')

 class Meta:
  verbose_name = u'5.Profissional'
  verbose_name_plural = u'5.Profissional'

class Info(models.Model):
 user = models.OneToOneField(User, default=0, null=True, blank=True, verbose_name='Nome Completo')
 info = models.TextField(verbose_name=u'Demais informações relevantes')

 class Meta:
  verbose_name = u'6.Demais informações'
  verbose_name_plural = u'6.Demais informações'

admin.py

# -*- coding: utf-8 -*-
from django.contrib import admin
from models import User, Address, Pretensoes, Graduation, Professional, Info

# Register your models here.
class UserAdmin(admin.ModelAdmin):
    list_display = [
        'name',
        'bdate',
        'gender',
        'cpf',
        'oab',
        'phone',
        'email',
    ]

class AddressAdmin(admin.ModelAdmin):
    list_display = [
        'user',
        'cep',
        'address',
        'bairro',
        'city',
        'uf',
    ]

class PretensoesAdmin(admin.ModelAdmin):
    list_display = [
        'user',
        'cargo',
        'salario',
        'cidade1',
        'cidade2',
        'cidade3',
        'cidade4',
    ]

    search_fields = ['cargo', 'salario']

class GraduationAdmin(admin.ModelAdmin):
    list_display = [
        'user',
        'scholarity',
        'course',
        'school',
        'year',
        'others',
        'msword',
        'msexcel',
        'msinternet',
    ]

    list_filter = (
     ('scholarity'),
     ('msword'),
     ('msexcel'),
     ('msinternet'),
    )

    search_fields = ['scholarity', 'course', 'school', 'year', 'msword', 'msexcel', 'msinternet']

class ProfessionalAdmin(admin.ModelAdmin):
    list_display = [
        'user',
        'company',
        'start',
        'end',
        'p_city',
        'p_phone',
        'functions',
    ]

class InfoAdmin(admin.ModelAdmin):
    list_display = [
        'user',
        'info',
    ]

admin.site.register(User, UserAdmin)
admin.site.register(Address, AddressAdmin)
admin.site.register(Pretensoes, PretensoesAdmin)
admin.site.register(Graduation, GraduationAdmin)
admin.site.register(Professional, ProfessionalAdmin)
admin.site.register(Info, InfoAdmin)
Answer: You can use admin model inline :)
from django.contrib import admin

from .models import Choice, Question

class AddressInline(admin.StackedInline):
    model = Address

class UserAdmin(admin.ModelAdmin):
    inlines = [AddressInline]

admin.site.register(User, UserAdmin)

You can use multiple inlines as well for like foreign keys and such, try it out it was in the polls tutorial https://docs.djangoproject.com/en/1.8/intro/tutorial02/
Bloop Bloop happy djangoing!

Django admin inheritance


Fine uniformity on a set

Question: I came across the term fine uniformity while reading a paper.
I want to know

What is meant by fine uniformity on a set? Is this the largest uniformity that can be defined on it? That is, uniformity containning diagonal of the set?
Comment: my guess is that the term fine uniformity applies to a uniformity on a topological space. The same (given, fixed) topology could be generated by different uniformities, and among these uniformities there is a finest one (containing the most entourages, compatible with the given topology). There are certain conditions guaranteeing that a finest uniformity exists, since it doesn't always exist.
Comment: When asking for the definition of a term found "while reading a paper," it is helpful to Readers to cite the paper (title, author, journal or website of publication).
Answer: A topological space is uniformizable if and only if it is completely regular.
One can show that, on a completely regular space, there is a finest uniformity compatible with the topology, called the fine uniformity.
The fine uniformity is generated by all open neighborhoods $D$ of the diagonal of $X \times X$ (with the product topology) such that there exists a sequence $(D_n)_{n \geqslant 0}$ of open neighborhoods of the diagonal such that $D = D_0$ and $D_{n+1}\circ D_{n+1}\subseteq D_n$ for all $n$. See the wikipedia entry uniformizable space for more details.
In contrast, every topological space is quasi-uniformizable (the definition of a quasi-uniformity is the same as that of a uniformity, except that the inverse of an entourage is not required to be an entourage).

Fine uniformity on a set


TFS Automated Build

Question: I have this enterprise setup: The Team Foundation Server is 2012 with Update 3 on it (no Build service/controller/agents enabled on it).
The Build Server has only VS2010 Ultimate with SP1, also with the Build service enabled and 1 controller and 4 agents on it.
I cannot run the build definition. I keep getting TF900558: This build process template cannot be run on build server -Controller. Upgrade this build server to a newer version.
As far as I read, TFS2012 Update 2 (I hope Update 3 as well) can accept build definitions from VS2010. What should I do next?
Comment: Isn't this just that you need to install VS2012 on your build agent (the machine with you build agent/s on)?
Answer: As I read the error, you are using a 2012 build template on a 2010 build controller/agent. You can upgrade just the TFS part on the build machine, or use an old 2010 build template.
Comment: Can you be more specific ....how should I upgrade just the TFS part on the build machine? I setup the Build Service, controller and agent on 2010....just to accommodate VS2010 builds.On the build machine I'm suppose to do builds only up to VS2010.
Comment: You can use TFS 2012 Build Agent to build solutions using VS 2010 (the VS version and TFS versions are independent).
Comment: Initially I installed TFS 2012 Build Service/controller/agent on the Build Server. The problem was that installed the Framework 4.5 as well, and we don't do builds for 4.5 yet. I uninstalled and installed the TFS 2010 BS/Contr/Agent.
Comment: So your only option is to use a 2010 template. It was called DefaultTemplate.xaml or similar, while the 2012 should be DefaultTemplate.11.xaml: check for yourself as I do not have an old machine to validate.

TFS Automated Build


Understand the reason for calculating the MSE

Question: Im following an introduction course into R-machine Learning. Im doing the following:

Load the faithful dataset (standard in R)
Creating a model that predicts waiting time -> eruptions of the first 136 items of the dataframe.
mymodel = glm(data=faithful[1:136,], waiting ~ eruptions)
Calculate the mean standard error on the second half of the data.
mean((faithful$waiting - predict(mymodel, faithful[137:272, ])), ^2)

The way I see it you take the mean of all waitingtimes - the predicted values (using the glm model) and do exponent^2.
I do not understand however why exactly this is done? Could anybody explain this to me in plain English?
Answer: Using mean squared error can be seen as a special case of the maximum likelihood parameter estimation. One wants to choose the model such that the likelihood of the observation is maximal for the selected model. The likelihood is:
$$
{\cal L} = p(z_1|y_1) \cdot \ldots \cdot p(z_N|y_N)
$$
where p(z|y) is the probability of the observed value z when the model predicts value y.
So 'fitting' a model is done by maximizing L or equivalently minimizing
$$
    - \log({\cal L})
$$
If you assume a Normal distribution centered at the y_i for the p's and you assume that all p's have the same width parameter sigma (set to one for convenience), you'll get:
$$
    - \log ({\cal L}) = constant - \log ( e^{-\frac{1}{2} \cdot (y_1-z_1)^2} ) - \ldots - \log ( e^{-\frac{1}{2} \cdot (y_N-z_N)^2} )
$$
Setting the width parameter of all Gaussians to the same value means that all your measurements have the same uncertainty (i.e. the same precision).
where the log and exp cancel each other and you'll end up with:
$$
    - \log ({\cal L}) = constant + \frac{1}{2} \cdot (y_1-z_1)^2 + ... + \frac{1}{2} \cdot (y_N-z_N)^2
$$
For the purposes of minimization, you can drop the constant and also the factors 0.5 and you'll end up with the mean (or summed) squared error.


How do you write an MSBuild task to support cancelation?

Question: I have a custom MSBuild task for xUnit.net. When the task is running, if I hit Ctrl+C, it 'tries' to cancel the task, but of course it fails (since my task doesn't support cancelation). No amount of MSDN doc searchs or Google-fu have landed on a solution. Since I can't find an obvious interface to implement, I'm guessing maybe cancelation is supported by way of some convention.
Has anybody done this before, and knows what's required to get cancelation to work?
Answer: Your task needs to implement ICancelableTask. It's a very simple interface added in 4.0.
Basically you just add a Cancel() method. It must be ready to be called on a different thread, at any time, and return promptly. Your task must then return from Execute promptly. Typically you'd set a boolean flag inside Cancel(). Then inside your task you'd typically have a loop processing each input in turn -- for example, copying one file after another -- and in each iteration, check the flag; if it's true, break out. It doesn't matter whether you return true or false from Execute in this context.
If you're deriving from ToolTask -- if your task spawns a tool, it's very strongly recommended that you do this, as it saves a great deal of code, handles async logging, and other things -- then it already handles Cancel automatically. When Cancel happens, it kills the tool it spawned and all its children. The C++ team's tasks in some cases override this default behavior, so that their compiler/linker has a few seconds to clean up their half-written outputs before returning.
(Trivia: when I first implemented this in MSBuild, I accidentally made VS bluescreen the box occasionally. This nearly shipped in VS10 beta but was discovered just in time. The bluescreen was because the logic for figuring out the process tree was wrong, and would sometimes kill a system process. Oops.)
Dan
Comment: I'm guessing the reason I never saw this was because it's new for 4.0, and my tasks are still targeting 2.0. Good to know, though, that when I upgrade to 4.0 I can start using this. Thanks!
Comment: "the logic for figuring out the process tree was wrong, and would sometimes kill a system process. Oops." +1 for being able to figure that out! Hahahaha!
Answer: I know you're well aware of the Task hierarchy, but on the offchance this is what you're looking for and it's just the fact that you're not implementing a ToolTask...
Inside MSBuild 2nd ed says (p118) of ToolTask.Cancel

This method is called to cancel the task execution. Once this method is called by MSBuild, if the task does not complete, it will be forcefully terminated

There are no other references to cancellation in it.
Comment: Yeah, I looked at that, but I'm not running an external tool, so ToolTask is most definitely not the right bit of hierarchy. I suppose I could just complement a method that looks like that and see if MSBuild called me... before I wandered down that path, though, I figured I'd ask and see if anybody had ever done it.
Comment: In the book we didn't have space to cover this. We may be doing an update, in which case I will include this.


Right Hand Picking Technique of Strummed Octaves

Question: My very first time picking up a electric guitar and i am confused as to how to play with just my right hand, the first link below is the tabs i am learning from, with me confuse about the first few notes which to my understanding means pluck two strings at the same time, however on the second video that person flicks her hand around almost seems like shes just gliding her hand all over the strings at once.
What style is she using to accurately and smoothly pluck the required strings without touching the other strings caught in the middle?
First Video (Skip to 0:54):

Second Video (Skip to 0:13):
Answer: Wow - that is a fairly complicated song for someone picking up an electric guitar for the first time!  I admire your penchant for a challenge! But I think you might want to start with some easier songs to play and work your way up to that one.
It is likely that the guitarist in the video is muting the unplayed strings by lightly touching them with one of her fingers.  In the second video you can see her reaching over the top of the fretboard with her thumb to mute the bass strings so she can strum all six strings with a steady up and down strumming pattern but only play the top four or five or middle four strings.
In some cases she may be muting certain strings with one of the other fretting fingers by angling her finger to allow it to lightly touch and thus mute the strings that are not to be played.  In some cases it may be a non fretting finger or the edge of her hand that might be muting certain strings (such as the first skinniest string most often tuned to high e).
With practice you will learn to strum and intentionally miss the 6th string or the 6th and 5th string.  It comes with a great deal of practice.  But if you can learn to mute the strings that are not to be played, you will eliminate the chance you might accidentally hit a string that is not supposed to be played.  If you can't comfortably reach around with your thumb, you can use the tip of your index (pointer) finger to mute the bass string.
It's not shown in your linked video, but another technique for playing two non adjacent strings simultaneously is to pluck them at the same time using your thumb and middle or index finger.  You can also do this with a pick and your middle finger.  This is sometimes referred to as a "pinch".
Don't be discouraged if you can't do any of the foregoing right away.  It takes a great deal of intentional practice to master these string muting techniques.  While you are practicing those, try learning some songs with some basic chords that don't require so much string missing and muting.
Good luck and have fun on your journey towards becoming a great guitarist.
Comment: @ToddWilcox  there are some licks in some songs that I have been working on for years hoping to master them.  One day ........
Comment: I think my second song I started learning was "Under the Bridge" by Red Hot Chili Peppers. Yeah, that was a little... ambitious. It was only about two years later when I could actually make it all the way through the song, having learned several other much easier songs ("Wild Thing", for example) in the meantime. To this, day, I still can't do complete justice to "Under the Bridge", but you know, not being able to perfectly imitate John Frusciante isn't keeping me up at night.
Comment: I learnt by trying to play Hotel California. I'd practice all the normal basic beginner stuff and then every now and then go back and try to play it. It was actually quite motivating to see how the whole song got slightly easier each time. Put all the sloggy strumming / chord transition practice into context. Can't play it for toffee now, but it did keep me enthused at the time.
Comment: @Whelkaholism  I can relate.  Some songs I gave up on but later revisited  after improving my abilities and found new hope.  I have heard more than one accomplished guitarist say they started with an ambition to learn one cool guitar song (such as Stairway To Heaven or Blackbird) and that was their driving motivating force.
Answer: The first notes is something I would call octave chord or something like this, sorry, I don't know the correct english name for it.
You play it like a normal powerchord, which means you put your index finger at the 7th string of the a string and the ring finger on the 9th string on the g string. But as shown in the tabs, you don't wan't to play the d string in this chord. To do that, you dampen this string with your index fingerwhile pressing the 7th string. Try to lay your finger firmly on the d string, so that it can't swing. Then you can strum the chord like any other chord, but try to hit only the a, d and g string. That way you can play that kind of chord quite easily. It takes a bit of practice to find out the right amount of pressure you have to apply and the position of your finger, but it shouldn't take to long. Nothing impossible =)
Comment: Most guitarists just call them "octaves" and in this style assume this technique you described.
Comment: Ahh, nice to know. Thank you. The german word for it is "Oktavgriff" which basically means that you grab an octave =)


$G$ finite metabelian group, $P$ a Sylow $p$-subgroup. Show that $P'$ is abelian and normal in $G$

Question: Let $G$ be a finite metabelian group and let $P$ be a Sylow $p$-subgroup of $G$. I have to observe that the derived subgroup $P'$ is abelian and normal in $G$.
Since $G'$ is abelian, the subgroup $P' \leq G'$ is abelian too, and it's normal in $G'$. How can I obtain the normality in the entire $G$?
Answer: For $g \in G$, we have $[P,P]^g = [P^g,P^g]$. Now $P$ and $P^g$ are Sylow $p$-subgroups of $PG'$, and hence they are conjugate by an element of $G'$. So there exists $h \in G'$ with $P^g=P^h$ and hence
$$[P,P]^g = [P^g,P^g] = [P^h,P^h] = [P,P]^h = [P,P]$$
because $G'$ is abelian.
Answer: A slightly different proof runs along the following lines. First some generalities: if a subgroup $H$ of $G$ contains the commutator subgroup $G'$, it must be normal (proof: $H/G'$ is normal in the abelian group $G/G'$). So if $P \in Syl_p(G)$, then $PG' \unlhd G$. Of course $P$ is a Sylow $p$-subgroup of $PG'$, hence the Frattini Argument yields $G=N_G(P)PG'=N_G(P)G'$. So in general the following holds.
Proposition Let $G$ be a finite group and $P \in Syl_p(G)$, then $G=N_G(P)G'$.
Now observe that $P' \text{ char } P \unlhd N_G(P)$, so $P' \unlhd N_G(P)$. Assume from this point on that $G'$ is abelian (that is, $G$ is metabelian), then $P' \unlhd G'$. The proposition now implies $P' \unlhd G$. Finally we mention an additional observation: note that $P \cap G'$ is the unique Sylow $p$-subgroup of the abelian $G'$. Hence $P \cap G' \text{ char } G' \unlhd G$, whence $P \cap G' \unlhd G$.

Note Using Dedekind's Modular Law and induction one can actually prove this.

Proposition Let $G$ be a finite group, $P \in Syl_p(G)$, and $i$ a non-negative integer, then $G=N_G(P \cap G^{(i)})G^{(i+1)}$.

Corollary Let $G$ be a finite solvable group of derived length $n$, $P \in Syl_p(G)$, then $P^{(n-1)}$ and $P \cap G^{(n-1)}$ are both abelian normal subgroups of $G$.


Pegar objeto ao clicar em uma commandLink no DataTable

Question: Estou tentando pegar um objeto ao clicar em um commandLink que fica em cada coluna da DataTable, porém sempre da erro de nullPointerException. Alguem pode ajudar?
Estou fazendo dessa forma:

            <f:setPropertyActionListener
                target="#{controleAuditoriaBean.solicitacoesBD}"
                            value="#{controleAuditoria}" />

Método:
public void prepDownload() throws Exception {
        System.out.println("Caminho "+solicitacoesBD.getCaminhoArquivo());
        File file = new File(solicitacoesBD.getCaminhoArquivo());

        InputStream input = new FileInputStream(file);
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        setDownload(new DefaultStreamedContent(input, externalContext.getMimeType(file.getName()), file.getName()));
        System.out.println("PREP = " + download.getName());
    }

Answer: Techies, seu problema está em utilizar o actionListener enquanto que o correto seria apenas action.
O problema do actionListener é que ele executa antes do action.
Seu código ficaria:

            <f:setPropertyActionListener
                target="#{controleAuditoriaBean.solicitacoesBD}"
                            value="#{controleAuditoria}" />

Comment: Mais uma vez muito obrigado Maicon. Você tem me ajudado bastante.
Comment: Funcionou, porém tenho que clicar 2x no link pra começar o download do arquivo. Seu clico 1x ele pega o objeto certinho mas o download não inicia.
Comment: @Techies Você pode voltar pra `actionListener` e tenta passar o valor por parâmetro ao invés de `f:setPropertyActionListener`, experimenta!
Comment: Pra passar por parâmetro não preciso usar o `f:setPropertyActionListener`?
Comment: Depende da versão do seu jsf, qual é? :)
Comment: Creio que seja a 2.2
Comment: Pode sim, faz um `actionListener="#{controleAuditoriaBean.prepDownload(controleAuditoria)}" `
Comment: Voltei para o `actionListener`, você só precisa alterar seu método `prepDownload` para receber esse tipo de parâmetro
Comment: pra receber esse parametro no meu método uso o requestContext?
Comment: ou é só colocar o objeto no método pra receber esse parâmetro? por exemplo `prepDownload(Auditoria a)`
Comment: @Techies só colocar o objeto no método, igual seu último exemplo