Can I apply GPO settings to 2008 R2 member servers if I have a 2003 domain functional level?

Question: I was asked to help out in a problem, there is a domain still operating at a 2003 functional level, there are 2008 R2 member servers in this domain and we need to know if there is anything we have to do to plan or anticipate when trying to apply the GPO settings to the 2008 R2 member servers.
- Will I need a 2008 R2 server with GPMC in order to deploy the GPO settings or can we deploy them with the GP tools in 2003 server?
- are there any gotchas we need to know about.
Appreciate the feedback.

Our situation is that we have member servers we need to apply security settings for not Domain controllers, we have no intention of standing up 2008 DC's, we only need to know what's required or involved to successfully patch those 2008 R2 servers in a 2003 domain.  Someone from another team mentioned the following: Requirements: ADPREP /forestprep, then ADPREP /domainprep /gpprep, this updates the GUIDs for the GPOs in order to enable the increased security requirements. There is no need to deploy a 2008 R2 or 2012 R2 Domain Controller, only a member server is needed to update the forest GUIDs, and when running the ADPREP /domainprep /gpprep is ran it will update both the domain GUIDs, and GPO GUIDs, without affecting the functionality of the forest or domain functional level.
My question is, are these steps required, we have no plans of using ADMX, we just have a GPO to apply server policies and that's it.  I did search extensively and did not find any solution to this question. Thanks.
Answer: This has been asked here for member servers being added only. If you want to make the 2008 box a DC you will need to use ADPREP link here.
We have a 2003 domain functional level with 2008 members and DC's. All have GPO's applied created from 2008 and 2003 DC's, hope that helps.
Comment: Some additional information on adding DC's here: https://technet.microsoft.com/en-us/library/cc733027(WS.10).aspx
Answer: ... You dont need to run ADPREP for this ... same like you dont need to prep your AD for 2012 gpos with function level 2008r2... would be the same thing
Just deploy the policys.. download all the ADMX templates for this step
Comment: Thanks, its my first time posting a question so I appreciate the info and that's what I thought.  I figured it would be easy enough to just create a GPO and apply it.  Thanks for confirming.


How to scroll the page with javascript before body load?

Question: I'm trying to scroll the page 50px before body load. But it always waits for body load before running the code.
I'm not quite sure what's the reason, I seem to remember  running as they are parsed.
I tried with both, jquery and plain javascript, this is my code:
$(document).scrollTop('50');
window.scrollBy(0,50);

How do I make it work before body load?
Comment: There is nothing to scroll before the body is parsed and rendered on the screen
Comment: Would CSS work? Body { margin-top:-50px}
Comment: You mean to scroll blank page before any html is loaded?
Comment: you can set the body opacity to 0 then on body loaded execute the scroll and finally set its opacity to 1 so it will be shown already scrolled
Comment: It's not clear why you should scroll the page 50px before the body is load, so a proper answer is hard to give. The scroll took in account two things:  the size of the document, and the size of the window. So, if the size of the document is bigger than the size of the window, you can scroll. But if the body is not loaded, you have no idea if the size exceed. Are you doing that because you're on mobile (e.g. iOS)? If is that the case, there are different approaches.
Answer: there is no body when you are calling the event so nothing would happen
one way around to this is that set the height of body so some constant number
and add onLoad event on the body tag

Answer: Found one working solution, maybe somebody will find cleaner one.
This can scroll the page even before the onload:
document.writeln(' ');
document.body.style.height = '5000px';
$(window).scrollTop(50);

Test script here.
Answer: 1. Create css offset class and assign to the body

    .offset{
         margin-top:-500px;
        }

    So that body will be loaded with 500px offset from top

    2. Then add following code to the body

    3. then using jquery, remove offset class when page is loaded

        $(document).ready(function(){
         $(".row").removeClass("offset");
        });

This will work http://www.frameinn.com/thatisuday/about


Tratando dados Array PDO CRUD

Question: lista-prato.php:
  <?php
    //inclui as bibliotecas
    require_once('conexao.class.php');
    //faz a canexão
    $pdo = new Conexao();

    // determina o numero de registros que serão visualisados
    $maximo = 20;
    // armazenamos o valor da pagina atual
    $pagina = isset($_GET['pagina']) ? ($_GET['pagina']) : '1';
    // subtraimos 1, por que os registros sempre começam do 0
    $inicio = $pagina - 1;
    //multiplicamos a quantidade de registros pelo valor da pagina atual
    $inicio = $maximo * $inicio;

    $strCount = $pdo->select("SELECT COUNT(*) AS 'id_prato', 'titulo', 'descricao', 'preco' FROM prato");

    $total = 0;
    $pratoId = 0;

if(count($strCount)){
    foreach ($strCount as $row)  {
        // armazeno total de registros da tabela para fazer paginação
        $total = $row["id_prato"];

    }

    $pratoid = $pdo->select("SELECT  id_prato FROM prato");
    $titulo = $pdo->select("SELECT  titulo FROM prato");
    $descricao = $pdo->select("SELECT  descricao FROM prato");
    $preco = $pdo->select("SELECT  preco FROM prato");
    }
echo "

 Total de pratos cadastrados
" . print_r($total, 1) . "
";
?>

            <colgroup>
                <col class="coluna1"/>
                <col class="coluna2"/>
                <col class="coluna3"/>
            </colgroup>

Paginação com PHP

                    Codigo
                    Prato
                    Descricao
                    Preco

            <?php
                //se a tabela nao estiver vazia, percorremos linha por linha pegando os valores
                if(count($strCount)){
                    foreach ($strCount as $res) {
                        echo "
";
                        echo "  ".print_r($pratoid, 1)."	";
                        echo "  ".print_r($titulo, 1)."	";
                        echo "  ".print_r($descricao, 1)."	";
                        echo "  ".print_r($preco, 1)."	";
                        echo "
";

                    }
                }
            ?>

