Priorização em Hierarquia de resultado em uma view (Maior Registro e Ordem especifica dentro do maior registro)

Question: Estou montando uma estrutura dentro de uma view onde estou trabalhando com níveis mercadológicos (segmento do varejo). Seguindo essa ideia tenho um produto que pode conter mais de um registro vigente; pode conter, por exemplo, a seção A com 10% de desconto e a marca B com 15% e em uma linha a nível de produto um produto X com desconto de 8%.
Preciso que o Retorno seja caso eu selecione o Produto X o valor de desconto seja 8% (mesmo que dentro deste produto contenha a seção A, e Marca B).
Quando eu selecionar um produto da marca B deve retornar 15% (desde que não esteja cadastrado no mesmo registro na "aba" de produtos e independente se estiver cadastrado na aba de Seções).
Quando eu selecionar algum produto da Seção A, este produto não pode estar "dentro" da marca B e nem dentro das demais classificações.
Existem outras regras dentro da View que são mais tranquilas são não consegui resolver este ponto acima.
Lembrando que preciso sempre considerar o maior registro cadastrado Vigente entre o produto escolhido, e o menor nível mercadológico parametrizado.
A priorização é da esquerda para direita:
Produto / Marca / Classes / Subgrupo / Grupo / Seções
Segue view para quem topar dar um toque:
SELECT A.TABELA_DESCONTO             ,
       Z.PRODUTO                     ,
       A.TIPO_CALCULO_PRECO_PROMOCAO ,
       CASE WHEN A.TIPO_CALCULO_PRECO_PROMOCAO = 1
            THEN A.DESCONTO_PADRAO
            ELSE 0
       END                                              AS DESCONTO_PADRAO ,
       A.DATA_HORA_INICIAL,
       A.DATA_HORA_FINAL,
       CASE WHEN A.TIPO_CALCULO_PRECO_PROMOCAO = 2
            THEN A.LUCRO_BRUTO_TABELADO
            ELSE 0
       END                                              AS LUCRO_BRUTO_TABELADO,
       A.APENAS_CLIENTES,
       A.APENAS_CONVENIOS
    FROM TABELAS_DESCONTOS_SECOES    A WITH(NOLOCK)
    JOIN MAIOR_TABELA_DESCONTO       J WITH(NOLOCK) ON J.TABELA_DESCONTO = A.TABELA_DESCONTO
    JOIN PRODUTOS                    Z WITH(NOLOCK) ON Z.SECAO_PRODUTO    = A.SECAO_PRODUTO
    LEFT
    JOIN TABELAS_DESCONTOS_GRUPOS    C (NOLOCK) ON C.GRUPO_PRODUTO = Z.GRUPO_PRODUTO
    LEFT
    JOIN TABELAS_DESCONTOS_SUBGRUPOS D (NOLOCK) ON D.SUBGRUPO_PRODUTO = Z.SUBGRUPO_PRODUTO
    LEFT
    JOIN TABELAS_DESCONTOS_CLASSES   E (NOLOCK) ON E.CLASSE_PRODUTO = Z.CLASSE_PRODUTO
    LEFT
    JOIN TABELAS_DESCONTOS_MARCAS    F (NOLOCK) ON F.MARCA = Z.MARCA
    LEFT
    JOIN TABELAS_DESCONTOS_MARKUP    G (NOLOCK) ON G.PRODUTO          = Z.PRODUTO
    WHERE GETDATE() BETWEEN A.DATA_HORA_INICIAL AND A.DATA_HORA_FINAL
        AND ( ( DATEPART(DW, GETDATE() ) = 1 AND A.DOMINGO       = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 2 AND A.SEGUNDA_FEIRA = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 3 AND A.TERCA_FEIRA   = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 4 AND A.QUARTA_FEIRA  = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 5 AND A.QUINTA_FEIRA  = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 6 AND A.SEXTA_FEIRA   = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 7 AND A.SABADO        = 'S') )
        AND C.GRUPO_PRODUTO     IS NULL
        AND D.SUBGRUPO_PRODUTO  IS NULL
        AND E.CLASSE_PRODUTO    IS NULL
        AND F.MARCA             IS NULL
        AND G.PRODUTO           IS NULL

UNION ALL

SELECT A.TABELA_DESCONTO             ,
       Z.PRODUTO                     ,
       A.TIPO_CALCULO_PRECO_PROMOCAO ,
       CASE WHEN A.TIPO_CALCULO_PRECO_PROMOCAO = 1
            THEN A.DESCONTO_PADRAO
            ELSE 0
       END                                              AS DESCONTO_PADRAO ,
       A.DATA_HORA_INICIAL,
       A.DATA_HORA_FINAL,
       CASE WHEN A.TIPO_CALCULO_PRECO_PROMOCAO = 2
            THEN A.LUCRO_BRUTO_TABELADO
            ELSE 0
       END                                              AS LUCRO_BRUTO_TABELADO,
       A.APENAS_CLIENTES,
       A.APENAS_CONVENIOS
    FROM TABELAS_DESCONTOS_GRUPOS    A WITH(NOLOCK)
    JOIN MAIOR_TABELA_DESCONTO       J WITH(NOLOCK) ON J.TABELA_DESCONTO = A.TABELA_DESCONTO
    JOIN PRODUTOS                    Z WITH(NOLOCK) ON Z.GRUPO_PRODUTO = A.GRUPO_PRODUTO
    LEFT
    JOIN TABELAS_DESCONTOS_SUBGRUPOS D (NOLOCK) ON D.SUBGRUPO_PRODUTO = Z.SUBGRUPO_PRODUTO
    LEFT
    JOIN TABELAS_DESCONTOS_CLASSES E (NOLOCK) ON E.CLASSE_PRODUTO = Z.CLASSE_PRODUTO
    LEFT
    JOIN TABELAS_DESCONTOS_MARCAS F (NOLOCK) ON F.MARCA = Z.MARCA
    LEFT
    JOIN TABELAS_DESCONTOS_MARKUP  G (NOLOCK) ON G.PRODUTO          = Z.PRODUTO
    WHERE GETDATE() BETWEEN A.DATA_HORA_INICIAL AND A.DATA_HORA_FINAL
        AND ( ( DATEPART(DW, GETDATE() ) = 1 AND A.DOMINGO       = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 2 AND A.SEGUNDA_FEIRA = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 3 AND A.TERCA_FEIRA   = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 4 AND A.QUARTA_FEIRA  = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 5 AND A.QUINTA_FEIRA  = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 6 AND A.SEXTA_FEIRA   = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 7 AND A.SABADO        = 'S') )
        AND D.SUBGRUPO_PRODUTO  IS NULL
        AND E.CLASSE_PRODUTO    IS NULL
        AND F.MARCA             IS NULL
        AND G.PRODUTO           IS NULL

UNION ALL

SELECT A.TABELA_DESCONTO             ,
       Z.PRODUTO                     ,
       A.TIPO_CALCULO_PRECO_PROMOCAO ,
       CASE WHEN A.TIPO_CALCULO_PRECO_PROMOCAO = 1
            THEN A.DESCONTO_PADRAO
            ELSE 0
       END                                              AS DESCONTO_PADRAO ,
       A.DATA_HORA_INICIAL,
       A.DATA_HORA_FINAL,
       CASE WHEN A.TIPO_CALCULO_PRECO_PROMOCAO = 2
            THEN A.LUCRO_BRUTO_TABELADO
            ELSE 0
       END                                              AS LUCRO_BRUTO_TABELADO,
       A.APENAS_CLIENTES,
       A.APENAS_CONVENIOS
    FROM TABELAS_DESCONTOS_SUBGRUPOS    A WITH(NOLOCK)
    JOIN MAIOR_TABELA_DESCONTO       J WITH(NOLOCK) ON J.TABELA_DESCONTO = A.TABELA_DESCONTO
    JOIN PRODUTOS                    Z WITH(NOLOCK) ON Z.SUBGRUPO_PRODUTO = A.SUBGRUPO_PRODUTO
    LEFT
    JOIN TABELAS_DESCONTOS_CLASSES E (NOLOCK) ON E.CLASSE_PRODUTO = Z.CLASSE_PRODUTO
    LEFT
    JOIN TABELAS_DESCONTOS_MARCAS F (NOLOCK) ON F.MARCA = Z.MARCA
    LEFT
    JOIN TABELAS_DESCONTOS_MARKUP  G (NOLOCK) ON G.PRODUTO          = Z.PRODUTO
    WHERE GETDATE() BETWEEN A.DATA_HORA_INICIAL AND A.DATA_HORA_FINAL
        AND ( ( DATEPART(DW, GETDATE() ) = 1 AND A.DOMINGO       = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 2 AND A.SEGUNDA_FEIRA = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 3 AND A.TERCA_FEIRA   = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 4 AND A.QUARTA_FEIRA  = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 5 AND A.QUINTA_FEIRA  = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 6 AND A.SEXTA_FEIRA   = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 7 AND A.SABADO        = 'S') )
        AND E.CLASSE_PRODUTO    IS NULL
        AND F.MARCA             IS NULL
        AND G.PRODUTO           IS NULL

UNION ALL

SELECT A.TABELA_DESCONTO             ,
       Z.PRODUTO                     ,
       A.TIPO_CALCULO_PRECO_PROMOCAO ,
       CASE WHEN A.TIPO_CALCULO_PRECO_PROMOCAO = 1
            THEN A.DESCONTO_PADRAO
            ELSE 0
       END                                              AS DESCONTO_PADRAO ,
       A.DATA_HORA_INICIAL,
       A.DATA_HORA_FINAL,
       CASE WHEN A.TIPO_CALCULO_PRECO_PROMOCAO = 2
            THEN A.LUCRO_BRUTO_TABELADO
            ELSE 0
       END                                              AS LUCRO_BRUTO_TABELADO,
       A.APENAS_CLIENTES,
       A.APENAS_CONVENIOS
    FROM TABELAS_DESCONTOS_CLASSES    A WITH(NOLOCK)
    JOIN MAIOR_TABELA_DESCONTO       J WITH(NOLOCK) ON J.TABELA_DESCONTO = A.TABELA_DESCONTO
    JOIN PRODUTOS                    Z WITH(NOLOCK) ON Z.CLASSE_PRODUTO = A.CLASSE_PRODUTO
    LEFT
    JOIN TABELAS_DESCONTOS_MARCAS F (NOLOCK) ON F.MARCA = Z.MARCA
    LEFT
    JOIN TABELAS_DESCONTOS_MARKUP  G (NOLOCK) ON G.PRODUTO          = Z.PRODUTO
    WHERE GETDATE() BETWEEN A.DATA_HORA_INICIAL AND A.DATA_HORA_FINAL
        AND ( ( DATEPART(DW, GETDATE() ) = 1 AND A.DOMINGO       = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 2 AND A.SEGUNDA_FEIRA = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 3 AND A.TERCA_FEIRA   = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 4 AND A.QUARTA_FEIRA  = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 5 AND A.QUINTA_FEIRA  = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 6 AND A.SEXTA_FEIRA   = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 7 AND A.SABADO        = 'S') )
        AND F.MARCA             IS NULL
        AND G.PRODUTO           IS NULL

UNION ALL

SELECT A.TABELA_DESCONTO             ,
       Z.PRODUTO                     ,
       A.TIPO_CALCULO_PRECO_PROMOCAO ,
       CASE WHEN A.TIPO_CALCULO_PRECO_PROMOCAO = 1
            THEN A.DESCONTO_PADRAO
            ELSE 0
       END                                              AS DESCONTO_PADRAO ,
       A.DATA_HORA_INICIAL,
       A.DATA_HORA_FINAL,
       CASE WHEN A.TIPO_CALCULO_PRECO_PROMOCAO = 2
            THEN A.LUCRO_BRUTO_TABELADO
            ELSE 0
       END                                              AS LUCRO_BRUTO_TABELADO,
       A.APENAS_CLIENTES,
       A.APENAS_CONVENIOS
    FROM TABELAS_DESCONTOS_MARCAS    A WITH(NOLOCK)
    JOIN MAIOR_TABELA_DESCONTO       J WITH(NOLOCK) ON J.TABELA_DESCONTO = A.TABELA_DESCONTO
    JOIN PRODUTOS                    Z WITH(NOLOCK) ON Z.MARCA = A.MARCA
    LEFT
    JOIN TABELAS_DESCONTOS_MARKUP  G (NOLOCK) ON G.PRODUTO          = Z.PRODUTO
    WHERE GETDATE() BETWEEN A.DATA_HORA_INICIAL AND A.DATA_HORA_FINAL
        AND ( ( DATEPART(DW, GETDATE() ) = 1 AND A.DOMINGO       = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 2 AND A.SEGUNDA_FEIRA = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 3 AND A.TERCA_FEIRA   = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 4 AND A.QUARTA_FEIRA  = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 5 AND A.QUINTA_FEIRA  = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 6 AND A.SEXTA_FEIRA   = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 7 AND A.SABADO        = 'S') )
        AND G.PRODUTO           IS NULL

