Menu dropdown movendo divs abaixo

Question: O meu menu dropdown está movendo todas as divs abaixo dele.
Aqui está o html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

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

<link rel="stylesheet" type="text/css" href="estilo_home.css"/>

Asa de Livro

Home

Missão

Categorias

Notícias

Brasil

Mundo

Cadastre-se

Contato

Lojas

SP

São Paulo

Guarulhos

Tatuí

MG

BH

Ouro Preto

Nova Lima

RJ

 Oferta Limitada! Apenas R$30,00
 1984 - George Orwell

 Oferta Limitada! Apenas R$20,00
 A Farsa - Christopher Reich

Lançamentos

Box Trilogia Sprawl - R$109,90

Inferno - Dan Brown - R$70,00

  Site convida autores consagrados a indicar escritores em início de carreira

Diante de estantes abarrotadas pela sempre crescente oferta de títulos, quem visita uma livraria pode sair sem saber quais são as novas obras relevantes para a literatura brasileira. Para orientar o público, escritores já consagrados podem ser boas referências, apadrinhando um ou outro novato e os apresentando a seus pares e leitores. Leia mais.

  "Clube da leitura" de Mark Zuckerberg faz vendas de livro dispararem

 Mark Zuckerberg, cofundador e CEO do Facebook, traçou um plano para 2015: ler um livro a cada quinze dias e comentá-lo na rede social. Na verdade, a ideia é mais elaborada: Zuckerberg escolhe uma obra, informa o título aos participantes do clube do livro, página que ele criou (chamada A Year of Books), e duas semanas depois realiza um debate público com o autor da obra. Nesta terça-feira, ocorreu o primeiro encontro virtual, com o escritor venezuelano Moisés Naím, autor de O Fim do Poder

 Oferta Limitada! Apenas R$40,00
 A Rosa e o Povo - Carlos Drummond de Andrade

 Oferta Limitada! Apenas R$47,00
 Quem é você Alasca? - John Green

Matriz: Rua das Flores, nº20 - Funcionários - Belo Horizonte - Minas Gerais | Tel: (31)3854-7952; (31)9851-7412

CSS
    @charset "utf-8";
/* CSS Document */

body{font-size:62.5%;}

div{border: #000 solid 1px;}

#mae{
    width:95%;
    min-height:80em;
    margin:auto;
    padding:0.3em;
    background-color:#FC6;
    }

#topo{
    width:98%;
    height:15em;
    margin-left:0.9%;
    background:url(Imagens/livros4.jpg);
    border:none;
}

#titulo{
    width:45%;
    min-height:5em;
    border:none;
    margin-left: 35em;
    }

#titulo a{
    text-decoration:none;
    font:Verdana, Geneva, sans-serif;
    font-size:9em;
    color:#000;
    font-weight:bold;
    }

#menu{
    width:98%;
    height:4em;
    margin-left:0.9%;
    margin-top:0.1%;
    }

#menuh{
    width: 70%;
    height: 3em;
    margin-left: 20em;
    margin-top:0.7em;
    }

#promocoes1{
    width:15%;
    height:50em;
    margin-left:0.9%;
    margin-top:0.2%;
    float:left;
    }

#conteudo{
    width:66.5%;
    height:50em;
    margin-left:0.3%;
    margin-top:0.2%;
    float:left;
    }

#promocoes2{
    width:15%;
    height:50em;
    margin-left:0.3%;
    margin-top:0.2%;
    float:left;
    margin-bottom:0.2%;
    }

#rodape{
    width:98%;
    height:7em;
    margin-left:0.9%;
    clear:both;
    }

#menuh ul  {
    list-style:none;
    margin:0;
    padding:0;
    display:inline;
    }

#menuh ul li{
    float:left;
    }

ul li a{
    display:block;
    background-color:#FC6;
    color:#663300;
    text-decoration:none;
    font-size:1.5em;
    width:8em;
    height:1.5em;
    text-align:center;
    margin-bottom:1px;
    margin-left:0.1em;
    border: #663300 1px solid;

    }

ul li a:hover{
    color:#600;
    font-weight:bold;
    }

ul li ul li a:hover{
    background-color:#F60;
    display:block;}

ul li ul li ul li a{
    width:6em;
    }

ul li ul li{display:none;
    clear:both;
    position:absolute;}

ul li:hover ul li{
    display:block;
}

ul li ul li{
    position:relative;
    }

ul li ul li ul{
    display:none;
    margin-top:0.1em;
    position:absolute;
    left:12.3em;
    top:-0.6px;

    }

ul li ul li:hover ul{
    display:block;
    }

#rodape p {
    font:Verdana, Geneva, sans-serif;
    font-size:1.5em;
    color: #663300;
    margin-left:24em;
    margin-top:2em;
    }

div.prom{
    width:70%;
    min-height:16em;
    margin:auto;
    margin-top:5em;
    border:none;
    }

div.lanc{
    width:15%;
    min-height:14em;
    margin-left: 1.5em;
    margin-top:1.5em;
    border:none;
    font:Verdana, Geneva, sans-serif;
    font-size:1.3em;
    color: #663300;
    float:left;
    }

#noticia_rap{
    width:80%;
    min-height:3em;
    margin-left: 1.5em;
    margin-top:1.5em;
    border:none;
    font:Verdana, Geneva, sans-serif;
    font-size:1.3em;
    color: #663300;
    float:left;
    }

Comment: Tem demasiado código nessa pergunta. Dá para usar este jsFiddle e simplificar o exemplo do problema? -> https://jsfiddle.net/yu8t49z0/
Comment: Quando for perguntar, procure por abstrair o problema e o ilusionar para que possamos entender o problema em si e não ter que analisar e ficar chutando possíveis erros no seu código, isso facilita para nós e consequentemente você terá uma resposta melhor e que poderá ajudar outros usuários.
Answer: Para que o dropdown não altere o resto da estrutura, adicione:
ul li:hover ul li{
    display:block;
    position:absolute;
}

Realmente tem muito código na sua pergunta, e a quantidade de uls e lis confunde um pouco então você deveria dar uma refatorada nesse código, mas de imediato para a tua pergunta é só inserir o
position:absolute

no lugar certo.

Menu dropdown movendo divs abaixo


File structure of libraries folder and detection of module external plugins

Question: The module CKeditor anchor link require a CKEditor plugin.
Can this plugin be placed in subfolder of the /libraries folder or does it have imperatively to be placed at the root of /libraries ?
More generally, does drupal parse recursively the libraries folder when intenting to detect external plugins ?
Comment: I'm voting to close this question because there is documentation for this. Please read the module's [README.md](https://git.drupalcode.org/project/anchor_link/-/blob/8.x-2.x/README.md) file before asking installation questions.
Comment: @No Sssweat Up to u. As far as i am concerned, that change of usage is good to know for those that do not know it
Answer: The libraries folder is no longer managed by Drupal. The project Libraries doing this jobs in older Drupal versions seems to be deprecated in favor of a composer based concept. Modules still using the libraries folder use their own logic and you have to follow their instructions on the project page or README.


mysterious rtm abort using haswell tsx

Question: I'm experimenting with the tsx extensions in haswell, by adapting an existing medium-sized (1000's of lines) codebase to using GCC transactional memory extensions (which indirectly are using haswell tsx in this machine) instead of coarse grained locks. I am using GCC's transactional_memory extensions, not writing my own _xbegin / _xend directly.  I am using the ITM_DEFAULT_METHOD=htm
I'm having issues getting it to work fast enough because I get high rates of hardware transaction abort for mysterious reasons. As shown below, these aborts are not due to conflicts nor due to capacity limitations.
Here is the perf command I used to quantify the failure rate and underlying causes:
perf stat \
 -e cpu/event=0x54,umask=0x2,name=tx_mem_abort_capacity_write/ \
 -e cpu/event=0x54,umask=0x1,name=tx_mem_abort_conflict/ \
 -e cpu/event=0x5d,umask=0x1,name=tx_exec_misc1/ \
 -e cpu/event=0x5d,umask=0x2,name=tx_exec_misc2/ \
 -e cpu/event=0x5d,umask=0x4,name=tx_exec_misc3/ \
 -e cpu/event=0x5d,umask=0x8,name=tx_exec_misc4/ \
 -e cpu/event=0x5d,umask=0x10,name=tx_exec_misc5/ \
 -e cpu/event=0xc9,umask=0x1,name=rtm_retired_start/ \
 -e cpu/event=0xc9,umask=0x2,name=rtm_retired_commit/ \
 -e cpu/event=0xc9,umask=0x4,name=rtm_retired_aborted/pp \
 -e cpu/event=0xc9,umask=0x8,name=rtm_retired_aborted_misc1/ \
 -e cpu/event=0xc9,umask=0x10,name=rtm_retired_aborted_misc2/ \
 -e cpu/event=0xc9,umask=0x20,name=rtm_retired_aborted_misc3/ \
 -e cpu/event=0xc9,umask=0x40,name=rtm_retired_aborted_misc4/ \
 -e cpu/event=0xc9,umask=0x80,name=rtm_retired_aborted_misc5/ \
./myprogram -th 1 -reps 3000000

So, the program runs some code with transactions in it 30 million times. Each request involves one transaction gcc __transaction_atomic block.  There is only one thread in this run.
This particular perf command captures most of the relevant tsx performance events described in the Intel software developers manual vol 3.
The output from perf stat is the following:
             0 tx_mem_abort_capacity_write                                  [26.66%]
             0 tx_mem_abort_conflict                                        [26.65%]
    29,937,894 tx_exec_misc1                                                [26.71%]
             0 tx_exec_misc2                                                [26.74%]
             0 tx_exec_misc3                                                [26.80%]
             0 tx_exec_misc4                                                [26.92%]
             0 tx_exec_misc5                                                [26.83%]
    29,906,632 rtm_retired_start                                            [26.79%]
             0 rtm_retired_commit                                           [26.70%]
    29,985,423 rtm_retired_aborted                                          [26.66%]
             0 rtm_retired_aborted_misc1                                    [26.75%]
             0 rtm_retired_aborted_misc2                                    [26.73%]
    29,927,923 rtm_retired_aborted_misc3                                    [26.71%]
             0 rtm_retired_aborted_misc4                                    [26.69%]
           176 rtm_retired_aborted_misc5                                    [26.67%]

  10.583607595 seconds time elapsed

As you can see from the output:

The rtm_retired_start count is 30 million (matches input to program)
The rtm_retired_abort count is about the same (no commits at all)
The abort_conflict and abort_capacity counts are 0, so these are not the reasons. Also, recall it is only one thread running, conflicts should be rare.
The only actual leads here are the high values of tx_exec_misc1 and rtm_retired_aborted_misc3, which are somewhat similar in description.

The Intel manual (vol 3) defines rtm_retired_aborted_misc3 counters:

code: C9H 20H

mnemonic: RTM_RETIRED.ABORTED_MISC3

description: Number of times an RTM execution aborted due to HLE unfriendly instructions.

The definition for tx_exec_misc1 has some similar words:

code: 5DH 01H

mnemonic: TX_EXEC.MISC1

description: Counts the number of times a class of instructions that may cause a transactional abort was executed. Since this is the count of execution, it may not always cause a transactional abort.