RESULTADO:
         Total de pratos cadastrados
    8
                Paginação com PHP

 Codigo         Prato           Descricao                       Preco

                                     Array
    (
    )
        Array
    (
        [0] => Array
            (
                [titulo] => xx
                [0] => xx
            )

        [1] => Array
            (
                [titulo] => f
                [0] => f
            )

        [2] => Array
            (
                [titulo] => adad
                [0] => adad
            )

        [3] => Array
            (
                [titulo] => aa
                [0] => aa
            )

        [4] => Array
            (
                [titulo] => f
                [0] => f
            )

        [5] => Array
            (
                [titulo] => czx
                [0] => czx
            )

        [6] => Array
            (
                [titulo] => zc
                [0] => zc
            )

        [7] => Array
            (
                [titulo] => ddd
                [0] => ddd
            )

    )
        Array
    (
        [0] => Array
            (
                [descricao] => xx
                [0] => xx
            )

        [1] => Array
            (
                [descricao] => f
                [0] => f
            )

        [2] => Array
            (
                [descricao] => dasda
                [0] => dasda
            )

        [3] => Array
            (
                [descricao] => aa
                [0] => aa
            )

        [4] => Array
            (
                [descricao] => f
                [0] => f
            )

        [5] => Array
            (
                [descricao] => zxc
                [0] => zxc
            )

        [6] => Array
            (
                [descricao] => zxc
                [0] => zxc
            )

        [7] => Array
            (
                [descricao] => dd
                [0] => dd
            )

Como organizo esses dados para imprimir as informações corretas nas tabelas?
Answer: O print_r() é uma função para imprimir a estrutura de um array/objeto bom para realizar debbugins, no seu caso não não é necessário usar ele. Para exibir os valores corretamente, faça um foreach e use o nome das chaves correspondetes.
Como as informações são da mesma tabela não é necessário fazer uma consulta para cada coluna.
$pratoid = $pdo->select("SELECT  id_prato FROM prato");
$titulo = $pdo->select("SELECT  titulo FROM prato");
$descricao = $pdo->select("SELECT  descricao FROM prato");
$preco = $pdo->select("SELECT  preco FROM prato");

O bloco a cima deve ser trocado por esse que faz a mesma coisa porem usando uma consulta.
$pratos = $pdo->select("SELECT  id_prato, titulo, descricao, preco FROM prato");

//Caso queira exibir todos os campos troque os nomes por asterisco
//$pratos = $pdo->select("SELECT * FROM prato");

Para exibir as informações dos pratos basta chamar as chaves corretas seus nomes são definidos na consulta sql.
if(count($strCount)){
   foreach ($pratos as $res) {
      echo "
";
      echo "  ". $res['id_prato'] ."	";
      echo "  ". $res['titulo'] ."	";
      echo "  ". $res['descricao'] ."	";
      echo "  ". $res['preco'] ."	";
      echo "
";
   }
}

Comment: Deste modo não é impresso nada na tela.
Comment: @manzetti.denis ele não imprime nem as celulas vazias da tabela?
Comment: não. fiz umas alterações:
`if($pratos>0){
   foreach ($pratos as $res) {
      echo "";
      echo "  ". $res['id_prato'] ."";
      echo "  ". $res['titulo'] ."";
      echo "  ". $res['descricao'] ."";
      echo "  ". $res['preco'] ."";
      echo "";
   }

}   var_dump($pratos)` pelo que eu entendi, não tem valor nenhum salvo em `$pratos`. O programa imprime: **array (size=0)
  empty**
Comment: @manzetti.denis A definição de `$pratos` está igual a resposta?
Comment: ele só imprime o `$total`, que é o número de registros da coluna `id_prato`
Comment: Código atualizado: http://pastebin.com/TxaKH1ML <-
Comment: Mude seu if de `if($pratos > 0)` para `if(count($pratos) > 0)`. @manzetti.denis
Comment: Consegui, usei `$pratos = $pdo->select("SELECT * FROM prato");` e funcionou.
Comment: Então o nome de alguma coluna foi escrito errado na consulta para não ter retornado nada. @manzetti.denis
Comment: Só mais uma coisa, não está imprimindo caracteres como **"ç"**.
No banco atribui as colunas como **utf8-bin**. tem alguma coisa a ver?
Comment: @manzetti de uma olhada [nessa pergunta](http://pt.stackoverflow.com/q/8429/91) talvez o problema seja a codificação do arquivo ou a saída do html

Tratando dados Array PDO CRUD


IPSec on OpenVZ multiple ip addresses, using 127.0.0.2 on venet0

Question: I have an OpenVZ box with IPSec enabled.
root@wa000:~# ipsec verify
Checking your system to see if IPsec got installed and started correctly:
Version check and ipsec on-path                                 [OK]
Linux Openswan U2.6.38/K2.6.32-042stab094.7 (netkey)
Checking for IPsec support in kernel                            [OK]
 SAref kernel support                                           [N/A]
 NETKEY:  Testing XFRM related proc values                      [OK]
    [OK]
    [OK]
Checking that pluto is running                                  [OK]
 Pluto listening for IKE on udp 500                             [OK]
 Pluto listening for NAT-T on udp 4500                          [OK]
Two or more interfaces found, checking IP forwarding            [FAILED]
Checking NAT and MASQUERADEing                                  [OK]
Checking for 'ip' command                                       [OK]
Checking /bin/sh is not /bin/dash                               [WARNING]
Checking for 'iptables' command                                 [OK]
Opportunistic Encryption Support                                [DISABLED]

I installed openswan and xl2tpd for L2TP VPN. When I restart ipsec:
# service ipsec restart
ipsec_setup: Stopping Openswan IPsec...
ipsec_setup: Starting Openswan IPsec U2.6.38/K2.6.32-042stab094.7...
ipsec_setup: multiple ip addresses, using  127.0.0.2 on venet0

It detected 127.0.0.2, which I believe is a local ip to serve. I want it to serve on my public ip address. But I have no idea how to let ipsec serve on the right ip. I did googling, but nothing seems to be really helpful.
Here is the ifconfig -a output. I replaced the actual IPs with x.x.x.x, y.y.y.y and z.z.z.z.
# ifconfig -a
eth0      Link encap:Ethernet  HWaddr 00:18:51:69:44:e6
          BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

gre0      Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
          NOARP  MTU:1476  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

gretap0   Link encap:Ethernet  HWaddr 00:00:00:00:00:00
          BROADCAST MULTICAST  MTU:1476  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:118 errors:0 dropped:0 overruns:0 frame:0
          TX packets:118 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:18229 (18.2 KB)  TX bytes:18229 (18.2 KB)

venet0    Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
          inet addr:127.0.0.2  P-t-P:127.0.0.2  Bcast:0.0.0.0  Mask:255.255.255.255
          UP BROADCAST POINTOPOINT RUNNING NOARP  MTU:1500  Metric:1
          RX packets:126133 errors:0 dropped:0 overruns:0 frame:0
          TX packets:102937 errors:0 dropped:724 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:11322355 (11.3 MB)  TX bytes:40737353 (40.7 MB)

venet0:0  Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
          inet addr:x.x.x.x  P-t-P:x.x.x.x  Bcast:x.x.x.x  Mask:255.255.255.255
          UP BROADCAST POINTOPOINT RUNNING NOARP  MTU:1500  Metric:1

venet0:1  Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
          inet addr:y.y.y.y  P-t-P:y.y.y.y  Bcast:y.y.y.y  Mask:255.255.255.255
          UP BROADCAST POINTOPOINT RUNNING NOARP  MTU:1500  Metric:1

venet0:2  Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
          inet addr:z.z.z.z  P-t-P:z.z.z.z  Bcast:z.z.z.z  Mask:255.255.255.255
          UP BROADCAST POINTOPOINT RUNNING NOARP  MTU:1500  Metric:1

Comment: First post the output of ifconfig -a so you can determine what the right IP and interface actually is, and post your /etc/ipsec.conf file so we can see what's missing.
Comment: Thanks @qasdfdsaq. I posted the output of the `ifconfig -a` as a separate answer as it's too long for here.
Comment: The best thing to do would be to edit that information into your question instead of posting it as an answer.
Comment: Thanks @qasdfdsaq. I edited it in my original question, and deleted the answer.
Comment: Which of those interfaces is the external interface you *want* to listen on? And are you doing this on the OpenVZ host or a client/container?
Comment: Any of the x, y or z. I'm doing this on the OpenVZ container machine.
Answer:
You didn't specify, but from your ifconfig -a excerpt we can assume you're running ipsec inside OpenVZ VE, not hardware node (HN). Just to be sure — did you check out theirs recommendation for that kind of set-up?
OpenVZ's templates for VEs are really mind-blowing sometimes. I asked the devs why would one want to use 127/8 range IPs on non-loopback interfaces, but their answer was "well, we don't know, somebody else added it and it's legacy now". Absolute crap. You can safely remove this 127.0.0.2 "kludge" from the interface in question, it doesn't do a thing:
ip ad del 127.0.0.2/32 dev venet0. The problem is, though, on every VE restart this silly crap would be re-added. If you're controlling the hardware node you can set template to something that wouldn't trigger theirs "kludge" containing networking configuration. If you're not controlling it, well, the workaround is to put this "ip ad del" into something like /etc/rc.local and then re-start ipsec.
Answer: From https://lists.openswan.org/pipermail/users/2010-June/018901.html

When Openswan starts up, it looks like it picks the first IP Address on the br0 interface to announce what it's
    picking.  In case it picks wrong one of these days, how do I tell it definitively which IP Address on which
    interface?  Or is this just an opening announcement and I don't need to worry about it?

It binds to all addresses that are configured at startup. If an address is added
  later on, currently, pluto needs to be told to rebind these with "ipsec whack --listen"

ipsec_setup: multiple ip addresses, using  10.0.0.10 on br0

The message is a bit confusing. It will "use" the IP address it received a packet
  of when responding, and it uses the "nearest" IP address when initiating when
  using "%defaultroute". If will use the ip or resolved host name ip if specified
  in the conn.

It's possible your OpenVZ interfaces are not being bound automatically as they don't exist at startup.
Additionally, you can force it to listen on only one IP by editing your /etc/ipsec.conf file, adding the correct XX.XX.XX.XX or interface venet0:X specification using the listen=XX.XX.XX.XX or interface=venet0:X directives under the config setup section.
http://linux.die.net/man/5/ipsec.conf
Comment: Thanks @qasdfdsaq. I tried adding `listen` and `interface` under `config set` in `/etc/ipsec.conf`, but it's the same.


The clean URL test failed. (ubuntu14.04 lts + virtualmin + Apache/2.4.7)

Question: i can't enable clean url. Mod_rewrite is already enabled. Anything i'm missing? here is the conf
my apache is running user mode, the document root is in /home/drupal/public_html
/etc/apache2/sites-available/drupal.domain.local.conf
<VirtualHost *:80>
SuexecUserGroup "#1008" "#1008"
ServerName drupal.domain.local
ServerAlias www.drupal.domain.local
ServerAlias webmail.drupal.domain.local
ServerAlias admin.drupal.domain.local
DocumentRoot /home/drupal/public_html
ErrorLog /var/log/virtualmin/drupal.domain.local_error_log
CustomLog /var/log/virtualmin/drupal.domain.local_access_log combined
ScriptAlias /cgi-bin/ /home/drupal/cgi-bin/
ScriptAlias /awstats/ /home/drupal/cgi-bin/
DirectoryIndex index.html index.htm index.php index.php4 index.php5
<Directory /home/drupal/public_html>
Options -Indexes +IncludesNOEXEC +SymLinksIfOwnerMatch +ExecCGI
allow from all
AllowOverride All
#Options=ExecCGI,Includes,IncludesNOEXEC,Indexes,MultiViews,SymLinksIfOwnerMatch
Require all granted
AddHandler fcgid-script .php
AddHandler fcgid-script .php5
FCGIWrapper /home/drupal/fcgi-bin/php5.fcgi .php
FCGIWrapper /home/drupal/fcgi-bin/php5.fcgi .php5
</Directory>
<Directory /home/drupal/cgi-bin>
allow from all
AllowOverride All Options=ExecCGI,Includes,IncludesNOEXEC,Indexes,MultiViews,SymLinksIfOwnerMatch
</Directory>
RewriteEngine on
RewriteCond %{HTTP_HOST} =webmail.drupal.domain.local
RewriteRule ^(.*) https://drupal.domain.local:20000/ [R]
RewriteCond %{HTTP_HOST} =admin.drupal.domain.local
RewriteRule ^(.*) https://drupal.domain.local:10000/ [R]
RemoveHandler .php
RemoveHandler .php5
php_admin_value engine Off
IPCCommTimeout 7200
FcgidMaxRequestLen 2073741824
<Files awstats.pl>
AuthName "drupal.domain.local statistics"
AuthType Basic
AuthUserFile /home/drupal/.awstats-htpasswd
require valid-user
</Files>
</VirtualHost>
<VirtualHost *:443>
SuexecUserGroup "#1008" "#1008"
ServerName drupal.domain.local
ServerAlias www.drupal.domain.local
ServerAlias webmail.drupal.domain.local
ServerAlias admin.drupal.domain.local
DocumentRoot /home/drupal/public_html
ErrorLog /var/log/virtualmin/drupal.domain.local_error_log
CustomLog /var/log/virtualmin/drupal.domain.local_access_log combined
ScriptAlias /cgi-bin/ /home/drupal/cgi-bin/
ScriptAlias /awstats/ /home/drupal/cgi-bin/
DirectoryIndex index.html index.htm index.php index.php4 index.php5
<Directory /home/drupal/public_html>
Options -Indexes +IncludesNOEXEC +SymLinksIfOwnerMatch +ExecCGI
allow from all
AllowOverride All Options=ExecCGI,Includes,IncludesNOEXEC,Indexes,MultiViews,SymLinksIfOwnerMatch
Require all granted
AddHandler fcgid-script .php
AddHandler fcgid-script .php5
FCGIWrapper /home/drupal/fcgi-bin/php5.fcgi .php
FCGIWrapper /home/drupal/fcgi-bin/php5.fcgi .php5
</Directory>
<Directory /home/drupal/cgi-bin>
allow from all
AllowOverride All Options=ExecCGI,Includes,IncludesNOEXEC,Indexes,MultiViews,SymLinksIfOwnerMatch
</Directory>
RewriteEngine on
RewriteCond %{HTTP_HOST} =webmail.drupal.domain.local
RewriteRule ^(.*) https://drupal.domain.local:20000/ [R]
RewriteCond %{HTTP_HOST} =admin.drupal.domain.local
RewriteRule ^(.*) https://drupal.domain.local:10000/ [R]
RemoveHandler .php
RemoveHandler .php5
php_admin_value engine Off
IPCCommTimeout 31
FcgidMaxRequestLen 1073741824
SSLEngine on
SSLCertificateFile /home/drupal/ssl.cert
SSLCertificateKeyFile /home/drupal/ssl.key
<Files awstats.pl>
AuthName "drupal.domin.local statistics"
AuthType Basic
AuthUserFile /home/drupal/.awstats-htpasswd
require valid-user
</Files>
</VirtualHost>

.htaccess
   #
    # Apache/PHP/Drupal settings:
    #
    # Protect files and directories from prying eyes.
    <FilesMatch "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)(~|\.sw[op]|\.bak|\.orig|\.save)?$|^(\..*|Entries.*|Repository|Root|Tag|Template)$|^#.*#$|\.php(~|\.sw[op]|\.bak|\.orig\.save)$">
      Order allow,deny
    </FilesMatch>

    # Don't show directory listings for URLs which map to a directory.
    # Options -Indexes

    # Follow symbolic links in this directory.
    # Options +FollowSymLinks

    # Make Drupal handle any 404 errors.
    ErrorDocument 404 /index.php

    # Set the default handler.
    DirectoryIndex index.php index.html index.htm

    # Override PHP settings that cannot be changed at runtime. See
    # sites/default/default.settings.php and drupal_environment_initialize() in
    # includes/bootstrap.inc for settings that can be changed at runtime.

    # PHP 5, Apache 1 and 2.
    <IfModule mod_php5.c>
      php_flag magic_quotes_gpc                 off
      php_flag magic_quotes_sybase              off
      php_flag register_globals                 off
      php_flag session.auto_start               off
      php_value mbstring.http_input             pass
      php_value mbstring.http_output            pass
      php_flag mbstring.encoding_translation    off
    </IfModule>

    # Requires mod_expires to be enabled.
    <IfModule mod_expires.c>
      # Enable expirations.
      ExpiresActive On

      # Cache all files for 2 weeks after access (A).
      ExpiresDefault A1209600

      <FilesMatch \.php$>
        # Do not allow PHP scripts to be cached unless they explicitly send cache
        # headers themselves. Otherwise all scripts would have to overwrite the
        # headers set by mod_expires if they want another caching behavior. This may
        # fail if an error occurs early in the bootstrap process, and it may cause
        # problems if a non-Drupal PHP file is installed in a subdirectory.
        ExpiresActive Off
      </FilesMatch>
    </IfModule>

    # Various rewrite rules.
    <IfModule

mod_rewrite.c>
  RewriteEngine on

  # Set "protossl" to "s" if we were accessed via https://.  This is used later
  # if you enable "www." stripping or enforcement, in order to ensure that
  # you don't bounce between http and https.
  RewriteRule ^ - [E=protossl]
  RewriteCond %{HTTPS} on
  RewriteRule ^ - [E=protossl:s]

  # Make sure Authorization HTTP header is available to PHP
  # even when running as CGI or FastCGI.
  RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

  # Block access to "hidden" directories whose names begin with a period. This
  # includes directories used by version control systems such as Subversion or
  # Git to store control files. Files whose names begin with a period, as well
  # as the control files used by CVS, are protected by the FilesMatch directive
  # above.
  #
  # NOTE: This only works when mod_rewrite is loaded. Without mod_rewrite, it is
  # not possible to block access to entire directories from .htaccess, because
  # <DirectoryMatch> is not allowed here.
  #
  # If you do not have mod_rewrite installed, you should remove these
  # directories from your webroot or otherwise protect them from being
  # downloaded.
  RewriteRule "(^|/)\." - [F]

  # If your site can be accessed both with and without the 'www.' prefix, you
  # can use one of the following settings to redirect users to your preferred
  # URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
  #
  # To redirect all users to access the site WITH the 'www.' prefix,
  # (http://example.com/... will be redirected to http://www.example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} .
  # RewriteCond %{HTTP_HOST} !^www\. [NC]
  # RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  #
  # To redirect all users to access the site WITHOUT the 'www.' prefix,
  # (http://www.example.com/... will be redirected to http://example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  # RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]

  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  # RewriteBase /drupal
  #
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  RewriteBase /

  # Pass all requests not referring directly to files in the filesystem to
  # index.php. Clean URLs are handled in drupal_environment_initialize().
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

  # Rules to correctly serve gzip compressed CSS and JS files.
  # Requires both mod_rewrite and mod_headers to be enabled.
  <IfModule mod_headers.c>
    # Serve gzip compressed CSS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.css $1\.css\.gz [QSA]

    # Serve gzip compressed JS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.js $1\.js\.gz [QSA]

    # Serve correct content types, and prevent mod_deflate double gzip.
    RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
    RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]

    <FilesMatch "(\.js\.gz|\.css\.gz)$">
      # Serve correct encoding type.
      Header set Content-Encoding gzip
      # Force proxies to cache gzipped & non-gzipped css/js files separately.
      Header append Vary Accept-Encoding
    </FilesMatch>
  </IfModule>
</IfModule>

/etc/apache2/mods-available/userdir.conf
<IfModule mod_userdir.c>
    UserDir public_html
    UserDir disabled root
    <Directory /home/*/public_html>
                AllowOverride All
        #AllowOverride FileInfo AuthConfig Limit Indexes
                Options Indexes
        #Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
        <Limit GET POST OPTIONS>
            Require all granted
        </Limit>
        <LimitExcept GET POST OPTIONS>
            Require all denied
        </LimitExcept>
    </Directory>
</IfModule>

Comment: It's probably better to raise this with the Virtualmin community, as it's largely about Virtualmin-specific conf and apache setup. I can't see any issues with the files supplied, and you'd need to debug logs to see if there's any issues. Are you sure mod_rewrite is working? Have you tested it? Does the site work without rewrite?
Comment: i can access the website by http://drupal.domain.local/node/1 like, that, but i can't make the clean urls enable in configuration, where can i find the log?
Comment: Looks to me like your clean urls (mod_rewrite) are working fine. If it wasn't working, the url would be drupal.domain.local/?q=node/x. Perhaps you mean SEO-friendly urls. Pathauto module does that as it's not part of core. https://www.drupal.org/project/pathauto
Comment: I created another drupal vhost using virtualmin, using the dev version, the clean urls started with no need to enable. It is strange
Comment: It may help to remove the new lines in the htaccess file for the conditional If mod_rewrite.c
Answer: In my case, changing Options +FollowSymLinks in Drupal's .htaccess file worked:
Options +SymLinksIfOwnerMatch

It looks like it is more secure too: http://drupal.org/node/1269780


error operators == cannot be applied search array?

Question: this probably will be confusing or messy but I need help with my program
this is my program:
public partial class Form1 : Form
{
    int itemCountInteger;

    public struct Patient
    {
        public string patientidstring;
        public string firstNameString;
        public string lastNameString;

    }

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    public class Patientn
    {
        private int patientId;
        public string firstName;
        private string lastName;

        public Patientn()
        {
            patientId = 0;
            firstName = "";
            lastName = "";
        }

        public Patientn(int idValue, string firstNameVal, string lastNameVal)
        {
            patientId = idValue;
            firstName = firstNameVal;
            lastName = lastNameVal;
        }

    }

I want to be able to use a patient class instead of a struct to add patients and for the search code bellow I get the error "operators == cannot be applied" i want to be able to search the array if the text in textbox matches a name in array if so display surname help?
    //Array
    Patient[] patientInfo = new Patient[10];

    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            foreach (Patient patientinfoIndex in patientInfo)

            patientInfo[itemCountInteger].patientidstring = textBox1.Text;
            patientInfo[itemCountInteger].firstNameString = textBox2.Text;
            patientInfo[itemCountInteger].lastNameString = textBox3.Text;

            string names = patientInfo[itemCountInteger].firstNameString + " " + patientInfo[itemCountInteger].lastNameString;
            listBox1.Items.Add(names);
            itemCountInteger++;
            listBox1.SelectedItem = names;
        }
        catch
        {
            MessageBox.Show("Contacts are limited to 20. Please delete some contacts prior to adding more.");
        }

    }

    //Search Button search a patients name and display his surname in the label if patient is found  display his surname
    private void button2_Click(object sender, EventArgs e)
    {

        int intTest = 0;

        for (int x = 0; x < patientInfo.Length; x++)
        {
            if (textBox4.Text == patientInfo[x])
            {
                label6.Text =("surname");
                intTest = 1;
            }

        }

        if (intTest == 0)
        {
            label6.Text = ("not found");
        }
    }

I'm new to all of this sorry for asking and thanks in advance if you can help me with anything.
Comment: Please tell us where the error is.
Comment: Can you explain in human language how can string be equal to struct Patient?
Answer: You're getting the error because of this line; textBox4.Text == patientInfo[x]. There are a few problems here but firstly, textBox4.Text is a string and you're trying to do an equality comparison with a Patient the compiler is saying there is no == operator defined for that. You can overload the == operator for Patient but this would only allow you to compare one instance of type Patient to another, never will you be able to compare a Patient to a string unless you cast both to type object in which case it's just going to do a reference comparison (not what you want).
I'm not sure which property in Patient you want to use here but I do know you need to compare textBox4.Text to one of the strings within the Patient class. Something like this would work; (textBox4.Text == patientInfo[x].lastName)
Comment: thanks it worked, you have any suggestion on how to get rid of the struct patient and use the class patientn instead?
Comment: @user3439080 yeah, where you declare `public struct patient` just make it `public class patient` I think the only functional difference (there are other differences but this is not the place to get intot that) will be that if you don't specify public/private the default is private for classes while it's public for structs.
Answer: It makes no sense to compare System.String--the type returned by textBox4.Text--to a Patientn instance. You probably mean to compare Text to patientInfo[x].lastNameString.
Answer: You can't do
textBox4.Text == patientInfo[x]

patientInfo contains instances of Patience and textBox4.Textis a string. There is no possible comparison between those two and that's why you get the error.
You're probably trying to do something like this
textBox4.Text == patientInfo[x].patientidstring


Ordenação da mat-angular-table está priorizando letras maiúsculas

Question: Estou utilizando o mat sort para ordenar uma mat-table no angular, o problema é que quando ordeno de forma ascendente o algoritmo está levando em conta letras maiúsculas como prioridade, logo, se eu tiver uma tabela com os seguintes nomes:
"Marcos"
"antonio"
Marcos aparece primeiro na ordenação.
Esse é o algoritmo que usa pra ordenar:
sortData(sort: Sort) {
    const data = this.descricoesProdutos.slice();
    if (!sort.active || sort.direction === '') {
      this.sortedData = data;
      return;
    }

    this.sortedData = data.sort((a, b) => {
      const isAsc = sort.direction === 'asc';
      switch (sort.active) {
        case 'nome': return this.compare(a.nome, b.nome, isAsc);
        case 'descricao': return this.compare(a.descricao, b.descricao, isAsc);
        default: return 0;
      }
    });
  }

  compare(a: number | string, b: number | string, isAsc: boolean) {
  return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
  }

Meu html:

Answer: Consegui resolver capitalizando antes de comparar:
 return this.compare(a.nome.toUpperCase(), b.nome.toUpperCase(), isAsc);


passing parameters to dynamic drop down function jquery

Question: I have a for loop which generates few 'a' tag buttons and few divisions. I am trying to write a function in which with a toggle effect. If I click on a specific a tag only the corresponding div tag should get toggled. I am trying to pass a dynamic value to this function but it doesn't work. Here is the code. Please help. Thank you.

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="layout.css" rel="stylesheet" type="text/css">

<?php
$num_row = 5; //dynamic value
$i = 0;
$header_title = "";
    for ($i=0;$i<$num_row;$i++)
      {
        $header_title = $i; // Displaying all the headers and menus for the hotel.
        echo "
";
        echo "
";
        echo "$header_title";
        echo "
Hello World!
";
        echo "
";
        echo "
";
      }
?>

Comment: Just an fyi, the callback function you pass to the click handler is an event object, not the id of the clicked element.
Answer: This solution should work for you.
$(this).next('div').slideToggle('fast');
There are some things that you are doing wrong.

Starting an id with a number. In fact your id is the number. It should start with a letter
Having the script after the body. Typically it should be either in the head element or just before body ends
In the .click() function, you are passing $i. It makes no sense. You should be using event instead. In this case, you don't really need it and can have the method without passing anything to it. This is for times when you would use the event parameter.


Como obter o maior e o menor número entre 15 números digitados? C++

Question: Algorítmo que leia 15 números reais, e escreva o maior e o menor entre os números lidos. Não estou conseguindo fazer a parte de escrever o menor e maior dos números digitados.
Código:
#include <iostream>
using namespace std;
int main(){
    float numero;
    int cont;
    cont=1;
    while(cont<=15) {
       cout << ("Digite um numero real:");
       cin >> numero;
       cont++;
    }
}

Como obter o maior e o menor número entre os números digitados?
Comment: Defina as variáveis `maior` e `menor`, após a leitura de num faça: `if (cont == 1) menor = maior = num; else {if (num > maior) maior = num; if (num < menor) menor = num;}`. Após o loop imprima as variáveis `maior` e `menor`.
Comment: Estava seguindo a linha que diogoBRRN estava seguindo no desenvolvimento e ele não estava utilizando tais features e existe solução possível sem utiliza-las..
Comment: @anonimo não seria melhor utilizar o `std::set` ou um `vector` com o `algorithm`?
Answer: Você pode insirir os dados de entrada em um std::set, que é um container ordenado, e então basta pegar o primeiro elemento (menor) e o último elemento (maior).
#include <iostream>
#include <set>

int main( [[maybe_unused]] int argc, [[maybe_unused]] char ** argv )
{
  // a inicialização é para simular a entrada de dados
  std::set<float> numbers = { 100.1, 23.3, 84.3, -1.4, 1234.5, /* ... */ 40.22 };

  std::cout << "Min:" << *numbers.begin() << std::endl;
  std::cout << "Max:" << *numbers.rbegin() << std::endl;

  return 0;
}

