Application of Monotone Convergence Theorem

Question: Suppose $f ∈ L^{1}([0, 1])$. Prove that $lim$ $ε→0^{+} \int_{[0,ε]} f dµ = 0$
My attempt at proof:
Let $B_N$ be an open ball of radius $N$ centred at origin.
$E_N:=$ {$x: f(x)\leq N$}
$f_N(x):=f(x) \chi_{E_N}$
$f_N$ is measurable. Also, $f_{N+1}\geq f_{N}$ and $lim _N\to \infty f_N(x)=f(x)$
By Monotone Convergence Theorem,
$lim _N\to \infty \int_{[0,1]} f_N d\mu=\ \int_{[0,1]} f d\mu$
$\implies 0\leq \int_{[0,1]} f(x)\ d\mu- \int_{[0,1]} f(x)\chi_{E_N}\ d\mu<\epsilon/2$ for some $\epsilon$
$\implies \int_{[0,1]} [f(x)-f_N(x)]\ d\mu<\epsilon/2$.
$\mu([0,\epsilon])=\epsilon$.
So, $\int_{[0,\epsilon]} f\ d\mu= \int_{[0,\epsilon]} [f-f_N]\ d\mu+\int_{[0,\epsilon]} f_N\ d\mu\leq \int_{[0,1]} [f-f_N]\ d\mu + \int_{[0,\epsilon]} f_N\ d\mu \leq \epsilon/2+N \epsilon$
Please suggest if the proof is correct.
Comment: first, you wnt to know what happens near 0. why are you taking a look at infinity? is at least $f$ defined near infinity?
Comment: Apologies for the above comments. Some of the issues would be that Monotone convergence only applies to positive (or negative) functions, not general $L^1$ functions. Also, since your final bound contains $N$, you can't know how it will behave in the limit, so that the proof is not complete.
Comment: @mookid: Can you please suggest a proof then? I was thinking to prove that the integral is always less than $\epsilon$
Comment: @WSL: Thanks for pointing that out. Actually I also saw that the final bound has $N$ and hence presented the proof here for refinement. Any suggestions on how to prove this then?
Comment: I suggest splitting $f$ up $f= f^+-f^-$ and starting with the assumption that you are dealing with a positive function. That way, monotone convergence is applicable and you can go from there.
Comment: @Silvermoon I did it. tell me if you have any more question.
Comment: @WSL: I am sorry for not writing $f=f^{+}- f^{-}$. But in fact, I was assuming in my solution that $f$ is positive
Comment: @mookid: Agree with you
Answer: Let us assume $f\ge 0$.
Consider the sequence $f_\epsilon = f\times 1_{(0,\epsilon)}$. $f_\epsilon$ decreases when $\epsilon\to 0$ as $f\ge 0$, and $f_\epsilon (x) \to 0$ pointwise.
Applying the monotonic convergence theorem, you get
$$
\int_0^\epsilon fd\mu = \int f_\epsilon d\mu\to 0
$$

When $f\in L^1$, write $f = f^+ - f^-$ with $f^\pm \ge 0$. And apply the first part twice.
Comment: It is the product of measurable functions
Comment: But how do we claim $f_\epsilon $ is sequence of measurable functions?
Answer: This can be done without any of the convergence theorems. First, it's clear if $f$ is bounded. For the general $f\in L^1,$ let $t> 0.$ Then there is a simple function $s$ such that $\int_0^1|f-s|<t.$ Thus
$$\int_0^\epsilon|f| \le \int_0^\epsilon|f-s|+\int_0^\epsilon|s|< t + \int_0^\epsilon|s|.$$
This shows
$$\limsup_{\epsilon\to 0}\int_0^\epsilon|f| \le t.$$
Since $t>0$ is arbitrary, we have the desired result.


In Public IaaS cloud, if my VM is given any available pCPU core, how sure am I that I get all the cores I pay for?

Question: I am a new comer to virtualization!
At least from what I know, in virtualization if I have a VM, the scheduler will give it any core available for processing in the physical CPU (pCPU) and it is also not advisable to permanently assign a pCPU core to a VM. In public IaaS clouds, customers select a VM with preset resources and they will certainly pay for these resources as long their VMs are active even if they are probably utilizing their resources say 20 % these resources. How sure am I that I get all the cores I pay for even when I am not using them?
Answer:
How sure am I that I get all the cores I pay for even when I am not using them?

The thing is just the opposite: Depending on the specific virt model and instance type, you can be sure that you don't get the resources when you don't use them.
Providers will overcommit resources on the assumption that many customers won't have 100% utilization at all times. This is reflected in the contracts and essentially is what you are paying for.


MvvmCross Android Dialog Bing Programmatically - ViewModel is not updated

Question: This is a follow up of the post about MvvmCross Android Dialog Bing Programmatically
I've implemented the bindings of a Dialog in a Droid project:
    this.Root = new RootElement("Customer Info")
    {
        new Section("Private Configuration")
        {
            new EntryElement("Pin:").Bind(this, "{'Value':{'Path':'Configuration.Pin'}}"),
            new EntryElement("Name:").Bind(this, "{'Value':{'Path':'Configuration.Name', 'Mode':'TwoWay'}}"),
        };
    };

I've added the TwoWay in the Configuration.Name bind just for test purposes.
The problem now is that the bind is working only in OneWay. The object is not updated if I change something in the view, but the view is notified if the object is changed. This happens in both binds described above (with or without TwoWay in bind Mode).
This is the only thing left to have a full Droid.Dialog project, working with bind and multiple views, controlled by viewModels, using MvvmCross framework.
From what I've been able to debug (only Droid code and no PCL, in VS2010), every time I change the text in the EntryElement, the OnTextChanged method is called and the property Value is beeing updated.
EntryElement.cs
    public virtual void OnTextChanged(string newText)
    {
        //Log.Info("Just playing","New text:" + newText);
        OnUserValueChanged(newText);
    }

ValueElement.cs
    protected void OnUserValueChanged(TValueType newValue)
    {
        Value = newValue;
        FireValueChanged();
    }

    protected virtual void FireValueChanged()
    {
        var handler = ValueChanged;
        if (handler != null)
            handler(this, EventArgs.Empty);
    }

Here's the code I have in core and droid projects
CORE
BaseViewModel.cs
    public class BaseViewModel : MvxViewModel, IMvxServiceConsumer
    {
        protected IConfigurationDataStore ConfigDataStore
        {
            get
            {
                if (_configDataStore == null)
                    _configDataStore = this.GetService<IConfigurationDataStore>();

                return _configDataStore;
            }
        }
        private IConfigurationDataStore _configDataStore;
    }

EditConfigurationViewModel.cs
    public class EditConfigurationViewModel : BaseViewModel, IEditConfigurationViewModel
    {
        public ConfigurationSet Configuration
        {
            get { return _configuration; }
            set
            {
                if (_configuration != value)
                {
                    _configuration = value;
                    RaisePropertyChanged(() => Configuration);
                }
            }
        }
        private ConfigurationSet _configuration;

        public EditConfigurationViewModel(string id)
        {
            Guid value;
            if (string.IsNullOrEmpty(id) || !Guid.TryParse(id, out value))
            {
                Configuration = new ConfigurationSet();
            }
            else
            {
                Configuration = ConfigDataStore.GetConfiguration(value);
            }
        }

        public void SaveConfiguration()
        {
            ConfigDataStore.UpdateConfiguration(Configuration);
        }
    }

ConfigurationSet.cs
    public class ConfigurationSet : MvxNotifyPropertyChanged
    {
        public string Pin
        {
            get { return _pin; }
            set
            {
                if (_pin != value)
                {
                    _pin = value;
                    RaisePropertyChanged(() => Pin);
                }
            }
        }
        private string _pin;

        public string Name
        {
            get { return _name; }
            set
            {
                //if (_name != value)
                //{
                    _name = value;
                    RaisePropertyChanged(()=> Name);
                //}
            }
        }
        private string _name;

        public string PrivateDescription
        {
            get { return _privateDescription; }
            set
            {
                if (_privateDescription != value)
                {
                    _privateDescription = value;
                    RaisePropertyChanged(() => PrivateDescription);
                }
            }
        }
        private string _privateDescription;
    }

DROID
EditConfigurationView
    public class EditConfigurationView : MvxBindingDialogActivityView<EditConfigurationViewModel>, IMvxServiceConsumer
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            DroidResources.Initialise(typeof(Resource.Layout));

            Root = new RootElement()
                {
                    new Section("Private Configuration")
                    {
                        new EntryElement("Pin:").Bind(this, "{'Value':{'Path':'Configuration.Pin'}}"),
                        new EntryElement("Name:").Bind(this, "{'Value':{'Path':'Configuration.Name'}}"),
                        new EntryElement("Description:").Bind(this, "{'Value':{'Path':'Configuration.PrivateDescription'}}")
                    }
                };
        }

        public override void OnBackPressed()
        {
            ViewModel.SaveConfiguration();

            base.OnBackPressed();
        }

        protected override void OnViewModelSet()
        {

        }
    }

Answer: Second answer after seeing your repo on https://github.com/zleao/MvvmCross.Dialog

Thanks for the additional information.
I've not run your sample yet, but seeing the simple code to reproduce the problem helps a lot.
I think the problem is probably in your Setup file - https://github.com/zleao/MvvmCross.Dialog/blob/master/MvvmCross.Dialog.UI.Droid/Setup.cs
The Setup there inherits from MvxBaseAndroidBindingSetup which is the base setup class for everything in Cirrious.MvvmCross.Binding.Droid and which itself inherits from MvxBaseAndroidSetup from Cirrious.MvvmCross.Droid
Since you are using the Dialog code in addition to "just Binding" then you need to take your setup further - you need to add MvxBaseAndroidDialogBindingSetup from Cirrious.MvvmCross.Dialog.Droid. This class adds a number of important steps including registering a two-way binding for Value on all ValueElement instances - see:
    protected override void FillTargetFactories(
        Cirrious.MvvmCross.Binding.Interfaces.Bindings.Target.Construction.IMvxTargetBindingFactoryRegistry registry)
    {
        registry.RegisterFactory(new MvxPropertyInfoTargetBindingFactory(typeof (ValueElement), "Value",
                                                                         (element, propertyInfo) =>
                                                                         new MvxElementValueTargetBinding(element,
                                                                                propertyInfo)));
        base.FillTargetFactories(registry);
    }

in https://github.com/slodge/MvvmCross/blob/vnext/Cirrious/Cirrious.MvvmCross.Dialog.Droid/MvxBaseAndroidDialogBindingSetup.cs

So - to try to fix the problem, try inheriting Setup from  MvxBaseAndroidDialogBindingSetup

For more info about the layers of MvvmCross, please see http://slodge.blogspot.co.uk/2012/12/a-short-guide-to-layers-of-mvvmcross.html

I hope this helps and solves the problem.
Thanks for the excellent level of detail supplied.
Please do note, though, that the Droid.Dialog code is still quite young compared to the Touch Dialog code - so you may hit genuine bugs and problems along the way. When you hit them, please do ask question here, or if they are bugs, then please do log them on Issues on https://github.com/slodge/MvvmCross/issues?state=open
Stuart
Comment: I've just tested with the change you sugested, and the magic is all there now!!! :) I'll update the repo with a more complex and complete scenario, as soon as I can (hopefully tomorrow). Thank you for the help!
Answer: I've just tested this with a modified CustomerManagement sample app - and this binding is working Two-Way fine for me.
My code:
        Root = new RootElement()
            {
                new Section("Customer Info")
                    {
                        new EntryElement("Name").Bind(this, "{'Value':{'Path':'Customer.Name'}}"),
                        new EntryElement("Website").Bind(this, "{'Value':{'Path':'Customer.Website'}}"),
                        new EntryElement("Phone").Bind(this, "{'Value':{'Path':'Customer.PrimaryPhone'}}"),
                    }
            };

