Is there research material on NTP accuracy available?

Question: As far as I know, accuracy of NTP syncronization highly depends on the network. I've seen some numbers from 50 microseconds to a "below one second" over the internet. Well, this is a huge difference.
I believe, accuracy dependence is a great question to study, but so far I failed to find any material, which clearly states that, say, some particular configuration grants that particular accuracy.
It is said on http://www.ntp.org/ntpfaq/NTP-s-algo.htm:

A time difference of less than 128ms between server and client is required to maintain NTP synchronization. The typical accuracy on the Internet ranges from about 5ms to 100ms, possibly varying with network delays. A recent survey[2] suggests that 90% of the NTP servers have network delays below 100ms, and about 99% are synchronized within one second to the synchronization peer.
With PPS synchronization an accuracy of 50µs and a stability below 0.1 PPM is achievable on a Pentium PC (running Linux for example).

That's something, but maybe there is some more thorough analysis on the topic?
Comment: Whilst I think this question shows no research effort at all, and am downvoting on that basis - it's not even clear the OP has read any of the material on http://www.ntp.org - I do think it's a lawful question, and would argue against closure on that basis.  Wanting to know why a protocol will work as advertised, instead of blindly deploying and hoping for the best, isn't a waste of time.
Comment: NTP hasn't changed in at least 14 years, why would it's accuracy have changed significantly?? As mentioned below, NTP is not meant to be super accurate, it's meant to get within 1s (which is probably where that underinformed quote came from). If you need sub 1ms accuracy then you'd want to use PTP. I really can't see any value in studying the accuracy of something that in very wide deployment does exactly what it was intended to do.
Comment: Actually, Chris, the two pieces of work quoted make it clear that the accuracy of NTP servers on the internet (not the protocol itself, which was always excellent) **has** improved between 1999 and now.  I suspect this is partly because the internet's better - latencies are somewhat lower and *much* less variable than once they were - and partly because the quality of S1 servers has improved (the 1999 paper says that the single most common clock source for S1 servers is the OS clock!).  I'm glad the OP asked this question, I think it's worthwhile.
Comment: Fair enough. The paper is an 14 years old overall survey on NTP network. It has further links, but all of them are, of course, even older. I've tried Google Scholar and CiteSeer, but most of the links are the same Mills and Millnar works from the nineties. I'm still browsing, but I am a bit far from the topic, and this might take a lot of time, so I choosed to ask the community for help.
Comment: Thanks for updating the question, I've recanted my downvote.  That said, you may feel it's annoying to be sent back whence you came, **but if you don't tell us where you've been when you ask the question, how can we know?**  I also note that the very text you post above includes a pointer to an academic paper studying the accuracy of NTP servers.  Did you read that, and if so, can you indicate why that wasn't enough?
Comment: See my updated answer below.  That was linked from my second page of google answers, but hey, glad to help.  And it *is* an interesting question.
Answer: No-one can guarantee how well NTP will work on your network, because no-one knows how well connected your network is to the internet, and to the clock servers thereon.  However, according to the clock discipline algorithm page on ntp.org

If left running continuously, an NTP client on a fast LAN in a home or
  office environment can maintain synchronization nominally within one
  millisecond. When the ambient temperature variations are less than a
  degree Celsius, the clock oscillator frequency is disciplined to
  within one part per million (PPM), even when the clock oscillator
  native frequency offset is 100 PPM or more.

Note that large-but-stable latency between your LAN and the internet's clock servers doesn't have as bad an effect on accuracy as highly-variable latency.
You don't say where you got the estimates above ('50 microseconds to ... "below one second"'), so I can't comment on them, but in my experience 50us is unlikely unless you have a directly-attached clock source, and 1s is unlikely unless you have a piece of wet string connecting you to the internet and you're using upstream servers in Antarctica.
Edit: the text you now quote in your question gives a pointer to a paper which, in 1999, did indeed establish that 99% of ntp servers are synch'ed to within one second.  Fortunately, there is more recent work; in this paper some authors from the Federal University of Parana, Brazil,
 repeated the experiment in 2005, and found (if I understand their Fig. 1 correctly) that north of 99% - more like 99.5% - of servers now have offsets less than 100ms, and that 90% have offsets less than 10ms.   This fits in pretty well with my experiences (see above).
Edit 2: one last wrinkle: all these studies don't investigate how accurate local clock is, but instead how far it differs from the upstream reference clock.  These are patently not the same thing.  But the first is unknowable; to know how wrong your clock is, you have to know exactly what time it is, and if you knew that, why would you have set your clock wrong in the first place?  Just be aware that what these studies are measuring is not the difference between local clock and absolute time, but between local clock and reference clock.
Comment: +1 I ran a pool server as well, >20ms drift monitored clear across the country was odd.
Answer: What problem are you trying to solve?
The solution I've encountered for environments requiring more precision than NTP is the Precision Time Protocol (PTP). I've had it in scientific computing and financial computing applications. There are tradeoffs, though.
Also see: ptp time synchronization on centos6/rhel
Comment: "What problem are you trying to solve?" My favorite question - I ask it all the time.
Comment: @mfinni, When you need to rank which of your clients submit first (e.g. [HFT](http://en.wikipedia.org/wiki/High-frequency_trading)), it helps to be accurate with your time.
Answer: A few other things worth mentioning:

You'll be lucky to get < 100ms of clock jitter on a virtual machine, so all the below is for a physical host
Sub 100ms jitter is nearly immeasurable for almost every task, and easily achievable over the Internet
Sub 30ms jitter may be needed for some general serving environments (I needed it for log correlation at a previous job), and is easily achieved using NTP servers on the same continent where the connection is not via "consumer" links (eg, not satellite, ADSL, DOCSIS, GPON, UMTS/LTE/HSPA/etc)
For absolute accuracy below this you should be installing hardware NTP servers from a quality vendor (eg, Symmetricom)
Sub 10ms (often sub 1ms) local agreement can easily be achieved by simply having a trio (you can do with less, but there's reasons to use three or five) within the same datacenter enough for pretty much every non-Science application
Answer: Vested interest on my part: I'm a Meinberg agent :-)
Yes NTP can achieve an end-to-end precision down to approx. 50 us (that's microseconds) of jitter, if you sync a linux "client" on bare metal running Chrony or ntpd, to a Linux-based NTP server disciplined by a GPS, local atomic clock or some such source.
On the machine that has a local GPS (with a PPS interconnect), you will probably see 0-2 microseconds of offset, between the ntpd instance running in the OS, and its PPS refclock driver's input.
Those residual 50 us "end to end over a LAN" are a result of several stages of buffering, variable IRQ latency, other traffic interfering on the LAN and on the computer busses involved and whatnot. 50 us means a LAN with very little traffic. Even just a switch can add some microseconds of jitter - and higher-end switches with complex features add more latency and jitter.
In other words, it can be pretty difficult to achieve those 50 microseconds in your real-world conditions on some practical LAN.
Similarly, those cca <2us of the PPS offset result from just the IRQ latency uncertainty and general bus latency jitter on well behaved PC hardware.
Note that NTP and its implementations ntpd and Chrony certainly measure NTP transaction round-trip time and subtract (add, actually) a half of that round trip, as a measure to filter away the systematic transport latency (one way). They also perform outlier rejection, quorum consensus, syspeer election and any NTP demon filters the responses it gets to its upstream queries. So as others have said, the milliseconds that you see in Ping and Traceroute do not directly offset your local clock. What matters is the variability of transaction round-trip, i.e. other traffic on the path to your upstream NTP server. Ntpq -p is your friend.
A basic GPS receiver for timing use, with a TCXO, can have maybe 100-200 ns of residual jitter+wander on its PPS output. Plenty good enough for NTP, as long as the GPS stays locked. (Holdover performance is not very good with TCXO's.) A quality timing GPS with an OCXO can be well within 100 ns, maybe more like 10-30 ns of residual error (offset from the global UTC).
Note that actual satellites flying overhead and beaming at you through an atmosphere may be a slightly tougher game for the receiver, than benchmarking in a lab with a GPS generator.
PTP is a hammer. You need HW support in the grandmaster, and in the slaves, and in any switches - but if you get all that, residual offsets down to low double digit of nanoseconds are possible. I have personally seen this in ptp4l running with an i210 NIC which has HW support (timestamping with a nanosecond resolution).
The i210 chip is a wonder. It has 4 general-purpose pins that can be used to input or output a PPS signal. The reference Intel addon NIC board with i210 (and its OEM versions from several big vendors) comes equipped with a pin header that gives you access to at least 2 of those GPIO pins (SDP's they're called by Intel). Apart from implementing a PTP grandmaster port, the PPS input can be leveraged for precise timestamping in packet capture. You need a precise source of PPS and a custom piece of software to run a servo loop, fine-tuning the i210's PHC to the ext.PPS. On my test rig, this resulted in single digit ns (per 1 s iteration) of residual offset. This is the precision that you then get in your capture timestamps, if you run a recent tcpdump or wireshark on a modern Linux kernel (all the software needs support for nanosecond-level resolution). Better yet: I went all the way and built a simple PLL synth to produce 25 MHz for the NIC clocks, locked to a precise upstream 10MHz reference. After that, the residual offset in the servo loop of my packet capture rig dropped to a clean 0 (a proof that my 10 MHz reference is phase-synchronous with the PPS from that same GPS box).
Note that PTP grandmasters may be specified to provide timestamps with an actual granularity per 8 ns (in a data type with 1 ns resolution). This makes sense - gigabit Ethernet tends to use a 125 MHz clock, used as a byte clock in the internals of the MAC, this clock is probably also used in the GMII, and it's also the symbol clock in metallic 1000Base-TX (four pairs in parallel, 2 bits per symbol per pair). So unless you're using 1000Base-FX (fiber optic) with SERDES and an extremist implementation of the HW timestamping unit in the PHY that works down to individual SERDES bits, those 8 ns are all you can ever realistically hope for on gigabit Ethernet. Some chip datasheets (with PTP support) even claim that the MII data path is not free of buffering and some jitter can come from there.
The PTP packets actually contain timestamps stored in a data type that allows for deep sub-nanosecond resolution. But the "sub-nanosecond fractional field" is nowadays typically unused. AFAIR only the White Rabbit project (related to CERN the Swiss research center) has implemented sub-ns precision so far.
PTP is also available in pure software, without HW acceleration. In that case, for a SW-based GM and a SW-based client, expect to get a similar residual jitter as with NTP - i.e. about 50 us on a dedicated but PTP-unaware LAN. I recall getting sub-microsecond precision from a HW grandmaster on a direct interconnect (no switch in-between) and a SW-only client (on a PTP unaware PC NIC). Compared to NTP, the PTP's servo converges much faster.
While doing some "homework", it recently occurred to me that transporting PPS or similar "discrete" timing signals over wide-area fiber optic routes may be susceptible to temperature-dependent propagation time "wander". And although I have no way to test this experimentally, some sources in the interwebs quote figures between 40 and 76 picoseconds per km and Kelvin. Note that while this kind of "thermal wander" is impossible to mitigate "in band" in simplex PPS transmission, PTP would post-compensate this inherently, based on its standard path delay measurements (which depends on full duplex transmission).
So much for an overview of what the "precisions" look like, at different timing technologies / interfaces. What level of precision is good enough for you, that depends on your application, on your actual needs.
---- Update in 2020: ----
A colleague has recently demonstrated to me, that Chrony can be made to run NTP on well behaved PC hardware (with no special treatment to its bus clock oscillators) with a residual end-to-end jitter of a microsecond or less. This can be observed under the following conditions:

systems idle
network idle
poll interval configured for 1 s (minpoll=maxpoll=0 , I believe)
Chrony can also make use of HW timestamping if available

There's a Gentoo wikipage claiming that the hardware timestamping is dependent on co-existence with ptp4l, which I doubt (not suggested by Chrony's own documentation) - though it does make sense to me, that the PHC in a NIC should get somehow disciplined for HW timestamping to make good sense... not sure if Chrony can benefit from a PHC with a free-running clock. Apart from ptp4l, I can hack an i210 NIC to have its 25MHz clock PLL'ed to a precise frequency reference and its PPS bolted to a precise PPS reference. I haven't yet tried running Chrony on top of that though :-)
Another interesting observation: standard PTP with G.8275.2 Telecom Profile (i.e. not White Rabbit) can achieve low double-digit nanoseconds of "wander" over a modern MPLS VPN that's not congested and gives priority to PTP traffic. That, with the MPLS switches unaware of PTP (no on-path support) and over ~1000 km of distance... Measured as MTIE between PPS signals = the ultimate net result, and the oscillator in the slave was a high-end double-oven OCXO. Yes this practically means ideal conditions, and the real world tends to be a cruel place. Those figures are not something you should take for granted. Just demonstrating the potential. Also note that the immediate protocol jitter reported by the PTP slave at runtime is much worse than the net deviation measured at the oscillator's 1PPS output. And, over those distances / hop counts, you will get a hefty constant offset (path asymmetry) that needs to get calibrated / subtracted for the extracted PPS signal to be any use. And the asymmetry will change upon topology changes (path backup routes kicking into action)...


How to properly use Jinja2 count/length without errors?

Question: I've got this in my template:

    Users ({{ users|length }})

And I've also got a loop showing rows of users:
    {% for user in users %}

            {{ user.email }}
            etc...

    {% endfor %}

I can't see what I'm doing wrong. The users table works great. But when I add the h2 with the length filter, I get this error:
Traceback (most recent call last):
  File "/Users/sean/Projects/appcash.me/_git/www/bottle.py", line 856, in _handle
    return route.call(**args)
  File "/Users/sean/Projects/appcash.me/_git/www/bottle.py", line 1721, in wrapper
    rv = callback(*a, **ka)
  File "/Users/sean/Projects/appcash.me/_git/www/views/admin.py", line 27, in custom_admin_page
    return template('admin/users.html', users=users)
  File "/Users/sean/Projects/appcash.me/_git/www/bottle.py", line 3487, in template
    return TEMPLATES[tplid].render(kwargs)
  File "/Users/sean/Projects/appcash.me/_git/www/datafly/core.py", line 184, in render
    return self.tpl.render(**_defaults)
  File "/Users/sean/Projects/appcash.me/_git/venv/lib/python2.7/site-packages/jinja2/environment.py", line 969, in render
    return self.environment.handle_exception(exc_info, True)
  File "/Users/sean/Projects/appcash.me/_git/venv/lib/python2.7/site-packages/jinja2/environment.py", line 742, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "<template>", line 3, in top-level template code
  File "<template>", line 57, in top-level template code
  File "<template>", line 8, in block "content"
TypeError: object of type 'Cursor' has no len()

Comment: Could you clarify how you 'add the h2 with the length filter'?
Answer: You can try this:
{{ users.count() }}

Answer: Your users variable seems to be of type Cursor (which has no length).
Perhaps you meant to do rows = users.fetchall() in your python (not template) code?  Then len(rows) will work, as will rows|length in your template.


Pass data Model element to CellTemplate KoGrid

Question: I'm using KoGrid in order to make my custom Ajax grid.I don't know how to pass model element to some Javascrit method for generating a custom Template.
I tried like this and doesn't work:
PluginGrid.AjaxUrl("MyControler/GetGrid").Columns(
       [
           { field: "UserName", displayName: "Model", width: "*", cellClass: "text-center", headerClass: "grid_width_270", cellTemplate: PluginHelpers.HtmlUserInformation($parent.entity, true) },
           { field: "StatusId", displayName: "Status", width: "*", cellClass: "text-center", headerClass: "text-center" }
       ]).Show("grid");
    });
This is actually a wrapper over KoGrid.I want to pass the data model somehow, to my Js method :
 PluginHelpers.HtmlUserInformation($parent.entity, true) }

