Grails DataSource Exception

Question: I have an application in production that that recently had a MySQL timeout, so I am trying to add extra parameters to the datasource to prevent this. In the 1.3.7 documentation it shows that I can add a properties value like so:
properties {
        maxActive = 50
        maxIdle = 25
        minIdle = 5
        initialSize = 5
        minEvictableIdleTimeMillis = 60000
        timeBetweenEvictionRunsMillis = 60000
        maxWait = 10000
        validationQuery = "/* ping */"
    }

However, when I add this to my development datasource I get the following error:
 ERROR Error executing bootstraps: Error creating bean with name 'messageSource': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager': Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource': Cannot resolve reference to bean 'dataSourceUnproxied' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSourceUnproxied': Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'maxActive' of bean class [org.springframework.jdbc.datasource.DriverManagerDataSource]: Bean property 'maxActive' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'messageSource': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager': Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource': Cannot resolve reference to bean 'dataSourceUnproxied' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSourceUnproxied': Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'maxActive' of bean class [org.springframework.jdbc.datasource.DriverManagerDataSource]: Bean property 'maxActive' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
    at org.grails.tomcat.InlineExplodedTomcatServer.doStart(InlineExplodedTomcatServer.groovy:112)
    at org.grails.tomcat.InlineExplodedTomcatServer$doStart.callCurrent(Unknown Source)
    at org.grails.tomcat.TomcatServer.start(TomcatServer.groovy:97)
    at grails.web.container.EmbeddableServer$start.call(Unknown Source)
    at _GrailsRun_groovy$_run_closure5_closure12.doCall(_GrailsRun_groovy:158)
    at _GrailsRun_groovy$_run_closure5_closure12.doCall(_GrailsRun_groovy)
    at _GrailsSettings_groovy$_run_closure10.doCall(_GrailsSettings_groovy:280)
    at _GrailsSettings_groovy$_run_closure10.call(_GrailsSettings_groovy)
    at _GrailsRun_groovy$_run_closure5.doCall(_GrailsRun_groovy:149)
    at _GrailsRun_groovy$_run_closure5.call(_GrailsRun_groovy)
    at _GrailsRun_groovy.runInline(_GrailsRun_groovy:116)
    at _GrailsRun_groovy.this$4$runInline(_GrailsRun_groovy)
    at _GrailsRun_groovy$_run_closure1.doCall(_GrailsRun_groovy:59)
    at RunApp$_run_closure1.doCall(RunApp:33)
    at gant.Gant$_dispatch_closure5.doCall(Gant.groovy:381)
    at gant.Gant$_dispatch_closure7.doCall(Gant.groovy:415)
    at gant.Gant$_dispatch_closure7.doCall(Gant.groovy)
    at gant.Gant.withBuildListeners(Gant.groovy:427)
    at gant.Gant.this$2$withBuildListeners(Gant.groovy)
    at gant.Gant$this$2$withBuildListeners.callCurrent(Unknown Source)
    at gant.Gant.dispatch(Gant.groovy:415)
    at gant.Gant.this$2$dispatch(Gant.groovy)
    at gant.Gant.invokeMethod(Gant.groovy)
    at gant.Gant.executeTargets(Gant.groovy:590)
    at gant.Gant.executeTargets(Gant.groovy:589)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager': Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource': Cannot resolve reference to bean 'dataSourceUnproxied' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSourceUnproxied': Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'maxActive' of bean class [org.springframework.jdbc.datasource.DriverManagerDataSource]: Bean property 'maxActive' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
    ... 25 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource': Cannot resolve reference to bean 'dataSourceUnproxied' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSourceUnproxied': Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'maxActive' of bean class [org.springframework.jdbc.datasource.DriverManagerDataSource]: Bean property 'maxActive' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
    ... 25 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource': Cannot resolve reference to bean 'dataSourceUnproxied' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSourceUnproxied': Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'maxActive' of bean class [org.springframework.jdbc.datasource.DriverManagerDataSource]: Bean property 'maxActive' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
    ... 25 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSourceUnproxied': Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'maxActive' of bean class [org.springframework.jdbc.datasource.DriverManagerDataSource]: Bean property 'maxActive' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
    ... 25 more
Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'maxActive' of bean class [org.springframework.jdbc.datasource.DriverManagerDataSource]: Bean property 'maxActive' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
    ... 25 more

What could be the problem? Thanks.
Comment: Why is this a new question and not a comment on http://stackoverflow.com/questions/7260365/grails-and-mysql-connection-exception ?
Comment: @Burt Beckwith - Seemed like a different problem. First one was "why am I getting this error?" and this one is more like "when adding these parameters, why am I getting this [other] error?" In any case, do you know the answer? :)
Answer: I was testing this locally, so I put the properties in my development block. However, I didn't add pooled = true since it usually isn't in this section. This was causing the error. Once I added the pooling statement everything worked correctly.
Comment: Right - pooling is important, otherwise you slow performance by waiting for a new connection each time. It may be possible to set those properties in the DriverManagerDataSource you get when not pooling, but there isn't a standard naming convention for those properties, so they're different for each impl. For example using a C3P0 pool would also fail since some of the names are the same but others aren't.
Comment: @Burt Beckwith - Your help has been invaluable. As you can see I still have a lot to learn. Do you have a top recommended resource for Grails (book, video, etc)? I have read through the documentation but I guess I miss a lot that I have to come back to. In any case, thanks for all of your help thus far (and likely in the future).

Grails DataSource Exception


Drupal 7.4.2 Can't Login after installing MySQL 5.7.9

Question: I have a Mac with the following
PHP 5.6
MySQL 5.7.9
Apache/2.4.16 (Unix)
Drupal 7.4.2
After upgrading to El Capitan and deleting MySql and then installing a new version of MySql, I can no longer login to Drupal.
I tried to update the user 1 password script, even though I did not forget my password. It said it was successful but I still cannot login.
When I go to my localhost /user/login  I enter the username and password and submit the form. The page reloads, no messages are displayed.
Any suggestions?
httpd.conf Apache Configuration
ServerRoot "/usr"
Listen 80

LoadModule authn_file_module libexec/apache2/mod_authn_file.so
#LoadModule authn_dbm_module libexec/apache2/mod_authn_dbm.so
#LoadModule authn_anon_module libexec/apache2/mod_authn_anon.so
#LoadModule authn_dbd_module libexec/apache2/mod_authn_dbd.so
#LoadModule authn_socache_module libexec/apache2/mod_authn_socache.so
LoadModule authn_core_module libexec/apache2/mod_authn_core.so
LoadModule authz_host_module libexec/apache2/mod_authz_host.so
LoadModule authz_groupfile_module libexec/apache2/mod_authz_groupfile.so
LoadModule authz_user_module libexec/apache2/mod_authz_user.so
#LoadModule authz_dbm_module libexec/apache2/mod_authz_dbm.so
#LoadModule authz_owner_module libexec/apache2/mod_authz_owner.so
#LoadModule authz_dbd_module libexec/apache2/mod_authz_dbd.so
LoadModule authz_core_module libexec/apache2/mod_authz_core.so
#LoadModule authnz_ldap_module libexec/apache2/mod_authnz_ldap.so
LoadModule access_compat_module libexec/apache2/mod_access_compat.so
LoadModule auth_basic_module libexec/apache2/mod_auth_basic.so
#LoadModule auth_form_module libexec/apache2/mod_auth_form.so
#LoadModule auth_digest_module libexec/apache2/mod_auth_digest.so
#LoadModule allowmethods_module libexec/apache2/mod_allowmethods.so
#LoadModule file_cache_module libexec/apache2/mod_file_cache.so
#LoadModule cache_module libexec/apache2/mod_cache.so
#LoadModule cache_disk_module libexec/apache2/mod_cache_disk.so
#LoadModule cache_socache_module libexec/apache2/mod_cache_socache.so
#LoadModule socache_shmcb_module libexec/apache2/mod_socache_shmcb.so
#LoadModule socache_dbm_module libexec/apache2/mod_socache_dbm.so
#LoadModule socache_memcache_module libexec/apache2/mod_socache_memcache.so
#LoadModule watchdog_module libexec/apache2/mod_watchdog.so
#LoadModule macro_module libexec/apache2/mod_macro.so
#LoadModule dbd_module libexec/apache2/mod_dbd.so
#LoadModule dumpio_module libexec/apache2/mod_dumpio.so
#LoadModule echo_module libexec/apache2/mod_echo.so
#LoadModule buffer_module libexec/apache2/mod_buffer.so
#LoadModule data_module libexec/apache2/mod_data.so
#LoadModule ratelimit_module libexec/apache2/mod_ratelimit.so
LoadModule reqtimeout_module libexec/apache2/mod_reqtimeout.so
#LoadModule ext_filter_module libexec/apache2/mod_ext_filter.so
#LoadModule request_module libexec/apache2/mod_request.so
#LoadModule include_module libexec/apache2/mod_include.so
LoadModule filter_module libexec/apache2/mod_filter.so
#LoadModule reflector_module libexec/apache2/mod_reflector.so
#LoadModule substitute_module libexec/apache2/mod_substitute.so
#LoadModule sed_module libexec/apache2/mod_sed.so
#LoadModule charset_lite_module libexec/apache2/mod_charset_lite.so
#LoadModule deflate_module libexec/apache2/mod_deflate.so
#LoadModule xml2enc_module libexec/apache2/mod_xml2enc.so
#LoadModule proxy_html_module libexec/apache2/mod_proxy_html.so
LoadModule mime_module libexec/apache2/mod_mime.so
#LoadModule ldap_module libexec/apache2/mod_ldap.so
LoadModule log_config_module libexec/apache2/mod_log_config.so
#LoadModule log_debug_module libexec/apache2/mod_log_debug.so
#LoadModule log_forensic_module libexec/apache2/mod_log_forensic.so
#LoadModule logio_module libexec/apache2/mod_logio.so
LoadModule env_module libexec/apache2/mod_env.so
#LoadModule mime_magic_module libexec/apache2/mod_mime_magic.so
#LoadModule expires_module libexec/apache2/mod_expires.so
LoadModule headers_module libexec/apache2/mod_headers.so
#LoadModule usertrack_module libexec/apache2/mod_usertrack.so
##LoadModule unique_id_module libexec/apache2/mod_unique_id.so
LoadModule setenvif_module libexec/apache2/mod_setenvif.so
LoadModule version_module libexec/apache2/mod_version.so
#LoadModule remoteip_module libexec/apache2/mod_remoteip.so
LoadModule proxy_module libexec/apache2/mod_proxy.so
LoadModule proxy_connect_module libexec/apache2/mod_proxy_connect.so
LoadModule proxy_ftp_module libexec/apache2/mod_proxy_ftp.so
LoadModule proxy_http_module libexec/apache2/mod_proxy_http.so
LoadModule proxy_fcgi_module libexec/apache2/mod_proxy_fcgi.so
LoadModule proxy_scgi_module libexec/apache2/mod_proxy_scgi.so
#LoadModule proxy_fdpass_module libexec/apache2/mod_proxy_fdpass.so
LoadModule proxy_wstunnel_module libexec/apache2/mod_proxy_wstunnel.so
LoadModule proxy_ajp_module libexec/apache2/mod_proxy_ajp.so
LoadModule proxy_balancer_module libexec/apache2/mod_proxy_balancer.so
LoadModule proxy_express_module libexec/apache2/mod_proxy_express.so
#LoadModule session_module libexec/apache2/mod_session.so
#LoadModule session_cookie_module libexec/apache2/mod_session_cookie.so
#LoadModule session_dbd_module libexec/apache2/mod_session_dbd.so
LoadModule slotmem_shm_module libexec/apache2/mod_slotmem_shm.so
#LoadModule slotmem_plain_module libexec/apache2/mod_slotmem_plain.so
#LoadModule ssl_module libexec/apache2/mod_ssl.so
#LoadModule dialup_module libexec/apache2/mod_dialup.so
LoadModule lbmethod_byrequests_module libexec/apache2/mod_lbmethod_byrequests.so
LoadModule lbmethod_bytraffic_module libexec/apache2/mod_lbmethod_bytraffic.so
LoadModule lbmethod_bybusyness_module libexec/apache2/mod_lbmethod_bybusyness.so
#LoadModule lbmethod_heartbeat_module libexec/apache2/mod_lbmethod_heartbeat.so
LoadModule unixd_module libexec/apache2/mod_unixd.so
#LoadModule heartbeat_module libexec/apache2/mod_heartbeat.so
#LoadModule heartmonitor_module libexec/apache2/mod_heartmonitor.so
#LoadModule dav_module libexec/apache2/mod_dav.so
LoadModule status_module libexec/apache2/mod_status.so
LoadModule autoindex_module libexec/apache2/mod_autoindex.so
#LoadModule asis_module libexec/apache2/mod_asis.so
#LoadModule info_module libexec/apache2/mod_info.so
#LoadModule cgi_module libexec/apache2/mod_cgi.so
#LoadModule dav_fs_module libexec/apache2/mod_dav_fs.so
#LoadModule dav_lock_module libexec/apache2/mod_dav_lock.so
#LoadModule vhost_alias_module libexec/apache2/mod_vhost_alias.so
LoadModule negotiation_module libexec/apache2/mod_negotiation.so
LoadModule dir_module libexec/apache2/mod_dir.so
#LoadModule imagemap_module libexec/apache2/mod_imagemap.so
#LoadModule actions_module libexec/apache2/mod_actions.so
#LoadModule speling_module libexec/apache2/mod_speling.so
#LoadModule userdir_module libexec/apache2/mod_userdir.so
LoadModule alias_module libexec/apache2/mod_alias.so
LoadModule rewrite_module libexec/apache2/mod_rewrite.so
#LoadModule php5_module libexec/apache2/libphp5.so
LoadModule php5_module /usr/local/opt/php56/libexec/apache2/libphp5.so
LoadModule hfs_apple_module libexec/apache2/mod_hfs_apple.so