My ViewModel and Customer object are:
public abstract class BaseEditCustomerViewModel
    : BaseViewModel
{
    private Customer _customer;
    public Customer Customer
    {
        get { return _customer; }
        private set { _customer = value; RaisePropertyChanged("Customer"); }
    }

    // ...
}

public class Customer : MvxNotifyPropertyChanged
{
    public Customer()
    {
    }

    private string _name;
    public string Name
    {
        get { return _name; }
        set { _name = value; RaisePropertyChanged("Name"); }
    }

    private string _website;
    public string Website
    {
        get { return _website; }
        set { _website = value; RaisePropertyChanged("Website"); }
    }

    private string _primaryPhone;
    public string PrimaryPhone
    {
        get { return _primaryPhone; }
        set { _primaryPhone = value; RaisePropertyChanged("PrimaryPhone"); }
    }

    // ...
}

From your description I couldn't spot any obvious errors - although obviously I can't see all the details - e.g. what is the Configuration object on the ViewModel side?

If you suspect this might be a bug, it's probably easiest to log these on https://github.com/slodge/MvvmCross/issues/new
The more detail you can include with a bug the quicker it will get looked at - e.g. if you can include a sample github repo which reproduces the problem, then it's quick and easy for a developer to test. If, instead, you just provide instructions, then it might take a developer 1 or more hours to test - so you need to wait for them to have 'spare time'.

For the complaint about 'debug ... only Droid code and no PCL, in VS2010', please ensure you've raised this with Xamarin - the only way they will fix these things is if there paying customers tell them about problems.
Comment: I've edit the question and added the code I have in the 'Core' and 'Droid' projects. I'll prepare a sample to put in GitHub repo. Thanks
Comment: I've added a repo in GitHub with a very simple example of what I've described here. (https://github.com/zleao/MvvmCross.Dialog)
Answer: this is also required in iOS.
public class Setup : MvxIosDialogSetup//MvxIosSetup


Moderator deleted my question as spam, but it is the opposite of spam - I am calling out the company's claims

Question: A moderator said my question looked like spam and deleted it. I was asking about   LiteSpeed Web Server with LiteMage Cache. It is a genuine question. I specifically called the company's claims into question and asked if I should believe them. That is the opposite of spam. I'm not promoting the company, I am questioning the company's claim. Furthermore, I really do need to know the answer.
How can I have my question undeleted? I am open to editing it to make it even more clear that I am not promoting the company in any way.
In case it is required, here is the url to my deleted question: https://magento.stackexchange.com/questions/298027/
Answer: Sorry about that. I went through a list of spam posts containing "lite"-something. I guess thid got in the middle and disn't pay much attentìon. Will un delete it.
Comment: I made some edits. I hope it is more clear now. Thanks again.
Comment: Thank you. If you want me to reword it, I'm happy to do so.


Looking for a formula to determine accuracy of a sample

Question: I am looking for a formula to help me determine the accuracy of a population.
Here is my business problem.
I have about 1 million scanned documents of many types that are currently unclassified sitting in one folder.
I have used an AI program to group each different type of document into each own folder.
So I now have about 90 folders, each folder is supposed to only have one type of document in it.
So if I go into Folder A, all the documents in that folder should be the same.
If I go into Folder B, all the documents in that folder should be the same.
etc.
Now I want to check how well this model is working. I am looking for 90% accuracy.
Meaning in Folder A I am confident that 90% of the documents in that folder are all of the same type.
I could have a user go into Folder A and check every document but there could be 10k documents in there. So that manual work is not feasible.
So I want them to check a sample of the documents in folder A so that I am fairly certain that I have achieved the 90% accuracy rate.
Is there a formula that:
given a size of population (how many documents are in the folder),
desired accuracy (90%)
returns how many documents need to be validated.
And if the sample check are all correct the probability is the rest of the population is correct?
Appreciate the help,
Alex
Comment: Do you have an expected accuracy rate? If you're regularly getting 100% accuracy, you'd only need about 50 examples to very convincingly show that you're better than 90% accuracy. But if your observed accuracy is 90.1%, you'll need about a million examples to convincingly show that you're truly doing better than 90%.
Comment: I want a 90% accuracy rate. Meaning each folder is 90% accurate. If there are 10 documents in the folder 9 are the same. My goal is without checking all 10 documents can I check a subset and be confident if the subset is all the same then at least 90% of the total population is the same.
Comment: Right, what I'm getting at is the number of documents you need to review depends on what the observed accuracy values look like. If you review 10 documents and find that 0 of them are correct, you don't need to review anything else in that folder - even from a very small sample with 0% accuracy, it's incredibly unlikely that the true accuracy rate is higher than 90%. But if you find that 9 of the 10 documents are correct, it's still entirely plausible that the true accuracy is only 85%, and that's still true even if you find 90 of 100 correct.
Comment: Correct. So what I am looking for is a formula given a size of a set population how many documents do I need  to check to be at least 90% confident. So if I have 1000 documents in a folder how many do I check to be confident 90% of the population is correct. 100? 200? 300? etc.
Answer: Were the 90 types defined in advance, and each folder labelled with the expected type? If so, they you are right to say that you can measure accuracy. For each document, there is a yes-no question "is this document in the right folder?" This is a Bernoulli trial. Your question about sample size is answered by well known statistics.
Or did you run a clustering algorithm, so the clusters are emergent from the data? Then the question about a document is "does it resemble the other documents in the same folder?". That is a harder question. There are several alternative relevant quality scores. Sorry, I don't know what the rules are for sample size in these cases.
Comment: Hi, the way the model works is I fed one example of each document to the AI application and it used these 90 different examples to break out the remaining documents. So the 90 types are known in advance because I gave 90 examples. Now I want to check how successful the application was. Without going into each folder and checking every single document.
Comment: Great, in that case you are sampling from Bernoulli distributions, so the link will tell you the answer: in brief, the error bar is proportional to the square of the sample size, which isn't particularly good news.


How to set gradient background in TopAppBar using Jetpack Compose

Question: I want to set the gradient background of my TopAppBar:
My code:
TopAppBar(
    modifier = Modifier.background(
        Brush.horizontalGradient(
            colors = listOf(
                Color.Red,
                Color.Green
            )
        )
    ),
    title = { Text("UI Components") },
    backgroundColor = Color.Transparent
)

Result:

I found this post: Jetpack Compose Button with gradient background? for button - so I set backgroundColor transparent and custom background via a modifier. Sadly in my case, there is an additional shadow around text which I don't know how to remove. What should I change or maybe TopAppBar is just not designed to be used using gradient and I should write something completely custom?
Answer: This shadow is caused by default elevation. Set it to zero:
TopAppBar(
    modifier = Modifier.background(
        Brush.horizontalGradient(
            colors = listOf(
                Color.Red,
                Color.Green
            )
        )
    ),
    title = { Text("UI Components") },
    backgroundColor = Color.Transparent,
    elevation = 0.dp
)

Answer: In TopAppBar from Material3 like this:
TopAppBar(
    modifier = Modifier.background(
    Brush.horizontalGradient(
        colors = listOf(
            Color.Red,
            Color.Green
            )
        )
    ),
    title = { Text("UI Components") },
    colors = TopAppBarDefaults.smallTopAppBarColors(containerColor = Color.Transparent, navigationIconContentColor = onPrimaryColor, titleContentColor = onPrimaryColor),
)

notice of  containerColor = Color.Transparent
Answer: In latest TopAppbar
you cannot set
  backgroundColor = Color.Transparent, instead you have to use
colors = TopAppBarDefaults.topAppBarColors(
            containerColor = Color.Transparent
        )


Array() vs new Array()

Question: What is the difference (if there is any) between
x = Array()

and
x = new Array()

Which one should I use?
Comment: You might find this interesting: http://stackoverflow.com/questions/383402/is-javascript-s-new-keyword-considered-harmful
Answer: The spec says:

When Array is called as a function rather than as a constructor, it creates and initialises a new Array object. Thus the function call Array(…) is equivalent to the object creation expression new Array(…) with the same arguments.
Answer: You should use the literal []. Reasons are outlined here. Using the Array() constructor can be ambiguous, since it accepts either a length or a list of elements:
new Array(5)   // [ , , , , ]
new Array('5') // ['5']

[5]   // [5]
['5'] // ['5']

The reason you can use Array without the new operator is that internally it does a common trick with constructors:
function Thing(){
    if (!(this instanceof Thing)){
        return new Thing()
    }
    // ... define object
}

That is, if you call Thing() it will call new Thing() for you.
Comment: Actually, ```new Array(5)``` gives ```[,,,,]```
Comment: In ES5, To avoid this issue, you can use `Array.of`: "Array.of(7) creates an array with a single element, 7, whereas Array(7) creates an empty array with a length property of 7"
Answer: Some facts that worth to mention:
Array === Array.prototype.constructor //true

and
new Array() does the same as new Array and [] as well
However, the result of calling a constructor is not necessarily equivalent to creating a new instance of an object. Example:
Foo = function(){}

x = Foo()   // undefined
y = new Foo // {}

So x and y can be different.
But if the Object itself is an Array you will get the same by definition, as mentioned earlier.
x = Array()   // []
y = new Array // []

Even if you pass one integer (telling the length)
x = Array(3)     // [empty × 3]
y = new Array(3) // [empty × 3]

or one non integer (telling the content)
x = Array(true)     // [true]
y = new Array(true) // [true]

or more parameters (telling the content)
x = Array(1,2,3)     // [1,2,3]
y = new Array(1,2,3) // [1,2,3]

Comment: @Melab what is the 1 %?
Comment: that part about object literal `[]` being the same as `Array` and `new Array` is not true am afraid. Read more here: https://stackoverflow.com/questions/931872/what-s-the-difference-between-array-and-while-declaring-a-javascript-ar
Comment: @azrahel you will get the same empty array using any of above expression (if `Array` is native), try: `{a:new Array,b:new Array(),c:[]}`
Comment: no you will not :) just read the link or documentation. Using object literal `[]` takes some shortcuts and internally does not execute some code that constructor does. If you don't care about performance or other edge case issues, sure, use whichever. If you do care though, you should know about differences, cause there are some. So what am saying is 'yes' you will get empty array in each case, but 'no' it s not going to be the same structurally/internally.
Comment: @azrahel It's no doubt that performance may differ, but technically each do the same thing. Ref:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Array_literals , https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Using_object_initializers
Comment: That `Array === Array.prototype.constructor` evaluates to `true` is completely uninteresting and holds for 99% of all JavaScript functions.

Array() vs new Array()


Questions regarding python setup script

