Secondary DNS server cannot communicate with primary DNS server (but vise versa is possible)

Question: Our secondary DNS server (Windows Server 2003) cannot see or connect to our primary DNS server (Windows Server 2008). (We can ICMP by name, but we cannot add in the DNS Manager GUI.) But our primary DNS server can talk to our secondary DNS server. We are trying to troubleshoot but are at a loss for what to do next. Here is what we know:

Both servers have entries on the primary DNS server.
In DNS Manager, when we click on actions and then connect to DNS server, we can connect from primary to secondary but not the other way around.

Any ideas of how we might further troubleshoot this issue? I'd be happy to provide as much more information as I am able.
Thanks!
Comment: `cannot see or connect to our primary DNS server` - start by getting more precise about what cannot see means.  Do you mean it lacks ICMP connectivity?  Does it mean you can't see it in the GUI, or what.  If you are not sure use wireshark.
Comment: @Zoredache Great question. We can ICMP by name. We cannot add in the DNS Manager GUI.
Comment: I assume you have looked at your Windows Firewall then?  Try disabling your firewalls?  If that fixes things, then go back and figure out what is being clocked.  Then un-block it.
Comment: @Zoredache We'll check and give it a try. Thanks. One minute.
Comment: @Zoredache The firewall is off on both. When we try connecting with just server name, we get server unavailable. When we try fqdn or ip address, we get access denied. (I'll have to do more work on this tonight when I get home.)
Answer: I think it's a Windows authentication problem. You're trying to use an MMC console to access one server from another server where the two servers don't share a centralized user account database. If you want to be able to access one server from the other you'll need to configure a common user account and password on both servers and launch the DNS management console with that user account.
I've tested this on both of my DNS servers and it proves out. The only thing I can't explain is why you can't connect from the older OS to the newer OS but can from the newer OS to the older OS.
Both of my servers are W2K8R2 and when I changed the Administrator password on one server I got access denied when trying to add the other server to the DNS management console. When the Administrator password on both servers matches I can successfully add and connect to each server from each server in the DNS management console.
Note that in the case where I get access denied because of a password mismatch, it DOES NOT prevent DNS record additions and deletions from propagating from the Primary to the Secondary server.
Comment: Thank you for the response! I am unfortunately cut off from the servers tonight, but I will report back the results just as soon as I can gain access to these servers again (tomorrow or the next day). I will also be sure to accept this answer if it leads to our discovery of the issue. Thanks again!
Comment: There was a bit more going on, but the authentication allowed the two dns servers to connect. Thanks!
Comment: Glad to help...


Multiple Imputation by Chained Equations (MICE) Explained

Question: I have seen Multiple Imputation by Chained Equations (MICE) used as a missing data handling method. Is anyone able to provide a simple explanation of how MICE works?
Answer: MICE is a multiple imputation method used to replace missing data values in a data set under certain assumptions about the data missingness mechanism (e.g., the data are missing at random, the data are missing completely at random).
If you start out with a data set which includes missing values in one or more of its variables, you can create multiple copies of this data set - for example, you can create 5 copies of the original data set - and replace the missing data values in each copy using the MICE procedure. You can then:

Analyze the 5 complete data set copies using your intended statistical analysis;
Combine (or pool) the results of these complete data analyses;
Report the combined result.

The rules for combining (or pooling) results are specific to the results being combined and were initially developed by Rubin.
Figure 1 in the article Multiple Imputation by Chained Equations in Praxis: Guidelines and Review by Jesper N. Wulff and Linda Ejlskov is visually summarizes the process described above: https://vbn.aau.dk/en/publications/multiple-imputation-by-chained-equations-in-praxis-guidelines-and.
How does MICE replace the missing data values in each copy of the original data set?
The article Multiple Imputation by Chained Equations: What is it and how does it work? by Azur et al. explains what happens underneath the MICE hood with a nice example: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3074241/
In the example, the author articles start out with a simple data set which includes only 3 variables: age, income, and gender.  All 3 have at least some missing values.
To apply MICE, create 5 copies (say) of this simple data set and cycle multiple times through the steps below for each copy:
Step 1: Replace (or impute) the missing values in each variable with temporary "place holder" values derived solely from the non-missing values available for that variable. For example, replace the missing age value with the mean age value observed in the data, replace the missing income values with the mean income value observed in the data, etc.
Step 2  Set back to missing the "place holder" imputations for the age variable only. This way, the current data copy contains missing values for age, but not for income and gender.
Step 3: Regress age on income and gender via a linear regression model (though it is possible to also regress age on only one of these variables); to be able to fit the model to the current data copy, drop all the records where age is missing during the model fitting process. In this model, age is the dependent variable and income and gender are the independent variables.
Step 4 Use the fitted regression model in the previous step to predict the missing age values. (When age will be subsequently used as an independent variable in the regression models for other variables, both the observed values of age and these predicted values will be used.) The article doesn't make it clear that a random component should be added to these predictions.
Step 5: Repeat Steps 2–4 separately for each variable that has missing data, namely income and gender.
Cycling through Steps 1–5 once for each of the variables age, income and gender constitutes one cycle.  At the end of this cycle, all of the missing values in age, income an gender will have been replaced with predictions from regression models that reflect the relationships observed in the data between these variables.
As stated earlier, MICE requires that we cycle through Steps 1–5 for a number of cycles, with the imputations of the missing values of age, income and gender being updated at each subsequent cycle.
We can specify in advance the number of cycles to be performed (e.g., 10 cycles) – once we reach the final cycle, we retain the imputed values corresponding to that final cycle, obtaining an imputed data set (i.e., a data set where all missing values in age, gender and income were replaced with imputed data values obtained via an iterative procedure).
To sum up, MICE imputes missing values in the variables of a data set by using a divide and conquer approach – in other words, by focusing on one variable at a time. Once the focus is placed on one variable, MICE uses all the other variables in the data set (or a sensibly chosen subset of these variables) to predict missingness in that variable. The prediction is based on a regression model, with the form of the model depending on the nature of the focus variable (e.g., age and income will require linear regression models for prediction of their missing values, but gender will require a logistic regression model).
Comment: Hey Isabella. Thanks for a really wonderful explanation! Really well written. Just to be clear, the only source of variation is the noise component added to the predictions in step 4?
Comment: Thanks @isabella-ghement, your comment in Step 4 about the Azur et al article not making clear that a random component needs to be added was the required lightbulb appearing above my head.
Comment: This is a great answer, +1


NFL Combine Worst Performances

Question: I am attempting to clean a data set of NFL Combine performances; because some values of the data set are physically impossible, I would like to know the best and worst performances in the combine (to eliminate data that is not within this range). Obtaining data for the best performances in the combine is simple. Obtaining data for the worst performances in the combine, however, has proven difficult; I have searched through multiple websites with no luck.
I would like to know the following:

What is the slowest twenty-yard shuttle in the NFL Combine of all time, and by who?
What is the shortest vertical in the NFL Combine of all time, and by who?
What is the shortest broad jump in the NFL Combine of all time, and by who?
Answer: After some digging, I manually searched through Pro Football Reference.
According to the site:

The slowest twenty-yard shuttle in the NFL Combine is 5.56 seconds by Isaiah Thompson in 2011.

The shortest vertical in the NFL Combine is 17.5 inches by Josue Matias in 2015.

The shortest broad jump in the NFL Combine is 74 inches by Stefon Wheeler in 2006.

NFL Combine Worst Performances


github3.py Repository class is there a way to "Create" a branch?

Question: Using version 1.0.0a4 of the github3.py library.
I am trying to create a new file in the repository on a new branch.
Assumption:  gh is an authenticated object.
repo = gh.repository('User','Repo')
repo.create_file(path='NewFile',message='Commit Message',content='File Content', branch='NewBranch')

The call to create_file fails to create the 'NewFile' and the 'NewBranch'.
If I do the following the file is created ok on the "Default" branch as I would expect.
repo.create_file(path='NewFile',message='Commit Message',content='File Content')

I was sure that the first form of the 'create_file' did in fact create the branch once, but I'm unsure why it isn't happening now.  Is it not a fair expectation that the 'branch' would be created by this call?  I haven't found another API that would create a branch.
Comment: Ok, looks like the create_file doesn't support the creation of the branches.  Needed to use the `create_ref` method and give it the new **reference** `refs/heads/new_branch` and then it was created.  I can now use that new branch and create the new file there.
Comment: Since "The call to create_file fails to create the 'NewFile' and the 'NewBranch'" could you add the stack trace?
Comment: @Hipny traceback? But, yes, anyway
Comment: The call itself doesn't fail, that seems to work just fine, but the actions expected don't happen.  I don't seem to get much of a helpful error back from github3.py as well.
Answer: Since 1.2.0 you can use Repository.create_branch_ref:
repo = gh.repository('User','Repo')
repo.create_branch_ref('NewBranch')
repo.create_file(path='NewFile',message='Commit Message',content='File Content', branch='NewBranch')

By default the branch will be forked off the default branch (usually main / master), but you can also supply a sha to specify the exact fork point.


NetBeans for Mac c++ Input

Question: I have just installed NetBeans 8.2 on my Mac and made simple programe with some cin and cout. Output works fine, but it didn't asked me to type anything in cin and programe ended without it.
int main(int argc, char** argv) {
    int a;
    cin <> a;
    cout >> "Hello world";
}

So how can I make my keyboard inputs working?
Answer: Your >> and << are the wrong way around. This should work:
cin >> a;
cout << a;
cout << "Hello world";

NetBeans for Mac c++ Input


How to build a linked list with a method that has two integer parameters and returns the reference to the first element of a list of nodes?

Question: So I am having trouble trying to build a linked list from a method that has two integer parameters n and m. Parameter n is the length of nodes of the linked list, and m is the parameter that contains random integers from 0 to m-1 inside the list of nodes. I am required to build this linked list from a predefined Node class that cannot be changed, and to return the reference to the first element from the linked list. I don't know how to traverse the linked list in the while loop.
Node class
public class iNode{
public int item;
public iNode next;

public iNode(int i, iNode n){
    item = i;
    next = n;
}
public iNode(int i){
    item = i;
    next = null;
}

Build the linked list method
    public static iNode list(int n, int m){

    iNode first;
    iNode newNode;
    iNode last;

    first = null;
    while ( )
    {
        newNode = new iNode(m, first.next);
        if (m > 0){
            newNode.item = m-1;
        }
        newNode.next = null;

        if (first == null)
        {
            first = newNode;
            last = newNode;
        }
        else
        {
            last.next = newNode;
            last = newNode;
        }

    }
    return first;
}

Answer: You are overcomplicating it. Just go from the end of the list and add nodes with the link to the previous one. In the end just return the last created node. Also, you are not adding random int from the range 0..m-1. Here it is:
    public static void main(String[] args) {
        iNode res = list(5, 10);

        while(res != null){
            System.out.println(res.item);
            res = res.next;
        }
    }

    public static iNode list(int n, int m) {

        iNode previous;
        iNode current;

        int i = 0;
        previous = null;
        while (i < n) {
            current = new iNode(ThreadLocalRandom.current().nextInt(0, m), previous);
            previous = current;

            i++;
        }
        return previous;
    }

Output:
2
5
7
8
9

P.S. Please follow java code convention. Class names should start with capital letter - iNode
Comment: Yes, but how can i generate random numbers from m-1 to 0 range.


Calculation of $ \int_{0}^{\sqrt{n}}\lfloor t^2 \rfloor dt\;$, where $n\in \mathbb{N}$ and $\lfloor x \rfloor = $ floor function of $x$.

Question: Calculation of $\displaystyle \int_{0}^{\sqrt{n}}\lfloor t^2 \rfloor dt\;$, where $n\in \mathbb{N}$ and $\lfloor x \rfloor = $ floor function of $x$.
$\bf{My\; Try}::$ Let $t^2 = u$ and $\displaystyle dt = \frac{du}{2\sqrt{u}}$ and changing Limits, we get $\displaystyle \frac{1}{2}\int_{0}^{n}\frac{\lfloor u \rfloor }{\sqrt{u}}du$
Now Let
$\displaystyle I = \int_{0}^{n}\lfloor u \rfloor \cdot u^{-\frac{1}{2}}du = \int_{0}^{1}0\cdot u^{-\frac{1}{2}}du+\int_{1}^{2}1\cdot u^{-\frac{1}{2}}du+\int_{2}^{3}2\cdot u^{-\frac{1}{2}}du+.........+\int_{n-2}^{n-1}(n-2)\cdot u^{-\frac{1}{2}}du+\int_{n-1}^{n}(n-1)\cdot u^{-\frac{1}{2}}du$
$\displaystyle =-2\left\{1\cdot \left(\sqrt{2}-1\right)+2\cdot \left(\sqrt{3}-\sqrt{2}\right)+3\cdot \left(\sqrt{4}-\sqrt{3}\right)+.......+(n-2)\cdot \left(\sqrt{n-1}-\sqrt{n-2}\right)+(n-1)\cdot \left(\sqrt{n}-\sqrt{n-1}\right)\right\}$
Now how can i calculate given sum in closed form
please Help me
Thanks
Comment: I don't think there is a closed form here
Comment: Check your steps, I don't think there will be a $-2$ in front.
Comment: The large expression can be simplified as $(n-1)\sqrt {n} - \sum_{r=1}^{n-1} {\sqrt {r}}$. I don't think there is a closed form for $\sum_{r=1}^{n-1} {\sqrt {r}}$.
Answer: Actually I think is way simpler... The floor function is a step function, possibly the simplest kind to integrate. Note that
$$
  \lfloor t^2 \rfloor
~=~
  k
\quad\text{whenever}\quad
  t\in \big[\,\sqrt k,\,\sqrt{k+1}\,\big)
~\text{and}~k\in\mathbb Z
$$
As you are integrating between $0$ and $\sqrt n$, such integers $k$ range from $0$ to $n-1$.
Graphically, the function is constantly equal to the integer $k$ in the interval $[\sqrt k,\,\sqrt{k+1})$. Therefore, the contribution of this interval to the whole integral is $(\sqrt{k+1}-\sqrt k)\cdot k$.
You can sum all the steps yielding
$$
  \int_0^{\sqrt n}
  \lfloor t^2\rfloor{\rm d}t
~=~
  \sum_{k=0}^{n-1}
  (\sqrt{k+1}-\sqrt k)\cdot k
$$
I strongly doubt a close form exists, but it can be worked in something simpler. Adding and substracting $\sum_{k=0}^{n-1}\sqrt{k+1}$,
\begin{align}
  \sum_{k=0}^{n-1}
  (\sqrt{k+1}-\sqrt k)\cdot k
~=~&
  \sum_{k=0}^{n-1}
  (k+1)\sqrt{k+1}
-
  \sum_{k=0}^{n-1}
  \sqrt k\cdot k
-
  \sum_{k=0}^{n-1}
  \sqrt{k+1}
\\
~=~&
  n\sqrt n
-
  \sum_{k=0}^{n-1}
  \sqrt{k+1}
~=~
  (n-1)\sqrt n
-
  \sum_{k=1}^{n-1}
  \sqrt k
\end{align}
To sum up,
$$
  \int_0^{\sqrt n}
  \lfloor t^2\rfloor{\rm d}t
~=~
  (n-1)\sqrt n
-
  \sum_{k=1}^{n-1}
  \sqrt k
~=~
  \sum_{k=1}^{n-1}
  \big(
    \sqrt n-\sqrt k
  \big)
$$
Answer: You can obtain $$\frac{1}{2}\int_0^n\frac{\lfloor u\rfloor}{u^{1/2}}\text{d}u =\frac{1}{2}\int_0^n\frac{u-\{u\}}{u^{1/2}}\text{d}u = \frac{1}{2}\int_0^n u^{1/2}\text{d}u - \frac{1}{2}\int_0^n\frac{\{u\}}{u^{1/2}}\text{d}u,$$ which gives
$$\frac{1}{2}\int_0^n\frac{\lfloor u\rfloor}{u^{1/2}}\text{d}u =\frac{1}{2}\left[\frac{2}{3}u^{3/2}\right]_0^n-\frac{1}{2}\int_0^n\frac{\{u\}}{u^{1/2}}\text{d}u=\frac{1}{3}n^{3/2}-\frac{1}{2}\int_0^n\frac{\{u\}}{u^{1/2}}.$$
Not sure if you can do much with the last integral, but for a "similar" integral notice that
$$\lim_{n\longrightarrow\infty}\int_0^n\frac{\{u\}}{u^{s+1}}\text{d}u = -\frac{\zeta(s)}{s},$$ where $\zeta(s)$ is the Riemann zeta function and $0<s<1$.


Are there any free software to test web server?

Question: I wrote own http server. Are there any free software, test packages or toolset to validate whether it complies fully or partially with HTTP 1.0 (rfc 1945). And moreover it'd great if this software could estimate http performance and check for potential security issues. The same is wanted from this software in respect of FTP compliance validation.
Comment: Noticed in replies to http://serverfault.com/questions/2107/tools-for-load-testing-http-servers someone has suggested OpenSTA. Is it capable for compliance testing?
Answer: You could use apachebench for the performance testing.
Comment: Right, it's a benchmarking tool, but I'm interested more in full coverage of HTTP server implementation. Thank you!
Answer: This is really a programming issue, but as you have a bounty on the question it will stay here, at least for now.
There are a lot of Firefox add-ons designed for testing and debugging, so have a search through those see what you think is suitable for you. For security issues there are a lot of different scripts around but I should warn you that of those I've tried the results have been inconsistent and even contradictory, so I'm of two minds about their value.
The single largest issue seen in any software is buffer overflows. They can be a real pain to find at times, because they can be anywhere in the code, and often won't show up under automated testing. When I first started programming for Windows I wrote a program in which a buffer overflow went undetected for more that two years, even though the program was in daily use by several thousand users.
Comment: How/If code implements written requirements falls straightly under SO's domain; why and how code on one computer interacts with another is SF. Regardless, a program that tests RFC compliance sure would be nice for much more than just HTTP.
Comment: I pretty sure that I'd redirected here if posted in SO, so I've posted it here. I'd look at Firefox addons, however I think they are more focused on web design and web layout testing. The main point of this question is not static/runtime code analysis but in understanding which I missed and undone in my implementation of HTTP 1.0 server.
Comment: @Chris, I figure code testing, in whatever form that is, is very much a dev thing, sot sysadmin.
Answer: I do not know a tool for testing HTTP RFC compliance.
For performance tests use apachebench like topdog mentioned.
For security testing, I can recommend Nikto and Google's skipfish . Although harder to configure, Nessus is capable too.
Answer: Lots of questions here. While I'm sure lots of people will tell you their tool does everything if only you will buy it, there are very few tools available which make a reasonable attempt at any one of these.
For the security side of things, assuming that you are only interested in serving of static content, there is a list of useful software here.
For capacity testing you could use ab which ships with apache. You might also consider scripting more complex interactions using loadrunner ($$$) or http::Recorder and www::mechanize
Most of the large software packages available as source code come with automatic testing scripts (usually a target in the Makefile, e.g. 'make test') but the Apache build instructions don't mention this - might be worth downloading the src and configuring it to see if it does have test scripts included which could be adapted.
As for performance testing/monitoring - IME there's nothing currently available which is any good (and I include Oracle's Grid Control, BMC Patrol, Google Analytics and a large number of other products in the 'not any good' category). Personally I'm using a home-grown solution which relies on very detailled logging of URL generation (have a look at mod_log_config %D option and mod_log_firstbyte).
One area I've not studied in great depth is passive monitoring - there are tools like vantage agentless but these are very, VERY expensive. PastMon may meet your requirements (its good and its free) but you're going to need some specialist and expensive hardware to run it on if you expect to measure what happens when your webserver reaches saturation.
HTH
C.
Comment: Your answer is the most comprehensive!
Answer: For code quality (buffer overflows etc) you can use http://www.coverity.com/ They have picked up so many in open source programs http://scan.coverity.com/index.html
Comment: The main point of this question is not static/runtime code analysis but in understanding which I missed or yet left undone in my implementation of HTTP 1.0 server. Thank you!
Comment: unless i do not understand english what does this mean "and check for potential security issues and the same for ftp server"
Comment: Sorry if something wasn't clear; corrected.
Answer: You could try some of this:
http://java-source.net/open-source/web-testing-tools
or
http://www.softwareqatest.com/qatweb1.html
have fun


Purpose of Fermat's Little Theorem

Question: What is the purpose of using Fermat's Little Theorem, and a proof of it?
Comment: Did you try http://en.wikipedia.org/wiki/Fermat's_little_theorem ?
Comment: There are a full 6 proofs on wikipedia.
Comment: What do you mean by "purpose?"
Answer: Below is what Weil wrote on proofs of Fermat's little theorem, from p. 56 of his Number theory: An approach through history. As for its purpose, it helps serve to reveal the  multiplicative structure  of $\rm\:\mathbb Z/p\:,\:$ and problems in $\rm\:\mathbb Z\:$ are often best solved by reducing them to much simpler problems in its finite images $\rm\:\mathbb Z/p\:,\:$ e.g. so-called "local-global" principles. No doubt a search on "Fermat little" will uncover many applications - both here and elsewhere.
Comment: where could i find Leibniz's proof using multinomial theorem ?? can someone summarize thanks
Answer: In modular arithmetic e.g. mod m you can reduce big numbers down to numbers between 0 and m.
Fermat's little theorem lets you reduce the exponents (of numbers of the form $b^e$) down to numbers between 0 and $\varphi(m)$ (without knowing anything about the base).

For example of the first, $x = 0,1,2$ or $3$ mod 4 so the number $x^2$ must be equal to 0 or 1 mod 4. So $x^2$ is of the form 4k or 4k+1.
For an example of the second, if p is prime $\varphi(p) = p-1$ then  $p^2 = 1$ mod p-1 so $x^{(p^2)} = x$ mod p. I just made that up but you can probably see from it that you can use this for lots of things.
Comment: Surprisingly, Euler's extension of Fermat's Little Theorem plays a crucial role in modern cryptography.
Comment: @lhf: Actually Fermat's little theorem is enough for RSA, and Euler's theorem is not needed. The reason is that given distinct primes $p,q$ and $jk = a(p-1)(q-1)+1$ we have $x^{jk} \equiv (x^{a(p-1)})^{q-1} \cdot x \equiv x \pmod{q}$ (using Fermat's little theorem if $q \nmid x$), and by symmetry $x^{jk} \equiv x \pmod{p}$, and hence $p,q \nmid x^{jk}-x$, and the proof is finished using Euclid's lemma. =)
Answer: Fermat's little theorem states that, for a prime $p$:
$$ a^p \equiv a \pmod{p} $$
alternatively:
$$ a^{p-1} \equiv 1 \pmod{p} $$
The easiest proof that I've seen is as follows:  Consider any integer, $g$, that is relatively prime to $p$.  Let $x$ be the product of all of the (distinct) integers $\pmod{p}$.  i.e.:
$$ x = 1 \cdot 2 \cdot 3 \dots (p-1) \pmod{p} $$
Now, multiply each term on the right by $g$:
$$ g^{p-1} x = (g \cdot 1) (g \cdot 2) (g \cdot 3) \dots (g \cdot (p-1)) \pmod{p} $$
Since multiplication is 1-1 and onto, all this does is permute the values involved in the product on the right to give back $x$.  So:
$$ g^{p-1} x = x \pmod{p} $$
$$ g^{p-1} = 1 \pmod{p} $$
One needs to prove multiplication is 1-1 and onto (for $p$ prime), but once that's done, the proof above is (in my opinion) straight forward and simple.
EDIT:  I originally restricted the product, $x$, to be the product of powers of a generator, $g$.  As lhf points out, this can be any number.  I've changed the above to reflect this.
Comment: No need to use a generator. Consider the product of $ax$ for $x=1,\dots,p-1$.
Comment: Wow, that's not "easy" because knowing that there is a generator for the multiplicative group is non-trivial, isn't it?  And if you are gonna jump to group theory, you know that $g^{|G|}=1$ for all $g\in G$ for any group $G$, so you don't really need a generator.
Comment: @lhf, you are absolutely right.  @Thomas, the above proof without the generator condition is now much simpler.
Answer: We prove by fermat's little theorem by induction. Firstly, the base case tells us that
$1^{p} \equiv 1$ (mod $p$), which is true.
Assume true for $a=k$, namely that we assume $k^{p} \equiv k $ (mod $p$).
Then for $a = k+1$, we observe that $(k+1)^p - (k^p +1) = pk$ + $p \choose 2$ $k^2$ + $\ldots$ $k^{p-1}$ $p\choose p-1$.
I leave it as an exercise to check that the R.H.S. is divisible by $p$, and so we have the chain of congruences (using the induction hypothesis) that $(k+1)^p \equiv k^p + 1 \equiv k+1 $ (mod $p$). So the statement of fermat's little theorem is true for $a = 1$, $a = k$ and $a = k+1$ and hence is true for all natural numbers $k$.
$\hspace{6in}\blacksquare$
Ben

Purpose of Fermat's Little Theorem


use of aggregate function in Laravel Lumen with Jessengers MongoDB

Question: I have the following collection:
[
   {
      "_id":"5fabdd45bf510000d7001430",
      "application_id":27,
      "employ_id":1,
      "reason":"email",
      "score":1800
   },
   {
      "_id":"5fabdd50bf510000d7001431",
      "application_id":28,
      "employ_id":1,
      "reason":"email",
      "score":1800
   },
   {
      "_id":"5fabdd5dbf510000d7001432",
      "application_id":28,
      "employ_id":2,
      "reason":"email",
      "score":1800
   },
   {
      "_id":"5fabdd68bf510000d7001433",
      "application_id":27,
      "employ_id":2,
      "reason":"email",
      "score":1800
   },
   {
      "_id":"5fabdd79bf510000d7001434",
      "application_id":27,
      "employ_id":2,
      "reason":"facebook",
      "score":1000
   },
   {
      "_id":"5fabdd84bf510000d7001435",
      "application_id":27,
      "employ_id":1,
      "reason":"facebook",
      "score":1000
   }
]

I want to calculate the score of each "employ_id" on the base of each "reason". for instance employ_id has score against reason email: 3600 and and against facebook: 1000
I am using Laravel Lumen and Jessengers MongoDb library.
here is my code:
Model::groupBy('employ_id')-get('reason','score');

Answer: though it might be quite a bit late, but I hope it helps,
For what I have understood, here is what you can do in mongodb,
db.getCollection('yourcolection').aggregate([
                { $group :
                    { _id : {employ_id:"$employ_id", reason:"$reason"},
                      count: {
                                  $sum:"$score"
                            }
                }}
            ])

It will return you,
/* 1 */
{
    "_id" : {
        "employ_id" : 1,
        "reason" : "facebook"
    },
    "count" : 1000
}

/* 2 */
{
    "_id" : {
        "employ_id" : 2,
        "reason" : "facebook"
    },
    "count" : 1000
}

/* 3 */
{
    "_id" : {
        "employ_id" : 2,
        "reason" : "email"
    },
    "count" : 3600
}

/* 4 */
{
    "_id" : {
        "employ_id" : 1,
        "reason" : "email"
    },
    "count" : 3600
}

writing that using Jenssegers mongodb for Laravel in model,
$result = DB::collection('yourcollection')->raw(function($collection)
{
    return $collection->aggregate([
        [    '$group' => [
                    '_id' => [
                            'employ_id'=>"$employ_id",
                            'reason'=>"$reason"
                        ],
                    'count' => [
                        '$sum' => "$score"
                    ]
            ]
        ]
    ]);
});


How to check if the string is empty in Python?

Question: Does Python have something like an empty string variable where you can do:
if myString == string.empty:

Regardless, what's the most elegant way to check for empty string values? I find hard coding "" every time for checking an empty string not as good.
Comment: How is `""` not as good?
Comment: None won't match "". So depends on the context as to what you want.
Answer: Empty strings are "falsy" (python 2 or python 3 reference), which means they are considered false in a Boolean context, so you can just do this:
if not myString:

This is the preferred way if you know that your variable is a string.  If your variable could also be some other type then you should use:
if myString == "":

See the documentation on Truth Value Testing for other values that are false in Boolean contexts.
Comment: Be careful, since lots of other things are false as well.
Comment: OP wants to know if the variable is an empty string, but you would also enter the `if not myString:` block if `myString` were `None`, `0`, `False` etc.  So if you aren't sure what type `myString` is, you should use `if myString == "":` to determine if it is an empty string as opposed to some other falsy value.
Comment: @Joan: It evaluates as false in a boolean context.
Comment: @AndrewClark, for such a case, instead of a chain of `if myString == ...` expressions, we could use `if myString in (None, '')` or per @Bartek, `if myString in (None, '') or not myString.strip()`
Comment: I never heard of the term falsy before. Does it mean it returns false?
Comment: Checking for Falsyness results in bugs. Explicit is better than implicit, `the_string == ''` is harder to misinterpret.
Comment: Well, if it *contains* a newline character, then it is not empty. Same goes for tabs, spaces and all forms of non-printable characters.
Comment: @Bartek answer below should be taken into consideration too. Being hit by this today, thinking django forms required validation will take care empty string such as `" "` while it's not.
Comment: Worth noting that you may get a positive on `if string` if the line appears blank, but actually contains a newline character "\n"
Comment: @JoanVenge: the term `falsy` (as well as `truthy`) is widely used in JavaScript. See https://developer.mozilla.org/en-US/docs/Glossary/Falsy
Comment: if is not your string then whose it is ;)
I would rather prefer == '''
Comment: FYI truth value testing for python 3: https://docs.python.org/3/library/stdtypes.html#truth-value-testing
Answer: From PEP 8, in the "Programming Recommendations" section:

For sequences, (strings, lists, tuples), use the fact that empty sequences are false.

So you should use:
if not some_string:

or:
if some_string:

Just to clarify, sequences are evaluated to False or True in a Boolean context if they are empty or not. They are not equal to False or True.
Comment: PS: In the PEP's defense, one could argue that saying "*x is false*" (lowercase *false*) already means that, rather than meaning `x == False`. But IMHO the clarification is still welcome given the target audience.
Answer: The most elegant way would probably be to simply check if its true or falsy, e.g.:
if not my_string:

However, you may want to strip white space because:
 >>> bool("")
 False
 >>> bool("   ")
 True
 >>> bool("   ".strip())
 False

You should probably be a bit more explicit in this however, unless you know for sure that this string has passed some kind of validation and is a string that can be tested this way.
Answer: I would test noneness before stripping. Also, I would use the fact that empty strings are False (or Falsy). This approach is similar to Apache's StringUtils.isBlank or Guava's Strings.isNullOrEmpty
This is what I would use to test if a string is either None OR empty OR blank:
def isBlank (myString):
    return not (myString and myString.strip())

And the exact opposite to test if a string is not None NOR empty NOR blank:
def isNotBlank (myString):
    return bool(myString and myString.strip())

Comment: `s.strip()` allocates a new string, which is pure waste.  Use `string.isspace()`
Comment: this answer is not very pythonic
Comment: How is it different from `string and not string.isspace()`?
Answer: I once wrote something similar to Bartek's answer and javascript inspired:
def is_not_blank(s):
    return bool(s and not s.isspace())

Test:
print is_not_blank("")    # False
print is_not_blank("   ") # False
print is_not_blank("ok")  # True
print is_not_blank(None)  # False

Answer: The only really solid way of doing this is the following:
if "".__eq__(myString):

All other solutions have possible problems and edge cases where the check can fail.

len(myString) == 0 can fail if myString is an object of a class that inherits from str and overrides the __len__() method.

myString == "" and myString.__eq__("") can fail if myString overrides __eq__() and __ne__().

"" == myString also gets fooled if myString overrides __eq__().

myString is "" and "" is myString are equivalent. They will both fail if myString is not actually a string but a subclass of string (both will return False). Also, since they are identity checks, the only reason why they work is because Python uses String Pooling (also called String Internment) which uses the same instance of a string if it is interned (see here: Why does comparing strings using either '==' or 'is' sometimes produce a different result?). And "" is interned from the start in CPython
The big problem with the identity check is that String Internment is (as far as I could find) that it is not standardised which strings are interned. That means, theoretically "" is not necessary interned and that is implementation dependant.
Also, comparing strings using is in general is a pretty evil trap since it will work correctly sometimes, but not at other times, since string pooling follows pretty strange rules.

Relying on the falsyness of a string may not work if the object overrides __bool__().

The only way of doing this that really cannot be fooled is the one mentioned in the beginning: "".__eq__(myString). Since this explicitly calls the __eq__() method of the empty string it cannot be fooled by overriding any methods in myString and solidly works with subclasses of str.
This is not only theoretical work but might actually be relevant in real usage since I have seen frameworks and libraries subclassing str before and using myString is "" might return a wrong output there.
That said, in most cases all of the mentioned solutions will work correctly. This is post is mostly academic work.
Comment: @simpleuser you are of course right. In the real world it is completely ok to use the falsiness of the string or compare it to an empty string. This here answer is overkill on purpose.
Answer: Test empty or blank string (shorter way):
if myString.strip():
    print("it's not an empty or blank string")
else:
    print("it's an empty or blank string")

Comment: If `myString = None`, it will raise an exception. Better use @vault's [answer](http://stackoverflow.com/a/27982561/1168315)
Comment: @Dominik if myString `isinstance(myString, int)` will also raise exception.  What is your point? The OP asked for ways to test empty strings, his question does not include type checking.
Answer: If you want to differentiate between empty and null strings, I would suggest using if len(string), otherwise, I'd suggest using simply if string as others have said.  The caveat about strings full of whitespace still applies though, so don't forget to strip.
Comment: I don't know why you'd want to avoid using "", unless it impacts performance somehow, but I prefer your answer to the one with zillions of upvotes, as it's less confusing. However, I wanted to point out that an empty list is also False, apparently.
Answer: if stringname: gives a false when the string is empty. I guess it can't be simpler than this.
Answer:
I find hardcoding(sic) "" every time for checking an empty string not as good.

Clean code approach
Doing this: foo == "" is very bad practice. "" is a magical value. You should never check against magical values (more commonly known as magical numbers)
What you should do is compare to a descriptive variable name.
Descriptive variable names
One may think that "empty_string" is a descriptive variable name. It isn't.
Before you go and do empty_string = "" and think you have a great variable name to compare to. This is not what "descriptive variable name" means.
A good descriptive variable name is based on its context.
You have to think about what the empty string is.

Where does it come from.
Why is it there.
Why do you need to check for it.

Simple form field example
You are building a form where a user can enter values. You want to check if the user wrote something or not.
A good variable name may be not_filled_in
This makes the code very readable
if formfields.name == not_filled_in:
    raise ValueError("We need your name")

Thorough CSV parsing example
You are parsing CSV files and want the empty string to be parsed as None
(Since CSV is entirely text based, it cannot represent None without using predefined keywords)
A good variable name may be CSV_NONE
This makes the code easy to change and adapt if you have a new CSV file that represents None with another string than ""
if csvfield == CSV_NONE:
    csvfield = None

There are no questions about if this piece of code is correct. It is pretty clear that it does what it should do.
Compare this to
if csvfield == EMPTY_STRING:
    csvfield = None

The first question here is, Why does the empty string deserve special treatment?
This would tell future coders that an empty string should always be considered as None.
This is because it mixes business logic (What CSV value should be None) with code implementation (What are we actually comparing to)
There needs to be a separation of concern between the two.
Comment: I would disagree with that answer. Magic numbers are bad, that makes sense. Magic values in general as well. But `""` is not a magic value, same as `True`, `False` or `None` aren't magic values.
Comment: Does one really need to go to that much trouble to avoid a ""? In the context of comparison what else could a blank string mean?
Comment: @firelynx how much more explicit explicit can you get to say "this string is empty" than to use `""`? Would you also redefine `True` as `REALLY_TRUE`? In the end you will end up with a lot of variables (that are non-constant compared to a literal `""`) that say the same thing. So, is CSV_NONE different to JSON_EMPTY_VALUE? The problem then occurs when you transfer between different parts of the program. Then you might not know anymore if you have a `None` or a `""`, especially if you name your constants something misleading like `CSV_NONE`, which is actually not `None` but `""`.
Comment: you say "not_filled_in" is more descriptive than "empty_string" ? I say you are high.
Comment: @firelynx This causes more ambiguity than just use the constant values `None`, `True`, `False` or `""`. Using variables instead of magic values is useful whenever you encode more information in the name then what the value itself already has, e.g. use `STATE_A` instead of `27`. Or whenever there is ambiguity, e.g. `GPIO.HIGH` instead of `1`, because depending on the logic you use, `1` could be `HIGH` or `LOW`. But in the given example using a variable causes more harm than good.
Comment: As I write in my answer, CSV cannot represent null without using a string. If you are context free then congratulations! Most code isn't.
Comment: @TuncayGöncüoğlu "Empty string" does not describe what the if statement tests for.
Comment: @Dakkaron maybe. But explicit is better than implicit. I think my point is valid, making your code readable is important (to me). But not everyone is a clean code Zealot like me.
Comment: @Dakkaron Some CSV files use "NA" as None. What would be better: `EMPTY_STRING = "NA"` or `CSV_NONE = "NA"`
Answer: if you want to check if a string is completely empty
if not mystring

which works because empty strings are false
but if a string is only whitespace it will be true so you might want to
if not mystring.strip()

Comment: Isn't this already covered by the other answers?
Comment: @MateenUlhaq Sorry for the late response,but Yes you are right but I feel that more answers saying the same thing gives the op more reassurance,and to be totally honest I don't really care about stupid internet points.
Answer: How about this?  Perhaps it's not "the most elegant", but it seems pretty complete and clear:
if (s is None) or (str(s).strip()==""): // STRING s IS "EMPTY"...

Comment: For most purposes, a string containing blanks is not "empty".
Comment: I assume you mean nothing but white space? You are referring to my use of strip()?  For most purposes that IS empty!  It is ridiculously common to compound something like s.trim().isEmpty()
Comment: Hey @Chris Johnson, did you see that MOST of the answers here use strip() as well?  Did you down vote all of us, or just me?
Answer: I did some experimentation with strings like '', ' ', '\n', etc. I want isNotWhitespace to be True if and only if the variable foo is a string with at least one non-whitespace character. I'm using Python 3.6. Here's what I ended up with:
isWhitespace = str is type(foo) and not foo.strip()
isNotWhitespace = str is type(foo) and not not foo.strip()

Wrap this in a method definition if desired.
Answer: Responding to @1290. Sorry, no way to format blocks in comments. The None value is not an empty string in Python, and neither is (spaces). The answer from Andrew Clark is the correct one: if not myString. The answer from @rouble is application-specific and does not answer the OP's question. You will get in trouble if you adopt a peculiar definition of what is a "blank" string. In particular, the standard behavior is that str(None) produces 'None', a non-blank string.
However if you must treat None and (spaces) as "blank" strings, here is a better way:
class weirdstr(str):
    def __new__(cls, content):
        return str.__new__(cls, content if content is not None else '')
    def __nonzero__(self):
        return bool(self.strip())

Examples:
>>> normal = weirdstr('word')
>>> print normal, bool(normal)
word True

>>> spaces = weirdstr('   ')
>>> print spaces, bool(spaces)
    False

>>> blank = weirdstr('')
>>> print blank, bool(blank)
 False

>>> none = weirdstr(None)
>>> print none, bool(none)
 False

>>> if not spaces:
...     print 'This is a so-called blank string'
...
This is a so-called blank string

Meets the @rouble requirements while not breaking the expected bool behavior of strings.
Comment: `python -c "if (str(None) == 'None'): print ('OMG, WHY ??')"`
Answer: The clearest approach is:
if s == "":

Benefits:

Additional indication to the programmer what the type of s should be.
"" is not "hard-coding" a magic value any more than x == 0 is.
Some values are fundamental and do not need a named constant; e.g. x % 2 to check for even numbers.
Cannot incorrectly indicate that any falsy value (e.g. []) is an empty string.

Consider how one checks if an integer is 0:
if x == 0:

One certainly should not do:
if not x:

Both integers and strings are primitive value types. Why treat them differently?
Answer: a = ''
b = '   '
a.isspace() -> False
b.isspace() -> True

Comment: Really don't understand what this solution gains. The question is about testing whether a string is empty. If you set `a='a'` you would get `a.isspace() -> False`, but `a` would not on that account be an empty string.
Answer: not str(myString)

This expression is True for strings that are empty. Non-empty strings, None and non-string objects will all produce False, with the caveat that objects may override __str__ to thwart this logic by returning a falsy value.
Answer: for those who expect a behaviour like the apache StringUtils.isBlank or Guava Strings.isNullOrEmpty :
if mystring and mystring.strip():
    print "not blank string"
else:
    print "blank string"

Answer: When you are reading file by lines and want to determine, which line is empty, make sure you will use .strip(), because there is new line character in "empty" line:
lines = open("my_file.log", "r").readlines()

for line in lines:
    if not line.strip():
        continue

    # your code for non-empty lines

Answer: If you are not totally sure, that your input is really a string, I would recommend to use isinstance(object, classinfo) link in addition, as shown in the example.
If not, lists or a True bool value could also be evaluated as True.

def test_string(my_string):
    if isinstance(my_string, str) and my_string:
      print("It's a me, String! -> " + my_string)
    else:
      print("Nope. No, String")

def not_fully_test_string(my_string):
    if my_string:
      print("It's a me, String??? -> " + str(my_string))
    else:
      print("Nope. No, String")

print("Testing String:")
test_string("")
test_string(True)
test_string(["string1", "string2"])
test_string("My String")
test_string(" ")

print("\nTesting String or not?")
not_fully_test_string("")
not_fully_test_string(True)
not_fully_test_string(["string1", "string2"])
not_fully_test_string("My String")
not_fully_test_string(" ")

Answer: You can check if the string is completely empty or not as shown below. *strip() can remove spaces:
test1 = ""
test2 = "    "
test3 = "    ".strip()

print(bool(test1), bool(test2), bool(test3))
         # False      # True       # False

if test1:
    print("test1") # Not run

if test2:
    print("test2") # Run

if test3:
    print("test3") # Not run

if not test1:
    print("test1") # Run

if not test2:
    print("test2") # Not run

if not test3:
    print("test3") # Run


Como faço para diminuir meu código? (Estudos) Calculadora PHP

Question: Fiz uma calculadora PHP, com require peguei a função de outra aba etc... Eu gostaria de saber como posso fazer para exemplificar minha function, exemplo fazer uma calculadora em so uma fuction não usar varias e cada uma com uma operação, se puderem me instruir, agradeço.
meu código principal:
require 'function.php';
$soma = somar(10,5);
$diferenca = subtrair(10, 5);
$produto = multiplicar(10, 5);
$quociente = dividir(10, 5);

echo 'A soma de 10 e 5 é: ' . $soma . "\n";
echo 'A diferença entre 10 e 5 é: ' . $diferenca . "\n";
echo 'O produto de 10 por 5 é: ' . $produto ."\n";
echo 'O quociente de 10 por 5 é: ' . $quociente;

function que usei:
function somar($a ,$b){
   return $a + $b;
}
function subtrair($a,$b){
   return $a - $b;
}
function multiplicar($a ,$b){
   return $a * $b;
}
function dividir($a ,$b){
   return $a / $b;
}

Comment: Dá pra fazer sim em uma function - basta receber a operação como parâmetro (em um enum, ou uma constante que identifique o tipo, por exemplo). Mas, o código **não ficaria melhor**. Normalmente, não é uma boa opção juntar tudo em uma function - isso aumenta a complexidade de leitura (entre outros possíveis problemas).
Comment: O que deu pra entender dessa pergunta, algo parecido com isso:
echo 'A soma de 10 e 5 é: ' . ($a + $b) . "\n";
echo 'A diferença entre 10 e 5 é: ' . ($a - $b) . "\n";
echo 'O produto de 10 por 5 é: ' . ($a * $b) ."\n";
echo 'O quociente de 10 por 5 é: ' . ($a / $b);
Comment: @Froslass é somente para ser um exemplo do que vai exibir o importante e a calculadora, por que a única coisa que quero é  saber se tem como diminuir a função.
Comment: Então o que eu escrevi acima serve
Answer: Como levei em consideração que você está iniciando, fiz algo bem simples e bem "porco". Mas o intuito aqui é você poder analisar o código, e ver de uma outra forma. NÃO recomendo utilizar essa forma que fiz, embora você pode otimizar o código ou com base nele criar outro "melhor" (Não existe sempre um código melhor se funcionou e atendeu a demanda então está ok, se preocupe com performance e detalhes mais avançados, quando estiver mais acostumado a programar)
O código ficou assim:
<?php

ini_set('display_errors', true);

$numero1 = !empty($_POST['numero1']) ? intval($_POST['numero1']) : 0;
$numero2 = !empty($_POST['numero2']) ? intval($_POST['numero2']) : 0;
$operadores = $_POST['operadores'] ?? null;

function calcular($numero1, $numero2, $operador)
{
    switch ($operador) {
        case 'somar':
            return $numero1 + $numero2;
            break;
        case 'subtrair':
            return $numero1 - $numero2;
            break;
        case 'dividir':
            if ($numero1 === 0 || $numero2 === 0) {
                echo 'Voltar';
                throw new DivisionByZeroError('Divisão por zero');
            }
            return $numero1 / $numero2;
            break;
        case 'multiplicar':
            return $numero1 * $numero2;
            break;
    }
}

$resultado = calcular($numero1, $numero2, $operadores);

?>
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Calculadora</title>

    <form action="" method="POST">
        Campo1:
        <input id="numero1" name="numero1" type="text" style="margin-right: 5px; font-size: 1.4rem;">
        <select name="operadores" id="operadores" style="width: 50px !important; margin-right: 10px; font-size: 1.4rem;">
            <option value="somar" <?=$operadores === 'somar' ? 'selected' : '';?>>+</option>
            <option value="subtrair" <?=$operadores === 'subtrair' ? 'selected' : '';?>>-</option>
            <option value="dividir" <?=$operadores === 'dividir' ? 'selected' : '';?>>/</option>
            <option value="multiplicar" <?=$operadores === 'multiplicar' ? 'selected' : '';?>>*</option>
        </select>
        Campo2:
        <input id="numero2" name="numero2" type="text" style="margin-right: 5px; font-size: 1.4rem;">
        <button style="font-size: 1.4rem;">Calcular</button>

        Resultado:
        <input id="resultado" name="resultado" type="text" readonly value="<?= $resultado; ?>" style="font-size: 1.4rem;">
    </form>

Eu fiz de propósito de uma forma que fique faltando validações, e utilizei algumas variáveis e escopo que não são tão recomendáveis para programar, mas a ideia é fazer você analisar, entender, e criar um novo à partir de seu entendimento.
Answer: Visualizando o seu problema eu reparo que, você já fez um código curto o suficiente para a proposta, mas ainda sim tem como melhorar mais utilizando as arrow functions do PHP, você pode consultar a documentação para mais exemplos, resolução abaixo:

<?php

//Como está:
function somar($a ,$b){
   return $a + $b;
}

//Como vai ficar:
$somar = fn($a) => fn($b) => $a + $b;

//Uso:
$resultado = $somar(2, 5);

?>


VBA Excel check if a particular table exist using table name

Question: I have several tables in an excel sheet. Each having unique table Name. I want to know if a table which has a name "Table123" exist or not in the current sheet.
Could some one help me on this?
Thanks
Jeevan
Comment: just loop table/shape colection colection and check if any table/shape has desired name.
Comment: How do I do that? How do I loop a ListObject?
Comment: Why is this question voted down with "-2" ?
Comment: @Jeevan its common practice on SO to downvote questions that dont abide by the community guidelines for asking questions -http://stackoverflow.com/help/how-to-ask.  In your case, the lack of attempted code has resulted in some people downvoting your question.  I still chose to answer because the solution was quite short, but that is the cause of the downvotes
Answer: TableExists = False
On Error GoTo Skip
If ActiveSheet.ListObjects("Table123").Name = "Table123" Then TableExists = True
Skip:
    On Error GoTo 0

This code will work and avoid loops and errors
Comment: For very large data sets, this method will be much faster than looping through every shape on the sheet and will return exactly the same result
Comment: Getting run-time error for this. Its caused because i dont have shape Table123 on sheet, only table. So you need to change it to `ListObjects` and also when table isnt on sheet, you will get error. Not false
Comment: It is erroring out in this line "If Not ActiveSheet.Shapes.Range(Array("Table123")) Is Nothing Then" saying "The item with the specified name wasn't found"
Comment: It should not error out for me also that time that table was present.
Comment: error is Run-time error 1004 The item with the specified name wasnt found. (and i updated my previous coment)
Comment: @Jeevan see the editted code. this should work as desired
Comment: RGA: again in the IF statement, I get "Run-time error '9' Subscript out of range"
Comment: @Jeevan I have no idea why you got an error, as the errorhandler should avoid that, so I've adjusted the errorhandler.  I've tested it in a variety of ways on my machine and it works perfectly, so if you are still having issues with this then it is the result of something else
Comment: @RGA: Actually I tried the code in empty sheet to check if it returns false. I will test and let you know. So far it did not work for me. Thanks.
Comment: @RGA: The code works fine, unless there are 0 ListObjects. If there is some object in the worksheet then it works fine. I added another If statement to check if there are any List Objects using "If ActiveSheet.ListObjects.Count > 3 Then". Then it worked fine. Thanks a lot.
Comment: @Jeevan glad it worked, though I'm not sure why it didn't work if there were 0 objects.  I tested it on a completely blank sheet that was freshly opened and had no issues.  Will do a little research to figure out what that cause would be
Comment: @RGA: Thank you :)
Answer: Here is an alternative function:
Function TableExistsOnSheet(ws As Worksheet, sTableName As String) As Boolean
    TableExistsOnSheet = ws.Evaluate("ISREF(" & sTableName & ")")
End Function

Comment: This will return true for Names listed in the Name Manager and any strings that are Cell references. Since not all Names are tables, it might be better to use structured reference.  i.e. "ISREF(" & sTableName & "[[#All]])" should evaluate false on non-table references. **I'm not sure if there are any edge cases.
Answer: You can list shape collection and compare names like this
Sub callTableExists()

    MsgBox tableExists("Table1", "Shapes")

End Sub

Function TableExists(tableName As String, sheetName As String) As Boolean

    Dim targetSheet As Worksheet
    Set targetSheet = Worksheets(sheetName)

    Dim tbl As ListObject

    With targetSheet
        For Each tbl In .ListObjects
            If tbl.Name = tableName Then TableExists = True
        Next tbl
    End With

End Function

Answer: Another option, using a bit lazy approach with error catching:
Public Sub TestMe()

    If TableExists("Table1243", ActiveSheet) Then
        MsgBox "Table Exists"
    Else
        MsgBox "Nope!"
    End If

End Sub

Public Function TableExists(tableName As String, ws As Worksheet) As Boolean

    On Error GoTo TableExists_Error
    If ws.ListObjects(tableName).Name = vbNullString Then
    End If
    TableExists = True

    On Error GoTo 0
    Exit Function

TableExists_Error:
    TableExists = False

End Function

Answer: Try this, use err to get data table status information
also, consider testing the data table on an inactive sheet.
Sub Test_TableNameExists()
    TableNm = "Table00"
    MsgOutput = TableNm & vbTab & TableNameExists(TableNm)
End Sub

Private Function TableNameExists(nname) As Boolean '#Table #Exist
'Returns TRUE if the data table name exists
'Can test table on inactive sheet
Dim x As Object
On Error Resume Next
'use Range(nname).Parent to get data table sheet name.
'So the function can test data table on inactive sheet.

Set x = Range(nname).Parent.ListObjects(nname)
If Err = 0 Then TableNameExists = True _
    Else TableNameExists = False

End Function

Answer: Without the use of GoTo, which is a lot more powerfull than appropriate.
Set TableExists = False

On Error Resume Next
If ActiveSheet.ListObjects("Table123").Name = "Table123" Then Set TableExists = True

Be aware that this applies to a single line, thus requiring the line continuation symbol _ to keep larger statements readable.


Some fields are not sorting properly in view

Question: I'm trying to create a directory list in view. But some of the fields are not properly sorting.
See the below image for my view configuration.

And the output of the view.

Update:  Style setting

Update:  Field Settings

Grouping

Please anyone help me to get the correct output.
Comment: Also please check if any of your node titles start with a space.
Comment: @J.Reynolds I've updated the question. I'll check the node. I think may be that is the problem.
Comment: I think problem with the grouping. Add a screenshot of style setting too.
Comment: Why do you have the `content: title` field two time in your fields section?
Comment: @Djouuuuh That one title is for grouping.
Comment: Yes sorry I understood that just after asking actually ;)
Comment: @SumitMadan I've updated the question
Comment: Not field style setting. Your views format settings.
Comment: There is nothing wrong with the sorting. There is a problem with your grouping. Can you show us that, as well as the field settings for the field you are grouping  on, like are you rewriting anything?
Comment: @J.Reynolds, Thank you for your suggestion, Actually I had space before the content title.
Comment: How to you group the items with letters, if you group with **Content: Title**?
Answer: It's probably not a configuration problem.  Examine the nodes that aren't sorting correctly.  They likely have spaces at the beginning of their titles.


How do I get alerted when a workstation falls back from wired networking to wifi?

Question: I have a bunch of medical-grade all-in-one workstations in use in a high-demand medical environment that spend their lives plugged in to power and wired networking. The systems came with a 30 minute backup battery and a wifi card for redundancy. The idea was that they'd run on wired net, and if a cable got tripped over or unplugged, the workstation would switch over to wifi, and case documentation could continue. The catch with this plan is that we need to know WHEN that switch-over to wifi happens so we can go remedy the problem with the wires that triggered the switch in the first place. The systems run WinXP (a vendor requirement). We don't run them totally on wifi because it's an electrically noisy environment and wifi not 100% reliable - that, and throughput isn't quite as good over wifi.
Can I get / how can I get these systems to alert me when they switch from wired to wifi networking?
Thanks!
Comment: or if you don't want a central server collecting this info you could go lowend and just have a scheduled task that reads the logs looking for disconnects then sending an email etc...
Comment: the event is logged in the system log so you could look there, and or have a passive solution like splunk etc..
Comment: Just remember - whatever you put in place is going to spam the hell out of you when people shut off their machines at the end of the day. Do you really need this real-time?
Comment: guess thats one thing in favor of the lowend method!
Answer: I can think of a few different ideas.
The "built-in" functionality in Windows XP that yoy're looking for is the Network Location Awareness service. Having said that, though, you'll need custom code to take advantage of it, because it's just an API and not a finished "solution".
You could use a "ping probe" tool to poll the wired NIC IP addresses on the client computers and report if they become unavailable. You would probably need to use DHCP reservations or static IP addresses on the clients if your probe utility couldn't handle probing DNS names.
You might have luck monitoring your Ethernet switch ports using a tool like Nagios, Zabbix, a syslog receiver, an SNMP trap receiver, etc, and acting on port "down" events with a script. If you're comfortable with scripting I suspect you could cobble something together fairly easily.
Comment: We ended up doing a little Network Location Awareness app for each workstation that monitors the interfaces, and if wired is down for a configurable amount of time, it reports it. Thanks for the tip on this API!
Comment: Glad I could help. It's neat to hear that somebody actually got something working with that API. I'd heard bad things about the API's reliability.
Answer: Yes.
A more precise answer will require more detail, because there are several ways to go about it,but from the sounds of things you really need a moniroing system.  At a minimum, look into setting up an SNMP server which all your clients can report to and send an alert out over SNMP if the status of their wired connection changes.
You could even do something simpler, like monitor via ping traces and have a script that sets off alarms if it misses [x] pings in a row... but the thought of that being used in a medical enivronment chills my blood.  As doe the question, now that I think of it.
If it's that important, shell out the money for an enterprise-grade monitoring suite.
Comment: We currently run this environment wired-only right now, and that's been good enough for the past 12 years - the system involved is redundant enough that it keeps working if the network disappears for short periods. Users are trained to contact support if they notice no-network symptoms - I'm asking this question because the wifi cards give us the ability keep running, and to notice and fix the problem before the users notice anything amiss. So, is it important enough for a pro monitoring solution? No. Is it a chance for us to improve service to our users, yes.


Can't access any of Linq methods

Question: I'm writing a simple ApiController for getting product stocks, but I'm having a strange issue. I get the data from a method that returns a System.Linq.IQueryable (In a library), but I can't apply any of the Linq methods, like Count or ToList(). The import directive is present and doesn't report any problem. Also intellisense shows Data as System.Linq.IQueryable.
The code:
Imports System.Web.Http
Imports System.Linq

Public Class ProductSearchController
    Inherits ApiController

    Public Function Get(...) As IQueryable

        Dim nvc As NameValueCollection = HttpUtility.ParseQueryString(Request.RequestUri.Query)
        Dim sEcho As String = nvc("sEcho").ToString()
        Dim iDisplayStart As Integer = CType(nvc("iDisplayStart"), Integer)

        'Signature of Stock:  public IQueryable Stock(...)
        Dim Data = New GenericSearches().Stock(...)
        Dim Count As Integer = Data.Count() 'Error Here!

        Dim result = New DataTableResult With {
            .sEcho = sEcho,
            .iTotalRecords = Count,
            .iTotalDisplayRecords = Count,
            .aaData = Data.ToList() 'Error Here!
            }
        Return result
    End Function
End Class

Also, I noticed that error correction and intellisense asks me to choose those methods from a weird Devexpress library something like DevXpress.Data.Helpers.Linq.
Comment: What *exactly* is the error? If you hover over `Data`, what does it show the type as?
Comment: @JonSkeet : The queston says it is `System.Linq.IQueryable`
Comment: Oh, and also: if you type `Data.` what members *does* Intellisense suggest?
Comment: @Sandesh: Had missed the Intellisense part... oops!
Answer: The non-generic IQueryable interface doesn't have extension methods of Count and ToList(). Only the generic IQueryable<T> does.
If you can modify the library to return a suitable IQueryable<T>, I suggest you do so. If you can't, you may need to call Cast<T>() or OfType<T>() to create an appropriate IQueryable<T> with the right extension methods.
Comment: @Sergio: Yes, exactly. Although if it's coming from a `DataTable`, why are you using `IQueryable` at all (rather than `IEnumerable`)?
Comment: You mean like IQueryable or IQueryable ?
The data comes initially from a dataTable.
Comment: I'm currently using an old DAL that still can't deal with paged queries. So I have a service that gets the data and then the paging it's managed between this and the apicontroller. Also I don't remember if it was a requirement for a REST web api and AttributeRouting. Does it make sense?
Anyway, your solution runs smooth like silk. Thanks!
Comment: @Sergio: It doesn't make a lot of sense, to be honest - if the paging is all done locally, you could still just use `IEnumerable`. I think it would be worth revisiting your approach - but I'm glad that the workaround helped for the moment.

Can't access any of Linq methods


Even numbers in Pascal's triangle.

Question: Basically i've been looking at Pascal's triangle and been wondering how it represents Sierpinski's triangle once the even numbers are shaded. Once I rewrote the triangle in terms of C I observed that 2C1 is an even number and 4C1/4C2/4C3. However, I cannot postulate a reasonable statement which describes the rational behind the connection of Pascal's and Sierpinski's triangles.
Answer: Hint: have a look at https://en.wikipedia.org/wiki/Lucas%27_theorem, which describes a trick well known to algebraic topologists for calculating binomial coefficients modulo a prime $p$. When you apply this trick with $p =2$, the connection with the Sierpinski triangle should begin to make sense.

Even numbers in Pascal's triangle.


Bar width in Sibelius

Question: I'm using Sibelius 7.5 and I want to have some lines with 4 measures and others with 3 measures. When I try to do this, I end up with both lines having the same width. I would like to the 3 measure lines to be shorter. Is this possible?
Answer: Certainly is! Just click after the end of the stave you want to change the length of. You can then move the last bar line of that stave, and so also move the whole stave.
If you look at the picture below, you'll see a little purple square after the end of the second stave. This appears if you left-click after the end of that stave:

Then, you select this purple square and drag it leftwards, until it is in the position you want the barline:

Also, just in case you don't know how to do it, to change the number of bars in a line of music, select the barline you want to be the last barline of that line and press return.
Comment: I tried that. If I click at the last bar line and try to drag it, it will stay in the same place and the notes will move instead. But, I am able to drag the beginning of the line, though.
Comment: I've added more info, you need to click *after* the barline.
Comment: And it should be a *left* click (not right, sorry!)
Comment: Ok. If I right click at the end, I get a menu.
Comment: Yes, I just updated that, too.
Comment: I don't see the purple thing when I left click.
Comment: Are you clicking in the position it appears in the first picture above?
Comment: yes. I did that. Does it matter if I got the sore scanned with PhotoScore?
Comment: Sorry, I don't use photoscore, so don't know.
Comment: I was able to get the purple thing by ticking layout marks in view. But they are not moving. Thank you for your answer -- now I know about purple things.
Comment: Once you have the purple square appear, make sure you drag the purple square, *not* the barline.
Comment: I finally managed to drag the small box. I had to tick Handles in view to get the box. To drag it, you have to move the cursor a lot -- it is not very responsive. Thanks.

Bar width in Sibelius


Qual a definição do termo acoplamento?

Question: Qual o significado dos termos alto/baixo acoplamento em desenvolvimento de sistemas orientados a objetos ou programação orientada a objetos (POO)?
Answer: Conceito

Em um aspecto global acoplamento é o grau de dependência entre dois
"artefatos". Onde artefatos podem ser entidades, métodos, componente,
tabelas, enfim qualquer coisa que esteja na outra.
Acoplamento baixo - é quando um "artefato", tem pouco ou nada de
dependência em relação aos outros.
Acoplamento alto - é o inverso do baixo obviamente, sendo quando um
"artefato" tem uma grande dependência em relação a outro.

Boas Práticas (Design Principle)

Alto acoplamento não é considerado uma boa prática de programação,
onde seus componentes, "artefatos", terão um alto grau de dependência,
tornando mais difícil de manter e testar.*¹
Já o baixo acoplamento é considerado uma boa prática de programação (loose coupling),
já que com ele você mantem seus componentes, "artefatos", menos
dependentes um dos outros, tendo maior rastreabilidade e
testabilidade.*¹

*¹ Mas isso trata-se apenas de Boas Práticas (princípio de design), não quer dizer que você não possa utilizar alto grau acoplamento em seu projeto, por que ele é inevitável em alguns casos. Só se deve ter o cuidado de manter seu projeto com o menor grau de acoplamento possível.

Exemplos

Um exemplo corriqueiro de alto acoplamento é herança, onde sua
entidade não consegue existir sem a sua entidade base. Em modelagem esse é
considerado o grau mais alto de acoplamento. Mas nem por isso deve deixar
de ser utilizado, somente deve ser utilizado com maior moderação,
sempre analisando se é realmente necessário esse alto grau de
acoplamento.
Uma boa prática para reduzir o acoplamento é a utilização de outros
padrões, como por exemplo Injeção de Dependencia (dependency
injection), que ajuda a reduzir o dependência entre camadas,
entidades ou módulos.
Para reduzir o acoplamento também é aconselhável a analise de suas
dependências, verificando se elas possam ser removidas, ou trocadas
por outra com um grau de dependência menor (por exemplo, trocar uma
herança por uma agregação), isso já vai melhorar a rastreabilidade e
testabilidade de seu projeto.

Considerações
O acoplamento é necessário, entre diferentes módulos, o que os padrões pregam é que seja o menor possível, sempre avaliando se é necessário criar determinada dependência ou se pode ser substituída por uma dependência menor.

Obs.: O conceito de acoplamento é independente de linguagem de programação ou tecnologia utilizada em seu projeto. É questão de boas práticas.
Comment: @Piovezan, sua edição e descrição dela foi tão boa que devia virar comentário para deixar claro para todo mundo.
Comment: Pessoal, obrigado pelo feedback. Não sei se em todas as edições compensa esse nível de detalhe, coloquei mais por se tratar de um assunto potencialmente espinhoso (a definição de _design pattern_) e que poderia resultar em discussões se não fosse devidamente justificado.
Comment: Sim @bigown! Também li o comentário da edição e vi que esse erro persistiu na resposta por mais de um ano, nem tinha conhecimento deste termo "Design Principle", mas está correto isso não pode ser um Design Pattern, pois é algo mais abstrato que não pode ser feito como um bolo. Então acredito que o termo "Design Principle" é muito mais adequado. Obrigado pela edição @Piovezan.
Answer: Acoplamento é o quanto uma classe sabe de outra classe.
O ideal é que haja baixo acoplamento entre as classes pois as classes devem ser especialistas para o serviço o qual elas foram designadas.
O baixo acoplamento também é desejado pois fica mais fácil identificar problemas relativos a classe, que é um dos princípios do paradigma da orientação a objetos.
EDIT
"Saber de outra classe" significa que a classe em questão usa métodos e/ou atributos de alguma outra classe. Isso faz com que a classe dependa da outra classe, ou seja, o comportamento da classe estará diretamente ligado ao comportamento da outra.
O alto acoplamento entre as classes torna difícil a manutenção delas, pois imagine, cada vez que você editar uma classe você também estará alterando o comportamento das classes que estão acopladas com ela, se você não tiver conhecimento das classes acopladas você estará correndo um grande risco de estar inserindo bugs e comportamentos inesperados ao seu programa.
Answer: Falaram tanto da definição, vou falar então um pouco sobre Acoplamento fraco:
Introdução
Acoplamento fraco é um dos principais requisitos para se construir software orientado a objetos (OO) de qualidade. O acoplamento fraco mede o quanto uma classe, depende de, ou está relacionada a, outra classe ou subsistema. A capacidade de uma classe em herdar o comportamento de outra(s) é uma das principais características do paradigma OO. A principal vantagem é poder criar novas classes quase de graça, aproveitando o código de outra. Esse artigo discute esses dois conceitos e mostra porque a herança, em geral, ajuda a comprometer o acoplamento fraco.
Acoplamento fraco
Uma classe com acoplamento forte depende muito (em geral sem necessidade) de outras. Isso pode conduzir aos seguintes problemas [Larman]:
·         classes difíceis de aproveitar tendo em vista que sempre que esta for utilizada todas as outras das quais ela depende devem estar presentes;
·         alterações nas classes relacionadas podem forçar mudanças locais e
·         são difíceis de compreender isoladamente.
Formas comuns de acoplamento ocorrem através de: variáveis de instância, variáveis locais a métodos ou de seus argumentos, chamada de serviços em outra classe, uma classe deriva direta ou indiretamente de outra ou uma classe implementa uma determinada interface. Resumindo, sempre que uma classe referencia um outro tipo em qualquer uma das circunstâncias acima está ocorrendo acoplamento. Considere o código:
<code>public class X
{
    private ClasseConcretaY var1;
void M1(ClasseConcretaW var2 ) { … }
}
</code>
Existem dois pontos principais de acoplamento, na variável de instância var1, que é do tipo ClasseConcretaY, e no argumento var2, que é do tipo ClasseConcretaW. Nestas duas partes do código a classe X referencia outras duas classes concretas. Isso significa que, sempre que esta classe for utilizada, as outras duas deverão estar disponíveis no espaço de nomes do programa. No caso de Java, o(s) pacote(s) onde estas se encontram deverá(ão) estar no classpath.
Mas, referenciar outras classes sempre causa problemas de acoplamento? A resposta é, depende! Referenciar classes estáveis e disseminadas raramente é um problema. Por exemplo, utilizar o pacote java.util num programa em Java dificilmente causará problemas futuros de acoplamento, uma vez que qualquer ambiente de execução Java contém essa biblioteca. O problema está em classes instáveis, pouco conhecidas, ou seja, nas classes que são criadas para atender os problemas específicos dos projetos.
Como diminuir o acoplamento?
Uma regra geral para diminuir o acoplamento é "programar para uma interface e não para uma implementação" [Gamma]. No exemplo acima isso significa substituir as declarações das classes concretas por declarações de interfaces. Fazendo isso desacopla-se o código de uma implementação específica, tornando-o dependente apenas de uma interface. Essa não é a solução definitiva, um bom projeto com boas atribuições de responsabilidades é crucial, porém ajuda muito. É mais fácil compreender isoladamente uma classe que referencia apenas interfaces e mais [Gamma]:
os clientes (usuários da classe) permanecem sem conhecimento dos tipos específicos dos objetos que eles usam, contanto que os objetos tenham aderência à interface que os clientes esperam,
os clientes permanecem sem conhecimento das classes que implementam estes objetos; eles somente têm conhecimento das classes abstratas que definem a interface.
Fonte: http://www.devmedia.com.br/acoplamento-fraco-x-heranca/3714

Qual a definição do termo acoplamento?


Nginx call script before every request

Question: I need to run a script from nginx (preferably PHP) before every request. All my served pages are plain HTML. Googling took me as far as LUA but, even though I have full access to server I would rather not change anything apart from nginx configuration (either http or server blocks).
I have php5-fpm also running on-site.
The reason is, we would like to allow developers do create HTML static one-page-apps that would need to AJAX post to an external API. CORS and all setup fine, all good, but we wanted to initiate a session on the destination API server.
Comment: What do you want the script to change?
Comment: I'll use the script to start a session on the destinaiton API server (basically cURL to it)
Comment: Yeah, the Lua module can handle that just fine. Of course you know those are scripts embedded inside your nginx configuration files.
Comment: yes, I'm starting to get frustrated already with googling for an alternative to Lua. Probably that's the only way!?
Comment: You could abuse `auth_request` for this
Answer: To whom it may interest, I ended up using the following solution (Thanks to all the comments that helped me follow along):

Configured NGINX to process HTML as PHP
https://stackoverflow.com/questions/12258524/unable-to-run-html-files-on-nginxphp-fpm
Used php5-fpm auto-prepend to "prepend" a specific php file on every request, as seen here, but be careful with CGI caching. Better use different php5-fpm pool for vhosts using this technic.

Hope this can help someone.
Note: As alerted in comments, this has a significant impact on performance, because nginx will not serve static files anymore as it will need to send them back and forth to PHP-FPM.
Comment: Be aware that this has a significant performance penalty, from having to process static files with a script interpreter, and so it is unlikely to scale very well.
Comment: It probably won't be too bad, as long as there isn't actually any PHP code in the file. In that case it just has to read it and spit it back out at the browser. But that's still much slower than simply having nginx send the file with the kernel-accelerated `sendfile()` call, which is what it normally does when serving a static file.
Comment: @MichaelHampton Does it perform worst compared to processing a normal script file like `php` ?
Comment: @MichaelHampton right, ok then. Avoiding PHP code inside our files was a priority, of course performance too. So I guess this is still is good solution if I can't recompile nginx with lua. Thanks for the comment Michael.

Nginx call script before every request


How to replace string on Donner standard series

Question: My son just got his first guitar. I know NOTHING about guitars. One of the strings broke and we can't figure out how to replace it. The videos I've found on YouTube make it look easy and spend about 5 seconds on the part that's perplexing me. None of them look anything like my son's guitar so they wouldn't be helpful anyway.

From what I can tell, I need to remove all of the strings, unscrew that metal plate, and thread the replacement string in from behind. Hoping there's an easier way.
Comment: I bought it on Amazon. :) I did end up going to a local music store to get some help. She was very friendly and didn't charge anything.
Comment: I'm also delighted at the response here to such a basic beginner question. They say musicians tend to make good programmers. I wonder if that has less to do with mathematical thinking and more to do with having learned a skill that takes a lot of practice in a community with an ancient ethos of welcoming and supporting one another.
Comment: Why not go to the guitar shop you bought it?  The vendors will be happy to help, teach to replace strings, etc. (Maybe clarify if they will charge a fee for that, but they usually don't.)
Answer: Unscrewing the bridge is surely not the right way to do this. Rather at the back of the guitar there should be a removable plate (which might even have a slot for changing the strings). If there is no slot, remove the plate (if there is you might want to remove it too if it is too hard to get the string inside). Under this plate should be the springs for the whammy system and the bridge should have a block with holes. Find the right one and put the string through that hole.
Comment: You're welcome! I wish your son a lot of joy with his guitar!
Comment: Thanks! It didn't even occur to me to look at the back of the guitar.
Answer: It appears to be a 'Stratalike' guitar. Google 'Changing strings on a Fender Stratocaster', and you'll find many sites that will show how it happens.
You may end up taking the backplate off, one, in order to find the way through with each string, and two, to recover the ballend that may be rattling around, or even stopping the new string entering the bridge from the back.


Reutilizar código no onClick de vários botões

Question: Estou desenvolvendo um aplicativo onde ele conterá vários botões.
Preciso da sua ajuda para ver se consigo melhorar o código.
As ações fazem a mesma coisa apenas mudam a cor de fundo e me passam qual o valor do botão.
O aplicativo possui várias outras telas que possuem muitos botões com quase as mesmas ações, apenas com algumas alterações no retorno.

Meu código:
btnBall01.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    count1++;
                    selectedNumber++;
                    games.setBallId(btnBall01.getId());
                    btnBall01.setBackgroundResource(R.mipmap.ball_verde);
                    games.setActualNumber(btnBall01.getText().toString());
                    Toast.makeText(ActivityMegasenaCreateGame.this, "Verde " + games.getActualNumber(), Toast.LENGTH_SHORT).show();

                    if (count1 != 1){
                        count1 = 0;
                        selectedNumber = selectedNumber -2;
                        btnBall01.setBackgroundResource(R.mipmap.ball);
                         Toast.makeText(ActivityMegasenaCreateGame.this, "Branco " + games.getActualNumber(), Toast.LENGTH_SHORT).show();
                        initializeComponentsBallsButtons();
                    }
                }
            });

            btnBall02.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    btnBall02.setBackgroundResource(R.mipmap.ball_verde);
                    count2++;
                    selectedNumber++;
                    games.setBallId(btnBall02.getId());
                    games.setActualNumber(btnBall02.getText().toString());

                    if (count2 != 1){
                        count2 = 0;
                        selectedNumber = selectedNumber -2;
                        btnBall02.setBackgroundResource(R.mipmap.ball);
                        initializeComponentsBallsButtons();
                    }
                }
            });

            btnBall03.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    btnBall03.setBackgroundResource(R.mipmap.ball_verde);
                    count3++;
                    selectedNumber++;
                    games.setBallId(btnBall03.getId());
                    games.setActualNumber(btnBall03.getText().toString());

                    if (count3 !=1){
                        count3 = 0;
                        selectedNumber = selectedNumber -2;
                        btnBall03.setBackgroundResource(R.mipmap.ball);
                        initializeComponentsBallsButtons();
                    }
                }
            });

            btnBall04.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    btnBall04.setBackgroundResource(R.mipmap.ball_verde);
                    count4++;
                    selectedNumber++;
                    games.setBallId(btnBall04.getId());
                    games.setActualNumber(btnBall04.getText().toString());

                    if (count4 != 1){
                        count4 = 0;
                        selectedNumber = selectedNumber -2;
                        btnBall04.setBackgroundResource(R.mipmap.ball);
                        initializeComponentsBallsButtons();
                    }

                }
            });

            btnBall05.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    btnBall05.setBackgroundResource(R.mipmap.ball_verde);
                    count5++;
                    selectedNumber++;
                    games.setBallId(btnBall05.getId());
                    games.setActualNumber(btnBall05.getText().toString());

                    if (count5 != 1){
                        count5 = 0;
                        selectedNumber = selectedNumber -2;
                        btnBall05.setBackgroundResource(R.mipmap.ball);
                        initializeComponentsBallsButtons();
                    }
                }
            });

            btnBall06.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    btnBall06.setBackgroundResource(R.mipmap.ball_verde);
                    count6++;
                    selectedNumber++;
                    games.setBallId(btnBall06.getId());
                    games.setActualNumber(btnBall06.getText().toString());

                    if (count6 != 1){
                        count6 = 0;
                        selectedNumber = selectedNumber -2;
                        btnBall06.setBackgroundResource(R.mipmap.ball);
                        initializeComponentsBallsButtons();
                    }
                }
            });

            btnBall07.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    btnBall07.setBackgroundResource(R.mipmap.ball_verde);
                    count7++;
                    selectedNumber++;
                    games.setBallId(btnBall07.getId());
                    games.setActualNumber(btnBall07.getText().toString());

                    if (count7 != 1){
                        count7 = 0;
                        selectedNumber = selectedNumber -2;
                        btnBall07.setBackgroundResource(R.mipmap.ball);
                        initializeComponentsBallsButtons();
                    }
                }
            });

            btnBall08.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    btnBall08.setBackgroundResource(R.mipmap.ball_verde);
                    count8++;
                    selectedNumber++;
                    games.setBallId(btnBall08.getId());
                    games.setActualNumber(btnBall08.getText().toString());

                    if (count8 != 1){
                        count8 = 0;
                        selectedNumber = selectedNumber -2;
                        btnBall08.setBackgroundResource(R.mipmap.ball);
                        initializeComponentsBallsButtons();
                    }
                }
            });

            btnBall09.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    btnBall09.setBackgroundResource(R.mipmap.ball_verde);
                    count9++;
                    selectedNumber++;
                    games.setBallId(btnBall09.getId());
                    games.setActualNumber(btnBall09.getText().toString());

                    if (count9 != 1){
                        count9 = 0;
                        selectedNumber = selectedNumber -2;
                        btnBall09.setBackgroundResource(R.mipmap.ball);
                        initializeComponentsBallsButtons();
                    }
                }
            });

            btnBall10.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    btnBall10.setBackgroundResource(R.mipmap.ball_verde);
                    count10++;
                    selectedNumber++;
                    games.setBallId(btnBall10.getId());
                    games.setActualNumber(btnBall10.getText().toString());

                    if (count10 != 1){
                        count10 = 0;
                        selectedNumber = selectedNumber -2;
                        btnBall10.setBackgroundResource(R.mipmap.ball);
                        initializeComponentsBallsButtons();
                    }
                }
            });

            btnBall11.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    btnBall11.setBackgroundResource(R.mipmap.ball_verde);
                    count11++;
                    selectedNumber++;
                    games.setBallId(btnBall11.getId());
                    games.setActualNumber(btnBall11.getText().toString());

                    if (count11 != 1){
                        count11 = 0;
                        selectedNumber = selectedNumber -2;
                        btnBall11.setBackgroundResource(R.mipmap.ball);
                        initializeComponentsBallsButtons();
                    }
                }
            });

            btnBall12.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    btnBall12.setBackgroundResource(R.mipmap.ball_verde);
                    count12++;
                    selectedNumber++;
                    games.setBallId(btnBall12.getId());
                    games.setActualNumber(btnBall12.getText().toString());

                    if(count12 != 1){
                        count12 = 0;
                        selectedNumber = selectedNumber -2;
                        btnBall12.setBackgroundResource(R.mipmap.ball);
                        initializeComponentsBallsButtons();
                    }
                }
            });

            btnBall13.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    btnBall13.setBackgroundResource(R.mipmap.ball_verde);
                    count13++;
                    selectedNumber++;
                    games.setBallId(btnBall13.getId());
                    games.setActualNumber(btnBall13.getText().toString());

                    if(count13 != 1){
                        count13 = 0;
                        selectedNumber = selectedNumber -2;
                        btnBall13.setBackgroundResource(R.mipmap.ball);
                        initializeComponentsBallsButtons();
                    }
                }
            });

            btnBall14.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    btnBall14.setBackgroundResource(R.mipmap.ball_verde);
                    count14++;
                    selectedNumber++;
                    games.setBallId(btnBall14.getId());
                    games.setActualNumber(btnBall14.getText().toString());

                    if (count14 != 1){
                        count14 = 0;
                        selectedNumber = selectedNumber -2;
                        btnBall14.setBackgroundResource(R.mipmap.ball);
                        initializeComponentsBallsButtons();
                    }
                }
            });

Answer: Sabia que:

um mesmo método pode ser associado ao evento de click de vários botões?
num array podem ser guardados valores diferentes, que podem ser acedidos através de um índice?
num objecto da classe View pode ser guardada uma referência a um qualquer objecto?

Agora que sabe, é fácil resolver o problema.
(1) permite ter apenas um método para tratar o click de todos os botões.
(2) permite guardar todos os contadores numa variável.
(3) permite guardar a posição no array onde está guardado o valor do contador correspondente a esse botão.
O método tem de ter uma assinatura do tipo:
public void nomeMetodo(View button)

O método é atribuído a cada evento de click usando o atributo android:onClick, na declaração de cada botão no XML:
android:onClick="nomeMetodo"

O array deve ser do tipo int e ter o número de itens igual ao número de botões.
Na declaração de cada botão, no XML, use o atributo android:tag para guardar a posição, no array, do seu contador.
android:tag="0"

Use 0 para o botão1, 1 para o botão2 e assim por diante.
No java, dentro do método nomeMetodo, esse valor pode ser obtido com
int tag = (int)button.getTag();

Use-o no array para obter o valor do contador.
Informação complementar:

Qual objetivo dos métodos setTag e getTag na View?
Android - Formas diferentes de "setar" um listener em objetos
Comment: Muito obrigado, deu certo!!
Answer: Você pode criar um método, com todo esse código repetitivo, e cada vez que precisar dele é só chama-lo, e como você quer um retorno de um numero é só definir o tipo de método como int ou double e fazer o retorno no final, e coloque como parâmetros o que precisar dentro do método, talvez vc tenha pensar um pouco para criar um "método universal" para todos os seus botões
public int meuMetodo(int parametro){
  int numero=2;
  int resultado=numero+parametro;
  return resultado;
}

Fiz só um exemplo pq não entendi o que realmente você quer como retorno, mas espero que tenha te ajudado


Unique foreign key in rails migration

Question: In migrations file, I'm adding foreign key using below syntax.
class CreatePreferences < ActiveRecord::Migration
  def change
    create_table :preferences do |t|
      t.integer :user_id, null: false
      t.timestamps null: false
    end
    add_foreign_key :preferences, :users, column: :user_id, dependent: :destroy, :unique => true
  end
end

But :unique => true is not working.
mysql> show indexes from preferences;
+-------------+------------+---------------------+--------------+--------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table       | Non_unique | Key_name            | Seq_in_index | Column_name  | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------------+------------+---------------------+--------------+--------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| preferences |          0 | PRIMARY             |            1 | id           | A         |           0 |     NULL | NULL   |      | BTREE      |         |               |
| preferences |          1 | fk_rails_87f1c9c7bd |            1 | user_id      | A         |           0 |     NULL | NULL   |      | BTREE      |         |               |
+-------------+------------+---------------------+--------------+--------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

What is the right way to add a unique foreign key using migrations?
I could've added uniqueness validations in the model itself. But it won't be foolproof if I have multiple workers running. (Reference)

Comment: I guess you should add index to make it unique in the DB level
Answer: In Rails 5 you can accomplish the same with the more elegant:
t.belongs_to :user, foreign_key: true, index: { unique: true }

This will generate a foreign key constraint as well as a unique index. Don't forget to add null: false if this is a required association (sounds like it in the case of the original question).
Note that belongs_to is just an alias for references.
Answer: class CreatePreferences < ActiveRecord::Migration
  def change
    create_table :preferences do |t|
      t.integer :user_id, null: false
      t.timestamps null: false
    end
    add_foreign_key :preferences, :users, column: :user_id, dependent: :destroy, :unique => true
    add_index :preferences, :user_id, unique: true
  end
end

Comment: As of Rails 5.2, `unique` is not a valid option for [`add_foreign_key()`](https://apidock.com/rails/v5.2.3/ActiveRecord/ConnectionAdapters/SchemaStatements/add_foreign_key), and is silently ignored. It is however a valid option for [`add_index()`](https://apidock.com/rails/v5.2.3/ActiveRecord/ConnectionAdapters/SchemaStatements/add_index).
Comment: Do I need to have `unique` in both `add_foreign_key` and `add_index` ?
Comment: `foreign_key` and `index` are different things, so I think you can have both `unique`

Unique foreign key in rails migration