Apache2 not sending installed SSL certificate

Question: I've spent hours and hours researching this problem and before I do something drastic like redoing all of the relevant configs I thought I'd ask for help.
I'm a student sys-admin at a college and we've been having a problem with a website we're hosting.  Visiting the website gives a "security certificate not trusted warning".  Viewing the certificate shows it is the default, self-signed server cert, not the one we purchased and that is supposed to get served.
This problem first came to our attention when we tried to switch this domain from pointing to a "regular" site to a new Drupal site.  Originally domain.flavor.name.edu and domain.name.edu both pointed to the same regular site.  We wanted to keep domain.flavor.name.edu pointing to the old and point domain.name.edu to the new Drupal site, so I deleted the domain.name.edu.conf files out of vhosts.d.  Understandably, the SSL errors came but since I had never seen any of our other sites with valid SSL I didn't think much of it.  However, the boss insists that the SSL was working fine before.  To backtrack I moved back the files that I had removed, but I don't think that solved the problem (sorry I'm a bit hazy here, it's been several weeks since this first happened, and the other sys-admin may have changed some things too).  Anyway maybe that means the problem is really just with the .confs in vhosts.d since domain.name.edu is still pointing to the new Drupal site and not back to the old.  I have done several restarts of apache, both graceful and regular restart.
The server (running Gentoo) is set up with Name Based Virtual Hosts, all on the same IP.  As I understand, we should be able to have multiple sites with different SSL certs through SNI.  The error_log confirms that we have SNI set up (Init: Name-based SSL virtual hosts only work for ...).
in  /etc/apache2/vhosts.d/ there's:
00_default_vhost.conf
00_ssl_domain.name.edu.conf
05_default_ssl_vhost.conf
blah blah more .confs
I remember reading there can be some kind of conflicts if Apache reads the wrong .conf in vhosts.d first and it does whatever's there without looking further or something of the sort but I think the numbers are supposed to take care of that, order wise 00_ssl_domain.name.edu should come before the default.
In 00_ssl_domain.name.edu.conf
...
SSLCertificateFiles /etc/ssl/apache2/domain.name.edu.crt
...
SSLCertificateKeyFile /etc/ssl/apache2/domain.name.edu.key
...
SSLCertificateChainFile /etc/ssl/apache2/geotrust.crt
...
Both the certificate and intermediate should be good, I even dug up the email from earlier this spring when we got the certificates and recopied them in. openssl verify -CAfile geotrust.crt domain.name.edu.crt returns OK.
Maybe this is a Drupal problem, maybe I've botched something horribly, but any help would be so greatly appreciated.
*disclaimer: Sorry about the long text and also I have only been at my post for a year, and only in any capacity since the beginning of this semester.  The previous sys-admin who did everything here left this sem.  So basically I didn't set up these servers and the apache install etc.
Edit1:Testing on Windows 7 with Firefox 15, Chrome 22, and IE 9 all give the same result
Edit2: Relevant vhosts.d 00_ssl_domain.name.edu.conf
<IfDefine SSL>
#<IfDefine SSL_DEFAULT_VHOST>
<IfModule ssl_module>
# see bug #178966 why this is in here

# When we also provide SSL we have to listen to the HTTPS port
# Note: Configurations that use IPv6 but not IPv4-mapped addresses need two
# Listen directives: "Listen [::]:443" and "Listen 0.0.0.0:443"
Listen 18.104.22.168:443

#Added so that the ServerName directive works
NameVirtualHost 184.108.40.206:443
# Go ahead and accept connections for these vhosts
# from non-SNI clients
SSLStrictSNIVHostCheck off
<VirtualHost 18.104.22.168:443>
        ServerName domain.name.edu
        #Include /etc/apache2/vhosts.d/default_vhost.include
        Include /etc/apache2/vhosts.d/domain.include

        <IfModule log_config_module>
                TransferLog /var/log/apache2/ssl_access_domain.name.edu
        </IfModule>

        ## SSL Engine Switch:
        # Enable/Disable SSL for this virtual host.
        SSLEngine on
        #SSLLog /var/log/apache2/ssl_engine_log
        LogLevel debug

        ## SSL Cipher Suite:
        # List the ciphers that the client is permitted to negotiate.
        # See the mod_ssl documentation for a complete list.
        SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL

        ## Server Certificate:
        # Point SSLCertificateFile at a PEM encoded certificate. If the certificate
        # is encrypted, then you will be prompted for a pass phrase. Note that a
        # kill -HUP will prompt again. Keep in mind that if you have both an RSA
        # and a DSA certificate you can configure both in parallel (to also allow
        # the use of DSA ciphers, etc.)
        SSLCertificateFile /etc/ssl/apache2/domain.name.edu.crt

        ## Server Private Key:
        # If the key is not combined with the certificate, use this directive to
        # point at the key file. Keep in mind that if you've both a RSA and a DSA
        # private key you can configure both in parallel (to also allow the use of
        # DSA ciphers, etc.)
        SSLCertificateKeyFile /etc/ssl/apache2/domain.name.edu.key

        ## Server Certificate Chain:
        # Point SSLCertificateChainFile at a file containing the concatenation of
        # PEM encoded CA certificates which form the certificate chain for the
        # server certificate. Alternatively the referenced file can be the same as
        # SSLCertificateFile when the CA certificates are directly appended to the
        # server certificate for convinience.
        SSLCertificateChainFile /etc/ssl/apache2/geotrust.crt
        #SSLCertificateChainFile /etc/ssl/test-certs/geotrust.crt

        ## Certificate Authority (CA):
        # Set the CA certificate verification path where to find CA certificates
        # for client authentication or alternatively one huge file containing all
        # of them (file must be PEM encoded).
        # Note: Inside SSLCACertificatePath you need hash symlinks to point to the
        # certificate files. Use the provided Makefile to update the hash symlinks
        # after changes.
        #SSLCACertificatePath /etc/ssl/apache2/ssl.crt
        #SSLCACertificateFile /etc/ssl/apache2/ca-bundle.crt

        ## Certificate Revocation Lists (CRL):
        # Set the CA revocation path where to find CA CRLs for client authentication
        # or alternatively one huge file containing all of them (file must be PEM
        # encoded).
        # Note: Inside SSLCARevocationPath you need hash symlinks to point to the
        # certificate files. Use the provided Makefile to update the hash symlinks
        # after changes.
        #SSLCARevocationPath /etc/ssl/apache2/ssl.crl
        #SSLCARevocationFile /etc/ssl/apache2/ca-bundle.crl

        ## Client Authentication (Type):
        # Client certificate verification type and depth. Types are none, optional,
        # require and optional_no_ca. Depth is a number which specifies how deeply
        # to verify the certificate issuer chain before deciding the certificate is
        # not valid.
        #SSLVerifyClient require
        #SSLVerifyDepth  10

        ## Access Control:
        # With SSLRequire you can do per-directory access control based on arbitrary
        # complex boolean expressions containing server variable checks and other
        # lookup directives. The syntax is a mixture between C and Perl. See the
        # mod_ssl documentation for more details.
        #<Location />
        #       #SSLRequire (    %{SSL_CIPHER} !~ m/^(EXP|NULL)/ \
        #       and %{SSL_CLIENT_S_DN_O} eq "Snake Oil, Ltd." \
        #       and %{SSL_CLIENT_S_DN_OU} in {"Staff", "CA", "Dev"} \
        #       and %{TIME_WDAY} >= 1 and %{TIME_WDAY} <= 5 \
        #       and %{TIME_HOUR} >= 8 and %{TIME_HOUR} <= 20       ) \
        #       or %{REMOTE_ADDR} =~ m/^192\.76\.162\.[0-9]+$/
        #</Location>

        ## SSL Engine Options:
        # Set various options for the SSL engine.

        ## FakeBasicAuth:
        # Translate the client X.509 into a Basic Authorisation. This means that the
        # standard Auth/DBMAuth methods can be used for access control. The user
        # name is the `one line' version of the client's X.509 certificate.
        # Note that no password is obtained from the user. Every entry in the user
        # file needs this password: `xxj31ZMTZzkVA'.

        ## ExportCertData:
        # This exports two additional environment variables: SSL_CLIENT_CERT and
        # SSL_SERVER_CERT. These contain the PEM-encoded certificates of the server
        # (always existing) and the client (only existing when client
        # authentication is used). This can be used to import the certificates into
        # CGI scripts.

        ## StdEnvVars:
        # This exports the standard SSL/TLS related `SSL_*' environment variables.
        # Per default this exportation is switched off for performance reasons,
        # because the extraction step is an expensive operation and is usually
        # useless for serving static content. So one usually enables the exportation
        # for CGI and SSI requests only.

        ## StrictRequire:
        # This denies access when "SSLRequireSSL" or "SSLRequire" applied even under
        # a "Satisfy any" situation, i.e. when it applies access is denied and no
        # other module can change it.

        ## OptRenegotiate:
        # This enables optimized SSL connection renegotiation handling when SSL
        # directives are used in per-directory context.
        #SSLOptions +FakeBasicAuth +ExportCertData +StrictRequire
        <FilesMatch "\.(cgi|shtml|phtml|php)$">
                SSLOptions +StdEnvVars
        </FilesMatch>

        <Directory "/var/www/localhost/cgi-bin">
                SSLOptions +StdEnvVars
        </Directory>

        ## SSL Protocol Adjustments:
        # The safe and default but still SSL/TLS standard compliant shutdown
        # approach is that mod_ssl sends the close notify alert but doesn't wait
        # for the close notify alert from client. When you need a different
        # shutdown approach you can use one of the following variables:

        ## ssl-unclean-shutdown:
        # This forces an unclean shutdown when the connection is closed, i.e. no
        # SSL close notify alert is send or allowed to received.  This violates the
        # SSL/TLS standard but is needed for some brain-dead browsers. Use this when
        # you receive I/O errors because of the standard approach where mod_ssl
        # sends the close notify alert.

        ## ssl-accurate-shutdown:
        # This forces an accurate shutdown when the connection is closed, i.e. a
        # SSL close notify alert is send and mod_ssl waits for the close notify
        # alert of the client. This is 100% SSL/TLS standard compliant, but in
        # practice often causes hanging connections with brain-dead browsers. Use
        # this only for browsers where you know that their SSL implementation works
        # correctly.
        # Notice: Most problems of broken clients are also related to the HTTP
        # keep-alive facility, so you usually additionally want to disable
        # keep-alive for those clients, too. Use variable "nokeepalive" for this.
        # Similarly, one has to force some clients to use HTTP/1.0 to workaround
                SSLOptions +StdEnvVars
        </Directory>

        ## SSL Protocol Adjustments:
        # The safe and default but still SSL/TLS standard compliant shutdown
        # approach is that mod_ssl sends the close notify alert but doesn't wait
        # for the close notify alert from client. When you need a different
        # shutdown approach you can use one of the following variables:

        ## ssl-unclean-shutdown:
        # This forces an unclean shutdown when the connection is closed, i.e. no
        # SSL close notify alert is send or allowed to received.  This violates the
        # SSL/TLS standard but is needed for some brain-dead browsers. Use this when
        # you receive I/O errors because of the standard approach where mod_ssl
        # sends the close notify alert.

        ## ssl-accurate-shutdown:
        # This forces an accurate shutdown when the connection is closed, i.e. a
        # SSL close notify alert is send and mod_ssl waits for the close notify
        # alert of the client. This is 100% SSL/TLS standard compliant, but in
        # practice often causes hanging connections with brain-dead browsers. Use
        # this only for browsers where you know that their SSL implementation works
        # correctly.
        # Notice: Most problems of broken clients are also related to the HTTP
        # keep-alive facility, so you usually additionally want to disable
        # keep-alive for those clients, too. Use variable "nokeepalive" for this.
        # Similarly, one has to force some clients to use HTTP/1.0 to workaround
        # their broken HTTP/1.1 implementation. Use variables "downgrade-1.0" and
        # "force-response-1.0" for this.
        <IfModule setenvif_module>
                BrowserMatch ".*MSIE.*" \
                        nokeepalive ssl-unclean-shutdown \
                        downgrade-1.0 force-response-1.0
        </IfModule>

        ## Per-Server Logging:
        # The home of a custom SSL log file. Use this when you want a compact
        # non-error SSL logfile on a virtual host basis.
        <IfModule log_config_module>
                CustomLog /var/log/apache2/ssl_request_log \
                        "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
        </IfModule>