Question: I have a few questions regarding python setup scripts or rather how to properly setup a module (as I am doing this for the first time and kind of struggling).
For simplicity I just post a link to the corresponding github repository rather than explaining the project in detail. I am fully aware that the project as it is will not work (e.g. the file constants.py is missing) but for starters I would like the "structure" to work.
There are two main components in this project, i.e. pymap and agb - both dependent on each other (which should not be a problem I guess). I also would like to use scripts located in the bin/ directory which of course use the modules pymap and agb. For installation I use sudo ./setup.py develop which installs the modules as I can now use them in a python3 shell. The line import pymap.pymap_gui will throw an error (since constants.py is not yet in the project) however the import can be resolved.
When - on the other hand - calling the scripts with pymap.py the same import can not even be resolved:
ModuleNotFoundError: No module named 'pymap.pymap_gui'; 'pymap' is not a package

How can this be even though from a python3 shell the import works perfectly fine?
Furthermore - where to improve my project structure? Is my setup the way to go (not minding the messy code and not yet working project itself - I am viewing this from kinda structure-ish perspective).
Answer: The problem was simply that the module had the same name as the script (pymap and pymap.py). Sorry for bothering!

Questions regarding python setup script


How to update/reset formBuilder attribute value?

Question: Trying to set CURRENT_TEXT value to empty string "" every time function is called but it is always getting previous selected value , Any idea what has been implemented wrong ?
main.ts
<code>constructor(private dataService: ApiService, private eventService: EventService, private formBuilder: FormBuilder) {
    this.questionForm = this.formBuilder.group({
        alrgyDetls: formBuilder.group({
            ALLERGY_DETAILS: ['']
        }),
        curntText: this.formBuilder.group({
            CURRENT_TEXT: ['']
        })
    });
}
formatSubQuestions(e: any) {
    const answerOption = [{
        "answerOptionId": 0,
        "answerText": "",
        "answerOptionId2": 0

    }];
    this.questionForm.currentText.patchValue({
        CURRENT_TEXT: " "
    });
    if (e) {
        answerOption[0].answerText = this.questionForm.get('curntText.CURRENT_TEXT').value || "";
    }
}
}
</code>
Answer: Hi do you really want to have two formGroups inside the form, maybe instead you wanted to have two form controls.
But for your example you can do it the following way:
<code>  formatSubQuestions(e: any) {
    const answerOption = [{
      "answerOptionId": 0,
      "answerText": "",
      "answerOptionId2": 0

    }];

    const formControl = this.questionForm.get('curntText').get('CURRENT_TEXT'); // get the wanted form control
    const oldValue = formControl.value; // save the old value before clearing it
    formControl.patchValue(''); // clear its value
    if (e) {
      answerOption[0].answerText = oldValue || '';
    }
  }
</code>


Set convergence and lim inf and lim sup

