Um teste de instrumentação é um teste de integração?

Question: Eu vi alguns vídeos onde explicam como testar a chamada de uma atividade por outra atividade.
Eu fiz o seguinte teste e, depois de uma reflexão, não tinha a certeza se o teste que executei era de integração, instrumentação ou teste funcional.
<code>public class OneActivityTest {

    private OneActivity mActivity = null;

    @Rule
    public ActivityTestRule<OneActivity> mActivityTestRule = new ActivityTestRule<>(OneActivity.class);

    Instrumentation.ActivityMonitor monitor = getInstrumentation().addMonitor(TwoActivity.class.getName(), null, false);

    @Before
    public void setUp() {
        mActivity = mActivityTestRule.getActivity();
    }

    @Test
    public void checkYes() {

        Assert.assertNotNull(mActivity.findViewById(R.id.checkbox_sim));

        onView(withId(R.id.checkbox_sim)).perform(click());

        Assert.assertNotNull(mActivity.findViewById(R.id.save));

        onView(withId(R.id.save)).perform(click());

        Activity secondActivity = getInstrumentation().waitForMonitorWithTimeout(monitor, 5000);

        Assert.assertNotNull(secondActivity);

        secondActivity.finish();
    }
}
</code>
Ele poderá ser considerado Teste de integração pelo simples facto de interagir com mais do que 1 activity?
Comment: Possível duplicata de [Testes, TDD, Unit Test, QA e assemelhados. Qual a diferença dos conceitos sobre testes?](https://pt.stackoverflow.com/questions/19177/testes-tdd-unit-test-qa-e-assemelhados-qual-a-diferen%c3%a7a-dos-conceitos-sobre)
Comment: Acredito que não seja duplicata. O AP quer identificar um tipo de teste a partir de um trecho de código.
Comment: agradeço desde já a tentativa de ajuda, mas como referi acima eu vi algumas explicações e fico mesmo sem compreender que tipo de teste é o que eu implementei...analisei o que sugeriu e a minha duvida permanece @Bruno Costa
Comment: Sério Nokas? O que o nome da classe `Instrumentation.ActivityMonitor`, que você está a usar, lhe diz?
Comment: comprendo o que me quer dizer @ramaral, mas a toda a informação que li esta a confundir bastante. mostro no comentário abaixo a confusão que me encontro neste momento
Comment: Testes de integração em Android - O Android Studio faz uma separação dos diferentes grupos de testes para aplicativos da plataforma Android. E essa separação pode ser feita da seguinte forma: Unit Tests: são executados na JVM (Java Virtual Machine), não acessam a API real de Android e, por consequência, não necessitam de um emulador Instrumentation Tests: acessam a API real de Android e, logo, precisam que um emulador esteja disponível para a execução de seus testes Logo, testes de integração, no contexo de desenvolvimento Android, são definidos como instrumentation tests @ramaral
Comment: segundo o que diz nesse texto, então testes de integração são considerados testes de instrumentação?
Answer: Os teste de integração visam verificar se o resultado da interacção entre as diversas partes/componentes da aplicação é o esperado.
Os teste instrumentais visam simular a interacção do usuário, via UI, com a aplicação.
Eles verificam se, a uma determinada acção na UI, a aplicação responde como esperado.
Ao fazê-lo, testam a integração da UI com o resto da aplicação e por isso são testes de integração.


Add subsequent natural numbers with a max difference of a prime to get to 119

Question: I found a really interesting math challenge that was given to 7 graders (around 13-14 years old). It goes like this:
Problem
Anne added subsequent natural numbers to get to $119$. The difference between the highest and lowest number is prime.
Find the subsequent numbers that fulfill this condition and show that this is the only solution.
Attempt at the solution
By factoring into primes, $119$ becomes $17\cdot 7$. Utilizing an adapted Gauss formula of sums
$$ \sum_{i=n_l}^{n_u} i = \frac{n_u-n_l + 1}{2}\cdot (n_u+n_l),$$
we can look for $7$ numbers with a sum of the lowest and highest number of $17$ to find $n_u=n_l+6$ and thus
$$ 119 = \sum_{i=n_l}^{n_l + 6} = \frac{7}{2}\cdot (2n_l+6)=7n_l+21 $$
$$\Rightarrow n_l=14$$
This way, one possible solution is $14+15+16+17+18+19+20$, but the difference is not prime.
After a lot of rewriting the formula I found the solution
$$2+3+4+5+6+7+8+9+10+11+12+13+14+15$$
with 13 as a prime difference, but in no way I can show that this is the only solution. Also, how is a 7 grader supposed to do this without knowing what a variable is?
Question
Are there any easy solutions I missed? How can you utilize the prime condition?
Comment: Why would 13-14 year olds not knwo what a variable is?
Answer: First off, you know that the number of naturals summed must be even, since the difference must be odd. Moreover, the even must be $p+1$ for some prime $p$. For a set of $2n$ consecutive naturals to sum up to $119$, $\frac{119}{2n}+\frac12$ must be an integer (since $(x-n)+(x-n+1)+...+(x+n+1)=2nx+n$). Hence, $n$ must divide $119$. So, we want to find a number $2n-1$ such that $2n-1$ is prime and $n\mid119$.
Since $119=7\cdot17$, the only choices for $n$ that we have are $1,7,17,119$. Clearly, $119$ doesn't work, and neither does $1$.
$2\cdot7-1=13$ works, but $2\cdot17-1=33$ doesn't, since it is not prime. So, $13$ is the only possibility.
I don't know how to do this without variables. Maybe use intuition with some of the formulas here?
Answer: This is a seventh-grader solution.
Let each number be represented by a row of counters. Now arrange the counters into a trapezium,  Let $h$ be the height of the trapezium (how many numbers there are), $a$ be the top base (the number of counters at the top), and $b$ be the bottom base (the number of counters on the bottom).

Then we have that:
$$\frac{1}{2}(a+b)h = 7\cdot17$$
$$(a+b)h = 2 \cdot 7 \cdot 17$$
Then they can test values of different values of $h$. To start off, in order for $a+b$ to be an integer, the only possible values of $h$ are the factors of this number: $1,2,7,14,17,34,119$ and $238$. In addition, the prime difference is one less than how many numbers there are. Students can reason this by writing down the list of numbers in one row, and counting the number of numbers in another row.
Subtracting $1$ from each value leaves the only candidate as $14$, as the rest are either divisible by $2$ or by $3$. Since there are $14$ numbers in total, the difference between the largest and smallest numbers is $14-1=13$.
Comment: Can you please elaborate on how to represent the number? I didnt undestand exactly how you are doing it. Other than that this looks great!
Comment: I forgot to mention the trapezium should be right-angled. [Here](https://docs.google.com/drawings/d/1F6kljSxk7_QYs8KG9FQI51Scd0XBiKhSkHyCSLStSns/edit) is what this should look like :)
Comment: Ah now I know what you mean. This is a great answer!
Comment: @Nurator No problem!


How to set up permissions for the private files directory?

Question: I'm trying to set up the private files directory and I'm getting the following error.

The backup file could not be saved to 'private://backup_migrate/'
  because the directory could not be created or cannot be written to.
  Please make sure your private files directory is writable by the web
  server.

Could someone help correct my misstep? I've scoured scads of pages of documentation, and oddly I don't seem to be able to find a reliable path to a solution. Lots of conflicting info and lots of missing details.
Here's my setup:

bitnami drupal image (centos)
path to Drupal /root/apps/drupal/htdocs
I've connected as root via ssh

Here are the exact steps I've followed, and which best reflect my understanding so far of what I should do:

# cd /root/apps/drupal/ to go to directory that contains the web root directory
# mkdir private-files
# drush dl file_permissions --destination=~/.drush to download the contributed file_permissions utility, which says it handles all necessary permissions changes
# nano sites/default/settings.php to tell Drupal where to find the directory, set $settings['file_private_path'] = '/root/apps/drupal/private-files';
# drush cr to clear Drupal and Drush caches
# drush fp to run the file_permissions utility; it responds:

Your httpd user: daemon                                      [status]
  Your httpd group: daemon                                     [status]
  You will be prompted for admin password to be able to change [warning]
  permissions with sudo command.
  Security warning: Couldn't write .htaccess file. Please create a     [error]
  .htaccess file inyour private:// directory which contains the
  following lines:
# Deny all requests from Apache 2.4+.
  <IfModule mod_authz_core.c>
  Require all denied
  </IfModule>
# Deny all requests from Apache 2.0-2.2.
  <IfModule !mod_authz_core.c>
  Deny from all
  </IfModule>
  # Turn off all options we don't need.
  Options -Indexes -ExecCGI -Includes -MultiViews
# Set the catch-all handler to prevent scripts from being executed.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
  <Files*>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
  </Files>
  # If we know how to do it safely, disable the PHP engine entirely.
  <IfModule mod_php5.c>
    php_flag engine off
  </IfModule>

# drush cr to clear Drupal and Drush caches
# ls -al to see permissions; it shows:

total 8628
  drwxr-xr-x  7 root   root       134 Jul 23 12:04 .
  drwxr-xr-x  5 root   root        53 Jun  7 13:52 ..
  lrwxrwxrwx  1 root   root        14 Jun  7 13:55 .bitnamimeta -> ../../var/meta
  -r-xr--r--  1 root   root   8826689 Jun  7 13:31 bnconfig
  drwxr-xr-x  4 root   root       146 Jun  7 13:51 conf
  drwxr-xr-x 12 root   root      4096 Jun  7 13:51 drush
  drwxr-x---  9 root   daemon    4096 Jul 18 13:46 htdocs
  drwxr-xr-x  2 root   root        25 Jun  7 13:51 licenses
  drwxrwsr-x  2 daemon daemon      23 Jul 23 13:45 private-files
  lrwxrwxrwx  1 root   root        33 Jun  7 13:54 updateip -> /opt/bitnami/apps/drupal/bnconfig

# ls -al private-files/ to see permissions; it shows:

total 4
  drwxrwsr-x 2 daemon daemon  23 Jul 23 13:45 .
  drwxr-xr-x 7 root   root   134 Jul 23 12:04 ..
  -rw-r--r-- 1 root   daemon 687 Jul 23 13:47 .htaccess

Needless to say, pretty frustrating since I've spent at least 4 hrs on what I imagine must be simple for someone already familiar with all the components.
Since I am new to servers as well as to Drupal, please break out actual steps vs merely invoking (vague-to-me) concepts such as 'change user group' or the like.
Comment: Are you running drush as root? That's not going to help because any files created by drush will not be writable by the webserver. Better to run it as the daemon user to reduce the chance of file ownership issues.
Comment: Sorry but that would be much too broad for a single question in this format. There are many different environments with many different considerations, too many to cover in a couple of paragraphs. File permissions are file permissions at the end of the day - Drupal just needs to be able to write to two folders (public and private), and read from the rest of the docroot. How you get that to happen across multiple platforms isn't something that Drupal is concerned with, it only cares about the _result_, and nothing in and of Drupal itself will teach you *nix file permissions
Comment: To put it succinctly: this is a file permission problem, not unique to Drupal, and we wouldn't teach you what you want us to teach you here (how to manage generic file permissions on any platform). It's been made specific to your current environment, in an attempt to avoid it being closed as "too broad" or otherwise off topic, because the knowledge you need is not unique to Drupal, but there\s an outside chance that there might be something unique to Bitnami that can be identified and addressed to help you and future users of the same platform
Comment: Ok I give :) I've edited into the more generic version - like I said before, I can't promise that's not going to make it attract "too broad" close votes (if I wasn't a mod and didn't have a binding vote I'd be voting it as such if I'm honest). Good luck getting it sorted anyway
Comment: Thanks Clive - I appreciate your efforts, and those of other long-time users, in keeping quality here high. There do seem to be unknown/unstated specifics regarding the private-files directory, and as you acknowledge, some holes in official documentation. I plan to help edit the Drupal docs page once I have a bit more clarity (ideally with similar help in making sure my edits are accurate and useful).
Comment: Thanks - I've come across instructions on acting as a different user. Will do that and follow the same steps above. I'm assuming no one actually sees issues with those steps other than doing things as root user? (btw, I've been following bitnami instructions, which don't mention the need to act as a different user....).
Comment: As the original poster of this question, I want to be sure to understand the considerations of setting up private files no matter the platform. For those editing my question to make it more specific to bitnami: please avoid doing so lightly. I don't believe Bitnami has some unique secret in this regard. Please address that uniqueness if in fact it's the case.
Comment: @clive - a polite request, since I'm attempting to learn - please note the above request and revert my question to my own title of a moment ago unless you are able to describe why this issue is specific to the Bitnami platform. Is there reason to believe that bitnami needs special permissions, ownership, locations or other consideration? Alternatively, please feel free to point me to an existing answer that actually covers all the details. I've not found one.
Comment: I will respectfully disagree, knowing you have a lot of experience on Stack Exchange. Please reconsider your stance. I'm unable to find a detailed explanation of Drupal's full requirements for private files, or a trouble-shooting guide. A good answer here will be a service to the community.
Comment: Drupal's full file permission requirements are very well documented: https://www.drupal.org/node/244924. The problem you're experiencing is not knowing how to set up your operating system/environment to fulfil those requirements. Drupal also requires MySQL and PHP, a web server, etc, but a question on how to install those wouldn't be on topic here either. I do understand it's something people do need to cover, that's why we deliberately let this question through the cracks: https://drupal.stackexchange.com/questions/373/what-are-the-recommended-directory-permissions. That's never going to be..
Comment: ...a full tutorial, though, you need to extract the information from there, combine it with knowledge of how to administer the server, and come up with a solution that matches your exact needs
Comment: Again with respect, Clive (and I know it's hard to convey in text, but sincerely!) - that page does not document requirements of private files. Please have another look (you can use your browser keyword find function with 'private') and reconsider. If someone is able to improve that page, I'd be a huge fan!
Comment: You're right, it doesn't, my bad. But that doesn't change the fact that what you need to know _isn't about Drupal_. You already know all the Drupal parts of this, which are basically 1. that the folder needs to be read/writeable by the user that executes the PHP part of the website, and 2. you need to set the path to it under Admin -> Config -> Media. There's nothing else to know from the Drupal perspective, everything else is about how to set up appropriate users/permissions to allow PHP to write to the folder
Comment: Thanks for the additional details, Clive. Unfortunately it does not seem that the 2 items you list in fact cover the requirements. There must still be something missing, as user, permissions and path all appear to be correct according to documentation, yet the error message persists. The strength of Stack Exchange is that a community can pool their knowledge; my request continues to be that the question continue to specify a need for details, and that the bitnami platform be an aside vs a primary point.
Answer: Your Drupal folder is owned by daemon:daemon and your private files directory is owned by root:root.
Fix it by making your private files directory at least owned by the same group:
$ chown -R daemon:daemon /root/apps/drupal/private-files

Sorry, I reread your ls -la output again, this time on a bigger screen, and it seems to be the other way around. Your
private files folder is already owned by daemon:daemon where in this setup it should be root:root instead:
$ chown -R root:root /root/apps/drupal/private-files

After reading through this thread from 2013 https://community.bitnami.com/t/how-in-bitnami-cloud-drupal-set-up-a-secure-private-file-system-path-folder/9652 it seems your files and folders ownership got messed. Seems that all your Drupal including private files should indeed recursively be owned by daemon:daemon. Generally, logging in as root should be avoided.
Comment: I have recursively set owner and group to daemon:daemon using $ chown -R daemon:daemon /root/apps/drupal/ --unfortunately the issue persists (I've confirmed all Drupal files/directories have that ownership and cleared caches several times with $ drush cr). I'm editing my original question to include this info.
Comment: Hi Clive - I notice you rolled back my edits, and I understand your doubts about this question broadly. Seems useful to me to include the changes mentioned here as an update to my question. Would doing so still be in keeping with the guidelines of the community?
Comment: @OwnSourcingstudent – I'm considering it, or to update the docs on drupal.org. But I guess I won't have the time until later this day or tomorrow.
Answer: I would not create the folder as root, let the site create its own folder. Just set the path in your settings.php and then go to 'File system' in the Drupal site (configuration). You can see your path reflected here. Then just save the form and Drupal will create the folders with right permissions.
Comment: Yeah, that's what I tried first. It reflects the correct path in the file system ("Private file system path /root/apps/drupal/private-files") but I still get the error.
Comment: How should that ever work when your private files path exists outside Drupal's web root in a directory where Drupal has no write permission for?
Comment: @leymannx it does work, you can fill in ../private and have Drupal create a folder on it's own, even if it's outside of the webroot.
Answer: Your configuration looks like this:
Your httpd user: daemon [status]
Your httpd group: daemon [status]

# ls -al /root/apps/drupal/private-files
total 4
drwxrwsr-x 2 daemon daemon 23 Jul 23 13:45 .
drwxr-xr-x 7 root root 134 Jul 23 12:04 ..
-rw-r--r-- 1 root daemon 687 Jul 23 13:47 .htaccess

On a vanilla *nix system, that is all it takes to give daemon full access to the private-files directory.  I.e. when the Drupal Backup and Migrate tries to create 'private://backup_migrate/ it should be allowed to to so.  As indicated by the error message you've posted, it is not.
Finding: You're not running a vanilla *nix system.
So what can be wrong?
There is no way of knowing without knowing a lot more about your server configuration, but given that you're running CentOS, I suspect that you're having an issue with something known as "SELinux". Btw. SELinux is great!  But it imposes an extra layer of security that sometimes comes as an surprise to the uninitiated.
Basically, if SELinux is in use, to fix permissions – in addition to the mod-bits – you also you need to make sure that the security policy for your private-files directory allows daemon to create subdirectories there.
First navigate to the the Drupal configuration directory (sites/default) and inspect the security context label for the public file upload directory:
$ ls -Z .
drwxrwxr x. daemon daemon unconfined_u:object_r:httpd_sys_rw_content_t:s0 files

The label here is httpd_sys_rw_content_t.
Then make sure that private-filesis tagged with the same label. Navigate to /root/apps/drupal and a give command similar to this (use the label used on your configuration):
$ sudo chcon -R -t httpd_sys_rw_content_t private-files

(Source: http://heim.ifi.uio.no/gisle/staging2/drupalprimer/drupal/cf_files.html#f_selinux)
Comment: Thanks for this detail, @free-radical. Great explanation, and strikes me as a likely explanation, but `# sestatus` returns `SELinux status: disabled`. I'd guess it's consequently no surprise that `# ls -Z sites/default/` returns a question mark for the security context label for the public file upload dir: `drwxrwsr-x daemon daemon ? files`. Interested whether there's another buried detail that similarly bears checking.
Comment: I agree: SELinux is disabled.  That rules out SELinux as the culprit. Unfortunately, I cannot think of any *other* things that may cause this.  Things to try: 1) Contact bitnami support and user forums; 2) Go over your configuration again, look for spelling errors and other trivial mistakes; 3) ditch your vhost - start from scratch. Going over your description agian, I see nothing wrong in the way you've tried to set this up.


Azure pipeline Stage and Job Dependencies

Question: I'm trying to create two pipeline templates used to integrate with an API which 1) installs an application 2) deploys the application to some devices that the API administers. The install template handles the install and gets back an application ID that the deploy template will require in order to deploy the app. There is no way to query the API later on to get the app ID so I must make it available for the install template for use later on by the deploy template. The install task will be called once, but the deploy task can be called multiple times for different device "rings".
I need to support the following scenario where the deploy template can have a dependency on both a job in the current stage, and can be dependent on the same job in a later stage.
<code>stages:
- stage: NonProd
  jobs:
  - template: install.yml@pipeline_template
  - template: deploy.yml@pipeline_template

- stage: Prod
  dependsOn: NonProd
  jobs:
  - template: deploy.yml@pipeline_template
</code>
I read we can do create these types of dependencies now here, but is it possible to set the dependencies to come from either a prior stage or a prior job?
I considered trying to combine these into a single template, but unfortunately if the same version of the app already exists the install step will not provide the app id back, just an error.
Answer: According to the update in 5/4 Jobs can access output variables from previous stages
You can currently specify that a stage run based on the value of an output variable set in a previous stage.
This is used in conditions of a stage.

but is it possible to set the dependencies to come from either a
  prior stage or a prior job?

You can't directly depend on a job from another stage.
But, when you define multiple jobs in a single stage, you can specify dependencies between them. Pipelines must contain at least one job with no dependencies.
Besides, you can also depend one stage on others.


VMWare steals IP addresses

Question: I'm having a peculiar problem, that I think I have narrowed down to VMware.
For the past one year, every once in a while we lose internet connection and not all users (about 10 users) go down at the same time, its usually one-by-one.  First someone will call me and say "Internet is down" and then we would go reset the router and modem and switch and it would be working again for a while, then go down again without any pattern or replicatable sequence.  We'd go repeat the steps again to get everyone in the office running again.
We called our Internet Service Provider and they constantly say, We see your modem and we see your router and from thier end everything is OK.
we replaced our router and switch and modem, twice!
Last friday, it dawned upon me, that everytime we turn on a VMware machine, this sequence of taking everyone down starts, which also explains the message that my users get for "IP Conflict Found"
So we do alot of VMware testing and lo and behold, it takes my Internet down.  My Yahoo and Gtalk would continue working but www is down when the VMware machines are started.
I do use bridged networking to all the VMware machines, but I dont know what else to set it at.
now, sorry for this long rambling but anyone have any clue on how to stop this?
Comment: Please update your question instead of leaving an answer with more details, it makes it easier for everyone to give you better answers.
Answer: You should only have one server serving IP addresses. The problem is you have two servers handing out new IP addresses to client computers.
Answer: Something somewhere is badly misconfigured -- my guesses:

Your VMWare machine & workstations have static IPs, and are both configured to use the same IP.
Your workstations are using DHCP, your VMWare system is static & using an IP in the DHCP pool.
You have N DHCP servers (where N > 1), and they're not doing ping-before-assignment.

(The problem here is N > 1, fix that.)

VMWare steals IP addresses


Problem with a Digital Piano

Question: So, I have a digital piano, a Casio CDP 130 that I bought at the start of the year. It has been working perfectly until yesterday a friend of mine was playing it and noticed that when the seventh B of the piano is pressed, all the keys near it lose all sensitivity. They sound louder even with the softest touch.
I don't use that part of the piano that often but it really bothers me because if I press that note and then another one near that one it sound really loud and breaks the harmony.
As I have said, it started happening recently. For details, I have a cat and she oftenly sits on top of the piano, but only when the piano is in its cover. I also clear it with napkins before and after playing. But even though I pressume that some of my cat's hair has gone into the piano and is causing this problem. I don't have a lot of knowledge on digital piano so I don't want to open it and break it completely, so if anyone knows how to resolve this problem it would very much appreciated.
Edit: As someone has asked in the comments, yes, the problems goes away as soon as I stop pressing the 7B key.
Edit2: So, I was about to open the piano in order to see if there was dust or something else in the key, but before I opened it I played the key once again to be sure it was that one, and suddenly the problem isn't there anymore. No matter if the key is pressed or not, the keys retain their sensitivity. So no more problem. I will be having an eye on that key even though in case something happens. Thanks to everyone who answered me.
Thanks for reading.
Comment: Is the piano still under warranty?
Comment: Sure sounds like dirt is causing one of the under-layers of the keys to get dragged around when you play the 7B key.  Does this problem go away as soon as you release that key?
Comment: Yes it goes away as soon as I release it. Added it now on the post.
Answer: If you're sure your cat has done no more than SIT on the keyboard, return it under warranty.  You must get at least a year?
If you must try to fix this yourself, and have the right sort of skills, dismantle down to the key contacts and associated circuit board.  My instinct tells me we're looking for an electrical problem here rather than a simple 'bit of dirt'.  But have a look.
Answer: Have you tried using a vacuum with a hose to get rid of any dust fallen between the keys? I had an issue with my Yamaha where one went much louder than the others. A good vacuum cured it a lot and it went away completely with more use.

Problem with a Digital Piano


Minimize the chance my email is blocked/filtered as spam

Question: I'm running a web-based store where order confirmations are sometimes blocked and don't reach the intended user. The structure of the business model is such that our product is marketed to the end-user by a 3rd parities - affiliates how are known entities to the end-users and email is freely exchanged between end-users and our affiliates.
Our confirmations being blocked is becoming a big enough problem that we are considering implementing a system where a 'confirmations' address is created within the affiliates domain, then we'd have our app send via the affiliate's mail server instead of our own. But that'd be lots of work.
The idea has been raised to have our app use our affiliates' email in the FROM field but still send from our server. My thinking is that would be detected at the end-users side and blocked just as often - we dealing with institutions large enough at least some checks up at the perimeter.
Is this assumption correct (more likely to be blocked) or is there a less round about way to send messages under the auspices of 3rd parties?
thx
Comment: See http://serverfault.com/questions/132113/does-sending-e-mail-in-the-name-of-customers-increase-the-risk-of-being-marked-as
Answer:
send valid messages - with nice / full headers, proper plain-text part and probably rich-text.
analyze what are the reasons for blocking - if someone uses spamassassin - check which rules were triggered by your mails.
ensure you send mails from server that is not on any blacklist - check it here or here or at other places. if you are blacklisted - find out why and 'drag' your ip out of blacklists.
configure properly rev-dns for your smtp server so it points to existing domain.
make sure you send mails with sender address and return address @valid.domain.com. add spf record to it that permits your smtp to send legitimate messages.
add your self to some white-lists like http://www.dnswl.org/
Answer: You can "spoof" their email domain: just make sure they have your mail server's in their SPF records.  I do this all the time for clients (on a smaller scale, but I'm sending out hundreds of confirmation e-mails, forum notifications, etc. every day from dozens of different domains; haven't had a problem yet).
Also make sure you have the items mentioned by pQd in place.
Answer: From our fearless leader here.  Most applies to regular email as well as code.
Answer: Here is a link from Jeff Atwood (Stack Overflow)
http://www.codinghorror.com/blog/2010/04/so-youd-like-to-send-some-email-through-code.html


How to expose edit link on editable areas for all authorized users?

Question: The ideas is that in Drupal 7, on mouse hover on a node (or block) a edit link  appear at top corner of the node (or block), just like  the cog that appears for admin when s/he hovers on editable areas.
By exposing the the edit link on hover, we can create a much better user experience, for users that are not necessarily familiar with Drupal backend. I appreciate your hints.
Answer: There are two ways to do this.
The "gears" feature is from the "Use contextual links" permission on admin/people/permissions.  If you give that to the appropriate roles, your users should see that.
Personally, I don't like the Contextual Links feature, mainly because the markup it adds can mess with theme layout when you have other positioning going on. I typically add in my own edit links to pages, usually below the content somewhere. I will sometimes use a display: none on them, and then have a link in the footer menu that shows them all via jQuery.


Finding angle boundaries of integration in spherical coordinates for $\theta $ and $\varphi $

Question: Let $S$ be the half-hemisphere $ x^2 +y^2 + z^2 = 1, y \ge 0, z \ge 0 $
The boundaries for the above question are
$$ 0 \lt \theta \lt \frac \pi 2 , 0 \lt \varphi \lt \pi$$
This example tells me to find the flux across S. I can set up the integration but I can't work out how to obtain the boundaries. I've tried drawing it up but I can't see it.
Another example is
Let A be the surface $x^2 +y^2 +z^2 = 100, z \gt 0$
The boundaries stated are $$ 0 \lt \theta \lt \frac \pi 2 , 0 \lt \varphi \lt 2\pi$$
Thank you in advance!
Answer: You are working with spherical coordinates using the typical Physics notation:$$x=r\cos\varphi\sin\theta\text{, }y=r\sin\varphi\sin\theta\text{, and }z=r\cos\theta,$$with $\varphi\in[0,2\pi]$, and $\theta\in[0,\pi]$.
In your first example, you want to have $y,z\geqslant0$. This means that $\sin\varphi\sin\theta,\cos\theta\geqslant0$. Since $\theta\in[0,\pi]$, $\sin\theta\geqslant0$, but $\cos\theta\geqslant0\iff\theta\in\left[0,\frac\pi2\right]$. On the other hand, $\sin\varphi\geqslant0\iff\varphi\in[0,\pi]$.
Can you work out the other example now?


How to mark up/edit short versions of pep band songs?

Question: Question
My band recently printed a brand new pep band flip book and we are required to make edits to the songs so that they are shorter.  Since the books are nice and new I am curious as to if their is a better way to delete and skip measures than simply crossing them off and/or drawing arrows.  Currently, allot of people use a combination of brackets, numbers, arrows, and crossing things off.  I would just use the Coda symbol, but that is technically improper.  Perhaps I should just go with "to measure X"?
Example

Song 1.long/original is 20 measures long.
Song 1.A is from measures 1 to 8.
Song 1.B is from measures 11 to 15 and skip to measures 19 to 20.
Song 1.C is from measures 5 to 12 and skip to measures 19 to 20.
Comment: How is the coda technically improper? Are crossing out and arrows, or "go to" more proper?
Comment: Good point, except the coda already has a musical definition and I was wondering if their was a method that was common/formal and well defined.
Answer: There is no standardized system for this. Anything that works for you — "to X", or even a coda symbol — is fine.
Allowing the book will be used only by you, just make sure your markings are easy to follow at a glance. To add a possibility to the ones you mentioned, you could color-code (e.g., highlight or under-/over-line) the played parts.
If the book is something that others will also use, then you'll want non-permanent markings. So, light pencil. Consider covering the unplayed parts with post-it notes rather than Xs.
For the best of all worlds, make your own copies. Either just make copies to mark up however you like, or cover the skipped measures with blank paper and then copy. In the latter case, you'll wind up with a "clean" version for yourself, and an unmarked original if needed.
Answer: If you are looking for a "standard" notation for a skipped section of music you can use the Latin term: vide.  Use "vi-" to mark the start, and "-de" to mark the end, with dashes spanning the section to be cut (i.e. vi- - -de).  But whether the performers will recognise this notation is perhaps unlikely; and you should have a footnote.
From the Dolmetsch Music Dictionary, Vi - Vl:

vide
vide is used as a mark in the score to show where a cut is to be made - the cut begins where Vi, sometimes followed by a long hyp[h]en (-), is marked and ends at the point where de is marked, so the performer skips, without a break, from the begin[n]ing to the end of the cut and continues on from there

From Elaine Gould's Behind Bars – The Definitive Guide to Music Notation, p. 496:

Optional cuts
Encountered usually in stage works, the relevant passage is marked at the top of the system with the divided word vi- -de (Latin, 'look!') and an explanatory footnote:

This is sometimes accompanied by a coda sign at the beginning or at both ends of the cut (the second coda sign is optional; as in a coda, this sign indicates a point from which to skip ahead).

For your particular example though, it seems like you are trying to deal with several different versions of the same piece, all represented on the same sheet of music.  You'll probably want to use rehearsal marks.  These are just large boxed measure numbers (as in the image above) or letters placed at the top of the score.  Explain the different versions as you have; e.g. Song 1.B: mm. 11–15, 19–20.  But be careful with the numbers because mm. 11-15 is a range that includes measure 15, but will stop at the [16] mark.
If you really want to have all the different versions encoded on the same sheet music this is inevitably going to be somewhat messy (especially given that they overlap).


Como criar um botão com o plugin Custom Scrollbar?

Question: Custom Scrollbar
A minha idéia é criar apenas um botão. Ao clicar nele ele ficar ativado e com o scroll automático funcionando, ao clicar novamente ele ficar desativado e desabilita o scroll automático.
Comment: Você poderia dar mais detalhes?
Answer: Cria o custom scroll para uma div:
$(".content").mCustomScrollbar({
    scrollInertia:150
});
Remove o custom scroll de uma div:
<code>$('#remove-scroll').click(function(e){
    e.preventDefault();
    $(".content").mCustomScrollbar("destroy");
});
</code>
Adiciona o custom scroll
<code>$("#adiciona-scroll").click(function(e){
    e.preventDefault();
    $(".content").mCustomScrollbar("update");
});
</code>
Re-cria o custom scroll
<code>$("#recria-scroll").click(function(e){
    e.preventDefault();
    $(".content").mCustomScrollbar({
        scrollButtons:{
            enable:true
        }
    });
});
</code>
Comment: Ficou um pouco confuso @VictorMendoça. Criei um JSFIDDLE e importei o css e o arquivo js do Custom Scrollbar, tente edita-lo  com sua logica? http://jsfiddle.net/jeffersonalison/4FTcU/1/
Comment: Fiz um fiddle, mas parece que o site do fonte deles está com pequeno bug no load dos javascripts. http://jsfiddle.net/vmendonca/CbfzT/

Dá uma olhada na página deles sobre remover/adicionas scrolls: http://manos.malihu.gr/tuts/custom-scrollbar-plugin/disable_destroy_example.html
 -
Recomendo você baixar o plugin em sua máquina e testar com o código que te passei ;]
Comment: Hum.. pior que parece estar com problema mesmo. Mas Victor minha ideia é de criar apenas um botao.. ai quando estiver ativado o scroll automatico funciona, senão estiver ativado ele não funciona.