Comment: Maneira curta e simples, vou seguir essa resposta :)
Answer: Defina duas variáveis de controle do tipo float, sendo elas maior e menor. Após a leitura do atributo numero faça a seguinte validação:
//Verifica se é o primeiro número digitado e define o valor das variáveis maior e menor igual ao número.
if (cont == 1) {
    maior = numero;
    menor = maior;
}
else if (numero > maior) //Verifica se o número digitado é maior do que o maior dos números digitados.
    maior = numero;
else if (numero < menor) //Verifica se o número digitado é menor do que o menor dos números digitados.
    menor = numero;

Código modificado:
#include <iostream>
using namespace std;
int main() {
    float numero, maior, menor;
    int cont = 1;
    while (cont <= 15) {
       cout << ("Digite um numero real:");
       cin >> numero;
       if (cont == 1) {
           maior = numero;
           menor = maior;
       }
       else if (numero > maior) {
           maior = numero;
       }
       else if (numero < menor) {
           menor = numero;
       }
       cont++;
    }
    cout << "Menor numero: " << menor << "\nMaior numero: " << maior << endl;
}

Answer: Leia um número, considere esse número como sendo tanto o maior como o menor até o momento.
Leia os outros 14 e vá comparando com o maior e o menor até o momento atual.
#include <iostream>
using namespace std;
int main(){
   float numero, maior, menor;
   int cont;
   cont=1;
   cout << ("Digite um numero real:");
   cin >> numero;
   maior = menor = numero
   while(cont< 15) {
       // aqui você coloca o código pra atualizar as variáveis maior e menor
       cont++;
}

}
Comment: Mas é justamente essa comparação que ele não sabe
Answer: Uma maneira que eu considero muito boa é utilizar vector e o algorithm, eles já possuem uma função para ver o menor valor e o maior, assim não será necessario utilizar nenhum if.
Código:
#include <iostream>
#include <vector>
#include<algorithm>

