Which numbers is bigger $80^{105}$ or $28^{140}$

Question:
Which numbers is bigger   $80^{105}$ or $28^{140}$

My try follows
$80^{105}$ = $(80^{3})^{35}$=$(512000)^{35}$
$28^{140}$=$(28^{4})^{35}$=$ (614656)^{35}$
So $28^{140}$ is bigger
Is there another idea for this problem involving relations between $80$ and $81$  and $27$ and $28$  since  $81$ and $27$  have common base $3$
Thank you for your help
Answer: $$28^{140}>27^{140}=3^{420}=81^{105}>80^{105}$$
Comment: Nice answer you wrote there.
Comment: @kingW3   vElegant  answer,  thank you very much  +1
Answer: Take logarithms, since $ \log{x} $ is monotonic. You can even use base 10.
Then $ \log_{10}{80^{105}} = 105 \log_{10}{80} \approx 200 $. Meanwhile,
$ \log_{10}{28^{140}} = 140 \log_{10}{28} \approx 203 $. Hence $ 28^{140} $ is bigger.
(Edit: This isn't as clever as the previous answer since you need a computer for it, but it can be extended to powers that are difficult to compute).
Answer: As $(105,140)=35$
we can check  for $80^3,28^4$
$80^3=(5\cdot2^4)^3=5^32^{12},28^4=(7\cdot2^2)^4=7^4\cdot2^8$
$80^3>=<28^4\iff5^32^{12}>=<7^4\cdot2^8\iff5^32^4>=<7^4$
Now $7^4=2401,5^32^4=2\cdot10^3=2000$
Comment: @BarryCipra, Thanks
Answer: kingW3's answer, which invokes only the inequalities $27\lt28$ and $80\lt81$, can hardly be beat, but here's another, lengthier, approach, invoking three inequalities ($48\lt49$, $8\lt9$, and $125\lt128$):
$$\begin{align}
48\lt49&\implies2^4\cdot3\lt7^2\\
&\implies2^8\cdot3^2\lt7^4\\
&\implies2^8\cdot2^3\lt7^4\quad(\text{since }8\lt9)\\
&\implies2^4\cdot2^7\lt7^4\\
&\implies2^4\cdot5^3\lt7^4\quad(\text{since }125\lt128)\\
&\implies(2^4\cdot5)^3\lt(2^2\cdot7)^4\\
&\implies80^3\lt28^4\\
&\implies80^{105}\lt28^{140}
\end{align}$$


How to get current function name in Python C-API?

Question: I implemented a bunch of functions and they are dispatched from the same C function called by the Python interpreter:
PyObject *
CmdDispatch(PyObject *self, PyObject *args, PyObject *kwargs)

Unexpectedly, self is NULL, and I need to get the function name currently being called.  Is there any way to get this information?
I have dozens of functions which are all going through this routine.  This command processes all of the options into a C++ map and passes it along to the implementation of each command.
Update:
http://docs.python.org/extending/extending.html#a-simple-example specifically says "The self argument points to the module object for module-level functions; for a method it would point to the object instance.", but I am getting passed null when linking against python 2.6.
Comment: Why do you say "unexpectedly"?
Comment: Because the api docs don't say the first argument doesn't mean anything
Comment: There's lots of API docs; you'll need to be more specific.
Comment: Based on my research, I don't agree. They are non specific and lacking
Comment: If you are using 2.6, you should look at 2.6 documentation(http://docs.python.org/release/2.6.7/c-api/structures.html), where says "The first one is the self object for methods; for module functions, it has the value given to Py_InitModule4() (or NULL if Py_InitModule() was used)."
Answer: I've been trying to solve very similar problem.
The conclusion I've come to suggests there is no way to determine name of current function or caller(s) at the level of Python C API. The reason being, Python interpreter puts on call stack only pure Python functions (implemented in Python itself). Functions implemented in C, regardless if registered in module methods table, are not put on Python stack, thus it's not possible to find them inspecting the stack frames.
Here is a quick example in Python illustrating what I wanted to achieve (I assume Juan asks for similar behaviour):
import sys
def foo():
    print('foo:', sys._getframe(0).f_code.co_name)
def bar():
    print('bar:', sys._getframe(0).f_code.co_name)
    foo()
bar()

Here is close equivalent of this example (based on the Python 3 docs) but implemented using Python C API:
// Based on example from Python 3.2.1 documentation, 5.4. Extending Embedded Python
// http://docs.python.org/release/3.2.1/extending/embedding.html#extending-embedded-python
//
#include <Python.h>
#include <frameobject.h>

static void foo()
{
    PyThreadState * ts = PyThreadState_Get();
    PyFrameObject* frame = ts->frame;
    while (frame != 0)
    {
        char const* filename = _PyUnicode_AsString(frame->f_code->co_filename);
        char const* name = _PyUnicode_AsString(frame->f_code->co_name);
        printf("foo: filename=%s, name=%s\n", filename, name);
        frame = frame->f_back;
    }
}

static void bar()
{
    PyRun_SimpleString(
    "import sys\n"
    "print(\"bar: filename=%s, name=%s\" % (sys._getframe(0).f_code.co_filename, sys._getframe(0).f_code.co_name))"
    );
}

static PyObject* emb_numargs(PyObject *self, PyObject *args)
{
    foo();
    bar();

    PyRun_SimpleString(
    "import sys\n"
    "print(\"emb_numargs: filename=%s, name=%s\" % (sys._getframe(0).f_code.co_filename, sys._getframe(0).f_code.co_name))"
    );

    return PyLong_FromLong(0);
}

static PyMethodDef EmbMethods[] = {
    {"numargs", emb_numargs, METH_VARARGS, "Return number 0"},
    {NULL, NULL, 0, NULL}
};

static PyModuleDef EmbModule = {
    PyModuleDef_HEAD_INIT, "emb", NULL, -1, EmbMethods,
    NULL, NULL, NULL, NULL
};

static PyObject* PyInit_emb(void)
{
    return PyModule_Create(&EmbModule);
}

int main(int argc, char* argv[])
{
    PyImport_AppendInittab("emb", &PyInit_emb);
    Py_Initialize();
    PyRun_SimpleString(
    "import emb\n"
    "print('This is Zero: ', emb.numargs())\n"
    );
    Py_Finalize();
    return 0;
}

I hope this completes Ned's answer too.
Answer: The Python api isn't built to tell you what function it is calling.  You've created a function, and it is calling it, the API assumes you know what function you've written.  You'll need to create a small wrapper function for each of your Python functions.  The best way to do this is to register your one C function as one Python function that takes a string as its first argument.  Then, in your Python layer, create as many Python functions as you need, each invoking your C function with the proper string argument identifying what function you really want to call.
Another alternative is to rethink the structure of your C code, and have as many functions as you need, each of which invokes your common helper code to process options, etc.
Comment: there is documentation on the web on using introspection from the scripting level to get the function name, but not on the c-api level
Comment: I ended up iterating over all of the functions in the module and creating a wrapper for each one passing the command name.
Answer: NOTICE error checking for API is not being provided for clarity;
This example insert a new function directly on python __builtin__ module, allowing to call the method without class.method schema. Just change mymodule to any other module as you wish.
PyObject* py_cb(PyObject *self, PyObject *args)
{
    const char *name = (const char *) PyCObject_AsVoidPtr(self);

    printf("%s\n", name);
    Py_RETURN_NONE;
}

int main(int argc, char *argv)
{
    PyObject        *mod, *modname, *dict, *fnc, *usrptr;
    const char      *mymodule = "__builtin__";
    PyMethodDef     *m;
    const char      *method = "hello_python";

    Py_Initialize();
    mod = PyImport_ImportModule(mymodule);
    modname = PyString_FromString(mymodule);
    dict = PyModule_GetDict(mod);
    m = (PyMethodDef *) calloc(1, sizeof(PyMethodDef));
    m->ml_name = strdup(method);
    m->ml_meth = py_cb;
    usrptr = PyCObject_FromVoidPtr("I'm am the hello_python!", NULL);
    fnc = PyCFunction_NewEx(m, usrptr, modname);
    PyDict_SetItemString(dict, method, fnc);
    ...

When python script execute hello_python, the py_cb extension function will show:
I'm am the hello_python!
The self is used to send a real pointer such as the library context instead of this const char * of this example, this is now a matter of changing it to something interesting though.
Answer: I don't know if can be done directly from the C-API. At worst, you could call the traceback module from C, to get the name of the caller.


Weblogic Domain creation error through script in putty

Question: I am trying to create weblogic domain using silent mode through putty .I have used below command:
./config.sh -mode=silent -silent_xml=/home/ec2-user/createdomain.xml
I am getting below error message while executing it:
<code>Exception in thread "Thread-1" java.lang.IllegalStateException: No able to create the instance of the template catalog class com.oracle.cie.domain.template.catalog.impl.GlobalTemplateCat
        at com.oracle.cie.domain.template.catalog.TemplateCatalogFactory.createGlobalTemplateCatalog(TemplateCatalogFactory.java:138)
        at com.oracle.cie.domain.template.catalog.TemplateCatalogFactory.getGlobalCatalog(TemplateCatalogFactory.java:78)
        at com.oracle.cie.domain.template.catalog.TemplateCatalogFactory.getGlobalCatalog(TemplateCatalogFactory.java:33)
        at com.oracle.cie.wizard.domain.silent.tasks.LoadTemplateCatalogTask$1.run(LoadTemplateCatalogTask.java:23)
        at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at com.oracle.cie.domain.template.catalog.TemplateCatalogFactory.createGlobalTemplateCatalog(TemplateCatalogFactory.java:133)
        ... 4 more
Caused by: com.oracle.cie.domain.env.EnvironmentServiceException: Failed to get inventory for /home/ec2-user/oracle/middleware/oracle_common/common/bin
        at com.oracle.cie.domain.env.EnvironmentServiceImpl.init(EnvironmentServiceImpl.java:425)
        at com.oracle.cie.domain.env.EnvironmentServiceImpl.<init>(EnvironmentServiceImpl.java:89)
        at `com`.oracle.cie.domain.env.EnvironmentServiceImpl.getInstance(EnvironmentServiceImpl.java:364)
        at com.oracle.cie.domain.env.EnvironmentServiceFactory.getEnvironmentService(EnvironmentServiceFactory.java:35)
        at com.oracle.cie.domain.template.catalog.impl.OracleHomeLocator.getProductInstalDirs(OracleHomeLocator.java:31)
        at com.oracle.cie.domain.template.catalog.impl.GlobalTemplateCat.populateProductCatalogs(GlobalTemplateCat.java:446)
        at com.oracle.cie.domain.template.catalog.impl.GlobalTemplateCat.<init>(GlobalTemplateCat.java:90)
        at com.oracle.cie.domain.template.catalog.impl.GlobalTemplateCat.<init>(GlobalTemplateCat.java:83)
        ... 9 more
Caused by: java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at com.oracle.cie.common.ReflectionHelper.process(ReflectionHelper.java:48)
        at com.oracle.cie.domain.env.EnvironmentServiceImpl.init(EnvironmentServiceImpl.java:384)
        ... 16 more
Caused by: com.oracle.cie.gdr.external.InventoryException: com.oracle.cie.gdr.utils.GdrException: The gdr meta-data directory /home/ec2-user/oracle/middleware/oracle_common/common/bin/inventory is invalid or does not exist.
        at com.oracle.cie.gdr.external.impl.OracleHomeInventoryImpl.<init>(OracleHomeInventoryImpl.java:55)
        at com.oracle.cie.gdr.external.impl.OracleHomeInventoryFactory.createInventory(OracleHomeInventoryFactory.java:60)
        at com.oracle.cie.gdr.external.InventoryFactory.getOracleHomeInventory(InventoryFactory.java:99)
        ... 22 more
Caused by: com.oracle.cie.gdr.utils.GdrException: The gdr meta-data directory /home/ec2-user/oracle/middleware/oracle_common/common/bin/inventory is invalid or does not exist.
        at com.oracle.cie.gdr.MetaDataHome.init(MetaDataHome.java:206)
        at com.oracle.cie.gdr.MetaDataHome.<init>(MetaDataHome.java:188)
        at com.oracle.cie.gdr.MetaDataHome.<init>(MetaDataHome.java:172)
        at com.oracle.cie.gdr.MetaDataHome.<init>(MetaDataHome.java:157)
        at com.oracle.cie.gdr.MetaDataHome.<init>(MetaDataHome.java:144)
        at com.oracle.cie.gdr.MetaDataHome.<init>(MetaDataHome.java:86)
        at com.oracle.cie.gdr.Home.getMetaDataHome(Home.java:619)
</code>
Answer: Which Weblogic version are you using? I have not seen a silent script to create domains for a While. If you are trying to do this on Weblogic 12c, it won't work as this kind of script used to be available for older versions such as 8 and 9 as far as I remember.
If you want to automate domain's provisioning for versions such as 12c you should use a newer approach. Here, I am proposing two options.

You can use Ansible, WLST and Python to create the domain. You can see an example here https://github.com/textanalyticsman/ansible-soa
You can use Weblogic Deploy Tooling, this is an Open Source tool provided by Oracle and you can find out it here https://github.com/oracle/weblogic-deploy-tooling
The combination of Weblogic Deploy Tooling and Ansible is also a good option as is shown in https://github.com/textanalyticsman/ansible-soa-wldt
You can also try Weblogic Kubernetes Operator https://oracle.github.io/weblogic-kubernetes-operator/userguide/managing-domains/domain-resource/


Legitimacy of Excluding Extreme Values - A Specific Case

Question: I'm handling surgical times: operating room time, time to do certain procedure, among others.
As you might guess, sometimes (hopefully rarely) surgeries have complications and thus aggravate immensely some of these surgical times, which then translates into a very rare but very extreme value (like - median 40 minutes, but these cases reach 200).
1) Is it expected for a variable such as surgical times, performed by the same team of surgeons on the same center during a not so long period of time, to have a normal distribution?
2) If my data is non-normally distributed, what statistical "excuse" / reason do I have to exclude these aberrant values?
2.1) For example, if the data is normally distributed, i would use the interquartile outlier labeling rule (Hoaglin) with k / the multiplier 2.2 as said "excuse"
2.2) But on the other hand, if I have non normal data, how could I justify, or better, is it statistically legitimate to exclude these values?
EDIT1: Adding clarity to the purpose of the study;
i'm addressing the influence of a new surgical technique (for the same procedure)
EDIT2: as suggested, I am adding some data to better contextualize the question. I have included the two variables mentioned in the comments - Time1 (one of these surgical times in minutes) and Blood Units Consumption - do note that "999" corresponds to missing value! N=120 - 60 in each group.
1) As you might notice, specially in the "old technique" group, there are a few aberrant values - if I understood correctly, there are no "statistically" valid reasons to exclude them, correct?
2) Secondly, I often read that choosing a mean comparison statistical test based solely on Normality Tests (Shapiro-Wilk, for example), despite being often suggested by some textbooks and websites, might not always be the best approach, and that nothing replaces "the good sense of a statistician" - as I am not a statistician, would you be so kind to elaborate on the subject and, more specifically, perhaps exemplify using the data provided?
3) Nick Cox said "t test usually works well even with moderate non-normality." which i found to be a very interesting statement - care to explain, please?
This has been really helpful, thank you all in advance!
<code>Old0New1Technique  Time1   BloodUnits

              0      36         3

              0      52        34

              0      52        30

              0      36         2

              0      38         6

              0     110        16

              0      45         8

              0      40         0

              0      40       999

              0      42        16

              0      81       129

              0      74        19

              0      44        26

              0      28         4

              0      44        18

              0      46        19

              0      43        18

              0      36         7

              0      40        29

              0      36        14

              0      65        34

              0      68        21

              0      35        15

              0      60        56

              0      43         9

              0      39        10

              0      39       999

              0      18         1

              0      44        14

              0      42        53

              0      42        53

              0      53        48

              0      36        16

              0      70        28

              0      34        28

              0      41         2

              0      30         0

              0      44         0

              0      31         2

              0      38         2

              0      43         5

              0      35        31

              0      38        28

              0      30         2

              0      37        21

              0      45         4

              0      38       999

              0      43         1

              0      41         2

              0      55        34

              0      51         9

              0      62         4

              0      47        16

              0     124       166

              0      55        14

              0      38        16

              0      50        31

              0      42        15

              0      36        16

              0      39        11

              1      47        12

              1      40         0

              1      75         8

              1      52         0

              1      50         0

              1      55         3

              1      43        17

              1      53         1

              1      56         1

              1      39         0

              1      53         9

              1      54         2

              1      47         7

              1      48         0

              1      51        11

              1      50         4

              1      81         1

              1      56         2

              1      54         0

              1      43         0

              1      33         6

              1      49         2

              1      42         7

              1      62         0

              1      50         0

              1      58         4

              1      68         0

              1      46         3

              1      45         0

              1      42         0

              1      73         3

              1      45         0

              1      54        17

              1      48         7

              1     189         1

              1      47         9

              1      47         5

              1      35         0

              1      45         0

              1      50         1

              1      47         0

              1      45         2

              1      47         3

              1      85         7

              1      49         1

              1      41         1

              1      90         0

              1      40        12

              1      45         4

              1      37         4

              1      50         0

              1      55         0

              1      50         3

              1      58         0

              1      47        10

              1      45         5

              1      55         0

              1      39         0

              1      43         0

              1      60         0