When I do like this I received some undefined error of $parent variable.
Please advice,
Comment: `$parent` is defined for use in the HTML `data-bind`, not in the JS code. Can you show the relevant HTML?
Comment: Actually I found it:) At the end I created a new html template and put data-bind on html with Js call...
Answer: Finally I found a solution for this:
<template id="XXX">

</template>
and then
PluginGrid.AjaxUrl("Controller/GetGrid").Columns(
       [
           { field: "UserName", displayName: "Model", width: "*", cellClass: "text-center", headerClass: "grid_width_270", cellTemplate: $("#XXX").html() },
           { field: "StatusId", displayName: "Status", width: "*", cellClass: "text-center", headerClass: "text-center" }
       ]).Show("grid");
This is the best solution I could find....


Como passar a PDO para outros objetos em aplicação MVC OOP

Question: Estou desenvolvendo um pequeno framework para fins de aprendizagem, e uma das formas que encontrei de passar o objeto PDO para ser usado nos controllers/models foi usando a seguinte abordagem:

O método construtor do Controller pai recebe um objeto PDO, e este é
  herdado por todos os "Controllers filhos", que também herdam o
  método "loadModel", que retorna um objeto já com o PDO que foi passado como argumento no Controller pai.

.
DÚVIDA: Esta é uma boa abordagem? senão, por que? quais as vantagens e desvantages? e qual seria uma boa alternativa?
COMPLEMENTO: fiz algumas pesquisas e parece que o pattern apropriado para isso seria o Factory, mas não sei como seria sua implementação no meu código de modo que fique disponível para todos os controllers, mesmo os que não utilizem conexão com o banco de dados.
Se possível, exemplificar baseado no meu código
connection.php
<?php

$options = array(
    PDO::ATTR_EMULATE_PREPARES => false,
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::MYSQL_ATTR_FOUND_ROWS => true
    );

$connection = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset='. DB_CHARSET, DB_USER, DB_PASS, $options);

return $connection;

index.php

// possui algumas validações e tratamento de URLs de rotas (controller -
  action) e define o controller na variável $controller, e este recebe,
  através do construtor, o objeto PDO para ser usado dentro do método.

$obj = new $controller($connection);

controller.php (Controller pai)
class Controller {

private $connection;

function __construct ($connection) {
    $this->connection = $connection;
}

public function loadModel ($model) {
    return new $model($this->connection);
}

UserController.php (controller de exemplo)
class UserController extends Controller {

    function registration () {

            $useCRUD = $this->loadModel('userCRUD');

            $info = array('name' => 'Joao', 'age' => 25);

            $userCRUD->create($info);
        }

}

userCRUD.php
Recebe pelo construtor o objeto PDO e faz as interações CRUD com o banco de dados.
Comment: Por que você não usa o padrão Singleton? Ele garante apenas uma instância de uma classe, que, no caso seria a sua conexão com o banco. Assim não precisaria de toda essa estrutura.
Comment: Mas o singleton não é um "anti-padrão"?
Answer: Criando os controllers
Factorys podem ser utilizadas para resolver o problema, para isso elas serão passadas para uma classe que irá executar os controllers verificando se existe alguma factory para sua criação.
A implementação da factory ficaria mais ou menos assim:
class UserControllerFactory
{
    // OBS: O método __invoke faz uma classe poder ser executada como uma função do PHP.
    public function __invoke()
    {
         $userCrud = new UserCrud(PDOFactory::create());
         return new UserController($userCrud);
    }
}

Já a classe que irá executar seus controllers seria assim:
class ControllerInitializer
{

    private $factorys;

    public function __construct(
        array $factorys
    ){

        $this->factorys = $factorys;

    }

