Help with compact notation for sum

Question: I've already understood the motive of this sum using the nom-compact way, but I want to do it in the compact way, so it will be rigorous. Please, I need some help:
$$\frac{1}{2}\sum_{k=1}^{n}\frac{1}{2k-1}+\frac{1}{2}\sum_{k=1}^{n}\frac{1}{2k+1}-\frac{1}{2}\sum_{k=1}^n\frac{1}{k}+\frac{n}{2n+1} = $$
$$\sum_{k=1}^n\frac{1}{2k-1}-\frac{1}{2}\sum_{k=1}^n\frac{1}{k}=$$
$$\sum_{k=1}^{2n}\frac{1}{k}-\sum_{k=1}^n\frac{1}{k} = \sum_{k=1}^n\frac{1}{n+k}$$
Well, I'm not lazy, I really understood what's happening, I've tried changing the index of some sums but I couldn't do it. I want to proof it without expanding the sum, only by doing manipulations with the compact notation for sums.
Comment: I don't quite understand your question. Are you asking whether the stated equalities are true?
Comment: @MichaelAlbanese, I imagine the OP wrote out some terms of each sum, saw the pattern, and drew conclusions, but now wants help constructing a more rigorous proof.
Comment: @MichaelAlbanese this is given to me as true. I want to be able to verify it, just by starting from the first line: $\frac{1}{2}\sum_{k=1}^{n}\frac{1}{2k-1}+\frac{1}{2}\sum_{k=1}^{n}\frac{1}{2k+1}-\frac{1}{2}\sum_{k=1}^n\frac{1}{k}+\frac{n}{2n+1}$. If I know how to arrive at the second line, then it will already help me a lot.
Answer: Of the four terms, the first two look most similar. The only difference between the two is the fact that one has denominator $2k - 1$ whilst the other has denominator $2k+1$. It would be nice if we could combine these two terms. We're going to convert the denominator $2k+1$ to $2k-1$, but we could go the other way. Note that $2k + 1 = 2(k+1) - 1$ so we have
$$\sum_{k=1}^n\frac{1}{2k+1} = \sum_{k=1}^n\frac{1}{2(k+1)-1} = \sum_{l=2}^{n+1}\frac{1}{2l-1}$$
where the last equality occurs due to a change of index, $l := k + 1$. As the name of the index is irrelevant, you can replace $l$ by $k$. Doing so gives
$$\frac{1}{2}\sum_{k=1}^n\frac{1}{2k-1} + \frac{1}{2}\sum_{k=2}^{n+1}\frac{1}{2k-1} = \frac{1}{2}\frac{1}{1} + \frac{1}{2}\sum_{k=2}^n\frac{1}{2k-1}+\frac{1}{2}\sum_{k=2}^n\frac{1}{2k-1} + \frac{1}{2}\frac{1}{2n+1}$$
where we have split off the first term of the first summation and the last term of the second summation so that now the index in both summations runs over the same values. Simplifying we obtain
$$\sum_{k=2}^n\frac{1}{2k-1} + \frac{n+1}{2n+1}.$$
If we want the summation to start at $k = 1$ instead of $k=2$ we can do that by realising that the term in the sum corresponding to $k = 1$ would be $1$ so we begin the summation at $k = 1$ and then subtract $1$ so that we don't change the expression. So we obtain
$$\sum_{k=2}^n\frac{1}{2k-1} + \frac{n+1}{2n+1} = \sum_{k=1}^n\frac{1}{2k-1} - 1 + \frac{n+1}{2n+1} = \sum_{k=1}^n\frac{1}{2k-1} - \frac{n}{2n+1}.$$
Now we have combined the first two terms. In terms of the initial expression we have
\begin{align*}
& \left(\frac{1}{2}\sum_{k=1}^{n}\frac{1}{2k-1}+\frac{1}{2}\sum_{k=1}^{n}\frac{1}{2k+1}\right)-\frac{1}{2}\sum_{k=1}^n\frac{1}{k}+\frac{n}{2n+1}\\
=& \left(\sum_{k=1}^n\frac{1}{2k-1} - \frac{n}{2n+1}\right)-\frac{1}{2}\sum_{k=1}^n\frac{1}{k}+\frac{n}{2n+1}\\
=& \sum_{k=1}^n\frac{1}{2k-1} -\frac{1}{2}\sum_{k=1}^n\frac{1}{k}
\end{align*}
which is the second expression you provided in your post. Note that we can rewrite this slightly as
$$\sum_{k=1}^n\frac{1}{2k-1} - \sum_{k=1}^n\frac{1}{2k}.$$
Now we see that the terms in the first summation are reciprocals of odd numbers between $1$ and $2n-1$, and the terms in the second summation are reciprocals of even numbers between $2$ and $2n$. If we had the sum of these two summations, we could combine it into a single summation which had terms which where the reciprocals of positive integers between $1$ and $2n$. That is,
$$\sum_{k=1}^n\frac{1}{2k-1} + \sum_{k=1}^n\frac{1}{2k} = \sum_{k=1}^{2n}\frac{1}{k}.$$
Unfortunately, we do not have the sum of these two summations, but rather their difference. However, we can use this equality to help simplify our expression. Note that
\begin{align*}
\sum_{k=1}^n\frac{1}{2k-1} + \sum_{k=1}^n\frac{1}{2k} &= \sum_{k=1}^{2n}\frac{1}{k}\\
\sum_{k=1}^n\frac{1}{2k-1} + \sum_{k=1}^n\frac{1}{2k} - 2\sum_{k=1}^n\frac{1}{2k} &= \sum_{k=1}^{2n}\frac{1}{k}-2\sum_{k=1}^n\frac{1}{2k}\\
\sum_{k=1}^n\frac{1}{2k-1} - \sum_{k=1}^n\frac{1}{2k} &= \sum_{k=1}^{2n}\frac{1}{k}-2\sum_{k=1}^n\frac{1}{2k}.
\end{align*}
So the initial expression reduces to the right hand side of the last equality. But now we have
$$\sum_{k=1}^{2n}\frac{1}{k}-2\sum_{k=1}^n\frac{1}{2k} = \sum_{k=1}^{2n}\frac{1}{k}-\sum_{k=1}^n\frac{1}{k}$$
which is the third expression you provided in your post. Now the terms in the first summation are reciprocals of positive integers between $1$ and $2n$, while the terms in the second summation are reciprocals of positive integers between $1$ and $n$. The only terms which remain once the subtraction is performed are the reciprocals of the positive integers betweeen $n+1$ and $2n$. So we have
$$\sum_{k=1}^{2n}\frac{1}{k} - \sum_{k=1}^n\frac{1}{k} = \sum_{k=n+1}^{2n}\frac{1}{k} = \sum_{l=1}^n\frac{1}{n+l}$$
where the last equality occurs due to a change of index, $l := k-n$. Finally, as the name of the index is irrelevant, you can replace $l$ by $k$. Doing so gives
$$\sum_{k=1}^n\frac{1}{n+k}$$
which is the final expression you provided in your post.
Answer: If you can't see the pattern, write out a few terms
$$
\sum_{k=1}^{n}\frac{1}{2k-1} = 1/1 + 1/3+ 1/5 + 1/7 \cdots
$$
$$
\sum_{k=1}^{n}\frac{1}{2k+1} =1/3+ 1/5 + 1/7 \cdots
$$
So these two can be combined except the extra term in the first sum.
$$
\sum_{k=1}^{n}\frac{1}{k} =1/1+ 1/2 + 1/3 +1/4+1/5\cdots
$$
Again you can see common terms with the others. With practice you will start to notice these patterns. There is no magic formula, just practice.
Comment: I really saw the pattern. I expanded the terms and recognized this as true. But what I wanted to do, is to be more rigorous, by proving it just manipulating the compact notation, without expanding.

Help with compact notation for sum


NLS_NUMERIC_CHARACTERS in Oracle's to_char() function

Question: I'm trying to convert numeric field to varchar.
select value from nls_session_parameters
where parameter = 'NLS_NUMERIC_CHARACTERS'

returns ','
code is:
select to_char(sm.trxn_amount, '999999999999D000', 'NLS_NUMERIC_CHARACTERS = '',.''')

sm.trxn_amount format is NUMBER(18,3)
for example, lets run this code
select sm.trxn_amount
from x

result is 106729,000
if i then run
select
to_char('106729,000', '999999999999D000', 'NLS_NUMERIC_CHARACTERS = '',.''')
from dual

result is

106729,000

but if i run
select to_char(sm.trxn_amount, '999999999999D000', 'NLS_NUMERIC_CHARACTERS = '',.''')

result is

106729.000

what am i missing? cant get decimal point to be ','
Comment: Can you clarify what your first query returns - ',' doesn't make sense. If it's ',.' then the third and fourth queries would both show commas. And if it's '.,' then the fourth would still show a comma, but the third would throw ORA-01722 invalid number. So something doesn't add up in what you're showing (hence your question!). Are all those queries and results exactly what you use and see? Which client are you running this in, and how (e.g. script vs. statement), and is your client applying formatting to the number result (e.g. via set numf or equivalent in your client) from the second query?
Answer: If that column's datatype is NUMBER, then it most probably doesn't have trailing zeros (behind the decimal point).
Anyway, it seems that everything is fine on my 11g:
SQL> create table sm (trxn_amount number(18, 3));

Table created.

SQL> insert into sm values (106729);

1 row created.

SQL> select * from sm;

TRXN_AMOUNT
-----------
     106729

SQL> select to_char(sm.trxn_amount, '999999999999D000', 'NLS_NUMERIC_CHARACTERS = '',.''') result from sm;

RESULT
-----------------
       106729,000

SQL>


Why are there chords that aren't a third away form the root considered chromatic mediants?

Question: For example, take a C chord. One of the requirements for a chord to be a chromatic mediant is that it is a major/minor third away from the root. So why are chords like Cm, Fm, C♯ and F♯ considered chromatic mediants as well?
Comment: Can you give an example of where you've heard those chords referred to in such a way? I've never encountered that. However, all of those chords contain the mediant or submediant *pitches* (E/Eb, A/Ab) relative to C major/minor.
Comment: I was reading an article from https://en.wikipedia.org/wiki/Chromatic_mediant
Answer: Your understanding of a chromatic mediant relationship is correct, so the chords you listed do not of have a chromatic mediant relationship to C major.
However, those four chords (Cm, Fm, C♯, F♯) all have roots a third away from A. A minor is the relative minor of C major, which means the two keys share the same key signature. So I think the source you were reading was listing out the chromatic mediants for the relative minor.
Comment: @MiaLee That's correct -- every chord has it's own set of chromatic mediants, based on the root of the primary chord.
Comment: I see. It just happens that those chords share similar notes with C major. Does this mean that every chord has their own chromatic mediant?


Overhead of Perfmon -> direct to SQL Database

Question: HI All,
First up, I'm a total newb at Performance Monitoring. I'm looking to set up central performance monitoring of some boxes.

2K3 TS ( Monitor General OS Perf & Session Specific Counters )
2K8 R2 ( XenApp 6 = Monitor General OS Perf & Session Specific Counters )
File Server ( Standard File I/O )