using namespace std;
int main(){
    float numero;
    vector<float> num;
    int cont, maximo, minimo;
    cont=1;
    while(cont<=15) {
       cout << ("Digite um numero real:");
       cin >> numero;
       num.push_back(numero);
       cont++;
    }

    cout << "Maior valor digitado: " << *max_element(num.begin(), num.end()) << endl;
    cout << "Menor valor digitado: " << *min_element(num.begin(), num.end()) << endl;

}

Veja funcionando no Repl.it


When does matrices represent the same bilinear form

Question: Here is the task I was recently asked to solve:
At what value of the paramter $a$ matrices
\begin{equation*}
A =
\begin{pmatrix}
1 & 4-a-a^2 \\
2 &  -1\\
\end{pmatrix}
\end{equation*}
and
\begin{equation*}
B =
\begin{pmatrix}
-a-1 & 3 \\
3 &  -5\\
\end{pmatrix}
\end{equation*}
can be the matrices of a same bilinear form $V \times V \rightarrow \mathbb{R}$ in different bases?
I know that if the matrices $A$ and $B$ represent the same bilinear form then
$$\exists \space S: A=S^TBS (1)$$
But what am I supposed to do next? Is it possible to solve equation $(1)$ for $S$?
I found the same post here: Find the values of parameter a so that matrices A and B  - But there is no reasonable answer(why does $A$ has to be symmetric?)
Answer: You can notice that B is symmetric while A isn't for every a. When you impose the condition on symmetry (you find the 2 values of a for wich A is symmetric) you can use spectral theory to determine wether or not they represent the same bilinear form. Obviously I consider that both are expressed in canonical bases.
Comment: Good job, bruh! Now I got it!
Answer: Given two bases for the same vector space, there exist a matrix, S, that transforms the vectors in one basis to the basis in the other basis.  Then a matrix, A, in one basis is the same as the basis $SAS^{-1}$ in the other.


Running a simulation: replications or bootstrap?

Question: I draw $n$ iid random draws from a univariate Gaussian distribution. My goal is to estimate the density $f$ using a nonparametric density estimation approach. To add a measure of uncertainty, I want to compute confidence bands for my estimate. Now I wonder how I should do that. Since I know the true distribution, I could just resample $m$ times. Or should I keep one sample and do bootstrapping? If I didn't know the true distribution, bootstrapping would be clearly the way to go but since I know $f$, there may be a way to use that information for adding confidence bands?
Answer: A (non-parametric) bootstrap sample is just sampling from the empirical distribution.  So when you do what is most commonly called bootstrapping you are just simulating from an estimate of the population/distribution.
Parametric bootstrap involves sampling from a distribution that you believe represents the population or random procedure, your described simulation is therefore a parametric bootstrap.
So your 2 choices are not really that different, mostly different in name.  Which to use depends on what future situations you want to generalize to.
Comment: What still confuses me: I resample $m$ times, for example, from $\mathcal N(0,1)$, compute estimates $\hat f_i$, $i=1,2,\dots,m$ and construct confidence bands from the $\alpha/2$ and $1-\alpha/2$-quantile of the empirical distribution of the $\hat f$'s. It could now be the case that my actual estimator $\hat f$ is outside of the confidence region. How do I ensure that the estimator is inside? Thank you for your reply
Comment: The very point of confidence bands is that not every realisation is inside. Even "worse", the definition of a confidence band of functions is rather unclear as should it impose for the entire function to stay within the band?
Comment: That's how I understand a pointwise (maybe I should have added that detail) confidence interval: the function stays within the band.


Como implementar esta classe numa TextView , para que funcione corretamente?

Question: Encontrei este código de "autoencolhimento" no link https://stackoverflow.com/questions/5033012/auto-scale-textview-text-to-fit-within-bounds e gostaria de saber  como implementar numa TextView.
**
 *               DO WHAT YOU WANT TO PUBLIC LICENSE
 *                    Version 2, December 2004
 *
 * Copyright (C) 2004 Sam Hocevar <email@example.com>
 *
 * Everyone is permitted to copy and distribute verbatim or modified
 * copies of this license document, and changing it is allowed as long
 * as the name is changed.
 *
 *            DO WHAT YOU WANT TO PUBLIC LICENSE
 *   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
 *
 *  0. You just DO WHAT YOU WANT TO.
 */

import android.content.Context;
import android.text.Layout.Alignment;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.TextView;

/**
 * Text view that auto adjusts text size to fit within the view.
 * If the text size equals the minimum text size and still does not
 * fit, append with an ellipsis.
 *
 * @author Chase Colburn
 * @since Apr 4, 2011
 */
public class AutoResizeTextView extends TextView {

    // Minimum text size for this text view
    public static final float MIN_TEXT_SIZE = 20;

    // Interface for resize notifications
    public interface OnTextResizeListener {
        public void onTextResize(TextView textView, float oldSize, float newSize);
    }

    // Our ellipse string
    private static final String mEllipsis = "...";

    // Registered resize listener
    private OnTextResizeListener mTextResizeListener;

    // Flag for text and/or size changes to force a resize
    private boolean mNeedsResize = false;

    // Text size that is set from code. This acts as a starting point for resizing
    private float mTextSize;

    // Temporary upper bounds on the starting text size
    private float mMaxTextSize = 0;

    // Lower bounds for text size
    private float mMinTextSize = MIN_TEXT_SIZE;

    // Text view line spacing multiplier
    private float mSpacingMult = 1.0f;

    // Text view additional line spacing
    private float mSpacingAdd = 0.0f;

    // Add ellipsis to text that overflows at the smallest text size
    private boolean mAddEllipsis = true;

    // Default constructor override
    public AutoResizeTextView(Context context) {
        this(context, null);
    }

    // Default constructor when inflating from XML file
    public AutoResizeTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    // Default constructor override
    public AutoResizeTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mTextSize = getTextSize();
    }

    /**
     * When text changes, set the force resize flag to true and reset the text size.
     */
    @Override
    protected void onTextChanged(final CharSequence text, final int start, final int before, final int after) {
        mNeedsResize = true;
        // Since this view may be reused, it is good to reset the text size
        resetTextSize();
    }

    /**
     * If the text view size changed, set the force resize flag to true
     */
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        if (w != oldw || h != oldh) {
            mNeedsResize = true;
        }
    }

    /**
     * Register listener to receive resize notifications
     * @param listener
     */
    public void setOnResizeListener(OnTextResizeListener listener) {
        mTextResizeListener = listener;
    }

    /**
     * Override the set text size to update our internal reference values
     */
    @Override
    public void setTextSize(float size) {
        super.setTextSize(size);
        mTextSize = getTextSize();
    }

    /**
     * Override the set text size to update our internal reference values
     */
    @Override
    public void setTextSize(int unit, float size) {
        super.setTextSize(unit, size);
        mTextSize = getTextSize();
    }

    /**
     * Override the set line spacing to update our internal reference values
     */
    @Override
    public void setLineSpacing(float add, float mult) {
        super.setLineSpacing(add, mult);
        mSpacingMult = mult;
        mSpacingAdd = add;
    }

    /**
     * Set the upper text size limit and invalidate the view
     * @param maxTextSize
     */
    public void setMaxTextSize(float maxTextSize) {
        mMaxTextSize = maxTextSize;
        requestLayout();
        invalidate();
    }

    /**
     * Return upper text size limit
     * @return
     */
    public float getMaxTextSize() {
        return mMaxTextSize;
    }

    /**
     * Set the lower text size limit and invalidate the view
     * @param minTextSize
     */
    public void setMinTextSize(float minTextSize) {
        mMinTextSize = minTextSize;
        requestLayout();
        invalidate();
    }

    /**
     * Return lower text size limit
     * @return
     */
    public float getMinTextSize() {
        return mMinTextSize;
    }

    /**
     * Set flag to add ellipsis to text that overflows at the smallest text size
     * @param addEllipsis
     */
    public void setAddEllipsis(boolean addEllipsis) {
        mAddEllipsis = addEllipsis;
    }

    /**
     * Return flag to add ellipsis to text that overflows at the smallest text size
     * @return
     */
    public boolean getAddEllipsis() {
        return mAddEllipsis;
    }

    /**
     * Reset the text to the original size
     */
    public void resetTextSize() {
        if (mTextSize > 0) {
            super.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize);
            mMaxTextSize = mTextSize;
        }
    }

    /**
     * Resize text after measuring
     */
    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        if (changed || mNeedsResize) {
            int widthLimit = (right - left) - getCompoundPaddingLeft() - getCompoundPaddingRight();
            int heightLimit = (bottom - top) - getCompoundPaddingBottom() - getCompoundPaddingTop();
            resizeText(widthLimit, heightLimit);
        }
        super.onLayout(changed, left, top, right, bottom);
    }

    /**
     * Resize the text size with default width and height
     */
    public void resizeText() {

        int heightLimit = getHeight() - getPaddingBottom() - getPaddingTop();
        int widthLimit = getWidth() - getPaddingLeft() - getPaddingRight();
        resizeText(widthLimit, heightLimit);
    }

    /**
     * Resize the text size with specified width and height
     * @param width
     * @param height
     */
    public void resizeText(int width, int height) {
        CharSequence text = getText();
        // Do not resize if the view does not have dimensions or there is no text
        if (text == null || text.length() == 0 || height <= 0 || width <= 0 || mTextSize == 0) {
            return;
        }

        if (getTransformationMethod() != null) {
            text = getTransformationMethod().getTransformation(text, this);
        }

        // Get the text view's paint object
        TextPaint textPaint = getPaint();

        // Store the current text size
        float oldTextSize = textPaint.getTextSize();
        // If there is a max text size set, use the lesser of that and the default text size
        float targetTextSize = mMaxTextSize > 0 ? Math.min(mTextSize, mMaxTextSize) : mTextSize;

        // Get the required text height
        int textHeight = getTextHeight(text, textPaint, width, targetTextSize);

        // Until we either fit within our text view or we had reached our min text size, incrementally try smaller sizes
        while (textHeight > height && targetTextSize > mMinTextSize) {
            targetTextSize = Math.max(targetTextSize - 2, mMinTextSize);
            textHeight = getTextHeight(text, textPaint, width, targetTextSize);
        }

        // If we had reached our minimum text size and still don't fit, append an ellipsis
        if (mAddEllipsis && targetTextSize == mMinTextSize && textHeight > height) {
            // Draw using a static layout
            // modified: use a copy of TextPaint for measuring
            TextPaint paint = new TextPaint(textPaint);
            // Draw using a static layout
            StaticLayout layout = new StaticLayout(text, paint, width, Alignment.ALIGN_NORMAL, mSpacingMult, mSpacingAdd, false);
            // Check that we have a least one line of rendered text
            if (layout.getLineCount() > 0) {
                // Since the line at the specific vertical position would be cut off,
                // we must trim up to the previous line
                int lastLine = layout.getLineForVertical(height) - 1;
                // If the text would not even fit on a single line, clear it
                if (lastLine < 0) {
                    setText("");
                }
                // Otherwise, trim to the previous line and add an ellipsis
                else {
                    int start = layout.getLineStart(lastLine);
                    int end = layout.getLineEnd(lastLine);
                    float lineWidth = layout.getLineWidth(lastLine);
                    float ellipseWidth = textPaint.measureText(mEllipsis);

                    // Trim characters off until we have enough room to draw the ellipsis
                    while (width < lineWidth + ellipseWidth) {
                        lineWidth = textPaint.measureText(text.subSequence(start, --end + 1).toString());
                    }
                    setText(text.subSequence(0, end) + mEllipsis);
                }
            }
        }

        // Some devices try to auto adjust line spacing, so force default line spacing
        // and invalidate the layout as a side effect
        setTextSize(TypedValue.COMPLEX_UNIT_PX, targetTextSize);
        setLineSpacing(mSpacingAdd, mSpacingMult);

        // Notify the listener if registered
        if (mTextResizeListener != null) {
            mTextResizeListener.onTextResize(this, oldTextSize, targetTextSize);
        }

        // Reset force resize flag
        mNeedsResize = false;
    }

    // Set the text size of the text paint object and use a static layout to render text off screen before measuring
    private int getTextHeight(CharSequence source, TextPaint paint, int width, float textSize) {
        // modified: make a copy of the original TextPaint object for measuring
        // (apparently the object gets modified while measuring, see also the
        // docs for TextView.getPaint() (which states to access it read-only)
        TextPaint paintCopy = new TextPaint(paint);
        // Update the text paint object
        paintCopy.setTextSize(textSize);
        // Measure using a static layout
        StaticLayout layout = new StaticLayout(source, paintCopy, width, Alignment.ALIGN_NORMAL, mSpacingMult, mSpacingAdd, true);
        return layout.getHeight();
    }

}