    public function init($controller, $action)
    {

        if(isset($this->factorys[$controller])){
             $factory    = $this->factorys[$controller];
             $controller = $factory();
             $controller->$action();
        }else{
            // Caso o controller não seja encontrado é um erro 404.
        }

    }

}

Comment: Acho que agora deu uma clareada, só não entendi muito bem o uso do __invoke(), e além da UserControllerFactory eu teria outra UserController ou poderia já usa-la de forma normal? com os métodos registration etc, e dentro desses métodos teria que abrir uma PDOFactory também?
Comment: e aproveitando o comentário acima do @João Pedro, uma solução poderia ser passar o PDO usando singleton? diretamente na chamada do model, por exemplo: `$userModel = new userModel(PDOFactory::getInstance());`


Formal proof for $A \cup (B-A) = A\cup B$

Question: I am just confused by the whole concept if someone can explain it to me or provide a different example so I can understand this would be much appreciated.
I want to prove that $$A \cup (B-A) = A\cup B$$
Comment: Welcome to MSE.  Please use [MathJax](https://www.onemathematicalcat.org/MathJaxDocumentation/TeXSyntax.htm) to format your posts.  To begin with, surround math expressions (including numbers) with `$` signs and use `_` for subscripts.  `$x_1$` comes out as $x_1$.
Comment: The answer below should be enough. Notice also that $(A-B)\cup (B-A)\cup (A\cap B)=A\cup B$ try to prove it.
Answer: Hint:
Usually, showing that two sets are equal (say $C=D$), can be undertaken in two steps:

Show that $C\subseteq D$ (that is, that every element $c\in C$ satisfies $c\in D$)
Show that $D\subseteq C$ (that is, that every element $d\in D$ satisfies $d\in C$.)

This is sufficient to show that the two sets are equal.
So, for your case:
Let $x\in A\cup (B\setminus A)$.  How can you show that $x\in A\cup B$? Start by noting that $x\in A\cup (B\setminus A)$ implies that either $x\in A$ or $x\in B\setminus A$. Can you proceed from there?
If you can do that, then you need to do the reverse: assume you have some $y\in A\cup B$, and prove that $y\in A\cup(B\setminus A)$.
Comment: thanks make sense now.


Force stacked tabs

Question: Is there any way to force stacked tabs? I want tabs separate of action bar (in a second row), even when landscape mode.
I am trying to force it but I can´t. For example, Twitter app in Android, when change to lanscape mode, continue showing two rows (tabs in a separate rows, which are known as stacked tabs).
Thanks!
Answer: Not only can you not force stacked tabs, you can't even force tabs -- Android can and will replace them with a drop-down list for navigation in some screen sizes and orientations.
Your only solution is to move away from action bar tabs, such as by using ViewPager and PagerTabStrip.
Answer: I had luck using the following reflection 'hack':
private void forceStackedTabs() {
    ActionBar ab = getSupportActionBar();
    if ( ab instanceof ActionBarImpl ) {
        // Pre-ICS
        disableEmbeddedTabs( ab );
    } else if ( ab instanceof ActionBarWrapper ) {
        // ICS
        try {
            Field abField = ab.getClass().getDeclaredField( "mActionBar" );
            abField.setAccessible( true );
            disableEmbeddedTabs( abField.get( ab ) );
        } catch (NoSuchFieldException e) {
            Log.e( TAG, "Error disabling actionbar embedded", e );
        } catch (IllegalArgumentException e) {
            Log.e( TAG, "Error disabling actionbar embedded", e );
        } catch (IllegalAccessException e) {
            Log.e( TAG, "Error disabling actionbar embedded", e );
        }
    }
}
private void disableEmbeddedTabs(Object ab) {
    try {
        Method setHasEmbeddedTabsMethod = ab.getClass().getDeclaredMethod("setHasEmbeddedTabs", boolean.class);
        setHasEmbeddedTabsMethod.setAccessible(true);
        setHasEmbeddedTabsMethod.invoke(ab, false);
    } catch (Exception e) {
        Log.e( TAG, "Error disabling actionbar embedded", e );
    }
}

Please note that I didn't think of this myself, but simply rewrote the code given in this answer: replicate ActionBar Tab(s) with custom view
Comment: This doesn't appear to work while compiling for Kitkat and Lollipop.  I can't find the ActionBarImpl class.
Answer: I used this to force ActionBar stacked or unstacked tabs from Gingerbread to KitKat.
Modded From: http://www.blogc.at/2014/01/23/android-tabs-appear-above-or-below-actionbar/

setHasEmbeddedTabs(mActionbar,false);

    public static void setHasEmbeddedTabs(Object inActionBar, final boolean inHasEmbeddedTabs)
    {
        // get the ActionBar class
        Class<?> actionBarClass = inActionBar.getClass();

        // if it is a Jelly Bean implementation (ActionBarImplJB), get the super class (ActionBarImplICS)
        if ("android.support.v7.app.ActionBarImplJB".equals(actionBarClass.getName()))
        {
            actionBarClass = actionBarClass.getSuperclass();
        }

        // if Android 4.3 >
        if ("android.support.v7.app.ActionBarImplJBMR2".equals(actionBarClass.getName())){
            actionBarClass = actionBarClass.getSuperclass().getSuperclass();
        }

        try
        {
            // try to get the mActionBar field, because the current ActionBar is probably just a wrapper Class
            // if this fails, no worries, this will be an instance of the native ActionBar class or from the ActionBarImplBase class
            final Field actionBarField = actionBarClass.getDeclaredField("mActionBar");
            actionBarField.setAccessible(true);
            inActionBar = actionBarField.get(inActionBar);
            actionBarClass = inActionBar.getClass();
        }
        catch (IllegalAccessException e) {}
        catch (IllegalArgumentException e) {}
        catch (NoSuchFieldException e) {}

        try
        {
            // now call the method setHasEmbeddedTabs, this will put the tabs inside the ActionBar
            // if this fails, you're on you own
            final Method method = actionBarClass.getDeclaredMethod("setHasEmbeddedTabs", new Class[] { Boolean.TYPE });
            method.setAccessible(true);
            method.invoke(inActionBar, new Object[]{ inHasEmbeddedTabs });
        }
        catch (NoSuchMethodException e)        {}
        catch (InvocationTargetException e) {}
        catch (IllegalAccessException e) {}
        catch (IllegalArgumentException e) {}
    }

Comment: This works, though the tab indicator is clipped on the leftmost and rightmost tabs.
Comment: It works good on Gingerbread, but on KitKat (Galaxy Tab Pro) and Lollipop (Nexus5) in portrait mode, tabs is placed a bit lower then where they should be (not centered), so the (blue) selection line is not visible.
Answer: If you need to support phones and tablets and don't want to use separate implementation you can put this in your activity:
@Override
public Resources getResources() {
    if (mResourcesImpl == null) {
        mResourcesImpl = new ResourcesImpl(super.getResources());
    }
    return mResourcesImpl;
}

class ResourcesImpl extends Resources {
    private Resources mResources;
    private Set<Integer> mActionBarEmbedTabsIds = new HashSet<Integer>();

    ResourcesImpl(Resources resources) {
        super(resources.getAssets(), resources.getDisplayMetrics(), resources.getConfiguration());

        mResources = resources;

        String packageName = getPackageName();
        mActionBarEmbedTabsIds.add(mResources.getIdentifier("abc_action_bar_embed_tabs", "bool", packageName));
        mActionBarEmbedTabsIds.add(mResources.getIdentifier("abc_action_bar_embed_tabs_pre_jb", "bool", packageName));
        mActionBarEmbedTabsIds.add(mResources.getIdentifier("action_bar_embed_tabs", "bool", "android"));
        mActionBarEmbedTabsIds.add(mResources.getIdentifier("action_bar_embed_tabs_pre_jb", "bool", "android"));
        mActionBarEmbedTabsIds.remove(0);
    }

    @Override
    public boolean getBoolean(int id) throws NotFoundException {
        if (mActionBarEmbedTabsIds.contains(id)) {
            return areActionBarTabsEmbed(); // stacked ot embed goes here
        }
        return super.getBoolean(id);
    }
}

Force stacked tabs


How to disable Toolbar on certain pages / theme?

Question: Before deprecation of hook_page_build/hook_page_build_alter() we used good old method:
$page['page_top']['toolbar']['#access'] = FALSE;

(Source)
It disabled Toolbar for specific route in specific theme.
Now I checked hook_page_top(), hook_toolbar() and hook_preprocess_page(). Nothing helped, so I temporarily removed {{ page_top }} region from my html.html.twig but it doesn't look as the right approach.
Comment: There is still hook_module_implements_alter :P
Comment: May you show the code you tried, so far? I don't understand in which way `hook_page_top()` could not help you. See [`toolbar_page_top()`](https://api.drupal.org/api/drupal/core!modules!toolbar!toolbar.module/function/toolbar_page_top/8) and [`block_page_top()`](https://api.drupal.org/api/drupal/core!modules!block!block.module/function/block_page_top/8).
Comment: @kiamlaluno `hook_page_top()` is for adding new content to top, not for altering existing one. So, I have to control the weight of my module which again looks odd for such simple task.
Comment: Since the array is passed by reference, you can alter existing array keys it contains too. Since there is not a `hook_page_top_alter()`, nothing forbids you from using that hook.
Answer: page_top and page_bottom are still available, but on html.html.twig. template_preprocess_html() initializes those variables with the following code.
  $variables['page_top'] = NULL;
  if (isset($variables['html']['page_top'])) {
    $variables['page_top'] = $variables['html']['page_top'];
    unset($variables['html']['page_top']);
  }
  $variables['page_bottom'] = NULL;
  if (isset($variables['html']['page_bottom'])) {
    $variables['page_bottom'] = $variables['html']['page_bottom'];
    unset($variables['html']['page_bottom']);
  }

Since toolbar_page_top() uses the following code, I take you can use hook_preprocess_html() to avoid the toolbar appears.
  $page_top['toolbar'] = array(
    '#type' => 'toolbar',
    '#access' => \Drupal::currentUser()->hasPermission('access toolbar'),
    '#cache' => [
      'keys' => ['toolbar'],
      'contexts' => ['user.permissions'],
    ],
  );

Bear in mind that a note on Added hook_page_attachments(_alter)() and removed hook_page_build/alter() says:

You no longer can change $page['content'] (or, generally speaking, $page[$region_name]) into something completely different.
Answer: The alternative is implementing hook_module_implements_alter() to remove the implementation of hook_page_top() done from the Toolbar module, implement hook_page_top() in your module, and call toolbar_page_top() when necessary.
function mymodule_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'page_top') {
    $group = $implementations['mymodule'];
    unset($implementations['mymodule']);
    unset($implementations['toolbar']);
    $implementations['mymodule'] = $group;
  }
}

function mymodule_page_top(array &$page_top) {
  $theme = \Drupal::theme()->getActiveTheme()->getName();
  if ($theme != "theme where you don't want the toolbar" && \Drupal::moduleHandler()->moduleExists('toolbar')) {
    toolbar_page_top($page_top);
  }
}

In the example code I am showing, the toolbar is added only when the current theme is not a specific one.
Comment: although this solution will remove the toolbar content, this is not going to remove classes added by the Toolbar to `body`.
Answer: The complexity with Toolbar removal is that not only markup in page_top must be removed, but also classes added to the .
The code below allows to add $settings['hide_admin_toolbar'] = TRUE; to your settings.local.php and remove both Toolbar markup and classes.
/**
 * Implements template_preprocess_html().
 */
function MYTHEME_preprocess_html(&$variables) {
  // Hide admin toolbar.
  if (Settings::get('hide_admin_toolbar')) {
    if (!empty($variables['attributes']['class'])) {
      unset($variables['page_top']['toolbar']);
      $variables['attributes']['class'] = array_filter($variables['attributes']['class'], function ($value) {
        return strpos($value, 'toolbar-') !== 0;
      });
    }
  }
}


What is the derivative of $\tan^{-1}(x)$?

Question: I have seen the derivative of $\tan^{-1}(x)$ set equal to both $\sec^{-2}(x)$ and $\frac{1}{1+x^2}$.
I can't find corroborating sources for either claim, so I'm asking here if either of these are true.
Comment: Let $u= arctan x$ then take tan for both sides $\tan u = x$ use implicit differential derivative $ u' sec^2 u = 1$ hence
Answer: This stems from the fact that many sources use the conflicting definitions that
$$\tan^{-1}{(x)}=\arctan{(x)}$$
But one may also interpret this as
$$\tan^{-1}{(x)}=\frac1{\tan{(x)}}$$
Both of these functions have different derivatives.
Answer: It boils down to: what do you mean by $\tan^{-1}(x)$. I think most people think of it as the inverse tangent function, i.e. $\arctan(x)$, but some think of it as $\frac{1}{\tan(x)}$. The derivative of the former is $\frac{1}{1+x^2}$, and the derivative of $\tan(x)$ is $\sec^2(x)$.
Comment: The derivative of $\frac{1}{\tan{(x)}}=\cot{(x)}$ is $-\csc^2{(x)}$
Comment: Yeah I meant $\tan(x)$, so I updated it.
Comment: Thank you. This answer was easy to understand.
Answer: If $y=\arctan x$ then $x=\tan y$ so $\frac{dx}{dy}=\sec^2y=1+x^2$. Therefore, $\frac{dy}{dx}$ is $\sec^{-2}y$ (note it's $y$, not $x$; also, we'd usually write $\cos^2 y$) or $\frac{1}{1+x^2}$.
On the other hand, if $y=(\tan x)^{-1}$ then $\frac{dy}{dx}=-\tan^{-2}x\sec^2 x=-\csc^2 x=-(1+y^2)$.
Answer: If by $\tan^{-1}$ you mean the inverse function of the restriction of $\tan$ to the interval $(-\pi/2,\pi/2)$, i.e. the function $\arctan$, you can apply the general formula for the derivative of an inverse function:
$$(\arctan)'(x)=\frac 1{(\tan)'(\arctan x)}==\frac 1{1+\tan^2(\arctan x)}=\frac 1{1+x^2}.$$
Answer: We have $\tan(\arctan(x)) = x$, and we can differentiate implicitly:
$$\tan'(\arctan(x))\arctan'(x) = 1$$
Rearranging:
$$\arctan'(x) = 1/\sec^2(\arctan(x))$$
See that $\sec(\arctan(x)) = \sqrt{1 + x^2}$ from the right triangle:
$\qquad \qquad \qquad$
So $\displaystyle \frac{\text{d}}{\text{d}x} \arctan(x) = \frac{1}{1 + x^2}$.