I checked the assembly location for the aborts using perf record/ perf report using high precision (PEBS) support for rtm_retired_aborted. The location has a mov instruction from register to register.  No weird instruction names seen nearby.
Update:
Here are two things I've tried since then:
1)  the tx_exec_misc1 and rtm_retired_aborted_misc3 signature we we see here can be obtained, for example, by a dummy block of the form
for (int i = 0; i < 10000000; i++){
  __transaction_atomic{
    _xabort(1);
  }
}

or one of the form
for (int i = 0; i < 10000000; i++){
  __transaction_atomic{
    printf("hello");
    fflush(stdout);
  }
}

In both cases, the perf counters look similar to what I see. However, in both cases the perf report for -e cpu/tx-abort/  points to the intuitively correct assembly lines: an xabort instruction for the first example and a syscall one for the second one.  In the real codebase, the perf report points to a stack push right at the start of a function:
           :    00000000004167e0 <myns::myfun()>:
    100.00 :      4167e0:       push   %rbp
      0.00 :      4167e1:       mov    %rsp,%rbp
      0.00 :      4167e4:       push   %r15

I have also run the same command under the intel software development emulator. It turns out that the problem goes away in that case: I get no aborts as far as the application is concerned.
Comment: Could you post your transactional loop?
Comment: Hi Matthew. Unfortunately its a somewhat large loop (spans multiple function calls, some of the functions are textually large, though the actual execution path need not be).
Comment: Is it possible for you to start cutting down the loop to see what's triggering this? This sounds like an accidental system call somewhere... though your perf results seem a bit bizarre.
Comment: I will try to, will be back in a few days. Thanks!
Answer: Though it's been the case for a while, I found this unanswered question while searching, so here's the answer: This is a hardware bug in Haswell and early Broadwell chips.
The particular hardware erratum assigned by Intel is HSW136, and is not fixable using microcode updates. Indeed, I think it was in stepping 4 that the feature was no longer reported as available by the cpuid instruction, even when there was (faulty) silicon on the chip to implement it.
Comment: Microcode updates have disabled TSX in Broadwell as well.  And due to TAA vulnerabilities, most Skylake-family CPUs also have HLE disabled in microcode, with RTM always aborting.  (Or the OS can set a bit to not advertize the useless "feature")
 https://www.intel.com/content/www/us/en/support/articles/000059422/processors.html .
 And the feature has been removed from Ice Lake.  https://en.wikipedia.org/wiki/Transactional_Synchronization_Extensions#History_and_bugs

mysterious rtm abort using haswell tsx


O que significa offset no pillow?