strapi uploaded file manager not showing multiple file select

Question: I'm using stapi beta as a backend for a website i'm building, and have noticed that i have no option for multiple file selection in the admin - file upload section.
This feature seems to be in a screen shot on the strapi website , so i'm wondering if this is the same for other users or if i have some sort of 'bug' or corruption in my install
I have been running in production mode, which i thought might be the problem, but have also tried running in develop mode and still have the same results
I'm running straight out of the box with this plugin, so have no additional code
No errors are shown.
Answer: When you create a new Media attribute in your model, you have a checkbox just under the name input.
You have to activate it to be able to upload multiple files.

Note: this is the new modal that will be released in next weeks - but the checkbox is in the same palce.
Comment: Thanks for the response @Jim LAURIE, I can upload multiple images in the way described , what i was referring to was the tick boxes next to the uploaded item and the action and apply button above the tick boxes to the left in the first image on the page linked below.

https://strapi.io/marketplace/file-upload
Comment: Hoo OKay! I re-read your message. Cristal clear now. In fact this box have been designed but the feature is not developed in Strapi. So it's "normal" to not having it in your application.
Comment: OK, great, I'm glad it's not a glitch on my install , thanks for responding Jim.


Swift AnyObject Parameters

Question: I am using the following initializer in my Swift application:
init(items :NSArray, identifier :String, configureCellClosure: (cell :AnyObject, item :AnyObject) -> ()) {

}