Note: This approach can be applied to find the derivative of any inverse function, assuming you know the derivative of the function itself.
 To wit:
Suppose $g(x) = f^{-1}(x)$.  Then:
\begin{align}
&f(g(x)) = x \\[1em]
&f'(g(x)) \cdot g'(x) = 1 \qquad \quad \text{(Differentiating implicitly)} \\[1em]
&g'(x) = \frac{1}{f'(g(x))}
\end{align}
Answer: The derivative of the inverse tangent function ($f(x)=\tan^{-1}{x}$), also commonly known as the arctangent function ($f(x)=\arctan{x}$), is: $$\frac{1}{1+x^2}.$$
Period. It's definitely not $\sec^{-2}{x}$. That's just pure nonsense. In fact, if you are thinking of $\tan^{-1}{x}$ as the reciprocal of the tangent function, then the derivative of $\frac{1}{\tan{x}}$ would actually be $-\csc^2{x}$:
$$
\frac{d}{dx}\left(\frac{1}{\tan{x}}\right)=\frac{d}{dx}\bigg[(\tan{x})^{-1}\bigg]=-1\cdot\left(\tan{x}\right)^{-1-1}\frac{d}{dx}\left(\tan{x}\right)=\\
-\frac{1}{\tan^2{x}}\cdot\sec^2{x}=-\frac{1}{\frac{\sin^2{x}}{\cos^2{x}}}\cdot\frac{1}{\cos^2{x}}=-\frac{1}{\sin^2{x}}=-\csc^2{x}.
$$


Can you run a DNS on the same machine as your webserver? If so, how do you set it up?

Question: Two-fold question from someone who has very little server experience.
I've set up a simple IIS8 (Windows 2012) server with a website on it.  That works fine.
I can access it outside of my house (yes, this is a SMALL server running in my house), but only if I type in my static IP address.  I'd like to get this running using a DNS address so I can use a domain name I've purchased, but I don't know how to do this.
Would I set up a DNS server on my current machine?  Would I need a different (separate) machine?  If I can put it on my current machine, are there any good instruction websites that detail how it's done for someone with a novice knowledge?  I'm a C# programmer, I don't know much about the server side.
Comment: Yes, but don't do it. DNS services are one of those type of things that you want to avoid running yourself unless 1) you have the technical ability to do so and 2) have a good reason to *not* have someone else run it.
Comment: This is good info.  I'm going to look into that CloudFlare suggestion.
Answer: Yes you can run DNS on you machine, but most registrars will require at least two IPs for setting up you own nameservers, and it would be wiser to use multiple external DNS servers for redundancy and security issues.
You can purchase a services like DynDNS where you can setup your domain to use their nameservers, and set you records to point to your home IP.
You can also take free CloudFlare account, and setup their nameservers, which I think would be best in your case.
Signup for a free CloudFlare account, and then you can just follow their guide to setup their nameservers on your domain, and then you can add records in their dashboard, and point the domain to your IP.
https://support.cloudflare.com/hc/en-us/articles/205195708-Step-3-Change-your-domain-name-servers-to-CloudFlare
Comment: Cloudflare was the way to go, and then I had to set up some forwarding within IIS and I was up and running.


Como bloqueio o acesso a criação de parametros numa classe?

Question: import math

class Circulo():

    def __init__(self):
        super()
        self.__raio = None

    def get_perimetro(self):
        return 2 * math.pi * self.raio

    def get_area(self):
        return math.pi * self.raio ** 2

    @property
    def raio(self):
        return self.__raio

    @raio.setter
    def raio(self, x):
        self.__raio = x

Tenho a classe acima e desejo encapsular o acesso, de forma que não seja possível atributos dinâmicos na instancia.
ex:
c = Circulo()
c.raio = 2 # ok
c.lado = 2 # AttributeError

Tentei bloquear os atributos dinâmicos com getattr e setattr, mas não tive sucesso.
def __getattr__(self, item):
    if item in self.__dict__:
        return self.__dict__[item]
    else:
        raise AttributeError('Paramentro ou atributo "%s" inexistente.' % item)

def __setattr__(self, key, value):
    if key in self.__dict__:
        self.__dict__[key] = value
    else:
        raise AttributeError('Paramentro ou atributo "%s" inexistente.' % key)

Answer: Tente isto:
import math

class Circulo():
    def __init__(self):
        super()
        self.__raio = None

    def get_perimetro(self):
        return 2 * math.pi * self.raio

    def get_area(self):
        return math.pi * self.raio ** 2

    @property
    def raio(self):
        return self.__raio

    @raio.setter
    def raio(self, x):
        self.__raio = x

    def __setattr__(self, key, value):
        if not hasattr(self, key):
            raise TypeError("Não pode criar atributos para esta classe")
        object.__setattr__(self, key, value)

c = Circulo()
c.raio = 2 # ok
c.lado = 2 # AttributeError

Veja "funcionando" no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: Infelizmente ainda não cai na exeção:

AttributeError: Paramentro ou atributo "_Circulo__raio" inexistente.
Comment: @britodfbr pra mim funciona: http://ideone.com/cbZdJh
Comment: Sim, mas o erro foi acusado em . E deverá ser acusado somente em .

Fiz um fork de teu código em http://ideone.com/BClC2X, acrescentei somente o key para apresentar onde o erro ocorre.
Comment: Talvez utilizar `__slots__` seja mais adequado: https://pt.stackoverflow.com/a/221432/5878
Comment: @AndersonCarlosWoss bem possível.
Answer: O que você deseja fazer é claramente função de __slots__, vide documentação:

Without a __dict__ variable, instances cannot be assigned new variables not listed in the __slots__ definition. Attempts to assign to an unlisted variable name raises AttributeError.

Ou seja, se você deseja que apenas o atributo __raio exista, basta colocar na classe:
__slots__ = ("__raio")

Veja o exemplo:
import math

class Circulo():

    __slots__ = ("__raio")

    def __init__(self):
        super()
        self.__raio = None

    def get_perimetro(self):
        return 2 * math.pi * self.raio

    def get_area(self):
        return math.pi * self.raio ** 2

    @property
    def raio(self):
        return self.__raio

    @raio.setter
    def raio(self, x):
        self.__raio = x

c = Circulo()
c.raio = 2 # ok
c.lado = 2 # AttributeError

Veja funcionando no Ideone.

O resultado será:
Traceback (most recent call last):
  File "./prog.py", line 27, in <module>
AttributeError: 'Circulo' object has no attribute 'lado'