Question: O método getoffset() da classe PIL.ImageFont.FreeTypeFont retorna uma tupla. O que são essas medidas exatamente?
Utilizo o Pillow na versão 6.1.0.
Comment: Que versão do Pillow você se refere?
Comment: Chegou a ver na [documentação](https://pillow.readthedocs.io/en/stable/reference/ImageFont.html?highlight=getoffset#PIL.ImageFont.FreeTypeFont.getoffset)?
Comment: @fernandosavio Isso não é da classe `PIL.ImageFont.FreeTypeFont`?
Comment: Yep, essa documentação me deixou mais confuso que surdo em bingo...
Ignora meu comentário anterior..
Comment: Olha não conheço, pillow, mas para mim tais valores dizem respeito as coordenadas x,y no plano cartesiano do objeto em questão.
Comment: Sim, recorri ao fórum pq também achei a documentação bem confusa. Me refiro à versão 6.1.0.
Comment: Anderson, sim a classe é PIL.ImageFont.FreeTypeFont. Obrigado pela correção, irei editar.
Answer: "offset" significa "deslocamento" -
O método .getoffset de objetos do tipo "Font" dentro do módulo ImageFont requer uma string de texto - e devolve a posição, em pixels, a partir da qual ele começaria a desenhar texto se aquele texto fosse ser desenhando em uma imagem.
Para quase todas as strings o retorno é "0, 0" - se você não está criando um programa para typesetting, e usando caracteres especiais bem estranhos, não vai encontrar nenhum caso em que o retorno do .getoffset vai ser diferente de 0,0 -
e, de qualquer forma, ele é desenhado para ser usado internamente pelas funções que de fato vão desenhar o texto nas imagens (usando, em geral, o método text de um objeto ImageDraw.Draw - você passa a fonte como parâmetro pra ele, e, o uso interno desse método é que vai usar  .getoffset, .getmask, etc... na fonte).
Resumindo:

o valor é o deslocamento em pixels onde o desenho de uma fonte vai começar
o valor retornado vai ser quase sempre (0, 0)
você não precisa chamar esse método diretamente
Comment: Muito obrigado, jsbueno!

O que significa offset no pillow?


How to acces gmap markers after map is generated?

Question: I've got a problem with Google map markers and I don't find a way to solve it.
I've got a map page view generated with the GMap module where I show certain nodes. I've got also a view block that show some of the same nodes that appear in the map in an unformatted list. What I need is to relate the nodes on the list with their respective markers in the map (so hovering the list change the marker icon or vice versa).
I could relate the nodes with the markers since I've got the exact coordinates of the node which coincide with the marker coordinates (obviously). My problem is that I don't know how to get a list of the existing markers on the map.
From what I've read I should push the markers in an array when they're generated so later I can acces to the markers using the elements in the array, but I couldn't found where does gmap generate the markers. I've tried creating a global array and pushing the markers in the gmap_marker.js inside:
obj.bind('addmarker', function (marker) {
  // ... //
    mymarker.push(marker.marker);
}

but even I can see any result. I tried counting the markers that are generated  with something like countmarkers += 1; but the output is also 0.
Anyone has a clue on hou could I achieve this? Any advice would be appreciated.

Edit:  Ok, I solved this problem.  It looks like what I did was fine
  and the problem was in the timing of the process. I called:
mymarkers.forEach(function(marker) {
        //funciona OK
        alert(marker.getPosition().lat() + ' - ' + marker.getPosition().lng());
    });

inside a setTimeout(function(){}); with a 10ms delay. By increasing
  the delay to 5000ms all the markers have enough time to be created and
  I can finally access the markers array.
Comment: `mymarkersarray[] = marker;` is not valid javascript, start with that
Comment: sorry I wrote this without the code in front of me, It's actually something like: 'mymarkers.push(marker);'
Answer: Here is a quote from the Comparison of mapping modules:

GMap is considered a legacy module.

So maybe you want to have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (Google, OpenLayers or Leaflet) with any location storage module of your choice, e.g.:

Get Locations,
Geofield,
Geolocation Field
Location.

This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).

Head over to its (impressive) project page for even more information about it (it would be way too long to include a quote of it all here). That project page also includes various screenshots.
Comment: Thanks for your answer but my question was more related with the specific issue of acessing the marker js objects of the map. I'll take your answer as a reference for future projects (changing the mapping module would take too much time in the current project which is almost finished).
Comment: Merci Miquel for your feedback, and considering it for future projects. About your "*... current project ...*": ***There is never time to do it right, but always time to do it again***", right?
Comment: Off course you're right but that's something which is not in my hands. :)
Comment: Yet another way to look at it: first try to make it work with gmap (whatever it takes), trying to deliver what the customer asked for. After you succeeded, suggest the customer a recommended alternative "for the next version of the site" (which didn't make it in the prior version due to deadlines coming close) ...


How to put line breaks every 30 records

Question: I have a program that writes MySQL data to Excel via PHPExcel and I am having no errors but the problem is they don't have any line breaks in every 30 records.
How can I achieve this programmatically in PHPExcel?
This is my code:
<code>require 'PHPExcel.php';
require 'PHPExcel/Writer/Excel2007.php';
require 'PHPExcel/IOFactory.php';

$user = "root";
$pass = "admin";
$host = "localhost";
$db = "hrtms";
$dept = "WAREHOUSE/DRIVER";
$TimeIn = "";
$LunchOut = "";
$LunchIn = "";
$TimeOut = "";
$objPHPExcel = new PHPExcel();
try{
$con = new PDO("mysql:host=$host;dbname=$db",$user,$pass);
$con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$con->exec('SET NAMES "utf8"');
}
catch(PDOException $e){
echo $e->getMessage();
exit();
}

try{
$query = $con->prepare("SELECT * FROM emptb WHERE Department = :dept ORDER BY id ASC");
$query->bindParam(':dept',$dept);
$query->execute();
}
catch(PDOException $e){
echo $e->getMessage();
exit();
}
$objPHPExcel->setActiveSheetIndex(0);
//set default font
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setName('Verdana');
//set titles
$objPHPExcel->getActiveSheet()->SetCellValue('B1','EMPLOYEE ATTENDANCE LOGS');
//$objPHPExcel->getActiveSheet()->getStyle('B1')->getAlignment()->setWrapText(true);
//merge cells
$objPHPExcel->getActiveSheet()->mergeCells('B1:T1');
$objPHPExcel->getActiveSheet()->mergeCells('C4:D4');
$objPHPExcel->getActiveSheet()->mergeCells('E8:F8');

//set text alignment
$objPHPExcel->getActiveSheet()->getStyle('B1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setSize(18);
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFill()->getStartColor()->setARGB('#333');
//set column width
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(6.14);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(0.67);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(10.86);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(1.43);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(9.71);
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(1.43);
$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(6.71);
$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(1.57);
$objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(2);
$objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(9);
$objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(0.58);
$objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(0.92);
$objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(9);
$objPHPExcel->getActiveSheet()->getColumnDimension('N')->setWidth(1.71);
$objPHPExcel->getActiveSheet()->getColumnDimension('O')->setWidth(2.43);
$objPHPExcel->getActiveSheet()->getColumnDimension('P')->setWidth(6.14);
$objPHPExcel->getActiveSheet()->getColumnDimension('Q')->setWidth(1.71);
$objPHPExcel->getActiveSheet()->getColumnDimension('R')->setWidth(9.29);
$objPHPExcel->getActiveSheet()->getColumnDimension('S')->setWidth(4);
$objPHPExcel->getActiveSheet()->getColumnDimension('T')->setWidth(0.67);
$objPHPExcel->getActiveSheet()->getColumnDimension('U')->setWidth(0.67);
//set text alignment
$rowCount = 4;
while($row = $query->fetch())
{
    $rowTitle = $rowCount + 2;
    $rowTitle1 = $rowCount + 4;
    //data label
    $objPHPExcel->getActiveSheet()->getStyle('C'.$rowCount)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    $objPHPExcel->getActiveSheet()->mergeCells('C'.($rowCount).':D'.($rowCount));
    $objPHPExcel->getActiveSheet()->getStyle('C'.$rowCount)->getAlignment()->setWrapText(true);
    $objPHPExcel->getActiveSheet()->getStyle('C'.$rowCount)->getFont()->setBold(true);
    $objPHPExcel->getActiveSheet()->getStyle('C'.$rowCount)->getFont()->setSize(12);
    $objPHPExcel->getActiveSheet()->getStyle('C'.$rowCount)->getFont()->setName('Arial');
    $objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount,'ID No:');

    $objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    $objPHPExcel->getActiveSheet()->mergeCells('C'.($rowTitle).':D'.($rowTitle));
    $objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle)->getAlignment()->setWrapText(true);
    $objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle)->getFont()->setBold(true);
    $objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle)->getFont()->setSize(12);
    $objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle)->getFont()->setName('Arial');
    $objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowTitle,'Name:');

    $objPHPExcel->getActiveSheet()->getStyle('I'.$rowCount)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    $objPHPExcel->getActiveSheet()->mergeCells('I'.($rowCount).':J'.($rowCount));
    $objPHPExcel->getActiveSheet()->getStyle('I'.$rowCount)->getAlignment()->setWrapText(true);
    $objPHPExcel->getActiveSheet()->getStyle('I'.$rowCount)->getFont()->setBold(true);
    $objPHPExcel->getActiveSheet()->getStyle('I'.$rowCount)->getFont()->setSize(12);
    $objPHPExcel->getActiveSheet()->getStyle('I'.$rowCount)->getFont()->setName('Arial');
    $objPHPExcel->getActiveSheet()->SetCellValue('I'.$rowCount,'Dept:');

    $objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle1)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    $objPHPExcel->getActiveSheet()->mergeCells('C'.($rowTitle1).':D'.($rowTitle1));
    $objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle1)->getAlignment()->setWrapText(true);
    $objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle1)->getFont()->setBold(true);
    $objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle1)->getFont()->setSize(12);
    $objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle1)->getFont()->setName('Arial');
    $objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowTitle1,'Section:');

    $objPHPExcel->getActiveSheet()->getStyle('I'.$rowTitle1)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    $objPHPExcel->getActiveSheet()->mergeCells('I'.($rowTitle1).':J'.($rowTitle1));
    $objPHPExcel->getActiveSheet()->getStyle('I'.$rowTitle1)->getAlignment()->setWrapText(true);
    $objPHPExcel->getActiveSheet()->getStyle('I'.$rowTitle1)->getFont()->setBold(true);
    $objPHPExcel->getActiveSheet()->getStyle('I'.$rowTitle1)->getFont()->setSize(12);
    $objPHPExcel->getActiveSheet()->getStyle('I'.$rowTitle1)->getFont()->setName('Arial');
    $objPHPExcel->getActiveSheet()->SetCellValue('I'.$rowTitle1,'Line:');
    //data contents
    $objPHPExcel->getActiveSheet()->mergeCells('E'.($rowCount).':G'.($rowCount));
    $objPHPExcel->getActiveSheet()->getStyle('E'.$rowCount)->getAlignment()->setWrapText(true);
    $objPHPExcel->getActiveSheet()->SetCellValue('E'.$rowCount,$row['EmpID']);
    $objPHPExcel->getActiveSheet()->getStyle('E'.$rowCount)->getFont()->setBold(true);
    $objPHPExcel->getActiveSheet()->getStyle('E'.$rowCount)->getFont()->setSize(12);
    $objPHPExcel->getActiveSheet()->getStyle('E'.$rowCount)->getFont()->setName('Arial');

    $objPHPExcel->getActiveSheet()->mergeCells('E'.($rowTitle).':S'.($rowTitle));
    $objPHPExcel->getActiveSheet()->SetCellValue('E'.$rowTitle,$row['Lastname'] . ', ' . $row['Firstname']);
    $objPHPExcel->getActiveSheet()->getStyle('E'.$rowTitle)->getFont()->setBold(true);
    $objPHPExcel->getActiveSheet()->getStyle('E'.$rowTitle)->getFont()->setSize(12);
    $objPHPExcel->getActiveSheet()->getStyle('E'.$rowTitle)->getFont()->setName('Arial');

    $objPHPExcel->getActiveSheet()->mergeCells('L'.($rowCount).':S'.($rowCount));
    $objPHPExcel->getActiveSheet()->SetCellValue('L'.$rowCount,$row['Department']);
    $objPHPExcel->getActiveSheet()->getStyle('L'.$rowCount)->getFont()->setBold(true);
    $objPHPExcel->getActiveSheet()->getStyle('L'.$rowCount)->getFont()->setSize(12);
    $objPHPExcel->getActiveSheet()->getStyle('L'.$rowCount)->getFont()->setName('Arial');

    $objPHPExcel->getActiveSheet()->SetCellValue('E'.$rowTitle1,$row['SectionName']);
    $objPHPExcel->getActiveSheet()->getStyle('E'.$rowTitle1)->getFont()->setBold(true);
    $objPHPExcel->getActiveSheet()->getStyle('E'.$rowTitle1)->getFont()->setSize(12);
    $objPHPExcel->getActiveSheet()->getStyle('E'.$rowTitle1)->getFont()->setName('Arial');

    $objPHPExcel->getActiveSheet()->SetCellValue('L'.$rowTitle1,$row['LineName']);
    $objPHPExcel->getActiveSheet()->getStyle('L'.$rowTitle1)->getFont()->setBold(true);
    $objPHPExcel->getActiveSheet()->getStyle('L'.$rowTitle1)->getFont()->setSize(12);
    $objPHPExcel->getActiveSheet()->getStyle('L'.$rowTitle1)->getFont()->setName('Arial');
    $rowCount++;

    try{
        $subquery = $con->prepare("SELECT c.dt,a.TimeIn,a.LunchOut,a.LunchIn,a.RNDOUT FROM cal c LEFT JOIN attendance a ON a.ValidDate = c.dt
        AND a.EmpID = :id WHERE c.dt BETWEEN DATE('2015-08-01') AND DATE('2015-08-30') GROUP BY c.dt ORDER BY c.dt ASC");
        $subquery->bindParam(':id',$row['EmpID']);
        $subquery->execute();
    }
    catch(PDOException $e){
        echo $e->getMessage();
        exit();
    }
    $rowCount += 6;
    while($subrow = $subquery->fetch())
    {

        if($subrow['TimeIn'] == "00:00:00")
        {
            $TimeIn = "";
        }
        else
        {
            $TimeIn = $subrow['TimeIn'];
        }

        if($subrow['LunchOut']=="00:00:00")
        {
            $LunchOut = "";
        }
        else
        {
            $LunchOut = $subrow['LunchOut'];
        }

        if($subrow['LunchIn']=="00:00:00")
        {
            $LunchIn = "";
        }
        else
        {
            $LunchIn = $subrow['LunchIn'];
        }

        if($subrow['RNDOUT']=="00:00:00")
        {
            $TimeOut = "";
        }
        else
        {
            $TimeOut = $subrow['RNDOUT'];
        }
        $titleRow = 10;
        $objPHPExcel->getActiveSheet()->getStyle('C'.$titleRow)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('C'.$titleRow)->getFont()->setBold(true);
        $objPHPExcel->getActiveSheet()->getStyle('C'.$titleRow)->getFont()->setSize(11);
        $objPHPExcel->getActiveSheet()->getStyle('C'.$titleRow)->getFont()->setName('Arial');
        $objPHPExcel->getActiveSheet()->SetCellValue('C'.$titleRow,'Date');
        $objPHPExcel->getActiveSheet()->getStyle('E'.$titleRow)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('E'.$titleRow)->getFont()->setBold(true);
        $objPHPExcel->getActiveSheet()->getStyle('E'.$titleRow)->getFont()->setSize(11);
        $objPHPExcel->getActiveSheet()->getStyle('E'.$titleRow)->getFont()->setName('Arial');
        $objPHPExcel->getActiveSheet()->SetCellValue('E'.$titleRow,'TimeIn');
        $objPHPExcel->getActiveSheet()->getStyle('G'.$titleRow)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('G'.$titleRow)->getFont()->setBold(true);
        $objPHPExcel->getActiveSheet()->getStyle('G'.$titleRow)->getFont()->setSize(11);
        $objPHPExcel->getActiveSheet()->getStyle('G'.$titleRow)->getFont()->setName('Arial');
        $objPHPExcel->getActiveSheet()->SetCellValue('G'.$titleRow,'LunchOut');
        $objPHPExcel->getActiveSheet()->getStyle('J'.$titleRow)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('J'.$titleRow)->getFont()->setBold(true);
        $objPHPExcel->getActiveSheet()->getStyle('J'.$titleRow)->getFont()->setSize(11);
        $objPHPExcel->getActiveSheet()->getStyle('J'.$titleRow)->getFont()->setName('Arial');
        $objPHPExcel->getActiveSheet()->SetCellValue('J'.$titleRow,'LunchIn');
        $objPHPExcel->getActiveSheet()->getStyle('M'.$titleRow)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('M'.$titleRow)->getFont()->setBold(true);
        $objPHPExcel->getActiveSheet()->getStyle('M'.$titleRow)->getFont()->setSize(11);
        $objPHPExcel->getActiveSheet()->getStyle('M'.$titleRow)->getFont()->setName('Arial');
        $objPHPExcel->getActiveSheet()->SetCellValue('M'.$titleRow,'TimeOut');
        $titleRow++;

        $objPHPExcel->getActiveSheet()->getStyle('C'.$rowCount)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('C'.$rowCount)->getFont()->setSize(10);
        $objPHPExcel->getActiveSheet()->getStyle('C'.$rowCount)->getFont()->setName('Arial');
        $objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount,$subrow['dt']);
        $objPHPExcel->getActiveSheet()->getStyle('E'.$rowCount)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('E'.$rowCount)->getFont()->setSize(10);
        $objPHPExcel->getActiveSheet()->getStyle('E'.$rowCount)->getFont()->setName('Arial');
        $objPHPExcel->getActiveSheet()->SetCellValue('E'.$rowCount,$TimeIn);
        $objPHPExcel->getActiveSheet()->getStyle('G'.$rowCount)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('G'.$rowCount)->getFont()->setSize(10);
        $objPHPExcel->getActiveSheet()->getStyle('G'.$rowCount)->getFont()->setName('Arial');
        $objPHPExcel->getActiveSheet()->SetCellValue('G'.$rowCount,$LunchOut);
        $objPHPExcel->getActiveSheet()->getStyle('J'.$rowCount)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('J'.$rowCount)->getFont()->setSize(10);
        $objPHPExcel->getActiveSheet()->getStyle('J'.$rowCount)->getFont()->setName('Arial');
        $objPHPExcel->getActiveSheet()->SetCellValue('J'.$rowCount,$LunchIn);
        $objPHPExcel->getActiveSheet()->getStyle('M'.$rowCount)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('M'.$rowCount)->getFont()->setSize(10);
        $objPHPExcel->getActiveSheet()->getStyle('M'.$rowCount)->getFont()->setName('Arial');
        $objPHPExcel->getActiveSheet()->SetCellValue('M'.$rowCount,$TimeOut);
        $rowCount++;
    }
}
$excelWriter = PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel2007');
header('Content-Type:application/ms-excel');
header('Content-Disposition:attachment;filename="'.$dept.'.xlsx"');
header('Cache-Control:max-age=0');
$excelWriter->save('php://output');
</code>
Comment: Can you provide your code?
Answer: If you mean every 30 rows of the spreadsheet, then use the print setup options as described in the documentation:
<code>$objPHPExcel->getActiveSheet()
    ->setBreak('A10' , PHPExcel_Worksheet::BREAK_ROW);