My ultimate aim is to get as many counters/information, without impacting the clients session experience at all. Including counters specific to their sessions.
I was thinking it logging directly to a SQL on another server, instead of a two part process of blg file then relog to sql.
Would that work ok? Does anyone know the overhead of going straight to SQL from the client?
I've searched around a bit, but havent found so much information it can be overwhelming.
thanks
Answer: We log from perfmon into SQL and have collected 10s of millions of datapoints this way. I've never noticed any appreciatable overheads, and it's great to have the data immediately available.
Comment: same opinion here.  Haven't noticed perf impact of remote perfmon on Server 2008 or newer.


Send PHP requests from dedicated IP instead of shared IP

Question: I have set a dedicated IP for a website (using directadmin), but all outgoing php requests are sent from the server's shared IP. Result of the following code is always the shared IP.
$a = file_get_contents("http://mxtoolbox.com/WhatIsMyIP/");
print $a;

I need to send requests from dedicated IP because my payment gateway only accepts requests from that IP.
Do I need to add iptables rules to send all requests from the dedicated IP or there is a better way?
Comment: [Administration panels are off topic](http://serverfault.com/help/on-topic). [Even the presence of an administration panel on a system,](http://meta.serverfault.com/q/6538/118258) because they [take over the systems in strange and non-standard ways, making it difficult or even impossible for actual system administrators to manage the servers normally](http://meta.serverfault.com/a/3924/118258), and tend to indicate low-quality questions from *users* with insufficient knowledge for this site.
Answer: Set a route to the payment processor via the dedicated IP. The ip route add command is your friend.
Answer: This should be at StackOverflow.  You need to create a context for your socket.
$opts = array(
    'socket' => array(
        'bindto' => '10.10.1.1:0',
    )
);

$context = stream_context_create($opts);
$a = file_get_contents("http://mxtoolbox.com/WhatIsMyIP/", false, $context);
print $a;

In this example, this will bind to IP 10.10.1.1.  Port 0 is used to allow the OS to choose the port.
Otherwise, you'll have to either change your default route for all traffic or determine the IP address of the site you are trying to reach.  The latter of which can be unreliable if they use a distributed network or change their address.
Comment: The user did not _ask_ for a programming solution. Your answer might be appropriate for SO, but it is not here.
Comment: @MichaelHampton yes but he gave PHP code and assuming he isn't the root user or doesn't want to change the default route, there is no other reliable way as per my last point.
Comment: I on the other hand was looking for a programming solution.
Comment: You're making an inappropriate assumption. Someone asking a question on [sf] almost always _is_ root and can change system routes. (If they aren't, then they shouldn't be asking questions here to begin with.)
Comment: ....and what happens when you bind the socket to an interface which doesn't have a route to the destination?
Comment: @symcbean: I suspect the same thing as if you added a faulty route in the routing tables...


Technical disavantages of application used on a windows network share/drive by multiple users

Question: Let's take a custom-made .NET application :

Dependency on the .Net Framework
A few dlls and an executable
A few dependencies on third parties (Crystal Reports, Connector, etc.)

What are the technical disadvantages of installing this kind of application. on a network share or drive, and allow multiple users to use it at the same time on a windows domain ? I'm looking for usage issues, not deployment issues.
I know that it's not the best case scenario, and that, auto-updatable local installs, TS sessions and other means are now available for this situtation, but I'd like to have a clear and deep answer to discourage such way to install applications across a network.
Answer: Depending on your actual application and setup you might run into

file locking issues
permission problems
network performance bottlenecks
availability issues

These might or might not be relevant to a specific installation. I would not claim that an executable on a network share is always a bad thing, but it is more prone to be than a local install.
Comment: I added some details on the kind of application I'm talking about, if that's of any help to precise the possible issues that could be encountered. But that's already a good answer, thanks :)


bind apache2 to localhost only Ubuntu 12.04.3 LTS

Question: Trying to bind apache2 to localhost only, running Ubuntu 12.04.3 LTS on OpenVZ VPS. It fails on me (see /var/log/apache2/error.log). Default configuration is:
<code># cat /etc/hosts
fe00::0     ip6-localnet
ff00::0     ip6-mcastprefix
ff02::1     ip6-allnodes
ff02::2     ip6-allrouters

127.0.0.1 localhost.localdomain localhost
# Auto-generated hostname. Please do not remove this comment.
<some-ext-ipv6-address> <some-hostname>
::1     localhost ip6-localhost ip6-loopback
# netstat -lntup
tcp6       0      0 :::80                   :::*                    LISTEN      623/apache2
</code>
I change Listen 80 to Listen 126.96.36.199:80 in /etc/apache2/ports.conf.
Apache2 errors out. There is no other service listening on port 80, also there is no other (conflicting) Listen declaration, just the default ports.conf apache2 ships with + the single change described.
<code># cat /var/log/apache2/error.log
apache2: Could not reliably determine the server's fully qualified domain name, using <some-ext-ipv6-address> for ServerName
(99)Cannot assign requested address: make_sock: could not bind to address 22.214.171.124:80
no listening sockets available, shutting down
Unable to open logs
</code>
Answer: localhost address is 127.0.0.1 not 220.127.116.11
Comment: omg, what a silly mistake. thanks, works perfect! back to preschool then.


Rank of the sum of an all-ones matrix and an identity matrix

Question: Let $B$ be an all-ones matrix of dimension $n \times n$, and $I$ be the identity matrix of dimension $n \times n$. Define $A = \frac{1}{n}B - I$. For $n=3$, $A$ would yield
\begin{equation*}
\begin{bmatrix}
-2/3 & 1/3  & 1/3  \\
1/3  & -2/3 & 1/3 \\
1/3  & 1/3 & -2/3
\end{bmatrix}.
\end{equation*}
How would one compute rank$(A)$ for any $n$?
I have noted that any row $r_i$ of $A$ can be written as a linear combination of the other $n-1$ rows. Specifically, $r_i = - \sum_{j\neq i} r_j$. This implies rank$(A) < n$, but I don't know how to compute the exact rank of $A$.
Any hint would be appreciated.
Comment: Multiply by $-3/2$ to obtain a matrix with $1$'s on the diagonal.
Answer: Notice the matrix rank is subadditive. i.e. for any $n\times n$ matrix $P, Q$, we have
$${\rm rank}(P+Q) \le {\rm rank}(P) + {\rm rank}(Q)$$
Since ${\rm rank}(B) = 1$, we have
$$n = {\rm rank}(-I) = {\rm rank}\left(A - \frac{B}{n}\right) \le {\rm rank}(A) + {\rm rank}\left(-\frac{B}{n}\right) = {\rm rank}(A) + 1$$
This implies ${\rm rank}(A) \ge n - 1$. Together with the inequality
you have ${\rm rank}(A) < n$, you can deduce ${\rm rank}(A) = n -1$.
Answer: It is easy to compute $ker(A)$:
$ker(A)= span \{(1,1,1,...,1)^T\}$.
Hence $\dim ker(A)=1$ and so $rank(A)=n-1$.
Answer: Suppose we are in characteristic zero. Then $B$ is symmetric over the reals and is diagonalisable.
The eigenvalues of $B$ are $n$ (with multiplicity one) and $0$
(with multiplicity $n-1$). Therefore the eigenvalues of
$rB+sI$ are $rn+s$ (with multiplicity one) and $s$
(with multiplicity $n-1$). When, say $rn+s=0$ and $s\ne0$, then $rB+sI$
has zero as an eigenvalue with multiplicity one, so its rank is $n-1$.


Error 503 Backend fetch failed

Question: Às vezes me aparece esse erro quando estou desenvolvendo alguma aplicação no wordpress, alguém sabe me dizer o motivo???
Answer: O Varnish é um "acelerador", ele é um sistema de cache das páginas, é um proxy reverso, ou seja as requisições passam por ele e as cópias ficam armazenadas na memória.
Sobre o erro, geralmente ele ocorre quando excede o limite de armazenamento na memória, você pode editar o arquivo o arquivo varnish (ou varnish.params) e ajustar parâmetro http_resp_hdr_len para que o servidor consiga suportar maior consumo (também depende de quanto o seu servidor tem de memória disponível para o serviço, se for Shared é provável que seja bem limitado).
Arquivos de configuração em diferentes distros:

CentOS 6: /etc/sysconfig/varnish
CentOS 7: /etc/varnish/varnish.params
Ubuntu: /etc/default/varnish

No entanto se você não tem acesso as configurações só entrando em contato com a hospedagem.
Vou deixar uma coisa bem claro, não estou defendendo as hospedagens a maioria tem problemas pequenos mesmo que muitas vezes causam transtornos, mas este problema na maioria das vezes é culpa é dos web-desenvolvedores e administradores de sites (no caso provavelmente você), que injetam inúmeros JavaScript, CSS, plugins e add-ons sem necessidade e com isto vão tornando o site cada vez mais pesados e lentos, mesmo com incríveis sistemas de cache e etc o servidor não tem como aguentar.
Então não é bem um problema de configuração, mas sim um problema de mau uso dos recursos, então você pode tentar dar uma revisada geral, analisar se tudo é necessário ou até pensar em trocar o WordPress por uma plataforma mais eficiente, fora isto não tem muito o que fazer.
Comment: ótimo esclarecimento, obrigado!

Error 503 Backend fetch failed


S3 DeleteObject - DeleteMarker always returns empty

Question: I am using the AWS SDK for PHP, version 2.4.7 installed via composer.  After deleting a file from an S3 bucket the DeleteMarker key in the response object is always empty even through the file has actually been deleted from S3.  The documentation states that DeleteMarker should be true if the operation was successful otherwise it's false.
My delete call is:
    // delete S3 object
    $result = $s3->deleteObject(array(
        'Bucket' => $this->_bucket,
        'Key' => $object_key,
    ));

and the response is:
Guzzle\Service\Resource\Model Object
(
    [structure:protected] =>
    [data:protected] => Array
        (
            [DeleteMarker] =>
            [VersionId] =>
            [RequestId] => 2CC3EC60C4294CB5
        )
)

If I then do:
    // check if was deleted
    $is_deleted = (bool) $result->get('DeleteMarker');

$is_deleted is always false.  How can it be that there is no value returned against the DeleteMarker key even though the delete operation was actually successful and the file was removed from S3?
UPDATE:
If I add a slash to the start of my key I get a response false back even though the file is still removed from S3.
Key "path/to/my/image.jpg" results in DeleteMarker having empty value
Key "/path/to/my/image.jpg" results in DeleteMarker having empty false
But in both cases the images is removed from the S3 bucket.
Comment: Having this same issue. Did you ever resolve this?
Comment: No, I never got this resolved.  I didn't want to enable versioning on the bucket so I just do as Simon has suggested below and issue a second call to check if the file exists after the delete call.  It's not ideal as it would be better if I could make one call to delete and know from this if it was successful or not.
Answer: In converting from SDK v. 1.? to 2.?, I too ran into the problem of not knowing if the file deleted (there used to be the ->isOK() method on just about everything that would let me know if the file had been deleted or not).
I finally stumbled upon this response from the Guzzle creator: https://forums.aws.amazon.com/thread.jspa?messageID=455154
Basically, there is no longer any 'did delete' flag of any kind.  What Michael (Guzzle) suggests is this: if you want to know if a file deleted, use ->deleteObject() and then run ->doesObjectExist() to see if the delete was successful.
The rationale for the change is this: the new approach lets you fire off tons of delete requests without having to wait for replies, etc.
For what it's worth.
David
Comment: The AWS Docs are really wrong. The object is deleted but the return DeleteMarker is always false for some reason. Using the ->doesObjectExist after the deleteObject is the only way to know if the object was deleted or not. So this is the right answer
Comment: as per AWS docs - https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-s3-2006-03-01.html#deleteobject the response is  `[
    'DeleteMarker' => true || false,
    'RequestCharged' => 'requester',
    'VersionId' => '',
]'
Answer: I am having the same issue with the Javascript SDK. The call to deleteObject returns fine (HTTP 204) regardless if the file exists or not! This makes it impossible to tell if the file was deleted from the response code. Furthermore, it seems that the response only includes DeleteMarker if the bucket has versioning enabled (see also this thread on DeleteMarker).
I see two possibilities to work around this issue.
As first option, you can enable versioning and use DELETE Object versionID to permanently delete your objects (see the AWS documentation). This will require you to either store the versionID in your database, or query it prior to deletion using listObjectVersions
As second option, you can use listObjects to check if the file exists, delete the file using deleteObject and check listObjects again to make sure the file was deleted for sure.
I am not satisfied with either solution, but they do the job for now
Comment: Really strange S3 SDK implementation :(


Nullpointer Exception in FragmentActivity while showing data in Spinner from database

Question: I am getting a problem in FrameActivity with FragmentPagerAdapter to declare my swipe-able tabs. In one of tabs contain Spinner in which i want to collect data from database. First i am going to post my FrameActivity
     public class TranscationMain extends FragmentActivity implements
  ActionBar.TabListener {
Context context;
private ViewPager viewPager;
Spinner spinner_question ;
ContentValues values;
SQLiteDatabase sql_lite_db_obj;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
Cursor cursor;
int i =0;
// Tab titles
private String[] tabs = { "Shipped In", "shipped Out", "New Entry" };

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.transcation_main);

    AndroidContext.setContext(this);
    sql_lite_db_obj = DatabaseHelper.getInstance().getDb();
    values = new ContentValues();

    // Initilization
    context = this;
    viewPager = (ViewPager) findViewById(R.id.pager);
    actionBar = getActionBar();
    mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

    viewPager.setAdapter(mAdapter);
    actionBar.setHomeButtonEnabled(false);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    spinner_question = (Spinner)findViewById(R.id.spinner_category);

    // Adding Tabs
    for (String tab_name : tabs) {
        actionBar.addTab(actionBar.newTab().setText(tab_name).setTabListener(this));
    }
    viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {

            actionBar.setSelectedNavigationItem(position);
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    });

}