Comment: Não está clara a sua pergunta. Como essa classe de exemplo *herda* de uma `TextView`, ela simplesmente **é uma** `TextView` especializada. Por isso o colega @ramaral respondeu com uma forma de usá-la em um Layout. Se não for esse o caso, por favor edite a pergunta para torná-la mais clara.
Answer: Suponho que se refere a utilizar este TextView num layout.
Assim sendo, depois de ter a classe no seu projecto, pode usá-la no XML da mesma forma que usa qualquer outra View.
A única diferença é que deve usar o caminho completo até ela:
<NomeDaSuaPeckage.AutoResizeTextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    ......
    ......
    ......
/>

Comment: fiz exatamente isso que você passou, porem me parece que código esta funcionado corretamente, mas no meu caso quando ele vai diminuir a texto , é como ele truncasse o texto ai você vai digitando ele vai diminuindo o que ficou na tela, mas a parte truncada, ela esta sendo digitada mas não aparece por que será que isso acontece?, não sei se fiz você entender o problema.


Contagem de Checkbox enabled

Question: Esse codigo faz a contagem de quantos checkbox fora marcados.
Como posso fazer para que ele não inclua na contagem os checkbox disabled

<input type="checkbox" name="check1" disabled value="1">
<input type="checkbox" name="check1" disabled value="2">
<input type="checkbox" name="check1" value="3">
<input type="checkbox" name="check1" value="4">
<input type="checkbox" name="check1" value="5">

Answer: Ao invés disso
var n = $( "input:checked" ).length;

Coloque isso:
var n = $( "input:enabled:checked" ).length;

Contagem de Checkbox enabled


Evaluating $\lim_{x\to 0}\left(\frac{1}{\sin x} - \frac{1}{\tan x}\right)$

Question: How to solve this limit
$$
\lim_{x\to 0}\left(\frac{1}{\sin x} - \frac{1}{\tan x}\right)
$$
without using L'Hospital's rule?
Comment: Also I suspect you'll need to use Taylor series, can you use them?
Answer: THE ANSWER
\begin{align}
\lim_{x\to0}\left(\frac{1}{\sin x}-\frac{1}{\tan x}\right)&=\lim_{x\to0}\left(\frac{1}{\sin x}-\frac{\cos x}{\sin x}\right)\\
&=\lim_{x\to0}\left(\frac{1-\cos x}{\sin x}\right)\\
&=\lim_{x\to0}\left(\frac{1-\cos x}{\sin x}\cdot\frac{1+\cos x}{1+\cos x}\right)\\
&=\lim_{x\to0}\left(\frac{1-\cos^2 x}{\sin x(1+\cos x)}\right)\\
&=\lim_{x\to0}\left(\frac{\sin^2 x}{\sin x(1+\cos x)}\right)\\
&=\lim_{x\to0}\left(\frac{\sin x}{1+\cos x}\right)\\
&=\frac{\sin 0}{1+\cos 0}\\
&=\LARGE0
\end{align}
Answer: Hint:
$$
\frac{1}{\sin x}-\frac{1}{\tan x} = \frac{1}{\sin x}-\frac{\cos x}{\sin x} = \frac{1-\cos x}{\sin x} = \frac{1-\cos x}{x}\frac{x}{\sin x}.
$$
Answer: By the formulas
$$
\cos 2x=\cos x ^2-\sin x ^2=1-2\sin x ^2, \sin 2x=2 \sin x \cos x,
$$
we have
$$
1-\cos x=2\sin^2 {\frac{x}{2}}, \sin x=2 \sin \frac{x}{2} \cos \frac{x}{2}.
$$
Then,
$$\begin{align}
\lim_{n\rightarrow \infty} (\frac{1}{\sin x}-\frac{1}{\tan x})
&=\lim_{n\rightarrow \infty} (\frac{1}{\sin x}-\frac{\cos x}{\sin x})\\
&=\lim_{n\rightarrow \infty} \frac{1-\cos x}{\sin x}\\
&=\lim_{n\rightarrow \infty} \frac{2\sin^2 {\frac{x}{2}}}{2 \sin \frac{x}{2} \cos\frac{x}{2}}\\
&=\lim_{n\rightarrow \infty} \frac{\sin {\frac{x}{2}}}{\cos\frac{x}{2}}\\
&=\frac{0}{1}\\
&=0.
\end{align}
$$
P.S. identities among triangle functions are very helpful when one wants to simplify formulas involving them.
Answer: Answer:
$$\begin{align}
\lim \limits_{x\to 0}\left(\dfrac{1}{\sin(x)}-\dfrac {1}{\tan (x)}\right)&=\lim \limits_{x\to 0}\left(\dfrac{1}{\sin(x)}-\dfrac {\cos(x)}{\sin(x)}\right)\\
&=-\lim \limits_{x\to 0}\left(\dfrac{\cos(x)-1}{\sin(x)}\right)\\
&=-\lim \limits_{x\to 0}\left(\dfrac{\cos(x)-\cos(0)}{x-0}\dfrac {x}{\sin(x)}\right)\\
&=-\lim \limits_{x\to 0}\left(\dfrac{\cos(x)-\cos(0)}{x-0}\right)\lim \limits_{x\to 0}\left(\dfrac {x}{\sin(x)}\right)\\
&=-\cos'(0)\cdot 1\\
&=-\sin(0)\\
&=0.
\end{align}$$
Answer: One way to do it, at least not mentioning L'Hospital would be
$$ \frac{1}{\sin x} - \frac{1}{\tan x} =
\frac{1-\cos x}{\sin x} = \frac{\frac12 x^2 + o(x^2)}{x + o(x^2)} $$
as $x\to 0$...


Om - pah - pah - pah