<IfModule unixd_module>
#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User _www
Group _www
</IfModule>

ServerAdmin email@example.com
ServerName myself1mac.employerdomain.com:80

<Directory />
    AllowOverride none
    Require all denied
</Directory>

DocumentRoot "/Library/WebServer/Documents"
<Directory "/Library/WebServer/Documents">
    Options FollowSymLinks Multiviews
    MultiviewsMatch Any

    AllowOverride None

    Require all granted
</Directory>

<IfModule dir_module>
    DirectoryIndex index.html
</IfModule>

<FilesMatch "^\.([Hh][Tt]|[Dd][Ss]_[Ss])">
    Require all denied
</FilesMatch>

<Files "rsrc">
    Require all denied
</Files>
<DirectoryMatch ".*\.\.namedfork">
    Require all denied
</DirectoryMatch>

ErrorLog "/private/var/log/apache2/error_log"

LogLevel warn

<IfModule log_config_module>
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b" common

    <IfModule logio_module>
      # You need to enable mod_logio.c to use %I and %O
      LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
    </IfModule>

    CustomLog "/private/var/log/apache2/access_log" common
</IfModule>

<IfModule alias_module>
    ScriptAliasMatch ^/cgi-bin/((?!(?i:webobjects)).*$) "/Library/WebServer/CGI-Executables/$1"
</IfModule>

<IfModule cgid_module>
</IfModule>

<Directory "/Library/WebServer/CGI-Executables">
    AllowOverride None
    Options None
    Require all granted
</Directory>

<IfModule mime_module>
    TypesConfig /private/etc/apache2/mime.types

    AddType application/x-compress .Z
    AddType application/x-gzip .gz .tgz
</IfModule>

TraceEnable off

# Server-pool management (MPM specific)
Include /private/etc/apache2/extra/httpd-mpm.conf

# Multi-language error messages
#Include /private/etc/apache2/extra/httpd-multilang-errordoc.conf

# Fancy directory listings
Include /private/etc/apache2/extra/httpd-autoindex.conf

# Language settings
#Include /private/etc/apache2/extra/httpd-languages.conf

# User home directories
#Include /private/etc/apache2/extra/httpd-userdir.conf

# Real-time info on requests and configuration
#Include /private/etc/apache2/extra/httpd-info.conf

# Virtual hosts
#Include /private/etc/apache2/extra/httpd-vhosts.conf

# Local access to the Apache HTTP Server Manual
#Include /private/etc/apache2/extra/httpd-manual.conf

# Distributed authoring and versioning (WebDAV)
#Include /private/etc/apache2/extra/httpd-dav.conf

# Various default settings
#Include /private/etc/apache2/extra/httpd-default.conf

# Configure mod_proxy_html to understand HTML4/XHTML1
<IfModule proxy_html_module>
    Include /private/etc/apache2/extra/proxy-html.conf
</IfModule>

# Secure (SSL/TLS) connections
#Include /private/etc/apache2/extra/httpd-ssl.conf
#
# Note: The following must must be present to support
#       starting without SSL on platforms with no /dev/random equivalent
#       but a statically compiled-in mod_ssl.
#
<IfModule ssl_module>
    SSLRandomSeed startup builtin
    SSLRandomSeed connect builtin
</IfModule>