@Override
public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
    // TODO Auto-generated method stub

}

@Override
public void onTabSelected(Tab arg0, FragmentTransaction arg1) {
    // TODO Auto-generated method stub
    viewPager.setCurrentItem(arg0.getPosition());

}

@Override
public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
    // TODO Auto-generated method stub

}
        public void clickHandler(View v)
{

    if (v.getId() == R.id.btn_new_category_id) {
        // btn click event that define in NewEntry.java calss
                    // click on this button alert dialog will open with editext
                    // from where i insert data in database. which i have to show in
                     // spinner which define in same activity. Insertion of data is
                   // done successfully.
    }

}
     private void insertData(String category) {
    // method to insert data in database
           // working fine
}

Now this is exception part of above code
   private void loadSpinnerData() {
    DatabaseHelper db = new DatabaseHelper(getApplicationContext());
    List<String> lables = db.getAllLabels();
    System.out.println(" data in array : "+lables);

    // Creating adapter for spinner
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, lables);
    System.out.println(" dapater : "+dataAdapter);

    // Drop down layout style - list view with radio button
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // attaching data adapter to spinner
    spinner_question.setAdapter(dataAdapter);
}

I want to call this method in this block
       if (v.getId() == R.id.btn_new_category_id) {
             loadSpinnerData()
              }

But always i am getting a NullPointer Exception . Only because of initialization of
        spinner_question = (Spinner)findViewById(R.id.spinner_category);

Spinner is not define in above TranscationMain's layout, It define in below Fragment
        public class NewEntry extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
       spnr = new Spinner(getActivity());
    View rootView = inflater.inflate(R.layout.new_entry, container, false);

    return rootView;
}

}
That why i am getting exception in below line.
   spinner_question.setAdapter(dataAdapter);

Now i didn't understand how can i solve this problem. How can i bind data in spinner in Fragment. I am new fro fragment activity. Thanks in advance to all
Answer: Spinner is not define in above TranscationMain's layout, It define in below Fragment

This is the reason for the crash.
findViewById looks for a view in the current inflated layout.
If the spinner is in fragment you need to initialize the same in fragment and then load the items from database to spinner in fragment.
In fragment
Spinner spinner_question;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {

View rootView = inflater.inflate(R.layout.new_entry, container, false);
spinner_question = (Spinner)rootView.findViewById(R.id.spinner_category);
return rootView;
}

Comment: @Raghunandan.. When i am trying to define spinner in Fragment findViewById is not working. Then how i will bind spinner in xml with java file.?
Comment: @Raghunandan...Spinner spnr;     spnr = new Spinner(getActivity());
        loadSpinnerData(); private void loadSpinnerData() {
        DatabaseHelper db = new DatabaseHelper(getActivity());
        List lables = db.getAllLabels();
        ArrayAdapter dataAdapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, lables);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spnr.setAdapter(dataAdapter);
    }
Comment: @Raghunanadan.. But i am getting error in ArrayAdapetr "The constructor ArrayAdapter(NewEntry, int, List) is undefined"
Comment: @BlueGreen you need to read the docs. `ArrayAdapter dataAdapter = new ArrayAdapter(getActivity(),android.R.layout.simple_spinner_item, lables);`. `this` refers to fragment not activity context
Comment: @BlueGreen what happens now??
Comment: @Raghunandan.. I will follow your suggestion.. Sure.. Thanks again


Can you use power analysis to find if the null hypothesis is true rather than not?

Question: So in power analysis I have only ever seen it explained like in this statquest video:
https://www.youtube.com/watch?v=VX_M3tIyiYk
Where you have two distributions and you're trying to see if they are really unique or if they come from the same underlying distribution. Can power analysis be used to change this situation round a little - say all you have is one distribution, can you find the probability that it is not actually a different distribution, just with samples that happen to be concentrated to (for example) the right of the actual distribution? I.e. imagine you make a drug to get rid of flu faster. You have a drug but no, you give group A the drug but don't do a placebo group. You plot the distribution for how quickly group A got better. Now you get a second group (group B) and give them all the same pill, but you don't know if that pill was the drug or a placebo (but everyone got the same pill!). You then plot a distribution of how long it took them to get better and the distribution looks like the distribution of group A but very slightly different, that pill could have been the placebo one right, just everyone in group C happened to get better a bit faster than average and thus the distribution looks like the one which took the drug.
Is there anyway to quantify how different the distribution of group B would need to be for us to confidently say that the group did not take the drug but instead were given a placebo? And also to quantify how confident we are. To be more clear, imagine the distribution of group B came out as very similar to group A, it's highly likely they took the drug but they could still have taken the placebo and all happened to get better fast. On the other hand the distribution comes out totally different to group A, it's highly unlikely the group took the drug but they still could have and all just taken ages to get better despite the drug being effective. Assume group A was huge thus the distribution is very well known, however the size of group B will likely be a parameter of how confidently we will be able to say if the distribution is the same or not. Please leave a comment if any of this isn't clear and I'll try clarify!
Comment: You may be interested in [tag:equivalence] tests such as [tag:tost]. The R package [PowerTOST](https://github.com/Detlew/PowerTOST) may also be of use to you.
Comment: What the OP is describing is the motivation for a traditional Bayesian procedure.
Answer: The first idea that comes into my mind would be a one-sample test, where you use your sample A to get an idea of what is the distribution of recovered patients and then compare remaining groups to said distribution.
A crude idea would be some t-test or Wilcoxon test for one sample but, then you would be comparing your response only to one parameter from A. Maybe Kolmogorov-Smirnov, where you can indeed compare samples and check if they come from the same distribution, would be a good solution.
Answer: What you're referring to is the "effect size" aspect of a power analysis. A power analysis relates the sample size, type I error rate, type II error rate (1-power), and effect size. We sometimes design experiments by fixing the desired type I and type II error rates, giving an expected effect size that we should be able to capture, and then finding a sample size that is sufficient to accomplish these goals. But you can also use power analysis to fix any three of the four variables and solve for the last one - given the type I and type II error rates and a sample size, you can calculate the effect size that you're likely to be able to capture. You'll always have a non-zero type II error rate, so you can't be sure that you'd reject the null hypothesis even given a large effect size, but you can use this approach to figure out what effects you're likely to find.
You can use this approach to help decide if "absence of evidence" is "evidence of absence" or not. Given a particular dataset of fixed sample size, you can determine how "useful" the dataset is in finding effects with desired error rates. You may find that your sample size is very small and the effect sizes you're able to reliably find are unrealistically large - suppose in your drug example, you find that your sample size only allows you to reliably identify an effect of a 1000-fold decrease in recovery time, which would be enormous. Finding no significant difference between placebo and drug in this scenario is utterly unsurprising - you've failed to reject the null hypothesis of no difference, but it certainly is not evidence that there is no difference, since your data is insufficient to find anything but absurdly large effects. On the other hand, if you have a very large dataset that is sufficiently powered to pick up on a 1% change in recovery time, seeing no significant difference is actually good evidence that there really is no effect - you very likely would have found even small effects if they existed.


Worst classifier

Question: What is the worst classier that learns badly in practical problems?
Edit:
Especially bad on test data..
Thanks
Comment: Mathematically speaking, in binary classification, knowing the worst is equivalent to knowing the best. If you know the best you reverse the rule and it becomes the worst. Why do you want the worst rule ? what do you mean by worst ?
Answer: Consider the binary case.  If you don't know the proportions of the two classes, then the worst you can do is to flip a fair coin in each case: the expected error rate is $1/2$.  If you do know the proportions, and the smaller of the two is $p$, say, then you should always classify objects in that category: the expected error rate is $1-p \gt 1/2$.  (However, it could be argued that this procedure is not worse.  After observing it sufficiently long, you would notice its error rate is significantly greater than $1/2$ and then you would have the option of negating it--that is, assigning the opposite classification--and that would have an error rate of only $p \lt 1/2$.)
Comment: I am curious if one can do even _worse_ than a coin flip in the case of unknown proportions of classes, but it seems probably not.
Comment: In addition to Dikran, the worst classifer I can imagine would be a classifier trained on a small amount of data which performs sometimes better and sometimes worse than random so that the negation is not possible, i.e. the is quality systematically unpredictable (but this seems ridiculous, so I'll stick with whuber).
Comment: @steffen I think you're right: complete unpredictability can be worse than random.  There is a difference!  But although there is no probability model available, we can analyze this situation with game theory.  It's you *vs* the classifier.  Assume the classifier is out to get you: it will do its worst.  What is your optimal strategy?  The answer, in the absence of any other information, is to flip the coin: that guarantees you won't lose more than half the time in the long run. What ruins this analysis is the eternal hope that *our* classifier is actually good, so we rarely use this strategy.
Comment: +1 If you wanted a straw man, that would indeed be a good one!
Comment: @Dikran You have read my answer as it was intended: tongue in cheek.  It's amusing to try to think of anything that could be worse and somewhat amusing to think of more sophisticated attempts that, in the end, haven't performed any better than a coin flip!
Comment: I suspect it is possible to make a classifier that is worse than coin flipping by using an overly complex model (such as an ANN with a large hidden layer) and too little data.  While it will out-perform coin flipping on the training set, it may well be worse on the test set.  AFAIK, there is no guarantee that an overfit model won't be arbitrarily bad on the test set.
Comment: I would say flipping a coin is the best you can do when the information you have is not related with the classification you want to make. Hence there are worst things to do ?
Answer: It is usually the statistician using the classifier that is the problem (for picking the wrong tool for the particular problem at hand, or for using it incorrectly).  The "no free lunch" theorems show there is no a-priori distinction between classifiers (which works best/worst depends on the data), so I'd say there isn't a worst classifier in a general sense.  However, some classifiers are easier to shoot yourself in the foot with than others, in which case, I would nominate artificial neural networks (the over-fit very easily and need proper architecture selection and none of the solutions to such problems are reliable).
Comment: Hah!  I think my proposal is worse than yours :-).
Comment: The no-free lunch theorem suggest that there will be problems where it works well and other algorithms dont! ;-P
Comment: Thank you.  Do you have a favorite reference or references to these NFL theorems?
Comment: The original papers were by David Wolpert, there are some references and info at http://www.no-free-lunch.org/ .  "no free lunch for the sandwich" would be a favourite reference, but only because of the title ;o)

Worst classifier


How to properly delegate form error to parent?

Question: I have a form with multiple radios. I need to display the radios in a certain way(separately with additional form elements) so I had to use radio form elements instead of one radios element.
The radios are required but I have an issue with delegating the error to the parent element. I switched off the error message for the radios themselves via the <code>#error_no_message</code> attribute. Now the form error is properly displayed for the parent element but the error message contains the label of the first radio element instead of the parent element. So for example if I have fieldset named "Manufacturer" and it contains radios with labels like "Audi", "Mercedes" or "BMW" and I won't select any radio the form error, after form submission, will say "Field Audi is required." instead of "Field Manufacturer is required".
So how can I delegate the form error to the parent(which is working) but with making the form error to be applied to the parent itself so the proper label is displayed?
Answer: I did what I could but in the end I had to create new form element that provided me with the proper structure. The important thing about it though is mostly that it has input so the form element can be properly delegated whereas before I used fieldset which has no input therefore it would not display error properly.


how to create generic hashmap in c++?

Question: How can I create a generic hashmap in vc++? I am using visual studio and vc++ as language option. I want to seperate my implementation into header(interface) and cpp files.
header:
template<class T1,class T2>
class Generic
{
  map<T1,T2> m1;

  public:

  // Standard constructors and destructors
  // -------------------------------------
     Generic ();
     virtual ~Generic ();

  // Copy constructor and equal operator
  // -----------------------------------
  Generic (Generic &);
  Generic& operator=(Generic&);

  void insert(const T1& key,const T2& value);
  T2 lookup(const T1&key);

};

and my cpp file:
MyGeneric::Generic()
{
}

//-----------------------------------------------------------------------------
// Generic : destructor
//-----------------------------------------------------------------------------
Generic::~Generic()
{
}

//-----------------------------------------------------------------------------
// Generic : copy constructor
//-----------------------------------------------------------------------------
Generic::Generic(Generic& original)
{
}

//-----------------------------------------------------------------------------
// Generic : equal operator
//-----------------------------------------------------------------------------
Generic& Generic::operator=(Generic& original)
{
  return *this;
}
void Generic::insert(const T1& key,const T2& value)
{
}
T2 Generic::lookup(const T1&key)
{
}

I am wondering whether I am making a mistake here. I am also being confused about its usage becuase I am not defining the template in my cpp file. Is that the problem?. How can I delete a single value for a corresponding key in hashmap?
Comment: What's wrong with `std::hash_map` or `std::unordered_map`?
Comment: Apart from all other comments, there is one more basic c++ concept that you need to accept: "You cannot separate the definition of your templates class from its declaration and put it inside a .cpp file". http://www.parashift.com/c++-faq-lite/templates.html#faq-35.12
Comment: @Cody, can we use them generically, i mean i need a single map object that can store any kind of key values in it. just based on key and its type i need to retrieve value of type that is binded to that key..if i wont use this logic, my program goes undoubtedly messy..
Comment: @user1061293: Both are template based generic standard library containers,You are essentially trying to re-invent the wheel.
Comment: If you are seriously interested in writing clean and generic C++ components, get a copy of _C++ Templates: The complete guide_ by Vandevoorde and Josuttis. Your code has several flaws, syntactically as well as conceptually.
Answer: It looks like you need a variant type. Have a look at the boost variant. It allows you to store and retrieve any type you want. You can of course use it in combination with sequences or maps like std::unordered_map.
Implementing it your own is quite messy itself. Believe me, I tried :)
Comment: In my answer, I posted a link to the Boost library **variant**. It provides the functionality you require. And no, there is no type safe *built-in* way to do this in C++.
Comment: I concur. Implementing a variant type yourself is exceedingly unpleasant.
Comment: @all, Do we have anything like this in c++:
var j;
j=10;
j="Student";
j=new MyClass;
Is there any generic variable in c++ like this?
Comment: but it has different ways of using in different operating system.. I am using VC++ in windows and the same code is will run on unix machine at at time..how can this work?