</code>
https://www.dropbox.com/s/4lp97nsv6f2jg99/SurgicalTechniqueDataSet.xlsx?dl=0
https://drive.google.com/file/d/0ByeSGirYFFwiUTkyMDNxV1ZWWjA/view?usp=sharing
Comment: I would add to Nick Cox and Scortchi's comments that without knowing what the research question (RQ) or intended analysis is, these "outliers" (note the quotation marks) might be the datapoints of interest. Think about the RQ: "what triggers extremely lengthy operations?" excluding these datapoints when trying to answer this question is non-sensical as these might be the outcomes you were looking for in the first place.
Comment: Strictly speaking, time, as in duration, could never be normally distributed because it's bound at zero (i.e., you could never have a procedure that took -10 minutes). You'd probably expect the distribution of procedure times to have a long tail
Comment: Excluded from what? I don't believe this question is answerable - except in a vague, general fashion - unless you edit it to explain what subsequent analysis you're proposing to carry out, to what purpose.
Comment: I wouldn't expect surgical times to be normally distributed in most cases. If there is a standard, predictably simple and rarely problematic procedure that might be approximately true. (Example: reversing dislocation of a shoulder.) For most procedures, I would expect that times would be definitely non-normal. There is no reason or excuse to throw out data that seem unusual unless you know **independently** that something quite special happened (e.g. a procedure was interrupted for some completely extraneous reason).
Comment: A t test usually works well even with moderate non-normality. You could try  a generalised linear model with technique as a binary predictor and test whether different link and family assumptions are crucial. I think you'd be likely to get an answer if you posted your data or otherwise made this really concrete. Otherwise we're speculating from other experience on what might or might not be good enough for your situation.
Comment: Sorry, but your data are inaccessible to me (and I guess many others) for reasons I don't have to explain. Copy and paste as text into your question for maximum accessibility.
Comment: Thanks for posting the data accessibly. I find that both logarithmic and reciprocal transformations work well to make the data more symmetrical; moderate outliers remain but do not seem pathological. I also find that various flavours of t test and various generalized models with log and reciprocal links all consistently give P-values around 0.05 for tests comparing the techniques. I don't know what to do with the blood units data, which aren't explained.
Comment: As for the RQ, i'm directly comparing specific surgical times and blood derivatives consumption using "the old" vs "the new" technique. For example - blood units consumption - with a median of 7 units, i have one case with 124. Naturally, when comparing both groups this value "ruins" any mean comparison test.
Comment: Indeed. but consider comparison on logarithmic scale or a different test.
Comment: even with log transformation the data does not assume a normal distribution. Still, the statistical significance of the data can be stated with a non parametric test (Mann-Whitney) ; Nonetheless, these cases have a noticeable impact on difference of medians and data variance. Any other suggestion? thanks!
Comment: Sure! I will share data from a few variables if might help. I'm currently at work, will try to post it whenever possible (a few hours probably). Thanks!
Comment: I reach similar values with an independent 2 sample t-test (p=0.05) , but with a Mann Whitney Test i get (p<0.001) - i was wondering which one would be more valid for this situation. Even though I like statistics and enjoy studying them, I realize how much of an amateur I am when I read your comment - nonetheless, you have given me plenty to make my own investigation on the matter. Concerning the blood units variable, the idea is pretty much the same - comparing blood unit consumption between the 2 groups. I have two gigantic extreme values on the old tecnhique group (166, 129).
Answer: If you are evaluating a new surgical technique then you should include the possibility of "complications" in your model. The new technique may alter the probability of complications and the time to deal with complications, not just the time to perform the procedure when there are no complications. You need to include those aspects in your model. This might not be so simple as a model based on log-normal or other simple distributions of procedure times, but it seems to be required for a fair comparison of the new technique against the present standard of care.
Comment: You make a valid point. Perhaps it would be wrong of me to simply discard and never mention these values as they probably coincide with complicated cases that should be reported and compared between groups. But then again, I could exclude them if I wanted to make an analysis on the procedures without complications, which are more frequent and more reproducible.
Comment: @Karpad: That's fair enough as far as it goes, but it needs to make sense to view a surgical procedure as either involving a complication or not (rather than viewing all as involving varying degrees of complication), and either those involving complications need to be recorded as such, or it needs to be so clear from their duration which they are that you can pick them out with a negligible chance of making a mistake (if you have to resort to mucking about with outlier tests, it's not clear - how will you take that uncertainty into account in your analysis?).
Answer: Typically "waiting times" (or "processing times") are modelled using an exponential distribution. An exponential random variable is positive, its distribution has a nice closed form, models the long tails that you are finding in your data, and is very well studied.
Comment: I'd want a really good argument that the modal duration of an operation was zero time, even as an approximation.
Comment: Sure, if you are trying to model it exactly. For the purpose of outliers, the exponential is a simple start. A better fit would be a Beta or Gamma distribution.


typeahead.js: change data source, which is given as a helper