Question: I'm a bit confused with the general concept of convergence of a sequence of sets.
I'm well aware that the limit of a sequence $\{C^{\nu}\}$ exists iff $$\liminf_{\nu \rightarrow \infty} C^{\nu} = \limsup_{\nu \rightarrow \infty} C^{\nu}$$ where lim inf (resp. lim sup) is the set of points that appear in the limit all but finitely many times (resp. infinitely many times).
However, intuitively, the limit point can appear only once, i.e., for $\nu \rightarrow \infty$. Isn't this in contrast with the concepts of lim inf and lim sup (defined as above)?
For instance, let $C^{\nu} \triangleq [0,1-1/\nu]$: the sequence $\{C^{\nu}\}$ should (intuitively) converge to $C \rightarrow [0,1]$. However, I think the point $\{1\}$ is included in $C$ only for $\nu=\infty$ and, therefore, it appears only once.
What am I missing?
Comment: The sequence $[0,1-1/\nu]$ converges to $[0,1)$.
Comment: $\nu$ does not take 'value' $\infty$.
Comment: @V.C.Are you absolutely sure? I have been told otherwise here by Jeff Snider http://math.stackexchange.com/questions/699384/nonconvex-set-converging-to-a-convex-set-despite-holes?noredirect=1#comment1465968_699384 (see comments)
Comment: @ItaAtz Yes, I'm sure. Since the sequence $[0,1-1/\nu]$ is monotone non-decreasing, we have that $\lim_{\nu\to\infty}[0,1-1/\nu]=\cup_{\nu=1}^\infty[0,1-1/\nu]=[0,1)$.
Comment: @V.C. Can I have a reference to this statement? As a general comment, can you suggest me a good reference (book, or whatever), other than "Variational Analysis" by Rockafellar and Wets (and possibly simpler) to study these concepts of set convergence theory? Thanks a lot
Comment: @ItaAtz Check Proposition A.4.2 in http://www.theanalysisofdata.com/probability/A_4.html. Also, there are nice chapters about limits of sets and monotone sequences in Sidney I. Resnick "A Probability Path" (Chapters 1.3 and 1.4).
Answer: There are two competing definitions of $\liminf$ and $\limsup$.  The one referenced by @V.C. in the comments is this:
$$\liminf_{\nu\to\infty} C_\nu := \bigcap_{n\in\mathbb{N}}\bigcup_{\nu\ge n}C_\nu$$
which we can rewrite in the notation of Rock & Wets as
$$\liminf_{\nu\to\infty} C_\nu := \bigcap_{N\in\mathcal{N}_\infty^\#}\bigcup_{\nu\in N}C_\nu.$$
The definition from Rock & Wets, and other sources such as Hocking & Young, adds a closure:
$$\liminf_{\nu\to\infty} C_\nu := \bigcap_{N\in\mathcal{N}_\infty^\#} \text{cl}\bigcup_{\nu\in N}C_\nu.$$
(For $\limsup$ simply transpose the union and intersection operators.)
For what it's worth, Wikipedia uses the latter definition, written equivalently as:
lim inf Xn, which is also called the inner limit, consists of those elements which are limits of points in Xn for all but finitely many n (i.e., cofinitely many n). That is, x ∈ lim inf Xn if and only if there exists a sequence of points {xk} such that xk ∈ Xk and xk → x as k → ∞.
Note that in a discrete space the two definitions coincide.  $\mathbb{R}^n$ with the usual topology is not a discrete space.
Comment: Thanks @Jeff Snider, I've been fighting with this dilemma for days. Perhaps you'd like to take a look at this other question of mine: http://math.stackexchange.com/questions/698966/sequence-of-solutions-of-approximated-problem-converging-to-stationary-solution It's the problem for which (very recently) I had to start studying set convergence theory.
Comment: Actually I've just noticed (from Rock & Wets Exercize 4.2(b)) that, to obtain the equivalent formula for the limsup, it's not just swapping the union and intersection operators but rather considering the whole set or the its "tail".

Set convergence and lim inf and lim sup


Where have we used that $G$ is a compact Lie group?

Question: Let $G$ be a compact Lie group acting on a topological space $X$.

I need to show that the orbit map $p:X\rightarrow X/G$ has the path
  lifting property.

Here is the proof -
Let $f:I\rightarrow X/G$ be a path in $X/G$. Let $G$ act trivially on $I$.
Consider $f^*X$ , the pullback of $X$ via $f$. That is $f^*X=\{(x,y)\in X\times I : p(x)=f(y)\}$. Let $p':f^*X\rightarrow X$ be the projection to first co-ordinate.
Then $f^*X$ has a natural $G$ action and the orbit space $(f^*X)/G\cong I$. Thus we have a section $\sigma:I\rightarrow f^*X$ (a section for the projection $p:X\rightarrow X/G$ is a continuous map $\sigma:X/G\rightarrow X$ such that $p\circ \sigma =id_{X/G}$)
So the map $p'\circ\sigma:I\rightarrow X$ is a lift of $f$ and we are done.

I don't see where we have used the fact that $G$ is a compact Lie group in this proof

As I understand, we can define pullback or sections in the context of any topological group $G$ acting on a topological space $X$. Or am I wrong?
Thank you!
Comment: Well: compactneess of $G$ does not guarantee that there is a section. For example, if $G=S^1$, viewed as a sbgroup of the multiplicative group of $\mathbb C$, acts on $S^3$, viewed as the unit sphere in $\mathbb C^2$, by scalar multiplication then the quotient map is $S^3\to S^3/G\cong S^2$ is the Holf fibration, and it does not have a section. (A simpler example is $G=\{\pm1\}$ acting on $S^1$ with quotient $S^1$, I guess)
Comment: That will not be continuous in general, as Eric's example shows...
Comment: What **is** true is that there are sections *locally* around every point of $X/G$, and that is enough to construct your lifting. (This is related to the existence of "slices" for the action,and this is much more delicate when the group is not compact (but it should hold when the the acion has compact stabilizers, I guess...))
Comment: No, you quite often can't.  For instance, if $X=\mathbb{R}$ and $G=\mathbb{Z}$ acting by addition, there is no section.
Comment: How did you get the section $\sigma$?
Comment: For any $X$ and $G$ we can find a section $X/G\rightarrow X$ right? So here since $f(^*X)/G\cong I$ so we can have a section
Comment: Since $X\rightarrow X/G$ is surjective, for $[x]\in X/G$ and a choice of $x\in p^{-1}[x]$ sending $[x]$ to $x$ gives a section doesn't it?
Comment: A section is injective: if in Eric's example there were a section we would have a subspace of $\mathbb R$ homeomorphic to $\mathbb R/\mathbb Z\cong S^1$.
Comment: Oh I see! So I guess that is where the compactness is needed. I shall think about it. Thank you @EricWofsey and Mariano
Answer: If $X$ is Hausdorff then the path-lifting property for the quotient map $X\to G/X$ is Theorem 6.2 in G.Bredon "Transformation Groups". The theorem itself is attributed to Montgomery and Yang. The proof is nontrivial.
Comment: thank you for the reference. Theorem 6.1 tells me how to get the section I need for the proof in my question to make sense.


What is the difference between "$=$" and "$\equiv$"?

Question: I was recently thinking about some of my past math classes, and depending on the context I recall my professors would sometimes use the "$\equiv$" symbol in places where I'd feel "$=$" to be more appropriate. For example, since this would often be the case in my classes on differential equations and Fourier series, we would have (for $n \in \Bbb N, k \in \Bbb Z$)
$$(-1)^{2n+1} \equiv -1$$
$$\sin(k\pi) \equiv 0$$
Is there a particular reason in this context why we would say "$\equiv$" instead of "$=$"? The latter feels more natural in this context, which makes me think that there's some reason my professors would use the former.
I'm familiar with the notion of the "$\equiv$" symbol in the context of, say, elementary number theory (specifically modular arithmetic) where we might say
$$10 \equiv 1 \pmod 3$$
which isn't saying "$10$ equals $1$", just that "$10$ is like $1$ in this context." But that doesn't seem to fit the case as with the first two statements - because I don't believe it is that $(-1)^{2n+1}$ is like $-1$, or that $\sin(k \pi)$ is like $0$, they are $-1$ and $0$ respectively.
Am I just mistaken on this latter fact? Is there something I'm missing? What, precisely, is the difference between the two notations?
Comment: I think people usually use $\equiv$ for equality of functions. For your examples, the functions $f: \mathbb{Z} \to \mathbb{R}$ and $g: \mathbb{Z} \to \mathbb{R}$ given by $f(n) = (-1)^{2n+1}$ and $g(k) = \sin(k \pi)$ are *identically* the functions $-1$ and $0$, so we write $f \equiv -1$ and $g \equiv 0$.
Comment: when speaking about functions, we would interpret $f(x) = 0$ as the statement that there exists an $x$ where $f(x) = 0$, and interpret $f(x) \equiv 0 $ as the statement that for all $x$, $f(x) = 0$. The first statement read aloud says $f$ is equal to 0 at $x$, the second is $f$ is identically 0, that is, it is equal to the 0 function.
Comment: @staedtlerr nobody interprets "$f(x) = 0$" as "there exists an $x$ where $f(x) = 0$". people would assume the speaker is referring to some specific $x$.
Comment: It is usually used as denoting "identically equal to". For example, $\sin(k \pi)=0$ could be read as an equation in $k$, but $\sin(k \pi) \equiv 0$ means that this is always 0 (for integer k). Just like $f(x) \equiv 0$ would mean the function is identically 0
Comment: To piggy-back on mathworker21's comment, $(-1)^{2n+1}$ is a number, depending on a variable $n$, whereas $\mathbb{N} \to \mathbb{Z} : n \mapsto (-1)^{2n+1}$ is a function. To say $(-1)^{2n+1} \equiv -1$ is shorthand for saying the above function is equal to the constant function $1$, or in other words,$$n \mapsto (-1)^{2n+1} = n \mapsto -1.$$
Comment: The first two are [identities](https://en.wikipedia.org/wiki/Identity_(mathematics)), i.e. equalities that hold true for all values of the free variables, i.e. they are implicitly universally quantified. The third is a [congruence relation,](https://en.wikipedia.org/wiki/Congruence_relation) i.e. an equivalence relation on an algebraic structure that is compatible with all operations.
Comment: Ahhhhh, I see. Thanks for the insight you two. ^_^
Answer: I'll give an example of each.
$$2x=x+1$$
This holds when $x=1$ only, and so the equality symbol is appropriate. In short, we use an $=$ when specific values solve the expression.
On the contrary, we have:
$$2x\equiv x +x$$
Whatever the value of $x$, this holds. This is an algebraically obvious one, but another might be $$\sin^2 x + \cos^2 x \equiv 1$$
The identity symbol $\equiv$ is used when an equality holds for all values in the domain specified (e.g. $\Bbb R$).
Comment: +1. I like to think of "$\equiv$" as "$=$" with an emphatic underscore. :)
Comment: Oooh, nice analogy, thanks for that Blue.
Answer: The equal sign "$=$" is used for equalities ,equations, identities and definitions of functions.
Examples of equalities are $3=2+1$ or $12^2 = 144$ where two numbers are the same.
Examples of equations are $ 3x+1=10$ or $x^2-4=0$ where for some values of the variable both sides result in the same value.
Examples of  identities are $\sin ^2 x + \cos ^2 x =1$ or $(x+y)^2 = x^2+y^2+2xy$ where both sides are identical for every value of variables.
For identities sometimes $\equiv $ is used instead of  $=$ for example we may use $ e^{i\theta} \equiv \cos \theta + i \sin \theta$ or $\sin ^2 x + \cos ^2 x \equiv 1$ or $(x+y)^2 \equiv  x^2+y^2+2xy$  to emphasize that this is an identity not an equation.
For functions we sometimes use $ f(x) \equiv c$ to emphasize that the given value $c$ is for all values of $x$


Set raw value with Rails.cache.write

Question: I'm trying to save entire response.body to memcached. I'm doing it like so:
Rails.cache.write(request.headers['HTTP_X_MEMCACHED_KEY'], response.body)

The problem is that it prepends some garbage to the value:
o: ActiveSupport::Cache::Entry  :@compressedF:@expires_in0:@created_atf1355928410.584484:@value"GsI";s<!DOCTYPE html>...

I tried to pass :raw => true to Rails.cache.write, but it returns false and doesn't put the value to memcached. I think it fails because response.body is not properly escaped.
I also tried this way:
Rails.cache.write(request.headers['HTTP_X_MEMCACHED_KEY'], Marshal.dump(response.body), :raw => true)

It works, but there's still some garbage in the value:
I"fD<!DOCTYPE html>...

How to put a clean value into memcached?
Answer: It seems memcached was unable to cache data because of unescaped unicode characters in response.body.
Now I'm passing response.body.bytes.to_a.map(&:chr).join as the value, it works fine, but I'm still wondering if it is the best solution.
Comment: Did you ever find a better solution? I want to get rid of those random values too.
Answer: writing response.body.force_encoding('ASCII-8BIT') might be a solution
Comment: Please explain your answer.

Set raw value with Rails.cache.write


Understanding Node.js event loop. process.nextTick() never invoked. Why?

Question: I am experimenting with the event loop. First I begin with this straightforward code to read and print the contents of a file:
var fs = require('fs');
var PATH = "./.gitignore";

fs.readFile(PATH,"utf-8",function(err,text){
    console.log("----read: "+text);
});

Then I place it into an infinite loop. In this case, the readFile function is never executed. If I am not mistaken it's because Node's single thread is busy iterating without letting I/O calls be executed.
while(true){
    var fs = require('fs');
    var PATH = "./.gitignore";

    fs.readFile(PATH,"utf-8",function(err,text){
        console.log("----read: "+text);
    });
}

So, I would like to do something so that I/O calls are assigned process time intertwined with the loop. I tried with process.nextTick() but it doesn't work:
while(true){
    process.nextTick(function(){
        fs.readFile(PATH,"utf-8",function(err,text){
            console.log("----read: "+text)
        });
    });
}

Why isn't it working and how could I make it?
Answer: Because your while loop is still running.  It's just infinitely adding things to do in the next tick.  If you let it go, your node process will crash as it runs out of memory.
When you work with async code, your normal loops and control structures tend to trip you up.  The reason is that they execute synchronously in one step of the event loop.  Until something happens that yields control to the event loop again, nothing 'nextTick' will happen.
Think of it like this, You are in Pass B of the event loop when your code runs.  When you call
process.nextTick(function foo() { do.stuff(); })'

you are adding the foo to the list of 'things to do before you start pass C of the event loop.' Every time you call nextTick, you add one more thing to the list, but none of them will run until the synchronous code is done.
What you need to do instead is create 'do the next thing' links in your callbacks.  Think linked-lists.
// var files = your list of files;
function do_read(count) {
     var next = count+1;
     fs.readFile(files[count], "utf-8", function(err,text) {
         console.log("----read: " + text);

         if (next < files.length) {
            // this doesn't run until the previous readFile completes.
            process.nextTick(function() { do_read(next) });
         }
     });
}
// kick off the first one:
do_read(files[0], 0);

(obviously this is a contrived example, but you get the idea)
This causes each 'next file' to be added to the 'nextTick' to-do queue only after the previous one has been fully processed.
TL;DR:  Most of the time, you don't want to start it doing the next thing until the previous thing is completed
Hope that helps!
Comment: very good explanation can you give some prove to verify your statement about process.nextTick. like any doc by node or javascript.


Possibility to limit old content that is displayed to a new user

Question: I am setting up a website with Drupal 7. I would like to provide premium content for subscribers on monthly basis. I would like provide ability to buy a recurring subscription.
To avoid leeching old content, that has previously been published, is it possible to limit visibility of blog posts form history?
Let me try to clarify the use case:
I would like to provide content to my Premium subscribers in December 2012. All the users that are members in December 2012 would be eligible to see all the content created then. Since I would like this type of subscription to be real time, it would need to restrict the usage of content created before one's membership. When January 2013 arrives, I would like to have recurring membership continue, but new users that arrive in January, would be restricted to content that have been published only when they are subscribers.
The best would be, that if one purchased Dec 2012, left Jan 2013 away and resubscribed Feb 2013, he or she would see material produced in Dec 2012 and Feb 2013, but not Jan 2013.
Dripping Content would be nice, but I am not providing that kind of cumulative courses but time based content instead, and would not like to provide new users the ability to leech all the old material that they've not paid for at the time.
Thank you in advance!
Answer: To do this, you probably should implement hook_node_access($node, $op, $account).
You should return:

NODE_ACCESS_ALLOW if content is new, or user have premium role
NODE_ACCESS_DENY if content is old and user does not have premium role
NODE_ACCESS_IGNORE if you do not want to control access for this content type

There are already contributed modules to sell roles, or to take payments, so this part should be easy.
Note that hook's documentation says:

See Node access rights for a full explanation.

I strongly advise to do it.


Github.com cannot render newlines

Question: I am facing a Git (Github.com) issue, that it cannot properly render newlines. Instead, it renders a set of "^M" symbols where newline character (-s) should be.
An image below is an excerpt of a diff:

I have set the git option "git config --global core.autocrlf true". I have also changed the file encoding to UTF-8. Before it was windows-1252 (I have recommited the files). Neither of these actions helped.
Environment details:

IDE: PHPStorm 2017.3.6
OS: Windows 10
Language: PHP

Thank you!
Answer: That's an artifact of the previous character encoding you were using, and whatever process you used to convert to UTF-8 didn't convert the newlines properly. The fixes in this question's answers should help you, too: '^M' character at end of lines
Answer: UTF-8 is character encoding.
The ^M is a token for a  CR character which is part of the end-of-line behavior your editor is using.
The end-of-line behavior is separate from character encoding.
how you set your git config is largely dependent on whether you are working from a windows box, and also whether you intend the code to execute on a windows box.  If everything is windows then you should be able to safely set it to
git config --global core.autocrlf false

which will commit the CR+LF (standard windows-style end-of-line) into the repository.
If you code is going to reside on a linux server then you will more likely want to set it to
git config --global core.autocrlf input

which will allow git to convert the CR+LF to LF (standard unix-style end-of-line) only on commits to the repository.

Github.com cannot render newlines


Why only hyperplanes in support-vector machines?

Question: I only recently learnt about support vector machines. From what I understood, hyperplanes are used to separate the data (raised to the higher dimension) into two mutually exclusive parts (partitions). My question is why should it be a hyperplane and not a surface with a curvature(s)? Wouldn't that provide a better suited separating 'surface'?
Comment: To my limited layman understanding, the space itself is manipulated to achieve the same effect.
Answer: Nonlinear classification is possible.
https://en.wikipedia.org/wiki/Support_vector_machine#Nonlinear_classification
Answer: That the hyperplane does not really exist. It is not computed. It is not really treated as a hyperplane either.
The SVM decision is based on the similarity to the support vectors; which implicitly defines a hyperplane in some Euclidean space. When using a kernel function, this does not need to be your original data space; and it may well be non-linear in the original data space, if you are using a non-linear kernel function for computing your similarities.
Answer: There exists something called a Kernel Function: http://en.wikipedia.org/wiki/Kernel_trick
From what I remember from a Data Mining class, you perform a non-linear transformation of each point into a higher dimension. Say your data is in just two dimensions and is not linearly separable. If you convert each (x, y) into (x, y, z) (or more dimensions if necessary, probably likely) using a Kernel Function then you may be able to separate the data with a plane / hyperplane / higher dimensional hyperplane without involving curvature.
As an example of a Kernel Function, apply this to "generate" a higher dimension, math is similar to binomial expansion: f(x, y) == (x*x, y*y, 2xy)


Product metric, continuity of functions and minimum

Question: Suppose there are $n$ metric spaces $(X_i,d_i)$, and $X$ being the product space with the product metric $\rho$.
In proving that the projection function $\pi_i(x_1,...,x_n) = x_i$ is continuous, the proof follows something like this (not rigorous since it's only serving to motivate the question):

Fix $\varepsilon > 0$. Then we get the existence of $\delta := \varepsilon *2^{-i}$ such that
$\rho(x,y)$ = $\sum_{j=1}^{n} 2^{-j} min(1, d_j(x_j,y_j))$ < $\delta$
Implies that, for a specific $i$,
$2^{-i}d_i(x_i,y_i) \leq \sum_{j=1}^{n} 2^{-j} min\{1, d_j(x_j,y_j)\} < \delta$ (1)
So $d_i(x_i,y_i) < \varepsilon$ and the function is continuous.

In this proof, it actually follows that we can, without lose of generality, consider $min\{1,d_i(x_i,y_i)\}$ as $d_i(x_i,y_i)$, in (1). I would like to know why that is the case.
Thanks
Comment: That is because d and min{ 1,d } are equivalent metrics, that is generate the same topology.  The proposition can be proved in general without the use of any metrics by considering the inverse image of an open set by a projection.
Comment: Could you provide a hint for proving this with inverse image of an open set?
Answer: Let p = $\pi_i:X_1×..×X_n$ -> $X_i, (x_1,.. x_n)$ -> $x_i.$
To show p is continuous, let U be any open subset of $X_i$
and show $p^{-1}(U) is open.  This will also show
projections of infinite products are continuous.
In fact without much ado the projections can be shown to be open.
Comment: Thanks. How do I deal with the fact that many vectors in X lead to a projection of $x_i$? So the pre-image has many possible points.
Comment: What vectors?  Topological spaces have points, they do not have vectors.   The preimage of a set A by a function f is { x : f(X) in A }.  It is uniquely determined and will be empty, a singleton, finite or infinite.


What could cause my LSTM loss to decrease then increase?

Question: I'm training 5 stacked Bi-LSTMs on an NLP task.  The network fits well with a time series of length 30, and converges to around 0.97 AUROC.  However, when I increase the length of the time series to 50, this happens:

I'm not using masking (slows training down) and some time steps are padded entries, the proportion of which will have increased when I increased the length of the time series from 30 to 50.
I've tried a couple of different learning rates from 0.001 to 0.00005.  This model is at the limit of my hardware so I'm looking for some hints to fix it without resorting to extensive hyper parameter tuning. The loss function is binary cross entropy with a single binary output and the optimiser is Adam.
Any ideas what I should look for?
Comment: Sorry, I meant to type "masking" in my first sentence. (I haven't had my coffee yet.)
Comment: Does this behavior evince if you use masking? Does this behavior occur if you use vanilla SGD without momentum? I'm wondering if the network tends to predict the padding character for everything, giving the early decrease in loss, but then Adam's momentum takes over and the optimizer can't change direction quickly enough, causing it to assign high probability to the padding character alone. If it also occurs with vanilla SGD, it could be that the gradients have vanished, so it can't correct itself.
Comment: Both the 30-length and 50-length datasets have padding.  The 50-length will certainly have more padded time steps.  I don't know if this is a red-herring or not though!  Your idea is an interesting one.  Each epoch has 12,000 batches, so although the reductions in loss look very steep, they are happening over roughly 4x12,000 parameter updates before the loss starts to climb back up.  I can run an experiment with SGD and see if it is momentum, thanks!
Comment: Thanks for your help!
Answer: It turns out this was only co-incidentally to do with the increase in the length of the time series.  I was using a generator to iterate the training set.  With the increase in the length of the time series, I tweaked the generator to use less RAM and introduced a bug.  It turned out that the generator was progressively scrambling the training examples.  On the first few epochs, the training samples were not so scrambled that the model couldn't find a pattern to fit, so the AUROC increased.   As the scrambling was random, any pattern in the data progressively became noise and the model soon starts to under-estimate the amount of scrambling on the current epoch and so the loss increases each time.


Proving that: $9.9998\lt \frac{\pi^9}{e^8}\lt 10$?

Question: I would like to use mathematical tools to prove that
    $$9.9998\lt \frac{\pi^9}{e^8}\lt 10$$
With an on-line calculator I got
$$  \frac{\pi^9}{e^8}\approx 9.9998387978$$
But I do not know any good way to prove this. I failed to use Taylor expansion
$$e^8 =\sum_{n=0}^{\infty}\frac{8^n}{n!}$$
Any idea?
Comment: Guy:  Please stop making very trivial edits to get you post bumped to the front page.  This example here, among many others: indicate very inappropriate behavior.
Comment: That's funny. How did you discover such inequality?
Comment: @GuyFsone: nbubis' answer to the linked question has a structure that is similar to my answer here. The point is that the constant $e^{\pi}$ appears in the context of j-invariants and modular forms, hence it can be computed through fast-convergent numerical algorithms, recalling the AGM mean for the computation of complete elliptic integrals of the first kind. nbubis' answer is *very* satisfactory by my point of view, but I will take some time to think about an alternative approach. I am not sure to be able to do better.
Comment: It's looks nicer to proof $\,2980909<100 \cdot \pi^9<2980910\,$  and   $\,298095<100 \cdot e^8<298096\,$ . :-)
Comment: Well, it looks like taking natural logs helps.  You want $\ln(9.9998)<9\ln (\pi)-8<\ln (10)$.  Still numerical.
Comment: A natural question might be the following: can you show two rational numbers $r,s$ such that there are no integers $i,k,j$ such that $r^i \sim 10^k s^j$?
Comment: @IvanDiLiberti: how is that possible, if $\mathbb{Z}\log(r)+\mathbb{Z}\log(s)$ is dense in $\mathbb{R}$?
Comment: But than this inequality was expected! We couldn't know that $i=9, j=8, k=1$, but such numbers had to exist.
Comment: @IvanDiLiberti: of course, I get your point, there is nothing really *special* here, but I still find such kind of numerical coincidences amusing.
Comment: @JackD'Aurizio Please here is another one. I found your answer here clear and direct. But for this I haven,t found a satisfactory answer: https://math.stackexchange.com/questions/2482717/how-to-prove-19-999e-pi-pi20?rq=1
Comment: Thanks in advance.  I am not so familiar with the notion of "j-invariants and modular forms" :) that is why I got lost at some point.
Answer: My approach can be summarized as follows:

By a well-known fact about Euler numbers, $\pi^9$ is given by a rational multiple of the fast-converging series $\sum_{n\geq 0}\frac{(-1)^n}{(2n+1)^9}$;
By the generalized continued fraction for the hyperbolic cotangent function, it is pretty simple to produce accurate rational approximations of $e^8$;
The given inequality can be proved by producing accurate rational approximations for both $\pi^9$ and $e^8$ through the previous points, then by comparing them.

$$\pi^9 = \frac{203325460470370265464832}{6820919298826171875}\pm 7\cdot 10^{-5} $$
$$ e^8 = \frac{6456755}{2166}\pm 4\cdot 10^{-8}$$
Done.
Comment: Amazing! $(+1)^\infty$
Comment: I wish everything was as simple as "1,2,3,done" for me (like it is for you). +1
Comment: @hypergeometric: $+500>(+1)^\infty$. One can do it by `start a bounty`.
Comment: Any idea here https://math.stackexchange.com/questions/2643216/prove-that-7-frac5-phi-e-pi-7-0000689-where-phi-is-the-golden-ratio?noredirect=1&lq=1
Comment: @Jack can one we give a bounty on a solved question?
Comment: @ParamanandSingh see here too https://math.stackexchange.com/questions/2643216/prove-that-7-frac5-phi-e-pi-7-0000689-where-phi-is-the-golden-ratio?noredirect=1&lq=1
Comment: @GuyFsone: it is possible to offer a bounty for an already answered question, yes.


Post-hoc chi-squared multiple comparison tests using complex samples module in SPSS v. 20

Question: This questions refers to computing cross-tabulations and chi-squared tests of independence through the SPSS complex samples module available in SPSS versions 19 and up. I am able to compute the overall chi-squared through the test of independence option, but I'd like to compute post-hoc tests of independence between all cells.
Does anyone know if this is even possible (i.e., post-hoc tests of independence through the complex samples module of SPSS)?
Answer: You can use the CSTABULATE command in the CS module to get the population proportion and standard error estimates. Use these to complete proportion tests either manually or in excel
Comment: This is in fact what we ended up doing. Thanks for the reply jake.


Given a $3m\times m$ table, how many ways can it be filled by $x$'s & $o$'s such that each column has at least $2$ $x$'s?

Question: Looking at this treat I thought it's a pretty easy one. Apparently not :]. Well,

Given a $ 3m \times m $ table, how many ways can we fill it with $x$'s and $o$'s, such that each column has at least $2$ $x$'s?

Well, my idea was pretty simple:
Let's have a look at all the possible ways to fill this table. We have $ 3m^2 $ cells, and 2 options for each. Then we have $ 2^{3m^2} $ ways to fill the table. Than, lets subtract all cases where $x$ appears once. This case looks this way:
$$ \prod_{i=1}^{m} \binom{3m}{1} = \binom{3m}{1} \cdot \binom{3m}{1} \cdot \binom{3m}{1}\dots\binom{3m}{1}$$
Then, we have $1$ single option to fill the table without x's at all. In conclusion, we have $$2^{3m^2}-(3m)^m - 1$$
BUT, looking at the final answers in the homework solutions, it says:
$$ (2^{3m} - 3m - 1)^m $$
Seriously, I don't understand how they got that. Does my way makes sense, or do I miss something here?
Comment: Your product is for the case where every $x$ appears once in *every* column (not just one column).  You are also ignoring the case where $x$ does not appear at all.  Hint: How many ways are there, in a single column, for there to be at least $2$ $x$'s?
Comment: By the way, you didn't specify if there were 3n rows or columns and n columns or rows.  Also if you do subtraction, watch out for double counting.  In fact.... don't do subtraction.
Answer: Given the solution (and working backwards) we understand that the solution considers each column separately:

$2^{3m}$ ways to fill it (without restrictions).
$3m$ ways with one $x$,
$1$ way with no $x$

So, there are $(2^{3m}-3m-1)$ ways to fill one column with the given restriction. Since there are $m$ columns which you can fill independently, there are: $$(2^{3m}-3m-1)^m$$ ways to complete the task.

The mistake in your reasoning is that you consider all columns at once. You count the ways that all columns simultaneously have $1$ $x$ or $0$ $x$'s but this ignores cases where for example the first column has no $x$'s and the rest $1$ $x$. You considered the whole table at once, but since the restriction concerns columns and columns can be filled independently, you should have followed the same approach by column-wise (as in the solution).
Comment: Awesome. Thanks a lot!
Comment: "but this ignores cases where for example the first column has no x's and the rest 1 x"  It also ignores the case where the first column has no x's and the rest have 1 *or more*  x.
Comment: In your correcting the reasoning you are implying all columns have at most one x.  Only one column need have at most one x.  Subtraction probably isn't the best way as account for double, triple etc. Counting will be a bear.  Can be done though.
Comment: @fleablood No, I do no imply this. I count the ways to fill a column correctly and then raise to the number of columns. So, each column has at least 2.
Comment: I'm not talking about you solution, which is perfect, I'm talking about your explanation as to why the OP made a mistake.  Which is also correct, but doesn't go far enough.
Comment: @fleablood Ok, now I see it. Thanks for elaborating, your observation is indeed correct. I will correct it as soon as not from mobile.


Explosão de Caracteres no Oracle

Question: Tenho a base de clientes, e a de notas por cliente:
   COD  CLIENTE
    128  JOAO
    129  MARIA
    130  DULCE

    NOTA
    234.123.334.128.50
    235.124.338.128.49

Nota-se que o código do cliente está inserido no número da nota, que no caso é o penúltimo conjunto antes do último ponto (128).
Como faço para "explodir" esses 3 números do código na tabela de notas para relacionar com o código registrado na minha base de cliente?
Answer: Crie uma função no Oracle:
create or replace function GetToken(
   tokenstring in varchar,
   tokenpos in number,
   delim in varchar )
   return varchar
is
   x number;
   i number;
   j number;
begin
  x := 1;
  i := 0;
  j := 0;
  while (i < TokenPos)
  loop
    j := x;
    while (x <= length( TokenString )) and ( substr( TokenString, x, 1 ) <> Delim)
    loop
       x := x + 1;
    end loop;
    i := i + 1;
    x := x + 1;
  end loop;
  return trim(substr(TokenString, j, x - j - 1));
end;

Agora você selecionar as partes como quer assim:
Passe à funcão a string, a posição que quer e o delimitador.
select gettoken( '234.123.334.128.50', 4, '.' ) from dual

Comment: Foi de muita ajuda,  muito obrigado.

Explosão de Caracteres no Oracle


How to hide Header and footer printed page?

Question: I'm using drupal 7 with print module,when printing some node there is some extra content like (date , pager and url) in the header and footer page that will be printed.
I just want to print the content of the node.
How can i remove this content?
Answer: You can use module to print a node
also to remove unwanted region you can change print.tpl.php inside the module
or you can use css
@media print
    {
        #header,.menu_background,.breadcrumb,#comments,#sidebar-first,.footer_bg,.node-links { display: none; }
        .node-view{ display: block;height:800px; }
    }

Comment: I'm using this module already, i removed the regions i want to hide from print.tpl.php.
but nothing happend, they just appear when open print preview page, i think the date and the pager... came from the browser setting.
Is there any way to set print setting by some code?
thanks
Comment: This content does not from the website it's from the browser.
Comment: are you sure your print.tpl.php is executing? try to clear theme register
Answer: copy sites/all/modules/print/print.tpl.php to your theme directory.
edit print.tpl.php and remove codes expect where main content has been printed:

<?php print $print['content']; ?>

save file, clear drupal cache


How to get an Integer from a String (contains letters and number)?

Question: Here is an example of what I'm trying to do:
String letternumber = "Example - 123";

I want to output "123" but I need to get it from the string, I can't just do:
String number = "123";
System.out.println(Integer.parseInt(number));

Or I will get an error.
Answer: You need to use Pattern and Matcher Classes.
String s = "Example - 123";
Matcher m = Pattern.compile("\\d+").matcher(s);
while(m.find())
{
        int num = Integer.parseInt(m.group());
        System.out.println(num);
}

Output:
123

Comment: Providing incomplete information gets you an incomplete answer.
Comment: Hi Avinash,

I tried using the Pattern and Matcher classes, but a problem I encountered was that since I am loading the names of non-player characters in my game, and some of them have one word names, some have up to 4 word names, that it wouldn't work because the group number would be different for each non-player character name I want to select. The number I am trying to get from the String is their ID.

Edit: I see you edited your response, maybe I was using it completely wrong. I will try this. Thanks, you helped me earlier too. :)
Comment: post an example along with expected output.
Comment: @Avinash Raj Thank you so much!! It worked. I think I will look further into these Classes. They are extremely useful.


velocity reassignment for collision detection is none-responsive when collision is triggered through a function

Question: import pygame as pg
import sys

def main():
    pg.init()
    clock = pg.time.Clock()
    fps = 60
    bg = (255, 255, 255)

    size = [400, 400]

    this = pg.display.set_mode(size)

    ay = .5
    vy = 2
    vx = 4

    player = pg.Rect(100, 50, 20, 20)
    platform = pg.Rect(0, size[1]-20, size[0], 20)

    objs = [player, platform]

    colors = [[255, 0, 0], [0, 255, 0]]

    move = [pg.K_LEFT, pg.K_RIGHT]

    def collide(player, platform, vy):
        hit = player.colliderect(platform)

        if hit:
            if player.bottom >= platform.top:
                player.bottom = platform.top
                vy = 0

    while True:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                return False

            if event.type == pg.KEYDOWN:
                if event.key == pg.K_SPACE:
                    vy -= 10

        key = pg.key.get_pressed()

        for i in range(2):
            if key[move[i]]:
                player.x += vx * [-1, 1][i]

        this.fill(bg)

        vy += ay
        player.y += vy

        collide(player, platform, vy)

        for i, obj in enumerate(objs):
            pg.draw.rect(this, colors[i], obj)

        pg.display.update()
        clock.tick(fps)

    pg.quit()
    sys.exit

if __name__ == '__main__':
    main()

As you can see from the above code i am attempting to create a landing procedure through the "rectcollide" method but for some unknown reason whenever the function is called although the collision is detected and the player's position is re-assigned, the player's velocity however is not altered in anyway. The strange thing is, if i don't use a function and directly implement the conditional in the main game update loop, it works just fine. So the problem is with the function's behavior i presume. Any help in solving this will be much appreciated. Thanks in advance.
Answer: In your inner function, vy is a local variable (an argument to the function). Changing its value doesn't change the value of the vy variable in the outer function. You either need to return the new velocity (and change the code calling the function to vy = collide(player, platform, vy)), or change your design around so that the velocity is an attribute of some other object (maybe player if you changed it to be an instance of a custom class).
If you were directly accessing vy in the outer namespace (without it being an argument), you could use a nonlocal statement in the inner function to let it write to the outer function's local variable. However, letting things scribble on other namespaces like this is often considered poor design. Using objects or return values is generally easier to reason about and much simpler to debug when things go wrong.
Comment: I tried returning the velocity but i received a none-type error.
Comment: Never mind, i accidentally called the return method within the if statement.


From origin walk halfway to $(8,6)$, turn $90$ degrees left, then walk twice as far.

Question: So, I've spent hours on this question and it's frustrating me way too much so I created an account for StackExchange just to understand how you solve this problem.
Let me start by sharing the question: "Sally has hidden her brother's birthday present somewhere in the backyard. When writing instructions for finding the present, she used a coordinate system with each unit on the grid representing 1 m. The positive y-axis of this grid points north. The instructions read "Start at the origin, walk halfway to (8,6), turn 90 degrees left, and then walk twice as far." Where is the present?" By the way, you have to answer the question algebraically and the answer in the textbook is (-2,11)
What I Know
Let P represent the coordinate of the present
Let M represent the midpoint between (0,0) and (8,6)

M is at (4,3) which is solved using the midpoint formula.
The distance from P to M is 10 m.
The equation for the line from the origin to the midpoint is:
y= $\frac{3x}{4}$
The equation for line PM is:
y= $\frac{-4x}{3}$ + $\frac{25}{3}$
Using the distance formula for two coordinates I know that the distance from M to P can be represented in this equation: $100=(4-x)^2 + (3-y)^2$ The x and y in the equation represents the x,y coordinates of the point P. I don't know how to simplify this equation further.

My troubles
I come to this point where I don't know what to do anymore. Please explain how you solved this problem.
Thank you so much
Comment: Please using subjective and superlative titles (in this case "incredibly hard"). Instead, provide an actual description of the question. Things like "question 23" are meaningless to almost everyone except you and those related to your class. You have 150 characters at your disposal, this is enough to provide a good title.
Comment: To solve this using brute force, just substitute $y = -\frac{4}{3}x + \frac{25}{3}$ into $100 = (4-x)^2 + (3-y)^4$ to get a quadratic equation in $x$. Solve that using factorization (or the quadratic formula if you're not comfortable with factoring) and you'll end up with two points. These correspond to turning left and turning right. Pick the one with the smaller $x$ coordinate to indicate that you turned left.

You can also draw this out with the origin moved to the point (4,3). You get a right triangle with horizontal side $3a$, vertical side $4a$ and hypotenuse $10$. Solve for $a$.
Comment: The above comment gives a great "algebraic" answer to your problem. You will find two points (two points that come from the intersection of a circle and a line). If the x coordinate gets larger, you are moving to the right. If it gets smaller, you are moving to the left. As for the triangle solution... you could just also draw a 2D Plot and use the information given, but I don't think that was the point of the exercise
Comment: Thanks, this helped me so much!
Answer: Equivalent to 4 steps east, 3 steps north, then 8 steps north, 6 steps west, resulting in (4-6, 3+8) or (-2, 11).  After plotting, it's much easier to see the triangles you have to describe algebraically.
Answer: If you know complex numbers, the problem becomes almost trivial to solve. Complex numbers lend themselves very naturally to mapping to vectors and points on the 2-d plane.
So you start at the origin (point $0+0i$) and walk halfway to $8+6i$, which means you end up at $4+3i$. At this point you turn ninety degrees to your left (which is counter-clockwise), and the vector for the new direction can be found by multiplying the previous one by $i$. And since you're walking twice as far, this is equivalent to again multiplying the result by two. So you're now taking the path $2i(4+3i) = -6 + 8i$. The final position is simply the sum of $4+3i$ and $-6+8i$, i.e. $4+3i -6+8i = -2 + 11i$. This is the point $(-2,11)$ as required.
Comment: He said he was in grade 10, so he probably doesn't know complex numbers yet.
Comment: @BorKari You have a point there. I'm not familiar with the US school system (I'm from Singapore, and have taken the UK-based GCE exams) - but even here, I think complex numbers are only "officially" covered starting from age 17 or so. Still, I had self-taught myself math from a young age. I think complex numbers are not that hard to learn, and they are so very useful in many fields. I am hoping to encourage the asker (and others) to pick up a new technique they may be unfamiliar with, or perhaps not have considered. :)
Comment: Could be done in a similar way but instead of using complex numbers, using 2D Coordinates...If the vector is 4i+3j, the perpendicular vector would be -3i+4j [i is vector notation, not imaginary, perpendicular turning to the left], That new vector has a lenght of 5, so if you need it to double the lenght, you just multiply it by 2 and work it the same way as in complex numbers, you'll end up with the same answer.
Comment: @JonathanPerales Yes, I realise that. I wanted to post the complex numbers method because a) it's my first line as it somehow feels more natural to me (it's basically just arithmetic) and b) a lot of people are unfamiliar with the versatility of the method. But thanks for the comment, that provides an alternative formulation that others may wish to use.
Answer: Go to (4,3), and then walk in the direction of slope -4/3, i.e., left 3 and up 4, twice as far, i.e., left 6 and up 8. So, 4-6=-2, and 3+8=11. There's a 3,4,5 right triangle and a 6,8,10 right triangle involved.
Solving quadratic equations is serious overkill.
Answer: It is quickly checked that an orthogonal vector to $\binom{4}{3}$ in the right direction is $\binom{-3}{4}$ and this vector has also length $5$.
So, the algebraic solution is
$$\binom{4}{3} + 2\binom{-3}{4} = \binom{-2}{11}$$
Answer: Hint:
You can make a second equation by considering the equation of the line because you know that the point has to be on that line.