UNION ALL

SELECT A.TABELA_DESCONTO             ,
       Z.PRODUTO                     ,
       A.TIPO_CALCULO_PRECO_PROMOCAO ,
       CASE WHEN A.TIPO_CALCULO_PRECO_PROMOCAO = 1
            THEN A.DESCONTO_PADRAO
            ELSE 0
       END                                              AS DESCONTO_PADRAO ,
       A.DATA_HORA_INICIAL,
       A.DATA_HORA_FINAL,
       CASE WHEN A.TIPO_CALCULO_PRECO_PROMOCAO = 2
            THEN A.LUCRO_BRUTO_TABELADO
            ELSE 0
       END                                              AS LUCRO_BRUTO_TABELADO,
       A.APENAS_CLIENTES,
       A.APENAS_CONVENIOS
    FROM TABELAS_DESCONTOS_MARKUP    A WITH(NOLOCK)
    JOIN MAIOR_TABELA_DESCONTO       J WITH(NOLOCK) ON J.TABELA_DESCONTO = A.TABELA_DESCONTO
    JOIN PRODUTOS                    Z WITH(NOLOCK) ON Z.PRODUTO = A.PRODUTO
    WHERE GETDATE() BETWEEN A.DATA_HORA_INICIAL AND A.DATA_HORA_FINAL
        AND ( ( DATEPART(DW, GETDATE() ) = 1 AND A.DOMINGO       = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 2 AND A.SEGUNDA_FEIRA = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 3 AND A.TERCA_FEIRA   = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 4 AND A.QUARTA_FEIRA  = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 5 AND A.QUINTA_FEIRA  = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 6 AND A.SEXTA_FEIRA   = 'S') OR
              ( DATEPART(DW, GETDATE() ) = 7 AND A.SABADO        = 'S') ) ```

Answer: Sem as estruturas das tabelas e os dados, é mais complicado dar uma resposta incluindo suas tabelas e colunas, então vou apresentar duas abordagens para fazer o que você precisa mas de maneira mais genérica.
Pelo que entendi, sua tabela de produto relaciona com as tabelas de descontos e você faz filtros para indicar que quando ocorre uma regra, não deve considerar a outra, então usei essas informações para montar um exemplo:
create table secao (
  id int primary key,
  nome varchar(50) not null);

insert into secao (id, nome) values (1, 'Seção A'), (2, 'Seção B'), (3, 'Seção C');

create table marca (
  id int primary key,
  nome varchar(50) not null);

insert into marca (id, nome) values (1, 'Marca A'), (2, 'Marca B');

create table produto (
  id int primary key,
  id_secao int,
  id_marca int,
  nome varchar(50) not null,
  foreign key (id_secao) references secao(id),
  foreign key (id_marca) references marca(id));

insert into produto (id, id_secao, id_marca, nome) values (1, 1, 1, 'Produto SA-MA 1'), (2, 1, 1, 'Produto SA-MA 2'), (3, 1, 1, 'Produto SA-MA 3'),
(4, 1, 2, 'Produto SA-MB 1'), (5, 1, 2, 'Produto SA-MB 2'), (6, 1, 2, 'Produto SA-MB 3'), (7, 1, 2, 'Produto SA-MB 4'),
(8, 2, 2, 'Produto SB-MB 1'), (9, 2, 2, 'Produto SB-MB 2'), (10, 2, 2, 'Produto SB-MB 3'),
(11, 3, 2, 'Produto SC-MB 1'), (12, 3, 1, 'Produto SC-MA 2'), (13, 3, 1, 'Produto SC-MA 3'),
(14, null, null, 'Produto S-B 1');

create table desconto_produto (
  id int identity primary key,
  id_produto int not null,
  percentual decimal(5, 2),
  foreign key (id_produto) references produto(id));

insert into desconto_produto (id_produto, percentual) values (1, 0.08), (4, 0.02), (5, 0.06), (9, 0.15), (12, 0.10);

create table desconto_secao (
  id int identity primary key,
  id_secao int not null,
  percentual decimal(5, 2),
  foreign key (id_secao) references secao(id));

insert into desconto_secao (id_secao, percentual) values (1, 0.17), (3, 0.19);

create table desconto_marca (
  id int identity primary key,
  id_marca int not null,
  percentual decimal(5, 2),
  foreign key (id_marca) references marca(id));

insert into desconto_marca (id_marca, percentual) values (2, 0.23);

Os produtos de ids 1, 4, 5, 9 e 12 tem respectivamente desconto de 0.08, 0.02, 0.06, 0.15 e 0.10, as seções de ids 1 e 3 tem 0.17 e 0.19 e finalmente a marca de id 2 tem 0.23. Com base nisso você pode fazer:
select
   p.id
  ,p.nome nome_produto
  ,m.nome nome_marca
  ,s.nome nome_secao
  ,coalesce(dp.percentual, dm.percentual, ds.percentual, 0) desconto_selecionado
  ,dp.percentual percentual_produto
  ,dm.percentual percentual_marca
  ,ds.percentual percentual_secao
from
  produto p with(nolock)
  left join marca m with(nolock) on (p.id_marca = m.id)
  left join secao s with(nolock) on (p.id_secao = s.id)
  left join desconto_produto dp with(nolock) on (dp.id_produto = p.id)
  left join desconto_marca dm with(nolock) on (dm.id_marca = p.id_marca)
  left join desconto_secao ds with(nolock) on (ds.id_secao = p.id_secao);

Nessa consulta, relacionei o produto com todas as tabelas de descontos, porém para exibir o percentual de desconto, considerando a regra produto > marca > seção, usei o coalesce, o que ele faz é retornar o primeiro valor não nulo de acordo com a ordem dos parâmetros passados, que representa a regra anterior.
Uma outra maneira de priorizar algo é utilizando o rank:
with regras as (
  select
     p.id
    ,p.nome nome_produto
    ,m.nome nome_marca
    ,s.nome nome_secao
    ,dp.percentual
    ,1 prioridade
  from
     produto p with(nolock)
     inner join desconto_produto dp with(nolock) on (dp.id_produto = p.id)
     left join marca m with(nolock) on (p.id_marca = m.id)
     left join secao s with(nolock) on (p.id_secao = s.id)

  union all

  select
     p.id
    ,p.nome nome_produto
    ,m.nome nome_marca
    ,s.nome nome_secao
    ,dm.percentual
    ,2 prioridade
  from
    produto p with(nolock)
    inner join desconto_marca dm with(nolock) on (dm.id_marca = p.id_marca)
    left join marca m with(nolock) on (p.id_marca = m.id)
    left join secao s with(nolock) on (p.id_secao = s.id)

  union all

  select
     p.id
    ,p.nome nome_produto
    ,m.nome nome_marca
    ,s.nome nome_secao
    ,ds.percentual
    ,3 prioridade
  from
    produto p with(nolock)
    inner join desconto_secao ds with(nolock) on (ds.id_secao = p.id_secao)
    left join marca m with(nolock) on (p.id_marca = m.id)
    left join secao s with(nolock) on (p.id_secao = s.id)

  union all

  select
     p.id
    ,p.nome nome_produto
    ,m.nome nome_marca
    ,s.nome nome_secao
    ,cast(0.0 as decimal) percentual
    ,4 prioridade
  from
    produto p with(nolock)
    left join marca m with(nolock) on (p.id_marca = m.id)
    left join secao s with(nolock) on (p.id_secao = s.id)),
prioridades as (
  select
     id
    ,nome_produto
    ,nome_marca
    ,nome_secao
    ,percentual
    ,rank() over(partition by id order by prioridade) posicao
  from regras)

select
   id
  ,nome_produto
  ,nome_marca
  ,nome_secao
  ,percentual desconto_selecionado
from
  prioridades
where
  posicao = 1

Utilizei o with para utilizar resultados nomeados e ficar mais fácil de trabalhar (não é possível utilizar o rank direto na cláusula where). Em cada consulta defini uma prioridade, quanto menor a prioridade, maior é sua importância. No rank utilizei o partition by para considerar o id do produto como discriminador, pois se o mesmo produto tiver mais de um tipo de desconto, o rank vai classificar de acordo com aquele que tem a menor prioridade (o order by dentro do rank tem essa função de dizer que a menor prioridade vale mais, se fosse em ordem contrária, seria necessário utilizar desc no order by).
Ainda é necessário considerar a questão de desempenho, melhoria das consultas, porém creio que agora você tenha uma base para trabalhar com o seu problema.
Referências:
COALESCE (Transact-SQL)
RANK (Transact-SQL)
WITH common_table_expression (Transact-SQL)


How do I configure Apache and Varnish with both HTTP and HTTPS access and prevent mixed content error?

Question: I have Drupal 7 installed on Ubuntu server with apache2 and varnish. I was asked to provide both http and https access to the site.
To utilize Varnish I setup apache reverse proxy to redirect all https traffic to varnish(http). Now I can access my site via http/https protocols fine.
However, when I load any https page with images in it, all images are served via http, thus making browsers issue a warning about mixed content. I would like to suppress that.
To suppress that, I changed $base_url to https:// in site/default/settings.conf and that worked fine for all https pages.
However, I experienced the same mixed content error while loading normal http pages (images were served via https this time.) Then, I created an if statement trying to differentiate between http and https and assigning different $base_url values accordingly.
I have tried using $_SERVER['']  array variables as well as $is_https, and nothing seems to be working.
I also used $GLOBALS[''] variable to make sure variables are defined. I would clear the Drupal cache as well as browsers before each testing. However, when I access https version of a site, all is rendered ok and everuthing is fine. But when I access http, all images are served with https. I would clear cache again, and try accessing http first, and everything would be fine. But when I access https after that, images would be served with http. So, the logic within settings.conf is fine, but possibly caching makes browsers/Drupal to serve images with the protocol they were first accessed (be it http OR https).
My question: is there a way to assign $base_url dynamically based on the protocol used?
Some of the settings I have tried:
-----------------------------------
if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
        $_SERVER['HTTPS']='on';
        $base_url = 'https://';
        }
else {
         $_SERVER['HTTPS']='';
         $base_url = 'http://';
}
-------------------------------------
#if (isset($GLOBALS['$is_https'])) {
#       $_SERVER['HTTPS']='on';
#       $base_url = 'https://example';
#       }
#else {
#        $_SERVER['HTTPS']='';
#        $base_url = 'http://example';
#}
---------------------------------------
$base_url = '//example'
---------------------------------------
$base_url = '';
---------------------------------------

Comment: My view is to push to use https-only. What is the justification not to do that?
Answer: Drupal 8
Apply the following settings in site's settings.php file:
$settings['reverse_proxy'] = TRUE;
$settings['reverse_proxy_addresses'] = [@$_SERVER['REMOTE_ADDR']]

It should work for CDN where IP addresses are dynamic.
This is explained in the following comment:
 * In order for this setting to be used you must specify every possible
 * reverse proxy IP address in $settings['reverse_proxy_addresses'].
 * If a complete list of reverse proxies is not available in your
 * environment (for example, if you use a CDN) you may set the
 * $_SERVER['REMOTE_ADDR'] variable directly in settings.php.
 * Be aware, however, that it is likely that this would allow IP
 * address spoofing unless more advanced precautions are taken

Drupal 7
$conf['reverse_proxy'] = TRUE;
$conf['reverse_proxy_addresses'] = [@$_SERVER['REMOTE_ADDR']];

See also:

Setting reverse_proxy and reverse_proxy_addresses behind AWS ELBs.
Using a load balancer or reverse proxy
Answer: I've had this problem, and haven't really found a solution. I wish there was a way to tell Drupal to serve all site content using relative links, rather than absolute http/https URLs.
You could try setting up separate directories in the drupal/sites directory for http and https, and give each its own version of the settings.php file with a different $base_url. Then create symlinks to the files and themes directories, so both versions have the same content.
Hope this helps you out.


Getting error "Table 'drupal.watchdog' doesn't exist" during install

Question: I'm a Drupal newbie and haven't been able to find this problem posted elsewhere online, so I'm hopeful someone here can help.
I have just set up php/mysql on a shared hosting environment and copied drupal 8.0.5 over to begin the installation (I changed some file permissions and copied settings.php and .htaccess over to the correct locations as per the instructions).
The server seems to be running MariaDB 10.0.23-MariaDB~trusty (debian maybe?) and ostensibly php 5.6. However, when I run php --version on the server I get PHP 5.5.32-nfsn1 (cli) (built: Mar 11 2016 21:11:51). However, Drupal hasn't complained so it seems to agree that they're running 5.6.
Where I'm getting stuck is during the installation phase, where it breaks about half way through with the following error message:
An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /core/install.php?rewrite=ok&langcode=en&profile=standard&id=1&op=do_nojs&op=do
StatusText: OK
ResponseText: Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'drupal.watchdog' doesn't exist: INSERT INTO {watchdog} (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9); Array
(
[:db_insert_placeholder_0] => 0
[:db_insert_placeholder_1] => DrupalKernel
[:db_insert_placeholder_2] => Container cannot be saved to cache.
[:db_insert_placeholder_3] => a:0:{}
[:db_insert_placeholder_4] => 3
[:db_insert_placeholder_5] =>
[:db_insert_placeholder_6] => http://www.mysite.info/core/install.php/?_format=json&id=1&langcode=en&op=do&op=do_nojs&profile=standard&rewrite=ok&rewrite=ok
[:db_insert_placeholder_7] => http://www.mysite.info/core/install.php?rewrite=ok&langcode=en&profile=standard&id=1&op=start
[:db_insert_placeholder_8] => 188.8.131.52
[:db_insert_placeholder_9] => 1459041023
)
in Drupal\dblog\Logger\DbLog->log() (line 84 of /home/public/core/modules/dblog/src/Logger/DbLog.php).

clicking the link to the error page takes me to this:

Catchable fatal error: Argument 1 passed to
  Drupal\Core\Routing\CurrentRouteMatch::getRouteMatch() must be an
  instance of Symfony\Component\HttpFoundation\Request, null given,
  called in
  /home/public/core/lib/Drupal/Core/Routing/CurrentRouteMatch.php on
  line 92 and defined in
  /home/public/core/lib/Drupal/Core/Routing/CurrentRouteMatch.php on
  line 104

I can't make a lot of sense of this message. A quick google search lead me to a bunch of pages for similar errors, but I couldn't find this same issue.
As this is the only database in the mysql instance I have simply given drupal the admin user/password, so I don't see how this could be a permissions issue.
I have not made any modifications to any files, other than copying default.settings.php -> settings.php.
What am I doing wrong here?
As per another user's request, I tried upgrading to drupal 8.0.6 and am now getting a 500 internal server error, with the following in the logs:
[Fri Apr 08 14:11:53.710451 2016] [core:error] [pid 54807:tid 34478458880] [client 172.17.240.6:45115] AH00124: Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.

I've posted another question to resolve this issue: https://drupal.stackexchange.com/questions/197400/500-server-error
Comment: Are you installing a fresh Drupal 8 installation or using a profile?
Comment: @MohammadAlQanneh it's a completely fresh install.
Comment: Sounds like there is an error or notification occurring early on during install, before the Watchdog table has been created. Pity you can't attach a debugger to DbLog.php and work backwards.
Comment: I think the install is failing to connect to the mysql server.Are you using a local mysql server? Check if the my.ini has a `skip-networking` entry, that would prevent you from connecting. I also had trouble using `localhost` as the host entry, make sure to test with both `localhost` and `127.0.0.1`.
Comment: @BalazsDianiska I am not using a local mysql server.
Answer: This is weird, since exactly in 8.0.5 is fixed that kind of error:
#2646410 by claudiu.cristea, dawehner: Container cannot be saved to cache
Can you try Drupal 8.0.6 maybe? Your MariaDB as well as PHP seem to be compatible with D8 requirements (your MariaDB is based on 5.5 plus Mysql 5.6 stuff).
Comment: I just copied drupal 8.0.6 to the public directory on the web server, but now I get a 500 "Internal Server Error". Looking at the server logs: `[Fri Apr 08 14:11:53.710451 2016] [core:error] [pid 54807:tid 34478458880] [client 172.17.240.6:45115] AH00124: Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.`
Comment: It seems to me like drupal devs are a bit liberal with their definition of "stable". As a drupal beginner, should I be using Drupal 7 instead?
Comment: @quant: Drupal 7 is way stable than 8 (and a bit faster). Also, since D8 is new, there are not many modules ported for it, unlike D7. If you can, I advise to wait up with using D8. Keep an eye on it for a few months and then try it again. As for the error, check http://stackoverflow.com/questions/19071324/request-exceeded-the-limit-of-10-internal-redirects
Comment: I upgraded to 8.0.6 and got the same error. I'm giving up and going with Drupal 7.
Comment: Drupal 7 gives me 500 errors. Posted this same question on the drupal site instead: https://www.drupal.org/node/2705087
Comment: You have quite a problems that should not occur. I am starting to think source of your problems could be in your host. Can you try out instructions from [this page](https://www.drupal.org/node/416906)? Note that it has 4 sublinks below that you should also give a try.


Find cell farthest to the bottom of spreadsheet containing specific value

Question: I have a spreadsheet with multiple tables containing the employee names. I'm trying to locate the cell farthest to the bottom of my spreadsheet containing the value "Person".
Sub findperson()

Dim a As Range

    With ThisWorkbook.Worksheets("sheet1").Columns(1)

        Set a = .Find("Person", LookIn:=xlValues)
        MsgBox a.Row

    End With

End Sub

My code locates the first value cell which contains "Person" e.g. returns 2 for a.Row when I would like it to return 12 (the bottom-most value).
Answer: You need to set .searchdirection of .Find to xlPrevious
Set a = .Find("Person", LookIn:=xlValues, searchdirection:=xlPrevious)


How to get results from javascript in .NET

Question: after long surfing via google I hope somebody can give good answer.
Here I have some javascript with I get in .NET C#

<asp:HiddenField runat="server" ID="hiddenField1" Value="" ClientIDMode="Static" />

and in codebehind file you can access the hidden field by
hiddenField1.Value;

Comment: That's also what I do when I'm not using json, post or query strings.


Computers losing contact to the Domain

Question: We have a problem with a set of computers on our domain. they are constantly losing their trust relationship with the domain. it first happened last week and 8 days later happened again. On the Server we are getting NETLOGON errors with event 5722.
<code>The session setup from the computer ComputerName failed to
authenticate. The name of the account referenced in the security database is
AccountName$.
The following error occurred:
Access is denied.
</code>
I was wondering if there was any way to determine why this is happening? I have checked the error logs and nothing seems to happen before these errors occur. I was thinking about re-imagaing the whole group of the machines.
If I do re-image them all would I be best deleting the computer objects out of AD completely and letting them create new computer objects when I re-join them to the domain? Is it best manually join them or is there a better method? I will have to re-name the machines as it is so will need to access them locally.
The Server is Windows Server 2008 R2 SP1, the machines are Windows 7 SP1
Edit: - In response to comments :-
These machines run Windows 7, Office and Adobe Audition, thats it so nothing odd. They are exactly the same as ten other machines in the room that we have no problem with.
The AD runs on Server 2008 R2 with a secondary domain controller running Windows Server 2008.
The machines sync time with the PDC and checking this they are at the correct time.
There are no duplicate names in AD.
If I remove them and re-add then they run fine again, thats what I did last time, then 8 days later they all dropped off again.
One odd thing:
The room next door had the same problem. I removed the PC's from the domain. Deleted the computer accounts from AD. Flushed the DNS Cache and removed the records of the machines from DNS. I then re-added them to the domain. they can contact the domain fine but their computer accounts do not show up in AD anywhere. Confused me something rotten.
Comment: Have you tried removing and readding these machines to the domain?  Are there any duplicate names in AD?
Comment: Is Active Directory running on Server 2000, 2003 or 2008?
Comment: You're not running anything that freezes the configuration of your clients over reboots?
Comment: I think the key might be that you're not removing them correctly from the domain as you pointed out in your question. If you're not removing them from the domain and making sure they're not in ADDS any more, when you readd the computer, it will generate a different SID then the current one in ADDS, which could be your whole issue, same computer name, different SIDs.
Comment: How are you imaging these machines?
Comment: They are deployed by WDS
Comment: What's the `pwdLastSet` attribute on the machine accounts set to when they break?
Comment: so about the "one odd thing"  are you looking via dsa.msc? or what?
Answer: Do you have anything altering the time on the PCs independantly to the domain?
Comment: +1 Not sure why he got a down vote. I've seen all sorts of login issues due to time.
Comment: Time can definitely cause an issue. What about weak battery on the motherboard? Is power being completely cut off to the clients overnight?
Comment: He got a downvote from me because it's a question....not an answer.
Comment: No, the PC's use the PDC for their time sync
Comment: Pfft.  Don't be such a pedant.  It is something to check that could lead directly to the solution.
Comment: Still, should be a comment, not an answer.
Comment: I don't agree. It is a possible solution to his problem therefore an answer.  Maybe it would confuse you less if it was not phrased as a question but the essential meaning would be the same.
Answer: One scenario where this can occur is if a computer backup is restored to second computer.  When that second computer comes online, the machine's password (which the machine changes every 30 days by default) does not match the password in and AD and disables the machine account.
Using System Restore may also restore a previous machine account password.
Note that the computer's password is not subject to the domain's password expiration policy.  It is controlled by the computer's netlogon service.
Answer: Was there a previous PDC? DNS working perfectly(pings working vice-versa)? Time differences between machines? And finally could you try changing the user's password from the workstation
or even vice versa?
When a workstation joins a domain it sets a trust between the DC and the workstation. Now there are a number of reasons which can be found here (Although most of them only for Server 2000) and a more recent article here that can prevent that from happening.
Answer: Unfortunately this problem resolved itsself once we deployed a self joining domain image out using WDS. We cleared all the computer names out of AD, prestaged all the machines and have never had any problems like this again.

Computers losing contact to the Domain


Infinite sum containing the Bernoulli numbers $B_{2n}$

Question: I am looking for a more direct way to show that

$$\sum_{n = 0}^\infty \frac{(-1)^n B_{2n} \pi^{2n}}{(2n + 1)!} = \ln (2)$$

Here $B_n$ denote the Bernoulli numbers.
By more direct I mean a proof that starts preferably with the sum, then uses it in some way, before arriving at the result of $\ln (2)$.
I have managed to prove it in a very indirect way as follows. Starting with the well-known result of (see here for example)
$$\int_0^{\pi/2} x \cot x \, dx = \frac{\pi}{2} \ln (2),$$
using the Maclaurin series expansion for the cotangent function of
$$\cot x = \sum_{n = 0}^\infty \frac{(-1)^n 2^{2n} B_{2n}}{(2n)!} x^{2n - 1}, \quad 0 < |x| < \pi,$$
on substituting this result into the above integral, after interchanging the summation with the integral, and performing the resulting integration, one arrives at the result in question and is essentially the same method that was used here. But does a more direct way exist?
Answer: Since $B_0 = 1$, $B_1 = -1/2$ and $B_{2n+1}= 0$ for $n \geqslant 1$, using the generating function we have
$$\frac{t}{e^{t} - 1} = 1 - \frac{t}{2} +\sum_{n=1}^\infty \frac{B_{2n}t^{2n}}{(2n)!},$$
and
$$\frac{it}{e^{it} - 1} = 1 - \frac{it}{2}+\sum_{n=1}^\infty \frac{(-1)^nB_{2n}t^{2n}}{(2n)!}.$$
Integration over $[0,\pi]$ and some rearrangement should produce what you want.
Note that
$$\int_0^\pi \frac{it}{e^{it}-1}\, dt = \pi\log 2  - \frac{i \pi^2}{4}$$
Answer: Your approach looks pretty direct to me.
Starting from the generating function for the Bernoulli numbers
$$\cot x = \sum_{n = 0}^\infty \frac{(-1)^n 2^{2n} B_{2n}}{(2n)!} x^{2n - 1},\qquad 0<|x|<\pi $$
is a straightfoward consequence, and the relation between the wanted series and $\int_{0}^{\pi/2}x\cot x\,dx$ is clear as well. By integration by parts the latter integral only depends on $\int_{0}^{\pi/2}\log\sin x\,dx$, which on its turn can be computed from symmetry or Riemann sums, via
$$ \prod_{k=1}^{n-1}\sin\left(\frac{\pi k}{n}\right) = \frac{2n}{\color{red}{2}^n}.$$
Ultimately, $\log 2$ arises from the highlighted $2$.


Use an appropriate Half-Angle Formula to find the exact value of the expression $\cos \left(\frac{9\pi}{ 8}\right)$

Question: I've been having problems all semester understanding radian fractions. If I were to double this fraction wouldn't it be $\frac{18\pi}{8}$. Yet, how does that help me find a reference angle on the unit circle? What is the best way for me to find a reference angle? I am familiar with $\frac{\pi}6$, $\frac{\pi}4$, $\frac{\pi}3$ but I am lost with radians that I can not convert to degrees.
Can someone explain. I have no problems with degrees but when it comes to radians that I am unable to convert to degrees, I am stuck.
Comment: $${18\pi\over8}={9\pi\over4}=2\pi+{\pi\over4}$$
Comment: a full circle has $2\pi$ radians. Half of a circle has $\pi$ radians. So $9\pi/8$ would be $9/8$ of half a circle.
Answer: From Gerry Myerson's comment, we have
\begin{align*}
\frac{18\pi}{8} &= \frac{9\pi}{4} \\
&=2\pi+\frac{\pi}{4} \\
\cos \frac{18\pi}{8} &= \cos \left(2\pi+\frac{\pi}{4}\right) \\
&= \cos \frac{\pi}{4} \\
&= \frac{\sqrt{2}}{2}
\end{align*}
We then have the half-angle formula
$$
\cos \frac{1}{2}\theta = (-1)^{\lfloor (\theta + \pi) / (2\pi) \rfloor} \sqrt{\frac{1 + \cos \theta}{2}}
$$
Setting $\theta = \frac{18\pi}{8}$, we have
\begin{align*}
\cos \left(\frac{1}{2}\right)\left(\frac{18\pi}{8}\right) &= (-1)^{\lfloor ((18\pi/8) + \pi) / (2\pi) \rfloor} \sqrt{\frac{1 + \frac{\sqrt{2}}{2}}{2}} \\
\cos \frac{9\pi}{8} &= (-1)^{\lfloor(13\pi/4)/(2\pi)\rfloor}\sqrt{\frac{2 + \sqrt{2}}{4}} \\
&= (-1)^{\lfloor 13\pi / 8\rfloor} \frac{\sqrt{2 + \sqrt{2}}}{2} \\
&= (-1)^1 \frac{\sqrt{2 + \sqrt{2}}}{2} \\
\cos \frac{9\pi}{8} &= - \frac{\sqrt{2 + \sqrt{2}}}{2}
\end{align*}


Prove this set is a $\sigma$-algebra

Question: Let $\mathcal{F}$ a $\sigma$-algebra of subsets from $\Omega$ and let $\Omega_0\subseteq \Omega$. Prove that $\mathcal{F}\cap\Omega_0:=\{F\cap\Omega_0 | F\in\mathcal{F}\}$ is a $\sigma$-algebra of subsets from $\Omega_0$.
My only problem is with the complements:
Let $F\cap\Omega_0 \in \mathcal{F}\cap\Omega_0$ so $(F\cap\Omega_0)^c=F^c\cup\Omega_0^c$ and so I don't know how to show it as an intersection with $\Omega_0$
Comment: Does it hold for sigma algebra of the type $\mathcal{F} = \{\varnothing, \Omega\}$?
Comment: Actually yes, doesn't it? $\mathcal{F}\cap\Omega_0=\{\varnothing, \Omega_0\}$, so $\varnothing \in \mathcal{F}\cap\Omega_0$, for the argument of carmichael561, $\varnothing^c=\Omega_0$ and vice versa and any countable union of $\varnothing, \Omega_0$ will remain in the set.
Answer: Once you restrict to $\Omega_0$, everything is happening inside this set. So for the complement you should consider $\Omega_0\setminus F=F^c\cap\Omega_0$ rather than $(F\cap\Omega_0)^c$.
Comment: Cool, thanks! :)

Prove this set is a $\sigma$-algebra


Pegar um arquivo em uma pasta

Question: Eu preciso pegar um arquivo com certa extenção para abrir no fopen, mas não sei o nome do arquivo, só sei que ele está na mesma pasta da main, teria alguma forma dentro da main de saber quais os arquivos da mesma pasta da main que contém a extenção que preciso?
Ex: na pasta tem a main.c e um teste.txt (no caso eu não sei o nome do arquivo, somente que ele é .txt), e gostaria de abrir o teste.txt na main pelo fopen (ou se tiver outro comando).
Espero que tenha ficado claro, desde já agradeço.
Answer: Neste exemplo tenho o codigo na pasta:
"/home/ricardo/Desktop/teste/"
Pretendo ler os ficheiros .txt na pasta:
"/home/ricardo/Desktop/teste/txtfolder"
Nesta pasta tenho ainda outros ficheiros que não são '.txt'

<code>#include <dirent.h>
#include <stdio.h>
//#include <errno.h>
//#include <sys/stat.h>
#include<string.h>
int main(void)
{
    DIR *d;
    struct dirent *dir;

    //Diretoria onde estao os ficheiros .txt
    char path[1000]="/home/ricardo/Desktop/teste/txtfolder";

    d = opendir(path);
    char full_path[1000];
    if (d)
    {
        while ((dir = readdir(d)) != NULL)
        {
            //Verifica se é um ficheiro regular.
            if(dir->d_type==DT_REG)
            {
                full_path[0]='\0';
                strcat(full_path,path);
                strcat(full_path,"/");
                strcat(full_path,dir->d_name);
                printf("\n\n%s\n",full_path);

                //Verifica se o ficheiro é '.txt'
                if(strstr(dir->d_name, ".txt") != NULL)
                {
                      printf("%s\n",dir->d_name);
                }

            }
        }
        closedir(d);
    }
    return(0);
}

</code>
Comment: acho que entendi, obrigado
Comment: Valida se responde à tua duvida, aceita a resposta como válida e dá up vote. Thanks!

Pegar um arquivo em uma pasta


How to conduct community division of a social network with R?

Question: I am trying to use R to conduct community division within my weighted network (based from an association matrix). I tried with igraph but I encountered some problems. I usually use the program Socprog (Whitehead 2009) for my analysis, but as I would like to conduct a community division with Newman modularity (2006) on 1000 bootstraps of my data in order to calculate the comembership matrice resulting from all the community division of the bootstraps. So I am looking for a script that would conduct a community division (Newman 2006) from an association matrice and that would give a list of individuals with their cluster.
Does anyone have a R script that works for this analysis? Any advice to implement this analysis would be much apreciated.
Best regards
Comment: check this out and all other questions asked its author on this exchange. thanks. [Weighted Community clustering](http://stats.stackexchange.com/questions/2981/interpreting-output-of-igraphs-fastgreedy-community-clustering-method)
Answer: Try the Louvain method for modularity optimization. It basically tried to optimize divisions within the network by recursively grouping and splitting off nodes form the bottom up.
In R, this kind of thing is super slow, but you can try the igraph package, combined with sna. The latter has methods for clustering.
If you're open to other tools, I'd actually recommend Pajek, which does this kind of thing much faster than R. It's pretty old school, but works wonderfullyhttp://pajek.imfm.si/doku.php?id=download


Views relationships with two views blocks

Question: I am trying to connect two different block views so as when you click the title of the first view block the second block will display the content of the url. Both views are of the same content type. How do i do this? or any usefull tutorials i can count on?
EDIT:
I have this company news page which is accessible from the main menu so that's why i wont to keep the same url. So i created a content type called company news and two views. The first view will display the date and the title of the company new and the second view block will display the content of the company new clicked. My first view is like a left-hand side bar with the 10 newly added. So if a user clicks for example at the second company new the second view block willk display the content of that new. I hope i made it more clear!
Comment: Is it going to another page when you click the title?
Comment: Yes. But i wont to keep the page path the same!
Comment: At least your should pass it through the url so the second view can be based on that contextual filter. Please, explain how the page is done, what do you show, why you want to keep the same url etc... edit your question so is more understandable and you have more chance to find a solution.
Comment: I edited my question. I hope this is easier for understanding
Answer: In this case I think you need one view who shows title, date and body.
So now you will have a full list of all the news and through jquery you can do something like this.
 $('.field-name-body').hide(); //it hides all the body fields.
 $('.views-row').click( function() { // The body is a children of the row.
$('.field-name-body').hide(); // it hides all the open body fields if there is one.
  $(this).children('.field-name-body').show();
});

Do you want something like this?
Fix the css with more specifications (view name, block name...)
With the css you can do the style you want.

If you want to have two different blocks you need to show in one view all the title fields and in the other view all the body fields.
You don't need contextual filter for the second view (a part from the company id). You will show all the body fields and then hide them.
Now you need to change the files views-view-unformatted.tpl copy it from views/theme, paste it into you template folder inside your theme and rename it with the name of the view.
To find the name of that view, you have to open your view, on the third column you click on theme and you will see the files and the suggested name to specify that view (views-view-unformatted-YOURVIEW-BLOCK_1.tpl or something like this). Do it for both views block, they have to be different, one could finish with block_1 and the other with block_2.
Clear the cache after you rename the files.
In the views you can add the node id and exclude it from display.
This is views-view-unformatted.tpl
<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div class="<?php print $classes_array[$id]; ?>">
    <?php print $row; ?>

<?php endforeach; ?>

AND YOU CAN MODIFY ADDING THE ID IN THIS WAY WITH $view->result[$id]->nid;
<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div class="<?php print $classes_array[$id]; ?>" id="<?php print $view->result[$id]->nid; ?>"> // in the body view use body-id
    <?php print $row; ?>

<?php endforeach; ?>

So, now again the js
$('.field-name-body').hide(); //it hides all the body fields.
$('.field-name-body:first').show(); // It will open the first news.
$('title:first').addClass('active');// add class active to the first title
$('.title').click( function() { // The body is a children of the row.
$('.title').removeClass('active'); // remove class active to all the title
    $('.field-name-body').hide(); // it hides all the open body fields if there is one.
    $(this).addClass('active'); //add class active to the clicked element
    var activeBody = $(this).attr('id'); //find the id of the clicked element
    $('#body-'+activeBody).show();
    });

Comment: I prefer to keep the two separate block because i already have the styling for two blocks and i dont like hiding elements. So am i adding the nid to the fields of the two views. And then ? I have to add a contexual filter for the second block? Am confused!!
Comment: Paranod, let me edit my answer. I'm having lunch now. I will tell you everything step by step. Anyway with this method you will always hide the contents, will work as tab.


adding yet another domain to multi-site but this time symlink not working

Question: Have no idea what's going on here. I'm trying to add another new domain to my multi-site but keeps directing to apache test page - not install.php.
Have many subdomains installed now and one new domain added to root one but this next one is giving me problems for some reason. Everything has been done same way. Set up in server to point to IP; separate database created; name of domain in sites folder created with default.settings.php copied to it as settings.php and chmod 644 then a symlink from the /var/www/html folder to the sites one but as I say just keep getting apache test page. Not found if try going to install.php. This is happened to me before but don't have a thorough understanding why...i am suspecting has something to do with database- not sure.
Answer: This has nothing to do with your database. At this point you have probably a problem completely unrelated to Drupal. Instead your Apache is not aware of your Drupal installation.
Here is a list of things you should check:

Is that domain we're talking about pointing to your server (or do you see the test page of a different one): compare IP by ping yourserver.com

If it's a "testdomain" you might want to add an entry to /etc/hosts

Is your virtual host configured correctly?

Did you set a ServerName or a ServerAlias
If you were setting up a new VHost, did you enable it (sudo a2ensite yourhost for instance)
Did you restart Apache/reload configuration after doing this (sudo service apache2 reload)?
Did you configure your VHost/your root directory to follow symlinks?
Have you set NameVirtualHosts?

Are your symlinks pointing to the right folder?

Do you get the contents of your settings.php by typing cat /var/www/html/sites/symlink/settings.php in a terminal or an error?

As an example:
<VirtualHost *:80>
  ServerName yourdomain.com
  ServerAlias sub1.yourdomain.com sub2.yourdomain.com # etc ...
  DirectoryIndex index.php
  DocumentRoot /var/www/html
  <Directory /var/www/html>
    AllowOverride All
    Options -Indexes FollowSymLinks Multiviews
    Order allow,deny
    Allow from all
  </Directory>
</VirtualHost>

Again, it's most probably not Drupal related. It would be if you'd see a different one of your multisites or Drupal complaining about something but since you got the Apache test page you might want to ask on a different board (serverfault) and provide some more information (OS, directory structure, current host configuration and so on) if my checklist didn't help you.
Answer: I just worked it out but thank yu for above important list of reminders.
Was symlinking to sites folder instead of drupal folder- knew it was something simple.
So logical and yet totally passed over my head ;o
Comment: If you accidentally created a second account, you can use the Contact Us link in the footer to request the accounts be merged.
Comment: its ok i don't mind haha
Comment: trying to be polite when so much trouble they went to help answer question but couldn't log in cause fb de activated account - i hate the red tape of forums but love the help! ;)


Sum of Cauchy Sequences Cauchy?

Question: Let $(X,+)$ be an abelian group and $d$ a metric on $X$. Suppose $\{a_n\}$ and $\{b_n\}$ are Cauchy sequences. What conditions on the relation between the group operation and the metric are sufficient to show that $\{a_n+b_n\}$ is Cauchy? The proof in $\mathbb{R}$ simply relies on the fact that the Euclidean metric is induced by a norm:
$$d(a_m+b_m,a_n+b_n)=\|(a_m+b_m)-(a_n+b_n)\|\leq\|a_m-a_n\|+\|b_m-b_n\|$$
I believe this proof works so long as the triangle inequality relates $+$ and the norm which induces $d$.
I think a weaker assumption which still works is if the metric is translation invariant. Then,
$$\begin{align*}
d(a_m+b_m,a_n+b_n) &\leq d(a_m+b_m,a_n+b_m) + d(a_n+b_m,a_n+b_n) \\
&= d(a_m,a_n) + d(b_m,b_n)
\end{align*}$$
Are there weaker assumptions under which the sum is Cauchy? What is an example in this case? Is there an example of a space and Cauchy sequences whose sum is not Cauchy?
This is probably not a standard way of phrasing the question. I'm just trying to strip down assumptions to clarify my understanding. I thought about this for a while but was having trouble coming up with examples.
Comment: No, continuity of $+$ is not enough.  For example, consider $\mathbb R$ with the metric $d(x,y) = |\arctan(x) - \arctan y|$.  Then $a_n = n$ and $b_n = (-1)^n - n$ are Cauchy but $a_n + b_n = (-1)^n$ is not Cauchy.
Comment: The natural requirement is simply that $+$ be continuous with respect to $d$.
Comment: Ok, so that's why I was having trouble proving that comment! Artan is even Lipschitz continuous, huh? Nice example! And that metric doesn't seem to be translation invariant, so it's not induced by a norm. This should be promoted to full answer.
Comment: What about a space which isn't translation invariant, but preserves the Cauchy property under addition?
Comment: This question is really a precursor to the question "when is the completion of a topological group also a topological group"? http://math.stackexchange.com/questions/85871/completion-of-topological-group-with-metric
Answer: A sufficient condition weaker than translation invariance is that translations are uniformly equicontinuous, i.e that for  every $\epsilon > 0$ there is $\delta > 0$ such that for all $x, y, z$,  $d(x,y) < \delta$ implies $d(x+z, y+z) < \epsilon$. For then if $\{a_n\}$ and $\{b_n\}$ are Cauchy sequences, take $N$ so for $n, m > N$, $d(a_n, a_m) < \delta$ and $d(b_n, b_m) < \delta$, and note that $d(a_n + b_n, a_m + b_m) \le d(a_n + b_n, a_m + b_n)
+ d(a_m + b_n, a_m + b_m) < 2 \epsilon$.
Comment: I ran into this while trying to prove the comment that regular continuity was sufficient; just define away the issue! I'm having trouble thinking of an example here which isn't translation invariant. But this brings up a question, related to the arctan example. If $d$ is induced by a norm, and $f : \mathbb{R} \rightarrow \mathbb{R}$, can we impose a growth-condition on $f$ so that $f \circ d$ is a metric? Can we refine this condition to say $f \circ d$ preserves Cauchy sequences under $+$? Maybe should make this own question unless answer is "no".
Comment: Looking at the Wikipedia page for uniform space, they give the example $d(x,y)=|e^x-e^y|$ and state that this has a different uniform structure than the usual metric. Though I don't understand "uniform structure" yet, maybe I'm thinking, can you put a condition on the uniform structure which guarantees preservation of Cauchy sequences under addition?
Comment: Instead of $f \circ d$, it's better to work with $d \circ (f \otimes f)$, i.e. $(x,y) \to d(f(x),f(y))$. For any one-to-one function from $X$ to a metric space $Y$ with metric $d$, $d \circ (f \otimes f)$  is a metric on $X$. This will typically not be translation-invariant. In the case $X=Y=\mathbb R$  with $d(x,y)=|x−y|$, it will satisfy my condition if there are constants $a$, $b$ with $0<a<f′(x)<b$ everywhere.
Comment: Right, I see why $f \circ d$ is incorrect. So in the case $X=Y=\mathbb{R}$, we can think of level sets of the graph of $d$ over $\mathbb{R}^2$. If $d$ is translation invariant, all level sets are parallel to the line $y=x$. In the $\arctan$ example, this is clearly not the case... the level sets diverge away from this line as $x\rightarrow\pm\infty$. I think your condition says that the level sets are bounded between two lines parallel to the line $y=x$. Haven't actually tried computing this, but I think I've satisfied my curiosity for today!

Sum of Cauchy Sequences Cauchy?


Começar a contagem do length a partir do 1

Question: Estou começando a aprender javascript, e gostaria que alguém me ajudasse a resolver o seguinte problema: Fiz um contador de caracteres simples mas ele começa a contagem do 0, será que existe uma forma de começar a contagem do 1?
<!DOCTYPE html>

    <title>Título da página</title>
    <meta charset="utf-8">

   <input type="text" onkeypress="contador()">

Answer: Para uma string vazia, length é 0. Quando você chamar a função "contador" e não houver caracter inserido, deve retornar 0, a menos que tenha um caracter não visível no campo, como um espaço. Se houver a necessidade, você pode somar +1 ao length:
var result = c[0].value.length + 1;

Answer: Basta colocar + 1 a seguir a cont[0].innerText = result logo a função contador ficaria:
function contador() {
        var c = document.getElementsByTagName("input")
        var result = c[0].value.length

        var cont = document.getElementsByTagName("p")
        cont[0].innerText = result + 1
    }


A flat question [bass guitar]

Question: What note is the note under FNG: 4?  It's A flat, how do you play A flat on the A string?
Comment: I'm guessing the 4 above the note is a fingering?  Then you'd play it on the 4th fret of the E string.
Comment: I'm curious: why did you think that the A string was specified?
Comment: @ggcg yes it's fingering.
Comment: Then I think you have the answer.   You play it on the E string
Comment: @ggcg Actually, it's the 3rd fret (4th finger), an A flat on the A string.  So do you just move down that fret to the E?
Comment: Im confused by your question but there is an answer that echos my comments
Comment: I changed the tag to *bass guitar*. Am I correct, or is this some weird way to write for ordinary guitar?  P.S. I understand that normal guitar is pitched an octave lower than written, however I have never seen it scored in the bass clef.
Comment: @db. FYI, the suggested fingerings here are suggested for upright Bass. e.g. the C# is 4th finger and B is 1st; yet this is only 2 frets away. It's a valid and good way to play E Bass, but this posting could be for [Bass] :)
Comment: @paiego - OP mentions **frets** so it's more likely to be EB.
Comment: @Tim It is electric bass, and the book is also for the EB.
Comment: @Tim. Yes, no doubt it's EB (as dlb verified). Yet the original question doesn't mention *frets* and could just as easily be understood and answered by an upright player.
Comment: @paiego - I agree. Finger numbers on(any)  bass do not relect fret numbers.
Answer: Quite simply, you don't. You can't. That A string is note A open, and you can't go to a lower note using that string. The fingering says 4, which is a good clue to playing the bottom string (E), with 4th finger, on 4th fret. That takes you down a semitone from A, to A♭. Job done!

A flat question [bass guitar]


Upgrade Path from OS X 10.5.7 to OS X Snow Leopard Server?

Question: I purchased an iMac back in March 2009 and it came with OS X 10.5.5 and I have been updating it since.  I see that I can upgrade the OS to "Snow Leopard" for $29.99 but......
I would like to upgrade up to OS X Snow Leopard Server, instead of the regular OS X, and was wondering if anyone knows if this is A) such an upgrade path exists and B) what the cost would be?
Answer: To the best of my knowledge, there is no upgrade path from OS X to OS X server and there never has been.
You would need to purchase the full version of OS X 10.6.0 Snow Leopard Server. The cost for this would be $499 for the unlimited client version.
Comment: Thank you for that info.  I had a feeling that might be the case.
Answer: One of the supported methods of installing Mac OS X Server on a computer that the Mac OS X Server Install DVD doesn't support (eg. computer released after the DVD was released) is to install Mac OS X Client (of the same version) - get it up to to date and then use the DVD to install Mac OS X Server overtop. See Apple's kbase article. Of note, this is not supported in Mac OS X 10.6 at the present time. (Oct. 2009)
However as Dan said there is no upgrade path for buying Snow Leopard Server. Those who purchased Leopard Server (10 user or unlimited) will still have to pay the $500 for Snow Leopard Server (which is a full install DVD - not just an upgrade DVD. The same as it is with Client)
Comment: Thank you for the details on that.  I will have to keep this in mind as I consider the option of moving to Server.


Lilypond - Custom Key Signature for Turkish folk music and microtonal accidentals

Question: I have to create this key signature in lilypond:

Would it be possible to create something like that?
I really appreciate any help you can provide.
Thanks!
Answer: <code>% LilyBin
\score{
    {
        \set Staff.keySignature = #`((-1 . ,FLAT) (3 . ,SHARP))
        \time 9/8
        \override Staff.KeySignature.stencil = #ly:text-interface::print
        \override Staff.KeySignature.text =
        \markup {
          \concat {
            \musicglyph #"accidentals.flat"
            \lower #0.4 \super \fontsize #-3 2
          }
          \concat {
            \raise #2 \musicglyph #"accidentals.sharp"
            \raise #1.6 \super \fontsize #-3 3
          }
        }
        s4.*3
    }

    \layout{}
    \midi{}
}
</code>
Lilybin: http://lilybin.com/ugfo88/1
Thanks to yoker from IRC
Answer: This works in latest stable 2.18.2
<code>\relative c' {
  \set Staff.keySignature = #`((6 . ,FLAT)
                               (3 . ,SHARP))
  c4 d e fis
  aes4 bes c2
}
</code>