</VirtualHost>
</IfModule>
#</IfDefine>
</IfDefine>

# vim: ts=4 filetype=apache

Edit 3: Output of apache2 -S
[Thu Oct 25 11:02:02 2012] [warn] _default_ VirtualHost overlap on port 80, the first has precedence
[Thu Oct 25 11:02:02 2012] [warn] _default_ VirtualHost overlap on port 80, the first has precedence
[Thu Oct 25 11:02:02 2012] [warn] _default_ VirtualHost overlap on port 80, the first has precedence
[Thu Oct 25 11:02:02 2012] [warn] _default_ VirtualHost overlap on port 80, the first has precedence
[Thu Oct 25 11:02:02 2012] [warn] _default_ VirtualHost overlap on port 80, the first has precedence
[Thu Oct 25 11:02:02 2012] [warn] _default_ VirtualHost overlap on port 80, the first has precedence
[Thu Oct 25 11:02:02 2012] [warn] _default_ VirtualHost overlap on port 80, the first has precedence
[Thu Oct 25 11:02:02 2012] [warn] _default_ VirtualHost overlap on port 80, the first has precedence
[Thu Oct 25 11:02:02 2012] [warn] _default_ VirtualHost overlap on port 80, the first has precedence
[Thu Oct 25 11:02:02 2012] [warn] _default_ VirtualHost overlap on port 80, the first has precedence
VirtualHost configuration:
wildcard NameVirtualHosts and _default_ servers:
*:80                   domain1.edu (/etc/apache2/vhosts.d/10_domain1.edu.conf:38)
*:80                   domain2.edu (/etc/apache2/vhosts.d/10_domain2.edu.conf:38)
*:80                   domain3.edu (/etc/apache2/vhosts.d/10_domain3.edu.conf:38)
*:80                   domain4.edu (/etc/apache2/vhosts.d/10_domain4.edu.conf:38)
*:80                   domain5.edu (/etc/apache2/vhosts.d/10_domain5.edu.conf:38)
*:80                   domain6.edu (/etc/apache2/vhosts.d/10_domain6.edu.conf:38)
*:80                   domain7.edu (/etc/apache2/vhosts.d/10_domain7.edu.conf:38)
*:80                   domain8.edu (/etc/apache2/vhosts.d/10_domain8.edu.conf:38)
*:80                   domain9.edu (/etc/apache2/vhosts.d/10_domain9.edu.conf:38)
*:80                   domain10.edu (/etc/apache2/vhosts.d/10_domain10.edu.conf:38)
*:80                   domain11.edu (/etc/apache2/vhosts.d/10_domain11.edu.conf:38)
Syntax OK

I don't have any problem accessing any sites, just the SSL errors
Comment: There's a typo in the path to the chain file.  Is that in the config or just in your question?
Comment: How are you testing the web site? For example, if you are testing with IE on XP, SNI definitely won't work.
Comment: Sorry about the lethargic reply, guess the email alerts didn't work as expected.
@Ladadadada Unfortunately it is just a typo in my question.  Wouldn't that have been a funny turn of events.
Comment: @David Schwartz I'm testing on Windows 7 with IE 9, Chrome 184.108.40.2069.94, and Firefox 15.0.1.  All return the cert error
Comment: Include the contents of the relevant vhost file, and the output of `apachectl -S`.
Comment: The [SSL Checker](http://www.sslshopper.com/ssl-checker.html) might be a handy tool to try as well.
Comment: @adaptr apache2ctl -S does not work for me
Comment: @Ladadadada SSL Checker gives me "No SSL certificates were found on bfsa.jhu.edu. Make sure that the name resolves to the correct server and that the SSL port (default is 443) is open on your server's firewall." I verified just now that 443 is open.  Does this provide any more clues?
Comment: Thanks everyone for your help so far.  Also while pasting my config I noticed that the SSLCACertificatePath lines are commented out, is this an issue?
Comment: @adaptr /usr/sbin/apache2ctl -S wouldn't return anything for whatever reason but I figured out I can just run /usr/sbin/apache2 -S.  I have added the output to my original post
Answer: You do not have any SSL vhosts configured; verify that the ssl config file is in fact included in the main config.
You also need to define a NameVirtualHost *:80 outside of any vhosts, or all requests will go to the first one, as the output tells you.
Comment: In the vhosts.d folder everything has .conf at the end including the ssl configs and consequently should be included.  I added NameVirtualHost *:80 to httpd.conf and while there are no more warnings from /usr/sbin/apache2 -S it has not fixed the SSL problem


Segmentation Fault Core Dumped in C

Question: I am having trouble with segmentation fault (core dumped) in C. I am compiling using gcc, and I can't seem to fix it! Here is the code, which is supposed to look at a csv file and perform 1 of 4 opperations:
<code>#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, const char * argv[])
{
    int lines=0, i=0, a=0;
    char strings[128], *broken=" ", *array[100][4], *err=" ";

    FILE *file;
    file=fopen("inventory.csv", "a+");
    broken= malloc(1000);
    err=malloc(100);

    while(fgets(strings, sizeof strings, file)!=NULL){
        ++lines;
        a=0;
        broken=strtok(strings, ",");
        while(broken!=NULL){
            strcpy( array[i][a], broken);
            a++;
        }
        i++;
    }
    if(strcmp(argv[1], "list")==0){
        printf("Name, Quantity, Reorder limit, Cost");
        while(fgets(strings, sizeof strings, file)!=NULL){
            while(broken!=NULL){
                printf("%s, ", array[i][a]);
            }
            printf("\n");
        }
    }
    else if(strcmp(argv[1], "reorder")==0){
        int i=0;
        printf("We need to purchase more of the following items: \n");
        for(i=0;i<lines;i++){
            if(strtod(array[i][1], &err)<=strtod(array[i][2],&err)){
                printf("%s\n", array[i][0]);
            }
        }
    }
    else if(strcmp(argv[1], "deduct")==0){
        if(argv[2]){
            int i=0;
            char str[100];

            for(i=0;i<lines;i++){
                if(strcmp(argv[2], array[i][0])==0){
                    if(strtod(array[i][1],&err)-1>0){
                        sprintf(str,"%f",strtod(array[i][1],&err)-1);
                        array[i][1]=str;
                        printf("Success\n");
                        fseek(file, 0, 1);
                        sprintf(str,"%s,%s,%s,%s", array[i][0], array[i][1],
                            array[i][2], array[i][3]);
                        fwrite(str,1,sizeof(str),file);
                    }
                    else{
                        printf("There are none left!\n");
                    }
                }
            }
        }
        else{
            printf("Enter a food item");
        }
    }
    else if(strcmp(argv[1], "add")==0){
        fseek(file, 0, 2);
        char str[100];
        sprintf(str,"%s,%s,%s,%s\n",argv[2],argv[3],argv[4],argv[5]);
        fwrite(str,1,sizeof(str),file);

    }
    else{
        printf("Please enter an argument: list, reorder, deduct _name_, add _name_
            _qty_ _reorderlimit_ _price_\n");
    }

    fclose(file);
    return 0;
}
</code>
Comment: file=fopen("inventory.csv", "a+"); It is better you check the return value for fopen if null don't proceed further.
Comment: please, use proper indentation!
Comment: `strcpy( array[i][a], broken);` `array[i][a]` is necessary to point to the area reserved for storing strings.
Answer: There is no way to get out of the while loop.
I would write one more strtok in:
<code>broken=strtok(strings, ",");
            while(broken!=NULL){
               strcpy( array[i][a], broken);
               broken=strtok(NULL,",");
               a++;
            }
</code>
Comment: Still gives me a core dump :(

Segmentation Fault Core Dumped in C


Kubernetes: How can I get which pod schedule GPU?

Question: I have three Nvidia GPUs in my cluster, and so many pods are running in my cluster. How can I find which one of these pods schedule GPU and how many GPUs they schedule?
I use this link to enable the GPU schedule in my cluster for Nvidia GPU.
https://kubernetes.io/docs/tasks/manage-gpus/scheduling-gpus/
thanks
Answer: Here's the example given from a kubectl plugin, kubectl-view-allocations:
<code>> kubectl-view-allocations -r gpu

 Resource                   Requested       Limit  Allocatable  Free
  nvidia.com/gpu           (71%) 10.0  (71%) 10.0         14.0   4.0
  ├─ node-gpu1               (0%)  __    (0%)  __          2.0   2.0
  ├─ node-gpu2               (0%)  __    (0%)  __          2.0   2.0
  ├─ node-gpu3             (100%) 2.0  (100%) 2.0          2.0    __
  │  └─ fah-gpu-cpu-d29sc         2.0         2.0           __    __
  ├─ node-gpu4             (100%) 2.0  (100%) 2.0          2.0    __
  │  └─ fah-gpu-cpu-hkg59         2.0         2.0           __    __
  ├─ node-gpu5             (100%) 2.0  (100%) 2.0          2.0    __
  │  └─ fah-gpu-cpu-nw9fc         2.0         2.0           __    __
  ├─ node-gpu6             (100%) 2.0  (100%) 2.0          2.0    __
  │  └─ fah-gpu-cpu-gtwsf         2.0         2.0           __    __
  └─ node-gpu7             (100%) 2.0  (100%) 2.0          2.0    __
     └─ fah-gpu-cpu-x7zfb         2.0         2.0           __    __
</code>
Seems to offer what you are looking for.
Furthermore apparently, sharing GPUs is possible (with Nvidia-provided software) - might be useful to you or whoever finds this in the future:

https://blog.ml6.eu/a-guide-to-gpu-sharing-on-top-of-kubernetes-6097935ababf
https://github.com/AliyunContainerService/gpushare-scheduler-extender


Backbone model fetch is hitting cache instead of server (in phonegap)

Question: I'm calling fetch on a model. Phone gap is returning a cached response instead of issuing a new request. (or maybe it's android that's caching...)
Can I override backbone.sync in such a way as to bust the cache problem from phonegap/android?
Alternatively, can I clear the cache manually from javascript?
Comment: It's very weird behavior that should to prove and to solve, but as a work around you can pass a _timestamp parameter_ in your Model url.
Answer: I think you will want to look at the documented bugs in IOS6 with Ajax.
See: http://www.devthought.com/2012/09/22/understanding-the-ios6-ajax-bugs/


Como faço para posicionar duas divs em relação a uma terceira (fixed)?

Question: Quero que duas divs fiquem abaixo de uma terceira que tem position: fixed, o problema é que essas divs ficam atras da terceira, ja tentei mudar a position das duas divs para relative, absolute e static, mas não funciona.
HTML
<!DOCTYPE HTML>

<title>blogg</title>
<link type="text/css" rel="stylesheet" href="MeuCss.css">

Titulo/Logo

dd/mm/aaaa

CSS
div{
    border-radius: 5px;
}

#header{
    z-index: 1;
    font-family: Arial;
    width: 97.5%;
    height: 50px;
    background-color: #FFCC99;
    margin-top: -15px;
    position: fixed;
margin-bottom: 7px;
}

.data{
    float:right;
margin-right: 5px;
}

.left{
display:inline-block;
    width: 100px;
    height: 300px;
    background-color: #99CCFF;
    float: left;
    margin-bottom: 7px;
margin-right: 7px;
}

.right{
margin-left: 7px;
margin-bottom: 7px;
width: 300px;
height: 300px;
background-color: #00CC99;
float: left;
}

#footer{
    position: relative;
    clear: both;
    height: 50px;
    background-color: #0066FF;
    width: 98.5%;
    margin-bottom: 5px;

}

#nome{
    margin-left: 5px;
    color:#009999;
    float: left;
display: inline-block;
}

#email{
    margin-right: 5px;
    float: right;
    color:#009999;
}

.divLink{
    position: static;
    width: 50px;
    height: 50px;
}

.divLink a{
    display: block;
    background-image: url("http://goo.gl/xPi76J");
    background-size: 50px 50px;
background-repeat:no-repeat;
    width: 50px;
    height: 50px;
    border-radius:5px;
}