GROUP BY ultimo registro por mes e ano como fazer?

Question: Estou fazendo uma consulta no banco, segue minha tabela abaixo
id | valor  |  mes |  ano  |
1    39.69      3    2017
1    7.69       3    2018
3    9.69       4    2015
3    3.69       2    2016
2    5.89       3    2017
2    39.69      8    2018

preciso trazer o resultado agrupando os valores pelo ultimo valor do mes e ano,
ou seja, preciso do resultado assim:
id | valor  |  mes |  ano  |
1    7.69       3    2018
3    3.69       2    2016
2    39.69      8    2018

Comment: alguma das respostas atendeu?
Answer: Acho que desta forma consegue o que pretende:
SELECT      T.*
FROM        Teste T
INNER JOIN  (
                SELECT      Id
                        ,   MAX(Ano) AS Ano
                FROM        Teste
                GROUP BY    Id) X   ON  X.Id    = T.Id
                                    AND X.Ano   = T.Ano
INNER JOIN  (
                SELECT      Id
                        ,   Ano
                        ,   MAX(Mes) AS Mes
                FROM        Teste
                GROUP BY    Id
                        ,   Ano) X2 ON  X2.Id   = T.Id
                                    AND X2.Ano  = T.Ano
                                    AND X2.Mes  = T.Mes