Question: I need to change the helper source of my typeahead-input-field (sergeyt:typeahead):
<template name="searchMain">
    <input  class="typeahead"
            type="text"
            autocomplete="on"
            spellcheck="off"
            data-sets="searchData" />
</template>

Now I want to change it on any event like this:
Template.searchMain.events({
    'keyup .typeahead': function(event, template) {
        if ($(event.currentTarget).val() == 'change') {
            // the user typed 'change'
            // now change data source to 'newData'
        }
        else {
            // else use original data source 'searchData'
        }
    }
})

helpers
Template.searchMain.helpers({
    searchData: function() {
        // build some dataset from collections
        return ['complex', 'old', 'dataset'];
    },
    newData: function() {
        // build some dataset from collections
        return ['another', 'new', 'dataset'];
    }
});

As I would change the dataset like this...
$('.typeahead').typeahead('destroy');
$('.typeahead').typeahead({
    local: data
});

... I couldn't use the helper. So I don't know how to get back to origin
Answer: Perhaps you could use a reactive variable for this?
<template name="searchMain">
    <input  class="typeahead"
            type="text"
            autocomplete="on"
            spellcheck="off"
            data-sets="varDataSets" />
</template>

events
Template.searchMain.events({
    'keyup .typeahead': function(event, template) {
        if ($(event.currentTarget).val() == 'change') {
            Session.set('dataSets', 'new');
        }
        else {
            Session.set('dataSets', 'search');
        }
    }
})

helpers
Template.searchMain.helpers({
  varDataSets: function() {
    if (Session.get('dataSets') === 'search') {
      // build some dataset from collections
      return ['complex', 'old', 'dataset'];
    }
    // build some dataset from collections
    return ['another', 'new', 'dataset'];
  }
});

onRendered
Template.searchMain.onRendered(function () {
  this.autorun(function () {
    // will trigger the autorun everytime dataSets changes
    Session.get('dataSets');
    Meteor.typeahead.inject('.typeahead');
  });
});

Comment: I think that would't work, as the dataset will be initialized on rendering. Changing anything after this point won't give me new results...
Comment: I see... And if you force re-rendering ? See my edit
Comment: No, this doesn't work, either. I think I need to destroy the instance and do something like `Meteor.typeahead.inject();`. But I don't really know how...
Comment: Then you can try to trigger `Meteor.typeahead.inject()` every time your session variable changes, using [`template.autorun`](http://docs.meteor.com/#/full/template_autorun) (see my edit)


SQL Server 2008 R2:error

Question: insert into [ULGP_CARES TEST].[dbo].[person](date_of_birth)

select [Dtest].[dbo].[ContactBase].[BirthDate]
from [Dtest].[dbo].[ContactBase]
where
[Dtest].[dbo].[ContactBase].[FirstName]=[ULGP_CARES TEST].[dbo].[person].[first_name]

and
[Dtest].[dbo].[ContactBase].[MiddleName]=[ULGP_CARES TEST].[dbo].[person].  [middle_name]
and
[Dtest].[dbo].[ContactBase].[LastName]=[ULGP_CARES TEST].[dbo].[person].[last_name]

while trying to run the above query i am getting the following error
"Msg 4104, Level 16, State 1, Line 6
The multi-part identifier "ULGP_CARES TEST.dbo.person.first_name" could not be bound.
Msg 4104, Level 16, State 1, Line 9
The multi-part identifier "ULGP_CARES TEST.dbo.person.middle_name" could not be bound.
Msg 4104, Level 16, State 1, Line 11
The multi-part identifier "ULGP_CARES TEST.dbo.person.last_name" could not be bound."
how to solve this?
Answer: Try this:
insert into [ULGP_CARES TEST].[dbo].[person](date_of_birth)
select [Dtest].[dbo].[ContactBase].[BirthDate]
from [Dtest].[dbo].[ContactBase]
join [ULGP_CARES TEST].[dbo].[person]
on [ContactBase].[FirstName]=[person].[first_name]
and [ContactBase].[MiddleName]=[person].[middle_name]
and [ContactBase].[LastName]=[person].[last_name]

Without including the person table in the JOIN clause, SQL doesn't realize that it exists.
If that doesn't help out, you should also check the following:
Are you sure that the database named "ULGP_CARES TEST" exists? Perhaps it is spelled or capitalized differently, or that the space character is actually an underscore or vice versa. It's unusual to have an underscore and a space in the same database name.
Are you sure that the table named "person" exists in the database named "ULGP_CARES TEST"? Perhaps it is spelled or capitalized differently, or perhaps it is not part of the "dbo" schema.
Are you sure that the columns "first_name", "middle_name" and "last_name" exist in the table named "person" in the database named "ULGP_CARES TEST"? Perhaps it is spelled or capitalized differently.

SQL Server 2008 R2:error


Delphi é uma IDE ou linguagem de programação?

Question: Através de uma pergunta que apareceu aqui O que é linguagem de programação, IDE e compilador?, me surgiu uma dúvida:
Delphi é uma IDE ou linguagem de programação? Eu já ouvi programadores que trabalham com Delphi dizer que Delphi é uma IDE utilizada para programar em pascal. Mas qual é a real resposta?
Comment: A pergunta que não quer calar: a pronúncia é *Délfi* ou *Délfai*? :P
Comment: @utluiz é *delfái* :P
Comment: Podemos dizer que Delphi é uma IDE e a versão (depois do 7) do ObjectPascal usada com o compilador do Delphi é uma fork com modificações e acredito que esta fork foi rebatizada de Delphi, assim ambos levam o mesmo nome, semelhante a situação do Webkit (safari) e do Blink (Chrome). Não tenho a fonte desta informação e ela pode ser errônea, mas se eu conseguir irei tentar postar uma resposta :)
Comment: @GuilhermeNascimento é serio mesmo, nos primeiros capítulos deve ter essa informação, acredito eu.
Comment: @EduardoSeixas Acho que Pascal é uma coisa e ObjectPascal é outra. E pelo que estou lendo, na verdade parece que a linguagem é ObjectPascal e foram os usuários que começaram a dar este nome, o problema é que eu não encontre fonte oficial.
Comment: @rray Se isso for sério eu vou procurar kk, se bem que revistas antigas podem ter muita informação errada. O site deles carece de fontes (um wiki).
Comment: @utluiz Depende de qual país voce esta... [veja](http://delphi.wikia.com/wiki/Delphi_Pronunciation)
Comment: @utluiz Parece que a grande maioria utiliza [Delfi](http://english.stackexchange.com/a/32261)
Comment: o pascal existe desde 1970, ai vem o Delphi 35 anos depois e utiliza a linguagem e seu compilador, faz umas modificações, e a linguagem passa a se chamar Delphi? Ava
Comment: @GuilhermeNascimento vai no sebo veja se acha a biblia do delphi 6 e 7 :P pode ter alguma resposta ou dica.
Comment: Para ajudar mais um pouco a questão da pronúncia: https://translate.google.com/#en/pt/delphi.
Answer: Há controvérsias, eu já vi fontes que alegam uma coisa ou outra.
Isso tem pouca importância prática mas vale a curiosidade, ainda mais porque ajuda entender um pouco melhor o que está se fazendo e usando. Curiosidade é uma característica de todo bom programador, ou talvez qualquer profissional qualificado.
Object Pascal é uma linguagem originalmente criada pela Apple para melhorar o que o Pascal fazia, e um dos objetivos era adicionar capacidade de lidar com orientação a objeto.
A linguagem criada pela Apple nunca foi padronizada e foi abandonada. A Borland que tinha o melhor produto em cima da linguagem Pascal, o Turbo Pascal, usou a criação da Apple para melhorar seu produto que foi usado como base pela Apple. Depois ela mesma foi melhorando o tal do Object Pascal, se distanciando do que a Apple havia criado.
Em determinado momento não dava mais para chamar aquilo de Object Pascal e o nome da linguagem mudou para Delphi, confundindo com o nome do IDE. O que todo mundo já fazia. O que aumenta a confusão que as pessoas têm sobre o que é linguagem de programação e IDE. Mas o próprio site da Embarcadero chega usar o termo Object Pascal ainda. Note que em nenhum momento eles tentam resolver a questão. Parece que o termo exato foi escolhido para não deixar claro o que é linguagem e o que é IDE. No fim Delphi talvez seja o pacote todo da linguagem, IDE e outras ferramentas com as bibliotecas.
Pelo menos é isto que diz essa fonte. E a Wikipedia confirma (ou foi usado de fonte) de alguma forma como sendo uma linguagem que é um dialeto do Object Pascal. O outro artigo dá mais informações.
Há o Lazarus que é compatível com Delphi e pode ser usado em diversas plataformas gratuitamente. Não é exatamente a mesma coisa, é muito semelhante.
Delphi é marca registrada da Embarcadero, atual detentora do produto.
O mais importante é que você pronuncie corretamente delfái :P
Coloquei no GitHub para referência futura.
Comment: Recentemente a Embarcadero foi adquirida pela Idera. O produto(IDE) há alguns anos passou a chamar RAD Studio. O compilador(32bits) é dcc32.exe, por sua vez, a versao 64 é dcc64.exe
Comment: Já sobre o nome, quando a IDE é instalada, pode-se instalar suporte à C++ e Delphi. Podemos assumir que é oficialmente Delphi
Answer: Pelo que encontrei até agora, atualmente Delphi é uma linguagem de programação, conforme esse link da embarcadero/borland.

Delphi is a high-level, compiled, strongly typed language that supports structured and object-oriented design.

Essa resposta do SOen, ajuda a contar parte da história, até a versão 6 o Delphi era uma IDE para object pascal, como a linguagem foi descontinuada pela Apple, a partir da versão 7, a borland pegou o que tinha do object pascal fez algumas modificações e passou a chamar de linguagem Delphi.
Answer: Delphi de fato é uma IDE para programação de Pascal.
Mas não só isso, também serve de compilador para a mesma linguagem. Então, além de IDE é um compilador para programadores Pascal.
É muito utilizado no desenvolvimento de aplicações desktop. Aplicações multicamadas e cliente/servidor, compatível com os bancos de dados mais conhecidos do mercado.
Se alguem lhe perguntar em que linguagem você programa, não diga "DELPHI" voce só deve dizer DELPHI, quando lhe perguntarem em qual ambiente de desenvolvimento voce trabalha ou com qual ferramenta voce desenvolve. Quando você está usando o DELPHI, a linguagem gerada por ele é o Object Pascal.
Artigo interessantes sobre Delphi. O que é Delphi
Se souber inglês, aqui vai um artigo interessante sobre Delphi.
Comment: eu acho que esses "eu acho" acabam gerando a tal discussão
Comment: +1 Ao autor da resposta aqui mais um adicional para a resposta: https://en.wikipedia.org/wiki/Delphi_%28programming_language%29
Comment: Não tem nenhum referência da embarcadero/boarland?
Comment: Não é o que esse artigo diz http://www.clipatecinformatica.com.br/2012/04/delphi-linguagem-de-programacao-ou-ide.html
Comment: Já esse fala que é ide http://blog.scriptseguro.com.br/o-que-e-delphi/
Comment: Exato, alguns dizem que é e outros que não, me parece mais simples para a resposta dizer que é uma IDE.
Comment: Já esse aqui diz as duas coisas: https://www.oficinadanet.com.br/artigo/745/conhecendo_o_delphi
Comment: Também acho que é linguagem e IDE, linguagem baseada em object-pascal.
Comment: Adicionarei a resposta.
Comment: @rray, não achei nada muito produtivo, se tiver algo e quiser adiconar a resposta, fique a vontade. :)
Comment: http://groups.engin.umd.umich.edu/CIS/course.des/cis400/delphi/delphi.html artigo publicado pela universidade de michigan. Essa questão é muito polêmica.
Comment: Todo mundo sabe que Delphi é IDE, ai ficam colando links para blogs de gente que sabe menos que agente.
Answer: Qual compilador Object Pascal que compila essas instruções (generics) se não for o Delphi ?
<code>Var
    List : TList<String>;
Begin
    List : TList<String>.Create;
End;
</code>
Qual compilador Object Pascal que compila Métodos Anônimos ?
Qual compilador Object Pascal que compila Class Helpers ?
Qual compilador Object pascal que compila Class Attributes e a insere na RTTI ?
E da forma e na sintaxe que faz o Delphi ?
Diferentemente do Eclipse que possibilita edição de PHP, JAVA e outras linguagens permitindo perspectiva, a IDE do Delphi somente se ajusta ao próprio Delphi, então a IDE do Delphi é própria para ele mesmo, não podendo ser usada para outras linguagens.
Logo o Delphi é Linguagem + Compilador + IDE
Object pascal é a linguagem que se originou o Delphi, até mais ou menos o Delphi 7, após isso foi chamada de Delphi Language por um tempo, e recentemente a embarcadero voltou a chamar a linguagem de Object Pascal, mas também a chama de Delphi, ou seja parece não haver consenso.
Então não é errado chamar a linguagem de Delphi como também não pode-se taxar como erro chamar de Object Pascal de onde tudo se originou.
Comment: excelente resposta +1
Answer: Miguel, Delphi é uma IDE usada para criar programas nativos para plataforma windows. A história dessa IDE é longa, existem centenas de capítulos. Eu tenho comigo que a história da informática (como um todo) é bastante extensa, e uma das ferramentas mais usada no mundo é o DELPHI. As informações são tantas, são tantas modificações com o passar dos anos, o sentido se perde se não houver um a resposta bem pensada. o Delphi foi lançado em 1995, são 20 anos de história e inovação, hoje ele é completamente diferente do que já foi. Tome note, considere o Delphi como IDE, (e também como RAD), e seja feliz.
Answer: Como alguns já falaram, Delphi atualmente é linguagem de Programação, como se fosse um fork do Object Pascal, quem nomeia a linguagem é o desenvolvedor e mantenedor da linguagem e eles chamam de Delphi.
http://docwiki.embarcadero.com/RADStudio/Rio/en/Delphi_Language_Guide_Index
Answer: Vou programar usando a "linguagem de programação Delphi". Opa! Mas isso é um Pascal com algumas melhorias!
Pode chamar do que for, pra mim ainda é Pascal. Até em respeito aos que criaram a linguagem.
Comment: Acho melhor chamar de ALGOL, afinal o Pascal é só ALGOL com algumas melhorias. Deveria respeitar os criadores de ALGOL.


Optimizing SQL query, altering ORs

Question: With below condition query executes very long time. I think it depends from or conditions. How I can alternate these ors?
WHERE (p.tran_number = LTRIM(RTRIM(@tran_number)) OR ISNULL(LTRIM(RTRIM(@tran_number)), '') = '')
    AND (CAST(p.fiscal_date AS DATE) >= CAST(@begin_date AS DATE) OR @begin_date IS NULL)
    AND (CAST(p.fiscal_date AS DATE) <= CAST(@end_date AS DATE) OR @end_date IS NULL)
    AND CAST(@end_date AS DATE)
    AND (p.operation_type = @operation_type OR @operation_type = '-1')
    AND (
           ce.username = @username
        OR @role_code LIKE '%admin%'
        OR @role_code LIKE '%Statists_GO%'
        OR (
            (ce.username IN (
                SELECT e.domain_username
                FROM @childTable c
                LEFT JOIN FstP.dbo.employees e ON e.id = c.obj_id
                    AND c.obj_type = 'employee'
            )
        )
        AND @role_code LIKE '%supervisor%')
    )
    AND (p.rnm = @rnm OR ISNULL(@rnm, '') = '')
    AND (ce.username = @author OR ISNULL(@author, '') = '')
    AND (
           d2.docs_num = @policy_number
        OR dGate.DealNumber = @policy_number
        OR ISNULL(@policy_number, '') = ''
    )
ORDER BY insert_date DESC, fiscal_date DESC

Comment: Please provide execution plan...
Comment: Prepare all your variables before the query. I mean all those `ltrim`, `isnull(, '')`, `cast as date`.
Answer: SET @begin_date = CAST(@begin_date AS DATE)
SET @end_date = DATEADD(DAY, 1, CAST(@end_date AS DATE))
SET @tran_number = LTRIM(RTRIM(@tran_number))

...
WHERE (p.tran_number = @tran_number OR ISNULL(@tran_number, '') = '')
    AND (p.fiscal_date >= @begin_date OR @begin_date IS NULL)
    AND (p.fiscal_date < @end_date OR @end_date IS NULL)
    AND (p.operation_type = @operation_type OR @operation_type = '-1')
    AND (
           ce.username = @username
        OR @role_code LIKE '%admin%'
        OR @role_code LIKE '%Statists_GO%'
        OR (
            ce.username IN (
                    SELECT e.domain_username
                    FROM @childTable c
                    JOIN FstP.dbo.employees e ON e.id = c.obj_id
                        AND c.obj_type = 'employee'
                )
            AND @role_code LIKE '%supervisor%'
        )
    )
    AND (p.rnm = @rnm OR ISNULL(@rnm, '') = '')
    AND (ce.username = @author OR ISNULL(@author, '') = '')
    AND (
           d2.docs_num = @policy_number
        OR dGate.DealNumber = @policy_number
        OR ISNULL(@policy_number, '') = ''
    )
ORDER BY insert_date DESC, fiscal_date DESC
OPTION(RECOMPILE)

Optimizing SQL query, altering ORs


Matrix problems with unknowns on both sides.

Question: I have reduced a computational task to looking for solutions to problems of the form:
$$\mathbb{A}.\mathbb{X}=\mathbb{Y}\,,$$
where $\mathbb{A}$ and $\mathbb{Y}$ are $N\times(L+1)$ matrices.  $\mathbb{A}$ is given, but $\mathbb{Y}$ is given up to undetermined entries in the last column.  Finally $\mathbb{X}$ is a real $(L+1)\times(L+1)$ square matrix to be solved for, but the last row must be all zeros with a 1 at the end.
An example problem $N=4$, $L=2$ might be:
$$
\left(\begin{array}{cc|c}
1&0&0\\
0&1&2\\
0&1&1\\
1&1&1\\
\end{array}\right).\left(
\begin{array}{cc|c}
\alpha_1 & \alpha_2 & \alpha_3 \\
\beta_1 & \beta_2 & \beta_3 \\\hline
0 & 0 & 1
\end{array}
\right) = \left(\begin{array}{cc|c}
1&0&0\\
0&1&0\\
0&1&Y\\
1&1&0\\
\end{array}\right)
$$
where the six variables $\alpha_1$ ... $\beta_3$ along with $Y$ need to be solved for.
Question
Has this kind of linear algebra problem been studied before?  Or can this problem be reformulated in terms of something known?
Answer: Just multiply out the left hand side and equate entries with the right hand side.  You will obtain a system of $12$ linear equations in $7$ variables.  This system will have no solution, one solution or infinitely many solutions (depending on the specific details) and all solutions can be determined by standard methods.
In this case, for example, multiplying out the top row gives immediately $\alpha_1=1$, $\alpha_2=0$, $\alpha_3=0$.  But note that these may be contradicted by other equations, in which case there would be no solution.  I haven't pursued the specific calculations any further, will leave that to you.
Comment: Computational issues are not my strength :)  You can't invert $A$ as it is not square but maybe you could look up "generalised inverses" and see if there is anything useful.
Comment: Well, I was hoping to avoid this since sometimes the matrices are very large.  Is there not a standard algorithm to invert the rectangular $\mathbb{A}$ matrix to get $\mathbb{X}$ and $Y$, or something like that?