.divLink a:hover{
    display: block;
    border-radius: 5px;
    background-image: url("http://goo.gl/9t07bt");
    background-size: 50px 50px;
    width: 50px;
    height: 50px;
background-repeat:no-repeat;
}

Resultado:
Answer: Amigo, faça assim:

Adicione uma div em volta de tudo, pode chamar ela de .wrap
Nessa div, adiciona um margin-top ou padding-top do mesmo tamanho da div que está com position fixed.

Dessa forma, o conteúdo da página, começará sempre abaixo do .header ;)
Comment: Valeu, consegui resolver dessa forma.
Answer: Pode dar margin-top nas div que quer que fique pra baixo.
Exemplo:
http://jsfiddle.net/uU5Bn/
Comment: Não teria como eu colocar margin-top em relação à div header?
Dessa maneira realmente funciona, mas eu queria que as divs se posicionassem de maneira "correta"
Comment: Você esta usando position: fixed, não sei se existe outra forma de fazer isso.


Find All Classes with Selenium Python

Question: Hi I want to know how I can get element by class name where every class partially same like
class = "cursor earn_pages_button profile_view_img_xxxx" where xxxx is undefined
I just want to get all images from this class name profile_view_img_xxxx
some where it is profile_view_img_32487 or profile_view_img_86732 or profile_view_img_3278324
Comment: https://developer.mozilla.org/en-US/docs/Web/XPath/Functions/contains
Answer: You can use this:
<code>driver.find_elements_by_xpath("//*[contains(@class,"cursor earn_pages_button profile_view_img_")]").
</code>
It will match all classes with that text. Just try to iterate through it using a for-loop.
Comment: Should be `driver.find_elements...`
Comment: but you have `find_element` instead of `find_elements` which will not return all elements.

Find All Classes with Selenium Python


Como substituir um caractere do meio de uma string e trocar por dois caracteres?

Question: Por exemplo,
Char s1 [  ] = "azul";
 Char S2 [ ] = "z";
Char S3 [ ] = "PP";

Puts(s1); //azul

Código para substituir...
Resultado esperado:
Puts(s1); //aPPul

Obs.: Consegui fazer alterando 1 caractere por outro, mas 1 por 2 e ainda manter os caracteres subsequentes, não.
Comment: o que é o tipo `Chris`?
Comment: É tipo char, consertei na edição.
Answer: Não tem escapatória: você vai ter que alocar outro lugar para armazenar o seu resultado.  Fazendo isso você pode depois substituir a sua sequência de caracteres e ter espaço suficiente para guardar tudo:
char *
substituir(char * original, char busca, char * subst) {
    int i, num_inst;
    char * ptr, * ptr2, * resultado;

    /* conta o número de instâncias de busca em original */
    for (ptr = original, num_inst = 0; *ptr; ptr ++) {
        if (*ptr == busca) num_inst ++;
    }
    /* aloca memória suficiente para guardar o resultado */
    resultado = malloc(
        strlen(original)/* letras no original */
        + (strlen(subst) - 1) * num_inst /* número de caracteres extra para caberem as instâncias de subst */
        + 1 /* para o '\0' final */
    );
    if (resultado == NULL) return resultado; /* se não conseguiu alocar memória, retorne */
    for (ptr = original, ptr2 = resultado;
         * ptr; ) {
        if (*ptr == busca) {
            /* concatene a sequência de substituição e depois ache o fim da string */
            strcat(ptr2, subst);
            while (* ptr2) ptr2 ++;
            ptr ++; // tem que avançar o ponteiro de original, também
        } else {
            /* copie o byte */
            *ptr2 ++ = *ptr ++;
        }
    }
    * ptr2 = '\0';

    return resultado;
}

Note que o código acima aloca uma string nova, então se você for substituir a antiga e esta for alocada dinamicamente, lembre-se de chamar free() nela! Note também que original não foi tocada e permanece com o valor original.
Comment: `*ptr`, como você sabe, desreferencia o ponteiro, isto é, traz o valor guardado no endereço de memória apontado por `ptr`. Quando um valor vem sem um operador lógico como `==` ou `<`, é equivalente a testar se ele é diferente de zero. Como as _strings_ em C terminam sempre com o caracter zero (`'\0'`), isto é equivalente a parar quando chega ao final da _string_. É uma construção muito idiomática em C.
Comment: Wtmute, obrigado pela dica. Mas, tenho uma dúvida: qual a lógica no primeiro "for" para que a condição de parada seja "*ptr"?
Comment: Entendi e gostei muito da dica. A partir de agora vou tentar encontrar outras situação para utilizar.


A non-compact $ T_{2} $ space which is not a k - space

Question: A topological space is called k - space  provided it has the property that any subset $ S $ such that $ S \cap K $ is closed for all closed compact $ K $ is  itself closed.
A topological space is called $ KC$ - space  provided every compact sets are closed.
A topological space is called $ US $ - space  provided each convergent sequence has unique
limit.
$ T2⇒ KC ⇒ US ⇒ T1 $
Theorem: Let $ X $ be a $ KC $ space . Then $ X ^ { * } $ ( one point compatification of $ X $ ) is $ KC $ iff $ X $ is a k space.
To show that a $ US $ space is not $ KC$ space. let $ X $  be a non- compact $ T_{2} $ space  which is not a k- space, so according upper theorem $ X^{*} $ is compact $ US $ but not $ KC $ .for example:
A non-compact  $ T_{2} $ space which is not a k - space. Let $ X = N \cup \{ b\} $ , where $ b \in \beta\mathbb{N} - \mathbb{N} $ . If $ S $ is any infinite subset of $ \mathbb{N}$ , neither $ S $ nor $ S \cup \{ b \} $
 is closed in . Hence neither is compact. Thus $ X $ is pseudo - finite ,i.e. all its compact sets are finite. if $ X $ were a k - space , it would , being pseudo- finite, be discrete.

why is it right that :If $ S $ is any infinite subset of $ \mathbb{N}$ , neither $ S $ nor $ S \cup \{ b \} $
   is closed in . Hence neither is compact. Thus $ X $ is pseudo - finite ,i.e. all its compact sets are finite. if $ X $ were a k - space , it would , being pseudo- finite, be disceret." ?