ORDER BY    T.Id

Tem aqui o exemplo no DbFiddle: https://www.db-fiddle.com/f/sAVS8KHcs7HS39fWnRGCT8/0
Answer: Você pode fazer isso utilizando uma table temp auxiliar:
--tabela fake
/*
DECLARE @TABLE TABLE (ID INT, Valor FLOAT, Mes INT, Ano INT)

--valores fake
INSERT INTO @TABLE VALUES(1, 39.69,3, 2017)
INSERT INTO @TABLE VALUES(1, 7.69 ,3, 2018)
INSERT INTO @TABLE VALUES(3, 9.69 ,4, 2015)
INSERT INTO @TABLE VALUES(3, 3.69 ,2, 2016)
INSERT INTO @TABLE VALUES(2, 5.89 ,3, 2017)
INSERT INTO @TABLE VALUES(2, 39.69,8, 2018)
*/

SELECT ID, MAX(Ano) AS Ano
INTO #Temp
  FROM @TABLE
 GROUP BY ID

SELECT T2.*
  FROM #Temp T
  JOIN @TABLE T2 ON T2.ID = T.ID AND T.Ano = T2.Ano

 --DROP TABLE #Temp

Answer: Segundo esta pergunta do SOEN, é possível usar MAX junto com GROUP BY; então podes fazer o seguinte:
SELECT id, valor, mes, ano, CONCAT(ano, mes) as anoMes
FROM tabela
GROUP BY id