Lembrando que como __raio pertence a lista definida em __slots__, a exceção não é disparada no inicializador da classe ao definir o atributo de instância self.__raio = None. Não definindo a lista corretamente, uma exceção pode ser disparada dentro da própria classe.
Comment: Relacionada a resposta: [Qual é a finalidade de `__slots__`?](https://pt.stackoverflow.com/q/176757/5878)
Comment: Valeu @Anderson Carlos Woss, Muito obrigado!!!

Vou estudar este __slots__ agora!! ;D
Comment: Anderson Carlos Woss, + uma duvida.
O @property se torna desnecessário?
Comment: Aí é você que tem que dizer. Como seu *get/set* só retornam e atribuem o valor, sem nenhuma regra de negócio, sim, ele é desnecessário. Você pode utilizar apenas o atributo como "público".
Comment: Valeu Anderson. Muito obrigado.
Ampliei meus conhecimentos com tua ajuda.
Answer: O final com ajuda de Anderson Woss, ficou assim:
import math

class FormaGeometrica:
    __slots__ = ()
    def get_area(self):
        raise NotImplementedError(NotImplemented)
    def get_perimetro(self):
        raise NotImplementedError(NotImplemented)

class Circulo(FormaGeometrica):
    __slots__ = ("raio")

    def __init__(self):
        super()
        self.raio = None

    def get_perimetro(self):
        return 2 * math.pi * self.raio

    def get_area(self):
        return math.pi * self.raio ** 2

if __name__ == '__main__':
    c = Circulo()
    c.raio = 2  # ok
    c.get_area()
    c.get_perimetro()
    c.lado = 2  # AttributeError

Anteriormente, para conseguir implementar a classe restringindo a criação dinamica de atributos e metodos, tive que reescrever o setattr, getattr e controlar o dict da classe.
A solução final ficou como o código abaixo. Se alguém tive sugestões para melhoria, serão bem vindas.
from incolumepy.geometria.figura_geometrica import FiguraGeometrica
import math

class Circulo(FiguraGeometrica):
    '''
    >>> c = Circulo()
    >>> c.raio = 1
    >>> c.raio
    1
    >>> c.lado = 2
    Paramentro ou atributo "lado" inexistente.
    '''
    __dict__ = {'raio': None}

    def get_perimetro(self):
        return 2 * math.pi * self.raio

    def get_area(self):
        return math.pi * self.raio ** 2

    def __getattr__(self, item):
        if item not in self.__dict__:
            raise AttributeError('Paramentro ou atributo "%s" inexistente.' % item)
        return self.__dict__[item]

    def __setattr__(self, key, value):
        if key not in self.__dict__:
            raise AttributeError('Paramentro ou atributo "{}" inexistente.'.format(key))
        self.__dict__[key] = value

if __name__ == '__main__':
    import doctest
    doctest.testmod()

Comment: Neste caso você desistiu de utilizar a propriedade?
Comment: Foi o que havia conseguido fazer. Não conhecia o __slots__.


coldfusion store variables in table and output without using Evaluate

Question: I have come across a scenario that I don't know how to avoid using Evaluate.  I have stored in a database table session vars and when I output the query results, I want to show the value of the session var.
so here's the set up:
INSERT THE DATA...
<cfquery datasource="TEST" >
insert into testTable (labelVar) values ("session.test")  <- I don't want the value of the session var stored I just want to store the session var
</cfquery>

OUTPUT THE RESULTS...
<cfquery name="qExample" datasource="TEST" >
select labelVar from testTable
</cfquery>

<cfset session.test="Hi!">
<cfset TextValue = Evaluate("#qExample.LabelVar#")>
<cfoutput>#TextValue#</cfoutput> <-Outputs Hi!

Now this all works BUT how do I accomplish this without using Evaluate?
Comment: If you want to avoid using evaluate, write your query results to a .cfm file and then cfinclude that file.  Personally I think evaluate would be the lesser of two evils here.
Comment: `evaluate()` has gotten a bad rap over the years (deservedly so), but in the last few years, performance has vastly improved. The only other option is what Dan mentioned about writing to a .cfm and including it, but the performance there will be much worse than `evaluate()`. This is one of the few use cases I have seen where `evaluate()` really is the best option.
Comment: How many rows are you expecting from testTable?
Answer: You can use structGet() here, if the value in the DB purely is a scoped variable name:
<cfset TextValue = structGet(qExample.LabelVar)>

I did some research into this allegation that evaluate() is intrinsically bad. I think it's often avoidable, but it doesn't really seem to be much of a problem, these days: '"evalulate() is really slow". Is it now?'
It is, however, vitally important when considering using evaluate() to be mindful of Leigh's comment below:

One thing to keep in mind is how it is used. Evaluate is not picky
  about what it executes. If used on client supplied values, FORM, URL,
  it can pose some risks, so use it sparingly and wisely IMO.
Comment: One thing to keep in mind is how it is used. `Evaluate` is not picky about what it executes. If used on client supplied values, FORM, URL, it can pose some risks, so use it sparingly and wisely IMO.
Comment: Good thinking, @Leigh. I've added your comment as a post script to my answer, lest ppl don't read down the comments.
Comment: Perfect Adam!  Thank you so much for both the read and option.  structGet does work and the knowledge that eval won't drastically hurt performance is a relief.
Comment: Evaluate() real power comes when using it with DE():

You need to escape hashes inside DE() by adding an extra hash to each one, for this to work.
Answer: Adam Cameron's option is best, but here's just a few different ways to achieve your goal.
(I create a zession scope just as a quick test so you can test your options.
<cfset zession = StructNew()>
<cfset zession.test = "Hi there">
<cfset labelvar = "zession.test">

Option 1:
<cfoutput>#evaluate(labelvar)#</cfoutput>

Option 2:
<cfoutput>#zession[listGetAt(labelvar,2,".")]#</cfoutput>

J only bring up Option 2 to point out further options. Is your variable always going to be in the session scope? If so, you can save the key name rather than the whole variable name. So if labelvar was "test" then
<cfoutput>#zession[labelVar]#</cfoutput>

Years ago, Evaluate() was terrible, and I think the lingering stigma is good because it forces developers not to resort to lazy methods when they're avoidable. Above were some ways to avoid the function when it was slower.


how to build reactjs files for nginx using ansbile & then rsyncing those files to ansible inventory?

Question: I have a ReactJS app, from which I got to build asset files for webserver. For this approach I use Docker container.
Container In Use: node:12-alpine
App Data: ./app which will then be mounted to /app in container.
So I can build these js files by running a docker container directly like so
# docker container run -ti --name builder \
-v $PWD/app:/app -w /app node:12-alpine \
sh -c "apk update -qq && \
apk add git -qq && \
NODE_ENV=development npm install && \
mkdir dist && \
npm run build:staging"

Now I'm trying to automate all of this with ansible, so here are the tasks
- name: Run Container
  docker_container:
    name: "{{ container }}"
    image: "{{ image }}"
    volumes: "{{ lookup('env', 'PWD') }}/app:/app"
    working_dir: "/app"
    command: "{{ command }}"
    state: present
  delegate_to: localhost

- name: Update Frontend
  synchronize:
    src: "{{ lookup('env', 'PWD') }}/{{ component }}/dist/"
    dest: "/{{ parent }}/{{ component }}"
    archive: no
    compress: yes
    recursive: yes
    delete: yes

Here are some of variables used in command
image: "node:12-alpine"
container: "builder"
command: "docker container exec -ti {{ container }} sh -c builder.sh"

the container runs, but it seems it does not run the specified command,
the builder.sh carries same commands used to compile
# cat builder.sh
apk update -qq
apk add git -qq
NODE_ENV=development npm install
mkdir dist
npm run build:staging

Do I have to make builder.sh executeable or missing something else?
Also, I want synchronize module to execute after build process is finished in container. what's method to do that?
Comment: It seems like it'd be easier to use Node directly; you can ask Ansible to install it (using an `apt` or `brew` action) if you don't already have it.  If you really need to use a `docker_container:`, the `command:` is the single process the container runs, which should just be `./builder.sh`; it's not a `docker exec`.
Comment: @DavidMaze ok it didnt work either by `./builder.sh` or `sh -c builder.sh`
Answer: Use DockerFile with this parts.
# cat builder.sh
apk update -qq
apk add git -qq
NODE_ENV=development npm install
mkdir dist

- name: Run Container
  docker_container:
    name: "{{ container }}"
    image: "{{ image }}"
    volumes: "{{ lookup('env', 'PWD') }}/app:/app"
    working_dir: "/app"
    recreate: yes
    command: "npm run build:staging"
    state: started
  delegate_to: localhost

- name: Update Frontend
  synchronize:
    src: "{{ lookup('env', 'PWD') }}/{{ component }}/dist/"
    dest: "/{{ parent }}/{{ component }}"
    archive: no
    compress: yes
    recursive: yes
    delete: yes


Complex Numbers - Equation manipulation

Question: Please see link, I'm wondering how you end with RHS of equation on second line of image. Please can explain the step and algebra manipulation used
Thanks
Comment: How did they get to final answer, −iexp(−ma)/4a^3(1 + ma)
Comment: Notice that $a^2 + z^2 = (z - ia)(z + ia)$ which in in term cancels one power of $(z-ia)^2$ in the numerator. First simplify $(z-ia)^2/(a^2+z^2)^2$. The rest is computing the differential and then the limit.
Comment: Yep I had gone past that stage, however I'm still ending up with the wrong answer
Comment: Did you apply the quotient rule correctly?
Answer: You have the expression
$$\frac{(z-ia)^2e^{imz}}{(a^2+z^2)^2}$$
First we note that the roots of $a^2+z^2$ are $z = \pm ia$ so we have
$$\frac{(z-ia)^2}{(a^2+z^2)^2} = \frac{(z-ia)^2}{\left((z-ia)(z+ia)\right)^2}$$
$$= \frac{(z-ia)^2}{(z-ia)^2(z+ia)^2} = \frac{1}{(z+ia)^2}$$
Now what's left to do is to first compute
$$\frac{d}{dz}\left(\frac{e^{imz}}{(z+ia)^2} \right)$$
using the quotient rule $(u/v)'= (u'v - uv')/v^2 $ , we have
$$\frac{d}{dz}\left(\frac{e^{imz}}{(z+ia)^2} \right) = \frac{ime^{imz}\cdot(z+ia)^2 - e^{imz}\cdot 2(z+ia)}{(z+ia)^4} = e^{imz} \frac{im(z+ia)^2 - 2(z+ia)}{(z+ia)^4}$$
That's enough to set $z = ia$ now, so we have
$$e^{im(ia)} \frac{im(2ia)^2 -2(2ia)}{(2ia)^4} = e^{-ma} \frac{-im\cdot 4a^2- 4ia}{16a^4} = ie^{-ma} \frac{-ma-1}{4a^3} = -ie^{-ma}\frac{(1+ma)}{4a^3}$$
I guess you must have made a mistake during the simplifcation.
Answer: Perhaps they did directly
$$\lim_{z\to ai}\left[\frac{(z-ai)^2e^{imz}}{(z-ai)^2(z+ai)^2}\right]'=\lim_{z\to ai}\frac{ime^{imz}(z+ai)-2e^{imz}}{(z+ai)^3}=\frac{-me^{-ma}2a-2e^{-ma}}{-8a^3i}$$
$$=\frac{e^{-ma}(ma+1)}{4a^3i}=-\frac{ie^{-ma}}{4a^3}(ma+1)$$

Complex Numbers - Equation manipulation


Conditional aggregation query with a group by

Question: I have a system where users log in from different companies. I'm trying to run a query to see the number of active users vs total number of users for each company.
Users table:
userID, companyID, lastLogin
Desired Output:
companyID, totalCompanyUsers, numUsersWhoLoggedInWithinLastMonthFromCompany
Query attempt:
SELECT companyID, COUNT(userID) AS `numUsersWhoLoggedInWithinLastMonth`
FROM Users
WHERE IFNULL(TIMESTAMPDIFF(MONTH, lastLogin, NOW()),- 1) = 1
GROUP BY companyID;

I'm struggling to figure out how to have two aggregation functions, where one is conditional.
Comment: Not only column's name, but add some sample data and desired result.
Comment: Perfectly good question, an attempt was made and it's easy to visualise what is required based on the column names and the attempt that was made. Not all questions need sample data.
Answer: You're pretty close, you just need to put the conditions inside the aggregate function for the conditional aggregation you want to perform:
SELECT
companyID,
COUNT(userID) AS `totalCompanyUsers`,
SUM(CASE
  WHEN
    TIMESTAMPDIFF(MONTH, lastLogin, NOW()) < 1 THEN 1
  ELSE 0
END
) AS `numUsersWhoLoggedInWithinLastMonth`
FROM Users
GROUP BY companyID;

The results are still grouped by companyID, but the second aggregation function performs a sum of 1s and 0s depending on whether the user logged in within the last month or not.
Comment: scrap that I was being stupid, yours works perfectly, thanks
Comment: Thanks for quick reply, that unfortunately returns `0` for all `numUsersWhoLoggedInWithinLastMonth`
Comment: I'm not sure if this would effect it, but users who have never logged in, ie some not active users, have a `lastLogin` value of `Null`
Comment: I swapped your `<` for a `>`  and it is now working ! thanks!!


Turning a char sequence into a picture in a text field (smileys)?

Question: Say I have a text field on a website. How could I programmatically enable the user to write the letters " :) " and then turn these two chars into an actual smiley picture (.gif) in the editor?
I am kind of stuck, as I don't know how I would watch the text field for this, and also how to insert the picture at the right place?
Answer: You cannot insert a picture in a normal text field. You need something like https://www.tinymce.com/
That said, you could replace :) with a unicode smiley ☺ - here is a list:
http://www.utf8-chartable.de/unicode-utf8-table.pl?start=9728
then you can do

window.onload = function() {
  document.getElementById("inp").onkeyup = function() {
    var text = this.value;
    if (text) this.value = text.replace(/:\)/g, "☺");
  }
}
Try typing Hi there:): <input type="text" id="inp" value="" />


Laravel 8 "fortify" redirect not working after registration on production

Question: I have setup a role base authentication for admin and users to be redirected to a different route after registration and login which perfectly well on my local machine but when I deploy to production, it redirects to /home which I have not declared in my web.php
FortifyServiceProvider.php
$this->app->singleton(
  LoginResponseContract::class,
  LoginResponse::class
);
$this->app->singleton(
  TwoFactorLoginResponseContract::class,
  TwoFactorLoginResponse::class
);

loginResponse.php
public function toResponse($request)
{
  $role = \Auth::user()->role_id;

  if ($request->wantsJson()) {
     return response()->json(['two_factor' => false]);
  }

  $home = $role == 1 ? '/admin' : '/account';
  return redirect()->intended($home);
}

RouteServiceProvider.php
public const ACCOUNT = '/account';
public const ADMIN = '/admin';

CreateNewUser.php
$user = User::create([
   'name' => $input['name'],
   'username' => $input['username'],
   'email' => $input['email'],
   'password' => Hash::make($input['password']),
   'role_id' => 2,
   'referrer_id' => $referrer->id ?? null,
]);

$user->notify(new WelcomeEmail($user));
return $user;