Question: Is there a name for the "om - pah - pah - pah" accompaniment? Like a waltz ("om - pah - pah") but with 3 chords after the bass instead of 2?
I was thinking maybe stride bass or something.
Comment: Without the specific notes it's not as easy to say. If it's an arpeggio it could be an Alberti bass line.
Comment: Do you have an example? I can't think of one where the second "pah" isn't varied in some way.
Comment: @Max "Our House" by CSN&Y, "For No One" by the Beatles, ...
Answer: 'Waltz', of course, originates as a decription of a dance, extending to the style of music to which a waltz can be danced to – as indeed is the case with many musical characterisations. The dance of the waltz consists of one 'down' step (– a free, natural stride taken with the leg swinging in the same manner as in walking and with the heel making first contact with the ground) followed by two 'up' steps, taken with the legs extended and with the toe making first contact with the ground. Whether the dancers actually achieve different 'heights', as in the English or slow waltz (with the dancers remaining on the ball of the foot during the 'toe' steps), or remain level due to the need for rapid rotation in the quicker Viennese waltz does not change the fundamental pattern of a heel stride followed by two toe steps. This down-up-up pattern is matched by the music, whether you want to think of vertical inclination or perhaps weight: heavy-light-light, or any other approriate metaphor.
The Foxtrot is a dance danced in 4/4 consisting of a 'heel' stride over the first two beats, followed by two 'toe' steps on the third and fourth beats (if you have ever learnt the style taught by the Fred Astaire™ school of ballroom dancing then sadly what is called the Foxtrot is a strange modification in which the pattern of steps repeats every 6 beats, not every four; please put this from your mind). A foxtrot is normally danced to big band swing – think your big Sinatra numbers – which don't always have a down/up or heavy/light emphasis between the first beat of the bar and the remaining beats; however your examples of "Our House" and "For No One" are instantly recognisable to me as a Foxtrot rhythm, and probably would have been widely recognised as such certainly at the Beatles' time when ballroom dance styles were still part of the cultural memory.
Regarding other replies, a polka of course is a dance in 2/4 consisting of two quick steps followed by a slow step (followed by the same in the other direction), often slightly 'swung' in rhythm https://en.wikipedia.org/wiki/Polka. I don't see that as being at all a good fit for this question.
Edited to add: Dancing a polka can feel quite similar to dancing a Viennese waltz, and with good reason. However the polka dances the steps quicker than the waltz (you could perhaps write it "OM (pa)-pah - OM (pa)-pah"), whereas a Foxtrot dances them slower: OM - ? - pah - pah (– of course the musicians need something to do in that second beat!)
Answer: Certainly "waltz style" or "waltz accompaniment" etc. will be understood generally to be "bass chord chord" but it isn't a perfectly clear meaning.
I think historical period for various styles and basic variations of the patterns need to be considered when thinking about what label is appropriate.
Mozart wrote various dances and sometimes you can find "bass chord chord" patterns, but it wouldn't be appropriate to call that "waltz style". I found a collection of pieces titles "waltzes" by Clementi and they use many accompaniment patterns that are not "bass chord chord." Chopin's Mazurka's have many "bass chord chord" patterns, but they aren't waltzes.
There is a similar problem with using the term "stride." That's a particular jazz piano style. You might not want to use that term if the music isn't jazz. It's not some music theory sin, but it could give the wrong impression of the intended style.
I have thought that "polka style" would be a good label for waltz style in duple time. But the trouble with that is you might not want to suggest polka if the music isn't really a polka.
I don't think there is a problem with skipping the concern about how many "chords" are counted and just say "bass chord" accompaniment. If the meter is triple, it seems clear enough the pattern will be "bass chord chord" and if duple it's either "bass chord bass chord" or "bass chord chord chord."
The other thing, which ultimately I think is best, is just name the dance form intended. If it's a polka, call it "polka style". If it's a march, ecossaise, etc. just call it by that dance form. If it is not one of those well known dance styles, "bass chord" or "om pah" seems clear about what to play while stylistically and metrically neutral.
Answer: Example A might be called a 4/4 vamp, 'oom-pah' or 'boom-chick'.   If it's all done in the left hand on keyboard, example B, it's 'stride'.
The one you're asking about, C, could be called 'boom-chick-chick-chick' or (as you suggest) 'oom-pah-pah-pah' I suppose.   As far as I know there's no more respectable name for it!
Answer: I've heard it called the Oom-pah-pah just like for a waltz. Another name (I think there are several) is "boom-chick" accompaniment.
Comment: hmm what about polka? I did some more research and polka seems to fit this almost. Modified polka?
Comment: "Oom pah", Stride, Polka, etc., both have an "Oom" on 1 and 3.  OP's question suggests that there's only one Oom, on 1, a less common pattern.
Comment: I don't think there's a specific name for it. There are Oom-pah bands - especially in Germany - and I dare say they cut loose and play Oom-pah-pah-pah occasionally (on feast days, bank holidays etc.) but I've never heard a name for that pattern.
Comment: Btw, Stride is only a *piano* technique, I think: the left hand playing Low note - high chord, low note - high chord.
Answer: Stride is one way of putting it. In general, accompaniments that are based around one bass note and then a chord or two above it (for example, a polka that goes (C Eb-G -> G Eb-G)xF or a waltz that goes (C Eb-G Eb-G -> G Eb-G Eb-G)xF ) I have heard referred to as boom-chuck. What you are describing seems like an unconventional boom-chuck. Not bad by any means, just seen less frequently than the other two described

Om - pah - pah - pah


RPM 4.8.0 and 'Prereq'

Question: I am trying to install a large set of very old packages with rpm 4.8.0, and the transaction order is resulting in an installation failure.
Specifically,

I have a package (tzdata) that says: Prereq: /bin/cp
'/bin/cp' is in 'coreutils'

Yet 'coreutils' is still after tzdata in the installation order.
Looking at the source (rpm 4.8.0) I can see that the design in this area has changed a lot but it seems like the intent is that the old 'Prereq' flag is still supported.
<code>/* map legacy prereq to pre/preun as needed */
if (isLegacyPreReq(dsflags)) {
    flags |= (teType == TR_ADDED) ?
             RPMSENSE_SCRIPT_PRE : RPMSENSE_SCRIPT_PREUN;
}
</code>
Does that sound right?
Based on the code comments, I also get a strong sense that provide/require relationships will sometimes be ignored in order to eliminate dependency loops.  I would like to know if/when this is happening, but it doesn't seem like there are any messages emitted, even at debug level, for such an event ('dropping' a relationship).
Can anyone suggest how to generate and/or interpret debug information in the transaction output to understand why this particular ordering clue is not observed?
Comment: [This](https://gist.github.com/deryni/30afd029c30de0f04377) python script should (assuming it works correctly on 4.8.0 I wrote it against 184.108.40.206) show you the pre-reqs for the package you put on the command line. Change the loop at the bottom to print all the pre-reqs. Not sure if that'll help or not though. (I'm sort of astonished that packages as old as you claim can install correctly at all.)
Answer: The code in rpm-4.8.0 has chosen to remap Prereq: (which tries
to force a package installation before current package) as if
it were a Requires(pre): (which marks a require dependency needed
by a %pre scriptlet)contrary to what was originally implemented in rpm.
Yes: dependency loops will be dealt with "best effort" so that an
installation doesn't halt with dependency loops. One crude way to handle loops is to
discard all dependencies in a loop. Another, better, way yo handle loops is to attempt to
install all packages in the loop as a single entity. In both cases
the order determined by the dependencies in a loop is indeterminate and issues
like you are reporting can/will happen.
Installing with rpm -Uvv displays LOOP messages for all dependencies
that are ignored. Verify whether you have a LOOP that includes packages
involved with installing tzdata.
Meanwhile, using 2 transactions to guarantee the installation of a known prerequisite,
or using a hand crafted/ordered package manifest with --nodeps/--noorder during the installation, is
likely going to be your best work around to packaging flaw(s) and a change
in the semantics/implementation of Prereq: in rpm.

RPM 4.8.0 and 'Prereq'


Is this a valid proof that $A\cup\left(B\cap C\right)\,=\left(A\cup B\right)\cap\left(A\cup C\right)?$

Question: I'm an undergraduate taking a course in discrete mathematics and I recently ran into this problem on my homework:

Prove $A\cup\left(B\cap C\right) = \left(A\cup B\right)\cap\left(A\cup C\right)$

I ended up coming up with two proofs, the first is correct and not that interesting, but my second attempt was different. It is:

Proof: Let $P,Q,$ and $R$ be predicates defined:

$P\left(x\right)=x\in A$
$Q\left(x\right)  =  x\in B$
$R\left(x\right)  =  x\in C$

By substitution and the definitions of intersection and union, we can
rewrite $A\cup\left(B\cap C\right)$ as a logical equivalence:
$$P\left(x\right)  \lor\left(Q\left(x\right)  \land R\left(x\right)\right).$$
Applying the same logic to $\left(A\cup B\right)  \cap  \left(A\cup C\right)$ gives:
$$\left(P\left(x\right)\lor Q\left(x\right)\right)  \land\left(P\left(x\right)\lor R\left(x\right)\right).$$
Now suppose $n  \in  \mathbb{U},$ then $n  \in A\cup\left(B\cap C\right)$    iff $P\left(n\right)  \lor\left(Q\left(n\right)  \land R\left(n\right)\right)$.
Similarly, $n  \in\left(A\cup B\right)  \cap  \left(A\cup C\right)$  iff $\left(P\left(n\right)\lor Q\left(n\right)\right)  \land\left(P\left(n\right)\lor R\left(n\right)\right).$
Finally, notice that:
$P\left(x\right)  \lor\left(Q\left(x\right)  \land R\left(x\right)\right)\equiv\left(P\left(x\right)\lor Q\left(x\right)\right)  \land\left(P\left(x\right)\lor R\left(x\right)\right)$  by Distributive Law.
Therefore,  $A\cup\left(B\cap C\right)  =\left(A\cup B\right)\cap\left(A\cup C\right)$
$\square$

My thought process here was that I could substitute the set operations for their logical definitions. I haven't really been able to figure out if this proof is any good or not but I feel like I might at least be onto something.
Comment: $$\text{Why type like this?}$$
Comment: Sorry about that, I'm new to LaTex as well as set theory.
Answer: I don't know if setting up a simple set theory proof using logical tautologies is "interesting" or "boring". The stanbard proof would be a simple "two inclusions" proof with some case distinguishing for the unions.
I think that would be the text book's idea of how the proof ought to be done.
So ask yourself: what's goal of this exercise?
Comment: Why would you do it that way?  If you allow reasoning about elements, why not use logical equivalence and extensionality, like @M.F.? Alternatively, if you insist on set algebra and antisymmetry, you get a nice little exercise, but not an especially simple proof.
Answer: The conventional strategy sufficient to verify that two sets $\mathcal{A}$ and $\mathcal{B}$ are equal is:
$$x \in \mathcal{A} \Leftrightarrow x \in \mathcal{B}.$$
In this way, the case cited by you is enough to do:
\begin{eqnarray*}
x \in A \cup (B \cap C) & \Leftrightarrow & x \in A \ \ \mbox{or} \ \ x \in B \cap C\\
& \Leftrightarrow & x \in A \ \ \mbox{or} \ \ (x \in B \ \ \mbox{and} \ \ x \in C)\\
& \Leftrightarrow & x \in (A \ \mbox{or} \ B) \ \ \mbox{and} \ \ x \in (A \ \mbox{or} \ C)\\
& \Leftrightarrow & x \in (A \cup B) \cap (A \cup C).
\end{eqnarray*}


Closed point problems in $l$-spaces, namely $ l^1$ and $l^\inf$

Question: a) Give an example of a closed convex set $C$ and point $x$ in $l^\infty$ such that the closed point in $C$ to $x$ is not unique.
Solution: So I was thinking that a closed convex set would be the union of two closed balls in $l^\infty$ with a shared face as these will be cubes which are convex structures.
Let $C = \bar B(x,1) \cup \bar B(y,1)$; where $x = (0,0,...)$ and $y=(2,2,..)$
Consider $x= (-2,4,-2,4,-2,...)$ then $x \in l^\infty$
Then $\left\lVert x-(1,1,1,...) \right\rVert_\infty = \left\lVert x-(1,1/2,1,1/2...) \right\rVert_\infty = 3$ is are both the closest points to x where $\left\lVert \cdot \right\rVert_\infty = sup_{n \in \mathbb N} \lvert c_n \rvert $
I feel like this isn't a sufficient answer so I'm wondering what else I might need to show.
b) Show there is no closest point to $0$ in $C$ = {${x \in l: f(x) = 1}$} where $f:l^1 \rightarrow \mathbb R$ and $f(x) = \sum_{n=1}^\infty (1-1/n)x_n$
I'm not so sure how to go about this.
Suppose there was $y \in C$ such that $\lvert f(x) \rvert = \left\lVert x \right\rVert_1$ then this would be the closest point to $0$ in $C$ and so this would mean $\left\lVert x \right\rVert_1 = \sum_{n=1}^\infty \lvert x_n \rvert = 1$.
But in that case we have $\sum_{n=1}^\infty \lvert x_n \rvert = \lvert \sum_{n=1}^\infty (1-1/n)x_n \rvert$
And then I'd argue that this equality is never satisfied?
Answer: I have the impression that you are looking in the right direction, but your ideas are not really getting anywhere.
Regarding a), your set $C = \overline B(x,1) \cup \overline B(y,1)$ with $x = (0, 0, \ldots)$ and $y = (2, 2, \ldots)$ is not convex, because the two cubes don't share a face. Consider for example the points $r = (1,0,0,\ldots)$ and $s = (2,1,2,2,\ldots).$ We have $r\in \overline B(x,1)$ and $s \in \overline B(y,1).$ Put
$$
t = \frac12 (a+b) = (\frac32,\frac12,1,1,\ldots).
$$
We have $t\notin \overline B(x,1)$ because of the first coordinate, and $t\notin \overline B(y,1)$ because of the second coordinate, and thus $C$ is not convex.
We could construct an example using two cubes that share a face, but it's simpler to use just one cube. Put
$$
E = \overline B(x,1).
$$
Then $E$ is closed and convex. Put
$$
z = (3, 0, 0, \ldots).
$$
Please convince yourself that $dist(E,z) = 2$ and
$$
\{u = (u_1,u_2,\ldots) \in E | \|u-z\|_\infty = 2\} = \{(1,u_2,u_3,\ldots) | |u_j| \leq 1\ for\ j\in \{2,3,\ldots\}\}.
$$
This is a face of the cube $E,$ and certainly contains more than one element.
On to b). Let's put
$$
\varphi_n =1-\frac1n\quad for\ n\in \{1,2,\ldots\}.
$$
Then we consider the space $l^1$ and the linear map
$$
f:l^1\rightarrow \mathbb R, x = (x_1,x_2,\ldots) \mapsto \sum_{n=1}^\infty \varphi_n x_n.
$$
$f$ is nonzero, and it's "easy to see" that $f$ is continuous (use the fact that $0\leq\varphi_n \leq 1).$ This implies that the set
$$
G = f^{-1}(\{1\}) = \{ x \in l^1 | f(x) = 1\}
$$
is a closed, affine hyperplane ("affine" means "not passing through $0$"). Since affine hyperplanes are convex, $G$ is convex. Since $G$ is closed and $0\notin G,$ we must have
$$
dist(G,0) = \inf\{x\in G|\|x\|_1\} > 0.
$$
I have no idea about the exact value of that distance.
Now you want to argue that if we had a $y\in G$ with
$$
dist(0,y) = \|y\|_1 = f(y) = 1,
$$
we would get a contradiction. However, I can't see how to prove the existence of such a $y.$ Here's another argument.
Assume that we have a $u = (u_1,u_2,\ldots) \in G$ nearest to $0,$ i.e.
$$
dist(u,0) = \|u\|_1 = dist(G,0).
$$
Put
$$
v = (0,\frac{\varphi_1}{\varphi_2}u_1,\frac{\varphi_2}{\varphi_3}u_2,\ldots).
$$
From
$$
0\leq \varphi_n < \varphi_{n+1}\quad for\ n\in\{1,2,\ldots\},
$$
and $v\neq 0,$ we can infer
$$
\|v\|_1 < \|u\|_1.
$$
Note the strict inequality. Moreover, we compute
$$
f(v) = \sum_{n = 1}^\infty \varphi_{n+1}\frac{\varphi_n}{\varphi_{n+1}}u_n = f(u) = 1,
$$
and so
$$
v \in G.
$$
Now we have
$$
dist(G,0) \leq dist(v,0)= \|v\|_1 < \|u\|_1 = dist(u,0) = dist(G,0).
$$
That's a contradiction. So, in fact, there's no point in $G$ nearest to $0,$ i.e. of minimal norm, althoug (as noted above), $dist(G,0) > 0.$
Note: if you assume the existence of $u,$ there are other ways to arrive at a contradiction besides the "weighted shift" used above. For example, it's enough to "appropriately manipulate" just two coordinates of $u.$
Comment: Thank you very much for your thorough response. I was thinking just looking at your b) response that  $\sum_{n=1}^\infty \phi_n x_n \le \sum_{n=1}^\infty x_n = \lVert x \rVert_1$. But there are no values where the equality holds, It is nearly equivalent when n tends to infinity and then $ \phi_n$ tends to 1. So this might be the contradiction we are looking for.