how to create generic hashmap in c++?


Pointwise convergence and liminf

Question: Convergence in measure is strictly weaker than pointwise convergence.
To see this, take $(X, \mathcal{A} , \mu)$ = $([0, 1], \mathcal{B}[0, 1], λ|[0,1])$ and set:
$u_n(x) := \textbf{1}_{[i2^{−k},(i+1)2^{−k}]}(x)$,        where $n = i + 2^k, 0\leq i < 2^k$.
This is a sequence of rectangular pulses of width $2^{−k}$ moving in $2^k$ steps through $[0, 1]$, jump back to $x = 0$, halve their width and start moving again. Obviously $u_n \longmapsto 0$ in measure.
What about the pointwise convergence?
The book is reasoning by saying that the liminf = 0 and limsup = 1, so the limit doesn't converge anywhere.
My doubt is on the liminf. Why should it be 0?
My reasoning was: fixing an x on the interval $[0,1]$, infinitely often there will be a rectangle that make my indicator function taking value 1.
But I don't know what to say on the liminf.
Comment: Please see the typesetting edits
Answer: For any $x$ and any $k>1$ there is always an $i$ such that $[2^{k}x]\neq i, [2^{k}x]\neq i+1$. Let $n_k=i+2^{k}$. Then $x \notin [i2^{−k},(i+1)2^{−k}]$ so $u_{n_k}(x)=0$. Thus, infinitely many terms of the sequence $(u_n(x))$ are $0$ and this implies that $\lim \inf u_n(x)=0$.
Comment: But how can there be infinitely many terms = 0 if , infinitely often, there will be some 1?
Comment: @GabrielePillitteri Doesn't $\{0,1,0,1,0,1...\}$ have infinitely many $1$'s as well as infinitely many $0$'s?
Comment: Yes, that's why i was thinking that limsup could be 1 or 0. But I can't figure it out why liminf is zero
Comment: What do you know about lim sup of a  sequence of real numbers? Do you know that it is the smallest limit point of the sequence?
Comment: Yes, that's why the liminf is one. But I do not understand why infinitely many terms are 0, since, sometimes, there's some 1!
Comment: I have proved that infinitely many terms are $0$. My $n_k$'s are strictly increasing.

Pointwise convergence and liminf


How to add NanoSpell to CKEditor

Question: I am trying to integrate NanoSpell into CKEditor but it does not work for me and I have no idea why... I followed the instructions but it's seems like it's not registering the plugin.
You may download my code from here (Google Drive):
https://drive.google.com/file/d/0B_Cc00_51F-aNlFTZ3RlNDVMQm8/view?usp=sharing
Answer: if you want to add spell checker in CK editor just add below lines in config.js of your CKEDTIOR
config.disableNativeSpellChecker = false;
    config.removePlugins = 'scayt,menubutton,contextmenu';
Comment: Thank you for your answer. I tried what you suggested but it did not work for me.

How to add NanoSpell to CKEditor


Bootstrap Align Checkbox  next to Header

Question: I'm trying to vertically align a bootstrap checkbox & label with a header element. I also want the checkbox & label to be at the far right of the shared grid row.
HTML:

Chat Room

                <input type="checkbox" checked> enable presence events

CSS:

.form-inline h3 {
    display: inline-block;
}

label.checkbox-inline {
    float: right;
}

https://jsfiddle.net/zenwoof/7e1f47rz/7/
Results in:

I'm hoping there's a clean & responsive way to do this, other than a hacky margin/padding fix.
Thanks!
Comment: You need to add this css. `label.checkbox-inline {margin-top: 20px;}`
Answer: You can try this,Use same css style:

Chat Room

                <input type="checkbox" checked>       enable presence events

/Note:Please check cairfully hare one div closing tag is missing.chack same mistake in code may be this mistake is only in during posting the problem./
Answer: I'm new to Bootstrap so I figured there was some class I neglected to include, but guess not - came down to a hard-coded margin fix which is what I originally did.

Bootstrap Align Checkbox  next to Header


Getting array information from selected combobox item.

Question: I have a simple question. All I am needing to do is get the array information from the selected combo box item. I know about combobox.selectedindex but that's not my issue. I am needing to retrieve the Array information so once I select the students name it will show up their Original Grade and Curved letter grade. I have done the math already, I have everything down and done except for this. Here is my code.
<code>      Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click

    Dim Line_String As String

    Dim ArraySize_Integer As Integer = 0
    Dim Grades_StreamReader As IO.StreamReader
    Dim i As Integer = 0
    Dim GradesFile_String As String = "Grades.txt" 'To hold the filename for opening
    Dim DialogResponse As DialogResult
    Dim x_Integer As Integer
    Dim Mean_Decimal As Double = 0
    Dim Total_Integer As Double = 0
    Dim sum As Double
    Dim stDev As Double
    Dim x As Integer
    Dim y As Integer
    Dim orgScore As Integer

    'Prompt to open the file

    'Set the initial folder to display
    OpenFileDialog1.InitialDirectory = IO.Directory.GetCurrentDirectory

    'Open the file
    With OpenFileDialog1
        'Begin in the current folder
        .InitialDirectory = Directory.GetCurrentDirectory()
        .FileName = "Grades.txt"
        .Title = "Select File or Directory for File"
        'Filter to show only .txt files
        OpenFileDialog1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
        'Display the open file dialog box
        DialogResponse = .ShowDialog()
    End With
    'Get the filename
    GradesFile_String = OpenFileDialog1.FileName

    'Connect to the file
    Grades_StreamReader = IO.File.OpenText(GradesFile_String)
    'Read the file into a structure array until it runs out of data
    Do Until Grades_StreamReader.Peek = -1
        'Raed the data
        Line_String = Grades_StreamReader.ReadLine
        'Split the line into the fields
        StringArray_String = Line_String.Split(","c)
        'Dynamically size the array of structures
        ReDim Preserve StudentData_Person(ArraySize_Integer)
        'Assign the fields to the structure, trimming the space
        StudentData_Person(ArraySize_Integer).Name_String = StringArray_String(0).Trim
        StudentData_Person(ArraySize_Integer).Grade_String = StringArray_String(1).Trim
        'Increment for the next array element
        ArraySize_Integer += 1
        'Populate the combo box
        Students_ComboBox.Items.Add(StringArray_String(0))

    Loop
    'Close the file
    Grades_StreamReader.Close()

    'Count the scores
    'Convert from String to Integer
    Scores_TextBox.Text = ArraySize_Integer.ToString

    'Calculate the mean

    If StudentData_Person.Length > 0 Then
        For x_Integer = 0 To StudentData_Person.Length - 1
            Total_Integer += CInt(StudentData_Person(x_Integer).Grade_String)
        Next
        Mean_Decimal = Total_Integer / StudentData_Person.Length
    End If
    Mean_TextBox.Text = Mean_Decimal.ToString

    'Calculate the Standard Deviation

    If StudentData_Person.Length > 0 Then
        For x = 0 To StudentData_Person.Length - 1
            sum += ((CInt(StudentData_Person(x).Grade_String) - Mean_Decimal) ^ 2)
        Next
        stDev = Math.Round(Math.Sqrt(sum / (x - 1)), 2)

    End If
    stDev_TextBox.Text = stDev.ToString

    'Get information from ComboBox Selected Entry
    Students_ComboBox.SelectedIndex

    'Determine letter grade
    For y = 0 To StudentData_Person.Length
        If CInt(StudentData_Person(x).Grade_String) >= Mean_Decimal + (1.5 * stDev) Then
            CurvedGrade_TextBox.Text = "A"
        End If
        If (Mean_Decimal + (0.5 * stDev)) <= CInt(StudentData_Person(x).Grade_String) And CInt(StudentData_Person(x).Grade_String) < (Mean_Decimal + (1.5 * stDev)) Then
            CurvedGrade_TextBox.Text = "B"
        End If
        If (Mean_Decimal - (0.5 * stDev)) <= CInt(StudentData_Person(x).Grade_String) And CInt(StudentData_Person(x).Grade_String) < (Mean_Decimal + (1.5 * stDev)) Then
            CurvedGrade_TextBox.Text = "C"
        End If
        If (Mean_Decimal - (1.5 * stDev)) <= CInt(StudentData_Person(x).Grade_String) And CInt(StudentData_Person(x).Grade_String) < (Mean_Decimal + (1.5 * stDev)) Then
            CurvedGrade_TextBox.Text = "D"
        End If
        If CInt(StudentData_Person(x).Grade_String) < (Mean_Decimal - (1.5 * stDev)) Then
            CurvedGrade_TextBox.Text = "F"
        End If
    Next