See http://lilybin.com/4i8zxe/1
Comment: Am I missing something? I don't see any superscripts in the proposed solution.
Comment: No, apparently those are the actual accidentals; the superscripts indicate specific microtonal inflections. Is it possible to use a different font for the elements of the key signature in Lilypond?
Comment: You're right but in the comments nobody focused on the superscripts and I thought the key itself was the main problem. Also, the superscripts looked like footnote markings for some kind of explanation, more than an actual element of the signature. Anyway, I'm pretty confident on some ideas could came from http://lsr.di.unimi.it/LSR/Item?id=433 or http://lsr.di.unimi.it/LSR/Item?id=786 in which markups and custom key signatures are built.
Comment: For the current development version 2.19, the property is keyAlterations instead. Try \set Staff.keyAlterations = #`((6 . ,FLAT)
                               (3 . ,SHARP))


Asynchronously display data with react-leaflet's GeoJSON

Question: I have no trouble rendering geojson data by returning this in my render function :
<Map ref={(ref) => { this.map = ref; }} center={position} zoom={13}>
    <TileLayer
        attribution="&copy OpenStreetMap contributors"
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
    <GeoJSON data={this.state.geojson_data} /> }
</Map>

so next thing I tried is initializing this.state.geojson_data with null, and then loading data on componentDidMount, then I modified the line with the GeoJSON to this one, because obvisouly, null is not a valid geojson object.
 { this.state.geojson_data !== null && <GeoJSON data={this.state.geojson_data} /> }