OfficeJS Excel Sample error ( _host_Info=Excel )

Question: I am trying  to use example with shared folder like this
https://github.com/OfficeDev/office-js-docs/blob/master/docs/excel/build-your-first-excel-add-in.md
but got a strange error
cannot find
file://ff/?_host_Info=Excel$Win32$16.01$en-US.
make sure the path or Internet address is correct
Office version 1701 (7066.2092) Desktop Excel32
Answer: You should use a web server (local IIS instance, or a node-based dev hosting server, etc.) instead of serving the files off of the file system.
You need the file share for sideloading the manifest on Desktop, but the actual files should be served off of https://localhost:XXXX.
For what it's worth, if you're just starting with playing around with the Excel APIs, might I recommend Script Lab, a playground experience for learning and trying out the APIs.  It actually has that very same "Getting Started" sample (slightly modified and TypeScript-ified):

Hope you find it useful!
Comment: I did it   But it is workaround . And i need decision for my situation.
   - use shared folder it's one of availabale method to create AddIn .
Comment: You will need a web server to host the add-in's web content.  The manifest can be sideloaded via a network share, but you need a genuine web environment for the web files.


Visual Studio says, "Unable to read the project file" when opening a project from Source-Gear Vault

Question: I am using Visual Studio Express (v4.0.30319) singing to the tune of Visual Basic, and I'm using Source-Gear for my source control Visual Studio integration.
When I open a project I have to do it via the source control menu, and when it opens I get a warning message: "Unable to read the project file 'RemotingClasses.vbproj'."
After clicking the okay button, everything seems to work fine with the padlocks and checking out files, but I really don't like that I can't open a project from the splash screen, and that error box looks really bad in front of clients, who are inclined to panic at the very sight of the "E" word (error, that is)
...Fatal or not ^_^
Can I get rid of it?
Comment: Source Gear doesn't list Visual Studio Express on its [compatibility list](http://www.sourcegear.com/vault/documentation/compatibility_chart.html). Perhaps that is part of the issue.
Answer: Source Gear is not compatible with Visual Studio Express


How to delete from database