Criei este fiddle de exemplo pra validação.


Criterion for a basis of a topology

Question: Here is part of Munkres' book on topology:
I suppose the reader is supposed to use

to prove this. But I don't understand how. The lemma says that if there is a space with a fixed topology, then to show that a set forms a basis, one has to take an open set from the fixed topology and do something. But the order topology is being defined, how can I take an open set and prove that it contains a basis element if I don't know what open sets are yet?
Comment: My question is in the last sentence, I believe.
Comment: To step back a bit, one has a fixed topology when all the open sets are known (or, equivalently, when all of its *closed* sets are known).  In that context we can ask whether a certain subset of the open sets do or do not constitute a *basis* for the topology.  That's where the Lemma you cite might come into play.  Given that framework, what is *your* Question?  Merely quoting from the Munkres textbook does not fully state a problem to be solved.
Answer: $\mathscr B$ doesn't define a topology on $X$.  You need to take arbitrary unions and finite intersections of elements of $\mathscr B$ to fulfill the definition of a topology.
$\mathscr B$ is a basis for the topology it generates...
Actually,  $\mathscr B$ is closed under finite intersections, as Munkres notes.
But you need to throw in arbitrary unions...  $\mathscr B$ isn't closed under arbitrary unions.
Thus $\mathscr B$ generates a topology on $X$.
Comment: Munkres highlights a couple of things to check to be sure $\mathscr B$ actually serves as a basis.  Since the entire set $X$ must be open, every element $x\in X$ has to belong to some set in $\mathscr B$.  Munkres further asks the reader to check $\mathscr B$ is closed under finite intersections, as you noted.  I don't have my copy of Munkres handy, but it seems likely that a different Lemma than the one the OP has identified was intended to be used.
Comment: Perhaps...  I lost my copy of Munkres years ago.  I remember it was red...
Comment: @hardmath there are useful criteria on wolfram and Wikipedia...
Comment: @hardmath You are right, I think I should use just the definition instead of the lemma. (The definition can be found in my previous question.) But it looks like the definition is obviously satisfied, so now I'm confused why Munkres says to consider a few cases and verify something, if everything looks too trivial (or I misunderstand something).
Comment: Now I see. Not all cases are trivial. If we take $(a,b]$ and $[b,c)$, then the intersection will be a singleton. It will not contain a basis element. So it cannot be a basis, according to the definition... I must be missing something.
Comment: @user531587:  Note all "half-open" intervals are allowed in the order topology.  In particular the two sets you give are admitted only if $b$ is both a greatest element and a least element, in which case the intersection being a singleton is correct and desirable.
Answer: The requirements for $\mathcal{B}\subseteq \mathscr{P}(X)$ to be a base for some topology on $X$ are (second edition., paragraph 13, page 78):
(1) $\bigcup \mathcal{B} = X$, or equivalently for every $x \in X$ there is some $B \in \mathcal{B}$ such that $x \in B$.
(2) For all $B_1, B_2 \in \mathcal{B}$, for all $x \in B_1 \cap B_2$: there exists some $B_3 \in \mathcal{B}$ such that $x \in B_3 \subseteq B_1 \cap B_2$.
The lemma 13.2 is not used here: this is to characterise a base for an already given topology, while in the case at hand we want to define a topology by a suitable base.
Munkres suggests to check condition (2) by checking that the set of intervals he describes ($\mathcal{B}$) has the property that if $B_1 , B_2 \in \mathcal{B}$ we either have $B_1 \cap B_2 \in \mathcal{B}$ again (so we can take $B_3 = B_1 \cap B_2$) or $\emptyset$ (in which case the condition is voidly true as there are no $x \in B_1 \cap B_2$ to check.

Criterion for a basis of a topology


JPA 2.0: Mapping between three entities

Question: I want to implement the following relationship using JPA 2.0. Entity Diagram
In a few words: A user can have several roles in a group.
Is there a convenient way to achieve this? A code example would be nice.
Thanks in advance!
Comment: The entity diagram is not opening!
Answer: public class Users implements Serializable {
private static final long serialVersionUID = 1L;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 10)
@Column(name = "id_usuario")
private Integer idUsuario;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 80)
@Column(name = "nombre")
private String nombre;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "Users")
private Collection<NzSistemaControl> nzSistemaControlCollection;

Roles
public class Roles implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@Column(name = "id_rol")
private Integer idRol;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 50)
@Column(name = "nombre")
private String nombre;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "Roles")
private Collection<NzSistemaControl> nzSistemaControlCollection;

Relationship table
public class SistemaControl implements Serializable {
@EmbeddedId
protected NzSistemaControlPK nzSistemaControlPK;
@JoinColumn(name = "id_usuario", referencedColumnName = "id_usuario_sistema", insertable = false, updatable = false)
@ManyToOne(optional = false)
private Users user;
@JoinColumn(name = "id_rol", referencedColumnName = "id_rol", insertable = false, updatable = false)
@ManyToOne(optional = false)
private Roles roles;

RelationShipPK
public class NzSistemaControlPK implements Serializable {
@Basic(optional = false)
@NotNull
@Column(name = "id_usuario")
private int idUsuario;
@Basic(optional = false)
@NotNull
@Column(name = "id_rol")
private int idRol;

JPA 2.0: Mapping between three entities


Reindex dataframe reverse multiindex levels

Question: I have Pandas dataframe with a Multindex of "group" and "date" that I want to convert into one with the indices reversed, ie. "date" then "group". I've tried reindexing but this sets all values to NaN.
I tried this:
by_date = MultiIndex.from_product([index.levels[1], index.levels[0]])
df.reindex(index=by_date)