Now, I need to utilize so I do the following:
 let sessionsDataSource = SessionsDataSource(items: [], identifier: "") { (cell :UITableViewCell, item :Session) -> () in

        }

But it complains about me specifying UITableViewCell and Session object. Can't I provide anything I want when I am using AnyObject?
Comment: Is 'Session' a struct or a class?
Comment: You're just getting confused. You mean `closure` which is the object, not `configureCellClosure` which is its type.
Comment: And you're failing to store the closure as a stored property of the class, so it's not available in other methods at the moment now anyway.
Comment: See my updated answer.
Answer: No, Swift cares too much about type safety. You're claiming to be passing in a [closure that takes as parameters a] UITableViewCell and a Session when you're really making no such guarantee. Functions are defined by their entire signature, which includes the function name, and the type and number of parameters. There's some larger design error or incorrect assumption you're making, such that you feel you need to accept a closure in your constructor that doesn't fit what you need to use it for.
Why not just force code that calls the constructor to pass in the right thing?
The closure can always, based on whatever mysterious logic, downcast cell from UITableViewCell to MyFunkyTableViewCell inside of it in order to configure properties specific to the latter subclass, and do other downcasts based on other conditional logic.
Comment: Your design is broken in a way that is hard to fathom with a tiny snippet. Your question probably needs to be about 4 times as long and spells out your design goals and some specific scenarios. I mean, it's called configure**Cell**Closure, and yet you don't want to define cell as what it is, a UITableViewCell. Anything that *inherits* from UITableViewCell is perfectly acceptable here.
Comment: Basically this datasource can be used by many different entities so I will never know what is the correct type! However, I can cast it to the correct type once I get the cell and item back.
Comment: Another possibility would be to define custom protocols and use them as types for the closure arguments instead of AnyObject.
Comment: I accept your suggestion for UITableViewCell but the second argument item can be anything! I guess anything which inherits from NSObject.
Comment: @JohnDoe How does your code use the second argument value without knowing anything about the API?
Comment: @jlehr When the closure returns the item I convert it to the type I want and then use it.
Comment: For some reason Swift does not like me using AnyObject. I can understand the type safety here but AnyObject was trying to provide flexibility.
Comment: When I was asking for a longer question, I meant along the lines of: what is the full *range* of types that this closure can generate for the 2nd param? How does that help you come up with a sensible constraint of a parent class type or protocol here? Unless you constrain your design it can spiral out of control. Granted such advice is a bit out of scope for this forum, but...anyway.
Comment: In any case, there's two separate issues here: good design, and getting the thing to compile. Use AnyObject all day and night, but the actual type being passed in (closure of (AnyObject, AnyObject)) has to match what's **wanted** by the receiver (closure of (UITableViewCell, Session)). If you had an AnyObject, would you understand that a function that expected a `String` argument would not accept it, such that your code wouldn't compile?
Comment: Thanks I actually got it to work! In the end where I receive the cell and item I caste the item to the entity I want and then simply use it.
Answer: The type signatures don't match.  In the init declaration, the type of the closure is (AnyObject, AnyObject) -> (), but when you actually call it, the type of the closure is (UITableViewCell, Session) -> (). These aren't the same types.
In the init declaration, you're telling the compiler that you might call the closure with two parameters of any object type. The compiler believes you. It doesn't look at what you actually pass to the closure when you do eventually call it.
But later, when you actually pass in a closure, you're passing a closure that cannot take any two object references. It requires a reference to a UITableViewCell and a reference to a Session. If the program calls the closure with something that's not a UITableViewCell for cell, or something that's not a Session for item, then the program will probably crash. But you told the compiler (in the init declaration) that you might indeed call the closure with something other than a UITableViewCell or a Session. The compiler refuses to compile this program because it might crash.
Try this instead:
let callback = { (cell: AnyObject, item: AnyObject) -> () in
    guard let cell = cell as? UITableViewCell else {
        return
    }
    guard let item = item as? NSPredicate else {
        return
    }

    // do work here
}