Include /private/etc/apache2/other/*.conf

Comment: Check the logs; something might be wrong in the background. Just in case, you can update admin password in `{users}` table with this hash: `$S$D4yuJ0m89lIAnmwog.4mEU7/xsgZa27827CGo5esMNwxILluedgj`. It corresponds with password `123456`.
Comment: Right now, this is too broad, as it could be a whole slew of things.  You should tell us if anything odd is reported in a `drush st`.  My *suspicion*, though is that when you upgraded, your user grants got messed up, and the user in the Drupal DSN can't write to the `{sessions}` table anymore.  A cookie domain problem can also cause the same symptoms.
Comment: Enable mod_rewrite - this is precisely your problem. I cannot post this as answer because the question is on hold.
Answer: It could be a host of things, but it should as if the connection from your Drupal site to the DB is working - you mentioned that you cannot log in, so I am assuming your site is showing the login screen, which means that Drupal is connecting to the DB.  If there was a DB connection issue you would get error message during bootstrap.
So it might just be that your admin account is locked.  The password may be right, but the account is still locked.  I had a situation a while back where password_policy module locked the admin account.
I would try to add a new user (drush create user), assign this user to the admin roles, and then try to login with this user.  If yo get access, you can 'reset' the admin account.
If you cannot log in with your new user, then there is something more sinister going on.
Comment: Drush added a new user, assigned an administrator role to it. The user cannot login. Upon entering the username and password, I submit the form and it returns to the page with no message.
Answer: This is a good thing to use drush for, since you can reset the password for user 1 (drush user-password), or check for error messages (drush ws). Drush can also create a one-time-link to test.
You can access the user/login page, so I'm guessing you don't have a problem with clean URLs (which would make it hard to log in). The one thing that might cause problem, however, would be what's the exact link you're browsing to.  Drupal handles its logins via a cookie that it sets, and cookies are tied to the exact site you're browsing to, even if you're just doing on your laptop. If the host name you log in on is different than the host name you get redirected to (say, you're using something like mysite.local to log in, but you browse to 127.0.0.1, then you'll be logged in only if the URL you're browing to is "mysite.local", even if mysite.local points to 127.0.0.1.
The other possibility is that your Apache configuration may be wrong. I don't think Apple has been using Apache 2.4 that long, and there are annoying differences in how you configure 2.4 as compared to Apache 2.2. You may want to edit your question to post your apache configuration, so folks can check if it's right for a local Drupal install.
Comment: I did not forget the password; However I had previously tried what you suggested, updating the password, this did not allow me to login.
Comment: Thanks for the feedback. I dug through the Apache httpd.conf file and found that I was incredibly careless and forgot to enable mod_rewrite. I also enabled the session ones. I am now able to login. Thank you!


What is Fluid inline form of {records.title}?

Question: How can i get the inline form of this fluid tag ?
<code><wwt:getCategory uid="{record.uid}" as="records">{records.title}</wwt:getCategory>
</code>
Thanks a lot!
Answer: Try with
<code>{records.title ->wwt:getCategory(uid: record.uid, as: 'records')}
</code>
It should be the same inline syntax like ForViewHelper.


ServerAlias not working | Apache 2.2.13

Question: I have this V-Host definition:
<VirtualHost *>
  ServerName www.example.com
  ServerAlias example.com

  DocumentRoot /srv/www/default
  Redirect 301 / http://www.example2.com/

</VirtualHost>

When I visit www.example.com, redirection works as expected, I end up at www.example2.com
When I type example.com, I get a 403 - Access Denied Page.
This is the relevant output of httpd2-prefork -S -D SSL -f /etc/apache2/httpd.conf:
wildcard NameVirtualHosts and _default_ servers:
*:*        www.example.com (/etc/apache2/vhosts.d/lnk-rp-www.example.com.conf:1)

I do not understand why and what is going wrong here.
Comment: Are you sure there is no other VirtualHost with `example.com` in the configuration? Do both addresses resolve to the same IP address?
Answer: Thank you very much for your hints.
Meanwhile it looks like I figured it out.
I had

NameVirtualHost 188.8.131.52:80

in my listen.conf.
Once I changed my Virtual-Host-Definition from

VirtualHost *

to

VirtualHost 126.96.36.199:80

it was working.
Thank you again for your help.
Stefanie

ServerAlias not working | Apache 2.2.13


In need of Fractional Brownian Noise (FBM) vs Perlin Noise clarification

Question: I'm  researching the various types of noise for terrain generation and I'm a little confused regarding when noise becomes perlin noise and when perlin noise becomes fbm. I'm hoping somebody could clarify anywhere that I'm going wrong. I currently assume the following
Noise: Contains a both amplitude and frequency which dictates the final value in conjunction with some form of interpolation such as linear, cosine or cubic.
Perlin Noise: A sum of octave noise functions(each successive function contains twice the frequency). From what I've read so far the amplitude always seems to be presented as a consistent reduction. For example, Noise1 contains A of 1, Noise2 contains A of 0.5, Noise3 contains A of 0.25 meaning that here amplitude halves each time. Must this it always be consistent like this?
FBM: The sum of multiple perlin Noise functions where each Perlin Noise function MUST contain only octaves with decreasing amplitudes.
Comment: another trick that looks great but kind of blurs the definitional boundaries is iq's analytical derivative jig: http://www.iquilezles.org/www/articles/morenoise/morenoise.htm
Answer: Perlin Noise is actually a method to calculate what you call Noise. It is a form of coherent noise computed as the interpolated normalized gradients of a pseudo-random underlying function (or pseudo-randomly generated gradients). The frequency controls the "sampling" distance of the gradients, so the higher the frequency, the smaller the sampling distance, and more gradients per unit of space. Amplitude controls the max and min values of the noise function.
Hugo Elias' page on Perlin Noise has a good description of the concept, the algorithm, etc.
Perlin Noise FAQ explains the algorithm in a very intuitive manner.
Noise is a general term. Perlin Noise is only a type of coherent noise. But there is many different types with different characteristics.
Fractional Brownian motion is, in fact, what you call Perlin Noise. It is a combination of multiple steps of Perlin Noise (or another similar noise function), each with a different frequency and amplitude. In the context of procedural generation, the variation in frequency from a step to the next is called lacunarity. The variation in amplitude from a step to the next is called gain.
Look at this.
This project on terrain generation gives a very good description of what fBm is and how it is computed.
Comment: Hugo Elias' page is confused, what he speaks about is called value noise, not Perlin noise. They are different approach and quality. Practically speaking value noise is a cheap alternative of Perlin noise. http://en.wikipedia.org/wiki/Value_noise
Comment: You can also find good information about noise in general here: http://www.scratchapixel.com/lessons/3d-advanced-lessons/noise-part-1/
Comment: [Perlin Noise FAQ Mirror](http://web.archive.org/web/20150712034206/http://webstaff.itn.liu.se/~stegu/TNM022-2005/perlinnoiselinks/perlin-noise-math-faq.html)
Answer: perlin noise uses slopes to create round bubbly looking correlations for a more natural look.
the octaves method combined noise at various scales to generate more complex forms. apparently, this technique is the thig that is called "fractal brownian motion". ive never heard this before but i did some research and this is what im getting.
you can use octaves with any kind of noise and scale them however you want in both frequency and amplitude. the halfing thing is done for mathematical reasons to remove certain artifacts from the results.
but this octaves thing is a technique independent to perlin noise. they work well together, so they are used together.
white noise octaves aka white noise fbm is called value noise. it has a tendency to reveal the underlying grid, so perlin noise is often used instead.


Four rational Pythagorean triples in a square

Question: Suppose we have a unit square $ABCD$. If we have a primitive Pythagorean triple $(a, b, c)$, let $CD = 1$ and hence $ED = a/b$. It also follows that $EC$ is rational of course.
In fact, using the similarity of $\Delta AFE$ and $\Delta ECD$, all of the sides will also be rational numbers except for $FC$. After some work, $FC^2 = 1^2 + \left(1 - \frac{a}{b} + \frac{a^2}{b^2} \right)^2$ $ = \frac{b^4 + (a^2 - ab + b^2)^2}{b^4}$. Thus we need $(b^2)^2 + (a^2 - ab + b^2)^2 = k^2$ for some positive integer $k$ for $FC$ to be rational:

Using Euclid's formula for Pythagorean triples, one option is that $p^2 - q^2 = b^2; \ 2pq = (a^2 - ab + b^2); \ p^2 + q^2 = k$, where integers $p > q > 0$ and $p, q$ are of opposite parity (otherwise the triple will not be primitive). Wolfram Alpha then uses the quadratic formula to tell me that $a = \frac{1}{2} \left(b \pm \sqrt{-3p^2 + 8pq + 3q^2} \right)$, which simplifies to $a = \frac{1}{2} (b \pm \sqrt{(3q - p)(3p + q)})$. This tells us that $3q > p$ or that $p/3 < q < p$.
Of course, the other option is that $p^2 - q^2 = a^2 - ab + b^2, 2pq = b^2$. This gives $a = \frac{1}{2} \left(b \pm \sqrt{2(2p+q)(p-2q)}\right)$ and hence $p > 2q$ or that $p/2 > q > 0$.
So can we find a configuration where $FC$ is rational, or where $(b^2)^2 + (a^2 - ab + b^2)^2 = k^2$ for some positive integer triple $(a, b, k)$?
Comment: I wonder if we can use Euclid's formula again on $b^2 + q^2 = p^2$ but it's going to be messy.
Answer: It is impossible.
Plug in $c^2=a^2+b^2 \tag{1}$ to get $$(c^2-ab)^2+(b^2)^2=k^2$$
$$(c^4-2abc^2)+(a^2b^2+b^4)=k^2$$
$$c^2(a-b)^2+b^2c^2=k^2$$
$$(a-b)^2+b^2=\frac{k^2}{c^2}=m^2 \tag{2}$$
Since $a^2$ and $b^2$ could only be $0$ or $1$ mod 4, with some casework on equation (1) and (2), we could see that $a=4a_1$ and $b=4b_1$. And this would lead to an infinite descending chain.
Comment: @TobyM $2m^2-1 = y^2$ would have been solvable as a Pell equation. But all its solutions have odd $m$.
Comment: Nicely done, thanks for answering!
Comment: @TitoPiezasIII Do you know how I could find solutions for $8n^2-1=y^2$ or $8n^2-y^2=1$? It is not in the form $x^2-ny^2 = 1$. Oh wait: there are no squares congruent to 7 mod 8, woops.


How to formulate arbitrary complex trigonometric polynomial?

Question: How to formulate arbitrary complex trigonometric polynomial? I know that in real form it is $\displaystyle\sum_{n=1}^k a_n\cos(nx)+b_n\sin(nx)$
Answer: $\cos(nx)=\frac{1}{2}(e^{inx}+e^{-inx})$, and $\sin(nx)=\frac{1}{2i}(e^{inx}-e^{-inx})$, so you have a sum of $A_{n}e^{inx}+B_{n}e^{-inx}$, where $A_{n},B_{n}$ are new constants. Then you can just write it as
$$\sum_{n=-\infty}^{\infty}{c_{n}e^{inx}},$$
for some $c_{n}$.
Clearly, this sum includes the possibility of a constant term, which you don't have in your original sum, but you can just set $c_{n}$=0. It should be easy enough to find a formula for $c_{n}$ in terms of $a_{n}$ and $b_{n}$ if you want to.


Fade-In css latency

Question: Hello so im trying to fade in to cotainers that are replaced with data fetched with flask
HTML + CSS code

.imgContainer {
-webkit-transition: all 1s ease;
-moz-transition: all 1s ease;
-ms-transition: all 1s ease;
-o-transition: all 1s ease;

}
This is how I "fade in my container"
And this is how I fade it out:
$.ajax({
        url : "/vote",
        type : "POST",
        data : { "winner" : "1", "player1" : player1, "player2" : player2 },
        cache : false,
        success : function(data) {
            $("#container").fadeOut()
            setTimeout(function(){
                $("#container").replaceWith(data);
            }, 1000);
        }
    });

My problem at the moment is that it doesnet fade in both containers at the same time and there is a latency between them.
What is the best way to fix that, and make them appear at the same time?
Comment: Your example code doesn't reference the html you've provided. Firstly, jQuery's fadeOut does not need transition to be set in css. You can edit the speed and easing as extra parameters. Second. If you're doing multiple asynchronous calls. They will fire the success callback at different times.
Answer: Onload events executed after the element has been loaded. Maybe your images doesn't load the same time, that's why your fades are not match. I would try to wrap the images into a div if that's possible and set onload on it, or use @keyframes instead of onload (I'm not sure about that tho).

Fade-In css latency


When do we say the uncountable sum $\sum \alpha_ie_i$ of vectors in non-separable Hilbert space is convergent?

Question: Let {$e_i$} be an uncountable orthonormal set in some non-separable Hilbert space. Then, when we say the uncountable sum $\sum \alpha_ie_i$ is convergent. ($\alpha_i$'s are scalars)
Answer: The sum $\sum_{i\in I}\alpha_ie_i$ converges if the set
$$\left\{\sum_{j\in J}\alpha_je_j:J\subset I,J\text{ finite}\right\}$$
has exactly one accumulation point.
Comment: What is an "accumulation point of a set"? Suppose all terms are zero; then the set is $\{0\}$. Not much accumulation, do you conclude it's not convergent?


How can I setup a DNS server for a subdomain behind a dynamic IP address?

Question: I'm working on a secure/isolated service that manages TLS certificates using the ACME protocol. The server needs to respond with a TXT record on a specific subdomain. This server won't service requests from the general public, but it needs to be publicly available.
CNAME records are permitted and can be followed.
Our TLS management server that hosts the dynamic TXT record is running Bind9, and is located in a place where dynamic IPs are the only option.
The domain's main DNS records are on a public DNS server with the registrar. We've successfully set up a subdomain that is updated using dynamic DNS, but it seems that the Dynamic DNS provider doesn't allow NS records.
So at the registrar we have:
domain.com          A   xx.xx.xx.xx
www.domain.com      A   xx.xx.xx.xx
dynamic.domain.com  NS  dynamic.provider.com

At the dynamic provider we have:
dynamic.domain.com  A yy.yy.yy.yy

At our TLS bot server, we have Bind9 running as the authority for dynamic.domain.com with a text TXT record:
test  TXT     "A nice Test."

So the desired result is that, from anywhere on the internet, you should be able to run dig TXT test.dynamic.domain.com and get A nice Test..
This seems to be failing at the dynamic DNS provider:
dig TXT test.dynamic.domain.com

just gives:
;; AUTHORITY SECTION:
dynamic.domain.com. 2208    IN  SOA dynamic.provider.com.

Is the only way forward to setup an NS record at the dynamic DNS provider (ie. switch providers to one that supports NS records or roll our own)? Or is there a workaround using CNAME records or A records to get this to work?
Comment: Why do you require ACME DNS challenge, instead of HTTP (or TLS-ALPN) ?
Answer: You do not. Seriously. This is highly problemtic
if the need arises, ther are 2 possible workarounds:

Use a vpn to a proxy VPS. I run into a similar situation, and all my traffic is routed through a US proxy server.
Use a cloudflare zero trust tunnel. This essentially is a gateway you run locally that connects outbound to cloudflare.

In your case: scenario 1 - I pay 7 USD per month for a mikrotik vps.
Comment: Wouldn't it be an option to use a cloudflare dns service or something like that, which has records for your acme workload. The benefit of it, is that will be available everywhere.https://www.cloudflare.com/application-services/products/dns/
Comment: Yes and no - if it is a pure dynanic ip without any blocking and you can live with hitting the wrong IP at times after a change - sure. Otherwise Cloudflare runs the same problem - you just hide it behind proxies that - incidentally - can not cache in this case.
Answer: I figured out how to make it work:
You need two subdomains: one to act as the dynamic A record, and one to point to the internal DNS service. Both get NS records at the registrar.
So at the registrar, the records look like this:
CNAME _acme-challenge.domain.com => tls.robert.domain.com
NS    dynamic.domain.com => dynamic.provider.nameservers
NS    robert.domain.com => ns.dynamic.domain.com

At the dynamic provider:
A ns.dynamic.domain.com => yy.yy.yy.yy (dynamic IP)

On the TLS bot server, in Bind:
$ORIGIN robert.domain.com.
$TTL 604800     ; 1 week
robert.domain.com.  IN SOA  robert.domain.com. domains.domain.com. (
                                21         ; serial
                                604800     ; refresh (1 week)
                                86400      ; retry (1 day)
                                2419200    ; expire (4 weeks)
                                604800     ; minimum (1 week)
                                )
        NS      ns.dynamic.domain.com. ; Dynamic A record to self
tls     TXT     "A nice Test."

With that setup:
dig TXT _acme-challenge.domain.com

Produces:
tls.robert.domain.com. 14199 IN TXT "A nice Test."

... from anywhere.
UPDATE: A previous minor issue has been fixed, and the above answer has been edited. There are no longer any caveats. I welcome constructive feedback on any potential issues.
Answer: To set up a DNS server for a subdomain on a dynamic IP, use a Dynamic DNS service. Sign up with a provider, and install their client on your server to update the IP dynamically. Configure your DNS records to point the subdomain to the Dynamic DNS hostname. This ensures your subdomain stays connected, even with a changing IP address


NIC firmware version on my DL380 G5

Question: I am trying to figure out what is my current NIC firmware version.
If I run the latest firmware upgrade from HP, I get the following:

It doesn't tell me the current version.
If I try to check it from Device Manager, I get this:

That's the driver version, not the hardware firmware version.
If I reboot the computer, I don't see the NIC firmware during the POST..
How would I go about finding the current firmware version...
Thanks a lot!
Toast
Comment: In the first picture, what did it do when you clicked "Install?"  The message says that will display the installed version... did it?
Comment: Hello, very good question, I forgot to mention that I do not want to upgrade, I just want to see the current firmware version.  (So basically I never clicked "install") Thanks!
Comment: You'll *probably* get a chance to cancel the installation, so you could try it and see what happens.
Comment: Ward you were right... (VERY late reply lol)
Answer: I found it.
For those who're interested, the firmware can be found in the HP System Management Homepage utility
Doh..
Comment: Any chance of getting this marked as the correct answer so it doesn't pop up on the front page?
Answer: If you run HP Insight Diagnostics (survey) you can view the NIC firmware. Mine is showing 1.9.6

NIC firmware version on my DL380 G5


Least Squares Line Fitting

Question: So yeah, I want to find a general line equation $Ax + By + C = 0$ that best fits a set of $n$ points.
We know upfront that the geometric center $(x_g, y_g)$ is a point that lies on this line, hence we can write the line equation as: $A(x - x_g) + B(y - y_g) = 0$. Now all we need to do is to find the normal $(A, B)$ of this line.
The cost function to optimize (sum of squares of distances from those $n$ points to the line) is: $F(A, B) = \sum_{i=1}^{n} (A(x_i-x_g) + B(y_i-y_g))^2$.
I then compute derivatives of this function with respect to $A$ and $B$. After equating those derivatives to $0$ I get:
$A = \frac{-B \sum_{i=1}^{n} (x_i-x_g)(y_i-y_g)}{\sum_{i=1}^{n} (x_i-x_g)(x_i-x_g)} $
$B = \frac{-A \sum_{i=1}^{n} (y_i-y_g)(x_i-x_g)}{\sum_{i=1}^{n} (y_i-y_g)(y_i-y_g)} $
Now if I plug one of these equations into the other the $A$ and $B$ cancel out, leaving me with identity without any $A$ nor $B$ to compute! Why is this the case?
One thing I would like to point out is that since the normal $(A, B)$ is (or just could be?) of unit length I know there is constraint: $A^2 + B^2 = 1$. If I use this condition along with one (the first one) of the two equations listed above I get perfectly valid result. The thing I don't really get is why do I need to make use of this constraint? I don't really care about the length of the $(A, B)$ normal. Or do I? Why would I need this sort of a "tie" between $A$ and $B$? I thought that unit length-ness is just an extra information I could use to simplify my calculations, but is not mandatory to use.
Answer: Your cost function is not perfect. The distance of the points to the line has to be normalized with the magnitude of the normal vector i.e, $\sqrt{a^2+b^2}$. After that your constraint makes sense.
Comment: Yes, exactly :). I forgot that the distance expressed by the general $Ax + By + C = 0$ formula must be normalized.
Comment: Also, I wondered why I had to use square of distance rather that just distance. The reason is that the "real" distance (non-signed) formula contains absolute value which is not differentiable.
Answer: Sai Kashyap provided valid part of the answer. Here goes the second part.
Equating $A$ to $0$ (and making use of $A^2 + B^2 = 1$) does not guarantee finding minimum. It can also return maximum. That's why it is also necessary to equate $B$ to $0$ and find its corresponding $A$. Then we go through all of the $A$ and $B$ pairs to find which is minimum and which is maximum.

Least Squares Line Fitting


Dispatching a Function Defined in Another Substrate FRAME Pallet

Question: I am familiar with one mechanism for achieving the goal described in this question's title: passing a dispatchable call, which is written in its own pallet, as an argument when invoking an extrinsic that is written in another pallet, as in the Sudo pallet or the multi-sig capabilities defined in the Utility pallet. What are the other options for dispatching functions across pallets? To be specific, I would like to include a pallet, Pallet A, as Trait-bound type for another pallet, Pallet B, and then dispatch a function that is defined in Pallet B from within Pallet A.
Answer: The behavior of dispatching calls like the Utility or Sudo pallet only makes sense when you need to control the origin/filters to a truly arbitrary dispatchable function.
If you have two specific pallets that want to interact with one another, using a Trait to couple them is the correct approach. You can see this behavior in Substrate master by looking at the ChangeMembers trait and how it is used across pallets like Collective, Membership, Society, Phragmen Elections, etc...
Additionally, you can look at a much bigger trait like Currency and see that it basically exposes the transfer "extrinsic" through Currency::transfer, allowing any pallet to execute this function in its own context.
So in summary:

Would recommend you move forward with a trait
Would not recommend you use call.dispatch for such a specific pallet to pallet interaction


Symfony 2 - Translation not working (xliff)

Question: I've read tons of answers and tutorials about Symfony 2 translation, but i'm still not getting it to work. No errors are shown, but messages are not translated in twig templates (nor by testing $this->get('translator')->trans('...') ). The xliff file seems to be loaded because if i add a wrong character on purpose the markup Symfony throws me an error.
Here is my setup :
app/Resources/translations/messages.en.xliff

config.yml
translator: { fallback: "%locale%" }
...
default_locale:  "%locale%"

parameters.yml
locale: en

Contents of messages.en.xliff
<?xml version="1.0"?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
    <file source-language="en" datatype="plaintext" original="file.ext">

            <trans-unit id="1">
                <source>test.message</source>
                <target>TRANSLATED TEST</target>
            </trans-unit>

    </file>
</xliff>

It still does not work even after runing
php app/console cache:clear

And in my twig template (it's a included template...)
{{ "test.message"|trans }}

Any idea ? PS: I don't have other Bundles installed appart from the liip-imagine Bundle. Any help would be strongly appreciated !
Answer: I solved my problem by adding symfony/translation into composer and then updating symfony and clearing the cache.
composer require symfony/translation

php app/console cache:clear

For those who stumble upon this post, here are some of the problems & things to check you could encounter when trying to make translations work (based on all of my reading)

Check composer for symfony/translation
Checks config.yml and parameters.yml (as show in initial post)
Check overriding of /messages.[locale].xliff from Bundle/Resources/translations/ vs app/Resources/translations/ don't override (or o
Always clear the cache when you add new translation files
Comment: Cool, I had the same issue, you saved my time, thanks


Is SpeechKit framework supported in watchOS 3?

Question: I tried to import the SpeechKit framework for watchOS and received an error. Is there a way to use it with watch? I am getting an error when I import the Speechkit Framework saying "no such module Speech"
import WatchKit
import Foundation
import Speech

class SpeechInterfaceController: WKInterfaceController, SFSpeechRecognizerDelegate {

override func awake(withContext context: Any?) {
    super.awake(withContext: context)

    // Configure interface objects here.
}

override func willActivate() {
    // This method is called when watch view controller is about to be visible to user
    super.willActivate()
}

override func didDeactivate() {
    // This method is called when watch view controller is no longer visible
    super.didDeactivate()
}

}
Comment: Pl. Post your code and error what you get.
Comment: I have added the code and error message
Answer: SpeechKit framework is not available for watchOS 3.
To get the speech recognition in a watch app you can instead use:
presentTextInputController(withSuggestions: nil, allowedInputMode: .plain) { (results) in
    if let results = results?.first as? String {
        self.label.setText(results)
    }
}

Comment: I don't get it, why -1 ?
Comment: I forgot about this option.  Thanks!  It's not exactly what I was looking for, but it's helpful.
Answer: The Speech framework is not in the watchOS SDK (as of watchOS 3.0-3.1, at least). You can see this in the framework docs:

(If it supported watchOS, tvOS, or macOS, those would be listed under SDK on that page.)
You can also see the set of available frameworks in your Xcode SDK: look at Xcode.app/Contents/Developer/Platforms/WatchOS.platform/Developer/SDKs/WatchOS3.1.sdk/System/Library/Frameworks/, or at the jump bar atop the Xcode editor pane when you look at the ObjC version of a watchOS system header file, or the list of available options when you manually add to Linked Frameworks and Libraries for your project's WatchKit extension target.


Displaying values on hook_form

Question: I'm displaying a form on admin url :admin/settings/custom. In the page argument I pass array('custom_admin_form'), to the menu item. In the form function I'm writing form elements to display folder and file names present in the public folder. I get those values through the code below:
$dir_path = variable_get('file_public_path', conf_path(). '/files') ;
$fileslist = glob($dir_path . "*.*");
$dirs = glob($dir_path . '/*' , GLOB_ONLYDIR);
foreach($dirs as $directs){
     $names = explode('/', $directs);
     $fnames[] = end($names);
}

How can I display the results in the form function? I tried it using print, echo, drupal_render but nothing is working. I've also used #markup element, but it was displaying array(), not the values of array.
Answer: You can try something like this:
 $form['sample'] = array(
     '#type' => 'item',
     '#markup' => print_r($sample_values, TRUE),
 );

or simply just
print_r($sample_values);

or install Devel module and use dsm function.
dsm($sample_values);

UPDATE:
Try this:
$form['sample'] = array(
    '#type' => 'item',
    '#markup' => print_array_values($sample_values),
);

Then declare the function below:
function print_array_values($sample_values){
    $content = '';
    foreach($sample_values as $val){
            $content .= '
' . $val . '
';
    }

    return $content;
}

Comment: @Suraj -> I updated my answer. Anyways, call me Ms. :)
Comment: Thankyou sir, but print_r($sample_values); will not display the values where i want to display. is there any way to display  values by using foreach loop for form element.So that for each value it will print value.
Comment: I edit the answer to add the second argument in the print_r function (TRUE), to return the sting instead of printing it.
Answer: I would suggest dpm or dsm or kpr, which is very common among Drupal developer for printing variables to debug in Drupal 7. But you need to enable Devel module in your site first as @AlyssaGono suggested.
If you want to use something not depends on other module, you can use var_dump().
Example:

var_dump($variable);
drupal_exit();

Displaying values on hook_form


What is the intuition behind (M)ANCOVA and when/why should one use it?

Question: As per my understanding here's the what/why/when of the following hypotheses tests in a crude sense:

t-test: Used when comparing means between two samples
ANOVA (one way): Used when you have one dependent variable and one independent  (i.e., categorical) variable and you wish to analyze the 'means' (i.e., effects) across multiple groups. Simply stated, multi-way t-tests in essence.
ANOVA (two way): Similar to one-way except you have two independent (i.e., categorical) variables
MANOVA: ANOVA with multiple dependent variables
ANCOVA: ??
MANCOVA: ??

Intuitively, the concepts/intuition behind (M)ANOVA makes sense and I understand when/how to apply it and why is it necessary. I've just overly simplified my understanding about them above. However, I lack the similar intuition behind (M)ANCOVA.
Comment: *ANCOVAs allow for both continuous and categorical variables. You can also have $n$-way versions, not just two-way.
Answer: To complete your scheme:

ANCOVA: ANOVA conducted to compare multiple (possibly only two) conditions on at least one independent variable while controlling for a set of continuous nuisance variables (possibly only one).
MANCOVA: MANOVA conducted to compare multiple (possibly only two) conditions on at least one independent variable while controlling for a set of continuous nuisance variables (possibly only one).
Comment: Let's say you want to assess the mean weight of vegetarians vs. omnivores, but you know that weight will vary in part as a function of height. You don't actually care about the relationship b/t height & weight, you just want to control for that so as to get a clearer picture of how mean weight differs by diet. If you ran a straight ANOVA (in this case, equivalent to a t-test), you could not include what you knew about each individual's height; when you (statistically) control for height, you are running an ANCOVA.
Comment: Yes, it means nothing more than "add it to the equation". My answer here: [How are regression, the t-test, and the ANOVA all versions of the general linear model?](http://stats.stackexchange.com/questions/59047//59048#59048) may help as well.
Comment: If you need more info than this, clarify your question w/ what more you want to know.
Comment: Could you please clarify what this means: *...while controlling for a set of continuous nuisance variables*? What does 'controlling' mean w.r.t. the math?
Comment: Makes sense. When you say "control for it" does it mean "just add it to the equation" (e.g., as an IV on the RHS of the equation) or is there something more subtle? Sorry, I'm not a statistician by trade. I just happen to keep stumbling into using it and seek clarification of the terms so as to not confuse myself.
Comment: To refer to control of some variable, say height, some people will discuss the relationship of interest (e.g., diet and weight) and use the phrase "while holding height constant."


Does a dropbox on a separate computer compromise the security of other devices on the same LAN?

Question: I wish to create a dropbox like service to reach my files remotely.
Let's say I setup a linux box, connect an external hard drive, share it via password protected ftp and use a dyndns service to be able to connect to my network.
Will I compromise the security on the other devices on the same LAN (other computers connected to my router)?
I mean hypothetically somebody who would hack the linux box could then be able to install sniffers and then from the linux box crash my other boxes. Correct?
Is this a realistic risk to consider? Are there other security implications I'm foreseeing?
Answer: Installing anything creates a potential for vulnerabilities - e.g., if there's a vulnerability in the dropbox daemon (or whatever protocol you use for sharing files), or in any other software on your Linux box, it would be possible to exploit it (once it's known). You'll need to evaluate how much of a risk this is for each component that you want to use (e.g. an up-to-date vanilla SSH server install is somewhat safe for such home-server use that you're outlining - given other precautions)
For security considerations: I wouldn't use FTP, it's a plaintext protocol (which may be a vulnerability in itself: your password and your files go over the wire in the clear); I'd go for a SSH server - gives you shell access and SFTP (secure file transfer), both encrypted; it is possible to limit access only to SFTP without a shell though.
Also, there are various helper services which can help against automated attacks, e.g. fail2ban (blocks an IP address from connecting after several failed attempts).
Usual other considerations apply: don't allow superuser (root) remote access, don't use weak passwords (and if possible, don't allow authentication by password at all, instead, use public key authentication and encrypt the private keys), update regularly (or set up automatic update), etc.
Also, block any access to the box except what is actually used (e.g. using iptables, deny everything, then only allow what's needed) - this is a lesser concern on most Linux installs, as there aren't many services open by default, but still worth mentioning.
Comment: I did not outline the case enough. The reason for ftp is that the shared space is also for non-tech-savy individuals. So ssh is not an option. However if sftp encrypts and enables access through password (without keys and known host lists) it is ofc preferrable. However, enabling sftp => enabling ssh - correct? This I find uneasing. When you say do not allow remote login. Do you mean remote login and remote file share differ? I mean ssh:ing in essentially is logging in, or am I misunderstanding? Thanks for the response @Piskvor
Comment: @chris:  As for the biggest issue, there are user-friendly SFTP clients, looking just like FTP clients (FileZilla, WinSCP); they can even be pre-configured for a particular user. Yes, you need to login; I meant "don't allow **superuser** (root) remote access". Next: you can limit a user to SFTP, without giving a remote shell (file share without a command line shell). Encryption is enabled regardless of auth method (password, publickey, what-have-you). Known host list is actually a Good Thing - *your server* is checked for authenticity, so that the user doesn't give a password to an impostor.
Comment: So I shall setup as follows: SFTP, restricted users, no root, no public/private-keys, username+password login, no ssh/shell acess. Thank you @Piskvor


How to deploy docker containers on to gcloud compute instance using travis ci?

Question: I am trying to deploy docker containers from my local machine, test them on Travis CI, Build them and push them to the Container Repository, and then deploy them on my gcloud compute instance. But I can't figure out how to do it and was wondering if someone had done this before and if they could point me to some material that would help me.
Answer: Let's start with Docker:  here you can find how to use Docker with Travis CI. At first, you need to install Docker and Google recommend to use version 18.03 or newer because it's required to use gcloud credential helper for authentication. Also, you need to install Google SDK and enable billing for your project. Check that you have permission to push and pull images to Google Container Registry and don't forget to enable Container Registry API in your project. After that, you can build Docker image, tag it with a registry name, push the image to Container Registry and than you'll be able to pull your images into your project. More information with examples and step by step instructions you can find here and here.


Probability question involving a lift

Question: I am stuck at the following probability problem. Will appreciate your help.
An office block has five floors (ground, 1, 2, 3 and 4), all connected by a lift. When it goes up to any floor (except 4), the probability that after it has stopped it will continue to rise is 3/4. When it goes down to any floor (except the ground floor), the probability that after it has stopped it will continue to go down is 1/4. The lift stops at any floor it passes.
The lift is currently at the first floor having just descended. Calculate the probability of the following events:
a) its second stop is the third floor
b) its third stop is the fourth floor
c) its fourth stop is the first floor.
For part (a), I did this: P(first stop is the second floor)*P(second stop is the third floor) = (3/4)(3/4) = 9/16
For part (b), I did this:
P(first stop is the second floor)*P(second stop is the third floor)*P(third stop is the fourth floor)
= (3/4)(3/4)(3/4) = 27/64
Since the lift is going up and continuing to rise after it stopped at each floor from first floor, finding answers to part (a) and (b) was easy, even though it is unsure whether my logic is sensible or not. Somehow the answers for part (a) and (b) are correct according to the book. If my methods and answers are incorrect, let me know.
Now, I am really stuck at part (c). Not understanding how to solve the problem. How will the lift's fourth stop be the first floor if the lift is continuing to rise from first floor and start descending from the fourth floor? Let me know where the mistake is.
Thanks is advance.
Comment: Why should it do that?  At any point, it might go up or down (with some probability).
Comment: You need to enumerate the routes that work.  the elevator might go $0-1-0-1$, for example.  Or $2-3-2-1$, etc.  Easy to calculate the probability of each.
Comment: Note:  unless I am misreading, this process is not path dependent at all.  That is, if the elevator is on $1,2,3$ then the probability that it goes down next is $\frac 14$, regardless of what it did to get there.  Is that what you intended?
Comment: I thought the lift will go from 0-1-2-3-4 and 4-3-2-1-0 successively. I followed the pattern of the questions.
Comment: Thanks. I will attempt solving part (c) from new perspective.
Answer: The following routes get you from the first floor to the first floor within $4$ moves:

UUDD
UDUD
UDDU
DUUD
DUDU
DDUU is impossible, since we cannot start by going down twice

Now, simply calculate the probability of each route, and then add up the results.
Comment: The general method is to split the problem into **disjoint** events, and then add up their probabilities.
Comment: Thanks for the possible routes you provided and your suggestions.
Comment: @tantrik: You're welcome. Do you understand how to solve from this point?
Comment: I got **45/256**. The answer in the book is **29/128**. Don't know whether the book's answer is correct or not. I took P(U) = 3/4 and P(D) = 1/4. Then for each route the probability is 9/256 which I added together to get 45/256. Let me know where the mistake is.
Comment: I got the answer correct this time. I know where the mistake is.
Comment: @tantrik: Well, where is it then?
Comment: I did not consider that the probability of the lift to go from underground to the first floor is 1.

Probability question involving a lift


Is the zero set of an analytic function closed nowhere dense?

Question: Given a non-constant analytic function $f(x)$ on a domain $D \subseteq \mathbb{R}^n$. I want to prove that
$\mathcal{Z} = \{x \in \mathcal{D} |f(x) = 0 \}$
is closed nowhere dense.
I originally wanted to prove this by contradiction as follows using the identity theorem.
"Assume that $\mathcal{Z}$ is not a closed nowhere dense set, then $\mathcal{Z}$ must contain a limit point", which shows that $f(x)$ is constant zero by the identity theorem and thus contradicts that $f(x)$ is non-constant.
However, I am not sure if the following statement is true:
"Assume that $\mathcal{Z}$ is not a closed nowhere dense set, then $\mathcal{Z}$ must contain a limit point"

If it is true, could you provide one reference?

If not, is $\mathcal{Z}$ closed nowhere dense, and how can I prove it?
Comment: You should say **connected** domain.  Otherwise, your function could be identically zero on some component of $D$ but not on others.  The **identity theorem** you cite is for domains in $\mathbb C$, not in $\mathbb R^n$; so you will need a different reference.
Comment: Here "domain" refers to a domain in $\mathbb{R}^n$ and is open and connected by definition.
Comment: The existence of a limit point of $Z$ is not going to get you very far if $n>1.$
Comment: For example, consider $f(x,y)=x$ on $\mathbb R^2.$
Answer: We know $Z$is closed. So we want to show $Z$ is nowhere dense. Assume, to reach a contradiction, that the interior of $Z,$ denoted by $\text {int } Z,$ is nonempty.
Let $x\in \text {int } Z.$ Let $y\in D.$ Because $D$ is open and connected, $D$ is path connected. So there is a continuous path $\gamma:[0,1]\to D$ with $\gamma(0)=x, \gamma(1)=y.$
Let $E$ be the set of $t\in [0,1]$ such that $f=0$ in an open ball $B_{\gamma(t)}$ centered at $\gamma(t).$ Clearly $0\in E.$ By continuity of $\gamma,$ $\gamma^{-1}(B_{\gamma(t)})$ is an open neighborhood of $t$ in $[0,1].$ And if $s$ is in this neighborhood, $\gamma(s)\in B_{\gamma(t)},$ hence there is an open ball centered at $\gamma(s)$ where $f=0.$ It follows that $E$ is a nonempty open subset of $FE.$
Furthermore, since $f$ is real analytic in $D,$ $E$ is precisely the set of $t\in [0,1]$ where all derivatives of $f$ vanish at $\gamma(t).$ Thus $E$ is closed in $[0,1].$ It follows that $E$ is nonempty and clopen in $[0,1].$ Since $[0,1]$ is connected, $E=[0,1].$
This implies $f(y)=0.$ Since $y\in D$ was arbitrary, we have $f=0$ in $D.$ This is a contradiction, since $f$ was assumed to be nonconstant in $D.$ Therefore $\text {int } Z$ is empty, and $Z$ is nowhere dense as desired.
Answer: Indeed, more is true. It is enough to assume that $\mathcal Z$ is not nowehere dense to show that it has a limit point.
To see it, recall that a set is nowhere dense, by definition, if and only if its closure has empty interior. Then if $\mathcal Z$ is not nowhere dense, its closure has nonempty interior. Any of these points is a limit point of $\mathcal Z$.
EDIT: As Conrad points out in reply to Shi James' comment, to complete the proof for the given $\mathcal Z$, which is a zero set of an analytic (hence continuous) function, we need to notice first that $\mathcal Z$ is necessarily closed.
Comment: Zero set of continuous function is closed always ( pretty much by definition)
Comment: I think for the contradiction proof, If we assume that it does not hold, then it should mean that " $\mathcal{Z}$ is not a closed set or $\mathcal{Z}$  is not a nowhere dense set", right? So I think we should also consider the case where $\mathcal{Z}$ is not closed but still nowhere dense.
Comment: Maybe more relevant to your question and comment, the statement "Assume that $\mathcal Z$ is not a closed nowhere dense set, then $\mathcal Z$ must contain a limit point" is not correct in itself I think. Indeed $\mathcal Z=\{1/n:\ n$ positive integer$\}\subset\mathbb R$ is not a closed nowhere dense set (it is not closed), and it does not contain a limit point.


PHP : Very big no sense with variable

Question: I'm working on a Symfony 2 app.
I've an object manage with Doctrine which it has private $beginDate which is a \DateTime.
I've a function very important :
public function isBefore($timestamp)
{
    print_r($this->beginDate);
    echo "
";
    $date = $this->beginDate->format("Y-m-d"); // (line 44)
    echo $date;
    echo "
";
    return $this->beginDate->getTimestamp() < $timestamp;
}

The first print_r display : DateTime Object ( [date] => 2015-01-01 00:00:00 [timezone_type] => 3 [timezone] => Europe/Paris )
The beginDate->format give me : Error: Call to a member function format() on a non-object in /var/.../GS/AcmeBundle/Entity/ARecur.php line 44
echo $date display : 2015-01-01
And $this->beginDate->getTimestamp() said nothing because the line 44 is blocking others errors (but without the line 44, i've the same error on this line !)
My PHP version :

PHP 5.4.4-14+deb7u14 (cli) (built: Aug 21 2014 08:36:44)
  Copyright (c) 1997-2012 The PHP Group
  Zend Engine v2.4.0, Copyright (c) 1998-2012 Zend Technologies

Any ideas (Sorry for my bad english)
Have a good day :)
Comment: `echo $date;` would not display anything if the error is thrown on `$date = $this->beginDate->format("Y-m-d");`  Are you positive that the error is on line 44 of the same file you are debugging?
Answer: Remove the echo "
" and try, it is not good the mix you html in you code.
Comment: It's for the debug, my really function is :

    public function isBefore($timestamp)
    {
     return $this->beginDate->getTimestamp() < $timestamp;
    }

And it not solve the problem.
Comment: print out $this, see if any difference
Comment: In this, i can the object like **DateTime Object ( [date] => 2015-01-01 00:00:00 [timezone_type] => 3 [timezone] => Europe/Paris )**
Comment: so that's the object in the first print? what about the second print? in the second print, just print out $this
Comment: append ->format("Y-m-d")  to your first object, if errors, then you know what it is
Answer: I've found a solution, not nice but it doesn't crash my app :
public function isBefore($timestamp)
{
    $myDate = json_decode(json_encode($this->beginDate), true);
    return strtotime($myDate['date']) < $timestamp;
}

Comment: That makes no sense at all.  Are you posting actual code or are you "cleaning it up"?  Like @STLMikey, I suspect you are looking at the wrong file.

PHP : Very big no sense with variable


Subdomain that uses Route 53 without migrating parent domain

Question: I currently have a domain (asoba.co) that is hosted on Linode, and for which I use Linode nameservers.  This site currently works as expected.
My goal is to have an additional subdomain for a webapp that is being served from an EC2 instance.  I initially followed the instructions from AWS here on this procedure.  The instructions had me create a hosted zone in Route 53
(picture of record set within the hosted zone) along with appropriate records.  Here I just created an A record that maps the subdomain to the Elastic IP address I assigned to the EC2 instance.
It then had me update the NS records for the subdomain on Linode like you see in this screenshot.
After waiting a few hours, I tested the record set in Route 53, which got the result I was expecting
Response returned by Route 53
Response from Route 53 based on the following options.

DNS request sent to Route 53
data.asoba.co.     IN     A
EDNS0 client subnet IP
24
DNS response code
NOERROR
Protocol
UDP
Response returned by Route 53
126.96.36.199

However, when I point my browser to the subdomain, I get the "domain does not exist" error.  Same thing when I use the "check my dns" services.
Is there a step that I have missed here?
Comment: @ceejayoz OHAI! [I totally stole your answer.](https://meta.serverfault.com/questions/1886/how-to-handle-unanswered-questions-that-have-the-answer-in-a-comment-or-edited-i/1931#1931) You're welcome. :P
Comment: You updated DNS records in Linode, but your DNS for the domain is hosted by CloudFlare. Wrong admin!
Comment: Had forgotten that I was using CloudFlare!  Thanks
Answer:
I currently have a domain (asoba.co) that is hosted on Linode, and for which I use Linode nameservers.

Unless you changed something very quickly after posting your question, it's looking like Linode isn't being used for your domain:
$ dig soa asoba.co

; <<>> DiG 9.11.6-P1-RedHat-9.11.6-3.P1.fc30 <<>> soa asoba.co
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 50883
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 2, ADDITIONAL: 2

;; QUESTION SECTION:
;asoba.co.                      IN      SOA

;; ANSWER SECTION:
asoba.co.               3554    IN      SOA     ben.ns.cloudflare.com. dns.cloudflare.com. 2028984216 10000 2400 604800 3600

;; AUTHORITY SECTION:
asoba.co.               86348   IN      NS      grace.ns.cloudflare.com.
asoba.co.               86348   IN      NS      ben.ns.cloudflare.com.

As a result, you did the work in Linode to delegate a subdomain, but since the main domain asoba.co is hosted by Cloudflare, it's all for naught:
$ dig soa data.asoba.co

; <<>> DiG 9.11.6-P1-RedHat-9.11.6-3.P1.fc30 <<>> soa data.asoba.co
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 18272
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;data.asoba.co.                 IN      SOA

The pertinent result in the above query being: status: NXDOMAIN
So you need to either go to your domain's registrar and change DNS to Cloudflare, and then work with Cloudflare to delegate a subdomain, or go to your registar and switch your authoritative name servers to use Linode.
Comment: I had completely forgotten that I had moved DNS management to Cloudflare.  The Linode piece is irrelevant in that case, and I just need to ad those 4 NS records to the DNS records management panel on Cloudflare.  Gave you the checkmark for answering this question.  Thanks!


Trazer a soma de IDS e dados em duas tabelas usando SQL

Question: Preciso fazer um SQL para que me trague os dados de:
`DATA | QTDE IDTa | QTDE IDTb | VALORa | VALORb | Saldo (diferença de VALORa - VALORb) `

Porém não estou conseguindo trazer os dados corretamente com esse SQL segue exemplo: https://www.db-fiddle.com/f/nU2Ds1qon4jXJd1jk24spQ/1
preciso que saia assim:
    DATA   | TITULOS A PAGAR | TITULOS A RECEBER | VALOR A RECEBER | VALOR A PAGAR | SALDO
01/10/2018 |         5       |         5         |    R$ 30.000    |  28.000       |  R$ 2.000

Nesse caso ele precisa somar todos os IDs da tabela baixagasto enquanto a data de vencimento for igual a data de vencimento, ou seja quero saber quantos títulos vence a cada dia assim como os que tenho para pagar a cada dia e exibir o saldo a diferença dos dois.
Comment: Você precisa dar um exemplo da saída real que você deseja no caso desses dados de exemplo que você informou
Comment: Opa, sim claro.
editei a pergunta e coloquei como preciso da saída exata.
Answer: Tem algumas coisas que eu acho que tu precisa levar em consideração, primeiro é teu JOIN, ele não tem um ON e olhando a estrutura das duas tabelas eu não vejo uma ligação entre elas para um JOIN.
Outra coisa é a falta de um GROUP BY para ficar claro por qual coluna (imagino pela tua saída que seja a data) tu está agrupando itens para somar.
Eu faria a união de dois selects distintos (um de receita e um de gasto, sendo o de gasto com valores negativos), agruparia o resultado por data e somarias os valores todos (como gasto é negativo na soma ele iria subtrair
SELECT U.datavencto, SUM(U.valorprogramado)
FROM (
    SELECT datavencto, valorprogramado
    FROM baixareceita

    UNION ALL

    SELECT datavencto, valorprogramado * (-1)
    FROM baixagasto
) U
GROUP BY U.datavencto

[EDIT]
Coloquei os outros campos que tu queria como retorno
SELECT U.datavencto, SUM(U.qtd_receber), SUM(U.qtd_pagar), SUM(U.valor_receber), SUM(U.valor_pagar), SUM(U.valor_total)
FROM (
    SELECT datavencto, COUNT(idbaixareceita) AS qtd_receber, 0 AS qtd_pagar, SUM(valorprogramado) AS valor_receber, 0 AS valor_pagar, SUM(valorprogramado) AS valor_total
    FROM baixareceita
    GROUP BY datavencto

    UNION ALL

    SELECT datavencto, 0 AS qtd_receber, COUNT(idbaixagasto) AS qtd_pagar, 0 AS valor_receber, SUM(valorprogramado) AS valor_pagar, SUM(valorprogramado)*(-1) AS valor_total
    FROM baixagasto
    GROUP BY datavencto
) U
GROUP BY U.datavencto

Comment: Obrigado pelo código,
Ajudou demais.
Valeu mesmo.


NSArray Sorting Examples

Question: Please anyone help me to find out the Sort elements of array which contains the names of students like:
NSArray *studentsNames=@[@"bill", @"rob", @"ady",@"jhon", @"robert", @"prince"];
All sorting function present in NSArray like following :

sortedArrayHint
sortedArrayUsingFunction:context
sortedArrayUsingFunction:context:hint
sortedArrayUsingDescriptors
sortedArrayUsingSelector
sortedArrayUsingComparator
sortedArrayWithOptions:usingComparator

Please give me proper examples or link for this.
Answer: You can sort NSArray in following manner
studentsNames = [anArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

Hope this will help you.

NSArray Sorting Examples


G Suite Admin API to access drive of all users

Question: I need to access all the files from the google drive account of all the G Suite user account from admin account.
Using Google Apps Admin SDKAPI, I can access information of all account but unable to access their Drive.
I have seen admin can access google drive of all the users by admin console UI, but unable to find  API for same. I can access google drive from individuals access token with this API, but not of all users by admin token. Can anyone please help me into this?
Answer: For this you must use Google Drive Api. You have to add the scope of your app inside security in the control panel.
With this you can autenticate has any user in the G Suite Domain and use the Google Drive as the user.
Here you can check more information about it https://developers.google.com/drive/v3/web/about-auth
Comment: than which API I should call,can u pls give me a link.
Comment: Inside security in the control panel, there are 6 section Basic,PasswordMonitoring,API ref ,SSO,Advance,SSL,Security& Privacy.None there have option to add scope,Am I missing some thing?can u pls tell me the path where to go.
Answer: You may check this thread Can the domain administrator see / edit all documents in Google Docs domain?.

No, the domain administrator can NOT see or edit any documents that you do not share with him or her. Google Docs are automatically private and you have to change the Share settings to invite the administrator as an owner, collaborator, or viewer.
However, the administrator is able to go in to his domain control panel and reset your password to a new password that he or she knows. Then the administrator can log in as you and see and edit your documents. Keep in mind that any password you set is private. The administrator can only reset your password to another password that he or she knows. Of course, with any domain, you need to trust the administrator not to invade your privacy and they should have posted their terms of use and privacy policy for their domain.

You can find in this link the Pre-built administrator roles wherein each role grants one or more privileges that together, allow performing a common business function.
Comment: I looked over the same,but the problem over here is to access any user file by admin password need to be reset,and there is no API to fetch users actual password,so when even admin accessing a file we have to update user by email that ur password has reset,so change your password.


How to derive the identity $\vert z_1 + z_2 \vert^2 = r_1^2 + r_2^2 + 2r_1r_2\cos(\theta_1 - \theta_2)$

Question: I am working through a System and Signals book on my own time, and have acquired a copy of the answer key to check my work.
One of the problems involves proving $(\vert z_1 \vert - \vert z_2 \vert)^2 \leq \vert z_1 + z_2 \vert^2$. The strategy the answer key uses relies on the identity $\vert z_1 + z_2 \vert^2 = r_1^2 + r_2^2 + 2r_1r_2\cos(\theta_1 - \theta_2)$, (where $r_1$ and $\theta_1$ are the magnitude and angle of $z_1$) which it simply declares without any further elaboration.
How does one get this identity? Is this well-known?
What I've tried:
Knowing that I probably ought to stay in polar form, I start with... $$\vert z_1 + z_2 \vert^2 = \vert r_1e^{j\theta_1} + r_2e^{j\theta_2} \vert^2 = \vert r_1^2e^{j2\theta_1} + r_2^2e^{j2\theta_2} + 2r_1r_2e^{j(\theta_1 + \theta_2)} \vert$$
...which I can then divide out $e^{j(\theta_1 + \theta_2)}$ with...
$$
\begin{align}
\vert r_1^2e^{j2\theta_1} + r_2^2e^{j2\theta_2} + 2r_1r_2e^{j(\theta_1 + \theta_2)} \vert &=
\vert r_1^2e^{j(\theta_1 - \theta_2)} + r_2^2e^{-j(\theta_1 - \theta_2)} + 2r_1r_2\vert \cdot \vert e^{j(\theta_1 + \theta_2)}\vert \\
&= \vert r_1^2e^{j(\theta_1 - \theta_2)} + r_2^2e^{-j(\theta_1 - \theta_2)} + 2r_1r_2\vert
\end{align}
$$
This seems to be getting closer to a cosine being inside the equation, but at the same time not where I would expect.
Comment: Expand using $|z|^2 = \bar{z} z$.
Comment: @copper.hat This answer let me figure out how the book would have expected someone at my skill level to solve it. You should make it its own answer.
Comment: Note that $|z|^2 = \overline{z} z$, this is easy to show by writing $z=x+iy$ and multiplying. $|z_1+z_2|^2 = (\overline{z_1+z_2}) (z_1+z_2) = |z_1|^2+|z_2|^2 + 2 \operatorname{re} z_1 \overline{z_2}$. Use $z_k = r_k e^{i \theta_k}$ to show that $\operatorname{re} z_1 \overline{z_2} = r_1r_2 \cos ( \theta_1-\theta_2)$.
Answer: My most immediate inclination is to use the inner product. Recall, if $z := a+ib, w := c+id \in \mathbb{C}$ then we may define
$$
\newcommand{\ip}[1]{\left\langle #1 \right\rangle}
\ip{z,w} := \overline{z} w = (a-ib)(c+id) = (ac+bd) + i(ad-bc)
$$
We can define norms via inner products (in general), too:
$$
\| z \| := \sqrt{\ip{z,z}}
$$
(We call this the norm induced by the inner product. For complex numbers, this is the modulus, $|z|$.)
An identity that holds for inner products in general (which you can prove from the definitions of such) is
$$
\|x+y\|^2 = \ip{x+y,x+y} = \|x\|^2 + \|y\|^2 + 2 \cdot \mathfrak{Re} \ip{x,y}
$$
To prove this, expand out $\ip{x+y,x+y}$ using the sesqui-linearity of the inner product, and the conjugate-symmetry rule of $\ip{x,y} = \overline{\ip{y,x}}$. If you wish to prove it for the given inner product described at the start without appealing to these rules, you may note that
$$
\overline{z+w} = \overline z + \overline w
$$
and
$$
|z|^2 = \overline z z
$$
and
$$
\ip{z+w,z+w} = \overline{(z+w)} (z+w)
$$
Of course, then, the question is how to rectify this $\mathfrak{Re} \ip{x,y}$ term into something useful. For that, simply find $\ip{x,y}$, express the result in the polar form, and take the real part according to Euler's formula, $e^{i\theta} = \cos \theta + i \sin \theta$.
Comment: This is a very beautiful proof, but the textbook I'm using begins by covering what complex numbers even are. I didn't even know what "sesqui-linearity" was until looking it up. That being said it does work!
Answer: As an alternative approach, I would recommend you to apply the triangle inequality twice.
To begin with, notice that
\begin{align*}
|z_{1}| = |(z_{1} + z_{2}) - z_{2}| \leq |z_{1} + z_{2}| + |z_{2}|
\end{align*}
Similarly, one also concludes that
\begin{align*}
|z_{2}| = |(z_{1} + z_{2}) - z_{1}| \leq |z_{1} + z_{2}| + |z_{1}|
\end{align*}
Gathering both results, it results that:
\begin{align*}
|z_{1} + z_{2}| \geq \max\{|z_{1}| - |z_{2}|, |z_{2}| - |z_{1}|\} = ||z_{1}| - |z_{2}||
\end{align*}
and we are done.
Hopefully this helps!
Answer: We can also show this geometrically by plotting the complex numbers as vectors on the Argand plane. Let $O$ be the origin, $A$ be the point represented by $z_1$, $B$ be the point represented by $z_2$ and $C$ be the point represented by $z_1 + z_2$.
We can see that the length of $OC$ is $|z_1+z_2|$. By chasing angles, you can show that $\angle OBC$ is equal to $\pi - (\theta_1 - \theta_2)$. Applying the cosine rule on $\triangle OBC$ gives you
$$ |z_1+z_2|^2 = r_1^2 + r_2^2 - 2 r_1 r_2 \cos(\pi - (\theta_1 - \theta_2)),$$
and the result follows after applying the identity $\cos (\pi - \alpha) = - \cos\alpha$.


Show that $S$ contains $n+1$ different numbers $a_1,\cdots, a_{n+1}$ such that $a_i | a_{i+1}$ for each $1\leq i\leq n.$

Question:
(Romanian IMO/BMO Team Selection Tests April 2005 Day 1 Problem 2). Let $n$ be a positive integer and $S$ a set of $n^2 + 1$ positive integers with the property that every $(n+1)$-element subset of $S$ contains two numbers one of which is divisible by the other. Show that $S$ contains $n+1$ different numbers $a_1,\cdots, a_{n+1}$ such that $a_i | a_{i+1}$ for each $1\leq i\leq n.$

I think there should be an elementary solution that doesn't require theorems such as Dilworth's Theorem regarding posets. For the elementary solution, it could be useful to use the pigeonhole principle, induction, or a proof by contradiction. It might also be useful to come up with a sufficiently-sized example of such a set of positive integers in the first place. For $n=1$, $S$ has two elements, one of which is divisible by the other and the claim trivially holds.

Here's a proof for the $n=2$ case that I came up with myself:

For $n=2$, $S$ needs $5$ integers. Write $S = \{b_1,b_2,\cdots, b_5\}, b_1 < b_2<\cdots < b_5$. Every $3$-element subset of $S$ has $2$ elements one of which divides the other. Suppose $S$ does not have $3$ different numbers that divide each other consecutively. Then consider the first three elements of $S$. We may find $a_1,a_2$ among them with $a_1 | a_2$. Then by assumption $a_2$ cannot divide any other element of $S$. Assume first that $a_1 = b_1$. If $a_2 = b_2$, then considering $\{b_2,b_3,b_4\}$, we see that $b_3 | b_4.$ Considering $\{b_2,b_3,b_5\},$ we see that $b_3 | b_5.$ Considering $\{b_2,b_4,b_5\},$ we see $b_4 | b_5.$ But this gives a contradiction since we can choose $\{b_3,b_4,b_5\}$ as the 3-element subset.
Now assume $a_2 = b_3$. Considering $\{b_3,b_4,b_5\},b_4 | b_5.$ Considering $\{b_2,b_3,b_4\},$ we see that $b_2 | b_3$. Considering $\{b_1,b_2,b_4\},$ we see that there is no possibility left (that won't lead to a contradiction).
Finally, assume $a_1 = b_2,a_2=b_3.$ Considering $\{b_3,b_4,b_5\}, b_4 | b_5.$ Considering $\{b_1,b_2,b_4\}$, we see that there is no possibility left. Hence the claim must hold for $n=2$.

Here's the technical solution I found online.

We can define a poset on $S$ by $x\leq y$ iff $x|y$. The condition that there does not exist an $n+1$ element subset such that no element divides another translates into the condition that there is no antichain of length $n+1$ in $S$. An antichain is any sequence of pairwise distinct elements of $S$ none of which are comparable according to the ordering on the poset on $S$. Hence the longest antichain in $S$ is of length at most n, so by Dilworth's theorem, $S$ can be written as the union of at most n chains. Since $S$ has $n^2+1$ elements, this implies one of these chains has a length of at least $n+1$.

Version of Dilworth's Theorem used: Let $P$ be a finite poset. Then the smallest set of chains whose union is $P$ has the same cardinality as the longest antichain.
Answer: Here is a simple proof that uses the pigeonhole principle.

Call a sequence of different numbers in $S$ a divisible sequence if each number except the first number in the sequence is divisible by the number preceding it. We are asked to show there is a divisible sequence of at least $n+1$ numbers.
Towards a contradiction, suppose any divisible sequence contains at most $n$ numbers.
For each number $s$ in $S$, let $D_s$ be one of the longest divisible sequences that start with $s$. So we have $n^2+1$ sequences (pigeons). The length of each   $D_s$ is one of $1,2,\cdots, n$, ($n$ holes). Hence, at least $\lceil\frac{n^2+1}{n}\rceil=n+1$ $D_s$'s must have the same length.
Consider the first elements of those at least $n+1$ $D_s$'s. One of them, $x$ must be divisible by another of them, $y$. We can prepend $D_x$ by $y$ to obtain a divisible sequence starting with $y$ that is longer than $D_x$ and hence also $D_y$, which contradicts with the definition of $D_y$.
Answer: This is more of an extended comment than an answer, but it may be worth noting that this problem's setup is "morally equivalent" to that of posets, in the following sense:
Claim. For every finite poset $P$ with elements $x_1,\dots,x_m$, there exist positive integers $y_1,\dots,y_m$ for which, for $1\leq i,j\leq m$, $x_i\leq x_j$ if and only if $y_i\mid y_j$.
Proof. For each $i$, let $S_i\subset\{1,2,\dots,m\}$ be the set of $j$ for which $x_i\leq x_j$. Let $p_1,\dots,p_n$ be distinct primes, and define
$$y_i=\prod_{j\not\in S_i}p_j.$$
Then, if $x_i\leq x_j$, $x_i\leq x_k$ whenever $x_j\leq x_k$, so $S_j\subset S_i$, meaning
$$y_i=\prod_{k\not\in S_i}p_k\ \bigg|\ \prod_{k\not\in S_j}p_k=y_j.$$
Conversely, if $y_i\mid y_j$, then $p_j$ cannot divide $y_i$ (since $p_j\nmid y_j$), so $j\in S_i$, meaning $x_i\leq x_j$. $\square$
So, Dilworth's theorem is equivalent to the following:

Call a sequence $(a_1,\dots,a_k)$ a divisible sequence if $a_1\mid a_2\mid \cdots\mid a_k$. For a set $S$ of positive integers, the maximum size of a subset $T\subset S$ for which no distinct elements of $T$ divide each other is equal to the minimum number of divisible sequences into which $S$ may be partitioned.

In particular, the solution of ApassJack can be rephrased, using "chain" instead of "divisible sequence," to give a proof of Dilworth's theorem.


How can I theme webform?

Question: I've got a website with a custom theme who was developed by an external group. I would like to custom the webform appearance.
In my form, there are grid fields. And these grid fields need to have a description. But in my custom theme, the description appears under the grid and I would like it appears just between the label and the grid. I hope you see what I mean.
In the theming.txt it seems that I have to edit the webform-form.tpl.php and save it to my theme folder. But in this file, there are only PHP code. So, how can I modify the HTML structure?
Answer: I found the solution.
Editing the template.php file of my custom theme and more specifically the theme_form_element() function. In that function, simply move these 3 lines where I want :
if (!empty($element['#description'])) {
    $output .= '
' . $element['#description'] . "
\n";
}

How can I theme webform?


DS or DC al coda how to tell go to 3 and 4 verses

Question: I have a song in this format:
Verse 1
Verse 2
Chorus  has a 1st and 2nd ending
Verse 3
Verse 4
Chorus
I use repeat for V1 and V2  and then I go to Chorus easy enough.
Now I want to go to Verse 3 and Verse 4 then finish with the Chorus and a little ending.
I know using a DS or DC al Coda will get me to the Beginning of song.
How do I tell go to Verse 3 and Verse 4 then chorus?
Do I place a note in the Chorus DC al coda to tell use Verse 3 and 4?
Answer: You can use the Dal Segno Al Coda.
The way this is used is:

Play until you reach the D.S. symbol
Go back to the 'S' (Segno) symbol
Play until the Coda symbol
Play the Coda.

Here are the symbols:

So, when the score reaches verse 4, put a D.S. Al coda symbol and the 'S' symbol on the beginning of the chorus.
At the end of the chorus put the Coda symbol and on the Coda put the ending of the chorus you want.


tournament winner python while loop

Question: I made a function 'Match' which takes two country and return a winner according to my algorithm.
EX)
def Match(England, Brazil) ----> England,
def Match(Mexico, France) ---> France

I need to write function Winner which takes list of 2^n nations and run a tournament and find a winner.
EX)
def Winner([England, Brazil, Mexico, France]) ---> France

England---Brazil,        Mexico---France  (Semifinal)

England---France (final)

France (winner) Return value

The length of nation list differs and I cannot make a winner choosing algorithm. The match-up is It would be great if the code uses while loop rather than for loop ^^.
Comment: Can you share your code please ? [edit] your post and add it
Comment: Can you share a small CSV example ? for me to understand the data
Comment: Is all your code mandatory regarding rules from the exercice or not ? Like for the `match` rules
Comment: there is A LOT of improvements to do to your code, you're doing same things SO many times instead of 1, come here and we'll work on it https://chat.stackoverflow.com/rooms/230994/67042729-tournament-winner
Comment: @태주강 come in the chat now
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/230998/discussion-between-azro-and-).
Comment: what's exactly your question ?
Comment: I am having trouble in creating a function 'Winner' which chooses the winner of the tournament.
Comment: I cannot enter the room and chat
Comment: It says I need 20 more reputation ...??
Comment: all functions are mandatory and I'll post the cvs
Comment: Guinea,Conakry,9.5,-13.700000,GN,Africa//
Guinea-Bissau,Bissau,11.85,-15.583333,GW,Africa//
Guyana,Georgetown,6.8,-58.150000,GY,South America//
Haiti,Port-au-Prince,18.533333333333335,-72.333333,HT,North America//
...
Answer: Your tournament method should make matches between consecutive pairs of players, for ["a", "b", "c", "d", "e", "f", "g", "h"] it should be a/b, c/d, e/f and g/h
You can achieve these with slicing and zip

countries[::2] takes 1 on 2 so ["a", "c", "e", "g"]

countries[1::2] same but starting at 1 so ["b", "d", "f", "h"]

zip pairs these 2 lists to create pairs of opponents

Keep the winner of each match, and call tournament recursivly with the next round of players which contains half of players
# FOR DEMO PURPOSER
def match(country_a, country_b):
    return random.choice([country_a, country_b])

def tournament(countries):
    n = len(countries)
    if not ((n & (n - 1) == 0) and n != 0):
        raise Exception("Size isn't power of 2")

    if n == 2:
        return match(*countries)

    next_round = []
    for player1, player2 in zip(countries[::2], countries[1::2]):
        winner = match(player1, player2)
        next_round.append(winner)

    return tournament(next_round)

Using list-comprehension the for-loop and return can be replaced with
return tournament([match(p1, p2) for p1, p2 in zip(countries[::2], countries[1::2])])

Improvement full code
After some time and discussion with the OP here's a major improvement of the full code with the major rules :

don't call the exact same method in a loop, do it outside
don't call a method again and again if it does the same, store the data somewhere
Comment: @태주강 a time limit ? I can't see how to improve that, it does the minimum of matches possible, the only way to gain time is on `match` method, can you edit your initial post and add your `match` code ? You can think about voting up that answer, and accepting it (green tick on left) it if satisfies you ;)
Comment: @태주강 As I asked already 2 times : it would be nice to post YOUR `match` code INTO your initial post up there yes, you may click 'edit' on your question post and add it (see my comment under your post, it also contains the 'edit' link for YOUR post)
Comment: It worked and I finally understand the code.
Comment: However, I was working on a tutor program and popped a Time Limit Exceeded problem... HaHa...
Comment: I actually had many codes before the 'tournament' method....Whole code is over 100 length and just like you said, the previous code occurs the problem.
Comment: I will try my best to simplify my code to shorter the operation time
Comment: I don't know what you mean at the last sentence. You mean posting my code here?
Comment: Got it. I was just little bit sorry(?) to post my long code and you to read it all...

tournament winner python while loop


TViOS third party library marmelroy/Zip

Question: Wanted to use carthage and this library...
https://github.com/marmelroy/Zip
But having updated brew and downloaded the latest carthage & Zip code I get this error when I try to build?
Module file was created for incompatible target arm64-apple-ios8.0: /Users/localuser/blah/blah/blah/blah/Carthage/Build/iOS/Zip.framework/Modules/Zip.swiftmodule/arm64.swiftmodule
My target is AppleTV iOS version 9.2: Noted too this error message ...
ld: building for tvOS, but linking against dylib built for iOS, file '/Users/localuser/blah/blah/blah/Carthage/Build/iOS/Zip.framework/Zip' for architecture arm64
Am I attempting the impossible here? Is there a way around it?
localuser$ carthage update --platform iOS
* Cloning Zip
 Checking out Zip at "0.3.4"
 xcodebuild output can be found in /var/folders/rd/m94y05zs6836d9lrmh44f0b40000gp/T/carthage-xcodebuild.O5thOi.log
* Building scheme "Zip" in Zip.xcodeproj
And this ...
* Checking out Zip at "0.3.4"
 xcodebuild output can be found in /var/folders/rd/m94y05zs6836d9lrmh44f0b40000gp/T/carthage-xcodebuild.vhb9nL.log
 Building scheme "Zip OSX" in Zip.xcodeproj
* Building scheme "Zip" in Zip.xcodeproj
Answer: The latest version of the library Zip (https://github.com/marmelroy/Zip) is 0.4.3 and it can be easily installed with the CocoaPods or the Carthage. I tested it on tvOS 9.2.

TViOS third party library marmelroy/Zip


Como descobrir o diretório do arquivo pelo "inspecionar elemento"

Question: Gostaria de saber em qual arquivo ( ou diretório ) se encontra o arquivo do elemento específico de uma página web inspecionado.
Importante: seria um arquivo do wordpress php, e não css.
Answer: Na guia 'Source' do Inspecionar você consegue visualizar algumas informações sobre o diretório do arquivo em sites comuns.
PS: só respondi aqui porque não consegui comentar sua pergunta.
Comment: Legal. Mas ele mostra um index dentro do wordpress que no "sources" aparece o código. Porém no servidor está em branco.
Comment: Claro, porque o arquivo .php roda do lado do servidor, para você (no navegador, ou seja, no cliente) ele mostra apenas os retornos, e não necessariamente o código PHP, por isso seria quase impossivel...
Comment: Sim. Mas mesmo baixando o arquivo e abrindo ele também não mostra nada. Apenas a mensagem abaixo:

<?php
// Silence is golden.
Comment: Cara, poderia por o link do que vc está tentando baixar, só para eu dar uma olhada?
Comment: Por gentileza,  é o seguinte.. eu preciso saber em qual arquivo ( ou diretório ) está o código do slider da home desse site.. https://f***.com.br/
Comment: a probabilidade de vc descobrir isso é 5%... Provavelmente, em alguma pasta de plugins do proprio wordpress, mas é dificil dizer só com isso...
Comment: Poise já procurei mas também não achei. Mas beleza.. Obrigado por tentar ajudar!
Answer: Se Clicar em cima da imagem e clicar para abrir em uma nova aba, na maioria das vezes dar certo também. Ele aparece o diretório.
Comment: Mas apenas o diretório da imagem. Eu previso do arquivo onde eu possa linkar o slider


Good PDE Book That Explains Why

Question: I am interested in studying the basics of PDEs. I cannot find a good book on PDEs. I want a book that is more on the abstract side and explains why (so not Evan's). For example, if the topic is second order linear PDEs, I want the book to explain why they are classified into elliptic, hyperbolic and parabolic, and then explain how the time coordinate can be separated in the hyperbolic and parabolic cases (preferably before trying to solve them). I have a fairly strong background in introductory mathematics and prefer that the book takes advantage of functional analysis (but with motivation) and (sometimes) considers general Banach spaces. I want specific PDEs (such as Laplace's equation) to only be examples.
Comment: http://eu.wiley.com/WileyCDA/WileyTitle/productCd-EHEP000037.html
Comment: https://books.google.com/books/about/Lectures_on_Partial_Differential_Equatio.html?id=qlNJAYwmfTcC
Answer: The book by Renardy and Rogers does a much better job of explaining this kind of thing than Evans (of course, others might have a different opinion).
https://www.amazon.com/gp/aw/d/1441918205/ref=mp_s_a_1_1?ie=UTF8&qid=1486424647&sr=8-1&pi=AC_SX236_SY340_FMwebp_QL65&keywords=renardy+rogers+partial&dpPl=1&dpID=41qkS5uoxSL&ref=plSrch

Good PDE Book That Explains Why