</code>
will set a print break on row 10
So just set those breakpoints every 30 rows as you're building the worksheet
Comment: where should i put it? inside the while loop or outside.
Comment: Personally I'd put it inside the while loop, where you're keep a count of your rows anyway, and can easily check the breakpoints
Comment: Thanks I will play with this.
Answer: You only need to use \n if you want to control exactly where a line wraps.
Example:
<code>$objPHPExcel->getActiveSheet()->setCellValue('H5', "Hello\nWorld");
</code>
You should always use double quotes when you add escape sequences in a PHP string.

How to put line breaks every 30 records


Calibration in the large for continuous outcomes

Question: I'm a bit confused around calibration in the large. I usually see it discussed in the context of binary outcomes, but am I correct in thinking it can also be valuable as a part of external validation for a continuous outcome?
Assuming it is still of interest, I have also seen two ways of calculating it

The difference between the mean of the observed/actual values and the mean of the predicted values.
As the intercept of a model of actual values regressed on predicted values.

Maybe (probably) there is some context I'm missing, but these give me considerably different answers. For example:
<code>library(tidyverse)

### make data
set.seed(1)
df <- mtcars %>% as_tibble() %>%
  mutate(
    random = rnorm(nrow(.), 1, 2),
    pred = mpg + random,
  )

### have a look
df %>%
  ggplot(aes(pred, mpg)) +
  geom_abline() +
  geom_point()

### method 1
observed_means <- mean(df$mpg)
predicted_means <- mean(df$pred)
calibration_in_large <- observed_means - predicted_means

calibration_in_large

# method 2
cal_mod <- lm(mpg ~ pred, df)
cal_mod
</code>
Thanks
Answer: I receieved an answer on Twitter from Gary Collins -
In 'method 2' you need to put pred as an offset (see https://sciencedirect.com/science/article/pii/S0895435615005818) so your call in R should be
cal_mod <- lm(mpg ~ offset(pred), df)
and the estimate will agree with 'Method 1'


Erro - Java Maven Não Compila - Release Version Not Supported

Question: Boa tarde pessoal,
Instalei sozinha o intellij no ubuntu versão 18.4. Preciso fazer um projeto Maven. Fiz um teste, criei o projeto e dentro uma classe para fazer um simples Hello world. No entanto só aparece esse erro da foto e não retorna o Hello world, alguém poderia me ajudar ?
Obrigada [Erro que aparece na tela esta na imagem]
Comment: Poste o código em formato de texto e se possível,coloque o erro também ,sugiro que você leia https://pt.meta.stackoverflow.com/questions/8089/guia-de-sobreviv%c3%aancia-do-sopt-vers%c3%a3o-curta?cb=1 e edite seu post para que ele não seja fechado.
Answer: O problema está na versão do Java que você está utilizando para a compilação no Maven.
Você pode corrigir isso de duas formas:
<plugins>
    <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
            <source>1.8</source>
            <target>1.8</target>
        </configuration>
    </plugin>
</plugins>

Ou:
<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

Estas instruções acima são equivalentes.
Sugiro também utilizar a última versão disponível do plugin, atualmente é a 3.8.1.

A partir do Java 9, deve-se utilizar release ao invés de source e target, como abaixo:
<plugins>
    <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
            <release>11</release>
        </configuration>
    </plugin>
</plugins>

Se você estiver utilizando Spring Boot, você pode apenas identificar a versão do Java através da propriedade java.version:
<properties>
    <java.version>11</java.version>
</properties>

Comment: muito obrigada pela ajuda :)
Comment: que bom que deu certo @FabíCanedoYugar :) não esqueça de marcar a resposta como aceita e dar upvote :)


If $T(x) = 0$ implies that $S(x) = 0,$ show that there is a constant $c$ such that $S(x) = c \cdot T(x)$ for all $x \in X.$

Question: Let $X$ be a normed vector space and suppose $T$ and $S$ are in $X^*.$
    If $T(x) = 0$ implies that $S(x) = 0,$ show that there is a constant $c$ such that $S(x) = c \cdot T(x)$ for all $x \in X.$
I somehow relate it to the equivalent of two norms, as the definition gives us a constant. However, I do not know how to solve this quetsion.
Any hint would be appreciated.
Comment: Hint: Suppose that there exists $u$ such that $T(u)\not =0$. For $x\in X$, put $y=x-\frac{uT(x)}{T(u)}$.
Comment: What is the motivation of getting $y = x - \frac{uT(x)}{T(u)}$?
Comment: A good exercise for you is that,    let $T:X \rightarrow R^n$  and $S:X \rightarrow R^m$, with same property you said , try  guess and formulate the conclusion  and then try to prove it ...
Answer: I constructed the following answer based on Kelenner's comment.
If $T(x) = 0$ for all $x \in X,$ then let $c = 0.$
This gives us that $S(x) = 0 = c \cdot T(x).$
Suppose that there exists $u \in X$ such that $T(u) \neq 0.$
Let $y = x - \frac{u \cdot T(x)}{T(u)}.$
Note that $T(y) = 0.$
By assumption, we have $S(y) = 0.$
Note that $S(y) = S(x) - \frac{S(u) \cdot T(x)}{T(u)} = 0.$
This implies that $S(x) = \frac{S(u)}{T(u)} \cdot T(x).$
Comment: Well done ! (+1)


Como saber se uma determinada "classe" esta em uso na minha pagina?

Question: Amigos,
Existem muitas DIVs na minha pagina, preciso checar se alguma ainda nao foi "finalizada", por exemplo:

 conteudo a ser analizado

as DIVs prontas ficam  com outra "class":

 conteudo ja checado

Tentei um JS mas nao funcionou pois nao tenho o elemento, ja que sao centenas e todos com ID diferentes:
if(.hasClass("triagem");){
   //tratamento:
}

outro exemplo que nao tive sucesso:
if(('[id^="triagem"]').classList.contains( 'triagem' ) ) {
                 //tratamento:
            }

Logo, minha pergunta eh:
 como usar java pra confereir se ainda tem alguma div usando a class "triagem" ?
Answer: Roberval, primeiro o seu html está errado, não seria isso:

 conteudo a ser analizado

mas sim isso:

 conteudo a ser analizado

Você pode utilizar $('.triagem').size().
var quantidadeTriagens = $('.triagem').size();
if (quantidadeTriagens > 0){
    console.log('Ainda existem triagens');
}else{
    console.log('Não existem mais triagens, vá para casa descansar.');
}

$('.triagem') irá retornar uma lista com todos os elementos que possuem a classe triagem. A função size vai retornar o tamanho da lista. O resto é história, se o tamanho for 0 não tem nenhuma, se for maior que 0 existe ainda.
Comment: claro, vou explicar melhor.
Comment: Da uma olhada para ver se agora ficou mais claro.
Comment: Ah sim...   obrigado!  foi erro de digitacao desse exemplo...  OUTRA COISA: Poderia repetir como usar o  exemplo { $('.triagem').size(). }  nao entendi?!?!  como usar com um IF por favor!
Comment: Ficou bem facil de enteder!  nem sei como agradecer!!!  vou testar ja! BRIGADAO MESMO!...  outra coisa.. onde voce esta a essa hora da matina escrevendo codigo pros outros?
Comment: Estou morando na India por algum tempo, então aqui é 3PM ;)
Comment: quando voce coloca um "console.log"  no codigo... o que significa?
Comment: meu caro ... acho que to comendo bola.. pensei ter errado a digitacao.. mas ta correto..   ele sempre  retorna "0"  ou vazio.... fiz varios testes... no console por exeplo dou um "$('.memo-list-check')"   e ele retorna 2...  o que voce acha que pode ser?


What exactly is the difference between arranging a piece of music and composing it?