Comment: Habib: It seems that you have already at least four different accounts on this site: [88416](http://math.stackexchange.com/users/88416/habib),
[88471](http://math.stackexchange.com/users/88471/habib),
[88563](http://math.stackexchange.com/users/88563/habib),
[88913](http://math.stackexchange.com/users/88913/habib). I guess registering would make your life much easier. And then you could merge your older accounts (or ask the moderators to do so, if you are unable to do it).
Comment: Did you want to write: " neither $ S $ nor $ S \cup \{ b \} $
 is closed in $\beta\mathbb N"? The current version of the post ends with: "closed in" and it does not say where.
Answer:
why is it right that :If $ S $ is any infinite subset of $ \mathbb{N}$ , neither $ S $ nor $ S \cup \{ b \} $
   is closed in . Hence neither is compact.

I suppose you meant to say closed in $\beta\mathbb{N}$.
The closure of $S$ in $\beta\mathbb{N}$ consists of all ultrafilters1 containing $S$. If $S$ is infinite, there are at least two such ultrafilters; to see this you can, for example, divide $S$ into two disjoint infinite subsets $S=A\cup B$ and take one free ultrafilter containing $A$ and $S$ and another one containing $B$ and $S$.
You can make basically the same argument using Engelking, Corollary 3.6.2: Every pair of completely separated subsets of a Tychonoff space $X$ has
disjoint closures in $\beta X$.
Two subsets $A$ and $B$ of a topological space $X$ are called completely
separated if there exists a continuous function
$f \colon X\to I$ such that $f(A)=0$ and $f(B)=1$. We say that $f$ separates sets $A$ and $B$.
Clearly, any two disjoint subsets of a discrete space are completely separated.
(Basically all you need for this argument to work is to show that closure of $S$ in $\beta\mathbb N$ contains at least two points from $\beta\mathbb N\setminus\mathbb N$.)

Thus $ X $ is pseudo - finite ,i.e. all its compact sets are finite. if $ X $ were a k - space , it would , being pseudo- finite, be disceret." ?

If we work with a $T_1$-space, all finite subsets are closed. Now we have that for any compact subset $K$ any any subset $V$ the set $V\cap K$ is finite, and thus closed. This shows that every subset $V\subseteq X$ is closed.

1 I am using a construction of $\beta\mathbb N$ using ultrafilters.
The construction of $\beta\mathbb N$ using ultrafilters is briefly described on Wikipedia.
You can find it also in many internet resources and books.
For example, it is described here:

Chapter I.3 in Hindman N., Strauss D. Algebra in the Stone-Čech compactification
Chapter II.14 in Todorcevic S. Topics in topology (Lecture Notes in Mathematics 1652).
Comment: what do you mean about:The closure of S in βN consists of all ultrafilters containing S. why you use ultrafiles?
Comment: @habib Are you familiar with the construction of $\beta\mathbb N$ as a topological space on the set of all ultrafilters on $\mathbb N$?
Comment: Although I study a lot about βN , I am not very good at notion of  the construction of  βN and βN - N as a topological space, and ultrafilter on them!   please help me.Thanks.
Comment: @habib I tried my best. But you still [haven't clarified](http://math.stackexchange.com/questions/459300/a-non-compact-t-2-space-which-is-not-a-k-space/459304?noredirect=1#comment988652_459300) your post. BTW if you register, you will be able to [talk in chat](http://math.stackexchange.com/help/privileges/chat) as soon as you get 20 rep points. (Maybe some users would be able to help you in chat.) I guess that you have earned at least 20 points, if you add reputation from your different accdounts.


How to display a comma-separated list of multiple field values?

Question: How can I render for example each taxonomy terms value as an inline comma-separated list (or add between each of them a "/" Character) in my field template field--node--field-tags.html.twig file or even visually with css?
Answer: While it's possible to use CSS for this I think it's better to avoid it. I've simplified the field twig file to illustrate, but it would look something like this:
{% for item in items %}
  {% if loop.last %}
    {% set separator = '' %}
  {% else %}
    {% set separator = '/' %}
  {% endif %}
  {{ item.content }}{{ separator }}
{% endfor %}

Comment: This works perfectly and should be the accepted answer, since the question was for a comma-separated list. The CSS proposal just looks like one but, as you can see when you copy and paste the rendered result, it is far from being it.
Answer: You can use CSS to accomplish this.
For example:
HTML

  Apple

  Orange

  Lemon

CSS
.field-item {
  float: left;

}

.field-item:after {
  content: ","; right: 3px; position: relative;
}

.field-item:last-child:after {
    content: none;
}

.field-item:last-child:before {
    content: " and ";
}

.field-item:first-child:before {
    content: none;
}

EXAMPLE DEMO
Answer: The https://drupal.stackexchange.com/a/238069/5501 should work.
However if you need to remove all markup from the output and ensure no whitespaces/new lines exists in it then it become tricky:
items|safe_join(', ')|preg_replace('/[\n\r]/', '')|replace({'  ': ''})|striptags|trim)

Let's break down the above:

safe_join filter iterates the list and trigger render/toString method to get item output, then joins all items by comma + whitespace
preg_replace filter used to remove all new lines
replace filter used to remove double whitespaces that were left from item's markup
striptags filter removes all tags in output
trim filter removes spaces from the start/end of the string

Note: preg_replace is used from Twig Tweaks module
Answer: I combined Classy's field.html.twig with Rene's suggestion, in the file field--node--field-tags.html.twig:
{%
    set classes = [
    'field',
    'field--name-' ~ field_name|clean_class,
    'field--type-' ~ field_type|clean_class,
    'field--label-' ~ label_display,
]
%}
{%
    set title_classes = [
    'field__label',
    label_display == 'visually_hidden' ? 'visually-hidden',
]
%}
{% if label_hidden %}
    {% if multiple %}

            {% for item in items %}
                {% if loop.last %}
                    {% set separator = '' %}
                {% else %}
                    {% set separator = ', ' %}
                {% endif %}
                {{ item.content }}{{ separator }}
            {% endfor %}

    {% else %}
        {% for item in items %}
            {% if loop.last %}
                {% set separator = '' %}
            {% else %}
                {% set separator = ', ' %}
            {% endif %}            {{ item.content }}{{ separator }}
        {% endfor %}
    {% endif %}
{% else %}

{{ label }}

        {% if multiple %}

        {% endif %}
        {% for item in items %}
            {% if loop.last %}
                {% set separator = '' %}
            {% else %}
                {% set separator = ', ' %}
            {% endif %}
            {{ item.content }}{{ separator }}
        {% endfor %}
        {% if multiple %}

        {% endif %}

{% endif %}

Answer: You don't even need to do this on a theme level, you could use a display suite block field embedding a view of comma separated terms, if you wanted.


mysql server upgrade problem from 5.0 to 5.1

Question: Hi I have upgraded my mysql server from 5.0 to 5.1.
But i am having a problem related to tables for InnoDB storage Engine.
My default engine is InnoDB, So it is enabled in my server.
But tables with InneDB engine are not displaying in phpmyadmin.
Tables with MyISAM are displaying properly.
and also i can't fire a query on the table with InnoDB Engine.
Thanks
Avinash
Answer: Have you read through, considered, and followed http://dev.mysql.com/doc/refman/5.1/en/upgrade.html in absolute detail?
Are you sure the InnoDB engine is enabled in your my.cnf?
What do your logs say?
Answer: check your /etc/mysql/my.cnf for a line like:
skip-innodb

or try:
show variables like 'have_innodb';

I would imagine innodb was disabled during your upgrade.
Answer: The definitive command to check for what storage engines you have available is SHOW ENGINES. It does sound like InnoDB is disabled for you though.


how to load sapbex.xla when the workbook opens

Question: I open a query from SAP BW... I make all the changes I need and I even check the box that says Refresh query every time you open the workbook. The problem is that when I reopen the workbook it's just like a regular Excel, because the SAPBEX.xla file is not loaded anymore.
Any ideas on how can I solve this?
I want the workbook updated with the latest data every time I open the workbook.
Thanks!
Comment: I am not familiar to SAP BW. Do you automatically query with Excel connections? What is SAPBEX.vba?
Comment: sorry, I made a mistake... it's sapbex.xla ... an ad-in for connecting and refreshing the queries
Comment: so the connection to SAP BW is operated by this add-in? Is it public? Apart from the fact that the add-in shouldn't get unloaded, I don't think I can help you here.
Comment: I solved the problem in the end... I had to set it up from Excel but now the add-in loads no matter what excel file I open... is there a way to make it load only when I open a specified file?
Answer: You can use an application event (see Chip Pearson's website).
Put this code in the This Workbook module of your PERSONAL.XLSM (see here).
Private WithEvents App As Application

Private Sub Workbook_Open()
    Set App = Application
End Sub

And in a module:
Private Sub App_WorkbookOpen(ByVal Wb As Workbook)
    MsgBox "New Workbook: " & Wb.Name
    'or better check here if this is your workbook and activate the addin
End Sub


RSA to encrypt 500 bytes of data using openssl library

Question: I am using RSA algorithm for shared key encryption/decryption.I am using open ssl libraries and c language.RSA_size() returns 256bytes.the key(data to enrypt) size is more than 256bytes but less than 500 bytes.The RSA keysize used for encryption is 1024.keypair is generated using openssl library.
If data to encrypt is less than or equals to 245 bytes the encryption works fine(because of padding).Otherwise i have to break the data(not sure it is ok as iam trying to exchange shared key)Is there any other way to increase RSA_size.my code doesn't call RAND_seed()(not sure what argment to pass) before calling rsa_public_encrypt.  Any help is appreciated.
Comment: Why would you need a key with greater than 256 bytes = 2048 bits?
Answer: You can either break your data into chunks, or use the "seal"/"open" OpenSSL functions.
Essentially what they do is generate a random set of keys, encrypt the keys using the public key and then use those keys to encrypt whatever you want. That way you're not limited to specific sizes and decryption is not too slow (you only decrypt the random keys using RSA, the rest is done using symmetric encryption so it's a lot faster).
I suggest you have a look at EVP_SealInit and EVP_OpenInit.


How can I connect pedals and amplifiers without accidentally damaging them?

Question: I've understood that there are some risks with connecting pedals, amplifiers, instruments and microphones and that I should be aware of what I'm doing, or it could damage my equipment. How can I figure out if connecting something (e.g. a bass guitar to a guitar amplifier, or a microphone to an effects pedal to a guitar amplifier) is risky or not?
Is this related to signal strength? Equipment impedance? I wish I could play around more with my setup, but I'm worried about damaging it.
Answer: With decent modern equipment, it's really hard to cause any real damage by incorrect connection. Tales like "bass into guitar amp will damage it" are pretty much this: tales.
Guitar and bass amps are anyways designed to be operated outside what would be considered the "safe range" for e.g. a HiFi amplifier. Overdrive is nothing else but overloading an amp, i.e. giving it more signal level than it can really handle. Because this is so commonly done, amp designers make sure that they will handle that gracefully, i.e. simply clip the signal. Decent amps therefore survive pretty much any signal you can possibly give them from an ordinary pedal or instrument.
The only thing that you should be careful with are speaker outputs. These offer much higher voltage and lower impedance than line-level outputs, therefore they can quite possibly fry something you connect. Furthermore, tube amps can even fry themselves when not connected to a suitable load, i.e. a speaker. But, there's probably not really anything interesting you'd want to try with a speaker output anyways – these are for speakers only, which I suppose is obvious!
tl;dr don't be afraid, just try out what you want to do. Usually the worst that can happen is a loud crack when connecting, or uncontrollable feedback, so just be prepared to quickly mute the power amp whilst experimenting.
Note that the tales do have some basis in reality: old equipment not always so robust. So if you have some kind of vintage boutique amp, better sell it and get a modern amp that won't have these problems (and probably will sound better anyways).
Comment: Thank you, I'm happy to hear that! Would you consider my Studio Pro 112 amplifier vintage or modern?
Comment: That seems to be a hybrid tube/solid state amp. These should be very robust.


Conexão SQL com PHP

Question: Tenho o seguinte PHP, estou utilizando o WAMP, e como na imagem abaixo, as dll's estão ativas:

<?php
$server = "dblinx";
$connection = array("Database"=>"Linx", "UID"=>"root","PWD"=>"root");
$conn = sqlsrv_connect($server, $connection);

if ($conn) {
  echo "Connected!";
} else {
  echo "Connection failed
";
  die( print_r(sqlsrv_errors(),true));
}
?>

Porém, sempre aparece isso quando tento abrir a página:

Alguém consegue me ajudar?
Ja adicionei os extensions no PHP.ini
Comment: Está tentando conectar ao SQL Server?
Comment: Provavelmente está faltando você incluir as extensões em seu php.ini que fica no mesmo caminho das dlls. Vou inserir na resposta para verificar se resolve.
Comment: Os drivers `pdo` só seriam necessários se estivesse usando PDO. Um possível problema, é estar usando 32bits e não 64bits (o xampp ou sql server?, até eu fiquei na dúvida agora), assim dá-se o erro.
Answer: De acordo com o site da Microsoft é necessário a inclusão no php.ini conforme abaixo.
extension=php_sqlsrv_72_ts.dll
Referência:
https://docs.microsoft.com/pt-br/sql/connect/php/loading-the-php-sql-driver?view=sql-server-2017
Comment: Ja adiconei nos extensions, mesmo assim ele continua aparecendo esse erro
Comment: Após adicionar a extensão é necessário reiniciar o seu servidor de aplicação. Pode compartilhar o que acrescentou em seu php.ini editando sua pergunta
Comment: Adicionei na pergunta, e sim, ja reiniciei o servidor, algumas vezes já hahah
Comment: Verifica se seu wamp está com o php7 selecionado. E verifica o que o RBZ comentou também.

Conexão SQL com PHP


Nginx configuration in OpenShift

Question: I have been struggling with a solution to have nginx running, in OpenShift there is no use of root user during creation of the containers. Then, I was getting the following error:
2023/06/21 10:37:45 [emerg] 1#1: mkdir() "/var/cache/nginx/client_temp" failed (13: Permission denied)
nginx: [emerg] mkdir() "/var/cache/nginx/client_temp" failed (13: Permission denied)

This is happening because the user is not root. The Dockerfile used for the configuration is the following:
# base image
FROM node:14.21.2 as build-deps

#more lines

RUN yarn build

FROM nginx:1.19-alpine
COPY --from=build-deps /usr/src/app/build /usr/share/nginx/html
COPY --from=build-deps /usr/src/app/nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80

RUN printenv
RUN ln -s /tmp/env.js /usr/share/nginx/html/static/env.js
CMD ["sh", "-c", "envsubst < /usr/share/nginx/html/static/env.template.js > /tmp/env.js && exec nginx -g 'daemon off;'"]

Then, I changed the nginx image to use nginxinc/nginx-unprivileged:1.23.2 to avoid the issue when creating the directory /var/cache/nginx/client_temp. I modified the Dockerfile shown above to remove the symbolic link and modified the last line to refer to the original path:
CMD ["sh", "-c", "envsubst < /usr/share/nginx/html/static/env.template.js > /usr/share/nginx/html/static/env.js && exec nginx -g 'daemon off;'"]

However, because this image (Debian OS) is using nginx as user, I am having issues to create the file env.js:
sh: 1: cannot create /usr/share/nginx/html/static/env.js: Permission denied

If I want to proceed with the creation of symbolic link as the first dockerfile example, then I get the following error:
ln: failed to create symbolic link '/usr/share/nginx/html/static/env.js': Permission denied

This image is using nginx belonging to the group nginx:
$ howami
/bin/sh: 1: howami: not found
$ id nginx
uid=101(nginx) gid=101(nginx) groups=101(nginx)

attempting to create a symbolic link to env.js file in static folder is failing because nginx is not part of the root group:
$ cd /usr/share/nginx/html/
$ ls -ltr
drwxr-xr-x 5 root root 4096 Jun 20 22:58 static

I cannot change permissions of the directory because this is happening before having the container up.
How could I have the environment variables under /usr/share/nginx/html/static folder in the same way I was trying to do with envsubst and have env.js with the values?
Thanks a lot
Comment: What version of OpenShift are you using? How are you deploying things in OpenShift? Please show us your deployment manifests.
Answer:
I have been struggling with a solution to have nginx running, in OpenShift there is no use of root user during creation of the containers.

That's not correct; while OpenShift won't permit you to run containers as root by default, you can certainly configure the necessary permissions. If you're working with OpenShift 4, then the documentation of interest is the section on "Managing security context constraints".
I put together an example demonstrating this for a colleague just yesterday; you can find it here.

In your Dockerfile, this command is failing:
RUN ln -s /tmp/env.js /usr/share/nginx/html/static/env.js

That's because:

/usr/share/nginx/html is owned by root
You're currently running as the nginx user

You can fix that by explicitly switching to the root user in your Dockerfile:
USER root
RUN ln -s /tmp/env.js /usr/share/nginx/html/static/env.js
USER nginx

Nginx configuration in OpenShift


Solutions for problem 1-1 of Introduction to Algorithms, Third Edition, by CLRS

Question: I'm working problem 1-1 of the textbook Introduction to Algorithms, Third Edition, by CLRS, and need to solve $n\log(n) = 10^6$, where the logarithm is base $2$. My first thought was to use the logarithm laws to get $n \log(n) = \log(n^n) = 10^6 \Rightarrow n^n = 2^{10^6}$, which, as I understand it, is algebraically correct, but doesn't solve for $n$.
This Github page claims that the solution is $6.24 \times 10^4$, but the answers to this Quora question claim that the solution is $8.78 \times 10^4$ (found using numerical methods).
I have reason to doubt the correctness of the Github page, because it also claims that for $\sqrt{n}$ and a time of $1$ hour, we have $1.3 \times 10^{19}$, which I believe is incorrect, since we have $3.6 \times 10^{15}$ for $\sqrt{n}$ and a time of $1$ minute, which, unless I've made an oversight, means that we have $\sqrt{n} = 3.6 \times 60 \times 10^{15} = 2.16 \times 10^{17} \Rightarrow n = 2.16^2 \times 10^{19}$ for $\sqrt{n}$ and a time of $1$ hour.
Is it the Github page that is making errors? Or are the Quora answers incorrect? Or am I also making an error? Or is it some combination?
I would appreciate it if people would please take the time to review this.
Answer: You should go the other way, apply the logarithm to the original equation to get
$$
\log_2n+\log_2\log_2n=\log_2(10^6)\approx 20
$$
The logarithm of numbers around 20 is between 4 and 5, so that $\log_2n\approx 16\iff n=64\cdot 1024$ appears reasonable. The result of $2^{16}\cdot 16=2^{20}=(1024)^2$ is slightly larger than the target value, further refinements need a numerical algorithm or the Lambert-W function.
As a first correction, notice that the function value is about $5\%$ too large. Reduce $n$ by the same percentage ($1024$ to $1000$ are $2.5\%$, the remaining $2.5\%$ give $64-1.6$) to get $n=62.4\cdot 10^3$ as second guess.
The exact solution is $62746.126...$, in the spirit of the task you have to round down for the correct answer.
Comment: Ahh, yes: $\log_2(n \log_2(n)) = \log_2(n) + \log_2(\log_2(n))$.
Answer: The Quora answer is correct but it is using natural logs not logs to the base 2.
I think you must be misunderstanding the Github page. For example, consider the $\sqrt{n}$ function.
$1$ hour is $3600 \times 10^6$ microseconds. Let $\sqrt{n}=3600 \times 10^6$ and you obtain $n=3600^2\times 10^{12}=1.296\times 10^{19}$ as (approximately) stated. Similarly the log to the base 2 answer is (approximately) correct although $6.27\times 10^4$ is more accurate.
Comment: Ahh, you're correct. The calculation $\sqrt{n} = 3.6 \times 60 \times 10^{15} = 2.16 \times 10^{17} \Rightarrow n = 2.16^2 \times 10^{19}$ is going about it incorrectly.
Answer: As noted in Lutz's answer, we have
$$\log_2(n)+\log_2(\log_2(n))=6\log_2(10)\simeq6\cdot\frac{10}3=20$$
Let $x=\log_2(n)$ to reduce the size of what we're working with to get
$$x+\log_2(x)=6\log_2(10)\simeq20$$
It is easy to observe that $16+\log_2(16)=20$. By applying fixed-point iteration for
$$x=6\log_2(10)-\log_2(x)$$
we get in only 4 steps the result of
$$x\simeq\color{#2288FF}{15.9372}42985748778$$
$$n\simeq\color{#2288FF}{62746}.309434432704$$
Comment: You simply substitute the previous approximate answer into $6\log_2(10)-\log_2(x)$. So on the first step you'd get $6\log_2(10)-\log_2(20)$ for example.
Comment: Thanks for posting an answer. I'll have to familiarise myself with https://en.wikipedia.org/wiki/Fixed-point_iteration
Comment: Ahh, yes, it seems to be a surprisingly simple (but effective) numerical method. Quite interesting.


Recover data in a string with fixed positions

Question: I have a file that contains data at fixed positions (no separator).
for exemple:
$string = '0412345678Mr foo    25.2';

with
code  = '04'       (integer with 2 characters)
ref   = '12345678' (string  with 8 characters)
name  = 'Mr foo  ' (string  with 8 characters)
price = '  25.2'   (double  with 6 characters)

I can do that:
$code  = (int) substr($string, 0, 2);
$ref   = substr($string, 2, 8);
$name  = substr($string, 10, 8);
$price = (double) substr($string, 18, 6);

It's work fine.
I would like to know if there is an another to do this.
I try that:
list($code, $ref, $name, $price) = sscanf($string, "%2d%8s%8s%6s");

But that don't work.
If I replace spaces with another character like _, that's work but I don't want change data.
Another Idea? Regular expression?
Comment: _Rule 10:_ If it aint broke, dont fix it!
Comment: You could do that by  using regular expression as you mention.
`([0-9]{2})([0-9]{8})([a-zA-Z ]{8})([0-9. ]{6})` https://regex101.com/r/2bS8af/1
Comment: @kaldoran: I try that, but I don't know how to put result in variables
Answer: As you mentioned it, you could use regexp.
Here is an example of a simple one that would work :
([0-9]{2})([0-9]{8})([a-zA-Z ]{8})([0-9. ]{6})

https://regex101.com/r/2bS8af/1
With the addition of http://php.net/manual/fr/function.preg-match.php, that could do the trick.
Then if you want them inside your variable simple assign them by taking the output of preg_match :)
<?php
$string = '0412345678Mr foo    25.2';

$pattern = '/([0-9]{2})([0-9]{8})([a-zA-Z ]{8})([0-9. ]{6})/';
preg_match($pattern, $string, $matches);
print_r($matches);

By the way, you can replace [0-9] by "\d" etc ...
Which could give :
(\d{2})(\d{8})([\w\s]{8})([\d\s.]{6})

https://regex101.com/r/2bS8af/3
Comment: Thank you, I had test `preg_split` but not `preg_match`
Comment: No problem :) I've added a simpler version by using \d, \w etc :)
Comment: THks very much :)


VB.NET Equivalent of this code

Question: What would be the VB.NET equivalent of this code..
public virtual ICollection<Comment> Comments { get; set; }

Comment: possible duplicate of http://stackoverflow.com/questions/460027/vb-net-equivilant-of-c-property-shorthand
Comment: @Phill: Not a duplicate. That answer has no `virtual` keyword.
Answer: VB.NET (in version 10) has automatic properties just like C#.  The equivalent syntax is as follows:
Public Overridable Property Comments() As ICollection(Of Comment)

The automatic converters tend to produce syntax that is more verbose than necessary. You can expand it if you want, but it's not strictly necessary unless you're using an older version of the compiler:
Private m_Comments As ICollection(Of Comment)

Public Overridable Property Comments() As ICollection(Of Comment)
    Get
        Return m_Comments
    End Get
    Set(ByVal value As ICollection(Of Comment))
        m_Comments = value
    End Set
End Property

Answer: Public Overridable Property Comments() As ICollection(Of Comment)

Answer:  Public Overridable Property Comments() As ICollection(Of Comment)
     Get
    Return m_Comments
    End Get
     Set
    m_Comments = Value
    End Set
 End Property
 Private Overridable m_Comments As ICollection(Of Comment)

VB.NET Equivalent of this code


Linear combination of cosines: so close to perodic.

Question: I'm interested in linear combinations of cosines:
$$f(x) = \alpha_1 \cos(2\pi \theta_1 x) + \alpha_2 \cos(2\pi \theta_2 x) +
\cdots + \alpha_k \cos(2\pi \theta_k x)\enspace,$$
where $\alpha_i \in \mathbb{Z}$ and the $\theta_i$'s are linearly dependent
irrational numbers (when they are rational numbers or irrational linearly
independent, I have less trouble, as in the former case the function is
periodic, and in the second, any value of each $\cos$ can be attained
independently of the others).
When plotting functions like this, one sees that they are not periodic, but
still, they are close to be.  In particular, it seems that there are values
$p$ and $\epsilon$ such that if $f(x) > \epsilon$, then $f(x+n\times p) >
\epsilon$, at least for the first few $n$'s.  I have two questions:

Is this true?
Is there a name for the pseudo-periodicity that $f$ seems to enjoy?

Thanks!
Comment: They are [almost-periodic functions](http://en.wikipedia.org/wiki/Almost_periodic_function).
Answer: You could be interested in almost periodic functions.

A function $f\colon \Bbb R\to \Bbb C$ is said almost periodic if for all $\varepsilon>0$, the set
  $$P(f,\varepsilon)=\{T\in\Bbb R\mid\forall x\in \Bbb R, |f(x+T)-f(x)|\leq \varepsilon\}$$
  is relatively dense, that is, we can find $L>0$ such that each interval of length $L$ has a non-empty intersection with $P(f,\varepsilon)$.

It can be shown that if $f\colon\Bbb R\to\Bbb C$, the following properties are equivalent:

$f$ is almost periodic;
for all $\varepsilon>0$, we can find an integer $N$, real numbers $\theta_1,\dots,\theta_N$ and complex numbers $a_1,\dots,a_N$ such that
$$\forall x\in\Bbb R,\quad \left|f(x)-\sum_{j=1}^Na_je^{i\theta_j x}\right|\leq \varepsilon.$$
The family $\{\tau_t f,t\in\Bbb R\}$ has a compact closure for the uniform norm on the continuous bounded functions over $\Bbb R$, where $\tau_tf(x)=f(x+t)$.

This concept has been introduced by Harald Bohr. A good reference is Corduneanu's book Almost periodic functions.


Enable scope permission

Question: I am trying to create a signed URL following this documentation but I fail to understand how to enable the scope for my Cloud Function.
I am sure that my Cloud Function has cloudfunctions.serviceAgent which includes signBlob. But then the doc says it needs either https://www.googleapis.com/auth/iam or https://www.googleapis.com/auth/cloud-platform scope which I have no clue how to enable them.
Answer: Found it after randomly trying few things.

From Console, go to IAM page.
Click the pencil icon on firstname.lastname@example.com service account. I choose that because the error in GCF Logs Viewer says:

Permission iam.serviceAccounts.signBlob is required to perform this
  operation on service account
  firstname.lastname@example.com

Add role Cloud Functions Service Agent and done.

The same role, Cloud Functions Service Agent, should be assigned to firstname.lastname@example.com as well to make sure your function can be created and updated. See Access Control.

Enable scope permission


JMap dump format specification

Question: Are there any open specifications for jmap heap dump format?
Thanks for help!
Comment: do you need to read the binary data ?
Comment: @Santosh, I need to build a histogram of Class instances amount form heap dump. So, yes, I need to read binary data.
Answer: If you need an histogram of the heap, you can use jmap -histo <pid> to get the histogram from your live JVM. If you already have the heap dump file, with Eclipse MAT (Eclipse Memory Analyzer Tool) you can load the dump and easily get the histogram you are looking for.
Maybe Lars Vogel tiny tutorial on it can be an easy first step.
Regarding the hprof binary format, I bookmarked this some time ago: http://java.net/downloads/heap-snapshot/hprof-binary-format.html, but developing your own parser to get an histogram is totaly overkill.
Comment: Yes, I know this. Thanks for the answer. As I specified above, I need heap dump to be parsed by my program (module). To do that I need some docs. I googled for them, but didn't find any useful information.
Answer: Other simpler solution for histogram is to use jhat without being worried about the format. you can drill down and do various things.

JMap dump format specification


HAProxy configuration for RabbitMQ

Question: I have an API that sends messages to RabbitMQ.
I have a high availability RabbitMQ cluster behind HAProxy.
When I load test my API I start seeing lots of this:
Recovering from a network failure...
Exception in the reader loop: AMQ::Protocol::EmptyResponseError: Empty response received from the server.

In my unicorn log.
If I connect directly to RabbitMQ as a posed to via haproxy I do not. Where am I going wrong, my haproxy config looks like this:
global
  log 127.0.0.1   local0
  log 127.0.0.1   local1 notice
  #log loghost    local0 info
  maxconn 4096
  #debug
  #quiet
  user haproxy
  group haproxy

defaults
  log     global
  mode    http
  retries 3
  timeout client 50s
  timeout connect 10s
  timeout server 50s
  option dontlognull
  option forwardfor
  option httplog
  option redispatch
  balance  roundrobin

# Set up application listeners here.

listen http_frontend
  bind *:80
  mode http
  default_backend http_backend
  option httpclose
  reqadd X-Forwarded-Proto:\ http

listen https_frontend
  bind *:443 ssl crt /etc/haproxy.pem
  mode http
  default_backend http_backend
  reqadd X-Forwarded-Proto:\ https

listen http_bucky_frontend
  bind *:1880
  mode http
  default_backend http_bucky_backend
  option httpclose
  reqadd X-Forwarded-Proto:\ http

listen https_bucky_frontend
  bind *:1443 ssl crt /etc/haproxy.pem
  mode http
  default_backend http_bucky_backend
  reqadd X-Forwarded-Proto:\ https

listen rabbitmq_frontend
  bind *:5672
  mode tcp
  default_backend rabbitmq_backend
  option tcplog

listen admin
  bind 127.0.0.1:22002
  mode http
  stats uri /

backend http_backend
  mode http
  server 0-http_backend x.x.x.x:9000 maxconn 100 check
  server 1-http_backend x.x.x.x:9000 maxconn 100 check

backend http_bucky_backend
  mode http
  option httpchk GET /status
  http-check expect string up
  server 0-http_bucky_backend x.x.x.x:9000 maxconn 100 check
  server 1-http_bucky_backend x.x.x.x:9000 maxconn 100 check

backend rabbitmq_backend
  balance roundrobin
  mode tcp
  server 0-rabbitmq_backend x.x.x.x:5672 maxconn 4000 check
  server 1-rabbitmq_backend x.x.x.x:5672 maxconn 4000 check

When under load the load balancer is normally 20-30% cpu
Comment: I have now determined that the reason for the errors is a timeout as it is happening 50s after the restart HAProxy, which is how long my timeouts are. The question of how to fix remains?
Answer: Nerijus is right, this issue is caused by the HAProxy having a client timeout, which means, if the connection is considered idle for more than X ms then the connection is dropped.
TCP can send keep-alive packets to ensure an idle connection should stay open.
You can check your TCP parameter for keep-alive packets using the following command:
$ cat /proc/sys/net/ipv4/tcp_keepalive_time

By default, this configuration is equal to 7200 seconds, which means TCP will begin to send keep-alive packets only after a connection is idle for more than 2 hours.
So, just update your HAProxy client timeout value to something > 2 hours, e.g:
timeout client 3h

And add the clitcpka option to your backend:
backend rabbitmq_backend
  balance roundrobin
  mode tcp
  option          clitcpka
  server 0-rabbitmq_backend x.x.x.x:5672 maxconn 4000 check
  server 1-rabbitmq_backend x.x.x.x:5672 maxconn 4000 check

Comment: clitcpka  is not valid in a backend. It's a frontend config option
Answer: Remvoe timeout client 50s from default section and move to all others except from rabbitmq_frontend. Client timeout means that it closes TCP session between rabbitmq client and haproxy so reading from this socket gets "".

HAProxy configuration for RabbitMQ


Create a Views Block to show all Node 'Attached Files' as a File list.

Question: In creating the CMS structure, I've been trying to do this today, but seem to be getting no where.
I simply want to show all the files as link (PDF, Doc, Docx etc) that have been uploaded by a user to a node type listing which has a Field already created in the Content type structure (by me, the Admin/web) using Views. I've got as far as creating the View with the relevant fields and set it in the Panel Page as a block, but in testing nothing seems to show.
All I require is any relevant 'attached' files related to that Node Content (ie XYZ rock Band, attached mp3 files at bottom of page) so that future readers can click to download to local.
Can someone refresh my memory as how to do it so I can compare where I may be going wrong? I have set the author ID in Relationship, but still the files I have set do not show. Maybe I'm missing something here.
Comment: Let me see if I get this: You have a content type A, with a file field. now when you visit a node B, below it you want to display the list of files attached by B's author to all other nodes of type A (as a download link)?
Comment: No not at all; all posts of the designed Content Type have a Field content in it using the 'Field' Type with 'Media Selector' and the file types such as PDF, are stored on the server. The maximum files that can be attached to the Field is five. The user (with permission) can post articles and attached relevant files to their posting. Visitors can view these files and download them as they wish. Very much like when you see a 'Job posting' with attached documents as PDFs below the job posting. I wish to show these as links so people can download them to open. I'm to use a View in  the Panel page
Comment: you can give a try to [download_file](https://drupal.org/project/download_file) module as well.
Comment: Thanks @arpitr I'll checkout download_file although I've already committed to the Node content structure and it may get in the way; but I'll read the docs on https://drupal.org/project/download_file.
Answer: Based on the discussion above, create a new view, and configure and filter it however you need. the main part is to have the file display as link for download. For this, when you add the relevant field to views, in the settings form, there will be a drop down option for "Link this field to". Choose "File" from there and the field value will be linked to it. Clicking on it will allow the user to download the file. Hope this helps.
Comment: Thank you @Neo that helps. That is sort of what I have been doing, but I cannot remember seeing the 'Link to' element s above. I'll see how I correct it and post my results here for future readers. Thanks again.
Comment: You are welcome. If this answers your doubt, be sure to mark this as correct answer, so the people looking at this question later will find some help too. Thanks.


Feeling like a hair stuck in my throat - could it be a "singing injury"?

Question: I've felt for a few days a bit like I've got a hair stuck in the back of my throat - but I figure after that length of time it can't actually be a hair.
Is this something singers would recognise as a sign of straining/damaging their vocal chords, i.e. is it a classic symptom singing teachers would be familiar with?
It doesn't hurt and it doesn't seem to affect my singing.
Comment: I'm voting to close this question as off-topic because this is a medical question that should be answered by a doctor.
Comment: No, it's a question to singers. If your answer is "as a singer, you should get this looked at" then that's fine, that's a perfectly acceptable answer.
Comment: Well true, but checking if it's a common thing makes sense. Just like a brand-new guitarist might worry "why do my fingers hurt"!
Comment: It's something doctors would be more familiar with, too. They'll give you a good answer, and probably a cure and preventative as well.
Comment: "as a singer, you should get this looked at"

Bahaha.

I've had something similar but it could be a number of things from onset of a throat infection to somethign actually stuck in your throat. Eg I had an ear infection for ages which affected my throat and made it feel like something was stuck.
Comment: Go see your doctor. Now.
Answer: I don't recognize that specifically as a vocal injury, though it very well could be, so I'll give you the usual advice.
Give it three or four days, drink plenty of hot tea (especially with honey, ginger, and/or lemon if you can manage it), plenty of water, and try not to overuse your voice. Specifically, no yelling over loud noises, no shouting, no strenuous or aggressive singing.
Whether it's a minor injury or something unrelated to singing may not matter so much, as once you have such a condition, the care and potential risks are very similar. If you don't feel better after several days, you might give it a full week (this may be hard for some vocalists), after which you probably want to see a doctor to be safe.
Comment: A "tickle" in my throat, like it's dry, no matter how much water or tea I drink, is my usual warning sign that I need to take it easy vocally (either I'm overdoing it or I'm getting a bit sick).
Comment: Thanks - seems good advice. It feels to me since posting more like it could have been a tickle in my throat, since my throat has since got a bit sore and dry... some low-grade cold/virus probably. Luckily I am visiting my doctor on an unrelated matter next week so I have no dilemma about whether it's worth a special trip!


Vertically flip ASCII art with Python

Question: for another code that I am working on, I need to vertically flip an ASCII image:
I want to make this:
     *
    ***
   *****
    ***
    ***

into this:
    ***
    ***
   *****
    ***
     *

All I have right now is to read input on multiple lines into an array, but how do I make it so that it prints the first array last and the bottom array first.
text = ""
stopword = ""
while True:
    line = input()
    if line.strip() == stopword:
        break

Comment: Depending on what your idea of "flip" is, you might need to swap some characters as well (e.g, `b` for `p`, ``\`` for `/`…)
Comment: Push each line onto a stack, and then pop them one by one to produce the output.
Comment: Would this work for any input? I am trying to make it so that any 'picture' inputted will be able to be reversed. Sorry, I am only a beginner at this so my apologies if this is an easy question.
Comment: Yes, it would work for any input.  It works because a stack is first-in, first out.
Answer: You can add each line to a list of lines (list.append) and then invert that list (list[::-1]) before printing:
lines = []
stopword = ""
while True:
    line = input()
    if line.strip() == stopword:
        break
    lines.append(line) # Add to the list of lines
for line in lines[::-1]: # [::-1] inverts the list
    print(line)

Answer: This is a reasonable use-case for a deque - you can use .extendleft with any iterable.
from collections import deque

stop_word = '' # an empty line causes a stop
lines_until_stop = iter(input, stopword)
d = deque()
d.extendleft(lines_until_stop)
print(*d, sep='\n')

Answer: You can simplify everything by just reversing all the lines using reversed.
>>> art = '''
...      *
...     ***
...    *****
...     ***
...     ***
... '''
>>> print('\n'.join(reversed(art.splitlines())))
    ***
    ***
   *****
    ***
     *

I am feeling generous today, so for your complete example:
text = ""
stopword = "END"
lines = []
while True:
    line = input()
    if line.strip() == stopword:
        break
    lines.append(line)

print('\n'.join(reversed(lines)))

Answer: for item in lines[::-1]:
    print item

Vertically flip ASCII art with Python


Como obter o valor de algum ítem do select ao clicar sobre ele

Question: No fonte apresentado abaixo, a lógica tem falha ao capturar o clique sobre o elemento do select retornando apenas o primeiro option, e pelo que parece é um problema de índice - selectedIndex.
Observe:

        function selecionar(link) {

                var element1 = document.getElementById("poster");
                var element2 = document.getElementById("titulo");

    var el = document.getElementById("lista")
        var opt = el.options[el.selectedIndex].text;

                var urlcomp = link;
                var tamurl = urlcomp.length;
                for (var i = tamurl; i >= 0; i--) {
                    if (urlcomp.substring(i, i - 1) == '/') {
                        var antes = i;
                        var depois = urlcomp.substring(antes, tamurl);
                        break;
                    }
                }

                if (depois == opt) {
                        element1.innerHTML = "";
                        element2.innerHTML = "
big buck bunny
";
                    } else if (depois == opt) {
                        element1.innerHTML = "";
                        element2.innerHTML = "
madagascar 2
";
                    } else if (depois == opt) {
                        element1.innerHTML = "";
                        element2.innerHTML = "
procurando dory
";
                    } else if (depois == opt) {
                        element1.innerHTML = "";
                        element2.innerHTML = "
meu malvado favorito 2
";
                        }
                    }
    select { color: red; }
<select id="lista" onchange="selecionar(this.options[this.selectedIndex].value)">

    <option value="" selected="selected"></option>

 <option value="https://sites.google.com/site/mplayerplugin/repositorio/big_buck_bunny">big_buck_bunny</option>

 <option value="https://sites.google.com/site/mplayerplugin/repositorio/madagascar_2">madagascar_2</option>

 <option value="https://sites.google.com/site/mplayerplugin/repositorio/procurando_dory">procurando_dory</option>

 <option value="https://sites.google.com/site/mplayerplugin/repositorio/meu_malvado_favorito_2">meu_malvado_favorito_2</option>

</select>

Vejo que falta alguma coisa à mais para instruir o código.

ACHO QUE - Percorrer os ítens e apontar na variável opt o qual foi selecionado no option.

Porque quero fazer uso de variável que é bem mais prático e elegante. Tipo assim:
            var el = document.getElementById("lista")
            var opt = el.options[el.selectedIndex].text;

                if (depois == opt) {
                        ...
                    } else if (depois == opt) {
                        ...
                    } else if (depois == opt) {
                        ...
                    } else if (depois == opt) {
                        ...
                        }
                    }

E evitar de preencher manulamente:
                if (depois == 'big_buck_bunny') {
                        ...
                    } else if (depois == 'madagascar_2') {
                        ...
                    } else if (depois == 'procurando_dory') {
                        ...
                    } else if (depois == 'meu_malvado_favorito_2') {
                        ...
                        }
                    }

Comment: não seria mais simples passar só o elemento: `onchange(selecionar(this))` e na *function* selecionar pegar o value: `var valor=link.value`?
Answer: Basta obter o atributo value:

document.getElementById('lst').addEventListener('change', function(){
  console.log('valor selecionado: ' + this.value);
});
<select id="lst">
  <option value="http://www.meusite.com.br" selected="selected">item1</option>
  <option value="https://wwww.seusite.net">item2</option>
  <option value="ftp://www.seuendereco.com">item3</option>
</select>
Answer: Em vez de repetir código, sugiro colocar como value nas options o nome do poster e como texto o título do filme, armazenando numa variável a URL da pasta das imagens, já que todas são iguais. Imagine ter que fazer um if para cada item!
Então, o código ficaria assim (veja comentários no código):

function selecionar(i) {

   // pego a option selecionada
   var opt = document.querySelectorAll("#lista option")[i];

   // pego o valor da option
   var valor = opt.value;

   // pego o texto da option
   var titulo = opt.textContent;

   // guardo a URL numa variável, já que são todas iguais
   var local = "https://sites.google.com/site/mplayerplugin/repositorio/";

   var element1 = document.getElementById("poster");
   var element2 = document.getElementById("titulo");

   element1.innerHTML = "";
   element2.innerHTML = "
"+titulo+"
";
}
<select id="lista" onchange="selecionar(this.selectedIndex)">
   <option value="" selected="selected"></option>
   <option value="big_buck_bunny">big buck bunny</option>
   <option value="madagascar_2">madagascar 2</option>
   <option value="procurando_dory">procurando dory</option>
   <option value="meu_malvado_favorito_2">meu malvado favorito 2</option>
</select>


How to add prefix (label) and postfix to commerce price field

Question: I am trying to implement Drupal Commerce in an existing site with existing nodes. In this process I need to replace the existing price field with the commerce price field. Since this field is locked, I cannot change the label.
So I thought I could use the raw price format and just add a prefix as a label in template.php or possibly in a hook in *.tpl.php file. But after spending hours googling without finding how to do this, I give up and post this question here. Anybody got an idea?
Answer: I'm not 100% that I understand your question correctly but I assume you need to add prefix & suffix to your commerce product prices. In that case, Drupal Commerce Extra Price Formatters does exactly that, have you tried using this module?
Comment: Thanks for your answer. I managed to do this an other way, but I will look into this module as well.
Comment: @TBJ would you like to give more information around how you managed to do it so others can benefit too? Also, if you find one of the answers provided to be correct as well, can you mark them as such, thanks.
Comment: Hello I gave you an upvote. What I did was to programmatically in a custom module add code to fetch the price from Drupal commerce and set that price in an existing price field in the product node (raw format). That old price field was already styled as needed. So now everything looks as wanted.
Answer: In case you are using Display suite, you always can use a prefix/suffix using the expert options available in Display.
Comment: Thanks for this answer. I will look into this. For now I managed to resolve the problem in another way.


'Guessing' local extrema of a polynomial given its roots

Question: To start with let's assume that $p$ is a degree $n>1$ polynomial in $x$ and has $n$ distinct roots $\alpha_1, \ldots, \alpha_n$. Without loss of generality we can also stipulate that $0 = \alpha_1 < \cdots < \alpha_n = 1$. This guarantees there are $n-1$ local extrema, occurring at locations $x_1 \in (\alpha_1, \alpha_2)$, $x_2 \in (\alpha_2, \alpha_3)$, and so on. One might like to guess at the values of $x_i$ based on knowledge of the roots, and I'm curious about any heuristics that could do better than guessing the midpoint of each interval.
Of course, if $n$ is small, then there exists an explicit formula; e.g. when $p(x)=(x-\alpha_1)(x-\alpha_2)$ then $x_1 = (\alpha_1 + \alpha_2)/2$, the midpoint between the roots. But as early as $n=3$ things get murky; if $p(x)=(x-\alpha_1)(x-\alpha_2)(x-\alpha_3)$, then $$x_{1,2}=\frac{\alpha_1+\alpha_2+\alpha_3}{3}\pm\frac{\sqrt{(\alpha_1+\alpha_2+\alpha_3)^2-3(\alpha_1\alpha_2+\alpha_1\alpha_3+\alpha_2\alpha_3)}}{3}$$
From this we see that the two extrema are centered around the mean of the roots. For example when $\alpha_2=1/2$, they are at $1/2 \pm \sqrt{3}/6$, so they're "pushed out" toward $0$ and $1$ (as opposed to being evenly distributed at $1/4$ and $3/4$).
Based on this idea, I can imagine a heuristic that says the extremal values will be nearer some roots and further away from others, where "nearer" and "further" should be taken in a relative sense; in the simple example above they would be nearer $\alpha_1=0$ and $\alpha_3=1$, and further from $\alpha_2 = 1/2$. Once there are more roots, do the roles of the roots alternate? (a "near" root, then a "far root", then a "near" root again?).
A more concrete question to ask is: suppose I just guess that the extrema are at the midpoints between each pair of roots, call them $m_1 = (\alpha_1+\alpha_2)/2$, $m_2=(\alpha_2+\alpha_3)/2$, and so on. Call the error term $E=\frac{1}{n-1}\sum|m_i - x_i|^2$. How does $E$ depend on the roots of $p$? Is it monotonic with $n$ in some sense?
This is an idle curiosity; I'm just trying to dream up interesting Calc I problems and found something that is a little too interesting.
Answer: Given the polynomial
$$
p_{\,n} (x) = \prod\limits_{k = 1}^n {\left( {x - r_{\,k} } \right)}
 \quad \left| {\;r_{\,k}  \le r_{\,k + 1} } \right.
$$
Putting
$$
p_{\,n} (x) = \prod\limits_{k = 1}^n {\left( {x - r_{\,k} } \right)}
 \quad \left| {\;r_{\,k}  \le r_{\,k + 1} } \right.
$$
then it is clear that if we keep only the absolute values, we are converting all the extremals
into maxima, preserving the abscissas where they occur and their absolute values.
Then consider to take the logarithm
$$
\eqalign{
  & \left| {\,p_{\,n} (x)\,} \right| = \prod\limits_{k = 1}^n {\left| {\,x - r_{\,k} \,} \right|}   \cr
  & L_{\,n} (x) = \ln \left| {\,p_{\,n} (x)\,} \right|
 = \sum\limits_{k = 1}^n {\ln \left| {\,x - r_{\,k} \,} \right|}  \cr}
$$
the extremals of $p_n(x)$ will be the maxima of $L_n(x)$, occurring in between its poles.
Let's take for example five roots, as in the following graph.

The contribution of the first two roots alone is shown by the black curve.  The maximum would occur
at the average of the two roots.
The contribution of the remaining three roots is the blue curve, which at a sufficient distance may be approximated by the pink
one, as if the three roots were concentrated at their barycenter.
Clearly the action of the roots on the right is such as to "push" leftward the maximum between $r_1,r_2$,
yet not  beyond $r_1$.
Same in the reverse direction,  the effect the effect of the first couple on the right triple.
To estimate the deviation, we can develop in series the two set of functions around $s = (r_1 + r_2)/2$.
Let's put
$$
s = {{r_{\,2}  + r_{\,1} } \over 2}\quad d
 = {{r_{\,2}  - r_{\,1} } \over 2}\quad t = {{r_{\,3}  + r_{\,4}  + r_{\,5} } \over 3}
$$
so that for
$$
0 \le \left| {\,x - s\,} \right| \le d \le t - s
$$
we can write
$$
\eqalign{
  & L_{\,a} (x) = \ln \left| {\,x - r_{\,1} \,} \right| + \ln \left| {\,x - r_{\,2} \,} \right|  \cr
  &  = \ln \left| {\,x - s + d\,} \right| + \ln \left| {\,x - s - d\,} \right| =   \cr
  &  = \ln \left( {d^{\,2}  - \left( {x - s} \right)^{\,2} } \right) =   \cr
  &  = 2\ln d + \ln \left( {1 - \left( {{{x - s} \over d}} \right)^{\,2} } \right) =   \cr
  &  = 2\ln d - \left( {{{x - s} \over d}} \right)^{\,2}  + O\left( {\left( {{{x - s} \over d}} \right)^{\,4} } \right)  \cr
  &   \cr
  & L_{\,b} (x) = 3\ln \left| {\,x - t\,} \right| = 3\ln \left( {t - x} \right) =   \cr
  &  = 3\ln \left( {\left( {t - s} \right) - \left( {x - s} \right)} \right)
 = 3\ln \left( {t - s} \right) + 3\ln \left( {1 - {d \over {t - d}}\left( {{{x - s} \over d}} \right)} \right) =   \cr
  &  = 3\ln \left( {t - s} \right) - 3{d \over {t - d}}\left( {{{x - s} \over d}} \right)
 - {3 \over 2}\left( {{d \over {t - d}}} \right)^{\,2} \left( {{{x - s} \over d}} \right)^{\,2}
  + O\left( {\left( {{{x - s} \over d}} \right)^{\,3} } \right) \cr}
$$
Therefore the maximum between $r_1$ and $r_2$ will move
of the following amount
$$
\left( {{{x - s} \over d}} \right) = 0\quad
  \Rightarrow \quad \left( {{{x - s} \over d}} \right) \approx  - {{3{d \over {t - d}}}
 \over {3\left( {{d \over {t - d}}} \right)^{\,2}  + 2}}
$$
Generalization
The example above straitghtly suggests how to generalize it.
Always given the $n$ roots $r_1,\, r_2, \,  \ldots , \, r_n$ arranged in a non-decreasing order
from the logarithm defined above
$$
L_{\,n} (x) = \ln \left| {\,p_{\,n} (x)\,} \right|
 = \sum\limits_{k = 1}^n {\ln \left| {\,x - r_{\,k} \,} \right|}
$$
we know that the positions of the extremes is given by the solutions to
$$
0 = L_{\,n} '(x) = \sum\limits_{k = 1}^n {{1 \over {\,x - r_{\,k} \,}}}  = {{p_{\,n} '(x)} \over {p_{\,n} (x)}}
$$
which actually is a $n-1$ degree polynomial.
If the roots were only two (or if they are quite isolated from the others) there would be an extreme right in the middle.
We want to estimate how much the extreme between a couple of roots is deviated from the middle due to the
influence of the other (external) roots.
So let's consider a consecutive couple of roots $r_j, \, r_{j+1}$ and let's define
$$
s_{\,j}  = {{r_{\,j + 1}  + r_{\,j} } \over 2}\quad d_{\,j}  = {{r_{\,j + 1}  - r_{\,j} } \over 2}
$$
and write
$$
\eqalign{
  & L_{\,j,\,n} '(x) = {1 \over {\,x - \left( {s_{\,j}  - d_{\,j} } \right)\,}}
 + {1 \over {\,x - \left( {s_{\,j}  + d_{\,j} } \right)\,}}
 + \sum\limits_{\left\{ {\matrix{   {k \ne j,\,j + 1}  \cr    {1\, \le \,k\, \le \,n}  \cr } } \right.}
 {{1 \over {\,x - r_{\,k} \,}}}  =   \cr
  &  = {{2\left( {x - s_{\,j} } \right)} \over {\,\left( {x - s_{\,j} } \right)^2  - d_{\,j} ^2 }}
 +  \sum\limits_{\left\{ {\matrix{   {k \ne j,\,j + 1}  \cr    {1\, \le \,k\, \le \,n}  \cr } } \right.}
 {{1 \over {\,\left( {x - s_{\,j} } \right) - \left( {r_{\,k}  - s_{\,j} } \right)\,}}}  =   \cr
  &  = {1 \over {d_{\,j} }}{{2\left( {{{x - s_{\,j} } \over {d_{\,j} }}} \right)}
 \over {\,\left( {\left( {{{x - s_{\,j} } \over {d_{\,j} }}} \right)^2  - 1} \right)}} + {1 \over {d_{\,j} }}
 \sum\limits_{\left\{ {\matrix{   {k \ne j,\,j + 1}  \cr    {1\, \le \,k\, \le \,n}  \cr } } \right.}
 {{1 \over {\,\left( {{{x - s_{\,j} } \over {d_{\,j} }}} \right)
 - \left( {{{r_{\,k}  - s_{\,j} } \over {d_{\,j} }}} \right)\,}}}  =   \cr
  &  = {1 \over {d_{\,j} }}\left( {{{2\xi _{\,j} } \over {\,\left( {\xi _{\,j} ^2  - 1} \right)}}
 +  \sum\limits_{\left\{ {\matrix{   {k \ne j,\,j + 1}  \cr    {1\, \le \,k\, \le \,n}  \cr } } \right.}
 {{1 \over {\,\xi _{\,j}  - \rho _{\,k,\,j} \,}}} } \right)  \cr
  & \left| {\; - 1 \le \xi _{\,j}  = {{x - s_{\,j} } \over {d_{\,j} }} \le 1 < \rho _{\,k,\,j}
  = {{r_{\,k}  - s_{\,j} } \over {d_{\,j} }}} \right. \cr}
$$
Since
$$
{1 \over {x - a}} =  - {1 \over a}{1 \over {\left( {1 - x/a} \right)}}
 =  - {1 \over a}\left( {1 + {x \over a} + \left( {{x \over a}} \right)^{\,2}
  + O\left( {\left( {{x \over a}} \right)^{\,3} } \right)} \right)
 \quad \left| {\;\left| {{x \over a}} \right| < 1} \right.
$$
and
$$
{x \over {\,\left( {x^2  - 1} \right)}}
 =  - x\left( {1 + O\left( {x^{\,2} } \right)} \right)
\quad \left| {\;\left| x \right| < 1} \right.
$$
we can approximate at various levels the expression for $L_{\,j,\,n} '(x)$,  the very first being
$$ \bbox[lightyellow] {
\eqalign{
  & 0 \approx  - 2\xi _{\,j}
  - \sum\limits_{\left\{ {\matrix{ {k \ne j,\,j + 1}  \cr {1\, \le \,k\, \le \,n}  \cr  } } \right.}
 {{1 \over {\,\rho _{\,k,\,j} }}}  - \xi _{\,j}
 \sum\limits_{\left\{ {\matrix{ {k \ne j,\,j + 1}  \cr  {1\, \le \,k\, \le \,n}  \cr  } } \right.}
 {{1 \over {\,\rho _{\,k,\,j} ^{\,2} }}} \quad  \Rightarrow   \cr
  &  \Rightarrow \quad \xi _{\,j}  \approx
  - \;  {{\sum\limits_{\left\{ {\matrix{   {k \ne j,\,j + 1}  \cr   {1\, \le \,k\, \le \,n}  \cr  } } \right.}
 {{1 \over {\,\rho _{\,k,\,j} }}} }
 \over
{2 + \sum\limits_{\left\{ {\matrix{ {k \ne j,\,j + 1} \cr  {1\, \le \,k\, \le \,n}  \cr } } \right.}
 {{1 \over {\,\rho _{\,k,\,j} ^{\,2} }}} }} \cr}
}$$
Comment: This is a very interesting idea! In your example, you chose the groupings (2 and 3) because they are sort of naturally clustered, right? I'm not sure I see a foolproof way to generalize this, but as an example it's really great!
Comment: Also I like your graphing software!
Comment: nice that you appreciate ! the graph has been made with Geogebra.  I'll work at generalizing the example: in my view, it shall be possible (we are always speaking of a first approximation)
Comment: @dbx: added general extension.
Comment: Well, this is some lovely mathematics but it's far too technical to be a heuristic I think. Thanks for spending your time and effort thinking about it!
Answer: In my opinion, it is wrong to try to look for extreme points through examination of either the polynomial $p(x)$ or any of its roots.  The polynomial is going to be continuous, and have both a first and second derivative everywhere.
Therefore, the extreme points are going to be the (n-1, not necessarily distinct) roots of $p'(x) = 0$ [i.e. $\{r_1, r_2, \cdots, r_{(n-1)}\}$].  For each root, $r_i$, the sign (positive or negative) of $p''(r_i)$ will indicate whether it is a local minimum or maximum.
Edit
In your example, under the assumption that $p(x)$ has $n$ distinct real roots, $p'(x)$ has to have $(n-1)$ distinct real roots, because $p(x)$ must change direction $(n-1)$ times.
As for whether you would expect (for example) that the $p'(x)$ root between $\alpha_k$ and $\alpha_{(k+1)}$ will in general be closer to $\alpha_k$ or $\alpha_{(k+1)}$, I consider that to be an enormously complicated (and perhaps relatively unexplored) question.  I think that you would have to somehow diagnose the interplay between the coefficients of either $p(x)$, $p'(x)$, or both.
Comment: It's not much of an answer to say "I don't like the question you're asking, and besides, the answer is complicated"
Comment: @dbx You misinterpreted my answer.  I **do** like the question that you are asking.  I think that it is both interesting and unexplored.  My answer was intended to signify that you should explore the topic by first analyzing $p'(x)$ and $p''(x)$, rather than $p(x)$.


0-truncation of infinity-presheaves

Question: Let $\mathcal{C}$ be a small 1-category endowed with a Grothendieck topology. Is it true that the 0-truncation $\tau_0(\mathrm{Shv}_\infty(N(\mathcal{C})))$ of the $\infty$-topos of $\infty$-sheaves on $\mathcal{C}$ is equivalent to the nerve of the ordinary topos of (Set-valued) sheaves over $\mathcal{C}$? According to higher topos theory 18.104.22.168, the 0-truncation of the $\infty$-topos is the nerve of an ordinary topos, but I can't figure out how to prove that it is the obvious one in my case.
At least for the case where $\mathcal{C}$ has the trivial topology, I tried using the universal property of the 0-truncation wrt. left adjoints to 1-categories (HTT 18.104.22.168), but the problem is that a functor $\mathcal{C} \times \mathcal{D} \rightarrow \mathcal{E}$ need not be a right adjoint even if its transpose $\mathcal{C} \rightarrow \mathcal{E}^\mathcal{D}$ is.
Answer: Let my try to give an answer, although I should note that I am not an expert so there is no guarantee that my answer will be correct.
I claim that it suffices to show that $\tau_{\leq 0}\mathcal{P}(\mathcal C)\simeq \operatorname{Fun}(\mathcal C^{\mathrm{op}},\tau_{\leq 0}\mathcal S)$ holds (I am supressing the nerve functor here). Indeed, your category $\mathcal X=\operatorname{Shv}_{\infty}(\mathcal C)$ sits as a left-exact accessible localization inside $\mathcal P(\mathcal C)$, and $\tau_{\leq 0}$ induces a left-exact accessible localization of $0$-truncations (this follows from [HTT, 184.108.40.206]). So if $\tau_{\leq 0}\mathcal{P}(\mathcal C)\simeq \operatorname{Fun}(\mathcal C^{\mathrm{op}},\tau_{\leq 0}\mathcal S)$ holds true, then $\tau_{\leq 0}\mathcal X$ is equivalent to a $1$-category that arises as a left-exact localization of $\operatorname{Fun}(\mathcal C^{\mathrm{op}},\tau_{\leq 0}\mathcal S)\simeq \operatorname{Fun}(\mathcal C^{\mathrm{op}},\mathsf{Set})$ and is therefore a $1$-category of sheaves.
Now the equivalence $\tau_{\leq 0}\mathcal{P}(\mathcal C)\simeq \operatorname{Fun}(\mathcal C^{\mathrm{op}},\tau_{\leq 0}\mathcal S)$  can be seen as follows: The left-hand side is the full subcategory of $\mathcal P(\mathcal C)$ spanned by $0$-truncated presheaves, and a presheaf $F$ is $0$-truncated precisely if $\operatorname{map}(-,F)$ takes values in $\tau_{\leq 0}\mathcal S$. Plugging in the presheaf represented by objects $c\in\mathcal C$ tells us that $F$ must factor through $\tau_{\leq 0}\mathcal S$ (using the Yoneda lemma). But any presheaf $F$ that takes values in $\tau_{\leq 0}\mathcal S$ must already be $0$-truncated: This follows from the observation that any presheaf $G$ can be written as a colimit of representables and $\operatorname{map}(-, F)$ takes colimits to limits in $\mathcal S$, together with the fact that the full subcategory $\tau_{\leq 0}\mathcal S\subset \mathcal S$ is stable under arbitrary limits (HTT, 22.214.171.124).

0-truncation of infinity-presheaves


Least upper bound of character of representation of compact Lie group

Question: I'm asked to show given a complex representation $V$ of a compact matrix Lie group $G$, the character of $V$ has the least upper bound dim$(V)$. It's not clear to me what knowledge of character should I use to cut in to solve this question. I'm appreciate if you can give a slight hint.
Answer: WLOG $\rho(g)$ is unitary (from the averaging trick), in which case $\rho(g)$ is diagonalizable. What can we say about its eigenvalues, and what do they have to do with its trace?
Comment: I should embed the unitary trick into my head...


How to add twig code in View 'global custom text' field?

Question: I want to show a link when a node is published.
I added the Content: Publishing status field and hid it. In global custom text, I added the following code.
{% if status == 0 %}

Apply

{% endif %}

The replacement pattern for the published status is {{ status }}, which shows 0 or 1.
I am using Drupal 8.2.0.
Can anybody help me to make this work?
Answer: I tried that and it worked for me.

Just make sure to set the output format to 0/1.
{% if  status  %}

Apply

{% endif %}

Comment: thanks for the reply, but same code is not working in mine.My status field output format is boolean only. If node is unpublished also link is getting displayed. I have updated my question with the version of drupal 8.
Comment: @rks what you mean, you can see in my answer my field is boolean too and my drupal version in 8.2.6.  do you want  not exclude status field from display?
Comment: With `{% if  status  %}` the link would be shown also for unpublished nodes. I take the view is showing every node, independently for their status. Differently, checking the node status before outputting the link wouldn't make sense.
Comment: @apaderno, new account name, cool!
if you put the output format on 0/1 then  status 0 is equal false.
Comment: But `status` is a `Drupal\Core\Render\Markup` instance, not a number. I have set the *Content: Published* field to use *Boolean* as formatter and *1 / 0* as output format, and the code shown in this question doesn't work, as it shows the link independently from the node status. (I am confirming what @rks said in his comment.)
Answer: The correct code to use for the Global: Custom text field is the following one.
{% if status == '1' %}

Apply

{% endif %}

(I left the Status field visible just to check the link was only shown for published nodes.)
I first tried the following code, which didn't work.
{% if status == 1 %}

Apply

{% endif %}

I then noticed this error in the Drupal log, which made me understand that the code I entered was converting status to an integer.

Notice: Object of class Drupal\Core\Render\Markup could not be converted to int in __TwigTemplate_0e6762666bfbb9311bd9151c5ea0be83db756ef416475732470b4e0d9f6604e6->doDisplay() (line 32 of /var/www/html.original/sites/default/files/php/twig/61222d7b5a923___string_template__3f0751_iIyQMmqa7AXU9cjNTkh8j_Ed3/jVctGpgldXY6pQdNOz4-EYc-iwQbJzqU8T1VgO6g32E.php)

Notice that also the following code wouldn't work.
{% if  status  %}

Apply

{% endif %}

It would show the link also for unpublished nodes.

As side note, if the view is only shown to users who don't have access to unpublished nodes, or to whom information about unpublished nodes should not be shown, adding Published (=Yes) to the filter criteria is what I would do.


Date form element

Question: I am using the following code.
function mymodule_form($form, &$form_state) {
  $form = array();

  // Creating the date/time element starts here.

  // Provide a default date in the format YYYY-MM-DD HH:MM:SS.
  $date = '2008-12-31 00:00:00';

  // Provide a format using regular PHP format parts (see documentation on php.net).
  // If you're using a date_select, the format will control the order of the date parts in the selector,
  // rearrange them any way you like. Parts left out of the format will not be displayed to the user.
  $format = 'Y-m-d H:i';

  $form['date2'] = array(
     '#type' => 'date_select', // types 'date_popup', 'date_text' and 'date_timezone' are also supported. See .inc file.
     '#title' => t('Date'),
     '#default_value' => $date,
     '#date_format' => $format,
     '#date_label_position' => 'within', // See other available attributes and what they do in date_api_elements.inc
     '#date_timezone' => 'America/Chicago', // Optional, if your date has a timezone other than the site timezone.
     '#date_increment' => 15, // Optional, used by the date_select and date_popup elements to increment minutes and seconds.
     '#date_year_range' => '-3:+3', // Optional, used to set the year range (back 3 years and forward 3 years is the default).
    '#datepicker_options' => array(), // Optional, as of 7.x-2.6+, used to pass in additional parameters from the jQuery Datepicker widget.
  );

  return $form;
}

$form['date2'] is an array that contains a time. I want to use just the year or the day of this array. What should I do?
Answer: According to the comments, you can change $format to show only the elements you want, so you can do
$format = 'Y';

to select only the year, and
$format = 'd';

for the day.

Date form element