data is fetched with no problem, but my geojson doesnt show at all, anybody knows why ?
I can see two ways of circumventing that :

using the map reference to add the layer the vanilla leaflet way, but I'd like to use a more react approach.
loading the data with the parent component and giving it as a prop, but I like the idea that the map is initializing and loading while the data loads, rather than after the data loads.

EDIT1: I investigated a little further and tried to feed the GeoJSON component some non geojson data, and it made an error, it still didn't draw the layer when the data is good.
Answer: It was a referential problem, I'm sorry I cant explain further, the gis people I talked with gave me another version of this geojson with another referential, it worked as intended.
the error is on me though, I first tried with a hardcoded geojson, and I was sure my backend used this same data when I tried loading it and it was the other one with the wrong referential.
EDIT: the people handling our gis gave us a geojson that didnt used the right referential


CPU error messages shown in console during boot -- "CPU1: Stuck ??"

Question: I recently installed a second CPU into a server. The CPU is identical to the first and I verified that the CPU is in good working order prior to the installation.
The server booted up and I installed CentOS 6 without issue.
The POST screen recognizes both CPUs -- screenshot: http://pasteboard.co/bOY8M04.png
However, upon first boot I noticed a strange error message on the console showing "CPU1: Stuck ??" -- screenshot: http://pasteboard.co/bOWvk1c.png
Upon digging through the /var/log/messages, I found more debug output on this error:
Sep 13 18:01:58 customer kernel: Kernel panic - not syncing: Fatal exception
Sep 13 18:01:58 customer kernel: Pid: 0, comm: swapper Tainted: G      D    ---------------    2.6.32-431.29.2.el6.x86_64 #1
Sep 13 18:01:58 customer kernel: Call Trace:
Sep 13 18:01:58 customer kernel: [<ffffffff8152873c>] ? panic+0xa7/0x16f
Sep 13 18:01:58 customer kernel: [<ffffffff8152ca74>] ? oops_end+0xe4/0x100
Sep 13 18:01:58 customer kernel: [<ffffffff81010e0b>] ? die+0x5b/0x90
Sep 13 18:01:58 customer kernel: [<ffffffff8152c552>] ? do_general_protection+0x152/0x160
Sep 13 18:01:58 customer kernel: [<ffffffff8152bd25>] ? general_protection+0x25/0x30
Sep 13 18:01:58 customer kernel: [<ffffffff8103eb79>] ? native_write_cr4+0x9/0x10
Sep 13 18:01:58 customer kernel: [<ffffffff81050a2e>] ? syscall32_cpu_init+0x6e/0x80
Sep 13 18:01:58 customer kernel: [<ffffffff8151bea2>] ? xsave_init+0x31/0x48
Sep 13 18:01:58 customer kernel: [<ffffffff8151be45>] ? fpu_init+0x7e/0xaa
Sep 13 18:01:58 customer kernel: [<ffffffff8151df1b>] ? cpu_init+0x309/0x35f
Sep 13 18:01:58 customer kernel: [<ffffffff81521fcd>] ? start_secondary+0xd/0x2ef
Sep 13 18:01:58 customer kernel: [<ffffffff81521fc0>] ? start_secondary+0x0/0x2ef
Sep 13 18:01:58 customer kernel: CPU1: Stuck ??
Sep 13 18:01:58 customer kernel: #2 #3
Sep 13 18:01:58 customer kernel: general protection fault: 0000 [#2] SMP
Sep 13 18:01:58 customer kernel: last sysfs file:
Sep 13 18:01:58 customer kernel: CPU 3
Sep 13 18:01:58 customer kernel: Modules linked in:
Sep 13 18:01:58 customer kernel:
Sep 13 18:01:58 customer kernel: Pid: 0, comm: swapper Tainted: G      D    ---------------    2.6.32-431.29.2.el6.x86_64 #1 Supermicro X7DWT/X7DWT

Here is a full output of the /var/log/messages during boot: http://pastebin.com/b3wfmLX6
After the system boots, if I run a cat /proc/cpuinfo only four cores are shown.
Does anyone know what could be causing these errors?
Comment: If the kernel somehow got the idea that you have _more_ than 2 CPUs, then you have a serious hardware problem.
Comment: I would've thought CPU1-8 were references to the specific CPU core -- these are quad core processors.
Answer: Hmm, looks like a Supermicro. Are you sure your hardware is healthy?
This just requires troubleshooting steps.

Try booting without the new CPU.
Try swapping the physical CPUs.
Eliminate the CPU socket as the cause.
Take the appropriate actions based on these results.
Comment: I had a feeling the only possibility was hardware failure. Just replaced the motherboard and all works well.


Which one is better to access the MySQL in online from Android application? Either RESTful web service or Async Task?

Question: I am developing an Android application where my application uses MySQL as database via PHP. Now I am developing an application with RESTful web service. I want to know which one is better for accessing the database? Either RESTful web service or Async Task?
Please explain with an example.
Comment: I would recommend using Retrofit to consume the service, it's great: http://square.github.io/retrofit/
Comment: Both, I think. Use async task to do http request to a REST API or am I misunderstanding something ?
Comment: @frz3993 I am using only RESTful web service. What is the different between both?
Comment: A REST API is the API to access the service. The web service will provide access to the server's resources. You use asynctask so you don't block your activity's main thread. In you asynctask, make a request to the web service using whatever library you are comfortable with. Example `httpurlconnection`.
Comment: Welcome to Stack Overflow.  I have fixed a few English issues and remove the thanks, which is not required.  You show your thanks by voting.
Answer: I'd go straight REST. It's much easier for error handling and imo a bit easier.


Infinite sum of products on my mid-term

Question: This problem was on my calculus mid-term : Determine the convergence or divergence of the   series  $$
\sum\limits_{n = 1}^\infty  {\prod\limits_{k = 1}^n  {\frac{{4k - 3}}{{4k - 1}}} }
$$
I tried everything, even the Wallis product formula, but nothing worked out. I'm pretty sure it diverges but I can't find a way to prove that the general term doesn't tend to 0.
 The following question was (I'm only including this because it involves roughly the same series) :
Determine the convergence or divergence of the alternating series: $$
\sum\limits_{n = 1}^\infty  {( - 1)^n \prod\limits_{k = 1}^n  {\frac{{4k - 3}}{{4k - 1}}} }
$$
Comment: the summand does not depend on $n$. This is a problem.
Comment: You cannot use $n$ as both the index of summation and the index of multiplication.
Comment: Do you have $n$ in both sum and product?
Comment: um how about like this?
Answer: Set $$a_n:=\prod_{k=1}^n\frac{4k-3}{4k-1}.$$
Now
$$a_n\ge\frac{1}{3}\prod_{k=2}^n\frac{4k-5}{4k-1}=\frac{1}{4n-1},$$
which means that the first series diverges.
For the second series, consider $\log a_n$:
$$\log a_n=\sum_{k=1}^n\log\left(1-\frac{2}{4k-1}\right)
\le-\sum_{k=1}^n\frac{2}{4k-1}\to-\infty$$
as $n\to\infty$. This means $a_n\to 0$ as $n\to\infty$, and the alternating series converges relatively but (as we've seen from the first series) not absolutely.
Comment: shouldn't there be $
\log (1 - \frac{2}{{4k - 1}})
$ ?
Comment: @maceq: yes, fixed it.
Answer: Consider $$S_m=\sum\limits_{n = 1}^m  {\prod\limits_{k = 1}^n  {\frac{{4k - 3}}{{4k - 1}}} }=\sum\limits_{n = 1}^m u_n$$ with $$u_n=\prod\limits_{k = 1}^n  {\frac{{4k - 3}}{{4k - 1}}} $$ So $$\frac{u_{n+1}}{u_n}=\frac{(4n+1)}{(4n+3)}=1-\frac{2}{4 n+3}$$
I am sure that you can you take from here.
Comment: Well I tried this as well, but the limit as n approaches infinity is 1, so the ratio test is inconclusive..
Comment: The limit to compute for Raabe test equals $-\frac{1}{2}$, so this test is also inconclusive.
Answer: $\prod\limits_{k = 1}^n  {\frac{{4k - 3}}{{4k - 1}}}$ is decreasing.
Also if you note $u_n=\prod\limits_{k = 1}^n  {\frac{{4k - 3}}{{4k - 1}}}$, you have $$\frac{u_{n+1}}{u_n}=1-\frac{2}{4n+3} \le 1-\frac{1}{2}\frac{1}{n+1} \le \frac{n^{1/4}}{(n+1)^{1/4}}$$
Consequently $u_n \le \frac{u_1}{n^{1/4}}=\frac{1}{3}\frac{1}{n^{1/4}}$ so $u_n$ converges to $0$ and according to the alternating series test the second series is convergent.
Comment: You also need to show that it converges to zero.
Comment: Good point... Let's have a further look!
Answer: First use gamma function to write the product conveniently:
$$\prod\limits_{k = 1}^n  {\frac{{4k - 3}}{{4k - 1}}}=\frac{\Gamma(\frac{3}{4})\Gamma(m+\frac{1}{4})}{\Gamma(\frac{1}{4})\Gamma(m+\frac{3}{4})}$$
(factor $4^n$ out and the reshuffle the rest.)
Now note that $$\begin{align}\frac{m\Gamma(m+\frac{1}{4})}{\Gamma(m+\frac{3}{4})}&=\frac{m\Gamma(m+\frac{1}{4})}{(m-\frac{3}{4})\Gamma(m-\frac{3}{4})}\\
&>1,
\end{align}$$
which implies that $$\frac{\Gamma(m+\frac{1}{4})}{\Gamma(m+\frac{3}{4})}>\frac{1}{m}.$$
Therefore your first series diverges.
Note that by the alternating series test and the fact that $\frac{\Gamma(m+\frac{1}{4})}{\Gamma(m+\frac{3}{4})}=O(m^{(-1/2)})$ the other series converges.

Infinite sum of products on my mid-term


templates in C++

Question:
Possible Duplicate:
Why can templates only be implemented in the header file?

hello everyone I've just read that if I write some template I must write all code in header file (including constructor, desctructors...), but I can't understand why, can somebody please explain?
Answer: Because the templated code can be compiled only after it is know, which class/type replaces the template, so all code must be available then.
There is a very detailed explanation of the details in the C++ FAQ
Answer: When a template is used, it's much like the defined template class or function is used to create a new class by replacing the template parameters with the provided parameters.
The code for this new class is compiled right when it's needed, so all the source needs to be there at that time.
See this link at the bottom of the page for a bit more detail.

templates in C++


Computing an integral on the unit sphere

Question: I am having trouble, trying to compute the integral
\begin{align*}
I(a)= \int_{\mathbb{S}^{d-1}} (1-\cos(a w_1)) \, d \sigma_{d-1}(w)\qquad a>1
\end{align*}
where $w= (w_1,\cdots, w_d)$ and $\mathbb{S}^{d-1}=\{w\in \mathbb{R}^{d}\,:\, w_1^2+\cdots+w_d^2=1\}$.
1- Can the explicit value of $I(a)$ be computed?
2- How can prove that there is $c>0$ such that $I(a)\geq c$ for all $a>1$?
PS: The second question is a conjecture.
Answer: This posting is to address question (2) of the OP. Guiseppe already addressed part (1).
Fixing $d$, we have from Fejer's theorem (see theorem in this posting for example) or alternatively, from Riemann-Lebesgue's lemma, that
\begin{align}
\int^1_{-1}(1-\cos(ax))(1-x^2)^{\frac{d-3}{2}}\,dx&\xrightarrow{a\rightarrow\infty}\Big(\frac{1}{2\pi}\int^{2\pi}_0(1-\cos x)\,dx\big)\Big(\int^1_{-1}(1-x^2)^{\frac{d-3}{2}}\,dx\Big)\\
&=\int^1_0(1-u)^{(d-3)/2}u^{-1/2}\,du=B(\tfrac12,\tfrac{d-1}{2})>0
\end{align}
Thus, there is $a_d>0$ such $I(a)>\frac12B(\tfrac12,\tfrac{d-1}{2})$ whenever $a\geq a_d$. Notice that $a\mapsto I(a)$ is positive and continuous on $(0,\infty)$. It follows that there is $C_d>0$ such that
$I(a)\geq C_d$ for all $a\geq 1$.

Edit:
The integral in the OP can also be written in terms of the Bessel function of the first kind $J_p$:
\begin{align}
I(a)&=|\mathbb{S}_{d-1}|-|\mathbb{S}_{d-2}|\int^1_{-1}(1-x^2)^{\frac{d-3}{2}} e^{-iax}\,dx\\
&=\frac{2\pi^{d/2}}{\Gamma(d/2)}-\frac{2\pi^{\frac{d-1}{2}}}{\Gamma(\frac{d-1}{2})}\frac{\Gamma(\frac{d-1}{2})\sqrt{\pi}}{(a/2)^{\frac{d-2}{2}}}J_{\frac{d-2}{2}}(a)\\
&=\frac{2\pi^{d/2}}{\Gamma(d/2)}-\frac{(2\pi)^{\frac{d}{2}}}{a^{\frac{d-1}{2}}}J_{\frac{d-2}{2}}(a)
\end{align}
where
$$
  J_p(z)=\sum_{n\geq0}\frac{(-1)^n}{n!\Gamma(n+p+1)}\Big(\frac{z}{2}\Big)^{p+2n}
$$
Comment: This is a great observation, but how can you sure that $I(a)\ge C_d$ for all $a\ge 1$? I am a bit concerned about $a\ge1$. Haven't you proved that $I(a)\ge C_d$ for all $a\ge a_0$ for some $a_0>0$? You only computed $\lim_{a\to \infty} I(a)$ after all
Comment: Yes, right. We know a priori that $I(a)>0$ unless $a=0$, this is important, great.
Answer: INCOMPLETE.
Certainly you can compute that when $d$ is odd.
For all $d\ge 2$, the surface measure reads
$$
d\sigma_{d-1}(w)=(1-w_1^2)^{\frac{d-3}{2}}dw_1 d\sigma_{d-2}, $$
so our integral reads
\begin{equation*}
\begin{split}
I(a)&=\int_{\mathbb{S}^{d-1}} (1-\cos(a w_1)) \, (1-w_1^2)^{\frac{d-3}{2}}dw_1 d\sigma_{d-2} \\
&=\int_{-1}^1 (1-\cos(aw_1))(1-w_1^2)^\frac{d-3}
{2}\, dw_1 \int_{\mathbb S^{d-2}} d\sigma_{d-2}\\
&=\lvert\mathbb S^{d-2}\rvert \int_{-1}^1 (1-\cos(aw_1))(1-w_1^2)^\frac{d-3}
{2}\, dw_1.
\end{split}
\end{equation*}
When $d$ is odd, the term $\frac{d-3}{2}$ is integer and the right-hand side integral is of the form $\int_{-1}^1 (1-\cos(ax))P(x)\, dx$ for a polynomial $P$, which can be explicitly computed by repeated integration by parts.
For $d=3$ this is very simple, as you do not need any integration by parts. Recalling $\lvert \mathbb S^{d-2}\rvert=\lvert\mathbb S^1\rvert=2\pi$,
$$
I(a)=4\pi\left(1-\frac{\sin a}{a}\right).$$
Proving your conjecture in this $d=3$ case is also immediate, as $\frac{\sin a}{a}$ has a strict global maximum at $a=0$, so $I(a)\ge C_\epsilon >0$ for $\lvert a \rvert \ge \epsilon$.

It may be the case that you can compute $I(a)$ also for even $d$, but that requires some trick to get rid of the square root in $(1-w_1^2)^\frac{d-3}
{2}$.
Comment: @J.G.: I guess it is just a matter of normalizations, I don't know whether $d\sigma_{d-1}$ denotes the **normalized** surface measure (in which case you are right) or the unnormalized one (in which case I am right). The difference is not substantial, anyway, it is just a multiplicative constant. Also, I expanded on the main equation, to make it clear where does $\lvert \mathbb S^{d-2}\rvert$ come from.
Comment: (+1) @GiuseppeNegro: One observation. By Fejer's theorem, for each $d$ $I_d(a)\xrightarrow{a\rightarrow\infty}B(1/2,(d-1)/2)>0$ where $B$ stands for Beta function. Hence, there is $a_d>0$ such that $I(a)>\frac12B(1/2,(d-1)/2)$ for all $a\geq a_d$. For $1\leq a\leq a_d$, $I(a)$ is positive and continuous. (2) follows.
Comment: I think your integral should be a ratio of two integrals with similar integrands. Dividing $I$ by the surface measure of $\Bbb S^{d-1}$ (why do you use $\Bbb S^{d-2}$?) should give$$\begin{align}\frac{\int_0^\pi(1-\cos(a\cos\theta))\sin^{d-2}\theta d\theta}{\int_0^\pi\sin^{d-2}\theta d\theta}&=1-\frac{\int_{-1}^1(1-u^2)^{(d-3)/2}\cos(au)du}{\int_{-1}^1(1-u^2)^{(d-3)/2}du}\\&=1-\frac{\int_0^1(1-u^2)^{(d-3)/2}\cos(au)du}{\int_0^1(1-u^2)^{(d-3)/2}du}.\end{align}$$
Answer: We want to calculate
$$F(s)=\int\limits_{\partial \mathbb B(0,1)}(1-\cos(sx_1)) \mathrm d^{n-1}\boldsymbol x$$
Of course you should switch to hyperspherical coordinates:
$$F(s)=\int\limits_{\theta_{n-1}=0}^{2\pi}~\underbrace{\int\limits_{\theta_{n-2}=0}^\pi\cdots\int\limits_{\theta_{1}=0}^\pi}_{n-2~\text{of these}}\big(1-\cos(s\cos\theta_1)\big)~\prod_{k=1}^{n-1}\sin(\theta_i)^{n-1-k}\mathrm d\theta_k$$
Now the integrals are separable.
$$F(s)=\int_{0}^{2\pi}\int_0^\pi\cdots \int_0^\pi\mathrm d\theta_{n-1} \prod_{k=1}^{n-3}\sin(\theta_k)^{n-1-k}\mathrm d\theta_k~\cdot~\int_0^\pi \big(1-\cos(s\cos\theta_1)\big) \sin(\theta_1)^{n-2} \mathrm d\theta_1 \\ =2\pi \prod_{k=1}^{n-3}\int_0^\pi \sin(\theta_k)^{n-k-1}\mathrm d\theta_k~\cdot~\int_0^\pi \big(1-\cos(s\cos\theta_1)\big) \sin(\theta_1)^{n-2} \mathrm d\theta_1\tag{*}$$
All the integrals of the form $\int_0^\pi \sin(t)^k\mathrm dt=2\int_0^{\pi/2}\sin(t)^k\mathrm dt$ are evaluated easily with the Beta function, so all that is left is the integral
$$\int_0^\pi \cos\big(s\cos t\big)\sin(t)^{n-2}\mathrm dt $$
There is a well known integral representation of the Bessel function
$$J_{\nu}(z)=\frac{(z/2)^\nu}{\sqrt{\pi} ~\Gamma(\nu+1/2)}\int_0^\pi\cos(z\cos \theta)\sin(\theta)^{2\nu}\mathrm d\theta \\ \Re(\nu)>-1/2$$
Which in our case means
$$\int_0^\pi \cos\big(s\cos t\big)\sin(t)^{n-2}\mathrm dt  \\ =\frac{\sqrt{\pi}~\Gamma\left(\frac{n-1}{2}\right)}{(s/2)^{\frac{n-2}{2}}}J_{\frac{n-2}{2}}(s)$$
So now just go back to $(\ast )$ and fill in the gaps.
Comment: By a rotation you get a simpler representation similar to what Giuseppe obtain: $\int_{\mathbb{S}_{d-1}}(1-\cos(a u_1))\,\sigma_{n-1}(d\mathbf{u})=\int_{\mathbb{S}_{d-1}}(1-\cos(a u_n))\,\sigma_{n-1}(d\mathbf{u})=|\mathbb{S}_{d-2}|\int^1_{-1}(1-\cos(a t))(1-t^2)^{\frac{d-3}{2}}\,dt$


Geodesics on a Hyperbolic Paraboloid

Question: Let $S \subset\mathbb{R}^3$ be a hyperbolic paraboloid and let $a,b \in S$.
I'm wondering how the Gauss-Bonnet Formula tells us that there is at most one geodesic $\gamma: [0,1] \rightarrow S$ such that $\gamma(0)=a$ and $\gamma(1)=b$.
\begin{equation}
\int_{S}KdA + \int_\gamma K_gds = 2 \pi
\end{equation}
Any help would be much appreciated!
Comment: The gamma in the formula you're citing corresponds to the boundary of $S$, which I'm pretty sure is empty in this case, so it probably won't help you.
Answer: Choose a smooth normal vector field of unit length on the hyperbolic paraboloid and fix positive orientation on it, so that when you look from the tip of the vector down on the surface the positive orientation is counterclockwise. Assume you have two different geodesics $\gamma_1$ and $\gamma_2$ connecting points $a$ and  $b$. Then the two geodesics cut out a topological disc $S$, a geodesic bi-gon on the surface. Then, orient these geodesics as follow: $\gamma_1$ from $a$ to $b$ and $\gamma_2$ from $b$ to $a$. Let angle $\alpha > 0$ be the counterclockwise angle at $a$ from $\gamma_1$ to $\gamma_2$ and  Let angle $\beta > 0$ be the counterclockwise angle at $b$ from $\gamma_2$ to $\gamma_1$. Then clearly
$$\alpha + \beta > 0$$
The geodesic curvature of the closed piecewise geodesic loop $\gamma_1 \cup \gamma_2 = \partial \, S$ is zero everywhere except at the vertices $a$ and $b$ where it is $\pi - \alpha$ at $a$ and $\pi - \beta$ at $b$. Recall that the Gaussian curvature $K$ of the hyperbolic paraboloid is negative! Then by Gauss-Bonnet
$$\int_{S} \,K \, dA + \int_{\gamma_1 \cup \gamma_2} k_g = 2 \, \pi \, \chi(S) = 2 \pi$$  so
$$\int_{S} \, K \, dA + 2 \pi - \alpha - \beta = 2 \pi$$ But then
$$0 > \int_S \, K \, dA  = \alpha + \beta$$ which is in a contradiction with the fact that $\alpha+\beta > 0$.
Answer: Hyperbolic paraboloid $S$ is given by $$ f(x,y)=(x,y,xy)$$
Consider $$ (x,0,0),\ (0,y,0)$$ which are geodesics in $\mathbb{R}$
Hence they are geodesics on $S$
In further $$f_x=(1,0,y),\ f_y=(0,1,x),\ E=1+y^2,\ G=1+x^2,\ F=xy
$$
\begin{align*} dA&=\sqrt{1+r^2}dxdy\\
\int_S K&= \int \frac{-1}{(1+r^2)^2} \sqrt{1+r^2} dxdy \\&=\int
\frac{-1}{(1+r^2)^\frac{3}{2}}\ rdrd\theta =2\pi
(1+r^2)^\frac{-1}{2}|_0^\infty=-2\pi\ \ast\end{align*}
Consider a geodesic triangle $\Delta$ : $(t,0,0),\ (0,t,0),\
(0,0,0),\ t>0$
Then $\int_\Delta K +\sum_i \theta_i=2\pi$ so that $$
\frac{\pi}{2}<\int_\Delta K+ \pi=\sum_i(\pi-\theta_i)$$
Here first inequality is followed since we have $\int_\Delta K>
\frac{1}{4}\int_S K$ by observing integrand in $\ast$ And last term
is sum of internal angles of $\Delta$ So we can not have a
contradiction
Comment: The hyperbolic paraboloid does *not* have constant negative curvature.
Comment: I see : $z=xy,\ K= \frac{-1}{(1+x^2+y^2)^2}$ Thank you

Geodesics on a Hyperbolic Paraboloid


Postfix keeps answering "User unknown in local recipient table"

Question: I am trying to set up postfix (on ubuntu 18.04) to accept incoming email locally, with no relaying involved.
I've made it work fine for users that actually exist in the system, but I want it to handle arbitrary recipients as long as the domain is mine. Basically, I want to specify the valid recipients without creating them as unix users.
I have set local_recipient_maps=
I have tried luser_relay=existing_user
I have tried virtual_alias_maps=pcre:/etc/mailist/recipients, a file containing /.*/ existing_user, which is readable by anyone.
(existing_user always is a real user that I have succesfully sent mail to)
I even added an entry to /etc/aliases, which is configured as alias_maps, and ran newaliases, without success.
And of course I have reloaded and restarted postfix after each change, so that's not the problem.
Creating a new user in the system works fine, I can immediately send mail to that user.
I have no clue. What am I doing wrong?
Answer: OK, it was too late in the evening for me... reading error logs helps. I kept looking in mail.log and forgot checking mail.err .
I still wonder why luser_relay did not work as expected, but it was not the way I wantoed to go anyway.
/etc/aliases.db somehow gives a "permission denied", that's why changing it did not help. But I won't investigate this, because it also is not my favored solution.
The reason my virtual_alias_maps=pcre:/etc/mailist/recipients didn't work was simply that I did not have postfix-pcre installed.


What hotfixes/updates does a new 2012 R2 Hyper-V server need?

Question: I'm building several new 2012 r2 Hyper-V servers. One thing that I've read over and over again is that there are A LOT of hotfixes that i need to install on top of the regular OS updates Microsoft pushes via Windows Updates. Every article i read points to this article as the best source for information on which hotfixes to install. However, most of the hotfixes on that list just say "Update not applicable" when i download and try to install them. Is there a way to tell which updates are applicable to my server? Or do i just have to try each one?
Also, are all of the updates that Microsoft puts in the rollups that are releases routinely included in Windows Update? If i just run Windows Update until it says there are no more updates, do i have all of the updates applicable to this server? Or do i still need to download the rollups separately?
Comment: Rollups include most updates published up to the point when they are released; but they also usually have several prerequisites. If you start from a RTM Windows Server ISO, you will need to perform several check-update-reboot-recheck cycles including a couple of several-hundred-MBs rollups, which is a royal pain (had to do it recently for several physical servers including 4 Hyper-V hosts, thus I speak from direct experience).
Answer: First of all, you should perform the OS installation using the latest OS ISO available from MSDN or VL; it already includes several update rollups (some of which are quite big), and it will save you a lot of update time and several check-update-reboot-recheck cycles.
Then install the latest .NET framework (currently 4.5.2): it also includes several updates for the previous releases, so you save some update time here too.
Lastly, perform a full Windows Update check and install everything (including the optional updates; I don't actually know how Microsoft is classifying them recently, but it appears several of them include actual OS bugfixes (!!!)).
Also, not Windows-related, but important anyway: after the OS is up and running, install the latest drivers and firmware from the hardware vendor of your server(s); this is especially important for network and storage devices. Also, make sure to update the server BIOS, and to turn on hardware virtualization support.
About non-WU hotfixes: you should install them only if you are experiencing specific issues which are fixed by them; there is a reason they are not released via Windows Update and are only available for manual download.

This advice also applies to all Windows Server installations, not only for Hyper-V hosts; just install from the latest ISO, and then update everything Microsoft is telling you to update. For physical servers, pay special attention to drivers and firmware, which usually are the top source of problems for Windows systems.
Comment: RE: Hotfix installation. I agree. Hotfixes outside of whatever updates are delivered via Windows Updates should be installed only if you're experiencing the specific issue or issues that the hotfix addresses. I've never heard of anybody installing "out of band" hotfixes as part of their OS deployment process.
Answer: Massimo's answer looked fine.  I want to emphasize one thing, change its order, and add one more thing.
I want to emphasize the importance of updating the BIOS.  For the hardware server supporting the VMs, the Hyper-V OS may need the latest BIOS.  This is probably the first thing that should be considered.  If you fail to do this, you may (or may not) need to reformat the hardware servers with the OS.  (This is the re-order and emphasis item combined.)
Finally, you may need to update the CMOS.  This is essentially updating firmware.  But I want to make you aware of the need.  I lost hours by not updating these things BEFORE I installed Hyper-V.
Comment: I didn't put it at the top because the question asks specifically about Windows hotfixes, while this is a more general issue; thus I thought to just mention it. But of course BIOS, firmware and drivers are critically important to any physical server.
Answer: Rollup Updates / Hotfixes
Microsoft Rollup Updates are inclusive so the latest Rollup Update includes updates from the previous released update, however, there are prerequisite (requirements) for installing most hotfixes, rollup updates, service packs, etc.
OS Version Dependencies
Each OS version's hotfix / update stream of course will have it's own prerequisite as updates may be unique to the version or may be a back-port from a later OS versions, etc.
For Example:
Windows 2012 R2 Rollup Updates
April 2014 Rollup Update MUST be installed prior to any later Rollup Update being installed.  Note: April 2014 Update includes ALL prior Rollup Updates (for 2012 R2).
November 2014 Rollup Update includes ALL prior (back to May 2014) EXCEPT for April 2014.  April 2014 Update is Required to Install November 2014.
December 2014 is the Last (Current) Rollup Update to date (11/30/2015) as development teams were (are) focused on Windows 10 / 2016 releases.  December 2015 Update does include additional patches, however, after applying December 2014 Update, you may need to apply later versions of hotfixes that were included in the December 2014 Rollup Update package.
December 2014 - December 2015 Hotfixes
Any hotfix released between November 2014 and December 2015 and is Not included within the November 2014 / December 2014 Rollup Update MUST be installed manually AFTER April 2014 & November 2014 Rollup Updates (minimum) have been installed
Note: (Check Hotfix file version numbers & file version Release Date)
Windows Update Service
Microsoft Windows Update Service will ONLY push critical updates and hotfixes that have wide-spread issues.  Windows Update will NOT show, recommend or push hotfixes for unique or specific issues unless they are wide-spread so you MUST install any of these hotfixes manually.
Later Windows Rollup Updates in Future?
Will MS release later Rollup Updates for Windows 2012 R2?  Yes, MS will likely Roll all hotfixes between Nov 2014 and Jan / Feb 2016 into a later Rollup Update once Win 10 / 2016 has been released, etc.
Final Reminder
You MUST install (at minimum) April 2014 & November 2014 prior to installing any later (~Nov 2014 thru 2016 Hotfixes).  Minimum Supported is 2012 R2 with April 2014 Rollup Update but November 2014 Update should also be installed (DO IT).
http://social.technet.microsoft.com/wiki/contents/articles/23823.list-of-rollup-updates-for-windows-8-1-and-windows-server-2012-r2.aspx
https://support.microsoft.com/en-us/kb/2974503
Regards,
Comment: A very thorough answer, but it will quickly become obsolete as more updates are released; better to give general advice than mentioning specific updates which are going to be superseded sooner or later.
Comment: I will not argue as the choice is yours, however, your statement is not accurate or correct.  As any MS CSS / Escalation engineer will say, You MUST install April 2014 and November 2014 Rollup Update before installing later Hotfixes.  As I stated previously and state again, MS will likely release later Rollup Updates but until that time, you MUST install as I stated.  This said, you could always call your OEM support or Microsoft and ask about the April 2014 & November 2014 Rollup Update requirements and who knows, you might find my name on the email thread :-).  Good luck!
Comment: I am *not* saying your answer is wrong; it's completely correct. But it *will* become obsolete when new updates are released. It actually already *is*, at least partially: the Windows ISO images on MSDN/VL are updated soon after a rollup update is released, and if you use them to install your O.S. (which you should), no manual installation of rollups will be required. Until a new one is released, of course.


Glimpse ASP.Net funcionando com Dapper

Question: Acabei de ver um conteúdo em que eu estudava sobre performance e otimização nas aplicações ASP.Net. Me apresentaram uma ferramenta de diagnóstico que se chama Glimpse.
O Funcionamento da ferramenta é perfeito, faz a medição dos tempos de execução das requisições ajax, tempo das consultas SQL e o comando das consultas SQL executadas diretamente no banco de dados, resumindo, um diagnóstico completo, porém as consultas só funcionam se forem feitas através do Entity Framework.
Tentando trazer essa realidade pro meu ambiente de trabalho, me deparei com a divergência que uso o Dapper e ele só funciona pro EF.
Minha dúvida então é se seria possível que tal ferramenta funcionasse com Dapper? Haveria outra ferramenta de diagnóstico que traga informações ricas como essas?
Answer: Bom, eu acabei utilizando o LightHouse do Google, acabou atendendo minhas espectativas. Abaixo um pouco mais sobre o LightHouse que é basicamente uma ferramenta de diagnóstico também

O Lighthouse é uma ferramenta automatizada de código aberto que aprimora a qualidade de apps da Web. Ele pode ser executado como extensão do Chrome ou na linha de comando. Informe ao Lighthouse um URL que você quer auditar. Ele executará uma série de testes na página e gerará um relatório sobre o desempenho da página. Nesse relatório, você poderá usar os testes que apresentaram falha como indicadores do que pode ser feito para aprimorar o aplicativo.

Ajudou bastante na questão de performance / otimização e gargalos.

Glimpse ASP.Net funcionando com Dapper


Return both a form and content in a menu callback

Question: I have the following code.
function mymodule_menu() {
  $items = array();

  $items['mymodules/page'] = array(
    'title' => t('my module settings'),
    'description' => t('change values here'),
    'page callback' => 'mymodule_page',
    //'page arguments' => array('mymodule_page'),
    'access arguments' => array('access administration pages'),
    'type' => MENU_CALLBACK,
   );

  return $items;
}

function mymodule_page() {
  return drupal_get_form('test_form');
}

function test_form() {
  $form = array();
  $brandarray = array('nokia','siemes');

  $form['mymodule_brand'] = array(
    '#type' => 'select',
    '#title' => t('Brand'),
    '#default_value' => variable_get('mymodule_brand', 'nokia'),
    '#options' => $brandarray,
    '#description' => t('Change this.'),
  );

  $form['my_markup'] = array(
  '#markup' => '
Lorem ipsum
',
  );

  return system_settings_form($form);
}

This works perfectly. What I wanted to so is returning a form and page content together, i.e after the page content, in a menu callback function; I tried using the following code:
function mymodule_page() {
  $variable =  drupal_get_form('test_form');
  $variable .= '
here
';

  return $variable;
}

But it prints something like the following:

    Array
    here

How do I return both the form and content together in a menu callback?
Comment: In Drupal 7, the arguments for your `test_form()` are `test_form($form, &$form_state)`; you should then remove the `$form = array()` line from that form builder. See [Form generation](http://api.drupal.org/api/drupal/includes--form.inc/group/form_api/7).
Answer: In Drupal 7 drupal_get_form() returns a render array instead of a string, so you should return a render array as well:
return array(
  'my_content' => array(
    '#type' => 'markup',
    '#markup' => 'Some markup',
  ),
  'my_form' => drupal_get_form(...),
);

Comment: you mean to say i cannot return both form and other contents together ?? because the content after the form will be more then a markup ie. it will have a image and other content also. So is there any other way to do it?


Qual a diferença nos métodos Refresh, Update, Repaint, Invalidate e no Application.ProcessMessages?

Question: Qual a diferença entre os métodos:

Refresh, de TControl;
Update, de TControl;
Repaint, também deTControl; e,
Invalidate, também de TControl;
Além do Application.ProcessMessages?
Answer: Invalidate
O método Invalidate só marca o componente para ser pintado na próxima vez que a interface for atualizada. Ele não re-desenha o componente no momento que foi chamado.
Update
Método que re-deseha o componente imediatamente, desde que ele já tenha sido invalidado, sem esperar pelo processamento das mensagens de re-desenhar pelo Windows. Gera consumo de tempo de processador pois vais parar todas as atividades da thread principal da aplicação para redesenhar.
Isto quer dizer que, se você tiver alterado algo que implique em mudança visual, e o componente não tiver sido Invalidado, depois do update a alteração pode não ser processsada.
Repaint
O repaint força o componente a se re-desenhar imediatamente. Se a propriedade ControlStyle incluir csOpaque, o componente irá redesenhar-se, senão será executado o método Invalidate e logo depois o método Update
Refresh
Segundo a documentação o Refresh executa o Repaint, e portanto fazem exatamente a mesa coisa, tanto que consta ainda que eles são intercambiáveis, isto é, tanto faz usar um ou o outro
Application.ProcessMessages
Força a aplicação a processar as mensagem do Windows.
Quando a aplicação está realizando uma operação de alto custo de processamento, ou realizando um loop, a thread fica ocupada realizando aquela operação e não realiza o processamento de nenhuma mensagem do Windows para a aplicação, como um clique em um componente, o pressionamento de uma tecla ou neste caso a atualização dos componentes gráficos da aplicação.
Ser chamar o método Invalidate e logo depois Application.ProcessMessages, o windows irá tratar da mensagem do Invalidate e providenciar o re-desenho da janela ou do componente, juntamente com todas as demais mensagens.


Expected class, delegate, enum, interface, or struct in c#

Question: this is my code
 using System;
 using System.Collections;
 using System.Collections.Generic;
 using System.Data;
 using System.Diagnostics;
 public partial class Class1
  {

     public void method2()
      {

          }

   }

I saw the solution for brackets problem but its in proper manner as you can see . whats the cause of this error can any one help me? i am using asp.net 1.1.
Comment: Please don't vote to close just because it works on your machine. That is selfish.
Comment: The code above compiles perfectly well. But you usually put your class inside a namespace.
Comment: What error are you getting. The code you have supplied will compile perfectly.
Comment: There is nothing wrong with this block of code. The error must be coming from a different piece of code. could you post all of the code in the file?
Comment: pls uplift your vote to this question thanks :)
Answer: The partial keyword is not supported in C# 1.x. You need to update your framework to v2.0 at least.
Comment: Hi Danny pls uplift my vote because currently my account is banned to ask question.
Answer: Partial classes are not supported in C# 1.x.
Comment: hi abdul please uplift my vote for question so that I can ask questions :)
Answer: Partial classes are not supported in C# 1.x. This will fix it.