Creating a TopAppBar for each composable with navigation

Question: I am currently using a navigation drawer in jetpack compose, but I have encountered a problem. When I added the navigation drawer to the mainDrawerScreen, it was displaying for every screen I added, in my case it said "Main Menu" for every screen composable when navigated to. This is not ideal.
I decided to remove TopAppBar from mainDrawerScreen and create a seperat scaffold with the TopAppBar for each composable screen. However, now the navigation does not work. I tried to create a trailing lambda for navigation but might have done it the wrong way. Anyone got a suggestion to why it is not opening the navDrawer ? Appreciate the feedback!
MainDrawerSCreen:
@SuppressLint("UnusedMaterialScaffoldPaddingParameter")
@Composable
fun MainDrawerScreen() {

   val scaffoldState = rememberScaffoldState(rememberDrawerState(DrawerValue.Closed))
   val scope = rememberCoroutineScope()
   val navController = rememberNavController()

   Scaffold(
       scaffoldState = scaffoldState,
       drawerContent = {

           DrawerHeader()
           DrawerLayout(scope = scope, scaffoldState = scaffoldState , navController = navController)

       }
   ) {

       Navigation(navController = navController) // TODO This controls the navigation between different screens
   }
}

My seperate created TopAppBar:
@Composable
fun TopAppBar1(
   scope: CoroutineScope,
   scaffoldState: ScaffoldState,
   text: String,
   onIconClick: () -> Unit
   ) {
   TopAppBar(

       title = { Text(text = text, fontSize = 18.sp) },
       navigationIcon = {
           IconButton(onClick = {
               scope.launch {
                   withContext(Dispatchers.IO) { // should I keep this coroutine on background thread ?
                       scaffoldState.drawerState.open()
                   }
               }
           }) {
               Icon(
                   Icons.Filled.Menu, "Menu",
                   Modifier.clickable { onIconClick.invoke()})
           }
       },
       backgroundColor = LightBlue,
       contentColor = MaterialTheme.colors.onPrimary,

       )
}