End Sub
End Class
</code>
I also would then need to retrieve the information from this and calculate their score as given and push it back out to the text boxes which I can do.
Would I just do
<code>    originalscore_textbox.text = StudentData_Person(SelectedIndex)
    curvedgrade_textbox.text = 'something like what's above this line
</code>
or something like that I know that's definitely wrong I am just showing y'all my concept of thinking. Any questions, please ask I will try my best to explain them. But this is literally all I need and I'm done with my program haha.
Answer: It would be helpful if you posted how StudentData_Person is defined.
I suggest adding a new Curved_String field to StudentData_Person. And populate it when you have calculated the curved grade. Then you just do.
<code>originalscore_textbox.text = StudentData_Person(SelectedIndex).Grade_String
curvedgrade_textbox.text = StudentData_Person(SelectedIndex).Curved_String
</code>


Undesired toggle effect with #states and checkboxes

Question: I'm working on a patch for the Login Disable module, and on the settings page, I want to have two mutually exclusive options so that when one is checked, the other is unchecked. Using the FAPI #states value, I have the following code:
function login_disable_settings_form($form, &$form_state) {
  $form = array();

  $form['all_users'] = array(
    '#type' => 'fieldset',
    '#title' => t('All Users'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );

  $form['all_users']['login_disable_is_active'] = array(
    '#type' => 'checkbox',
    '#title' => 'Prevent user log in',
    '#description' => t('When active the user login form will be disabled for everyone. For roles granted bypass rights they must use the access key defined below.'),
    '#default_value' => (bool)variable_get('login_disable_is_active', FALSE),
    '#states' => array(
      'unchecked' => array(
        ':input[name="login_disable_individual"]' => array('checked' => TRUE),
      ),
    ),
  );

  $form['all_users']['login_disable_key'] = array(
    '#title' => t('Access key (optional)'),
    '#description' => t('For added security, a word can be required to be added to the URL.'),
    '#type' => 'textfield',
    '#size' => 10,
    '#default_value' => variable_get('login_disable_key', 'admin'),
  );
  if (!empty($form['login_disable_key']['#default_value'])) {
    $form['login_disable_key']['#description'] .= '
' . t('The URL to use to log in is: @url', array('@url' => url('user/login') . '?' . $form['login_disable_key']['#default_value']));
  }

  $form['all_users']['login_disable_message'] = array(
    '#title' => t('End-user message when login is disabled'),
    '#description' => t('The message to display to users when login has been disabled.'),
    '#type' => 'textfield',
    '#size' => 80,
    '#default_value' => variable_get('login_disable_message', t('Member access has been temporarily disabled. Please try again later.')),
  );

  $form['individual'] = array(
    '#type' => 'fieldset',
    '#title' => t('Indivdual'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );

  $form['individual']['login_disable_individual'] = array(
    '#type' => 'checkbox',
    '#title' => t('Disable on user profile'),
    '#description' => t('Checking this box allows disabling individual logins on user profile pages.'),
    '#states' => array(
      'unchecked' => array(
        ':input[name="login_disable_is_active"]' => array('checked' => TRUE),
      ),
    ),
  );

  $form = system_settings_form($form);

  return $form;
}

So as I see it, my code should just uncheck a checkbox when the other checkbox is checked. I also want the option that neither is checked.  However, what's happening is that they are working as a toggle, in that if I uncheck one, the other one is being checked, which is prohibiting the third option of neither of them being checked. Can anyone tell me why I'm getting this effect?
Thanks.
Answer: Form API states act in both directions. Suppose you set an element to be unchecked if a condition X is true. Then it gets unchecked when X becomes true, and gets non unchecked (i.e. checked) when X becomes false. See the example code on drupal.org.
You need some custom jQuery in the case.
Answer: Alex is right of course, in that the way the mechanism behaves is that it always toggles. Either it toggles between a TRUE/FALSE of some active state ("enabled", "checked", etc) or it toggles between a TRUE/FALSE of some inactive state ("disabled", "unchecked", etc).
This doesn't mean it's impossible to achieve what you're trying to do though; in order to do that you'll want to use the logical AND modifier by specifying the condition like this:
STATE_WE_WANT_TO_SWITCH_TO => array(
  REMOTE_ELEMENT => array(THE_STATE_THAT_TRIGGERS_THIS => true),
  LOCAL_ELEMENT => array(THE_STATE_WE_WANT_TO_GET_OUT_OF => true),
)

or alternately I think this would work too ... but I haven't tested to see if it goes in a loop.
STATE_WE_WANT_TO_SWITCH_OUT_OF => array(
  REMOTE_ELEMENT => array(THE_STATE_THAT_TRIGGERS_THIS => false),
  LOCAL_ELEMENT => array(THE_STATE_WE_WANT_TO_GET_OUT_OF => true),
)

where
STATE_WE_WANT_TO_SWITCH_TO = the state you want to switch your form element into,
and NOT automatically toggle back out of again when the triggering thing gets switched back.
REMOTE_ELEMENT = the other form element whose state change triggers this action
THE_STATE_THAT_TRIGGERS_THIS = the state that element needs to be in, to trigger this
LOCAL_ELEMENT = this form element itself
THE_STATE_WE_WANT_TO_GET_OUT_OF = the state it needs to be in, in order for this action
to be triggered. Setting this makes the statement evaluate to FALSE once
it's happened once, making this a one-way action.

So in your case this becomes:
'#states' => array(
  'unchecked' => array(
    ':input[name="login_disable_is_active"]' => array('checked' => TRUE),
    ':input[name="login_disable_individual"]' => array('checked' => TRUE),
  ),
),

https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_process_states/7
Comment: I tried this and it did not work for me, sadly :(


Extract rows for change in variable, according to condition

Question: My data includes time stamps of activities completed by athletes over different periods. Each period goes for a maximum of twenty minutes. The corresponding weather conditions are noted.
I want to call out the first occurrence of weather and when conditions change. My question is similar to this question except I want the first occurrence and when a change occurs.
My data is structured as follows:
  df <- data.frame(Time=c("0:00:00","0:01:00","0:02:40","0:12:09",
                        "0:00:00", "0:02:07","0:07:19","0:15:16",
                        "0:00:00", "0:03:00","0:08:40","0:13:29",
                        "0:00:00", "0:02:10","0:08:47","0:17:55"),
                 Athlete = c('Paul', 'Paul', 'Paul', 'Paul',
                             'Paul', 'Paul', 'Paul','Paul',
                            'Joe', 'Joe', 'Joe', 'Joe',
                            'Joe', 'Joe', 'Joe', 'Joe'),
                 Period = c('P1', 'P1', 'P1', 'P1',
                            'P2', 'P2', 'P2', 'P2',
                            'P1', 'P1', 'P1', 'P1',
                            'P2', 'P2', 'P2', 'P2'),
                 Weather = c('Sunny', 'Sunny', 'Sunny', 'Cloudy',
                            'Rain', 'Cloudy', 'Rain', 'Rain',
                            'Rain', 'Sunny', 'Rain', 'Rain',
                            'Sunny', 'Sunny', 'Cloudy', 'Cloudy'))

How do I call out the first occurrence and change in weather, according to each athlete and period?
How do I have time in minutes.seconds? For example: 2.40

I have attempted the code below but this is not returning my anticipated output.
Test <- df[match(unique(df$Weather), df$Weather),]

My anticipated output would be:
Output <- data.frame(Time = c(0.0, 12.09,
                              0.0, 2.07, 7.19,
                              0.0, 3.00, 8.40,
                              0.0, 8.47),
                     Athlete = c('Paul', 'Paul',
                                 'Paul', 'Paul', 'Paul',
                                 'Joe', 'Joe', 'Joe',
                                 'Joe', 'Joe'),
                     Period = c('P1', 'P1',
                                'P2', 'P2', 'P2',
                                'P1', 'P1', 'P1',
                                'P2', 'P2'),
                     Weather = c('Sunny', 'Cloudy',
                                 'Rain', 'Cloudy', 'Rain',
                                 'Rain', 'Sunny', 'Rain',
                                 'Sunny', 'Cloudy'))

From this question, I understand the index of a change in factors within a column can be located, how do I arrange this code to have my desired output?
Thank you.
Comment: `as.difftime(as.character(df$Time), format="%H:%M:%S")` if you are happy to not use lubridate.
Answer: I'd suggest using something like rleid from "data.table". With that you can do:
library(data.table)
as.data.table(df)[, ind := sequence(.N), rleid(Athlete, Period, Weather)][ind == 1]
##        Time Athlete Period Weather ind
##  1: 0:00:00    Paul     P1   Sunny   1
##  2: 0:12:09    Paul     P1  Cloudy   1
##  3: 0:00:00    Paul     P2    Rain   1
##  4: 0:02:07    Paul     P2  Cloudy   1
##  5: 0:07:19    Paul     P2    Rain   1
##  6: 0:00:00     Joe     P1    Rain   1
##  7: 0:03:00     Joe     P1   Sunny   1
##  8: 0:08:40     Joe     P1    Rain   1
##  9: 0:00:00     Joe     P2   Sunny   1
## 10: 0:08:47     Joe     P2  Cloudy   1

Regarding your question about "How do I have time in minutes.seconds? For example: 2.40--that's not really a standard way of expressing time, is it? 0.4 * 60 = 24, so I wouldn't recommend converting it in that manner.
If you wanted those values as numeric values, perhaps you can split them out into separate columns. For that, I'd recommend my "splitstackshape" package.
library(splitstackshape)
cSplit(as.data.table(df)[
  , ind := sequence(.N), rleid(Athlete, Period, Weather)][ind == 1][
    , ind := NULL][], "Time", ":")
##     Athlete Period Weather Time_1 Time_2 Time_3
##  1:    Paul     P1   Sunny      0      0      0
##  2:    Paul     P1  Cloudy      0     12      9
##  3:    Paul     P2    Rain      0      0      0
##  4:    Paul     P2  Cloudy      0      2      7
##  5:    Paul     P2    Rain      0      7     19
##  6:     Joe     P1    Rain      0      0      0
##  7:     Joe     P1   Sunny      0      3      0
##  8:     Joe     P1    Rain      0      8     40
##  9:     Joe     P2   Sunny      0      0      0
## 10:     Joe     P2  Cloudy      0      8     47

"Time_1" would be hours, "Time_2" would be minutes, and "Time_3" would be seconds.
If you really wanted the "Time" column the way you described, you could do that with something like:
df$Time <- as.numeric(sub(":", ".", gsub("^[^:]*:", "", df$Time)))

And then, proceed with the "data.table" approach described earlier.

The "tidyverse" approach (still using rleid from "data.table") might look something like this:
library(tidyverse)
library(data.table)

df %>%
  mutate(ind = rleid(Athlete, Period, Weather)) %>%
  group_by(ind) %>%
  slice(1) %>%
  ungroup() %>%
  select(-ind) %>%
  mutate(Time = as.numeric(sub(":", ".", gsub("^[^:]*:", "", Time))))
# # A tibble: 10 × 4
#     Time Athlete Period Weather
#    <dbl>  <fctr> <fctr>  <fctr>
# 1   0.00    Paul     P1   Sunny
# 2  12.09    Paul     P1  Cloudy
# 3   0.00    Paul     P2    Rain
# 4   2.07    Paul     P2  Cloudy
# 5   7.19    Paul     P2    Rain
# 6   0.00     Joe     P1    Rain
# 7   3.00     Joe     P1   Sunny
# 8   8.40     Joe     P1    Rain
# 9   0.00     Joe     P2   Sunny
# 10  8.47     Joe     P2  Cloudy

Comment: If `Time` was in hours:minutes:seconds:milliseconds, for example, 00:12:09:01, how would I please use your `gsub` code to extract 12.09?
Comment: @user2716568, there would be several ways. Here's one: `x <- "00:12:09:01"; gsub("^.*:(.*:.*):.*$", "\\1", x)`.
Comment: Apologies for another question, but how would I extract use your code to extract the minutes.seconds from a column containing hours.minutes.seconds:milliseconds in a data.frame `df$Time`
Comment: @user2716568, Are you familiar with regular expressions? Regular expressions use parentheses to capture groups. In the comment above, I only captured one group (and returned it with `"\\1"`. You can use multiple groups of parentheses to capture multiple groups of data.
Comment: @user2716568, also, that's why I had suggested the `cSplit` approach to split into multiple columns in one go, and deal with the data from there....
Comment: I am very sorry but I am not familiar with regular expressions. How would I adapt the following code: `df$Time <- as.numeric(sub(":", ".", gsub("^[^:]*:", "", df$Time)))` to now read hours:minutes:seconds:milliseconds?
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/138495/discussion-between-a5c1d2h2i1m1n2o1r2t1-and-user2716568).
Answer: The not super elegant version:
df %>% filter(c(1,diff(as.numeric(Athlete)))!=0 |
              c(1,diff(as.numeric(Weather)))!=0 |
              c(1,diff(as.numeric(Period)))!=0)

Note that this requires the data to be sorted the right way.


How often should I wax my bass?

Question: When I bought my bass, it came with a surface finisher (beeswax). I've been waxing my bass about once every month/month and a half.
Why should I wax my bass and how often is it recommended I do it?
Comment: If you're talking about the body,and neck, which probably have either a polyurethane or cellulose paint job, it's hardly needed. The fingerboard may be a different point, as it's almost certainly raw wood, which could just need a rub down with lemon or such like, to take away the grease/sweat from your fingers.
Comment: What model is this? Like @Tim says, most electric basses shouldn't need this treatment.
Comment: Are you sure you have a bass guitar (tag) and not a double-bass ? In 50 odd years of playing in bands, I've never come across a bass guitarist who waxed his guitar.
Comment: Actually? No, this isn't about my double bass, it's about my electric six-string bass
Comment: It's a Warwick NT Thumb 6
Comment: Depends how fast the hair grows!
Answer: Having done some homework, your bass has no lacquer or paint as a finish - it's natural wood. As such, every couple of months it needs a feed/clean and beeswax is the stuff. Not heavily applied, and well rubbed off after, it puts a barrier on to help stop sweat etc., being absorbed into the wood. If you like a well-used look to your guitar, don't bother.(relic'd is in right now !) but to keep it pristine it needs the treatment. Apparently the instructions should have come with the new bass.
Answer: http://www.warwick.de/warwick/data/Warwick.de/Technical%20PDF/Manuals/WWBassManual_en_2013.pdf:

Natural Oil Finish:
  Here you can use the included beeswax. Apply the beeswax with a polishing cloth using circular movements. After applying, wait 2 to 3 minutes and then remove the excess with a dry polishing cloth. The beeswax should be applied a minimum of two times per year, more depending on how frequently theinstrument is played. A more frequent application of beeswax will keep your instrument looking great, as it ages over time.
Answer: Tim is right. It's just cosmetic - if you like the look, fine. But I have basses that have seen decades of frequent use that I haven't polished and they're fine.
Guitar repair people will tell you different, I imagine. But they earn their money that way.
Comment: I do not agree. Warwick builds expensive basses with a lot of attention to the woodwork. You should keep the surface of the wood sealed (especially the neck) to prevent deformation of the wood due to humidity changes .

How often should I wax my bass?


Sistema multi-linguagem

Question: Tenho um website e gostaria de implementar um sistema de multi-language. Tenho algumas duvidas a nível de boas práticas.
Queria ter apenas um domínio ****.com. Penso que isto me obrigaria a utilizar sistemas implementados em php, ou outras linguagens para comunicar com o servidor, certo?
A minha ideia seria ter uma variável global (não sei se existe algo deste género) e ao carregar na linguagem pretendida isso iria alterar a variável global e sempre que abrisse uma nova pagina do site ele assumiria a nova linguagem.
Seria esta uma boa prática?
Answer: Tem alguns recursos que você pode detectar o idioma pelo IP, caso seja a primeira visita do usuário ao seu site. (Esse tipo de serviço pode ser instável, existe outros pagos que são bem mais precisos e confiáveis.)
E armazenar o idioma em um Cookie. Assim toda a vez que o usuário entrar no teu site, você obtém essa informação:
$padrao = 'pt-BR';

if (empty($_COOKIE['lang'])){
    // Receba o idioma através de um formulário $_POST['lang']
    // Ou pela URL http://dominio.com/?lang=pt-BR
    // Ou busque um serviço de localização externo e baseie o idioma na localização do usuário

    $lang = $_POST['lang'] || $_GET['lang'] || buscaIdioma();

    $expire = 10 * 365 * 24 * 60 * 60; // 10 anos, ou nunca

    setcookie('lang', $lang, $expire);

    define(LANG, $lang);
} else {
    define(LANG, $_COOKIE['lang']);
}

Como definir qual idioma o usuário está usando é o mais simples. A parte mais complicada será fazer a tradução do conteúdo.
Comment: Obrigado pela sua ajuda.
Answer: A sua pergunta é relevante e a mesma, para mim, situa-se mais quanto à forma e não quanto ao como.
Eu coloquei uma pergunta que lhe recomendo a leitura:
MVC e alteração dinâmica de idioma
Posso falar por experiência que devemos de utilizar uma framework que implemente um MVC para qualquer um dos nossos projectos em PHP. Não irei colocar aqui os motivos pois ultrapassa os escopo da pergunta, mas é certo que alguns já entregam alguma lógica para controlo de idiomas.
Para quem, como eu, que profissionalmente utiliza uma framework própria e que implementa um MVC próprio e por várias razões é forçado a encontrar mecanismos para resolver vários problemas. O controlo de idiomas é um problema a ter sempre em conta.
Obter o idioma do browser.
è uma prática a adoptar. Desta forma estamos já a seguir definições que o próprio browser com mecanismos próprios assegura e que nos entrega de bandeja.
No entanto isso pode não ser suficiente para alguns projectos sendo que e novamente por experiência é desejado uma alteração de idioma funcional durante a utilização do mesmo, ou porque alguém tranca o acesso às definições de um browser por exemplo. Mas por norma obter inicilamente o idioma a partir do browser é claramente o caminho a tomar.
A partir desse ponto, penso que a manipulação de uma URL amigável para definir um idioma é uma solução simples, eficáz e muito direta num projecto PHP e não só.
acesso normal:
www.meuprojecto.com/[controlador]/[acção]/[parametros]
obtem as configurações do browser

acesso que afeta o idoma:
www.meuprojeto.com/pt/[controlador]/[acção]/[parametros]
força o idioma a ser pt "por exemplo"

Com esta abordagem os links são espalhados pelo projecto e a qualquer momento pode alterar o idioma.
A metodologia para guardar o idioma seleccionado depende da sua solução mas a gravação em COOKIE pode ser uma delas.

Sistema multi-linguagem


Compile java code at runtime

Question: I have a java class that is used to perform login action using selenium. There are currently 10+ different login types and as such there is a lot of if else involved which looks bad and is not efficient.
Eg:
if (logintype == 1 )
{
 driver.findElement(By.id("username")).clear();
                 driver.findElement(By.id("username")).sendKeys(username);
                 driver.findElement(By.id("password")).clear();
                 driver.findElement(By.id("password")).sendKeys(password);
                 driver.findElement(By.id("signin")).click();
}
else if (logintype ==2 )
{
 driver.findElement(By.id("username")).clear();
                 driver.findElement(By.id("username")).sendKeys(username);
                 driver.findElement(By.id("password")).clear();
                 driver.findElement(By.id("password")).sendKeys(password);
                 driver.findElement(By.id("signin")).click();
}
...........
...........

Other than code not being efficient the new code needs to be written, pushed and the server needs to be restarted every time a new login module is added.
I wanted to see if i can get the logic for login can be stored in db and if it can be compiled at runtime. I found groovy shell but i dont know how to get the results back to my class file. Also running groovy shell would require a lot of code changes. Is it  possible in java
public class ExecuteAuth implements Runnable{

    private WebDriver driver;

    driver = new FirefoxDriver(firefoxBinary, profile, cap);
    driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
    driver.manage().window().maximize();

    //MongoDB code
    DBCursor dbObjects = loginCollection.find();

    while (dbObjects.hasNext()) {
            DBObject dbObject = dbObjects.next();
            loginModule.add(new LoginModule((BasicDBObject) dbObject));

            String loginType = (String) dbObject.get("loginType")
            String script;
            if (loginType.equals("1")) {
                script = (String) dbObject.get("script")
            }
    }

    GroovyShell shell = new GroovyShell ();

    shell.evaluate(script);

    RUN REST OF THE LOGIN LOGIC AFTER THE CODE IS EVALUATED
}

Comment: If you're going this route, I'd look at [Geb](http://gebish.org) and particularly Page Objects.
Comment: Just to clarify: you want to re-compile an existing class fo your java-program and reload it, all while the program is running?
Comment: Why not make the login process a service that is independent of the rest of the application? Then it could be modified and re-deployed independently of the main application
Answer: I strongly advise against that approach. You are opening a door to bad code be injected in your application. Another way could be upload to your server your new jars and take advantage of class loader to load classes at runtime:

How should I load Jars dynamically at runtime?

Also, you have alternatives to avoid if-else's: usage of interfaces and factory methods are the way to go, imho. And put your login's implementations on different classes implementing a Login interface, for example.
Factory method design pattern:

http://www.oodesign.com/factory-method-pattern.html
http://www.javaworld.com/article/2077386/learn-java/factory-methods.html

Compile java code at runtime


How to call an enum from another class?

Question: I am currently working on a grails project. I've created an enum located on a certain project folder, and wanted to access it from a class located on another project folder.
My enum looks something like this:
public enum Options {

OPTION_1("Option_1"),
OPTION_2("Option_2"),
OPTION_3("Option_3");

final String option;

Options(String option) {
    this.option = option;
}

}
Now, I am having a problem in calling that enum from a certain class in my application. For example:
Response{
option = new Option.OPTION_1("Option_1") //not sure on how to call an enum
}

But what I wanted to do here is to assign the enum to the property option in the Response {} section..
How will I properly do that?
Help please?
Thanks.
Answer: Enums are predefined objects, it will have a private constructor, You can not create a new instance with new. You just need to call Option.OPTION_1;
Response{
option = Option.OPTION_1;
}

Comment: @ Rp- : your comment said not to use new. But the code had. I removed the 'new'. Hope that is fine.
Comment: Yeah.. Copied the code from OP's question, Thanks for the edit
Answer: You just need to reference it as Options.OPTION_1 there's no new on enums.
Option option = Options.OPTION_1;

Answer: You cannot instantiate an enum object, the only instances that are there are defined by you in the enum class.
So the correct way is:
Response {
    option = Options.OPTION_1;
}

Answer: You cannot create a new instance of an enum. There is no need to because it can hold only fixed number of values. So option = new Option.OPTION_1("Option_1") will do.
Answer: Should work.
Response{
def option = Option.OPTION_1;
}

related link Enums in groovy
Answer: Not aware of the grails part in this, but your usage of enum seems to be incorrect
If you have an enum as
public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY
}

You can access individual value using Day.MONDAY, Day.SUNDAY, etc.
Please check the java doc.
Comment: I think grails and java do same way in declaring enums, since grails is based in java..

How to call an enum from another class?


Is this notation standard?

Question: In a book I'm reading, "Sets: An introduction, by M.D.Potter", the symbol $\iota$ is used to mean "a definite", so that:
$\iota ! y(x\in y \iff \Phi(x))=\{x:\Phi(x)\}$
is read as $\{x:\Phi(x)\}$ is a definite unique $y$ such that $x\in y\iff \Phi(x)$, in other words "the unique $Y$ such that...".
Is this notation standard? or is there another symbol more often used?
Comment: I'm not familiar with this notation ($\iota$ seems to be used as the imaginary unit by some to avoid confusion with index $i$). Here $\iota!$ seems to introduce an universal property. Maybe you'll find some notation related to that term.
Comment: It's meant to mean "the unique"
Comment: Universal property is the same in fancier ("the object uniquely defined by $\ldots$ up to some isomorphy")
Comment: Possibly related? http://math.stackexchange.com/questions/852771/element-of-a-singleton-set-with-one-element-notation
Comment: It would be quite handy if it were more standard, because it sometimes replaces verbiage with tidy calculation. For example, if $f: A \to B$ is a surjection, and $g: A \to C$ is any function such that $f(x) = f(x')$ implies $g(x) = g(x')$, one can write $h(y) = \iota(g(f^{-1}(y))$ as an explicit formula for the unique function $h: B \to C$ such that $g = h \circ f$, and prove the latter equation by a tidy calculation involving the identity $\iota\{g(x)\} = g(x)$.
Answer: Yes, it is the standard (but not commonly used in textbooks of mathematical logic) symbol for Definite descriptions.
It was introduced by Bertrand Russell in his fundamental analysis of definite descriptions.
The reading of :

$\iota x \ \phi(x)$

is simply :

"the (unique) object $x$ such that $\phi(x)$", or "the (unique) object such that $\phi$ holds of it."

Thus : $\iota ! \ y \ (x \in y \Leftrightarrow \Phi(x))$ (but $!$ is redundant) means, as you say :

"the unique $y$ such that $x \in y$ iff $\Phi(x)$ holds".
Comment: This notation appears more commonly in logic books about linguistics, though.

Is this notation standard?


Proving an interesting basic inequality

Question: I was reading an old paper in french where the authors claim that the following "obvious and natural inequality" holds. If $a_1,\ldots,a_n>0$ are all positive numbers, then
$$\sum\limits_{j=1}^{n} a_j\leq \left(\, \sum\limits_{j=1}^{n} \frac{1}{a_j} \right)^{n-1}\left(\, \prod\limits_{k=1}^{n}  a_k\right).$$
I managed to prove this by induction, but I'm not satisfied at all by that approach. Is there a nice way to prove this directly? (using basic inequalities, or some convexity argument for example). Also, is there any reason for this inequality to be really "obvious" or "natural"?
Comment: It is a version of **Sierpinski inequality**. See this [recent question](https://math.stackexchange.com/q/4443889/305862)
Answer: Note that the asserted inequality is equivalent to
$$
\sum_{j=1}^n \prod_{\substack{1\le k\le n\\k\ne j}} \frac1{a_k} \le \biggl( \sum_{j=1}^{n} \frac{1}{a_j} \biggr)^{n-1};
$$
but this is indeed "obvious" because the right-hand side, when expanded out, becomes a sum of $n^{n-1}$ positive terms, $n$ of which are the ones on the left-hand side. (Indeed each summand on the left appears multiple times in the expanded version of the right, so one could even improve the inequality by a factor like $(n-1)!$.)
Comment: See my comment above.

Proving an interesting basic inequality


How to use variable as range upper bound

Question: I have the following problem in a bash script. I'm trying to use a variable N as the upper bound in a simple range, like
#!/bin/bash

N=10

for n in {1..$N};
do
    echo $n
done;

However, instead of displaying each number in the loop, the code above literally displays {1..10}. If I change $N to its value, i.e. 10, things work as expected. How can I overcome this and use the variable as the upper limit of the range?
Comment: This site appears to have an answer for you.  https://www.cyberciti.biz/faq/unix-linux-iterate-over-a-variable-range-of-numbers-in-bash/
Comment: My bad, thanks for pointing out the dupe
Answer: You can't do this, instead, do that :
n=10
for ((i=0; i<=n; i++)); do
    echo $i
done

or :
n=10
for i in $(seq 0 $n); do
    echo $i
done


Floor function with Multiplier

Question: I understand this: $f(x) = \lfloor x-4 \rfloor$
but how do you handle this $f(x) = 4\cdot\lfloor x-4 \rfloor$  . Do you distribute the $4$ then floor?
and the brackets denote floor.
Thank you
Comment: You can simplify it to $4(\lfloor x\rfloor - 4) = 4\lfloor x\rfloor - 16$.
Comment: No, there is no further simplification. I suggest playing with http://www.desmos.com
Comment: As it stands, your function will be a staircase, with the heights of the stairs $4$, and the width $1$.  The function $g(x)= \lfloor 4x - 16 \rfloor$ has stairs of height $1$ and width $1/4$.
Comment: I'm not sure exactly what you mean by 'handle'. If you want to know the order of operations to evaluate the expression you first subtract 4 from the input. Then you evaluate the floor function by selecting the greastest integer less than or equal to the resulting value. Finally you multiply that by 4.
Comment: Ok so Joshua and mjw that does look like you are distributing the 4 which makes perfect sense. Thank you everyone!
Comment: Are you asking about $4[x-4]$ or $[4x -4]$.  $[x +n] = [x]+ n$ con be easily seen it's straight rounding off integers but $[4x] = \begin{cases} 4[x]\\4[x] + 1\\4[x]+2\\4[x]+3\end{cases}$ depending and whether which of the following cases is true.  There is an $n$ so that $n \le x < n+\frac 14; n+\frac 14 \le x < n +\frac 12; n+\frac 12 \le x < n+ \frac 34;$ or $n+\frac 34 \le x < n + 1$.
Answer: Note that for every $x$ there is a unique $n$ so that $n \le x < n+1$.
And that means there is also a unique $r: 0 \le r < 1$ so that $x = n + r$.
$\lfloor x\rfloor = n$ and $\{x\} = x -\lfloor x\rfloor = r$.
And we always have $x = \lfloor x\rfloor + \{x\}$.
....
Okay get that under our belt.
.....
For any integer $n$ we have
$\lfloor x- n\rfloor= \lfloor x \rfloor -n$ because......
$x-n = \lfloor x \rfloor +\{x\} - n= (\lfloor x \rfloor  - n) + +\{x\}$ and $0\le \{x\} < 1$ and $(\lfloor x \rfloor  - n)$ is an integer so
$(\lfloor x \rfloor  - n)\le (\lfloor x \rfloor  - n) +\{x\} =x-n < (\lfloor x \rfloor  - n)+1$ so
$\lfloor x -n\rfloor =\lfloor x \rfloor  - n$.
.....
So $4\lfloor x -4\rfloor= 4(\lfloor x \rfloor  - 4)=4\lfloor x \rfloor -16$

Floor function with Multiplier


Incluir ícones nos botões do modal

Question: Boa tarde, estou criando um modal que está já está com todas as funcionalidades perfeitas, porém preciso incluir nos botões os ícones de aceito e cancelar pra deixar mais didático para o usuário, porém em jquery não sei como fazer isso. O código que estou utilizando para chamar o modal é este, não sei se existe outra maneira de fazer isso tbm.
<code>$('#div_dialog_MostrarTexto').dialog({
    open: function(event, ui) {
        $(this).parents(".ui-dialog:first").find(".ui-dialog-titlebar-close").remove();
    },
    resizable: false,
    minHeight: 600,
    minWidth: 650,
    maxHeight: 600,
    modal: true,
    autoOpen: true,
    title: titulo,
    position: { my: 'top', at: 'top' },
    overflow: scroll,
    buttons: [
        {
            text: $('#doc_aceita_' + dadosDocumentos[idDocumento]).val(),
            disabled: false,
            image: "../img/confirmar.jpg",
            click: function() {
                aceitou(idDocumento);
            }
        },
        {
            text: $('#doc_recusa_' + dadosDocumentos[idDocumento]).val(),
            disabled: false,
            image: "../img/cancelar.jpg",
            click: function() {
                recusou(idDocumento);
            }
        },
    ]
});
</code>
Comment: Você pode criar um botão no HTML e personalizar o background com CSS, não precisaria de jquery.
Answer: Porque não trabalha com ícones do jquery?
Se for com ícones segue, vou pesquisar sobre imagens.

<code>$('#div_dialog_MostrarTexto').dialog({
    open: function(event, ui) {
        $(this).parents(".ui-dialog:first").find(".ui-dialog-titlebar-close").remove();
    },
    resizable: false,
    minHeight: 600,
    minWidth: 650,
    maxHeight: 600,
    modal: true,
    autoOpen: true,
    title: titulo,
    position: { my: 'top', at: 'top' },
    overflow: scroll,
    buttons: [
        {
            text: $('#doc_aceita_' + dadosDocumentos[idDocumento]).val(),
            disabled: false,
            icons: { primary: 'ui-icon-check' },
            click: function() {
                aceitou(idDocumento);
            }
        },
        {
            text: $('#doc_recusa_' + dadosDocumentos[idDocumento]).val(),
            disabled: false,
            icons: { primary: 'ui-icon-close' },
            click: function() {
                recusou(idDocumento);
            }
        },
    ]
});</code>
Comment: Acredito que ele precise de uma variedade ícones maior, com outras cores e etc.
Comment: Então trabalhe com fontawesome, ficar fazendo imagens é trabalhoso... ou crie diversos ícones, compile e tenha personalizado.
Comment: Muito obrigado, resolveu o meu problema. No meu caso eu não precisaria de mais icones não, as opções sempre serão de sim ou não, porém com o texto de cada uma diferente a cada vez que abrir, agradeço a atenção de ambos!

Incluir ícones nos botões do modal


Crystal Reports MVVM Data Source

Question: I have an MVVM application and would like to add Crystal Reports. I have a ViewModel of PatientList and would Like to Bind the Report to an Observable collection of Patients in the ViewModel. the Collection is not appearing in the data sources window.
Answer: I guess you are refering to Crystal-Reports datasource window right?
If so - I think you will never find the ObservableCollection there (and I don't know if you can have CR observe the collection) but on the document-class in Crystal-Report you should have something like SetDatasource (I don't have the newest version anymore and CR changed this from time to time) - in the last version I know you had to cast to IEnumerable<...> in some cases (DataTable) so look out for this too.

Crystal Reports MVVM Data Source


Write to Organic groups

Question: I need option like on Facebook groups to publish something in group, and then user comment that.
Now i have only comment form which users use to post in groups.
I need something like posting nodes, but in group.
Is this possible?
Thank you!
Answer: You can allow any content type as content in the group. So if you want to set post in group you can edit post content type and make as group content.
When you edit the post content type usign admin>structure>content types>post you will find the following options to add this content type as group option.

After doing this when you  visit post create page you will find group select box. From here you can select the group.
Comment: And then how do i show that node in group? I created content type, added node, but now i dont know how to insert it in group? Thank you!
Comment: if you are using page manager, panel and organic group module then there will be page called **node_view** you have to enable it. flush cache and visit the group node
Comment: And one more thing there will be view named **OG content** you can view it and pass the group id to view the output
Comment: Hi, where will node_view appear? Yes i see OG Content, should i call it in node--group or? Thank you!
Comment: in **admin/structure/pages** you will find node_view it contains all the things in panel like latest posts, members list, add content link etc..
Comment: Yes, i enabled node_view and flushed cache. But still there is no content in group node. One more thing, i dont know how to implement view OG content in group?
Comment: Ok, its working now. I associate content type to group and i displayed nodes in group.

But when i create node in content type, i want to redirect user to group.

Not to node that is just created.

I need only this.

Thank you!
Comment: You can implement custom form alter and redirect to group node..and if u find helpful please accept the answer and upvote..

Write to Organic groups


Picker não seleciona manualmente

Question: Tenho este componente PickerUF, que exibe a lista dos estados.
import React, { Component } from "react";
import { StyleSheet, Platform } from "react-native";

import { Picker } from 'native-base'

export default class PickerUF extends Component {
    constructor(props) {
        super(props);
    }

    state = {
        selectedUF: this.props.value
    };

    render() {
        const pickerItems = UFList.map(uf => {
            return (
                <Picker.Item key={uf.sigla} label={uf.sigla} value={uf.sigla} />
            );
        });

        if (Platform.OS === 'android') {
            pickerItems.unshift(<Picker.Item key='select' label="Estado" />)
        }
        return (

            <Picker
                style={[styles.field, this.props.style]}
                iosHeader="Estado"
                mode="dropdown"
                selectedValue={this.props.value}
                onValueChange={(value) => {
                    this.setState({ selectedUF: value });
                }}
            >
                {pickerItems}
            </Picker>
        );
    }
}
const UFList = [
    { sigla: 'AC', estado: 'Acre' }
    , { sigla: 'AL', estado: 'Alagoas' }
    , { sigla: 'AP', estado: 'Amapá' }
    , { sigla: 'AM', estado: 'Amazonas' }
    , { sigla: 'BA', estado: 'Bahia' }
    , { sigla: 'CE', estado: 'Ceará' }
    , { sigla: 'DF', estado: 'Distrito Federal' }
    , { sigla: 'ES', estado: 'Espírito Santo' }
    , { sigla: 'GO', estado: 'Goiás' }
    , { sigla: 'MA', estado: 'Maranhão' }
    , { sigla: 'MT', estado: 'Mato Grosso' }
    , { sigla: 'MS', estado: 'Mato Grosso do Sul' }
    , { sigla: 'MG', estado: 'Minas Gerais' }
    , { sigla: 'PA', estado: 'Pará' }
    , { sigla: 'PB', estado: 'Paraíba' }
    , { sigla: 'PR', estado: 'Paraná' }
    , { sigla: 'PE', estado: 'Pernambuco' }
    , { sigla: 'PI', estado: 'Piauí' }
    , { sigla: 'RJ', estado: 'Rio de Janeiro' }
    , { sigla: 'RN', estado: 'Rio Grande do Norte' }
    , { sigla: 'RS', estado: 'Rio Grande do Sul' }
    , { sigla: 'RO', estado: 'Rondônia' }
    , { sigla: 'RR', estado: 'Roraima' }
    , { sigla: 'SC', estado: 'Santa Catarina' }
    , { sigla: 'SP', estado: 'São Paulo' }
    , { sigla: 'SE', estado: 'Sergipe' }
    , { sigla: 'TO', estado: 'Tocantins' }
]
const styles = StyleSheet.create({
    field: {
        width: '100%'
    }
});

Este componente é usado desta forma
<PickerUF
    value={this.state.uf}
    ref={'UF'} />

Neste caso, state.uf é carregado automaticamente quando busco pelo CEP. Isso está funcionando muito bem.
O problema é que não consigo alterar o estado selecionado.
Fazendo a alteração no PickerUF de selectedValue={this.props.value} para selectedValue={this.state.selectedUF} só consigo selecionar manualmente.
O que eu preciso alterar para poder fazer a seleção manualmente ou automaticamente?
Answer: Faz o seguinte: Passa uma função chamada onValueChange no <PickerUF value={this.state.uf} ref={'UF'} onValueChange={this.onValueChange} />. Nessa função você vai receber o value e vai alterar o this.state.uf.
onValueChange = (value) => {
  this.setState({uf: value})
}

No component PickerUF, você muda o onValueChange para onValueChange={this.props.onValueChange}.
Você não precisa passar a responsabilidade para o component filho, ele continua sendo apenas um component que exibe e você sobe um nível para tratar as alterações.
Espero que te ajude!

Picker não seleciona manualmente


ClickListener into BaseAdapter error

Question: i have the seguent cose into a baseAdapter...
final View finalConvertView1 = convertView;
    holder.buttonEliminaDalCarrello.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View view) {
                        try {
                            Log.w(null, "Cliccato sull'elemento del carrello " + position);
                            SingletonCarrello singletonCarrello = SingletonCarrello.getIstance();
                            Double prezzo = singletonCarrello.listaProdotti.get(position).getQuantita()*singletonCarrello.listaProdotti.get(position).getPrezzo();
                            singletonCarrello.listaProdotti.remove(position);
                            singletonCarrello.prezzoTotale = singletonCarrello.prezzoTotale - prezzo;
                            TextView textView = (TextView) finalConvertView1.findViewById(R.id.textViewPrezzoTotale);
                            Log.w(null, "Prezzo totale del carrello: " + singletonCarrello.prezzoTotale);
                            /*FragmentCarrello fragment = new FragmentCarrello();
                            fragment.aggiornaPrezzoCarrello();
                            fragment.aggiornaListaCarrello();*/
                            textView.setText("Prezzo totale: " + singletonCarrello.prezzoTotale + euro);
                            listViewCarrello.setAdapter(new CustomListAdapterCarrello(finalConvertView1.getContext(), singletonCarrello.listaProdotti));
                        }
                        catch (Exception e) {
                            Log.w(null, "Entrato nell'eccezzione dell'onclick Carrello: "+e.getMessage());
                        }
                    }
                });

When i try to run the project it find me a javaNullPointerExceptin in
textView.setText("Prezzo totale: " + singletonCarrello.prezzoTotale + euro);

can anyone explain me why? thanks in advance
Comment: Apparently `textView` is `null`.
Comment: no, euro is a string that i implement before
Answer: this is the problem
singletonCarrello.prezzoTotale = singletonCarrello.prezzoTotale - prezzo;

it's like 3= 3-1
Comment: Like `singletonCarrello.prezzoTotale -= 1`
Comment: Huh? That's not how assignment works. a = a - 1 is totally valid.

ClickListener into BaseAdapter error


mongod: automatically initiate replica-set

Question: Currently I manually execute the rs.initiate() in the shell after starting a mongo primary or secondary machine to join the replica-set "farm". Doesn't the /etc/mongodb.conf allow me to define the initiate command to do this automatically when starting the service after re-booting? - Thanks for help
Answer: I don't think so. But you shouldn't need to initiate every time you reboot. Are you shutting down all of your nodes at the same time? If you leave one up, and the replSet is set in the config file, others should rejoin automatically: http://mongodb.org/display/DOCS/File+Based+Configuration
Comment: You are right, it's rejoined :-)


Should the RMSE of the unrestricted (VAR) model for a time series that is being Granger caused by another be lesser than its restricted counterpart?

Question: I have a couple of time series, say, T1 and T2. I have established (using the grangercausalitytest library of Statsmodels in Python) that T1 Granger-causes T2 at 10% significance for lags 4 and 5. I now want to know whether I can validate the result by using VAR (unrestricted model).
Going by the definition of Granger causality mentioned in the book "Introduction to Modern Time Series Analysis", for 2 time series, "x" and "y",

...if future values of y can be better predicted, i.e. with a smaller
forecast error variance, if current and past values of x are used,

I should get less RMSE for the VAR model as compared to the Autoregression model with only T2. (I'm using ARIMA(p,0,0) for autoregression with p = 4,5 as the Granger - cause occurs at these lags)
My first question is my interpretation correct?
If not, why not? And if that is the case, the RMSE of what should I be comparing? I ask this question because T1 Granger-causes T2 at lags 4 and 5. Should I take the RMSE (for both VAR and Autoregression models) after lags of 4?
Also, should there be any other caveats?
Answer: Let me denote the first time series $\{Y_1\}$ and the second one $\{Y_2\}$.
Interpretation
Your interpretation is correct.
RMSE of what?
You may compare the RMSE of one-step ahead forecasts from the AR(p) model for $\{Y_2\}$ with one of the ARDL(p,p) model for $\{Y_2\}$ for either $p=4$ or $p=5$. The ARDL(p,p) model corresponds to the equation for $\{Y_2\}$ from the VAR(p) model that includes both $\{Y_1\}$ and $\{Y_2\}$. I think RMSE of $h$-step ahead forecast for $h>1$ would also work but may be a less common choice.
For more details on the logic of comparing AR and ARDL models in the context of Granger causality, see this.