Question: Ok guys from my code, I could update the edited record by pressing submit button and use this
$action =(isset($_POST['submit']) ? $_POST['submit'] : null);
if($action!=null) {
    $id =(isset($_POST['id']) ? $_POST['id'] : null);

    $query="update club set adminApprove='Y' where id=$id";
    $result=mysql_query($query);

    echo "

Club record has been updated
";

    echo mysql_error();

So how can I create something like this to delete from database? Thank You
Comment: You need to write delete query to delete something from the database.
Comment: `.php?id=0+or+id<>0` - use a parametrized query
Comment: Did you even bother Googling "delete mysql php"?
Answer: $query = "DELETE FROM club WHERE id = $id";
$result = mysql_query($query);

echo "

Club record has been DELETED!
";

Answer: DELETE FROM table_name
WHERE some_column = some_value

http://www.w3schools.com/php/php_mysql_delete.asp
Answer: $query = "DELETE FROM table_name WHERE id=$id";
$result=mysql_query($query);

How to delete from database


Convert a string to python quantity

Question: In one of my projects I'm using the quantities package to represent physical quantities. These quantities have to be stored in the metadata of pngs where they must be readable by other programs and by my own program. Thus, the quantities must be stored as string (requirement of png metadata) and it would be best to store it in a human-readable format.
While the package quantities provides conversation from quantities to string, there seems to be no readily available method to parse these strings back to a quantity. The strings generated by the quantities package are, e.g.,
1.3 nm
[1.4 3.1415 5.2] kg/m**2

Is there an easy way to convert these strings back to a quantities.Quantity?
Comment: When looking for answers to the above question I came across [this](https://stackoverflow.com/questions/13611851/converting-string-to-physical-quantity-object-in-python) question, which probably is the same thing but unfortunately the question is closed and the answers are not fitting all my needs.
Comment: There's very little point to a self-answered question so vague that: 1. Anyone else with a similar problem would struggle to find it; and 2. Nobody else could answer even if there's a better way to do it.
Comment: I don't understand your point @jonrsharpe. When I had this problem, I've been searching stackoverflow and I came across the question mentioned in my comment. Unfortunately, the answers there have not been satisfying, so I came up with my own solution. I then wanted to share this solution with the one asking the original question b/c I thought other people may have the same problem. As the original question was closed, I had to ask a new question to share the solution. What should I've done differently?
Comment: For starters, the PNG is irrelevant. Next, you don't actually show the string you're trying to parse, nor explain how it ended up in that format. Finally, your answer just boils down to *"separate number and units, parse number to float and pass float and units to initialise"*, and that seems trivial enough to not warrant this effort.
Comment: The package `pint` could suit your needs: http://pint.readthedocs.org/en/0.6/
Comment: @mmj My program is only part of a bigger project and I have to use quantities. But at first glance, pint looks very interesting.
Comment: @jonrsharpe Thanks for the feedback. I tried to give some more information. Of course, once you know the solution, it is fairly easy.
Answer: I tried the following code and I think it should work for most cases.
import quantities as pq
import numpy as np

def str2pq(s):
    p1 = s.find('[')
    if p1 < 0:
        sq, su = s.split()
        return pq.Quantity(float(sq), su)
    else:
        p2 = s.find(']')
        ss = s[p1+1:p2-1]
        return pq.Quantity(np.array(list(map(float, ss.split()))), s[p2+1:])

q = [pq.Quantity(10, 'nm'), pq.Quantity(1.0, pq.kilogram/pq.meter**2), pq.Quantity(np.array([1.2, 3.4]), pq.kilohertz)]
qs = list(map(str, q))
qret = list(map(str2pq, qs))
print(q)
print(qret)

Convert a string to python quantity


MS365: Sending encrypted to remote tenants occasionally fails with "user not in tenant"

Question: We are attempting to replace a secure email gateway solution with MS365's inbuilt email message encryption.
We have a mail flow rule set up to force encryption from a specific sending address to any recipient, as follows:

CONDITIONS:
Apply rule if:
Sender is 'firstname.lastname@example.com'
Do the following:
Modify message security - Apply Office 365 Message Encryption and rights protection

Rights protect message with 'Encrypt' (default Encrypt policy)

Now, when we send from alwaysencrypt - which is a Business Basic  licensed account in this tenant - we have odd results.

When sending to a non-MS365 account/tenant/domain, email messages are property delivered and require an OTP code to be sent to validate access.  This works fine.
For some MS365 tenant recipients but NOT part of the origin tenant, rights management works properly and properly identifies this external tenant as a recipient and the user is allowed access.
For other MS365 tenant recipients who are NOT part of the origin tenant, the system does not allow their user to login and use MS365 tenant auth to access the document and fails with a message akin to Selected user account does not exist in tenant 'Example Tenant' and cannot access the application 'UUID' in that tenant. The account needs to be added as an external user in the tenant first. Please use a different account.

It's very new that we have this third option happen, and MS365 does NOT offer external tenants the OTP code option.
I don't see a way to address this and permit access to the rights system to external tenants without adding them manually to our origin tenant, and this is a problem because this is an automated system sending encrypted message data as part of alerting systems to external recipients.
Has anyone seen this and does anyone have any idea how we can resolve this to force it to NOT use MS365 tenant authentication for access to encrypted messages and be only OTP-code verification if they are outside the organization?
I should note that MS365 is now forcing the use of Microsoft Purview so the legacy OME solutions will not function, and there's zero documentation on how to alter this or make these revisions as needed.
Note that I have access to a Global Admin on the origin tenant so I SHOULD have access to all the Powershell options if needed.
Comment: This is one of those complex problems that I would open a support case from your tenant for. It's free.
Comment: @joeqwerty thank you though for the help, it just took 12 hours for me to dig into the documentation to find it >.>  And then ten seconds to convince the powers that be to spend the fifty cents xD
Comment: Actually I think this is self-resolved after spending 12 hours in Microsoft's documentation.  I discovered that Business Basic doesn't have Microsoft Purview for the encryption entitlement.  There's an Azure Information Protection plan that's extra on top of Business Basic to allow encryption.  We're test-running this to see if that fixes this issue.
Comment: Ah, I didn't catch that you were using Business Basic. For what it's worth, a Microsoft 365 F1 license will give you AIP and Azure AD P1 (now named Microsoft Entra ID P1), as well as some other things at a cost of $2.25 per user/per month. - https://www.microsoft.com/en-us/microsoft-365/enterprise/f1
Comment: @joeqwerty yeah, well for the tenant in question we have (nearly) unlimited Business Basic as a non-profit, and have been using those for service accounts or cases where we need a send/receive mailbox but no actual need for Microsoft apps - this `alwaysencrypt` is an example of such an account.  Under the nonprofit license though it's like $0.50/month/license for AIP P1 so problem solved.  AAD P1 is already included on our tenant with our wide mix of 365 Bus Basic, E1s, E3, and E5 licenses in the tenant, we just didn't want to have to get *another* E3 license at $5/month to get it. :)
Comment: Happy to add my two cents.
Answer: So, in fact, it turns out this isn't a "tenant" issue at all, but a licensing one.  Which is not straight-forward to find in the documentation, because the basic Purview pages don't even reference this, it's only in the FAQ which you don't see when you try and debug encryption stuff.
Buried here in the Microsoft Purview OME documentation in the FAQ (but NOT anywhere else on the Purview documentation), it indicates what plans Purview is automatically supported in:

To use Microsoft Purview Message Encryption, you need one of the following plans:

Microsoft Purview Message Encryption is offered as part of Office 365 Enterprise E3 and E5, Microsoft 365 Enterprise E3 and E5, Microsoft 365 Business Premium, Office 365 A1, A3, and A5, and Office 365 Government G3 and G5. You don't need additional licenses to receive the new protection capabilities powered by Azure Information Protection.

You can also add Azure Information Protection Plan 1 to the following plans to receive Microsoft Purview Message Encryption: Exchange Online Plan 1, Exchange Online Plan 2, Office 365 F3, Microsoft 365 Business Basic, Microsoft 365 Business Standard, or Office 365 Enterprise E1.

Each user benefiting from Microsoft Purview Message Encryption needs a license to use message encryption.

Unfortunately, this is NOT listed on the MS365 plans pages, and not detailed in any of the other documentation about MS365 plans - at least, not anywhere obvious.
We obtained a license for Azure Information Protection Plan 1 as indicated and attached it to the alwaysencrypt user in the origin tenant.  After giving Microsoft time to apply this change and the AIP service to the origin tenant, it works as expected and external tenants can now view the messages, as can non-MS365 recipients as well.
Microsoft has scored a -1 on their documentation today, but at least we resolved this with a simple solution: throwing more money at Microsoft.


In the theorem of coincidence of $R$ and $L$ integrals: are we assuming the $\Bbb L$ $\sigma$-algebra? If not, how to prove the measurability of $f$?

Question:
Theorem:
If $f: [a,b] \to \Bbb R$ is Riemann-integrable, then $f$ is Lebesgue-integrable, and:
$$ \int_a^b f(x) dx = \int_{[a,b]} fd\lambda$$

Here is the proof: (assuming that we know that step functions are Lebesgue integrable and that their Riemann integral coincides with their Lebesgue one)
The Riemann-integrability of $f$ implies the existence of two sequences of step functions $(g_n) \uparrow$ and $(h_n) \downarrow$, such that $g_n \le f \le h_n$ for all $n$, and:

$\int_a^b (h_n(x) - g_n(x))dx \to 0$ $(\star)$

$\int_a^b f(x) dx = \lim \int_a^bg_n(x)dx$

It is easy to see that $(g_n)$ and $(h_n)$ converge pointwise to some $g$ and $h$ $\in L^1$ (respectively).
Letting $\gamma = |g_1| + |h_1|$, we get that $h_n - g_n \le \gamma$ for all $n$, and $\gamma \in L^1$ being the sum of two $L^1$ functions. Moreover, $h_n - g_n \to h - g$ is a sequence of $L^1$ functions converging to an $L^1$ function. Therefore, by LDCT, we get:
$$\int_{[a,b]} (h_n - g_n) d \lambda \to \int_{[a,b]} (h - g) d \lambda$$
Which implies that:
$$\int_{[a,b]} (h - g) d \lambda = 0$$
Hence $h - g = 0$ $\lambda-$a.e. since it is $\ge 0$, i.e. $h = g$ $\lambda-$a.e.
Now, $g \le f \le h$, hence $f = g$ $\lambda-$a.e.
But from this, we can only conclude that $f$ is measurable with respect to the Lebesgue $\sigma-$algebra on $[a,b]$, and not the Borel one.
Are we assuming the Lebesgue $\sigma-$algebra on $[a,b]$? If not, how can we prove that $f$ is measurable?
The rest of the proof becomes straightforward.
Comment: When you construct the Lebesgue integral, you assume that you are working with the Lebesgue $\sigma$-algebra on $[a,b]$.
Comment: I don't remember about explicit sources (I think Bartle's book "Elements of Integration" is a good choice), but when you speak about Lebesgue integral, you consider Lebesgue-measurable functions, that is, functions $f:[a,b]\to\mathbb{R}$ such that $f^{-1}(A)$ is Lebesgue-measurable for all Borel-measurable subset $A$ of $[a,b]$.
Comment: @ÁngelValencia: That's a common approach, but it's not universal: it's entirely possible to define the Lebesgue integral by only working with Borel-measurable functions.
Comment: @AngelValencia: our professor did not assume that, instead, we always talk about measurability with respect to the Borel $\sigma-$algbera; this is the source of my confusion. Can you give me some reference where this is explicitly stated? I searched the internet in vain.
Answer: A Riemann-integrable function is not necessarily Borel, see A Riemann integrable function $f$ on a bounded interval $[a, b]$ is measurable with respect to the Borel measure on $[a,b]$?
So you are going to have to assume you are working with the Lebesgue $\sigma$-algebra if you want to get a true theorem.
Comment: Thank you. Do you have in mind a good reference in which there is an elaborative construction of the Lebesgue integral?
Comment: @AhmedHussein: Honestly, that describes every book on basic measure theory.  Royden's book is nice and focuses on $\mathbb{R}$; Folland is another nice book but works on abstract measure spaces.
Comment: Heh. If you'd asked me I would have said a Riemann integrable function was Borel. Clearly not, the example is very simple. Something new every day...


Calculate and display value in the last td

Question: Goal:
Calculate and display right answer in the last td in the tr by selecting row(s). For instance, if I choose the second row, I would get value 44 and it should be applied in the last td of the row.
Problem:
I know how to do it in javascript but in jQuery.
Need help with the source code in jQuery.
// fullmetalboy

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

        <title>index</title>

    <INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />

    <INPUT type="button" value="Calculate selected row" onclick="deleteRow('dataTable')" />

            <INPUT type="checkbox" name="chk"/>
            1
            22

Comment: The question is too vague, you don't have 2 rows and if you added one I would assume you want to display the total so far of the third column in the last td of the tr you selected. But there are too many assumptions to really answer your question.
Answer: You could do (you can check more than one columns and the result is calculated for each row):
$(document).ready(function(){
    $('#calculate').click(function(){
        $('input:checkbox:checked').each(function(){
          var first = parseInt($(this).closest('td').next('td').text(), 10);

         var sec = parseInt($(this).closest('td').next('td').next('td').text(), 10);
            var result = (first*sec);
            $(this).closest('tr').find('td:last').html(result)

        });
    });
});

Fidlle here: http://jsfiddle.net/D2uVz/


Javascript object array. It's keep on over writing the first element

Question: I need to make an Object with name, id, and amount
var sales = {
             Name:"",
             ID:"",
             Amount: []
             };

var emp = new Array();

// Creating 10 arrays of sales objects
for (var a=0; a < 10; a++) {
    emp[a] = Object.create(sales);
}

in the amount I need to enter 4 values for e.g ($5435.90, $234.03, $6563.56, $1234.54)
when i do like this
var i=0;
for(var x=0; x<10; x++) {
emp[i].Amount[c] = Number(prompt("Enter amount:"));
i++
}

When i run that first entire works fine.. but the second entire going back and over writing the first element..
For example if i enter like this
1) 534, 574, 9767, 345
its stores fine in the
emp[0].Amount[0] = 534
emp[0].Amount[1] = 574
emp[0].Amount[2] = 9767
emp[0].Amount[3] = 345

2) 345, 6574, 545, 1234
emp[1].Amount[0] = 345
emp[1].Amount[1] = 6574
emp[1].Amount[2] = 545
emp[1].Amount[3] = 1234

at the end it changes the first array to the second one
emp[0] and emp[1] are same value
please help.. its 3:47AM
and i been working on this since 9PM
i hope u understand what i am trying to say.. :)
Comment: Please post more complete code.
Comment: adding jsfiddle(or any other collaboration site) would make life easier
Comment: One time it's `Amount`, then `salesAmount`, then `saleAmount`... Please be coherent if you want to avoid errors. And `c` doesn't exists, you should use `push` method instead.
Answer: Try changing var sales to

Comment: You should add that `emp[a]` now must be `new sales()` instead of `Object.create(sales)`.
Answer: You are creating an Amount array inside sales and changing saleAmount after.
This code worked for me:
var sales = {
         Name:"",
         ID:"",
         Amount: []
         };

var emp = [];

// Creating 10 arrays of sales objects
for (var a=0; a < 10; a++) {
emp[a] = Object.create(sales);
}

for(var x=0; x<10; x++) {
     for (var i = 0; i < 4; i++){
         emp[i].Amount[x] = Number(prompt("Enter amount:"));
    }
}

Comment: 1) `i` and `x` confused in inner loop, must be `emp[x].Amount[i]`. 2)It doesn't help, each Amount-array is overwritten with the last values.
Answer: Object.create creates a new object and sets its [[Prototype]] to the provided Object. So when you do:
for (var a=0; a < 10; a++) {
    emp[a] = Object.create(sales);
}

all of the Objects created have the same [[Prototype]], so they all share the same Name, ID and Amount properties.
To create instances of Sales, do:
function Sales(name, id, amount) {
  this.Name = name;
  this.ID = id;
  this.Amount = amount;
}

var emp = [];

// Creating 10 arrays of sales objects
for (var a=0; a < 10; a++) {
    emp[a] = new Sales();
}

Note that in your code:
emp[i].salesAmount[c] = Number(prompt("Enter amount:"));

should be:
emp[i].Amount[c] = Number(prompt("Enter amount:"));

since instances don't have a salesAmount property.


Long chords in Lilypond

Question: How do I write chords that are longer that a "1" in Lilypond? For instance, below I have a chord that spans 12/4 and where I currently have made a hack with r1. (N.C.).
<<
  \new ChordNames {
    \chordmode {
      c1. r1. f1. r1.
    }
  }
  \new Staff {
    \numericTimeSignature \time 12/4 \key c \major
    \relative {c'1. d1. f1. a1.}
  }
>>

There should be no "N.C.". I have also tried c1. ~c1. f1. ~f1., but that displays the chord multiple times.
Answer: In LilyPond, the duration that takes up two whole notes is called \breve, therefore you can use c\breve. (a dotted breve). Four whole notes would be \longa and eight would be \maxima.
Another solution in this particular case is c1.*2. The *2 multiplier normally modifies the duration without modifying the appearance (e.g., c'4*2 looks like a quarter note but takes the duration of a half note). Obviously, this has no impact on chord names.
Answer: You can also use s (space) instead of r (rest). This will not produce N.C. in the context of ChordNames.
\new ChordNames {
  \chordmode {
    c1. s1. f1. s1.
  }
}

Long chords in Lilypond