UPDATE
Your new error is because you're trying to call configureCellClosure, which is a type, instead of closure, which is the argument (to init) of that type. You need to rename configureCellClosure to ConfigureCellClosure, create a property in SessionDataSource of type ConfigureCellClosure, initialize the property in init, and call the property in tableView:cellForRowAtIndexPath:.
    typealias ConfigureCellClosure = (cell: UITableViewCell) -> ()

    private let closure: ConfigureCellClosure

    init(closure: ConfigureCellClosure) {
        self.closure = closure
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
        closure(cell: cell)
        return cell
    }

Comment: I just think that encouraging the OP to continue to use AnyObject in code that he controls furthers rather than discourages bad design. AnyObject is largely for interacting with legacy Objective-C APIs.
Comment: @BaseZen Basically, the whole point is to use it in UITableViewController. This code can be reused by almost all the controllers and special needs can be fulfilled by the cellConfigureClosure.
Comment: @JohnDoe A little awkward with two comment threads running, but doesn't the final (edit -added) paragraph of my answer make the most sense?

Swift AnyObject Parameters


How does UEFA spend its profits from broadcasting rights?

Question: In light of the fact that anyone who wants to watch Euro 2012 games has to pay UEFA (either pay directly through pay-for-view, or pay indirectly though the cable company), I am interested in knowing where this money goes.
I've been recently told that this money is not used to pay for the expenses of organizing football games (building stadiums, etc.), and the cities that host the games pay these expenses.
What does UEFA financially contribute to football that justifies the huge profits it makes by selling the broadcasting rights of the games?
Comment: I think it is worse for the Olympics.
Answer: UEFA's finance report for 2010/2011 shows exactly where their income originated from, and what they spent it on;
They summarise that football related income largely originates from;

broadcasting rights
commercial and licensing rights
ticket sales
hospitality sales
other football-related revenue: fines, FIFA contributions

However, football-related expenses includes;

distributions to the participating teams - Don't forget this one! This cost them a  total of €1,000,589,000 in 2010/11!
direct contributions to local organising committees (LOC)
agency commissions
various costs incurred during events such as technical and audiovisual
equipment and other material
rights-delivery costs such as signage, event promotion and rights
protection expenses
direct costs related to hospitality and TV production
ICT expenses such as IT projects in the football and event domains
match officials such as referees and delegates, as well as related
expenses (travel, accommodation and allowances)

Of course like any big organisation, they have running expenses as well which include;

salaries
travel expenses
marketing
rent, building maintenance and security


Trouble using new NSNumbeFormatter

Question: I have an app which read an import in a TextField then process it using
<code>let number = NSNumberFormatter().numberFromString(numberString)
if let number = number {
    let floatValue = Float(number)
}
</code>
While I'm working with regional formats which use comma as decimal separator (like Italy or Germany) everything works (I can write 17,80 or 17.80 and they work both). When I work with regional formats which use dot as decimal separator (like USA), when I use dot as decimal separator (17.80) OK but if I use comma (17,80) app crash!
How can I solve it?
Comment: Collin is right, my question is to understand the reason of this problem, I haven't asked how to convert a string with comma to a string with decimal!
Answer: Would looking at the string and changing it to whichever format you know (e.g. making it always use a decimal separator) won't cause problems be a viable fix here?
Comment: Best thing would be to understand why with some regional formats comma works and with other crash. Otherwise a solution could be check if TextField.text contains a comma and replace it with a dot.
Comment: I agree -- the best thing would definitely be to understand the underlying reason and fix it that way. Hence why I said replacing the characters would be a "fix" and not a "solution".

Trouble using new NSNumbeFormatter


Prove that $f(x) = x^3 -x $ is surjective

Question: Problem:  Prove that the mapping $ f: \mathbb R \rightarrow \mathbb R , f(x) = x^3-x$ is surjective.
Let $y\in \mathbb R$ such that $f(x)=y$ for some $x\in  \mathbb R$. Then $x^3-x=y$. If we can express $x$ in terms of $y$, then we can say something about surjectiveness. But I stuck at that point.
What is the way to solve this problem?
Comment: $\lim_{x\to-\infty} f(x)=-\infty$ and $\lim_{x\to\infty} f(x)=\infty$ and the function is continuous hence it is surjective.
Answer: You have $\lim_{x\to\infty}f(x)=\infty$ and $\lim_{x\to-\infty} f(x)=-\infty$, thus $f$ is surjective by the intermediate value theorem.
Answer: Any odd-degree polynomial with real coefficients has at least one real root (in fact, it has an odd number of them, counted with multiplicity). Now, consider the polynomial $x^3-x-a$ for any $a \in \mathbb{R}$. A root of this polynomial then gives a real number $b$ for which $b^3-b=a$. Hence, $\forall a \in \mathbb{R} \ \exists b \in \mathbb{R} \ (b^3-b=a)$, so the function $f(x)=x^3-x$ is surjective.
More generally, any odd-degree polynomial with real coefficients is surjective (from the reals to the reals).