Please any help would be appreciated, I have been stuck for the past two days
thanks
Answer: maybe the version of php of your local and production is different
so some php version does not work with this form of IF
use this way:
public function toResponse($request)
{
  $role = \Auth::user()->role_id;

  if ($request->wantsJson()) {
     return response()->json(['two_factor' => false]);
  }
  if($role == 1){
     $home = '/admin';
  }else{
     $home ='/account';
  }

  return redirect()->to($home);
}

Comment: yes PHP version is different. on my local machine its PHP8 and on the server it's PHP7.4. Although I made changes like you suggested and ran ```php artisan optimize``` but it still directs me to ```/home``` after registration
Comment: use return redirect::to($home);


Firefox scripting language: URL of active Tab and counting open Tabs

Question: Edit: I was able to go one step further :)
PSEUDO CODE (what I want)
if (CurrentTabURL == empty Tab) and (Tab.Count == 1)
{close Firefox}
else
{close Tab}

MY CODE (only the if statements don't work. Both actions are working)
if  (gBrowser.currentURI == "")
    and (tabbrowser.browsers.length == 1)
then
    goQuitApplication();
else
    gBrowser.removeTab(gBrowser.mCurrentTab);
end

This link helped me a lot.
Answer: gBrowser.currentURI is an nsIURI instance. If you want to compare the URL to a string you should look at gBrowser.currentURI.spec. The URL of an "empty tab" is about:blank by the way. Also, I guess that you want to use JavaScript? Corrected code:
if (gBrowser.currentURI.spec == "about:blank" && gBrowser.browsers.length == 1)
  goQuitApplication();
else
  gBrowser.removeTab(gBrowser.selectedTab);


Let $\Omega = \{ 1,2,3,4,5,6\}$. Determine the smallest $\sigma$ algebra

Question: Let $\Omega = \{ 1,2,3,4,5,6\}$. Determine the smallest $\sigma$- algebra that contains sets $A_{1} = \{1,3,5\},A_{2} = \{2,4,6\},A_{3} = \{1,3\},A_{4} = \{2,4\}$.
I was thinking of putting $A_{i}^{'} = \{i\}, i=1,...,6$ and now, $\sigma (A_{1},...,A_{4}) =\sigma (A_{1}^{'},...,A_{6}^{'})= P(\Omega)$. Is that good thinking?
Answer: As you need each of $\emptyset,\{1,2,3,4,5,6\},\{1,3,5\},\{2,4,6\},\{1,3\},\{2,4\}$ and any combination of unions, intersections, complements, and differences that can be made from these, it helps to try to spot what the essential "atoms" are in this sigma algebra.
You should be able to see that the list of atoms are $\{1,3\},\{2,4\},\{5\},\{6\}$
The sigma algebra then contains all sets from $\mathcal{P}(\{1,2,3,4,5,6\})$ with the exception of those where $1$ appears without $3$, or where $2$ appears without $4$ or vice versa.  Another way to visualize the set is to consider $\mathcal{P}(\{a,b,5,6\}$ and anywhere you see an $a$ replace it with "$1,3$" (including the comma) and anywhere you see a $b$ replace it with "$2,4$."
Comment: Thanks, your detailed answer was very helpful :)
Answer: Let's use an exhaust technique. The number of possible subsets of $ \Omega$ is $2^{|\Omega|}=2^6=64$. Let $ \mathcal{A}_1$ be the collection of the $n_1= 8 $ sets below.
$$
A_1, \quad A_2,\quad A_3,\quad A_4,\quad
A_{5}=A_1^c, \quad A_{6}=A_2^c,\quad A_{7}=A_3^c,\quad A_{8}=A_4^c,
$$
If  $\mathcal{A}_{1}$ is a sigma algebra and the work is finished.
Otherwise, let $\mathcal{A}_2$ be the collection of the $8\cdot 8=64$  sets below.
$$
\begin{array}
\,A_{i_1i_2}=A_{i_1}\cup A_{i_2} & \mbox{ for }\quad i_1>i_2 \mbox{ and } A_{i_1},A_{i_2}\in \mathcal{A}_1
\\
\,A_{i_1i_2}=A_{i_1}\cup A_{i_2} & \mbox{ for }\quad i_1=i_2 \mbox{ and } A_{i_1},A_{i_2}\in \mathcal{A}_1
\\
\,A_{i_1i_2}=(A_{i_1}\cup A_{i_2})^c & \mbox{ for }\quad i_1<i_2 \mbox{ and } A_{i_1},A_{i_2}\in \mathcal{A}_1
\\
\end{array}
$$
Notice that $\mathcal{A}_1\subset \mathcal{A}_2$, $\mathcal{A}_2\subset 2^\Omega$ and $|2^\Omega|=64$ then some of those sets above are eventually repeated. Let $ n_2 $ be the number of subsets different from each other of $ \mathcal{A}_2 $. If  $\mathcal{A}_{2}$ is a sigma algebra and the work is finished. Otherwise, let $\mathcal{A}_3$ the colection of $n_2\cdot n_2$ sets below.
$$
\begin{array}
\,A_{i_1i_2}=A_{i_1}\cup A_{i_2} & \mbox{ for }\quad i_1>i_2 \mbox{ and } A_{i_1},A_{i_2}\in \mathcal{A}_2
\\
\,A_{i_1i_2}=A_{i_1}\cup A_{i_2} & \mbox{ for }\quad i_1=i_2 \mbox{ and } A_{i_1},A_{i_2}\in \mathcal{A}_2
\\
\,A_{i_1i_2}=(A_{i_1}\cup A_{i_2})^c & \mbox{ for }\quad i_1<i_2 \mbox{ and } A_{i_1},A_{i_2}\in \mathcal{A}_2
\\
\end{array}
$$
Notice that $\mathcal{A}_2\subset \mathcal{A}_3$, $\mathcal{A}_3\subset 2^\Omega$ and $|2^\Omega|=64$ then some of those sets above are eventually repeated. Let $ n_3 $ be the number of subsets different from each other of $ \mathcal{A}_3 $. If  $\mathcal{A}_{3}$ is a sigma algebra and the work is finished. Otherwise, let $\mathcal{A}_4$ the colection of $n_3\cdot n_3$ sets below.
$$
\begin{array}
\,A_{i_1i_2}=A_{i_1}\cup A_{i_2} & \mbox{ for }\quad i_1>i_2 \mbox{ and } A_{i_1},A_{i_2}\in \mathcal{A}_3
\\
\,A_{i_1i_2}=A_{i_1}\cup A_{i_2} & \mbox{ for }\quad i_1=i_2 \mbox{ and } A_{i_1},A_{i_2}\in \mathcal{A}_3
\\
\,A_{i_1i_2}=(A_{i_1}\cup A_{i_2})^c & \mbox{ for }\quad i_1<i_2 \mbox{ and } A_{i_1},A_{i_2}\in \mathcal{A}_3
\\
\end{array}
$$
This process ends after a finite number $ k $ of interactions meaning that $\mathcal{A}_k =\mathcal{A}_{k+1}=\mathcal{A}_{k+2}=\ldots $. Thus, $ \mathcal{A}_k $ will be the smallest sigma algebra containing the sets $A_1$,$A_2$,$A_3$ and $A_4$.


Embaralhar números de uma lista?

Question: Bom, inicialmente, não entendo muito de lista em C#, mas tenho uma lista do tipo int que sempre vai ter 4 elementos que são: 1, 2, 3 e 4, estou atribuindo eles com o .Add, se alguém souber outro jeito me dê um help..
Eu queria embaralhar os itens dessa lista sempre, ou seja, ter uma função para embaralhar os itens da lista e me retornar a lista embaralhada para eu poder usar ela.

Exemplo:
Uma lista: 1, 2, 3, 4
Retornar: 2, 1, 4 ,3 (aleatoriamente)

E depois disso, eu tenho que usar os elementos dessa lista, como faço isso?  Na lista do exemplo a embaralhada ficou 2, 1, 4, 3 como uso cada valor desse no código como uma variável inteiro? Exemplo: Quero atribuir á uma variável soma o valor do 1º e 3º elemento da lista embaralhada, como indico o 1º e 3º elemento para a soma?
Comment: Talvez não basta. o fato é que supre. E o fato não ter o termo não significa que a pergunta não é duplicada. Duplicação não significa ter os mesmos termos, significa apenas querer o mesmo resultado.
Comment: Foi uma duplicata pois a anterior não era duplicata na minha opinião, até que a resposta mais simples não foi a mesma, então pra mim não é duplicata, eram situações diferentes.
Comment: É duplicata da que você perguntou que é duplicata da outra porque dá a mesma resposta. Quando as respostas de uma pergunta já feita não te satisfazem você coloca uma recompensa. Mas lá não te satisfez porque se produz exatamente o resultado que você espera? A mais simples também resolve de um jeito que você que está começando não tem ideia do que seja esse monte de coisa, ñ está pronta para uso em qualquer código. Se quisesse algo mais simples você teria dito que leu lá e queria algo "mais simples" (embora mais simples é um conceito subjetivo),aí as pessoas saberiam o que você está procurando.
Comment: Nada haver, para muitos i termo embaralhar pode ser definido em outras palavras como trocar, alterar etc e nem por busca no site tu encontra, só acho que deveria comentar com o link da outra pergunta que parece ser igual antes de marcar como duplicata, pois talvez aquela pergunta não supri a dúvida que a pessoa tem.
Answer: Eis uma solução simples:
var list = new List<int> {1, 2, 3, 4};
var rnd = new Random();

var query =
    from i in list
    let r = rnd.Next()
    orderby r
    select i;

var shuffled = query.ToList();

Comment: @LeonardoVIlarinho Mas não é igual. Tem alguns comportamentos semelhantes (usar como índice, por exemplo), mas as semelhanças acabam aí.
Comment: Foi o mais simples e que funcionou perfeitamente, só agora eu implantar numa função. Valeu aí, e aos demais, não sabia que era igual ao vetor do C
Comment: @LeonardoVIlarinho O melhor mesmo e' ler a [documentacao de `List`](https://msdn.microsoft.com/en-us/library/vstudio/6sh2ey19(v=vs.110).aspx). No fundo da pagina tem exemplos uteis.
Comment: Sim, não é igual kk é mais ou menos como Python né.. Não dá pra se comparar com C pois vetor armazena um item em dada posição, logo lista de string seria completamente diferente.. @dcastro valeu pelo link, vou dar uma olhada
Answer: Esta resposta ensina a fazer alguns algoritmos, como o de Fisher-Yates, mas é importante observar que esse algoritmo não é 100% aleatório, segundo a própria resposta. A resposta dá outras soluções mais confiáveis, mas para fins de simplicidade, vou manter apenas a primeira:
private static Random rnd = new Random();

public static void Shuffle<T>(this IList<T> list)
{
    int n = list.Count;
    while (n > 1) {
        n--;
        int k = rnd.Next(n + 1);
        T value = list[k];
        list[k] = list[n];
        list[n] = value;
    }
}

Uso:
List<int> numeros = new List<int> { 1, 2, 3, 4 };
numeros.Shuffle();

Para somar o primeiro com o terceiro elemento, você pode fazer da seguinte forma:
var soma = numeros[0] + numeros[2]; // 0 é a primeira posição, 2 é a terceira.

Answer: Esta resposta já existe no site desde 21/05/2014. Na verdade esta pergunta é a duplicata da duplicata. Como ela ficou aberta e foi respondida, vou responder também.
Note que não mudei a solução (aqui eu tirei a parte que melhorava o método para poder escolher qual faixa de dados deseja, mas não muda a execução em si), que é o importante. apenas tirei do exemplo a parte das strings. Se o problema é não saber somar elementos do array, então a pergunta deveria ser essa.
using static System.Console;
using System.Collections.Generic;

public static class Sorteio {
    public static void Main() {
        int[] array = { 1, 2, 3, 4 };
        array.Shuffle();
        foreach (var valor in array) WriteLine(valor);
        WriteLine("Soma: {0}", array[0] + array[2]); // soma 1o. e 3o. elemento
        //vamos de novo
        array.Shuffle(); //com poucos númros tem chance de repetir
        WriteLine($"Soma novo sorteio: {array[0] + array[2]}"); // soma 1o. e 3o. elemento
    }
}

namespace System.Collections.Generic {
    public static class IListExt {
        static Random r = new Random(DateTime.Now.Millisecond);

        public static void Shuffle<T>(this IList<T> list, int lowerItem, int upperItem) {
            upperItem = upperItem > list.Count ? list.Count : upperItem;
            lowerItem = lowerItem < 0 ? 0 : lowerItem;
            for (int i = lowerItem; i < upperItem; i++) {
                int j = r.Next(i, upperItem);
                T tmp = list[j];
                list[j] = list[i];
                list[i] = tmp;
            }
        }

        public static void Shuffle<T>(this IList<T> list, int upperItem) => list.Shuffle(0, upperItem);

        public static void Shuffle<T>(this IList<T> list) => list.Shuffle(0, list.Count);
    }
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Para atribuir para uma variável é só fazer isto:
var soma = array[0] + array[2]; //listas começam em zero então o elemento sempre é -1 ao desejado

Para mais detalhes, consulte as respostas já existentes lá na pergunta original.

Embaralhar números de uma lista?


Secure iframe on unsecure page in a different domain

Question: Our company is looking into allowing third party sites to use our online checkout system.
A client has stated that they would like to be able to use a lightbox style popup to display the checkout. And they would like this to be available on every page of the site, therefore mostly unsecure pages. Our checkout system and the client site are obviously on different domains.
I'm guessing that I could use a secure iframe (using https) to display our checkout system.
Would this iframe actually be secure?
Is the a sensible thing to do? (my gut says no, as how can the user tell the page is secure)
Are there any better ways to achieve this same functionality?
Comment: Hi Karl,
How did you go about this? I am doing a similar thing and have aa few problems. Can you share your findings.
Comment: Hi rAm. In the end we never went ahead with this project. But I would have pushed for just switching the page to the secure sever so the user can tell the page is secure. This is the approach taken by openID .
Comment: WePay.com does this for their payment processing forms on other sites. I saw a popup before on an insecure page and could not tell it was secured.
Answer: Yes, the iframe would be secure, but you're correct that the customer wouldn't actually be able to tell that it's secure.  On the other hand, most users can't tell if a page is secure anyway - a few images of padlocks scattered around will convince most of them.
Could you, when they click to pop out the checkout, send them to the same url under HTTPS then pop it out (you'd need your own SSL certificate of course)?
Answer: Have you seen how other similar checkout systems work? For example the paypal checkout on ebay? They take you trough the checkout process "full screen" and back to the original site when the transaction is complete.
Answer: I know this is an old question but I was planning to do the same thing. The work-around is either to do the paypal thing -> go to a secure site for payment -> return to return-url. Or you could set up your own website with a very generic, short name like shop.com (obviously taken) but one that is not taken.
Your clients could then have their own space like https/www.theirsitename.shop.com,
so they would move from http/www.theirsitename.com to the above.
Most users won't even be able to tell they've moved to a new website, and the page will be secure.
To get their products, you could make them POST it from their end, and perhaps also get them to POST a CSS file which would completely alter the layout so it looks like their own website.
Comment: Is a https iframe allowed to `Location`-redirect itself to a different (https or not) domain?
Comment: @DanMan pretty sure it is. Why don't you try it? I think the problem occurs when you mix https pages with unsecure http content. For example, if you have a https iframe, is it displayed in a https page or not? if it isn't, then it'd be better to use a pop-up window for the https


Apply filter based on select list - Angular JS

Question: Array 1: Categories -> Category_Name, Category_Id
Array 2: Items -> Item_name ... etc , Category_Belonging_Id
I need to filter shown items based on selected category.

    <select>
       <option ng-repeat="category in categories" ng-model="category_type">
          {{category.Category_Name}}
       </option>
    </select>

...

Comment: can you share this issue on jfiddle
Answer: Assuming you have:
Catergory = {
id
name
}

and
MeatType{
    id
    catergoryId
    name
    }

You can do something like

Comment: Sorry for misunderstanding the MeatTypes refers to Items.. I've edited my question. You say category_type.id but I assume you mean category_type.Category_Id. Right ??
Answer: first of all you should use ng-option instead of ng-repeat like
<select ng-model="category_type" ng-options="category.Category_Name for category in categories"></select>

and use filter like
filter:{Category_Belonging_Id:category_type.Category_Id }

see demo here
Answer: Try this


Problemas ao utilizar o iloc pandas

Question: Quero criar um novo DataFrame com a seguinte condição:
marvel.loc[ marvel['Orientation'] != 'NaN' ]

Ou seja, quero que todas as linhas que tenham a coluna 'Orientation'== 'NaN' sejam excluídas, porém tem algo dando errado. Segue o código:
marvel= pd.read_csv('Heroes_Marvel.csv')
marvel.count()
print(marvel.isna().sum())
marvel.columns
orientation=  marvel.loc[(marvel['Orientation']!='NaN')]

e quando eu coloco para imprimir o Orientation está tudo inclusive os NaN's
Answer: Devido a forma como NaN's são definidos NaN == NaN -> False.
Você deve usar a função pd.IsNull

Problemas ao utilizar o iloc pandas


If $H_{1}$ and $H_{2}$ are subgroups of (G,$\bullet$), then $H_{1}\triangle H_{2}$ is a subgroup of (G,$\bullet$) ? Prove or give a counterexample

Question: Let (G,$\bullet$) be a group. If $H_{1}$ and $H_{2}$ are subgroups
of (G,$\bullet$), then $H_{1}\triangle H_{2}$ is a subgroup of (G,$\bullet$)
where $\triangle$is the symmetric difference.
I think that is false.
My argument: Because (G,$\bullet$) is a group, then exist $e\in$
G where $e$ is the identity element. Now, because $H_{1}$ and $H_{2}$
are subgroups of (G,$\bullet$) then $e$ $\in$ $H_{1}$ and $e$
$\in$ $H_{2}$. Then, for definition of intersection betwen sets,
we have that $e$ $\in$ $H_{1}\cap H_{2}$. Now by definition of
symmetric difference we have that $H_{1}\triangle H_{2}$ = ($H_{1}\cup H_{2})-(H_{1}\cap H_{2})$
. Then we have that $e$$\notin$ $H_{1}\triangle H_{2}$ and then,
because $H_{1}\triangle H_{2}$ don't have the identity element, we
have that $H_{1}\triangle H_{2}$ is not a group. It is my argument correct? What counterexample can I use to disprove it?
Comment: Your argument is correct, and thus *any* two subgroups $H_1$ and $H_2$ will form a counterexample!
Comment: Incidentally, you can get a somewhat less trivial question by asking whether $(H_1\bigtriangleup H_2)\cup\{e\}$ is or can be a subgroup of $G$...
Answer: Your argument is correct. For a counterexample, simply let $H_1$ and $H_2$ be the trivial subgroup. As commented by Greg Martin, according to your argument any two subgroups will form a counterexample. It's especially obvious when the subgroups are equal because then the symmetric difference is empty!
Comment: Just to be clear. The empty set it's not a group? And if the answer is no: Why? It just that I read in the book ''proofs and fundamentals'' and it says that the empty set is a group.
Comment: @ManuelVargas There is no such thing as an empty group. A group must have an identity element, so every group has at least one element.
Comment: Okay, I understand. Thanks!
Comment: @ManuelVargas No problem.


How do I find a poorly configured router or diagnose intermittent request timeouts?

Question: I am an analyst programmer at my organisation and am finding some sort of intermitent time-out issue when using CVS and HTTP requests within our network.
After the time-out the request does complete though it takes just over 60-seconds, which is why I'm guessing that it's some sort of time-out fail-over problem happening.
I wish to try and figure out how to find if possible what the issue is, I'm assuming there's a bad rout being made somewhere or there's something wrong with one of the DNS servers. The infrastructure team has told me there isn't any issue with the network, which personally I'm thinking is a cop-out.
I have root access to two Linux (RHEL 5.4) machines.
Please excuse me if this task is obvious as I'm a software developer not a network engineer.
UPDATE
I thought I might mention that this problem occurs between clients and the CVS server and clients using VPN and the HTTP server. Our VPN clients do not reverse resolve and I've asked the network engineers to ammend that but they don't see that as being a problem.
Comment: Can you add some logging to your AJAX calls to get some timestamps of when things are being received, and when they are being returned? Is it possible whatever methods you are calling are actually timing out instead of the network?
Comment: Hi mpeterson, it doesn't appear to time out, it just takes 60 seconds for the request to complete, it's almost as if the packets are taking a very long time to get to the server. With the CVS server the server doesn't see the request until 60 seconds after I made it (using SSH), once the session is made it returns almost immediately. For the AJAX and other HTTP requests they are on a different server and do appear to time-out. I only have limited access to that server and it's windows which I know less about diagnosing proboems than on Linux.
Answer: Often places will screw up their reverse records.  You can tell you've got screwed up reverse records because if you run something like netstat -a and it takes a really long time to run and you get back a bunch of IP addresses in the rfc1918 address space.  Not having reverse records in this space by itself isn't really a problem, but it is a problem if your DNS people forward their DNS requests to the providers or to a broken DNS server.
A quick way to verify if it is a DNS issue is to log onto the system and lookup an IP of someone connected to the system (look at netstat -a and look for established connections) and then run
nslookup a.b.c.d (or whatever the IP of that host is)

if you've got an older system, you may need to type
nslookup d.c.b.a.in-addr.arpa.

In either case, the result may be something like "can't find that address" but the answer needs to come back quickly.  DNS timeouts can be on the order of seconds, and if you have 3 DNS servers in your resolv.conf, your server is going to try each one before it gives up.  This can easily add up to a really annoying amount of time.
A quick way to illustrate the problem to your boss is to run netstat -an and then run netstat -a and then say "if our DNS was working properly, these would both run in almost exactly the same amount of time.
If it is a reverse-record issue, you can probably "fix" the problem by turning off reverse lookups in your applications.  In this situation, it may be easier than getting another group involved.
There is also the remote possibility that there is a duplex mismatch between your servers and their switches.  That can be tested by looking at the output of (windows) netstat -e or (unix) netstat -i.  You're looking for "errors" or "collisions".  If you see "collisions" then your end is mis-configured; it is half duplex and should be full duplex.  If you see "errors" the switch end is half duplex and you're full duplex.  Both counters should be zero, or at least small and not increasing.  These problems can be really hard to track down because the link will work pretty well if it is unloaded and totally fall apart when there is lots of traffic.
Comment: Thankyou chris, very helpful and I will try to see if I can diagnose the latter part. I have seen this problem once before here which took me > 12 months to convince the infrastructure people there was a problem, it turned out that it was a misconfigured DNS server that no longer existed. I've tested the former part of your solution and everything seems fine, though VPN connections are not reverse resolving which could be compounding the issue. As mentioned I'm not much of a network person but I'll see if I can figure out the collisions side to your solution.
Comment: Sounds like you need better infrastructure people, or you need a supervisor who can pressure the infrastructure people's supervisor into actually making this work.  Or, this isn't really a problem and you're just trying to make things work better (bravo to you) but noone else is complaining.  If the developers are losing productivity over this, you need to make sure that mordac's boss gets an earfull.
Comment: Thanks Chris, I have spoken to the IT manager who is now looking into it. It costs around 2 hours per day of developer time if they make 20 commits a day. It also costs time with our merchandiser supervisors using the web based applications time, though the problem is always blamed on their 3G air-cards without any actual backing/investigation. Our infrastructure team is small (3) with an attitude of "If I can't see the problem then there isn't one", and looking will only reveal a problem.
Comment: Thanks Chris, I'll mark that as answered I think. I'm sorry I haven't up-voted you but I can not as yet otherwise I would have done so.
Comment: Check the edit -- I'm going to describe exactly how to identify if it is a DNS issue.  Rude and busy often look exactly the same from the outside so the more you can help them isolate the problem, the better...  Just be careful with the politics of this sort of thing.
Comment: Thanks Chis, much appreciated. While my specific problem hasn't been resolved your answer does fit the correct suggestions. Unfortunately I had checked all the server and client reverse resolving (for those involved) and were coming back correctly, applications have reverse resolve turned off also. However, I do know that something is very wrong internally with the DNS, as sometimes a DNS lookup takes an extreme amount of time (to a single server) and then the same request completes immediately.
Comment: Our infrastructure team frequently messes up the reverse-resolving. I'm not sure how AD handles the dynamic range, but there are clients that get associated with IP's that don't resolve, those clients see the worst problems around the site. From what I've fount it seems that when infrastructure build a server it gets a dynamic IP, then they allocate a fixed IP and the DNS is not updated to dissociate it or something, and clients get that dynamic IP which then messes things right up.
Answer: If the request completes, then it's not a timeout issue. If it were a timeout issue the request would never complete, hence the name "timeout". Do you mean that some requests timeout and some complete after a long period of time, because that makes more sense than what you've stated in your post.
As far as tracking down the issue, there are a lot of areas to look at. Here's a few suggestions to get you started:
Run a tracert from a client machine to the server in question. Count how many hops it goes through. Each hop is a router of some sort. If the tracert goes directly from your client machine to the server, then there are no routers in the path.
Run a pathping from a client machine to the server in question and look for latency and packet loss between the two.
Install a packet sniffer on the server and start a capture. Submit a request from the client and look at the output of the packet sniffer on the server. If you see a siginificant delay between the request and reply in the sniffer output then it's a server issue. If there's no significant delay then it's a network issue.
Comment: Good heavens.  That's going to be like trying to diagnose a problem by reading a 30mb tomcat dump.
Comment: I don't see it being that difficult. Depending on the packet sniffer used, you can filter based on protocol and source and destination ip addresses so the actual dump you're looking at should be pretty small. IMHO a packet sniffer is an invaluable tool and is one of the first things I fire up when trying to diagnose network performance problems. Nothing but a packet sniffer can tell me what's happening at the packet level.
Comment: Packet sniffers are invaluable, I'll agree.  In situations where you're seeing performance problems, though, they won't directly see problems like mis-configured or slow DNS or duplex mismatches or systems with failing hard disks.  I'd resort to the sniffer only after eliminating things that can be directly observed on the servers (dns, network configuration, is the app slow if I run a browser directly on the host, etc).
Comment: @ chris: for the most part I agree with you but I would say that I like to start from the ground up. By running a capture on the server I can quickly (within 5 minutes) determine if the issue is on the server or the network by looking at the request\response packets in the capture. If I start by looking at the routers, switches, DNS, etc., etc. it could take hours to track down what might eventually turn out to be a server problem.
Comment: @ chris: what I should have said is that I like to start at one end of the problem and work my way to the other. Since the server is the destination (one end) I would start my troubleshooting there and work my way to the client (other end).
Comment: Hi joeqwerty, very good advice. I had tried traceroute from both ways which works fine (1 hop), however trying from the server to the DNS servers it worked fine for one but the other would time-out after MAX_HOPS passed. We had a similar issue once before which turned out to be one of the DNS servers had a backup DNS configured which was no longer active, it emitted the exact same intermittent results as I'm seeing now, that's why I was thinking it was a similar issue. When I meant time-out, I was meaning a DNS request timeout, or a router path timeout and choosing another path.


Propensity score matching linearity assumption

Question: One of the advantage that i have herd talked about propensity score matching, vs. a regression, is that propensity-score matching doesn't rely on linearity assumptions.
This seems incorrect on the surface, given probit [/logit] models used to calculate the propensity scores, will embed linearity assumptions. [i.e assuming that you must estimate propensity scores]
What would be references to material which discuss this, or compare how similar the assumptions of matching and regressions are more broadly?
Answer: First, your question is limited to propensity score matching, but there are other matching procedures that do not use propensity scores, such as exact matching, genetic matching, and coarsened exact matching. See Ho et al. 2007 for a review. These alternative methods are non-parametric and do not make linear assumptions. In fact, unless your propensity-score model is very good, there are theoretical arguments that suggest such methods are preferable.
Second, propensity scores are most generally the predictions from a model that estimates probabilities conditional on covariates. Nothing prevents you from using non-linear models, such as random forest, boosted regression trees, neural networks, etc. In fact, there is a package for R called twang developed by the RAND Corporation that uses the gbm package to optimize the tuning parameters of boosted regression trees with respect to user-specified sample-balance criteria, then output the predicted propensity scores for your sample using the balance-optimized model. You can also specify whether you are after an average treatment effect (ATE) on the population or on the treated (ATT). I wrote a silly little LinkedIn post that gives some brief pointers on how to use twang-generated propensity scores as the distance metric for nearest-neighbor matching as implemented in the MatchIt package.


online tool for generating stubs for webservices jax-rpc

Question: is there any tool that generates stubs for RPC style wsdl online. I used the Netbeans plugin for RPC and tried to create one. But while executing the app I am getting errors like while calling a function.
<code>java.rmi.RemoteException: Runtime exception; nested exception is:
    deserialization error: unexpected element type: expected=
{http://account.type.engine.mdsp.huawei.com}UserBalanceInfo, actual=
http://account.engine.mdsp.huawei.com}UserBalanceInfo
</code>
Any suggestions?
Comment: Are you creating stubs by giving URL? Is your URL to WSDL correct? Does it end with a '?wsdl' ?
Comment: @sreehari i have wsdl file. url is correct. have generated the stubs properly. but execution time such errors occurs
Comment: @sreehari pls find the file at http://pastebin.com/18hgiwFZ
Comment: @sreehari i hav created the stubs with apache axis. but am not getting the procedure to call the method.
Answer: I would say using a tool like SoapUI will enable you to create stubs or even script out responses for your wsdl services.
SoapUI supports many configuration options. for example, you can mimic your existing services with specific header values or other payloads by using groovy scripts.
Link1: http://www.guru99.com/webservice-testing-beginner-guide.html
Link2: https://www.soapui.org/soap-and-wsdl/getting-started.html


Changing Android activity name in Cordova config.xml

Question: I have an old Android Cordova app whose manifest has <activity android:name=".MyActivity". This has already been published to the Play store, so I can no longer change the name.
I'm trying to migrate to the Cordova CLI workflow, but the Android app it generates has android:name="MainActivity". How can I customize this in config.xml, so it generates the right name?
I found an undocumented preference "android-activityName". I tried setting this to ".MyActivity", and removing/adding the android platform. But with this setting, it no longer created the activity class at all, and I got an error "Error: No Java files found which extend CordovaActivity".
Comment: I think its problem of Package name instead of activity name.
Answer: I've dealt with this using the cordova-custom-config plugin, adding this to my config.xml:
<custom-preference name="android-manifest/application/activity/@android:name" value=".MyActivity" />

Answer: Recently I also faced a similar situation.What I did was I changed the id of the widget tag inside config.xml to reflect the package name where I put my MyActivity class which extends CordovaActivity.Make sure you have deleted the unwanted MainActivity class that cordova generates(if you are putting your MyActivity class in the same package as MainActivity class).And also your MyActivity class should be extending CordovaActivity (important).Then open config.xml and change the widget tag as given below.
//Change the id value to the package name where you put your MyActivity class
<widget id="com.yourCompanyName.yourPackageName" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">

After doing this clean the project using cordova clean command and then rebuild the project.Additionally you can use android-packageName property to widget tag to give android specific package name and ios-CFBundleIdentifier for ios specific name.
Comment: @Hardik Vaghani I think the title is little bit confusing :)
Comment: I think that the simplest solution is to use a [cordova hook](https://cordova.apache.org/docs/en/latest/guide/appdev/hooks/) (eg. **after_platform_add** ) replacing the `MainActivity.java` with your custom `MainActivity.java`
Comment: This is not for changing activity name. This is for changing package name.
Comment: @Hardik Vaghani By default when you create a new cordova project by CLI you get an activity called MainActivity which extends CordovaActivity ,the OP said he used a different name for his activity so he needs cordova to find his MyActivity as the main activity.I have answered just for that ,delete the unwanted MainActivity that cordova generates,let him put his MyActivity class(make sure MyActivity extends CordovaActivity) in the same package or different package put that package name as the widget id value,clean the project and rebuild :)
Comment: It is important to note that if you change the package name, run the `cordova clean` command, and build your project again, the `MainActivity.java` file will get deleted because the `platforms/android/app/src/main/java/` folder gets removed. This will then cause the "No Java files found which extend CordovaActivity" error on subsequent builds. Either save this Java file somewhere else (or use your own) and replace it to enable builds again. Removing and adding the android platform again will also restore it (not great if you are customizing your build process, though.)
Answer: I had a similar problem and this was my solution in bash. I had the wrong Activity name and the wrong java file name, so I needed to change both.
I created the following bash function:
First I replace all MainActivity references with NewActivityName.
Then I look for the java file and rename it.
function rename_the_activity {
    platformDir="/path/to/platformdir"
    grep -rl 'MainActivity' $platformDir | sort | uniq | xargs perl -e "s/MainActivity/NewActivityName/" -pi
    activity=$(find $platformDir -name 'MainActivity.java')
    newactivity="${activity/MainActivity/NewActivityName}"
    mv $activity $newactivity
    print_blue "Renamed activity class MainActivity to NewActivityName"
}