Question: I was always under the impression that the composer wrote the piece, and the "arranger" was the one who made it "fuller" by arranging additional instruments for the piece, adding chords behind the basic melody, etc, but I wanted to know for sure and get a definitive answer.
I was wondering this after watching the credits and hearing the theme from the film Unforgiven Listen here
In the credits it says the score was written by Clint Eastwood and arranged by Lennie Niehaus. I imagine Clint Eastwood was plucking a guitar and came up with the simple melody, and then Lennie Niehaus arranged (composed?) the final composition with accompanying strings, percussion and backing chords.
Three questions I'm hoping to have answered in one reply:
1. Is Lennie Niehaus considered both the arranger and composer?
2. Is this a common way for scores/classical compositions to be written? With someone who is very good at writing basic melodies writing the melody, and a professional musician (usually with a degree in music composition I assume) composing the piece for a full orchestra?
3. If yes to the last question, can one be considered a great musician if he or she simply writes the melody and has other more learned musicians "fine tune" and orchestrate the piece?
For example (in regards to number three), Franz Liszt was an incredible virtuoso pianist and could arrange pieces brilliantly, but as for his completely original compositions, I do not know of any being considered that "great" (The Hungarian Rhapsodies were almost entirely based off gypsy folk tunes). He just (re)arranged the original melody.
Comment: The term 'writing a piece' is nebulous. Lots of pieces have been 'written' - or composed - by people who could not actually 'write' music. They made it up, recorded it, played it to someone else, etc., who then wrote out the music. After that, it may well have been changed around, orchestrated, etc., and that was done by the arranger. Question no. 3 - it doesn't necessarily need a 'great musician' to make up a great tune. The Beatles have to be an example of that - maybe. Depends on one's definition of a great musician.
Comment: In music production for movies, what you call "the arranger" is usually called "the orchestrator". The main reason for splitting up the work between a "composer" and (often several) "orchestrators" is simply to get the job done faster. In many other genres of music, working fast is not such relevant factor.
Comment: @masque, you're underrating Liszt's Transcendental Etudes (listen to the Cziffra versions--he brings out the musicality in them, not just the technical difficulty) and his famous Liebestraum No. 3 (which shows that Liszt doesn't necessarily have to overload on technical difficulty in order to sound good, IMO).
Answer: This is not always separable.  As an extreme case, take "The Musical Offering" by Bach.  Nobody would claim that Frederick the Great was the composer and Bach the arranger, even though the former pitched the theme pervading all of the composition.
Then take something like "Es ist ein Ros entsprungen" in the version of Michael Praetorius: the melody was preexistent, but the four-voice choral setting is definitely very much more than an "arrangement" of melody/harmony.
The German description would be "Melodie: traditionell, Satz: Michael Praetorius".  "Satz" is more than "arrangement": it is basically creating something musically unique out of a given material.  It is also used for the (usually) more constrained task of converting a figured bass harmonic description into a full version, something that was expected to be done on the fly from contemporary Baroque musicians in their own time, just like one expects Jazz musicians to get along with a lead sheet in our times.
The mark of a "mere" arrangement tends to be that it does not add significant musical material.  Something like Ravel's Bolero or Mussorgski's Pictures at an Exhibition started out as piano pieces but were later arranged for orchestra.  Of course, the original did not have a percussion group (even though the piano is an instrument with percussive attack, so usually there are good pointers).  And the variation in loudness and timbre and the ability to sustain long notes (and consequently the potential for slow speed) is so much greater that there are a lot of subtleties to explore and make sensible use of that just aren't there in the original.
An arrangement may add "filler" voices that don't contain harmonical information of its own ("orchestration" would not do that).  And may add repetitions and stuff.  Jazz "arrangements" may add bridges, other phrasing, other harmonies, particularly other bass lines: that again goes more in the direction of "version" than "arrangement".
So there is quite a bit of leeway of where one starts and one stops.
Answer: A composer may need an arranger.  An arranger always needs a composer!
'Composing' may consist of whistling a tune. The arranger takes it from there (and may feel he deserves more recognition than just 'arranger').  I imagine this was the situation with Clint Eastwood and Lennie Niehaus.
Or a modern-day 'arranger' may concoct a piece for wind band using themes from Beethoven's symphonies.
Note that if he had merely re-written a complete symphony for the instruments of a wind band he would have been 'orchestrating' rather than 'arranging'.
Even the film composers who are perfectly capable of doing the whole job themselves often cope with the workload by delivering a complete sketch, with indications of the required instrumentation, to a team of 'orchestrators'.


difference between instantiating before the for loop and instantiating in the for loop

Question: so I've just started learning C# and I got across this exercise that rolls a die N times and then print the number of times each side is rolled. I got the answer however, my question lies on instantiating a Random number object before the loop and in the loop.
my code goes like this (this is instantiation before the loop):
static void DiceRoll(int RollTimes)
    {

        int roll = 0;

        int counter1 = 0;
        int counter2 = 0;
        int counter3 = 0;
        int counter4 = 0;
        int counter5 = 0;
        int counter6 = 0;

        Random rnd = new Random();

        for (int ctr = 0; ctr < RollTimes; ctr++)
        {
            roll = 0;
            roll = (int)rnd.Next(1, 7);

            switch (roll)
            {
                case 1:
                    counter1++;
                    break;

                case 2:
                    counter2++;
                    break;

                case 3:
                    counter3++;
                    break;

                case 4:
                    counter4++;
                    break;

                case 5:
                    counter5++;
                    break;

                case 6:
                    counter6++;
                    break;
            }
        }

        Console.WriteLine("1 is rolled {0} times.", counter1);
        Console.WriteLine("2 is rolled {0} times.", counter2);
        Console.WriteLine("3 is rolled {0} times.", counter3);
        Console.WriteLine("4 is rolled {0} times.", counter4);
        Console.WriteLine("5 is rolled {0} times.", counter5);
        Console.WriteLine("6 is rolled {0} times.", counter6);
    }

and the result is like this:
1 is rolled A times.
2 is rolled B times.
3 is rolled C times.
4 is rolled D times.
5 is rolled E times.
6 is rolled F times.

before I got that right, the instantiation line (Random rnd = new Random();) was in the loop.
for (int ctr = 0; ctr < RollTimes; ctr++)
        {
            roll = 0;
            roll = (int)rnd.Next(1, 7);
            Random rnd = new Random();
            // rest of the code

then the result (at random):
1 is rolled (N) times.
2 is rolled (N) times.
3 is rolled (N) times.
4 is rolled (N) times.
5 is rolled (N) times.
6 is rolled (N) times.

Can somebody explain or enlighten me why the position of instantiation alters the result? Thanks!
Answer: The ideea is that the random object is not actually "random" and to be honest there is no such a thing in reality, except maybe in quantum mechanics. Ok, going back to your problem, to enlight you the ideea is that behind the scenes there is a series ( very complex one ) that for a given starting value ( the default value is zero) next values are computer by grabbing internally the next series value. The complexity of the internal series gives you the feeling that values are actually random. Whenever you instantiate a new Random object with the same seed you will have the same series values. The best pattern would be to use the overloaded constructor that takes a seed and use for the seed value something lime Datetime.Now.Ticks and try to cache your random object.
So the answer is to create a single instance outside the loop and even better use a different seed for each instantiation.


How to determine reliability of a change in an arbitary metric

Question: I have been using a/b testing in order to optimise changes I make to my websites.  Previously, I have set a single conversion goal and have ended up with a conversion rate for each group.  I then used R (with the power.prop.test function) to calculate the power and significance of the change in conversion rate to decide when it is safe to stop the test and be confident that the values have meaning.
I am now able to get information on a wide range of metrics about the site for each group.  However I am not sure how to do the same test for an arbitrary metric - e.g., revenue.  Could someone point me in the right direction?  I am happy to use R so just pointing me at the right set of functions would be great, but I do like to try and understand what I am calculating so any explanations or links to useful site would be even better.
Answer: The simplest method I can recommend in this case is permutation testing. You basically have two groups of values (A and B) and you want to know if B is meaningfully larger than A. Let's say you can measure this as the distance between the mean values of A and B. (This is usually clinically meaningful in the context you mention.)

The null hypothesis is that A and B are "equivalent" which means that we can combine A and B values into a single data set, from which we draw (without replacement) two new groups of values $A_p$ and $B_p$.

Compute differences of the means of $A_p$ and $B_p$.

Repeat the above two steps a large number of times. From this step, you get an entire distribution of differences of means based on the null hypothesis.

Check how often the values in the distribution from the previous step are equally or more extreme than the one you observed in real life.

The result of 4 is how confident you can be in your result.
I gave this example in terms of "differences of means" but it works for any function improvement(A,B) that measures how much B improves over A. You simulate a bunch of A and B sets from the data you have and a null hypothesis that A and B are equivalent, compute the improvement for each simulated pair, and then see how often that is more extreme than the one you've seen.

Another option is the bootstrap:

From A, draw with replacement a new bootstrap replication $A_b$. Do the same with B, getting a bootstrap replication $B_b$.

Compute the improvement on the replicated pair of datasets.

Repeat the above a large number of times. You will get out of it a distribution of improvements that are all plausible given the observed distributions for A and B.

For e.g. a confidence level of 95 %, check if the largest 95 % of values the distribution of improvements from the previous step include 0. If it does, you have not observed a significant effect.

This is in some ways more indirect (you are using bootstrap replications to approximate the sampling distribution of the underlying problem, instead of showing what happens under the null distribution) but can also be easier to implement properly.
This code was written on my phone without testing it, so it probably doesn't work, but should get you started!
# assuming vectors A and B exist already, as well as a function
# improvement(A,B) that returns a number indicating
# the size of the improvement.

distr <- rep(NA, 5000)
for (i in 1:length(distr)) {
    distr[i] <- improvement(
        sample(A, length(A), replace=T),
        sample(B, length(B), replace=T)
    )
}

quantile(distr, probs=0.05)

This will give you the smallest value of the largest 95 % in the distribution. If that is greater than zero, you have a significant effect at the 0.05 level!


Duplicate Results in View with OG Relationship

Question: I have a view that uses the OG Relationship "OG membership: Group Content (node) from OG membership", and this relationship is causing duplicates when a person has more than one group assigned to them.
If I use aggregation settings along with checking the distinct checkbox in the query settings, the duplicates disappear. (Oddly enough, I needed to use BOTH aggregation and "Distinct".)
However, I want the ALL Content Titles for the related Group (which is why I needed the relationship).
I even tried the Views Distinct module, but after fumbling around with it, it either shows one Content Title from the group or all Content Titles from all groups.
All of this behavior leads me to believe there's an issue with OG relationships because there's no way to aggregate the content titles that I can find.
Am I looking at a views hook to fix the issue?
Answer: Okay, so I believe I traced the issue to a problem with Entity Reference Relationships in Views, and posted a bug.
However, I was able to solve the duplicate issue AND get the results I wanted (all titles from related groups) by taking a different approach in the View.
Instead of hook_query_alter() or hook_views_pre_render(), I just wound up adding the field that reference the groups, setting the Formatter to "Label", and checking the "Link label to referenced entity." This produced a comma-separated list of groups linked to the group page (exactly what I wanted).


Why does jQuery return null for element height?

Question: I faced the same problem as that is mentioned by Matt but it is little different. I am trying to get height of a div but every time I get null.
HTML:

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

JavaScript:
$(document).ready(function(){
   alert($("#ass-1415241823647 .item_message").height());
});

I tried this too but it didn't work.
$(document).ready(function(){
   alert($("#main .box_content #ass-1415241823647 .box .item_message").height());
});

Answer: ass-1415241823647 item-97   you can't have two id's remove one or try using class if u really want to
Comment: yes it will dear but if you really want to name for ids then use classes because id can only be one per element but classes can be many ! @BibashAdhikari
Comment: You can follow this : http://stackoverflow.com/questions/11884862/why-use-ids-classs-in-html-why-not-just-one
Answer: You don't seem to have any elements in your markup matching the selector #ass-1415241823647 .item_message" so it's unable to locate it.
Answer: Isn't the result of $("#ass-1415241823647 .item_message") empty jQueryObject? length 0?
.. id="ass-1415241823647 item-97">..

value of id attributes was wrong.
Answer: Try this using jquery:
$(document).ready(function(){
   alert($(".item_message").css("height"));
});

Hope this helps.


Reloading module's services.yml

Question: I am trying to reload the .services.yml file of a custom module without having to reinstall the module.
Is there a Drush command or another way to achieve this?
Does drush cr also clear the services.yml files information? It's really hard for me to tell.
Answer: Ok. After testing and more research "drush cr" does the job. Service.yml is reloaded after clearing the cache.

Reloading module's services.yml


What is the official way to deal with string in C++/FORTRAN interop

Question: I'd like to learn the latest improvement in C++/FORTRAN interoperability when it comes to string in particular. The following is my unsuccessful attempt, please help me correct or advise a better solution.
My compiler is gcc 4.8.5
In C++
#include <iostream>

extern "C"{
    void SayHello(char*);
}
int main(int argc, char** argv){
    char * name = argv[1];
    SayHello(name);
    return 0;
}

In Fortran
module MyModule

      contains
          subroutine SayHello(people) bind(c,name="SayHello")
              use, intrinsic :: iso_c_binding
              character, dimension(50), intent(in) :: people
              write(*,*) "Hello ", people
          end subroutine
end module MyModule

Comment: Why is your attempt unsuccessful?  You will certainly have a problem if `argv[1]` isn't at least length 50. That is, please show any errors or messages.
Comment: For a reason I don't know why (read: the reason why I am here), I got the following compilation error with codes above https://pastebin.com/Q4e48RkV
Comment: I'm not familiar with C++, but in the C version I posted in my answer, printing is left to the Fortran program. Do you need `std::cout`?
Comment: oops, I'll correct that
Answer: Try using the c_char type:
character(kind=c_char), dimension(*), intent(in)

EDIT 1
So, after @francescalus posed the question, I looked into this further. Basically, the "assumed size" character array is not necessary1, although I do believe that the size of the char array is (please correct me if I'm wrong about that). I'm going to post a C-calling-Fortran version below, since I don't know the C++ syntax and don't feel like looking it up.

EDIT 2
As mentioned in footnote 1, it is only correct to declare people in the Fortran program as an assumed size array of chars, or (as suggested by @VladimirF) with the size given directly by sz. I clear this up in the code below.
The Fortran program:
! SayHello.f90
subroutine SayHello(people,sz) bind(c,name="SayHello")
    use, intrinsic :: iso_c_binding
    implicit none
    ! Notes:
    ! The size `sz` of the character array is passed in by value.
    ! Declare `people` as an assumed-size array for correctness, or just use the size `sz` passed in from C.
    character(kind=c_char), intent(in), dimension(sz) :: people
    integer(kind=c_int), intent(in), value :: sz
    write(*,*) "Hello, ", people(1:sz)
end subroutine

And the C program:
/*Hello.c */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void SayHello(char *name, int len);

int main(int argc, char** argv){
    size_t sz = strlen(argv[1]);
    char * name = malloc(sz+1);
    strcpy(name, argv[1]);
    SayHello(name, sz+1);
    free(name);
    return 0;
}

Compilation (with ifort), call, and output:
ifort /c SayHello.f90
icl Hello.c /link SayHello.obj
Hello.exe MattP
// output: Hello, MattP

1Update: Seems like the official usage "for interoperability" is to declare as an array of characters, using assumed size: char(len=1,kind=c_char), dimension(*), intent(in)
Comment: You aren't passing the size of character array (or the length of the character scalar): `character(kind=c_char), intent(in) :: people` is a scalar length-1 character without a `dimension` statement.  `people(1:sz)` is an invalid substring reference for `sz` greater than 1 in this case (or invalid array reference for the scalar).
Comment: Just move the correct code from the comment to the real code. `character(kind=c_char), intent(in) :: people` is invalid, because you then do `people(1:sz)`. The `character(kind=c_char), intent(in), dimension(*) :: people` or even better `character(kind=c_char), intent(in), dimension(sz) :: people` is necessary.
Comment: gfortran -c mymodule.f90
mymodule.f90:7.34:

              write(*,*) "Hello ", people
                                  1
Error: The upper bound in the last dimension must appear in the reference to the assumed size array 'people' at (1)
mymodule.f90:7.41:

              write(*,*) "Hello ", people
                                         1
Error: Data transfer element at (1) cannot be a full reference to an assumed-size array
Comment: @fanhako, although this answer doesn't address it, you should be aware that `people` is an assumed size array of length-1 characters, not a scalar assumed length character.  With an assumed size array you cannot (as the compiler complains) reference it as a whole array.  You need to change much more than just the one declaration.
Comment: Can you explain why declaration of an explicit shape array should be changed to one of an assumed size array?
Comment: @francescalus Wellll...turns out, you *don't* need to do that. But as you mention, you do need the size of the character array. See my edit.
Comment: @francescalus Oh, the comment above is the compiler output when I tried Matt's suggested modification. I am really confused about the difference of array of char in these two languages. And I am just limiting myself to C char*, how about C++ standard string ? I am here to learn, so would you tell me more about "change much more than just the one declaration" ?
Comment: @fanhako Did you try the solution in the edited answer? You need to change a few things about the Fortran code (also, read the notes in the code).
Comment: @MattP: Thanks, your explanation was clear! I edited the code in C++, now it's working. Next step for me is to return a value
Comment: @francescalus I think that you are correct: `character(len=1,kind=c_char), dimension(*), intent(in) :: people` is prob the most technically correct. However, `sz` is most certainly the size (number of items) of the char array.
Comment: The program is invalid.
Comment: Ah, there you are @VladimirF! Could you be more specific?
Comment: Compile with `-fcheck=all` to see.
Comment: @VladimirF Agreed! Done. Should have made that change earlier.


Why are so many Eurovision song contest songs sung in English?

Question: One thing that strikes a lot of non-European viewers of the Eurovision Song Contest is that many of the songs are sung in English.
Outside of the ESC, are most modern songs produced in Europe typically produced in the native language of the singers, or in English? I assumed the former, but the mockumentary Get Ready to be Boyzvoiced was in Norwegian, except for the singing, which is in English. If it's common for modern songs to be in English, then maybe there's nothing aberrant about the ESC at all.
If the ESC has an unusually high proportion of English-language songs, is it because the lyrics are more likely to be understood by a large number of voters, or is English seen as a "cool" language, or is it something else?
I checked List of languages in the Eurovision Song Contest, but it only listed when people used English, not why.
Comment: It might be a good idea to study if songs in English are more likely to win than others.
Comment: @MischaArefiev Man, Terry Wogan looked so young back then
Comment: I have another possible explanation: since computers are programmed in English (see any programming language, all keywords are English) and most of the music for Eurovision is composed on a computer, the lyrics are naturally also in English, because this way they are easier to program
Comment: For the same reason why most contestants sung in Latin during Eurovisionum of 1580
Comment: @MischaArefiev http://www.youtube.com/watch?v=3FsVeMz1F5c
Comment: Over a lot of the history of the contest entries were required to be sung in one of the official languages of the country participating. These rules were finally removed in 1999.
Answer: Besides what is said above (English is understood by most people and thus sounds more familiar), there is also another aspect.
In Europe there are very many languages, each with their own characters and thus pronounciations. Some languages are considered less 'attractive' by hearing than others, although this differs between each two languages.
English is considered a neutral language by most other language (speakers), while others sound harsh or at least 'strange'.
Answer: Having read earlier answers (all have a point!), I'm thinking .. surely pop history has a part to play here ?
American (sung in English) Rock 'n Roll burst onto the scene and made a global impact in the 50's - the massive influnce of those early rockers : the likes of the Bill Haley / Buddy Holly (bless his chops) and latterly The Beatles / Rolling Stones etc etc would have an influence that has affected pop ever since.
I was talking to a French girl in the mid 80's asking what French pop music was like. Answer : English ! Some was in French of course but at that time (at least) she said, "We have our own pop, of course, but for many Britain is the first country for music".
Being English and a musician, I was elated to hear this. It didn't help though - she had a boyfriend.
Anyways my point is I think there's a historical reason regarding how pop has emerged, as well as the others cited here.
Comment: Well, it ain't bragging if it's true. Of course there has been and there is important musical scenes in other countries, namely France (let's not forget Daft Punk or that My Way as actually written by the Claude François :-), Italy (remember Giorgio Moroder), Germany  (the Kraut Rock scene)  etc. But Anglo-Saxon culture dominates the international European pop scene, that's undeniable. Even Asian pop (Japan, Korea), despite local acculturation is musically highly influenced by Anglo-Saxon pop (Indian popular music not so much so, I think).
Comment: I should point out I'm squirming when I wrote this post - although I think it's true, it does feel massively arrogant to say "because great music was invented in English". ugh.
Answer: I believe the presentation of the songs in English has to do with the attempt at catching the opportunity to sell in an international market, as much as a strategy directly aimed at winning the contest.
If the song is catchy and is presented with a good marketing package (good looking artists, etc.), Eurovision provides a unique opportunity for international exposure and to reach otherwise inaccessible markets. If it wins the contest, it won't hurt of course (as Abba have shown many years ago).
But it's a fact that songs in English have won the contest approximately half the time, as much as all other languages combined. Official English countries UK and Ireland have won 5 and 7 times respectively. Ireland has the record for winning most times, followed by Sweden, 6 times, but 4 of them with songs in English.
France and Luxembourg have also won 5 times each, with songs in French.
So yes, statistically, language seems to be a major factor in winning probability, which of course adds to the marketing strategy motivation.
However, each individual yearly result of the Eurovision song context is the result of the social and political inter-relations between countries, at least as much, if not more, as of the intrinsic quality of the songs and artists. Countries use their voting power to support or penalize other countries, so just singing in English is by no means a guaranty of a good result.
Source for statistics: Eurovision Song Contest Statistics
Comment: To me, this is the best answer. A hypothesis with real support and evidence to boot.
Answer: I doubt anyone can give a definitive answer to that question lest they do a impressive amount of study.
So here are my completely ungrounded two cents. I think this is due to a variety of factors. I doubt the fact that english lyrics are understood by more people is at stake here (because I doubt that the proportion of people whose English is good enough to understand a song lyrics on the fly is very high). However, I think most people are used to songs in English. Songs in Swedish? Out of Sweden and, perhaps, the rest of Scandinavia, they're mostly unheard of. And I don't know if I ever heard a single bit of Latvian. Songs in various European language would thus sound foreign to most European ears… and that's bad if you're trying to grab as many 12 points as you can.
Answer: I'm pretty sure it's just because English is a common language that most European countries speak.  It gives voters something to understand and judge.
It means you can relate to what the singers are on about, which compels you to vote for that country.  If it were in 90% languages that other countries don't speak, then all you'd have to go on would be the musical content, then no-one would win :O
As far as why most European countries speak English, well it's probably because of the British Empire colonizing everywhere, but you might want to get a historian on that one.
Comment: [There's a bit about English becoming a vehicular language in Europe on Wikipedia](http://en.wikipedia.org/wiki/List_of_lingua_francas#Europe). I would suggest an answer on the [History SE](http://history.stackexchange.com), but [the question was closed](http://history.stackexchange.com/questions/9890/when-and-how-did-english-become-the-lingua-franca) with the reason being more or less "look at Wikipedia".
Answer: The reason must be the same as the experience I have made in my own career as singer and also as teacher hundreds of singing pupils:
Singing in English is cool! (and also speaking of course, s. all the anglicisms in German, French, Italian ... in all European languages) from a certain age  cooler than the mother language. (Except Yodelling, traditionalists and patriots will prefer the mother language.
My psychological interpretation is: the expression of feelings in another language is less intimating than the mother language. e.g.  a prayer in English is more transzendent and less ordinary as in Swiss German (I can see there parallels to the the sermon in Latin).
Another assumption of mine is: In another language people will less realize the simplicity and triviality of the lyrics.
Why English and not French:
The winner of the 2nd World War have been the USA and Rock'Roll maybe the winner of the 3rd war. I'm learning Chinese to win the next ESC.
Answer: Because Occitan as the international language of troubadours has grown out of fashion?  For better or worse, English is the international language of pop.  That's what many national pop singers use for reaching the larger international market.  It's not like people pay a lot of attention to lyrics, anyway.  A few countries have their own traditional and untraditional styles, like Fado, Deutschrock, Chanson, various Latin styles and similar, but even singers like Shakira with a "native" market as large as the Spanish speaking one produce lots of English titles.


Is it possible for a normal distribution to have mean 0 and standard deviation less than 1?

Question: Is it possible to have a dataset having a normal distribution with mean close to 0 and standard deviation less than 1?
for eg, my dataset have mean 0.0004 and Standard deviation of 0.0089.
The reason for asking this, is that normally the standardized normal dist have mean 0 and standard dev of 1.
Comment: Just change the units of measurement.  For instance, if these data are in kilometers, convert them to millimeters: the mean becomes $400$ and the standard deviation becomes $8900$.  Although the mean is no longer "close to $0$" and the SD is definitely greater than $1$, your data haven't changed: we have only changed how they are described. Therefore there couldn't possibly be anything invalid about the original situation.
Comment: FYI to help you visualize standardization... changing the mean "shifts" the graft to the origin (addition or subtraction, applied first), changing the s.d. by scaling it squeezes or broadens it (multiplication or division, applied 2nd).
Answer: Yes, it is perfectly possible. It is true that if you standardise it you get a mean of 0 and an sd of 1 but you have not standardised it so that does not apply to you. You can have any mean and any non-negative standard deviation.
Answer: Simple example: mean 0 and std. dev. 0 corresponds to a variable whose value is 0 with probability 1.
(This is referred to as the degenerate case.)
So, yes, this is perfectly possible and sensible.
Comment: Is it a **normal** distribution then?
Comment: I don't know if this can still be considered as normal, but it is a matter of definition. Probably you are right, I just wondered.
Comment: A compromise might be to stress that this is a limiting or degenerate case. I wouldn't say that it was an _easy_ example compared with those already given.
Comment: @RichardHardy: Of course. Why wouldn't it be?
Comment: @RichardHardy: Zero is definitely nonnegative, so there's no problem there. I can see why it might trip someone up who's just learning about it, but I'm not actually aware of an accepted definition that doesn't allow it.
Comment: OK, it was just a question I had.
Comment: @RichardHardy: Yeah, I realize. I think in any case we can safely say it's not *ab*normal. ;)
Comment: @NickCox: Done.


I18n Springboot de uma biblioteca externa

Question: Senhores, em meu sistema tenho um componente externo que contem o bean messagesource configurado da seguinte maneira :
@Bean
public ReloadableResourceBundleMessageSource messageSource() {
    final ReloadableResourceBundleMessageSource source = new ReloadableResourceBundleMessageSource();
    source.setBasename("classpath:i18n/core/messages");
    source.setDefaultEncoding("UTF-8");
    source.setUseCodeAsDefaultMessage(true);
    return source;
}

No entanto  necessito que as mensagens de exceções sejam exibidas na aplicação que esta importando ele, algo que não está ocorrendo :
br.com.mv.liberty.editor3core.exception.vo.StudioException: group.length.max.description

Como devo configurar minha aplicação para exibir as mensagens desse componente embarcado ?
Answer: Como o baseName está source.setBasename("classpath:i18n/core/messages");, você precisa colocar o arquivo de messages.properties dentro do seguinte diretório:
 src/main/resources/i18n/core/message.properties


Generate sets of values with high correlation coefficient

Question: Apology if this is too simple. I couldn't get the more advanced r-help group to respond.
I am planning to characterize workloads by measuring the correlation coefficient of two sets of real values but before that I wish to generate two sets of sample values that have a high coefficient and a low coefficient. I want to plot both in the same graph so that I can see the highly correlated values' together(peaks and troughs). I use R and know about rseek.
If there is any particular R book that could help my capcaity planning efforts I will buy it.
Generate a random variable with a defined correlation to an existing variable is a tad too advanced for me at this time.
Note : The two sets of values that I am about to plot are related because I am plotting CPU usage and a througput number. So if the no: of bytes increases the CPU usage may increase. Both are postitive values. So if the correlation is high both will either increase together or decrease together.
Thanks.
Comment: What about the distribution of the values? Are they supposed to be Gaussian?
Comment: **Quick and dirty**: take two equal-length vectors of values `x` and `y` (such as the "real values" in the question, or simulations thereof). Look at `plot(sort(x),sort(y))`, `plot(x,sample(y))`, and `plot(sort(x),-sort(-y))` to see the extreme behaviors (high correlation, almost no correlation, high *negative* correlation).
Answer: You can for example generate data from a bivariate normal distribution. The off-diagonal entry of the variance-covariance matrix is the covariance. In R, this can readily be done with rmvnorm.
Example
Generate $1000$ realisations from $X=(X_{1}, X_{2})' \sim N(\mu, \Sigma)$ with
$$\mu = (-1, 5)', \quad \Sigma_{11} = V(X_{1}) = 0.7, \quad \Sigma_{22}= V(X_{2}) = 0.1$$
and $\Sigma_{12} = \Sigma_{21} = \textrm{Cov}(X_1, X_2)$ such that $\textrm{Cor}(X_{1}, X_{2})=0.85$.
<code>> #------load the package------
> library(mvtnorm)
> #----------------------------
>
> #------compute the covariance such that cor(X1, X2) = 0.85------
> covariance <- 0.85 * sqrt(0.7) * sqrt(0.1)
> #---------------------------------------------------------------
>
> #------variance-covariance matrix------
> sigma <- matrix(c(0.7, covariance, covariance, 0.1), nrow=2, byrow=TRUE)
> sigma
          [,1]      [,2]
[1,] 0.7000000 0.2248889
[2,] 0.2248889 0.1000000
> #--------------------------------------
>
> #------data generation------
> test <- rmvnorm(n=1000, mean=c(-1, 5), sigma=sigma)
> #---------------------------
>
> #------compute the empirical correlation on this particular data------
> cor(test[, 1], test[, 2])
[1] 0.8478849
> #---------------------------------------------------------------------
</code>
$$$$
NB: You can also generate data according to a linear regression model: $X_2 = a + bX_1 + \epsilon$.
Comment: Reminding that I am a learner. The mention of linear regression here seems to mean that the two sets of values that I am about to plot are related which is true because I am plotting CPU usage and a througput number. So if the no: of bytes increases the CPU usage may increase. Both are postitive values. Apology for alluding to capacity planning and not mentioning this properly . Both R code samples( ocram and user603 ) have negatives and the values are not continuously increasing or decreasing.
Comment: You should have added this requirement in the question. The method based on a linear model or other methods proposed in this page can make the job.
Answer: Others have given you code. Here is an idea behind that.
Generate $X$, and then let $Y = X+Z$, where $Z$ is independent of $X$.
If $var(Z)$ is small compared with $var(X)$ then the correlation between $X$ and $Y$ will be high. If $var(Z)$ is large compared with $var(X)$ then the correlation between $X$ and $Y$ will be low.
Comment: (+1) Since it is easy to characterize exactly what the (theoretical) correlation will be, adding that small bit might improve this answer even further.
Answer: <code>library("MASS")
highCor<-matrix(c(1,0.9,0.9,1),2,2)
lowCor<-matrix(c(1,0.1,0.1,1),2,2)
x_hc<-mvrnorm(100,rep(0,2),highCor)
x_lc<-mvrnorm(100,rep(0,2),lowCor)
plot(rbind(x_hc,x_lc),type="n")
points(x_lc,pch=16,col="green")#low correlation in green
points(x_hc,pch=16,col="blue") #high correlation in blue
</code>
Answer: The answers given here as well as the checked answer to the previous post give you a lot of valid ways to do this.  My suggestion would have been the same as the NB given above by ocram.  Take a linear function $Y=a+bX$ and add an error term  $N(0, σ)$ with a small value for the standard deviation $σ$.   This will generate a pair of random variables with a high correlation.  To generate a pair of variables with low correlation just take a large value for $σ^2$.


the Ref. hook is not showing the component details. while consoling the ref.current, it showing the undefine

Question: (code)
I have assigned the ref hook over the rightcompX div, when I render this component it will consol out undefined.
import React, { useRef, useState } from 'react';
import {gsap} from 'gsap';
import RingGraph from '../../../components/RingGraph/RingGraph';
import './CR.css';

const InterviewReport = (props) => {

    const Cbox = useRef()

    useState(()=>{
        // gsap.from(CRbox.current,{opacity:0,duration:0.8,x:-40})
        **console.log(Cbox)**
    },[])
    return (
        <>

                    close

                    candidate Report

                .....
    )
}

export default InterviewReport;

Comment: Seems you've used the wrong hook, `useState` instead of `useEffect`. Voting to close as "Not reproducible or was caused by a typo". Cheers.
Answer: You probably meant to use useEffect() hook, not useState()


Proving that a function is not an inner product

Question:
I have this function here that I need to prove is not an inner product.
I've been able to use the first three axioms (symmetry, additivity and homogeneity), which the function has satisfied, but I'm not sure how to go about using the positivity axiom to prove that it is not an inner product space.
How would I go about doing this?
Comment: @TeresaLisbon I'm not sure I follow.
Comment: The inner product of a vector with itself has to be non-negative. But if there's a $-$ sign in the inner product, (and you know it is not an inner product) then the best way to find a counterexample is to increase the term which has the $-$ sign (which is $z_1z_2$) and minimize the positive terms. Once you see this, the vector $(0,0,-1,0)$ is a problem : its inner product with itself has to be negative.
Comment: The $-$ sign is a problem for positivity. Exploit it.
Answer: Let $v=(0,0,1,0)$ and compute $\langle v,v\rangle.$


$3\times 3$ nonnegative matrices with purely imaginary eigenvalues

Question: This question arised from the more generic "does there exist entrywise nonnegative matrices with some non-zero purely immaginary eigenvalues?"
The answer is no for $2\times 2$ matrices (one can actually write all such kind of matrices and check it, or simply from Perron-Frobenius theorem).
Though, the answer is yes for $4\times 4$ matrices, since the companion matrix of $(x^2+1)(x^2-x-1) = x^4-x^3-x-1$ is nonnegative.
Now I am asking if there's a smaller example with $3\times 3$ matrices. What I know is that

the real eigenvalue must be nonnegative from the trace
the determinant must be nonnegative from the previous property
the real eigenvalue is bigger or equal in magnitude than the rest from Perron-Frobenius
no companion matrix with such properties is nonnegative
Answer: Yes. Let $H$ be a Housholder reflection matrix whose first row/column is positive, such as
$$
H=\pmatrix{\frac{1}{\sqrt{3}}&\frac{1}{\sqrt{3}}&\frac{1}{\sqrt{3}}\\
\frac{1}{\sqrt{3}}&\frac{2-\sqrt{3}}{3-\sqrt{3}}&\frac{-1}{3-\sqrt{3}}\\
\frac{1}{\sqrt{3}}&\frac{-1}{3-\sqrt{3}}&\frac{2-\sqrt{3}}{3-\sqrt{3}}}.
$$
Since $H=H^{-1}$, when $t\ne0$ is real, the matrix
$$
A=H\pmatrix{1&0&0\\ 0&0&-t\\ 0&t&0}H
$$
has a conjugate pair of purely imaginary eigenvalues $\pm it$. Since $A$ is entrywise positive when $t=0$, it is also entrywise positive when $t\ne0$ is sufficiently small.


increment numeric porition of a column name inside a SQL statement

Question: I have a table that contains columns q1,q2,q3,q4,q5,.. as you can see the columns names consists of letter q and numbers i,i+1,i+2,i+3,... inside a foreach loop, I want to loop through an array and add each array element to a single column. e.g. arr = [A,B,C,D] A goes to q1, B goes to q2,..
Here is my attempt:
<code>$selected_ans = $_POST['options'];
$answersArr = implode(' ', $selected_ans);
foreach ($answersArr as $ans) {
    // column name consisting of letter q and a numeric value
    $int = "q"+1;
    $sql = "INSERT INTO MyGuests ($int)VALUES ($ans) WHERE username = $VALID_USER";
    $conn->query($sql);
    // increment the numeric value
    $int++;
}
</code>
This does not work so how can this be correctly implemented? thanks
Comment: $int = "q"+1; must be $int = "q"+$int; and initially $int value is 1
Comment: implode is going to join array elements so there is no use using foreach I think you need to use explode
Comment: @vSugumar thanks for the comment so how can I correctly add the elements into an array?
Comment: @jimiss please see the answers below
Comment: If you find yourself with a table with columns q1, q2, a3, etc, then you can be sure that something has gone very, very wrong.
Comment: INSERT query doesn't support the WHERE clause: https://stackoverflow.com/questions/485039/mysql-insert-where-query You either need to construct a full INSERT query and run it once or run an empty INSERT and run UPDATE queries inside the loop.
Comment: @Strawberry I agree its a bad design. how should I handle a table that is suppose to hold a users answer to a list of questions?
Comment: @jimiss try my edited code to use single query to insert
Comment: The topic of database normalisation is surely exhausted. It ill behoves us to rehearse those strategies here.
Comment: yes @Strawberry you are right.
Answer: I think this is more like what you're looking for. It's a bit sloppy, but it'll get the job done and is a good starting point for you to refactor and improve upon.
<code>$selected_ans = $_POST['options'];
// Make sure to sanitize the raw input
foreach ($selected_ans as $k => $v) {
    $selected_ans[$k] = '"' . mysqli_real_escape_string($v) . '"';
}
// Dynamically create a list of column names
$columns = [];
for ($i = 1; $i <= count($selected_ans); $i++) {
    array_push($columns, 'q' . $i);
}
$sql = "INSERT INTO MyGuests (username, " . implode(", ", $columns) . ") VALUES (\"" . mysqli_real_escape_string($VALID_USER) . "\", " . implode(", ", $selected_ans) . ")";
$conn->query($sql);
</code>


A special ideal in a local ring

Question: Let $R $ be a local commutative ring with identity (may or may not be Noetherian), and let $0\ne a\in R $ be such that for every ideal $I $ of $R $  either $a\in I $ or there exists $r\in R $ such that $0\ne rI\subseteq \langle a\rangle $. How can we deduce that $\langle a\rangle $ is comparable with every ideal, that is, for every ideal $J $ we have either $\langle a\rangle \subseteq J$
or $J\subseteq\langle a\rangle $ ?
Comment: What have you tried.. are you able to prove some partial result or some weak version?
Answer: You can't deduce it : take $R$ to be any local domain and $a$ such that $\langle a \rangle$ is not comparable to every ideal. Then it satisfies the condition because for any nonzero ideal $I$, $0\neq aI\subset \langle a \rangle$.
For instance, take $\mathbb Z [X]$ localized at $(2,X)$. In that ring take $a=2$ and $J=(X)$. Then $a\notin J$ (if it were, there would be $2 P = QX$ with $P\notin (2,X)$, looking at the minimal degree coefficient yields a contradiction) and $J$ is not included in $\langle a \rangle$ (similar proof)
Comment: @roland : that was my point, and that's how my new (correct ?) example works
Comment: @Roland : you are right, I made a mistake : in fact $J$ is a legit ideal of the initial ring, but when you localize it becomes the ideal of the functions that vanish at $0$ so my example doesn't work : $a$ belongs to the localization
Comment: @Roland : I chabged my example, hopefully this one is correct
Comment: I've removed my comment. I just don't know if there is not a problem in the OP. After all, there is absolutely no condition on $a$ if $R$ is a domain...
Comment: Is there any additional condition on $R $ or $a $ under which the result is true?

A special ideal in a local ring


How can i retrieve a fields name

Question: I have a simple javascript function to check if a field is not empty:
function notEmpty( field , alert_text ){
if (field.val() === "" ||
    field.val() === null ||
    field.length === 0) {
    if ( alert_text ){
        alert ( 'Error: please enter some text - ' + alert_text );
    } // end if
    field.addClass( 'hightlight' );
    field.focus();
    return false;
} // end if
else {
    field.removeClass('hightlight');
    return true;
} // end else

I want to get the name of field to show in the alert without using the alert_text argument. I tried a whole load of things, with no luck, so I've left the function as is and I'm using the alert_text argument to pass the field name. All my form input tags are something like this:
  <input    type=       "text"
    name=       "artist"
    id=     'artistfield'
    size=       "60"
    tabindex=   "1" />

So they all have 'name' defined. There must be a way to get it into my alert box but I can't figure it out yet. I'm sure it's easy, I'm just very new to this. Thanks.
Answer: You can retrieve the name with this:
field_name = field.attr('name');

Answer: You can use jQuery's attr() method to get the name (and almost any other HTML attribute):
function notEmpty(field) {
    if (field.val() === "" || field.val() === null || field.length === 0) {
        if (field.attr('name')) {
            alert('Error: please enter some text - ' + field.attr('name'));
        }
        field.addClass('hightlight');
        field.focus();
        return false;
    } else {
        field.removeClass('hightlight');
        return true;
    }
}

Answer: You can use:
field.attr('name')
To get the name attribute from the field. You could change name for id if you wanted the fields ID for example.
Answer: To get the name-attribute of an element you can use the attr-function. It can get the value of any attribute.
Eg: http://jsfiddle.net/mqchen/LjFdC/
Comment: Thanks everyone for the prompt replies - all good now, cheers

How can i retrieve a fields name


Is there a way, or tag to use, to centre any HTML element?

Question: Is there any code or tag which can be used to centralise any HTML element? The only way I know to do this currently is to repeatedly adjust padding and margins (left) to push elements to an approximate centred position. I'm aware you can centralise text, but this doesn't appear to work for other elements such as divs, objects, etc.
Answer: In CSS, the code is {text-align:center;}.
You can do this in HTML two ways, though it is not good practice. One is
, and the other is thing to center
Answer: For divs try:
body {
    text-align: center;
    min-width: 600px;
}

#wrapper {
    margin:0 auto;
    width:600px;
    text-align: left;
}

Basically - setting margins to auto on your wrapper div almost always works, and text-align center for the div you'd like to be centered within it.
In html

works well.
Answer: Try margin: 0 auto;
Example:
http://jsfiddle.net/4KuRW/
Answer: The best way from my experience to center an element is by setting up the CSS this way:
width: 300px; /* You actually have to set the width! */
margin: 0px auto; /* margin-top & bottom = 0, margin-left & right = auto */

To center the text you simpy use text-align: center;.
Answer: To make the content center of the page try to use
body{ margin:0 auto;}

to align text center use
p{text-align:center} or div p{text-align:center;}

By using HTML tag for text
your text goes here

you can create a class on which you can write your css like

Your text goes here

.align-center { text-align:center; } or .align-center { margin:0 auto; }

so many ways are present to make the element center, its totally depends on you what layout you are creating and what kind of element you want to make center. Generally by using css we can make our elements center or as per our requirement. If you have any peculiar situation then ask.
Comment: This is the page i am working on. I'd like the facebook comments part to be centralised.

http://newmedia.leeds.ac.uk/ug10/cs10mm/youtube.html
Answer: I assume you mean: you have a div with id=X, height=H, width=W that you want to center horizontally and vertically relative to a parent container C (i.e. C must have be defined with position: relative)
In your CSS file, you should define the class for X like this:
#X{
 position: absolute;
 top: 50%;
 left: 50%;
 margin-left: -(W/2)px;
 margin-top: -(H/2)px;
}

Comment: Never use position:absolute for unnecessarily.


Problemas com PHP expressões regulares?

Question: Tô pegando um arquivo .txt e tirando as letras e linhas em branco. Tá dando problema com o carácter especial \t ou \s ele não reconhece.
O código abaixo:
<?php

function pass1() {
    $treat = fopen ("C:\\Users\\Bridge\\Downloads\\D_lotfac\\lott.txt", "r+w+");
    $treat1 = fopen ("C:\\Users\\Bridge\\Downloads\\D_lotfac\\lott1.txt", "r+w+");

    while (!feof ($treat)) {
        $linha = fgets($treat,4096);
        $patterns = array();
        $patterns [0] = '/[(A-Z)i]*/';
        $patterns [1] = '/Â|Ã|Á|À|É|Ê|Í|Î|Ç|Ó|Õ|Ô|Ö|Ú|Û|Ü/';
        $patterns [2] ='/ã|â|à|á|é|ê|í|î|ç|ó|ô|ô|ö|ú|û|ü/';
        $patterns [3] = '/\t/';
        $patterns [4] = '/[(a-z)i]*/';
        $patterns [5] = '   ';

        $replacements = array();
        $replacements[] = '';
        $linha = preg_replace($patterns, $replacements, $linha);
        fwrite ($treat1, $linha);

        printf($linha . "
");
        }
}

Tá gerando o arquivo lott1.txt corretamente, só que os tabs não estão sendo retirados nem os espaços (2x, 3x, etc ). Já coloquei o tab literalmente "   " ou coloquei \t dentro do array $pattern[]. Não elimina.
Qual o problema?
Comment: use uma única `pattern`, a `\w`, ela aceita todos os caracteres exceto os especiais
Comment: ja tentou mudar o tab para `/\t+/`
Comment: @lucasvscn Recomendo que leia [O que significa o atalho \s nas REGEX?](http://pt.stackoverflow.com/q/110701/14213)
Comment: @user6855041 coloque um antes e depois do arquivo, isso pode ajudar mais a entender a sua duvida?
Comment: para espaços, use `/\s+/` (1 ou mais ocorrências) , `/\s{5}/` (5 ocorrências)
Comment: @GuilhermeLautert obrigado pela indicação.
Answer: Primeiramente

\s Não é "espaço"!!

Você pode ver o que significa o \s aqui.
Problema

Pelo que eu notei você também deseja capturar caracteres acentuados. Para isso uso o modificados u, abordado aqui.
Para capturar tanto maiúsculas quanto minusculas pode usar [a-zA-Z], [[:alpha:]] ou [a-z] com modificador i.
Se seu intuito é remover todos tabs e espaços pode fazer assim [\t ]+.

Solução
Em resumo seu pattern seria :
~[a-z\t ]+~iu
Nota

[(A-Z)i] - se seu intuito era montar um grupo com A-Z isso não ocorre dentro do [...], sendo os parenteses interpretados literalmente.

Problemas com PHP expressões regulares?


In a graphical model of C dependant on both A and B, is it possible to get the joint distribution of C and B?

Question: Imagine we have a graphical model of random variable C that is dependent both on A and B. This is like a node C which has two incoming arrows. One from node A and the other from B.
An example is me getting Sinus dependent on either me being allergic or me having flu. So sinus is the node C. Allergic is the node A and flu being the node B.
I know that the joint probability of all these three random variables is P(A,B,C) which is P(C|A,B)*P(A)*P(B).
How do we get the joint distribution of C and B for example? How do we derive the P(C,B)?
In other words does it make sense at all for me to expect the joint distribution to exist? If no why not?
Thanks
Answer: It exists as long as the joint for all variables exist, and you can calculate it as follows:
$$P(B,C)=\sum_{a\in\mathcal{A}}P(A,B,C)=P(B) \sum_{a\in\mathcal{A}} P(C|A,B)P(A)$$
Comment: yes, it exists. it was a general statement not limited to bayesian networks.
Comment: thanks for this. Also you said as long as joint for all variables exist. Given the scenario can the joint of all variables not exist too? Is there a situation you can think of where the join doesn't exist? I thought in the given graphical model it always exists
Comment: thanks it is clear now