How many symphonic instruments in the same group to specify

Question: In a symphonic orchestra, or any other, how many of the same instruments do I specify in the score, if they play the same score?
For example, for violins, there is just one line.  What about the woodwinds or brass instruments?
Comment: Hi @EugeniyaBentsman - welcome. If you have an answer that is valuable, please select the check mark next to it to indicate you accept that answer. That helps future visitors.
Answer: Violins are traditionally divided into two sections, so there will normally be two lines.  In addition, the violas, cellos, and basses are one section each, though sometimes the basses and cellos are written as one section and sometimes as two.  Exceptions are fairly frequent.  The number of players in each section is usually not specified; it is left to the conductor's discretion.
Other instruments are typically written for a single player on each part (though multiple parts are typically written on a single staff un the score).  There are examples of performances where winds and/or brass were "doubled" in the sense of having multiple players for each part, but this is not the standard practice (in an orchestra; bands are another matter entirely).  So for example a standard classical-era woodwind section will be written on four staves in tbe score, one each for flute, oboe, clarinet, and bassoon, with two parts on each staff, played by one player each, for a total of eight woodwind players in tbe orchestra.  As orchestras expanded in tbe 19th century the number of staves increased.


Why are the cardinalities of these subsets not adding up to the universal set?

Question: Given a set of six letters $S$ = {A, B, C, D, E, F}, I am trying to find how many lists of four letters could be made that have exactly no repeated letters, exactly two repeated letters, exactly three repeated letters, and exactly four repeated letters.
The set of $6^4=1296$ possible lists in total represents the universal set of lists and has cardinality of $|S| = 1296$. Let $U$ = the universal set, and let $X_a$ represent the subsets of $U$ where $a$ is the number of repeated letters in the elements of the subset.  For example, ABCA $\in X_2$ and DAFE $\in X_0$.
By the addition principle, since $\bigcap_{a \in {\{0, 2,3,4\}}}X_a =\emptyset$, then $|\bigcup_{a \in \{0, 2, 3, 4\}}X_a|=|U|=1296$.  But this does not seem to be the case when I attempt to solve this problem.  Please let me know where I go wrong.
In order to find $|X_0|$, it is a permutations problem.  $6*5*4*3=360$, so there are $360$ lists of four letters with exactly no repeated letters.
$|X_2|$ and $|X_3|$ are where I am less confident in my method.
In order to find $|X_2|$, there are $4 \choose 2$ ways to choose two spots of the four possible in the list.  That means for any given spot in the list, there are $6$ letters that spot can be, but for another spot, but exactly one other spot must be that same letter.  So for any given choice of two spots in the list such as the first spot and the second spot, $6*1*5*4$ ways of arranging the letters for that specific choice of spots in the list.  Because of this, I believe that $|X_2|$ = ${4 \choose 2} * 6*5*4*1=720$.
In order to find $|X_3|$, there are $4 \choose 3$ ways to choose three spots of the four possible in the list.  I believe that the same logic as the previous step applies, where there are $6*1*1*5$ possible ways of choosing letters for each choice of three spots in the list.  Following this logic, there should be $|X_3|$ = ${4 \choose 3} * 6*5*1*1=120$.
Lastly, to find $|X_4|$, there are only six possible ways to arrange these letters where all four are the same:
AAAA, BBBB, CCCC, DDDD, EEEE, and FFFF, so $|X_4|=6$.
After all of this $|X_0|+|X_2| + |X_3| + |X_4| = 360+720+120+6=1206$ which is $90$ off from what it should be.  Can someone please explain what I've done wrong?
Answer: There is one more class of lists that you didn't count: lists with two different pairs of repeated letters, like AABB.  There are $\binom{4}{2}/2=3$ ways to split the places in the list into two pairs and then $6\cdot 5=30$ ways to assign different letters to each pair, so this accounts for the missing $90$.
Comment: THANK YOU SO MUCH!  It seems so obvious but I can't believe I missed this for hours lol.


Java archive file distribution and execution

Question: I've made a Java program I would like to make available to people of every stripe of computer (Windows, Linux, and OSX). So, as far as I know, all I have to do is make a Java archive, and the end users are able to run it with their particular flavor of Java.exe file.
If the above is correct, my questions are :
1) Is it possible to download each of the three kinds of Java.exe file from somewhere and package them together with the Jar file (do the end users have to have more than the appropriate Java.exe file to run the Jar file)
2) Is there a utility with which I can make the appropriate kind of zip file for each of the three kinds of destination machine (i.e., zip file, gzip file, and from what I have found on the web, an OSX zip file).
Comment: `java.exe` (or whatever it is named on other systems) alone is not sufficient to execute a Java program. You need a full virtual machine, which consists of a lot of more files. (Simply compare the download size with the size of your java.exe to see that there must be more.)
Answer: These days, java is considered a mainstream OS add on, like adobe reader, flash, and other very common "plugins".
Including java with your distribution is a very bad idea. Mainly because it's big and you then take on supporting latest releases.
Just send out the jars etc and perhaps a some shell scripts (.bat for windows and .sh for unix/linux) to start up your app. This is a common patter used by mainstream open source software, including Apache Tomcat, which is used by 1000's of sites.
If you want to get fancy, your scripts could detect if java is installed and redirect the user to the appropriate download page to install java.
Answer: The best strategy if your app. has a GUI & you can distribute from a web site is to deploy the app. using Java Web Start.  Use deployJava.js to (help) ensure the end user has a suitable minimum version of the JRE.
Note that even that will not work to get the app. running on all computers.  Some have no JRE and no user permissions to install one.


Lower limit of $\sqrt[n]{1^n+2^n+...+n^n}$ with sandwich rule

Question: I was asked to find (by the sandwich rule) the limit of: $$\lim_{n\rightarrow \infty}{\sqrt[n]{1^n+2^n+...+n^n}}$$
The upper limit is quite immidiate: $C_n = \sqrt[n]{n^n+n^n+...+n^n}$.
As for the lower part I'm facing quite an understanding conflict:
I'm looking for $A_n$ for which: $$\forall n\in \mathbb{N}: a_n \leq \sqrt[n]{1^n+2^n+...+n^n}$$
So I wanted to pick $\sqrt[n]{1^n+1^n+...+1^n}$  but I have a dillema:
$$\lim_{n\rightarrow \infty}{\sqrt[n]{1^n+1^n+...+1^n}} = 1$$
OR
$$\lim_{n\rightarrow \infty}{\sqrt[n]{1^n+1^n+...+1^n}} = \infty$$

Since $1$ to any power is $1$ we obviously get: $1^n=1$. Therefor we have $$\lim_{n\rightarrow \infty}{\sqrt[n]{1^n+1^n+...+1^n}} = \lim_{n\rightarrow \infty}{\sqrt[n]{n}} = 1$$
Since $n \rightarrow \infty$ we have infinite amounts of $1$'s. Therefore we virtually have $\infty$ under the $\sqrt[n]{}$ sign.

Ultimately I can't seem to determine what's the limit: $\lim_{n\rightarrow \infty}{\sqrt[n]{1^n+1^n+...+1^n}}$.
Is there a ground rule that helps me decide? I'm more prone to decide to go with what I know: $$\lim_{n\rightarrow \infty}{\sqrt[n]{n}} = 1$$
But since I have an inifinite number under the root, Im a bit skeptical. Plus, I already know the answer is $\infty$, but I insist on solving this conflict of mind.
Comment: Again, no: at the limit the number is $\;1\;$ , i.e.: the limit is $\;1\;$ . You can only evaluate limits of real sequences formed by real numbers (in real analysis, of course). Infinity is **not** a real numbers.
Comment: No, you don't an infinite number under the root: for any $\;n\in\Bbb N\;$ you have a pretty finite number under the root, namely the number $\;\sqrt[n]{1^n+\ldots +1^n}=\sqrt[n]n\;$
Comment: Thank you for your answer,
But at the limit of $n \rightarrow \infty$ this number is infinite, and the problem is about this limit. should it matter?
Comment: Thank you.
Suppose I insist on solving it with Sandwich Rule, do you have any clever way to come up with a lower series as limit?
Comment: How do you know that $\sqrt[n]n\to 1$ ???
Answer: $$\lim_{n\to\infty}\sqrt[n]n$$ is an indeterminate form $\infty^0$.
Taking the logarithm,
$$\log\sqrt[n]n=\frac{\log n}n$$ and the numerator grows much slower than the denominator. By L'Hospital, this limit is also
$$\lim_{n\to\infty}\frac1n.$$

It is a little funny that you are worried by the fact that the sum $1+1+1\cdots1$ diverges ("virtually $\infty$"), while you don't care about $n$ being exactly that sum !
Comment: He wrote he already knows that...and, besides, this limit is unrelated to his problem, in fact, and the OP seems to be confused by this.
Comment: @DonAntonio: my answer is about the form being $\infty^0$, because this is what puzzles the OP: how can an infinite sum lead to a finite value. I am also explaining the OP that there is no dilemma. By the way, the OP didn't answer my question about how he knows that $\sqrt[n]n\to1$.
Answer: What is $\lim_{n\rightarrow \infty}{\sqrt[n]{1^n+1^n+...+1^n}}$?
For any positive integer $n$, the following is an identity:
$$\sqrt[n]{1^n+1^n+...+1^n}=\sqrt[n]{n}$$
The question above is equivalent to ask what is $\lim_{n\rightarrow \infty}{\sqrt[n]{n}}$.
This is a well known limit and it appears in examples in lots of textbooks in real analysis. It is a fact that $\lim_{n\rightarrow \infty}{\sqrt[n]{n}}=1$. The proof in Rudin's Principle of Real Analysis uses the binomial theorem (and the sandwich theorem!). The trick there is writing $x_n=\sqrt[n]{n}-1$ and observe that
$$
n=(1+x_n)^n\geq \frac{n(n-1)}{2}x_n^2,\quad x_n\ge 0,
$$
which implies
$$
0\le x_n\le \sqrt{\frac{2}{n-1}}.
$$
See also this post: Intuitive reason why $\sqrt[n]n\to 1$ as $n\to\infty$?
What goes wrong in the argument for $\lim_{n\rightarrow \infty}{\sqrt[n]{1^n+1^n+...+1^n}}=\infty$?

Since $n \rightarrow \infty$ we have infinite amounts of $1$'s. Therefore we virtually have $\infty$ under the $\sqrt[n]{\phantom{1}}$ sign.