                  Nuts  Bolts  Screws
group date
1010  2020-03-13   1.0   44.0     1.0
      2020-02-19   2.0   44.0     0.0
3510  2020-03-13   1.0   26.0     1.0
5000  2020-02-28   1.0    3.0     0.0
3510  2020-03-02   2.0   26.0     0.0

And I would like this format
                 Nuts  Bolts  Screws
date        group
2020-03-13  1010    1.0   44.0     1.0

Is this possible reindexing? Or am I better unstacking and stacking?
Answer: Use DataFrame.swaplevel:
df1 = df.swaplevel(0,1)

#oldier pandas version
#df.index = df.index.swaplevel(0,1)
print (df1)
                  Nuts  Bolts  Screws
date       group
2020-03-13 1010    1.0   44.0     1.0
2020-02-19 1010    2.0   44.0     0.0
2020-03-13 3510    1.0   26.0     1.0
2020-02-28 5000    1.0    3.0     0.0
2020-03-02 3510    2.0   26.0     0.0

Comment: I thought they'd be a **simple and obvious** way to do this. Thanks very much!


Collection of Borel sets contains all $[a,b)$

Question:
Show that the collection of Borel sets is the smallest $\sigma$-algebra that contains intervals of the form $[a,b)$, where $a<b$.

So I first prove that the collection $S$ of Borel sets contains those intervals. $S$ contains the closed interval $[a,b]$ and the (closed) single point $b$, so it contains the difference $[a,b)$.
Now I have to prove that any $\sigma$-algebra containing all intervals $[a,b)$ must contain all elements of $S$. If I can prove that it must contain all open intervals $(a,b)$, I'll be done because any open set in $\mathbb{R}$ is a countable union of open intervals. But how do I show that $(a,b)$ belongs to such a $\sigma$-algebra?
Answer: $\sigma$-algebras are closed under countable unions. You need to use this to show that any $\sigma$-algebra containing the half open intervals contains the intervals as well.
For instance $(0,1)= \bigcup_{n=1}^{\infty} [\frac{1}{n}, 1)$.
Comment: I see.. with your example I can prove that any interval $(a,b)$ where $-\infty<a,b<\infty$ is in the $\sigma$-algebra. Also, $(-\infty,b)=\bigcup_{i=1}^{\infty}[b-i,b)$. Now I'm just stuck with $(a,\infty)$.
Comment: Ok that's not a worry. It's just $\bigcup_{i=1}^{\infty}(a,a+i)$.


How to extend the size of a text box when clicked into?

Question: I am currently working on a site that utilizes a search function.  I have a text box in the top corner and I want to set it so that whenever the user clicks into the box, it extends to twice the length that it currently is.  How exactly would I do that?  I have searched but cannot find any helpful information.
Comment: Which language? which platform/framework?!
Comment: Check out the w3cschools tutorials on "jquery" - attach an event handler to the text box when it gets the focus and modify its css to change its size
Comment: I should have been a bit clearer.  I am using Javascript, and I would like to avoid jQuery if at all possible
Comment: You can code it "natively" in javascript of course - but then you need to handle all of the cross-browser diferences in DOM and CSS support yourself -- a major PITA
Answer: why don't you use CSS3 transitions? you could do something like this to make the width of the textbox increase:
<code>input, textarea {
    width: 280px;
    -webkit-transition: width 1s ease;
    -moz-transition: width 1s ease;
    -o-transition: width 1s ease;
    -ms-transition: width 1s ease;
    transition: width 1s ease;
}

input:focus, textarea:focus {
    width: 340px;
}
</code>


Intermittent full system hang on VM server running CentOS 5.10

Question: CentOS 5.10 / VMWare ESX 5.1
I've got an older email server running CentOS 5.10 (with SendMail) and it's experiencing intermittent hangs wherein the system becomes completely unresponsive.  During these times, I can't connect to it at all and the virtual console is unresponsive.
The strange part is that our VMWare admin group aren't seeing any obvious resource spikes that would be indicative of insufficient resources, load spikes, etc.  Furthermore, when I examine the system logs (e.g. maillog, messages, etc) there's a noticeable absence in ALL log activity during the time of the hang which suggests that these outages are severe enough to prevent logging (or perhaps there's a filesystem/disk issue).
The one abnormality is that sendmail logging on the box was pretty high (98 instead of the usual level 9).  I'm going to set it back to normal shortly.
I'm stumped on where I can go for more info here.  Is there a thread dump that would tell me what the OS was working on during the hang?
Additional information:

Kernel version is: 2.6.18-371.4.1.el5 #1 SMP Thu Jan 30 06:09:24 EST 2014 i686 i686 i386 GNU/Linux
The storage is handled on a shared SAN.
VMWare tools is not installed on the system as per internal policy however we've been running for a long time without vmware tools so we don't think the absence of it is necessarily the root cause.
Specific version of VMWare is: VMware ESXi 5.1.0 build-2000251
Hardware is IBM 3850 M2,  Model 7233AC1
Comment: Please post the ESXi build number/version. Also, describe the storage configuration of the host. Is it a SAN? Is it local storage? Server make/model may also help.
Comment: Also post your kernel version and whether you're using VMware tools.
Comment: @ewwhite thanks.  Added some additional information.  Checking with the vmware team for the rest of it.
Answer: So, 32-bit CentOS 5.10... That's not necessarily a problem...
But you should always have the VMware tools installed when running an operating system supported by VMware. This can be extremely helpful when vSphere/ESXi host memory gets constrained, plus it adds the memory balloon driver, better NIC interface options (for your EL5 system) and power management.
In general, look at what the SAN is doing at the time these issues occur. Also, if you're not using VMware tools, there's a good chance that ESXi isn't on a stable revision level. Please report back on the ESXi build number. You'll see it at the top of the vSphere Client when connected to the host.

Edit:
Since this is a vSphere cluster, can you have the team check memory allocation. I've seen Linux VMs hang or lock-up because of bad memory configuration. This can include setting RAM limit in the vSphere client for the VM in question. This can also include situations where your cluster is too overcommitted on RAM and/or where the VMs have been allocated too much RAM.
See: vSphere education - What are the downsides of configuring VMs with *too* much RAM?
Any deeper analysis would require seeing some of the VMware cluster/resource status screens.
Comment: No, it's not immediately obvious. The VMware team would need to check the resource shares of the VM cluster/host in question. There are a few places to look, but it's hard to do this blind.
Comment: Thanks.  I'll request more information from the vmware team regarding build.  Can you elaborate on what you mean by "look at what the SAN is doing at the time..."?  Should the VMWare team be reviewing logs? Performance metrics? Etc?
Comment: Also, apologies for clearly asking a question that has been asked before (as per your meta post). I did check beforehand to see if this was already asked but didn't seem to find it. :-(
Comment: Oh, the meta post was more about people not upgrading VMware. It's almost dangerous not to these days.
Comment: Added additional information regarding VMWare build and VM host hardware.  Is 2000251 a "stable" build?
Comment: @MikeB That's [July 2014](http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=2079117). Not too bad... I suspect RAM, plus the lack of the balloon drive provided by the VMware Tools. See my edit above.
Comment: Thanks - I'm reviewing the other documentation but I'm still a bit confused (thanks so much for your patience). If these types of hangs are the result of bad memory configuration (or SAN issues), is that something that would be fairly obvious on the vmware management side? Is there a log that would show "proof"? The prevailing point coming back my way is that this is only happening on a few servers. I'm reluctant to tell them "check to see if it's something on your end" if they're not going to be able to prove it one way or the other.
Answer: I just wanted to close the loop on this one.  The mysterious hangs stopped occurring after we scaled back SendMail logging from 99 down to 9 (default).  Admittedly, that was a reaaaaaaly high log-level setting but I've never seen that completely grind a server to a halt.  Also no idea how long it had been set that way.
My guess is that the intermittent nature of this stemmed from a combination of mediocre disk I/O speeds and occasional SMTP load spikes.
Thanks everyone for your help.


for $abc = 1$ and $a \le b \le c$ prove that $(a+1)(c+1)>3$

Question: This inequality has been given to me by my teacher to keep me occupied and after hours of fumbling around with it, and later trying to google it. I found nothing at all.
For any three positive real numbers $a$, $b$ and $c$, where $abc = 1$ and $a\le b \le c$, prove that:
$$(a+1)(c+1)>3.$$
Comment: @lulu he stated that they are $3$ positive real numbers !.
Comment: Are you missing some assumptions like positivity?  Otherwise take $a=-1,b=-1, c=1$
Comment: @Ahmad  Ah, so he did.  Thanks!  Second problem today I have totally misread.
Comment: @lulu with such contribution to the site, you are entitled to make as many mistakes as they can count :)
Comment: @Ahmad  Kind of you to say.
Answer: First simplify the expression :
$ac + a + c + 1 \gt 3 \iff ac + a+c \gt 2 \iff 1/b + a+ c \gt 2 \iff 1 + ab+bc \gt 2b $
We should prove $1+ab+bc \gt 2b$ . Use the condition $a\le b\le c $ :
$a\le b\le c \iff 2a \le a+b \le a+c \to a+b\le a+c$
From these we have :
$a+b\le a+c \iff ab + b^2 \le ab + bc \iff ab + b^2 +1 \le ab + bc+ 1$
If we prove $ab + b^2 +1 \gt 2b $ then problem is solved :
$ab + b^2 +1 \gt 2b \iff ab + (b-1)^2 \gt 0$
which is obvious because $ab \gt 0 $ and $(b-1)^2 \gt 0$
Done !
Answer: Since $b$ plays no role in the minimizing quantity, we might as well set $b=c$ to get the smallest $ac=\frac1b$. That means
$$
ac^2=1\tag{1}
$$
Using $(1)$, we want to find the minimum of
$$
\begin{align}
(a+1)(c+1)
&=\left(\frac1{c^2}+1\right)(c+1)\\
&=c+1+\frac1c+\frac1{c^2}\tag{2}
\end{align}
$$
$(2)$ is minimized when
$$
c^3-c-2=0\tag{3}
$$
The real root of $(3)$ is
$$
c=1.521379706805\tag{4}
$$
Plugging $(4)$ into $(2)$ says that the minimum is
$$
(a+1)(c+1)\ge3.610718613276\tag{5}
$$
Comment: very nice (+1), also will delete my post,thanks.
Comment: Thanks, but where does $c^3-c-2=0$ come from?
Comment: @Vfdking: taking the derivative of $(2)$.
Answer: Our conditions give $c\geq1$ and $c\geq b$.
Thus, by AM-GM we obtain:
$$(a+1)(c+1)=ac+a+3\cdot\frac{c}{3}+1\geq5\sqrt[5]{ac\cdot a\cdot\left(\frac{c}{3}\right)^3}+1=$$
$$=\frac{5}{\sqrt[5]{27}}\sqrt[5]{a^2c^4}+1\geq\frac{5}{\sqrt[5]{27}}\sqrt[5]{a^2b^2c^2}+1=\frac{5}{\sqrt[5]{27}}+1>3.$$
Done!


Combinatorics problems that can be solved more easily using probability

Question: I'm looking for examples of combinatorics problems which would be very difficult to solve by direct enumeration, but can be easily solved using ideas from probability, like independence, commuting sums and expectations, etc.  I know I have seen such problems before, especially in the HMMT combinatorics subject tests, but I can't now recall any good examples.
I am NOT looking for probabilistic existence proofs (the so-called "probabilistic method" introduced by Erdos).  The sort of problems I'm interested in are enumerative.
Comment: What is HMMT?...
Comment: @Aqua: it's the Harvard-MIT Mathematics Tournament: https://www.hmmt.co/
Comment: FWIW, I don't know a good example of such a problem which isn't even more easily solved using generating functions.
Answer: This might be a good example. Prove that for any positive integers $m,n$ with $m< n$,
$$
\sum_{k=0}^n \frac{\binom{m}{k}}{\binom{n}k}=\frac{n+1}{n-m+1}.
$$
Solution: Imagine you have a deck of $n$ cards, $m$ of which are black, the rest of which are red. You shuffle the deck, and deal from the top until you deal a red card. What is the expected number of cards dealt?
Letting $X$ be the number of cards dealt, you have $P(X>k)=\binom{m}{k}/\binom{n}{k}$, since $X>k$ occurs if and only if the first $k$ cards are all black. Therefore,
$$
E[X]=\sum_{k=0}^nP(X>k)=\sum_{k=0}^n \frac{\binom{m}{k}}{\binom{n}k}
$$
On the other hand, the $n-m$ red cards divide the deck into $n-m+1$ sections of black cards. Each black card is equally likely to fall in each section. In particular, there is a probability of $1/(n-m+1)$ of it falling in the top section. By linearity of expectation, the expected number of black cards in the top section is $m/(n-m+1)$. Therefore, the expected number of cards dealt is
$$
1+\frac{m}{n-m+1}=\frac{n+1}{n-m+1}
$$

I think there are a lot of complicated combinatorial sums which can be made easy using linearity of expectation. For example,
$$
\sum_{k=0}^nk\binom{n}kp^k(1-p)^{n-k}=np
$$
is best understood by realizing the sum is the expected value of a binomial random variable with parameters $n$ and $p$, whose value is obviously $np$ by linearity of expectation. There, the sum is not hard, but there are probability examples in a similar vein.
Answer: Graph enumeration problems are often solved using the theory of random graphs. For example, if you want to asymptotically count the number of (labeled) connected graphs on $n$ vertices, it is easiest to estimate the probability that the Erdős–Rényi graph $\mathcal G_{n,1/2}$ is connected, then multiply by $2^{\binom n2}$, the total number of labeled graphs on $n$ vertices.
For a fancier example, the asymptotic number of labeled $d$-regular $n$-vertex graphs can be counted by a similar probabilistic strategy. If $d$ is sufficiently small as $n \to \infty$, we analyze the configuration model (which generates a random $d$-regular multigraph by picking a random matching between the $dn$ half-edges) and estimate the probability that the graph is simple. For an example of the newest and fanciest results in this vein, see this paper by Liebenau and Wormald.
The fundamental ideas in such cases are often about proving asymptotic independence between many very unlikely events, which lets us make Poisson or Gaussian approximations to random variables that approach the truth as $n \to \infty$. This would be difficult to recast in a purely deterministic form, and the result would be very hard to understand.
By contrast, in a problem where the "trick" was independence or commuting sums and expectations, the probability is essentially flavor and you could recast such a proof as taking a sum in two ways or something similar.
Answer: Here are some problems:

Find the sum of the number of all continuous runs of all possible sequences with $2019$ ones and $2019$ zeros
https://artofproblemsolving.com/community/c6h366278p2018435
https://artofproblemsolving.com/community/c6h60752p366512
https://artofproblemsolving.com/community/q2h1151650p5452212
http://artofproblemsolving.com/community/c6h1170845p5622460
https://artofproblemsolving.com/community/q4h1497881p9354029
https://artofproblemsolving.com/community/q1h79679p10589332