ProfileScreen:
@SuppressLint("UnusedMaterialScaffoldPaddingParameter")
@Composable
fun ProfileScreen1() {

   val scaffoldState = rememberScaffoldState(rememberDrawerState(DrawerValue.Closed))
   val scope = rememberCoroutineScope()

   Scaffold(
   topBar = {
       TopAppBar1(scope = scope, scaffoldState = scaffoldState, text = "Profile") {
           scope.launch { scaffoldState.drawerState.currentValue }     <----------- Trailing Lambda
       }
},
   content = {
       ActualBackground() // Background

       Column(
           modifier = Modifier
               .fillMaxSize(),
           verticalArrangement = Arrangement.Center,
           horizontalAlignment = Alignment.CenterHorizontally,
       ) { // Content }

Answer: I show you what I did :
TopAppBar.kt :
@Composable
fun TopAppBarScreen(
    title: String = "",
    screen: String,
    navController: NavController
) {
    TopAppBar(
        title = {
            Text(
                text = title,
                style = Typography.h2
            )
        },
        navigationIcon = {
            IconButton(
                onClick = {
                    navController.navigate(screen)
                }
            ) {
                Icon(Icons.Filled.ArrowBack, "backIcon")
            }
        },
        backgroundColor = Color.Background,
        contentColor = Color.BackgroundDarkGrey,
        elevation = 0.dp,
    )
}

Navigation.kt
@Composable
fun Navigation() {
    val navController = rememberNavController()
    val viewModel = hiltViewModel<CountrySelectorViewModel>()
    val userViewModel = InputViewModel(LocalContext.current)
    NavHost(
        navController = navController,
        startDestination = Screen.WELCOME_SCREEN
    ) {
        composable(Screen.WELCOME_SCREEN) {
            WelcomeScreen(navController = navController)
        }
}

Screen :
object Screen {
    const val WELCOME_SCREEN = "WelcomeScreen"
}

When I call my TopAppBar :
TopAppBarScreen(
        screen = Screen.WELCOME_SCREEN,
        navController = navController
)

Look at how the navigation works and it's the same if you are using a button to change screen.
I hope this can help you
Comment: Hello, thanks for the reply! So just 1 thing to clarify cause I might have been a bit vague explained by me, sorry! I want to be able to open a navigation drawer with the click event, not navigate to a different screen. I tried to implement what you did but I am getting 1 problem. It says I need a Job instead of a string in the screen constructor inside TopAppBarScreen
Comment: this is what I tried to do: TopAppBarScreen(title = "Search", navController = navController, screen = scope.launch { scaffoldState.drawerState.open() }), then I get this message: type mismatch.
Required:
String
Found:
Job
Comment: Try probably to change in the TopAppBar.kt screen, because for me screen is a String but For you a job. The thing strange is that a scope is something doing next to the app. I don't know how to for a navigation drawer. I'm going to search and try to help you.
Comment: https://www.youtube.com/watch?v=JLICaBEiJS0 Try to do this, and you can watch all his tutorial it's helping me a lot to learn jetpack compose
Comment: Appreciate it! I already watched that video a few times :P, but my navigation problem seem a bit more complex than explained in the video.
Comment: I somehow have to be able to call scaffold.drawerstate.open() but I cant do this without using scope.launch { } which requres me to pass it wihtin the TopAppBar
Comment: Do you have a git repo for your project I can check and try to find a solution
Comment: No, sorry, not for this project though. This works similar to any navigation Drawer out there so If you figure something out though, just let me know here and I will try it out! :)
Comment: The problem is that when you give your scaffoldState at your TopBar, your TopBar to send it back to you activity, you have to use ViewModel. But I'm trying and I can't really find the solution yet
Comment: ohhh I see, I will look into implementing a viewmodel then and see if that helps with the navigation drawer
Comment: you can try this when you call AppBar : AppBar(
                             onNavigationIconClick = {
                                 scope.launch {
                                     scaffoldState.drawerState.open()
                                 }
                             }
                         )
Comment: Idk why with the viewModel it doesn't change
Comment: https://github.com/lerey34/NavigationDrawer If you want to see What I did
Comment: alright will give it a try!
Comment: I tried implementing similar into my project but without success so far
Comment: im thinking, maybe there is a way to use the same topappbar but we configure a title seperate, for every composable screen within a navHost ?


The Jordan Decomposition Theorem, Folland

Question:
The Jordan Decomposition Theorem - If $\nu$ is a signed measure, there exists unique positive measures $\nu^+$ and $\nu^-$ such that $\nu = \nu^+ - \nu^-$ and $\nu^+\perp \nu^-$.

Attempted proof - Let $X = P\cup N$ be a Hahn decomposition for $\nu$ where $P$ and $N$ are positive and negative sets respectively.. Then let us define the positive and negative measure as such $$\nu^{+}(E) := \nu(E\cap P) \ \ \ \nu^{-}(E) := - \nu(E\cap N)$$ then,
\begin{align*}
\nu^+(E) - \nu^-(E) &= \nu(E\cap P) + \nu(E\cap N)\\
&= \nu(E)
\end{align*}
So we have $\nu = \nu^+ - \nu^-$ and $\nu^+\perp \nu^-$.
Now I believe to complete this proof we need to show uniqueness. As in assuming we have $\nu = \tilde{\nu^{+}} - \tilde{\nu^{-}}$ is another such pair and we have $\tilde{\nu^{+}}\perp\tilde{\nu^{-}}$ we can find $\tilde{N}$ and $\tilde{P}$ such that $X = \tilde{P}\cup\tilde{N}$ and we need to check that $\tilde{P}$ is positive and $\tilde{N}$ is negative (not sure how to do that yet).
Then we need to show that $\tilde{\nu^{+}} = \nu^+$ and $\tilde{\nu^{-}} = \nu^-$ again I am not sure how to do that either yet.
Any suggestions is greatly appreciated.
Answer:
The Jordan Decomposition Theorem - If $\nu$ is a signed measure, there exists unique positive measures $\nu^+$ and $\nu^-$ such that $\nu = \nu^+ - \nu^-$ and $\nu^+\perp \nu^-$.

Proof - Let $X = P\cup N$ be a Hahn decomposition for $\nu$ where $P$ and $N$ are positive and negative sets respectively.. Then let us define the positive and negative measure as such $$\nu^{+}(E) := \nu(E\cap P) \ \ \ \nu^{-}(E) := - \nu(E\cap N)$$ then,
\begin{align*}
\nu^+(E) - \nu^-(E) &= \nu(E\cap P) + \nu(E\cap N)\\
&= \nu(E)
\end{align*}
So we have $\nu = \nu^+ - \nu^-$ and $\nu^+\perp \nu^-$.
To complete this proof, let us to show uniqueness. Suppose that $\nu = \tilde{\nu^{+}} - \tilde{\nu^{-}}$ is another such pair and we have $\tilde{\nu^{+}}\perp\tilde{\nu^{-}}$ we can find $\tilde{P}$ and $\tilde{N}$  such that $X = \tilde{P}\cup\tilde{N}$,  $\tilde{P}$ is null for $\tilde{\nu^{-}}$ and $\tilde{N}$ is null for $\tilde{\nu^{+}}$. So, for any measurable set $E\subset \tilde{P}$,
$$ \nu(E)= \tilde{\nu^{+}}(E) - \tilde{\nu^{-}}(E)=\tilde{\nu^{+}}(E)-0 = \tilde{\nu^{+}}(E) \geq 0$$
So $\tilde{P}$ is a positive set for $\nu$.
In a similar way, So, for any measurable set $F\subset \tilde{N}$,
$$ \nu(F)= \tilde{\nu^{+}}(F) - \tilde{\nu^{-}}(F)=0-\tilde{\nu^{-}}(F)= -\tilde{\nu^{-}}(F) \leq 0$$
So $\tilde{N}$ is a negative set for $\nu$.
So  $\tilde{P}$,  $\tilde{N}$ is another Hahn decomposition for $\nu$. So, from 3.3 Hahn Decomposition Theorem, we have that
$P\Delta \tilde{P} = N \Delta \tilde{N}$ is a null set for $\nu$.
So, $P\setminus \tilde{P}$, $\tilde{P}\setminus P$, $N\setminus \tilde{N}$ and $\tilde{N} \setminus N$ are null sets for $\nu$
For any measurable set $H\subset X$, we have
\begin{align*}
\nu^+(H)&= \nu(H\cap P)= \nu(H\cap(P\cap\tilde{P} ))+\nu(H\cap(P\setminus \tilde{P}))=\nu(H\cap(P\cap\tilde{P}) )=\\&= \nu(H\cap(P\cap\tilde{P}) )+\nu(H\cap(\tilde{P} \setminus P))= \nu(H\cap \tilde{P})= \tilde{\nu^{+}}(H\cap \tilde{P}) - \tilde{\nu^{-}}(H\cap \tilde{P})=\\&=  \tilde{\nu^{+}}(H\cap \tilde{P})=  \tilde{\nu^{+}}(H\cap \tilde{P}) +  \tilde{\nu^{+}}(H\cap \tilde{N})=  \tilde{\nu^{+}}(H)
\end{align*}
So we have that $\nu^+=\tilde{\nu^{+}}$.
In a similar way, we can prove that $\nu^-=\tilde{\nu^{-}}$.
(Or, if we had assumed, without loss of generality, that $\nu$ does not assume the value +\infty, we have
$\nu^-=\nu - \nu^+ = \nu - \tilde{\nu^{+}}= \tilde{\nu^{-}}$).
Answer: If $\tilde\nu^+\perp\tilde\nu^-$ then by definition of singularity of measures, there exists a partition $(\tilde P, \tilde N)$ of $X$ such that $\tilde P$ is null for $\tilde\nu^-$ and $\tilde N$ is null for $\tilde\nu^+$. But this means $(\tilde P,\tilde N)$ is a Hahn decomposition for $\nu$, since $\tilde\nu^+$ and $\tilde\nu^-$ are (positive) measures. Recall that the Hahn decomposition theorem implies then that $P\bigtriangleup\tilde P$ is $\nu$-null. From here it is straightforward to show that $\nu^+=\tilde\nu^+$ and $\nu^-=\tilde\nu^-$.


Is it possible to change the fields' names of the JSON generated by Services module?

Question: I have a mobile app, which calls a legacy system's HTTP REST interface. Now I replaced the legacy system with Drupal and Services module. I forgot setting field machine name to match mobile app client, however, there is no chance to modify the mobile app. So, as I asked in the title: is there a way to change the fields' names of the JSON generated by Services module?
Answer: You can use hook_services_request_postprocess_alter(): http://cgit.drupalcode.org/services/tree/docs/services.alter.api.php?h=7.x-3.x
For example, say you wanted to replace the node title property with nodeTitle when a node is being retrieved, you can do so like this:
/**
 * Implements hook_services_request_postprocess_alter().
 */
function my_module_services_request_postprocess_alter($controller, $args, &$result) {
  if ($controller['callback'] == '_node_resource_retrieve') {
    $result->nodeTitle = $result->title;
    unset($result->title);
  }
}

Comment: If using [Services Views](https://www.drupal.org/project/services_views) module, we can "set custom value key"  in the field output configuration form to make it.


How to plot a vertical line on a time series axis?

Question: I would like to 'link' two pieces of code. One,
x= df[df['Value']==True].sort_values(by='Date').head(1).Date

Out[111]:
8    2020-03-04

extracts the date where the first value appears; the other one
df[df['Buy']==1].groupby('Date').size().plot(ax=ax, label='Buy')

should plot some information through time.
I would like to add a vertical line at the first date where the value is true, i.e. 2020-03-04. In order to do it, I would need to extract this information from the first code (not using copy and paste) to the other piece of code which generates the plot.
Can you give me some guide on how to do it? Thanks a lot
Update:
I tried as follows:
x= df[df['Value']==True].sort_values(by='Date').head(1).Date.tolist()

Out[111]:
8    ['2020-03-04']

df[df['Buy']==1].groupby('Date').size().plot(ax=ax, label='Buy')

ax.axvline(x, color="red", linestyle="--")

but I got a TypeError: unhashable type: 'numpy.ndarray'
Some data:
Date           Buy      Value
0   2020-02-23  0   False
1   2020-02-23  0   False
2   2020-02-25  0   False
3   2020-02-27  1   False
4   2020-03-03  1   False
5   2020-03-03  1   False
6   2020-03-03  0   False
7   2020-03-04  1   False
8   2020-03-04  0   True
9   2020-03-04  0   True
10  2020-03-04  1   False
11  2020-03-05  0   True
12  2020-03-05  1   False
13  2020-03-05  1   False
14  2020-03-05  1   False
15  2020-03-06  0   False
16  2020-03-06  1   False
17  2020-03-06  1   False
18  2020-03-07  1   False
19  2020-03-07  1   False
20  2020-03-07  1   False
21  2020-03-08  1   False
22  2020-03-08  1   False
23  2020-03-09  1   False
24  2020-03-09  1   False
25  2020-03-09  1   False
26  2020-03-10  1   False
27  2020-03-10  1   False
28  2020-03-10  1   False
29  2020-03-10  0   True
30  2020-03-11  1   False
31  2020-03-11  1   False
32  2020-03-13  0   True
33  2020-03-13  0   False
34  2020-03-15  0   True
35  2020-03-16  0   False
36  2020-03-19  0   False
37  2020-03-22  0   True

Comment: Does this answer your question? [How do you plot a vertical line on a time series plot in Pandas?](https://stackoverflow.com/questions/19213789/how-do-you-plot-a-vertical-line-on-a-time-series-plot-in-pandas)
Answer:
Make certain the Date column is in a datetime format.

import pandas as pd
import random  # for test data
import matplotlib.pyplot as plt

# setup sample data
random.seed(365)
rows = 40
data = {'Date': [random.choice(pd.bdate_range('2020-02-23', freq='d', periods=rows).strftime('%Y-%m-%d').tolist()) for _ in range(rows)],
        'Buy': [random.choice([0, 1]) for _ in range(rows)],
        'Value': [random.choice([False, True]) for _ in range(rows)]}

df = pd.DataFrame(data)

# set the Date column to a datetime
df.Date = pd.to_datetime(df.Date)

# extract values
x = df[df['Value']==True].sort_values(by='Date').head(1).Date

# groupby and plot
ax = df[df['Buy']==1].groupby('Date').size().plot(figsize=(7, 5), label='Buy')

# plot the vertical line; axvline works as long as x is one value
ax.axvline(x, color="red", linestyle="--", label='my value')

# show the legend
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')

package versions
import matplotlib as mpl

print(mpl.__version__)
print(pd.__version__)

[out]:
3.3.1
1.1.0

Comment: Thank you so much. The problem was in setting the Date column to a datetime


How to compare ip addresses in SQL Server?

Question: I need to perform compare two ip address.
This is the model:
public partial class CityIp
{
    [Key]
    public string IpStart { get; set; }
    public string IpEnd { get; set; }
    public string Country { get; set; }
    public string Province { get; set; }
    public string City { get; set; }
}

My DB holds 6M rows of the model above.
I get an ip address and I have to understand: is it between ipStart and ipEnd?
I store ipStart and ipEnd as nvarchar, but I'm not sure that it correct way.
What is the best way to compare it?
I think it's not good to pull all rows from db and compare it in C# code. I prefer do it using SQL, but I don't know how to do it.
I need perform something like
SELECT
    Country, Province, City
FROM
    CityIP
WHERE
    ipStart <= 'myIp' AND 'myIp' <= ipEnd

Comment: How are you storing IP addresses? You should be storing them as `int` (for IPv4) or `varbinary(16)` for IPv4+IPv6, not as strings.
Comment: Also, you should ensure that those IP address ranges are internally contiguous.
Comment: If you are storing them as string (!) this might help you https://msdn.microsoft.com/en-us/library/ms187928.aspx
Answer: 1) We should store ip addresses using VARBINARY(16)!
[Ip] VARBINARY (16) NOT NULL

2) To compare if an ip address is in range you can just write
SELECT * FROM CityIp WHERE IpStart <= @IpAddress AND @IpAddress <= IpEnd

Where IpStart, IpAddress, IpEnd are VARBINARY(16).
3) To work with ip address we should use System.Net.IPAddress. You can call GetAddressBytes() to get bytes of your ip
So, my model looks like this
public partial class CityIp
{
    [Key]
    public byte[] IpStart { get; set; }
    public byte[] IpEnd { get; set; }
    public string Country { get; set; }
    public string Province { get; set; }
    public string City { get; set; }
}

Answer: This do the trick:
DECLARE @ipaddress nvarchar(16) = N'22.214.171.124'

SELECT *
FROM CityIp
WHERE
    (
        CAST(PARSENAME(IpStart, 4) AS bigint) * 256 * 256 * 256 +
        CAST(PARSENAME(IpStart, 3) AS bigint) * 256 * 256 +
        CAST(PARSENAME(IpStart, 2) AS bigint) * 256 +
        CAST(PARSENAME(IpStart, 1) AS bigint)
    )
    <=
    (
        CAST(PARSENAME(@ipaddress, 4) AS bigint) * 256 * 256 * 256  +
        CAST(PARSENAME(@ipaddress, 3) AS bigint) * 256 * 256 +
        CAST(PARSENAME(@ipaddress, 2) AS bigint) * 256 +
        CAST(PARSENAME(@ipaddress, 1) AS bigint)
    )
    AND
    (
        CAST(PARSENAME(IpEnd, 4) AS bigint) * 256 * 256 * 256 +
        CAST(PARSENAME(IpEnd, 3) AS bigint) * 256 * 256 +
        CAST(PARSENAME(IpEnd, 2) AS bigint) * 256 +
        CAST(PARSENAME(IpEnd, 1) AS bigint)
    )
    >=
    (
        CAST(PARSENAME(@ipaddress, 4) AS bigint) * 256 * 256 * 256  +
        CAST(PARSENAME(@ipaddress, 3) AS bigint) * 256 * 256 +
        CAST(PARSENAME(@ipaddress, 2) AS bigint) * 256 +
        CAST(PARSENAME(@ipaddress, 1) AS bigint)
    )

Unfortunately the query is slow because a full scan is required.
EDIT
The above query will work with ipv4 addresses. To deal with ipv6 addresses I would use a CLR scalar function like the following:
public partial class UserDefinedFunctions
{
    [SqlFunction(DataAccess=DataAccessKind.None, IsDeterministic=true, IsPrecise=true, SystemDataAccess=SystemDataAccessKind.None)]
    [return: SqlFacet(MaxSize=16)]
    public static  SqlBinary TryParseIPAddress([SqlFacet(MaxSize=40)] SqlString iPAddress)
    {
        if (iPAddress.IsNull) return SqlBinary.Null;
        IPAddress address;
        if (IPAddress.TryParse(iPAddress.Value, out address))
        {
            return new SqlBinary(address.GetAddressBytes());
        }
        else return SqlBinary.Null;
    }
}

Then use it like this:
DECLARE @ipaddress varbinary(16) = dbo.TryParseIPAddress( N'2001:0db8:85a3:0000:0000:8a2e:0370:7334')

SELECT *
FROM CityIp
WHERE
    dbo.TryParseIPAddress(IpStart) <= @ipaddress
    AND dbo.TryParseIPAddress(IpEnd) >= @ipaddress

EDIT:
One thing that would speed up things is adding two binary computed columns that store IpStart and IpEnd in binary format. But the biggest performance improvement would be applying Relational Interval Tree as shown in the following article:
Interval Queries in SQL Server
Comment: Are they ipv6 addresses?
Comment: Yes, they are ipv6 addresses
Comment: @Kostya Vyrodov ipv6 addresses are imposible to parse with simple T-SQL expressions, scalar functions are required, but they are very slow. Are you willing to use a CLR scalar function?
Comment: I don't know... I think we should try. Can I compare VARBINARY(16) using sql query?
Comment: Please, see my edit. Yes you can compare varbinary(16) columns and variables


Why is the player in the middle of I-formation called the fullback?

Question: From the names of the positions, I would assume that in an I-formation the order (from front to back) would be quarterback, halfback, then fullback.
This Image of the I-Form shows the fullback in between the quarterback and the running back, and the text from wikipedia says

Typically, fullbacks are larger in size than halfbacks and in most
  offensive schemes their duties are split between power running and
  blocking for both the quarterback and the other running back.

So I can see why this kind of player would line up where he does, as it enables him to block for the other running back. But why is he called the fullback?
Answer: Here's an attempt to layout the history of the position, and the time periods in which it changed. All of this information can be found here, although it's buried with all of the history of every other position as well. This question requires a good understanding of nomenclature, and I would encourage you to read the entire article in the link, especially the sections labelled "Age of Confusion" and "Making Sense of it All." As the article states:

The trend away from geometric naming of the offensive positions has led to considerable confusion

So here are the bullet points that help identify the evolution of the fullback position. The origin of the fullback was in 19th century rugby. Originally these positions were named "tends," but the evolution of the game created some new positions with new names.

As the game became more sophisticated, backs positioned at different depths (i.e. distances behind the forwards) were further differentiated into half back, three quarters (the fraction 3/4) back, and full back... It was the Irish nomenclature of quarter back, half back, and full back that came to North America for use in what was to become the dominant native form of football. The terms became hyphenated and eventually unhyphenated single words, "quarterback" (QB), "halfback" (HB), and "fullback" (FB).

In the early days of American football (around the beginning of the 20th century), the role of the fullback was altered. Instead of the position just indicating a position behind the line of scrimmage, it began to also identify the role and physical nature of the position.

Over time, the typically fast back who played fullback, on offense and defense, was replaced by a heavier one who presented a greater threat to run with the ball more or less straight ahead, and to tackle his opponent trying to do the same. For this purpose, the player tended to be placed closer to the line than previously—often as far forward as the halfbacks (the offensive backs then forming a letter T, sometimes called a "straight T", later to distinguish it from slight variants wherein other backs did not form a line perpendicular to that from the quarterback) or even farther forward. But the position kept being called "fullback".

In the 1960s, many non-professional teams lost the distinction between a halfback and fullback. The NFL maintained the nomenclature of halfback and fullback:

...the distinction between fullback and halfback was erased, each replaced by "running back" (RB). That term became popular during the 1960s as well, although even into the 1970s, some playing the pro set kept the HB-FB distinction... The distinction referred to the build of the players, the fullback being a stronger runner more or less straight ahead, and the halfback faster to attack the defense's flanks. However, on many teams there was no strong distinction between those backs, and since their major role was running with the ball, "running back" was most descriptive without maintaining a spurious geometric connotation that'd become outmoded by their lining up in different depth relationships.

This trend has continued on. The present day explanation of fullbacks:

[T]o this day many teams maintain the offense's fullback-halfback distinction... [S]ome formations have placed the heavy back even more starkly forward, to function as a blocker for the running backs.

There are a number of current NFL teams that do not have a full-time fullback in their starting lineup. The three with no fullback listed:

New England Patriots
Indianapolis Colts
Detroit Lions

The four that have a hybrid fullback:

Kansas City Chiefs (Peyton Hillis is listed as a RB/FB)
Denver Broncos (Chris Gronkowski is listed as FB/TE)
Chicago Bears (Evan Rodriguez is listed as a FB/TE)
Seattle Seahawks (Michael Robinson listed as RB/FB)

In some instances, teams will line up a defensive lineman as a fullback:

In selected plays, some teams will have a defensive lineman report as an eligible receiver to line up as a fullback. Examples of such players who have been frequently used as situational fullbacks include Haloti Ngata, Vince Wilfork, and Isaac Sopoaga.
Answer: It all goes back to the beginning of the game.
Way back when, the Quarterback would be a quarter of a yard away from the line of scrimmage, the halfback would be half a yard away, and the fullback a full yard away.
Hence the name, Fullback.
Comment: That is sort of what I guessed must have been the case. If so, when did the change occur, and why?
Comment: @Fillet: The change occurred because offensive schemes gradually became using a fullback as a blocker, as they were bigger and stronger. There is no one date when this happened.
Comment: This answer makes no sense. The terms 'halfback' and 'fullback' are used in Rugby league and Rugby Union in which the 'half a yard -> halfback' would make no sense. These terms pre-date American Football's evolution as a separate code from Rugby football. Plus it is inconceivable that by moving less than a foot you are suddenly in a different position! The answer by sociomatt makes much more sense.
Answer: Perhaps a better way of putting this question would be, "Why did football teams put the fullback in the middle of the (relatively new) I formation in contrast to his traditional role?"
The three types of "backs" (the offensive players behind the line of scrimmage) are the quarterback, half back, and fullback.
Besides their "traditional" positioning, one quarter, one half, and one full yard behind the line, the quarterback is the most versatile, insofar as he can either pass or run with the ball.
The job of the two "halfbacks" is to use speed to run to either side of the line, sometimes past the end (end run), sometimes behind the tackle (off tackle).The job of a fullback is to run through the center of the opposing line (if the quarterback determines that his threatened pass maneuvers have caused the opponents to weaken their defense). But he was held back in "reserve" because this was typically the least favored offensive option.
Starting about 50 years ago, one of the halfbacks would become a "flanker" who would outflank one of his ends on the line of scrimmage to become a "wide receiver" This created a so-called "strong" side, with the extra pass receiver. Defenses adapted to this change by "shifting" an extra man on the strong side.
The I formation was the standard counter to this new defense. The idea was to use the non-flanking halfback to run to the weak side (the opposite side to the wide receiver). To create a further numerical imbalance, the fullback would be used as a blocker for the halfback, instead of as a runner up the middle. That's why the fullback was inserted between the quarterback and the halfback in the I-formation.
Of course there were variations of this, if the defense "compensated" by moving a man back to the "weak" side. The fullback could be deployed to the strong side as a blocker for a "pitchout" to the halfback, or given the ball to run through the center, depending on how the quarterback "sized up" the defense. The i-formation was adopted because it gave the most flexibility to the offense.


What is the rule in tennis doubles if the opposition change the sides they receive on

Question: What is the rule in tennis doubles if the opposition change the sides they receive On? Ie "Jim" was receiving from the ad side for the first 11 games, then started on the deuce.
I was in a match yesterday and the first point was played with the opponents on different sides of the court they had played for the rest of the set. They lost that first point then realised and wanted to start the game again. We were 6-5 up and serving. This was for the win.
I thought that actually meant they lost that game; although, I didn't want to win that way. I said they could continue from 15-0 if they wanted.
Answer: ITF Rule 27 (Correcting Errors), section e covers this:

During a standard game or a tie-break game in doubles, if there is an error in
the order of receiving, this shall remain as altered until the end of the game in
which the error is discovered. For the next game in which they are the
receivers in that set, the partners shall then resume the original order of
receiving.

So in your case, as the error was only discovered after the first rally, you should have continued the game with the opponents returning in that order. Neither replaying the game from the beginning nor switching the order within the game would have been correct.
Comment: Great. Thanks for the answer


How can I swallow all exceptions and protect my application from crashing?

Question: I've found several C# application crashes in response to error conditions such as obj = null or obj.member = null. A lot of time, the obj from the interface of 3rdPartyApp.
And caused both 3rdPartyApp and MyCsApp crashed together.
How could I add exception handling in all possible areas so that my application can survive in these disastrous situations? It is a challenge to add try-catch to ALL places, and recover from the situation.
How could I accomplish this in a way which is realistic, reliable and bullet-proof?
[Update: Industry Automation Control]
Structure:
GUI(asp.net, c++) - RuntimeApp (C++) - MyCsApp(cs) - 3rdPartyApp(Cs)
Normal procedure:

HostApp --(Connect through ethernet Cabele)--
MyCsApp
Operator -- GUI -- RuntimeApp --
MyCsApp

Abnormal conditions:

Some non-standard operation procedure;
some hardware issue occurred;
etc.

I'd better handle all the abnormall conditions.
And most importantly, I must think how to recover from the situations.
Comment: How about fixing the bugs instead?
Comment: Two words. Don't do it. Damn, that was three... Well now I may as well say why.  You will prevent your app from gracefully exiting when it needs to.  If you use the global and thread level exception handlers mentioned by others below, have a plan for WHAT to do when it's reached. . . Logging the error is fine, including the call stack will help with fixing the bug.  Keeping the app up after may not be a good idea in most cases... But then again it might... Know your code and environment to know for sure.
Comment: If each and every exception is truly coming from a 3rd-party app - and isn't just the result of various bugs in processing the data from it - then you obviously need to treat this app as untrustworthy, and put error handling in every instance of communication with this app, at the point of origin, *where you might actually be able to handle it*.  If a `NullReferenceException` bubbles to the top of the stack, you're doomed, there's no graceful recovery.
Comment: And having said that, looking at your comment, reading from a 3rd-party application's log file is **not** the way to do interop.  There are several options - memory-mapped files, named pipes, shared databases - but if you're reading directly from a log file, I would suspect that you are running into a number of locking issues and race conditions.  The fact that you mention multi-threading also lends credence to the explanation of inadequate synchronization and possible race conditions.  Sounds like you're in for a long month of debugging.
Comment: I'm sorry to have to tell you that it's too late. You already failed your company. The time to worry about exception handling was when the application was being designed. In fact, I'm shocked to hear of factory automation software not being designed for safety. Are you from Toyota?
Comment: @Aaronaught: I think it may be too late. If this were someone who understood memory mapped files, etc., then maybe it could get done. I think a better strategy would be to hire a consultant with advanced skills to clean up the mess, or to at least tell them how. I'm very concerned about the current path. I'm not visiting any factories until I know what company this guy works for.
Comment: @Aaronaught, we already protected some places currently, That means We can only fixed it after happend the cursh under abnormal operations. MyCsApp a multi-threads application based on the 3rdPartyApp. We must read several kinds logs(HostApp log, runtimeApp log,MyCsApp Log and 3rdPartyApp Log) and try our best to duplicate the issue. Then we can fix it.
Comment: @Aaronaught, And I would like to verify "every instance of communication with my app" as your suggestion.  Could you give me more guide about  **- memory-mapped files, named pipes, **. Can I add some trace log to MyCsApp and create the memory-mapped file and named pipes file? thanks.
Comment: @Nano HE: Memory-mapped files and named pipes are *methods of inter-process communication*, ones that you would design into an IPC application from the start.  They are not related to application tracing or exception handling in any significant way.  I suggest starting your research here: http://stackoverflow.com/questions/50153/interprocess-communication-for-windows-in-c-net-2-0
Comment: @John Saunders: Maybe it is too late, but if there's any chance we can help to prevent one more engineering disaster (without actually working for free), then I'll take the odds.  Call me an optimist!
Comment: @John Saunders: Hello. I am newbie from China, I worked as a hardware engineer till Aug 2008. After layoff, I found a new job to develope software from Apr 2009. Acturally I am not a Computer background student in university, but I am familiar to hardware. My new boss told me that I can get the job if I really enjoied to be a software engineer and detail oriented coding. Maybe I asked some dumb questions. It's an exciting thing to learn new programming knowledge for me. My team also try our best to prevent crush happening again. I posted here to get kind suggestion. thank you.
Comment: @John Saunders: "Are you from Toyota?" <- Ha! Hysterical!
Comment: @Nano HE: glad to hear more from China: It's not a dumb question - you've just got some dumb managers, apparently. If I'm ever fortunate enough to visit China, I will not be visiting any factories.
Answer: You do not want to catch every exception everywhere.
You want to prevent exceptions from "leaking out" of the lower layers of your application up to where they can kill the application or corrupt it.
But preventing corruption is going to require more than just catching exceptions. You're going to have to make sure that the application is always safe to interrupt at every point where an exception could be thrown. This may mean that you need to clean up complicated operations. For example:
ComplexBuilder cb = new ComplexBuilder();
try
{
    cb.AddOperation(...);  // Once building starts,
    cb.AddOperation(...);  // it's not safe to use cb
    cb.AddOperation(...);
}
catch (SpecificException ex)
{
    cb.Cleanup();          // until it's cleaned up
}

// Now safe to access cb, whether or not an exception was thrown

I recently ran into an application with a similar attitude. There was piece of this application that was considered to be "important". When that "important" thing happened, there were other things that were supposed to happen, but which were considered "not important". The idea was that if there was an exception in the "not important" part, then it was necessary for the "important" part to continue.
What happened is that an attempt to read a resource failed for some reason. This returned null instead of the string resource. This caused an ArgumentNullException in a String.Format call. This caused the exception to be caught by code that just continued.
But between the first exception and the last one, an object was to have been allocated, and the reference to the object was to have been set. But because of the exception, setting the reference never happened. The result was that I saw a NullReferenceException, four stack levels up, and two .csproj files away from where the actual problem happened.
So when you talk about catching exceptions so that your program can continue, you need to keep in mind that the control flow of your program is changed drastically by catching all these exceptions. In fact, it could be changed so much that you can no longer determine whether it's safe for your program to continue executing.
Comment: Ding, Ding, Ding.  We have a winner.
Answer: This is something that a lot of developers don't get. By the time your exception catch-all gets hit, your application has already crashed. Something unexpected happened, which means that your code didn't anticipate it, and things are very likely to be in an indeterminate state (i.e. you can't be certain exactly how much of the offending function completed at the point the exception was generated, you don't know how much data got written out, what bits got set in the hardware, etc.). Is it safe to continue on? Should you try to save out the user's data? Who knows!
When you reach this high-level catch-all you're going to provide, you haven't prevented your app from crashing. You're just deciding what to do about the crash at that point. You can put up a different message than the standard:

This application has performed an illegal operation

...but what's your custom message going to say that's any better?

We're shutting down without warning
  for unscheduled maintenance, but rest
  assured that it had nothing to do with
  a flaw in this excellent software

...?
Answer: you should certainly not add try catch everywhere
you just need a top level catch of all exceptions. If this is a GUI app then just display a nice dialog with a button saying 'please report to support' (it can write out a stack trace snapshot to the screen or a file)
if you are lucky then the app can continue (lucky since you have no way of knowing if you are really stuck badly)
note that you can also do this
        AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
        Forms.Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

but that doesnt stop it crshing, it just lets you capture the failure
Answer: It would make sense to cure the disease first, find out why it's causing to crash, sure the code is crashing because of obj = null or similar - using exception handling and swallowing all exceptions is just masking the problem....That's what it is not used for! It sounds like there's a lot of code-smells that is triggering the crashes - Protecting your application from crashing is not the right way to deal with it and only making things worse...
Ok, you can follow John Saunders's and pm100's suggestion to do that...but handle it in a manner to see what's the root cause, do not treat it as a 'magic silver bullet', at the end of the day, the code that is interacting with the third party application needs to be debugged thoroughly...
for instance

object foo = null;
bar baz;

// ....
// foo is now set by thirdparty app

if (foo != null && foo is bar)  baz = (bar)foo as bar;

if (baz != null){

  // Continue on, baz is a legitimate instance of type 'bar'

}else{

  // Handle it gracefully or throw a *user defined exception*

}

Notice how the 'as' is used to check if 'foo' is of the right type for 'bar' instance - now compare with this, that is a typical code smell...

object foo = null;
bar baz;

// foo is now set by thirdparty app - ARE YOU REALLY SURE ITS NON-NULL?
// IS IT REALLY OF TYPE 'BAR'?

baz = foo; // CRASH! BANG! WALLOP! KERRUNCH!
Comment: @tommieb75 & Aaronaught. I would like to accept your reply as my company application solution. **Try to find the root cause and fix it**. @ALL. I would like to do more study and practice based on your repliese. If possible, I would try to add the **sub module level** crash handle with your solutions. THANKS A LOT.
Answer: One technique to avoid such exceptions is to use the null object pattern.
So instead of having Account account = null; you would do Account account = Account.SpecialNullAccount; and in your Account class you would define SpecialNullAccount as a static Account object.  Now if you try to use account.Name in some inconsequential code (like, say logging code) you don't get an Exception, instead you get a value like, say "NO NAME" defined on the static null object instance.
Of course it's important that such an object DOES throw Exceptions in any important case like .PayInvoice() or objectContext.SaveChanges() so take steps to ensure that happens.
Comment: @Hightechrider: yes, the null object pattern prevents exceptions, but it doesn't make the program any more correct. It would be better to have the exception, safe the application, then fix the problem.
Comment: @John Saunders.  Disagree that null value pattern doesn't improve your code. The null value pattern prevents pointless exceptions that really weren't necessary (e.g. log (account.Name) is NOT somewhere you want an Exception just because the user isn't logged in) AND it reveals more about your code because it differentiates between forgetting to initialize a variable and having a value that's deliberately not set yet: When PayInvoice() fails you can immediately see whether it's because the account value was never set OR because the user wasn't logged in.
Comment: Null object pattern in OO is very similar to `NULL` values in databases - it solves some problems, but brings with it a mountain of new ones.  It prevents "fail fast", allowing a program to run incorrectly for a long time and fail mysteriously later on.  What *would* help to ensure correctness in this scenario is non-nullable types, such as those implemented by Spec#, but the time to introduce extensions like that is when the code is stable, not crashing everywhere.
Comment: What if the account's name is actually `NO NAME`?
Answer: AppDomain.UnHandledException and/or AppDomain.ThreadException are events you can subscribe to to catch unhandled exceptions. I don't think you can use this to continue execution where it left off (and this probably woudn't be a good idea anyway). They can be used swallow the error message or log it, etc.
Whether this is a good idea to do is up to you however!
Comment: One Caveat to this advice is that if the exception happened due to being in a bad/unrecoverable state, this will actually cause the app to continue to misbehave, and thoroughly frustrate a user.  Sure it's frustrating to deal with an app that crashes, however it's more frustrating to deal with an app that is overly misbehaving.
Answer: If it is a Winforms application add event handlers for for the following events in Main method like this
Application.ThreadException += Application_ThreadException;
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

You can then show a messagebox or other notification, loog the exeception etc and continue working without crashing the app.
Comment: One Caveat to this advice is that if the exception happened due to being in a bad/unrecoverable state, this will actually cause the app to continue to misbehave, and thoroughly frustrate a user.  Sure it's frustrating to deal with an app that crashes, however it's more frustrating to deal with an app that is overly misbehaving.
Comment: Agree with Jason. I was describing a LOB app that has errors due to individual bad data and not in general. So you can happily continue after catching the exception. Another set of data you work with may have no issue at all.
Comment: I wouldn't say that you can "happily" continue.  At a *bare minimum* these errors need to be thoroughly logged, investigated, tracked, resolved in a sane and organized fashion.  Simply skipping the file or outputting a cryptic debug message may allow the *application* to keep running but will bring down the *business* very fast.
Comment: Aaronaught, you misunderstood the "you". You in this case is the end user. Of course the exception handler logs everything and the end user reports the error via some ticketing system. Each support ticket is analysed, fixed, reported etc. What I meant is that for the end user the app doesn't crash but he/she can continue using it after reporting the error. You the developer of course has the responsibility the fix the cause of the error and not happily shove it under the bench.


how to set cron correctly on a shared server

Question: I set the following command for cron on a shared server.
<code>/usr/bin/php5.3 home/public_html/cron.php
</code>
(All the Drupal files are under /public_html)
This commend seems to be working but I get the following error
<code>PHP Warning:  Cannot modify header information - headers already sent by (output started at /home/public_html/sites/default/settings.php:1) in /home/public_html/includes/bootstrap.inc on line 1163
Sorry,  has been banned.
</code>
Am I missing something?
Answer: Looks like perhaps you settings.php file has some extra characters outside of the


If $A$ and $B$ have characteristic polynomial $x^5-x^3$ and minimal polynomial $x^4-x^2$, then they're similar.

Question: Let $A$ and $B$ be matrices with coefficients in some field $k$.  If they both have characteristic polynomial $x^5-x^3$ and minimal polynomial $x^4-x^2$, then they must be similar.
I've thought about this for awhile now, and I still have not made any progress.
Comment: Hint: you can prove $\det(xI-A)$ equals $\det(xI-P^{-1}AP)$ for an invertible matrix $P$
Comment: Yes.  Similar matrices have the same characteristic polynomial, but I'm not sure what you're getting at.
Comment: Yeah, that's not helpfull here. Hmmm the case is always true for $n \le 3$. See http://math.stackexchange.com/a/56725
Answer: Do you know about Jordan Canonical Form?
Two matrices are similar if and only they have the same Jordan Canonical Forms (same meaning up to rearrangements of the Jordan Blocks).
So we first factor $x^5 - x^3 = x^3 \cdot (x-1)(x+1)$ which means they have eigenvalues (including multiplicity, obviously) $0, 0, 0, 1, -1$.
If your field is not of characteristic $2$:
Since $1$ and $-1$ appear in the characteristic polynomial once, their Jordan blocks must have size $1$.$0$, a priori, could have a block of size $3$, a block of size $2$ and a block of size $1$, or three blocks of size $1$.
If your field is of characteristic $2$:
Your eigenvalues are $0, 0, 0, 1, 1$. Block sizes for $0$ are the same, block sizes for $1$ are one block of size $2$ or two blocks of size $1$.
We factor their minimal polynomial as $x^4 - x^2 = x^2(x+ 1)(x-1)$. The minimal polynomial tells us the largest Jordan Block corresponding to the eigenvalue $0$ is of size exactly $2$.  If we have one Jordan block of size exactly $2$, the other Jordan block is determined to be $1$.
If your field is of characteristic $2$, then you also get that the block with ones on the diagonal must be of size $2$ since the factor appears twice in the minimal polynomial.
So there is only one option for the Jordan Canonical form of a matrix with this characteristic polynomial and minimal polynomial,
In characteristic not $2$, a block of size $1$ with $1$ on the diagonal, a block of size $1$ with $-1$ on the diagonal, a block of size $2$ with $0$ on the diagonal, and a block of size $1$ with $0$ on the diagonal.
In characteristic $2$, a block of size $2$ with $1$ on the diagonal, a block of size $2$ with $0$ on the diagonal, and a block of size $1$ with $0$ on the diagonal.
As there is only one option for the Jordan Forms, they must have the same Jordan form, hence are similar.
Comment: You can also just extend your base field to an algebraically closed field, since extending the base field doesn't change whether two matrices are similar.
Comment: I'm aware of Jordan Canonical Forms for algebraically closed fields.  Does this solution generalize to arbitrary fields?
Comment: @GillyB Well Jordan Canonical form is only guaranteed to exist for algebraically closed fields, but if all of the roots of the minimal/characteristic polynomial lie in the field you're working in, the matrix can still be put into Jordan form, and results of uniqueness still hold. The field being algebraically closed only ensures that your field has all of the eigenvalues (This is the only place the algebraically closed condition is used). I just realized that what I gave doesn't work for Characteristic $2$ since $1 = -1$, but it is easily modifiable.
Comment: Interesting.  For some reason this never occurred to me.


What is the best statistics way to identify the gap of a plot?

Question: For example, I have the following plot, where y-axis is the values and x-axis is the index of the data point.

There are clearly two gaps in this plot, and I wonder what is the best way to identify these two gaps.
I hope the method could be based on statistics without fancy machine learning methods with regularizers, because I won't have development data set to tune the weight of a regularizer.
The one way I found can work is to calculate the mean and variance of the first fifty values (let's say we assume there are at least half of the values are in the first family), and test whether following points are five standard deviations away from this mean. This method works very well for to identify the second family, but the problem is that, since I don't know how many members will be roughly in the second family, it's hard to calculate the mean and variance for the second family. In addition, the number five seems to be very arbitrary. (A non-arbitrary choice might be 1.96, corresponding to the 5% of the Gaussian mass and 5% is more or less a standard choice of hypothesis testing, but 1.96 does not work.)
Are there any suggestions for the methods to identify such a gap?
Comment: Are you asking for change point analysis?....
Comment: Look for large first differences $\Delta y_t = y_{t} - y_{t-1}$ or large second differences $\Delta y_t - \Delta y_{t-1}$?
Comment: [Why?](http://arfer.net/w/statqgl)
Comment: @usεr11852 I just googled "change point analysis", it seems to be very relevant. Thanks. I will look into it further.
Answer: Since you are already onto a solution after @usεr11852's comment I'll just outline my suggestion instead of explaining a full solution.
This is similar to your idea of checking if the next point in the plot lies within 1.96 standard deviations.

Begin by taking the first 3 points on your graph and do a linear regression for them
Calculate a 95% prediction interval for the value of $y$ given the next value of $x$ on the graph. A 95% prediction interval for a given $x$ tells you the range of values where you will expect future observations (i.e. the points not used in the regression) Page 11 of these slides show the formula for a prediction interval.
If the next point is outside the prediction interval then it's probably not part of the line, if it is within the prediction interval then repeat the regression with this point included and make the prediction interval for the next point
Once you find a point which isn't in the prediction interval then that is where the gap starts

Once subtle point is that this repeated testing with the prediction interval isn't really giving you 95% certainty for the point where the gap starts. Since you are repeatedly testing with a 95% interval you should eventually find that a point is statistically significant even though it just a fluke.
To overcome this you should adjust the significance based on how many points you have already tested. If you already compared the prediction interval to $n$ points and you want 5% significance then use an adjusted significance of $1-(1-0.05)^{\frac{1}{1+n}}$. This comes from the Sidak correction