This argument is not even wrong. The symbol $\infty$ is not a real number. Beginners in real analysis should strictly follow definitions regarding any statements containing the symbol $\infty$ or the word "infinite". In the level of "intuition", note that in the expression
$$
\sqrt[n]{\underbrace{1^n+\cdots+1^n}_{n \textrm{ terms}}},
$$
 not only the radicand $n=\underbrace{1^n+\cdots+1^n}_{n \textrm{ terms}}$ goes larger as $n$ becomes larger, the index $n$ in the radical $\sqrt[n]{\phantom{1}}$ becomes larger too!
What is $\lim_{n\to \infty}{\sqrt[n]{1^n+2^n+...+n^n}}$?
$$
\sqrt[n]{1^n+2^n+...+n^n}\geq \sqrt[n]{n^n}=n
$$
which implies that
$$
\lim_{n\to \infty}{\sqrt[n]{1^n+2^n+...+n^n}}=\infty.
$$
Note that in this case, one cannot apply the sandwich theorem
for sequence of real numbers which says the following:
Let ${\displaystyle (a_{n}),(c_{n})}$ be two sequences converging to a real number $\ell$ , and $(b_{n})$ a sequence. If ${\displaystyle \forall n\geqslant N,N\in \mathbb {N} }$ we have $a_{n}\leqslant b_{n}\leqslant c_{n}$, then $(b_{n})$ also converges to $\ell$.
Answer: First of all, it must be clear by now that your sequence's limit is $\;\infty\;$, and if you insist in using the sandwich theorem then you could write
$$\infty\xleftarrow[n\leftarrow\infty]{}\sqrt[n]n\,n=\sqrt{n\cdot n^n}\le\sqrt[n]{1^n+\ldots +n^n}\le\infty$$
In this cases though, in which the sequence is clearly non-negative, it is enough to write the left hand inequality, as the right hand one is trivial.
Answer: We can get better inequalities than those presented.
$$ n -1 \;  \;   \; \;  < \; \left( \sum_{j=1}^n \;  j^n \right)^{1/n} \;  \; \;  <  n+1  $$
At least two answers point out that the sum is bigger than its final term $n^n,$ taking the $n$th root gives
$$ \color{red}{n  \;  \;   \; \;  < \; \left( \sum_{j=1}^n \;  j^n \right)^{1/n} \;  \; \;  <  n+1}  $$
PROOF:
If we have $f(x) > 0$ and $f'(x) > 0,$  then
$$ \int_{a-1}^{b} \; f(x) \;  dx \;  < \; \sum_{j=a}^b \;  f(j) \; < \; \int_{a}^{b+1} \;  f(x) \; dx   $$
here we are taking $f(x) = x^n,$   then $a=1$ and $b=n.$
$$ \int_{0}^{n} \; x^n \;  dx \;  < \; \sum_{j=1}^n \;  j^n \; < \; \int_{1}^{n+1} \;  x^n \; dx   $$
$$ n^n \left(  \frac{n}{n+1} \right) \;  < \; \sum_{j=1}^n \;  j^n \; < \; \; (n+1)^n - \frac{1}{n+1} <  (n+1)^n  $$
$$ n \; \left(  \frac{n}{n+1} \right)^{1/n} \;  < \; \left( \sum_{j=1}^n \;  j^n \right)^{1/n} \;  \; \;  <  n+1  $$
$$ n \; \left(  \frac{n}{n+1} \right)  \; <  \; n \; \left(  \frac{n}{n+1} \right)^{1/n} \;  < \; \left( \sum_{j=1}^n \;  j^n \right)^{1/n} \;  \; \;  <  n+1  $$
$$ n \; \left(  \frac{n}{n+1} \right)  \; \;  < \; \left( \sum_{j=1}^n \;  j^n \right)^{1/n} \;  \; \;  <  n+1  $$
NOTE that
$$  \frac{n-1}{n} < \frac{n}{n+1}  $$
$$n \; \left(  \frac{n-1}{n} \right)  \; \;   \; \;  < \; \left( \sum_{j=1}^n \;  j^n \right)^{1/n} \;  \; \;  <  n+1  $$
$$n -1 \;  \;   \; \;  < \; \left( \sum_{j=1}^n \;  j^n \right)^{1/n} \;  \; \;  <  n+1  $$
Answer: Hints:

${\sqrt[n]{1^n+2^n+...+n^n}}\ge \sqrt[n]{n^n} =n$
$n \to \infty$ as $n \to \infty$
Comment: This does not answer the question.
Comment: @YvesDaoust I could add $n \to \infty$ as $n \to \infty$, but I thought that would be obvious
Comment: Did you read the question ? Seriously ?
Comment: @YvesDaoust Using $\sqrt[n]{n}$ as a lower bound will not allow the sandwich rule to be used
Comment: Ok, this confirms you didn't read the question.
Comment: @YvesDaoust My reading is that the question is asking about finding the limit of $\lim_{n\rightarrow \infty}{\sqrt[n]{1^n+2^n+...+n^n}}$ by the sandwich rule


Filter by object array element and return only the value of a field in the array object MongoDB

Question: I'm using MongoDB 5.0.10 and the aggregation pipeline. I am trying to find out if there is a way to filter an array of objects AND return only the value of a field within the returned array object. I can easily filter the array based on a field value within the array. I currently can achieve what I want in 2 stages. I'm just trying to see if I can return a value within the same stage. I'm using a projection and $arrayElemAt to filter the array. Then I perform another projection to get the value I want.
Sample document:
{
  "_id": 1,
  "lastOpenedList": [
    {
      "_id": 4,
      "dateTime": {
        "$date": {
          "$numberLong": "1659970718606"
        }
      }
    }
  ]
}

First stage:
$project: {
'lastOpened':{$arrayElemAt: [
    {$filter: {
      input: "$lastOpenedList",
      cond: {
        $eq:[
          "$$this._id", '4'
          ]
      }
    }},0
    ]}
}

Second stage:
$project: {
'lastOpened': '$lastOpened.dateTime'
}

Result:
{
  "_id": 1,
  "lastOpened":
    {
        "$date": {
          "$numberLong": "1659970718606"
        }
     }
}

Answer: Query

filter can't change the member only keep it or not
we have 2 options $map + $filter => map keep those we want, and null in others, and then with $filter remove those nulls
other option is $reduce, and keep only those we want, in general $reduce is the most powerful
here $reduce, and if match keep it

Playmongo
aggregate(
[{"$project":
   {"_id": 0,
    "lastOpened":
     {"$reduce":
       {"input": "$lastOpenedList",
        "initialValue": null,
        "in":
         {"$cond":
           [{"$eq": ["$$this.dateTime", 2]}, "$$this.dateTime",
            "$$value"]}}}}}])

Comment: Thank you! This seems right but did you mean {"$eq": ["$$this._id", 5]}... instead of {"$eq": ["$$this.dateTime", 2]}? I need to filter by the _id in the array object. I changed your Playmongo to filter by id and it returns what I want, if I change the id value passed into the function.
Comment: ok good i wasnt sure what exaclty output you need, but this is common way, reduce or map+filter(remove nulls)


Problems with stacking div boxes vertically

Question: I have the following code:
.blueleft {
    background-color: white;
    width: 300px;
    border: 25px #cee2e8;
    padding: 25px;
    margin: 40px;
    float: left;
    font-family: "berlin sans fb";
    color: gray;
    font-size: 20px;
    text-align: center;
    vertical-align:middle;
}

.blueright{
    background-color: white;
    width: 300px;
    border: 25px #cee2e8;
    padding: 25px;
    margin: 40px;
    float: right;
    font-family: "berlin sans fb";
    color: gray;
    font-size: 20px;
    text-align: center;
    vertical-align:middle;
}

However I still get the box elements stacked horizontally like this:

I'm not sure what I need to do to make sure that the div boxes stack vertically, and still be able to format horizontally and centered if needed. I've been looking around but have been unable to find code that I could put into the html document.... how would I start from scratch when formatting the DIV elements in css?
Comment: Post your HTML please. We need a [mcve]. But the issue seems to be your use of floats
Comment: What exactly are you trying to achieve? If you want you could put    `display : block` to stack them vertically.
Comment: It seems the problem is that you floated your divs
Comment: Possible duplicate of [How do I automatically stack divs vertically inside a parent?](https://stackoverflow.com/questions/19284923/how-do-i-automatically-stack-divs-vertically-inside-a-parent)
Comment: @LucasWieloch I've already tried removing my float codes and even my margin codes.
Comment: @j08691 for the html I simply did  and floated an image withing the div element, along with adding some text. For the other box element I tried both  and  I also tried automatic and relative position tags but they didn't work either.
Comment: @VipulSharma All I'm trying to do is to get my div elements to flow vertically. I'm working on a mini website choose your own adventure type game and would like it to be formatted vertically for some of the website pages. Hopefully that clarifies it a little!
Answer: Here is a simple example with Flexbox:

.flex-container {
  display: flex;
  flex-direction: column;
  background-color: DodgerBlue;
  height: 400px;
  align-items: center;
  justify-content: center;
}

.flex-container > div {
  background-color: #f1f1f1;
  width: 100px;
  margin: 10px;
  text-align: center;
  line-height: 75px;
  font-size: 30px;
}

1

2

3


How To Improve My Sightreading?

Question: I've been reading music since I was five years old, but I learned how on the piano, never on the guitar.  I find that when I play guitar, I think of the notes as they relate to each other spatially: "that note is one string over and two frets up from this note, so they form a fifth", that sort of thing.  But I don't know the notes on the fretboard well enough to identify them instantly, and this makes sightreading difficult.  I want to be able to sightread well enough so that when the bandleader calls out a Real Book tune I've never heard before, I can play it on the spot.  How can I improve my sightreading?
Note: I'm emphatically not asking "should one learn how to read?"  No need to start a religious war.  I know how to read; I want to learn how to read faster.
Comment: Am I the only one to think that you title is misleading? It's more about learning the notes on the fretboard http://music.stackexchange.com/q/1621/29 than actual sightreading.
Comment: Is there a reason you're not just practicing reading out of your real book?
Comment: I am, but there are a lot of tunes in that thing, and I don't know them all by a long shot.
Comment: I started the same way, with piano when I was really young. It's a great starting point because the piano is the composer's instrument - every note is visible, not reached by changing air pressure or adjusting the bite on a reed or multiple valve combinations. The guitar is very repetitive. Learn a scale and it repeats up and down the neck and across it (until you hit the B string). Octaves, thirds, fifths, fourths, flatted-sevenths are the same way. Learn them once and you pretty much know them all. Then it's a case of saying, "here is C, here is the next C, here is G, another G..."
Comment: Another nice thing about the piano is that the keys match to pitches in a one-to-one relationship, i.e. there aren't several different ways of playing the same pitch, as there are on the guitar.  That's a double-edged sword, of course, but it sure makes sightreading easier.
Answer: In my personal opinion; the simplest and most effective way to learn notes/chords on the fretboard is using patterns; in the same way that when you glance at a chord in written music you can see from its shape what type of chord it is.  EG: knowing that chords are built from thirds and any deviation from that is usually 'stand out' in written music. Just to re-enforce what Anna said; recognising patterns in the music and mapping those patterns to the guitar patterns will help you a lot.
Your spatial way of learning on the guitar is a pretty good method; if your able to read the specific key signature, and you know scale/intervals/modes, the diatonic triads; and are able to apply them to the key signature then you are half way there.
Always remember that with guitar chords/scales that when starting on a particular string; the root note changes, but the pattern never does.  If you can already read music then its literally just a case of practice practice.
Answer: There are several approaches you can take to learning the fretboard.

You can either go by scales and sound out every note in the scale as you play them to memorize what the notes are
You can go the rote memorization route and memorize notes at the significant frets (5, 10) and just go from there -- most notes you need you'll be able to reach either by going up or down a tone/semitone from open strings, 5th, 10th, or 12th fret.
Pick a note and find it everywhere on the guitar.
Some combination of the above.

Whatever your chosen method is, repeat it until the notes are burned into your mind and you don't have to think about it anymore. Same as you'd know which notes were C's on the piano's keyboard, for example.
It looks like you are already familiar with the interval relationships between notes and how to determine them on the fretboaard, and that'll help you in your sightreading as well. Work on identifying the intervals in sheet music, so that you start recognizing them at a glance. Combined with knowing the notes on the neck cold, you should be able to sightread more seamlessly.
Comment: You say *Same as you'd know which notes were C's on the piano's keyboard*. It's NOT the same! On the piano, you only need to learn it in one octave, and the pattern repeats itself visually related to the groups of 2 and 3 black keys. On the guitar frets, it is no such visual pattern to help you.
Comment: @awe I meant that you can learn the fretboard and have the knowledge of where a note is be as ingrained in your head as knowing where a note is on the piano keyboard. It's certainly true that it's easier on the piano as you say.
Comment: @awe the patterns on the guitar are less immediately obvious; but they are there nontheless.
Answer: Like most things with guitar, the only real solution is to practice, practice, practice. That said, there are some tips for memorizing which notes occur where that will help with your practicing (most of this post is recycled from one I made on Reddit a while ago).
To find a specific note on the neck that you don't know, you just have to find the nearest note you do know. I've listed the notes on the frets below that I consider easiest to memorize.
Open string notes (low to high):
E A D G B E
Fifth fret notes:
A D G C E A
Seventh fret notes:
B E A D F# B
Twelfth fret notes:
E A D G B E
What makes them easier? Different things. I'll assume you know all the open strings by heart -- If not, start there! Once you have those memorized, the twelfth fret is easy. The open string notes are just an octave higher.
The seventh fret is next easiest. Each note on the seventh is an octave higher than the previous open string. The seventh fret on the fifth (A) string is an octave up from the sixth (E) string. The seventh fret on the fourth (D) string is an octave up from the fifth (A) string... get the idea? For reasons I'll get to later, this doesn't quite work for the second (B) string.
Now, the guitar is normally tuned in perfect fourths. Each string is a fourth higher than the previous. How many semitones are in a fourth? Five. Each fret is one semitone. Moving five semitones (frets) up the neck is the same as moving one string over. So the notes at the fifth fret are just the same as the open-string notes on the next string over. Fifth fret of the sixth string is A, fifth fret of the fifth string is D. Again, this breaks down at the B string.
So what's the problem with the B string? It's only tuned a major third above the previous string. Everything I've already said applies just the same to the B string, but it's shifted up by one fret.
--TANGENT ALERT--
Want to see something that will amaze you? Play an E-major chord. Now play an A-major. Now play a D-major. Each chord has the same interval pattern since they're all major chords. Each chord is also a perfect fourth higher than the last one - each root note is one string over from the previous. Examine the shapes of the chords - each shape only differs by one semitone from the last one - and that moved semitone only occurs on the B string. Each chord is the same shape, it's just been shifted when it crosses over the B string to compensate for the different tuning. If you had a guitar tuned in all fourths, you could play those three chords using the exact same chord shape.
But I digress.
--TANGENT END--
More tips: Learn the notes on the E strings first. Why? Because if you know all the notes on the low E string, you know all the notes on the high string, just two octaves up.
Know how to play an octave from any note. You probably already know it, but the most common octave shape is easy to remember - it's a capital 'L'. Two frets up, two strings over. If you know how to play a note on any of the strings, you can find it an octave up without moving your hand along the neck. This needs to be changed when you cross over the B string, but you can figure that out.
Also worth noting: Every note on the D string is a major ninth (octave + major second) above the same fret on the low-E string. That is, to find any note on the D string, just go down two strings and two frets (an octave) lower.
Hope this is helpful.
Answer: Ok, it might sound odd, but I used to take an old hymnal, no longer used at a church, and start reading the scores from it.
They're clearly laid out, and designed for people who are not classically trained musicians. The harmonies vary from straight-ahead classical, to some pretty cool chord structures.
Mostly though, those will be a decent basis for harder reading tasks that don't have tablature, written out chord changes, etc. In other words they're a dose of reality. I'd analyze the scores and add my interpretations of the chord changes too.
You can find lots of used hymnals at used book sales. Or, go to your local church, and ask if they have one that is trashed and nobody uses any more.
Answer: I'm pretty sure I read this in the bass guitar handbook, or something. But it's certainly helped me learn the fretboard (both for guitar and bass guitar).
Play either a scale starting at some random position of the fretboard, or simply move up and down the fretboard, playing uniformly. When you hear some noise outside - someone talking, or a car revving - then stop playing and try to say what note you've just played.
It is also very useful to learn where the open strings EADGB correspond to on the actual fretboard, both up and down strings.
Answer: I'm going through the opposite problem from you.  I can sight read guitar and have recently started learning piano. I think the difference is that when sight reading the guitar, I pretty much have the notes and possible locations memorized.  Thus, when I see a high A, I know it's either the 5th fret E String or 10th fret B String (rarely 14th fret G String).  In other words, my memory recall is in absolute locations.  Sight reading with this approach is only possible because over time you learn to feel where your hand is at on the guitar.  Thus, it is possible to quickly transition between positions on the guitar without looking rather easily.
On the other hand, now that I'm learning piano, I am struggling because there is no sense of feel of location on the piano.  Any piano key feels just like the rest.  Sure, I could look at the keys and tell the difference but that defeats learning to sight read.  Anyways, the one thing you have going for you on the piano is that you can look at the note and know exactly how many keys away the next note is from the one you just played (ie. you know the relative distance).  Over time, I'm sure that becomes natural (I haven't gotten there yet). Thus, I'm struggling to adjust my thinking to playing a note 3 keys away (on the piano) instead when I am intuitively thinking of a specific location (ie. the A Note). The problem is that I have no frame of reference to transition to a specific note since all the keys on the piano feel the same and if I forget where my current hand positions are at, the absolute thinking invariably gets me to play the wrong notes.
Anyways, I hope that made sense.  What you need to do is memorize the fretboard and be able to transition to any note without looking.  Think in terms of absolutes when on the guitar.  Relative when on the piano.
Comment: I'm in the middle of learning sightreading on the piano and I'd say that both absolute and relative thinkings are possible (at least that's how it goes for me). Sometimes I read relatively: "the next note will be 2 tones lower", and sometimes absolutely: "the next note is an A, and I remember where my hand is right now, and I can say that A will be right there". It's helpful to develop muscle memory for the intervals, so that you can play a tone for example one octave higher with no brain effort.
Answer: I learned my notes by learning all (as many as I can find) moveable barre chords and what each note is across the strings.  As I move the barre up and down the neck I would note how each note changed on each string.  Example:
The venerable Gmajor barre chord is 3 5 5 4 3 3
                                 or G D G B D G
By sliding that up a fret(1/2step) you get Ad 4 6 6 5 4 4 or Ad Ed Ad C Ed Ad
By the time you learn to visualize: Major/Minor/Dominant/Minor7/ Barres starting on 6th string then you will begin to get a sense of the entire neck and what other chord shapes and scale forms are hidden within and adjacent to the Barres.
This can be carried over to Barres starting on the 5th string and other moveable type triads starting on any 3 string set.  Eventually you will begin to notice things on a different level.  Learn to think of scale degrees as numbers instead of letters.....or even Solfegio syllables.  Moveable DO solfege is probably easiest to absorb.

How To Improve My Sightreading?


Place $R$ coins in a grid so that every row and column have at least one coin

Question: I found an interesting problem in spoj:
In how many ways can $R$ coins be placed on an $N * M$ grid such that each row and each column have atleast $1$ coin ?
First idea came to my mind is, solve it for $\max(N,M)$ coins so that every row and column gets at least $1$ coin and than put rest of the coins in any cell. But this will generate many duplicate results. I wonder if this is solvable by inclusion-exclusion!
Thanks for helping.
Link to problem
Comment: This sounds like a generalization of the classic Rooks on a chessboard problem: place Rooks on a chessboard so that they cannot attack each other. Wikipedia has an ok explanation of it here: http://en.wikipedia.org/wiki/Rook_polynomial. That would only provide a lower bound though, since your are saying that each row and column needs at least one coin. So I assume R can be large enough so that multiple coins have to be in the same row or column.
Answer: This is stated as a computational combinatorics problem since it's spoj, and sometimes these kinds of questions have a direct formula you can figure out and then code up, and other times you may actually have to utilize some non-trivial computation to help.  If you want to try for the more computational approach for this problem, you can do a recursion-based approach where you first place coins in the first row, and note it doesn't matter which places you put the coins; you still wind up with the same recursive smaller case that only depends on how many spaces you put coins in in the first row.  In general for a given row you're going to put coins in, you only need to keep track of how many coins you have left to place, and how many columns still have not received a coin.  So your recursion only involves two parameters (three including the row number), and you can set up the recursion using memoization or direct dynamic programming to help make sure it runs fast enough.  Also note you could get some really big answers even for rather small boards, so when you compute recursive cases and then multiply by appropriate coefficients and add to get the current answer, all computations should be done modulo the integer 1000000007 they want the final answer to be modulo by.  Since that is so close to 2^32, you'll either need native 64-bit integer arithmetic, or implement your own simple 64-bit arithmetic using 2 32-bit fields to represent a 64-bit integer field.  Also note during your recursion, if the number of coins remaining to be placed becomes greater than the total number of spaces in your rows you haven't placed coins in yet, then you can just return "0" and not recurse further because there is no solution; similarly if the number of coins remaining ever becomes smaller than the number of columns that still have not received a coin, you can similarly return "0" and not recurse.  And obviously, when you reach the final row, you have to place all the remaining coins you have left, making sure that you put a coin in every column that has not yet received a coin.


Testing of quadratic regression in R

Question: I'm looking to test explanatory variables that might have quadratic rather than linear relation to the dependent variable.
I have read in several places that this could be done using the squared (^2) values of the explanatory variables. However, in all the examples I found online, as well as for my analysis, results for both linear and quadratic regressions were significant (though sometimes opposite -/+).
I can see how both could be correct sometimes but just in case I ran it on a dataset that is obviously linear:
Var1 <- seq(1:51)
Var2 <- seq(0, 1, 0.02)
Var3 <- Var2^2
Test <- data.frame(cbind(Var1, Var2, Var3))
plot(Test$Var2, Test$Var1)

summary(lm(Var1 ~ Var2 + Var3, Test))

Call:
lm(formula = Var1 ~ Var2 + Var3, data = Test)

Residuals:
       Min         1Q     Median         3Q        Max
-3.801e-14 -1.868e-15  2.200e-17  3.997e-15  1.222e-14

Coefficients:
              Estimate Std. Error    t value Pr(>|t|)
(Intercept)  1.000e+00  3.099e-15  3.227e+14   <2e-16 ***
Var2         5.000e+01  1.433e-14  3.489e+15   <2e-16 ***
Var3        -3.977e-14  1.386e-14 -2.869e+00   0.0061 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 7.668e-15 on 48 degrees of freedom
Multiple R-squared:      1, Adjusted R-squared:      1
F-statistic: 9.395e+31 on 2 and 48 DF,  p-value: < 2.2e-16

Can anyone explain how is this possible and how should I approach it?
What are the circumstances where it should and shouldn't be used?
**Edit:
When i run the regression with only the quadratic variable such as
summary(lm(Var1~Var3, data = Test))

I get this result
Call:
lm(formula = Var1 ~ Var3, data = Test)

Residuals:
   Min     1Q Median     3Q    Max
-9.257 -2.645  1.077  3.317  4.107

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  10.2569     0.7979   12.86   <2e-16 ***
Var3         46.7616     1.7580   26.60   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 3.822 on 49 degrees of freedom
Multiple R-squared:  0.9352,    Adjusted R-squared:  0.9339
F-statistic: 707.5 on 1 and 49 DF,  p-value: < 2.2e-16

Can anyone explain the logic of the regression I think I'm missing?
Comment: The result may say the quadratic factor is statistically significant, but with a value is $10^{-14}$ it is physically insignificant.  Probably a result of a floating point rounding error
Comment: That's a very good point, thank you, but please see my edit to the question regarding a regression with only a quadratic variable.
Comment: I don't think this is a particularly instructive simulated data. Add a bit of noise and you'll get quite different results.
Answer: The result may say the quadratic factor is statistically significant, but with a value is $10^{−14}$ it is physically insignificant.
I am thinking your question is "Why is there a quadratic coefficient so small and not equal to 0 from the original definition?"  To answer this look at your plot.  The x range (from 0 to 1) is small and in that range the function is linear. (no curvature). The contribution quadratic (or higher orders) is very small in the range of -1 < x < 1. Since the square of small number is even smaller. ) $.1^2 = 0.01$, thus no contribution.
See the blue and green lines below.  Both lines are nearly equal.

Now for your second model, fitting a quadratic without the linear term.
The least squares method is finding the best 2 coefficients to minimize the error and the result is the red curve.  Again there are 50 data points in a small x-range where the quadratic effect is insignificant and thus still a pretty good linear fit.
In fact you just fit the intercept (without any independent variable) you will still end up with a decent fit.
Hopefully this help cleared up your confusion.
Var1 <- seq(1:51)
Var2 <- seq(0, 1, 0.02)
Var3 <- Var2^2
Test <- data.frame(cbind(Var1, Var2, Var3))
plot(Test$Var2, Test$Var1)

linear <- lm(Var1 ~ Var2, Test)
summary(linear)
abline(linear, col="blue")

quad <- lm(Var1 ~ Var2 + Var3, Test)
summary(quad)
lines(x=Test$Var2, y=predict(quad, Test), col="green")

quad_lite <- lm(Var1 ~ Var3, Test)
summary(quad_lite)
lines(x=Test$Var2, y=predict(quad_lite, Test), col="red")

intercept <- lm(Var1 ~ 1, Test)
summary(intercept)

Answer: Actually, your question is about model selection and not about statistical significance of regression parameters. Although the latter can be, and often is used for reducing a model, it is somewhat dubious for picking the degree of a polynomial, because the variables $x$ and $x^2$ are far from independent and, depending on their range, can be highly correlated:
> x <- -5:5
> cor(x, x^2)
[1] 0
> x <- 0:10
> cor(x, x^2)
[1] 0.9631427

Generally, using higher degree polynomials for fitting will always increase the fitting accuracy (measured by $R^2$ in linear regression) on the data used for fitting, but at some point, it will result in overfitting (i.e.: it will perform poorly on unseen data). To find this turnaround point, different indices can be used, e.g.:

the leave-one-out mean squared error or, equivalently, the leave-one-out $R^2$
the Akaike Information Criterion (AIC)

For linear models, both criteria are asymptotically equivalent. It is thus easiest to use AIC (which is a builtin R function) to find an appropriate degree: lower AIC is better. Code outline:
for (degree in 1:3) {
    cat(sprintf("degree=%i: AIC=%f\n", degree, AIC(lm(y ~ poly(x,degree), data))))
}

Comment: The Ramsey RESET test might be usueful to OP.
Comment: Thanks for pointing to this method, of which I have never heard before. Do you know how it compares to AIC based model selection? That this test is not (or rarely?) mentioned in text boooks on linear regression does not necessarily speak against it. It seems, however, to be solely based on in-sample estimates, so I wonder whether Ramsey's test can detect overfitting. Can you elaborate in the ideas in an answer?

Testing of quadratic regression in R


Find the prime numbers $p, q$ satisfying perfect square

Question:
Find the prime numbers $p, q$ satisfy: $p^2+3pq+q^2+6q+6p-60$ is perfect square

My try: $p^2+2pq+q^2+6q+6p+9+pq-69=r^2$ so $pq-69=(r-q-p-3)(r+p+q+3)$ and I stuck here, any hint please. Thank you.
Comment: Well, I did a quick search with Mathematica (using the bounds $2\le\text{p}\le10^4$ and $2\le\text{q}\le10^4$) and found: $\left(\text{p},\text{q}\right)\in\left\{\left(2,3\right),\left(3,2\right),\left(3,7\right),\left(3,23\right),\left(7,3\right),\left(23,3\right)\right\}$
Comment: Thank you, I only know $(p,q) = {(2,3),(3,2)}$
Comment: @JanEerland I'll just put up a thought that struck me... maybe you can clarify it for me? Why not take $s = p + q, m = pq$ and rewrite the equation as $s(s+6) + m = r^2 + 60$ and solve??  I'd like to know if this way of solving would end up being a lot more difficult...
Answer: The expression is
$$p^2+3pq+q^2+6q+6p-60 = r^2 \tag{1}\label{eq1A}$$
Using modulo $3$, we get
$$p^2 + q^2 \equiv r^2 \pmod{3} \tag{2}\label{eq2A}$$
Since perfect squares are congruent to $0$ or $1$ modulo $3$, if both $p$ and $q$ were not $3$, then the left side of \eqref{eq2A} would be congruent to $2$ modulo $3$. Thus, at least one of them must be $3$. Due to the symmetry between $p$ and $q$ in \eqref{eq1A}, WLOG have $p = 3$. Next, multiply both sides by $4$ to get
$$\begin{equation}\begin{aligned}
4r^2 & = 36 + 36q + 4q^2 + 24q + 72 - 240 \\
& = 4q^2 + 60q - 132 \\
& = 4q^2 + 60q + 225 - 225 - 132 \\
& = (2q + 15)^2 - 357
\end{aligned}\end{equation}\tag{3}\label{eq3A}$$
This leads to
$$(2q + 15)^2 - (2r)^2 = 357 \; \to \; (2q + 15 - 2r)(2q + 15 + 2r) = 3(7)(17) \tag{4}\label{eq4A}$$
To check the various factor possibilities (note since $2q + 15 + 2r \gt 0$, they'll both be positive), we have
$$2q + 15 - 2r = f_1 \tag{5}\label{eq5A}$$
$$2q + 15 + 2r = f_2 \tag{6}\label{eq6A}$$
with $f_1 f_2 = 357$, $f_1 \lt f_2$ and $f_1, f_2 \in \{1, 3, 7, 17, 21, 51, 119, 357\}$. Adding \eqref{eq5A} and \eqref{eq6A} gives
$$4q + 30 = f_1 + f_2 \; \; \to \; \; q = \frac{f_1 + f_2 - 30}{4} \tag{7}\label{eq7A}$$
This gives $q = \frac{1 + 357 - 30}{4} = 82$, $q = \frac{3 + 119 - 30}{4} = 23$, $q = \frac{7 + 51 - 30}{4} = 7$ or $q = \frac{17 + 21 - 30}{4} = 2$. Since only $2$, $7$ and $23$ are prime (with corresponding $r$ values of $1$, $11$ and $29$) then, along with switching $p$ and $q$ around, results in what Jan Eerland's question comment indicates, i.e.,
$$(p, q) \in \{(3,2),(2,3),(3,7),(7,3),(3,23),(23,3)\} \tag{8}\label{eq8A}$$


Deleting current unique session id by phalcon?

Question: When I logout from cop1 app (project), if I used$this->session->destroy :it is destroyed all two app sessions (two apps are logout), but if I used remove function it working well eg. $this->session->remove("user").Because its only destroyed relative session user thus only cop1 is logout. My needing one is deleting all current(cop1) sessions not only session variable user ? How can I handle this ?
localhost/cop1/..
$di->set('session', function () {
    $session = new SessionAdapter();
    $session->setOptions(['uniqueId'=> "cop1_"]);
    $session->start();
    return $session;
});

localhost/cop2/..
$di->set('session', function () {
    $session = new SessionAdapter();
    $session->setOptions(['uniqueId'=> "cop2_"]);
    $session->start();
    return $session;
});

Answer: Have you tried to use Session Bags, in addition to the normal Session?

This component helps to separate session data into "namespaces". Working by this way you can easily create groups of session variables into the application. By only setting the variables in the "bag", it's automatically stored in session.

Whenever someone logs into your app you create a Session Bag:
$sessionBag = new \Phalcon\Session\Bag('user');
$sessionBag->set('key', 'value');

And when you want to logout you do:
$sessionBag->destroy();

Answer: I can't try with session bag because my current project has so many modules and sessions ,so I have no time for replacing codes . Now my problem is solved by session_name but I don't know is it a good one ? Hoping helpful for some like me ...

session_name lets you give each application [same domain] a different session.

localhost/cop1/..
$di->set('session', function () {
    $session = new SessionAdapter();
    $session->setOptions(['uniqueId'=> "cop1_"]);
    session_name("cop1");
    $session->start();
    return $session;
});

localhost/cop2/..
$di->set('session', function () {
    $session = new SessionAdapter();
    $session->setOptions(['uniqueId'=> "cop2_"]);
    session_name("cop2");
    $session->start();
    return $session;
});