Erro na parte do codigo: navegador = webdriver.Chrome(service=servico, options=options)

Question: from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from time import sleep

options = Options()
options.headless = False #executar de forma visivel ou oculta

servico = Service(ChromeDriverManager().install())
navegador = webdriver.Chrome(service=servico, options=options)

link = "https://www.google.com/"
navegador.get(url=link)
sleep(5)

E ta dando esse erro
---------------------------------------------------------------------------
WebDriverException                        Traceback (most recent call last)
c:\Users\eleninha.santos\Desktop\ROBO1\1.ipynb Cell 1' in <cell line: 12>()
      9 options.headless = False #executar de forma visivel ou oculta
     11 servico = Service(ChromeDriverManager().install())
---> 12 navegador = webdriver.Chrome(service=servico, options=options)
     14 link = "https://www.google.com/"
     15 navegador.get(url=link)

File c:\Users\eleninha.santos\Desktop\ROBO1\vrobo\lib\site-packages\selenium\webdriver\chrome\webdriver.py:70, in WebDriver.__init__(self, executable_path, port, options, service_args, desired_capabilities, service_log_path, chrome_options, service, keep_alive)
     67 if not service:
     68     service = Service(executable_path, port, service_args, service_log_path)
---> 70 super(WebDriver, self).__init__(DesiredCapabilities.CHROME['browserName'], "goog",
     71                                 port, options,
     72                                 service_args, desired_capabilities,
     73                                 service_log_path, service, keep_alive)

File c:\Users\eleninha.santos\Desktop\ROBO1\vrobo\lib\site-packages\selenium\webdriver\chromium\webdriver.py:92, in ChromiumDriver.__init__(self, browser_name, vendor_prefix, port, options, service_args, desired_capabilities, service_log_path, service, keep_alive)
     89 self.service.start()
     91 try:
---> 92     RemoteWebDriver.__init__(
     93         self,
     94         command_executor=ChromiumRemoteConnection(
     95             remote_server_addr=self.service.service_url,
     96             browser_name=browser_name, vendor_prefix=vendor_prefix,
     97             keep_alive=keep_alive, ignore_proxy=_ignore_proxy),
     98         options=options)
     99 except Exception:
    100     self.quit()

File c:\Users\eleninha.santos\Desktop\ROBO1\vrobo\lib\site-packages\selenium\webdriver\remote\webdriver.py:275, in WebDriver.__init__(self, command_executor, desired_capabilities, browser_profile, proxy, keep_alive, file_detector, options)
    273 self._authenticator_id = None
    274 self.start_client()
--> 275 self.start_session(capabilities, browser_profile)

File c:\Users\eleninha.santos\Desktop\ROBO1\vrobo\lib\site-packages\selenium\webdriver\remote\webdriver.py:365, in WebDriver.start_session(self, capabilities, browser_profile)
    363 w3c_caps = _make_w3c_caps(capabilities)
    364 parameters = {"capabilities": w3c_caps}
--> 365 response = self.execute(Command.NEW_SESSION, parameters)
    366 if 'sessionId' not in response:
    367     response = response['value']

File c:\Users\eleninha.santos\Desktop\ROBO1\vrobo\lib\site-packages\selenium\webdriver\remote\webdriver.py:430, in WebDriver.execute(self, driver_command, params)
    428 response = self.command_executor.execute(driver_command, params)
    429 if response:
--> 430     self.error_handler.check_response(response)
    431     response['value'] = self._unwrap_value(
    432         response.get('value', None))
    433     return response

File c:\Users\eleninha.santos\Desktop\ROBO1\vrobo\lib\site-packages\selenium\webdriver\remote\errorhandler.py:211, in ErrorHandler.check_response(self, response)
    209     value = response['value']
    210 if isinstance(value, str):
--> 211     raise exception_class(value)
    212 if message == "" and 'message' in value:
    213     message = value['message']

WebDriverException: Message:
<meta type="copyright" content="Copyright (C) 1996-2019 The Squid Software Foundation and contributors">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>ERRO: A URL requisitada não pode ser recuperada</title>

ERRO

A URL requisitada não pôde ser recuperada

O seguinte erro foi encontrado ao tentar recuperar a URL: http://localhost:53893/session

Conexão para ::1 falhou.

O sistema retornou: (60) Operation timed out

O host ou rede remota pode estar fora do ar. Por favor, faça a requisição novamente.

Seu administrador do cache é <a href="mailto:email@example.com?subject=CacheErrorInfo%20-%20ERR_CONNECT_FAIL&body=CacheHost%3A%20localhost%0D%0AErrPage%3A%20ERR_CONNECT_FAIL%0D%0AErr%3A%20(60)%20Operation%20timed%20out%0D%0ATimeStamp%3A%20Wed,%2022%20Jun%202022%2019%3A07%3A17%20GMT%0D%0A%0D%0AClientIP%3A%20172.16.0.109%0D%0AServerIP%3A%20localhost%0D%0A%0D%0AHTTP%20Request%3A%0D%0APOST%20%2Fsession%20HTTP%2F1.1%0AAccept-Encoding%3A%20identity%0D%0AContent-Length%3A%20164%0D%0AAccept%3A%20application%2Fjson%0D%0AContent-Type%3A%20application%2Fjson%3Bcharset%3DUTF-8%0D%0AUser-Agent%3A%20selenium%2F4.2.0%20(python%20windows)%0D%0AConnection%3A%20keep-alive%0D%0AHost%3A%20localhost%3A53893%0D%0A%0D%0A%0D%0A">email@example.com.

Gerado Wed, 22 Jun 2022 19:07:17 GMT por localhost (squid)

Alguem pode ajudar a resolver
Answer: from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

class Navegador():

    def __init__(self):
        self.chrome_service = Service(ChromeDriverManager().install())
        self.driver = webdriver.Chrome(service=self.chrome_service, options=options)

    def abrir(self):
        try:
            self.driver.get("https://www.google.com/")
            return self.driver
        except Exception as e:
            raise("Erro ao abrir o navegador: " + str(e))

    def fazer_logout(self):
        self.driver.quit()

options=Options()
#options.add_argument("--window-size=1366,780")
#options.add_argument('--headless')
options.add_argument('-ignore-certificate-errors')
options.add_argument('-ignore-ssl-errors')
options.add_argument("--disable-notifications")
options.add_argument('--ignore-certificate-errors')
options.add_argument('--allow-running-insecure-content')
options.add_argument("--disable-extensions")
options.add_argument("--proxy-server='direct://'")
options.add_argument("--proxy-bypass-list=*")
options.add_argument("--start-maximized")
options.add_argument('--disable-infobars')
options.add_argument('--disable-gpu')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--no-sandbox')
options.add_argument('--force-renderer-accessibility')
options.add_argument('--ignore-ssl-errors')
options.add_argument('--enable-automation')

Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Como ter novamente acesso ao Label no Visual Studio

Question: Coloquei um Label no form, editei seu nome para ficar vazio, renomeei e até ai tudo bem, sendo que não consigo mais seleciona-lo no form para manipulação.
Ele funciona dentro da aplicação trazendo o ID do cadastro, preciso manipular pois está desalinhado com o conteúdo do form mas não consigo mais acesso a ele.
Estou usando Visual Studio 2015.
Comment: Tem uma janela chamada **document outline**, nela vão estar todos os controles de form e ao clicar em um, ele será selecionado no form designer.
Comment: Funcionou perfeitamente, mas seu comentário pode vir como resposta ?
Comment: Postei como resposta, eu estava esperando o Visual Studio abrir para poder postar uma imagem, mas não tá dando muito certo xD
Answer: Como mencionado pelo @Linq nos comentários, você pode usar a janela Document Outline e acessar qualquer controle no Form

Ou, na janela Properties você tem um combo, com os controles do Form também:
Comment: Funcionou, obrigado
Answer: Tem uma janela chamada document outline, nela vão estar todos os controles de form e ao clicar em um, ele será selecionado no form designer.

Vou colocar uma imagem assim que meu computador colaborar e eu conseguir abrir o Visual Studio -_-
Comment: Funcionou, obrigado


How to tell whether a variable should be treated as continuous or categorical?

Question: Suppose I used a multiple linear regression to model the association between cognitive score (Y) and sleep quality (X) along with other variables (gender, age etc.).
cognitive score ~ sleep quality + gender + age + ...

Sleep quality was measured and recorded in scores:0, 1, 2 or 3. How could I tell whether this variable should be treated as continuous or categorical? Is there any statistical analysis I can use? I tried to simply plot the X and Y to see if there's a linearity. However, this plot can still be interfered by gender, age or other variables (which I cannot add in the plot).
Comment: The context should decide whether it is a continuous or discrete variable, not a statistical test. Can you tell us more about this variable, what do these numbers represent?
Comment: Though you are not saying the scale is "likert" rating, this may be helpful: https://stats.stackexchange.com/q/10/3277
Comment: About ordinal predictor variables https://stats.stackexchange.com/q/195246/3277
Comment: You can fit the model both ways, in categorical and continuous form, using all other X variables in both models. Then draw graphs of the response function, each way, on the same set of axes, holding all other X variables fixed at, say, their mean values. Drastic differences in the two functions suggest the need to treat the X as categorical; otherwise, use the continuous form for parsimony. There are examples with R code here https://www.routledge.com/Understanding-Regression-Analysis-A-Conditional-Distribution-Approach/Westfall-Arias/p/book/9780367458522#
Comment: @user2974951 Thank you. This variable is a score used to quantify sleep quality (PSQI score). The score ranged from 0-3 based on self report question including time stayed in bed, daytime sleep etc.
Answer: Your variable is neither.
You have what is called an ordinal variable, which is kind of a hybrid of a numerical variable and a categorical variable. Think of it as an ordered category where the differences between categories are hard to quantify. We know that $1$ meter is the same amount shorter than $2$ meters as $2$ meters is shorter than $3$ meters. I struggle to say something similar for rating sleep quality.
Sometimes it can be fine to treat an ordinal variable as continuous, such as when you calculate your school GPA. Other times, it might make less sense.
Comment: I have no problem in calling ordinal scales categorical too, as well as nominal scales. That's a strong pattern in texts on categorical data analysis such as those of Alan Agresti.
Answer: The only elegant solution is to use a Bayesian model where the predictor is coded with indicator variables that are constrained by prior distributions that respect the ordinal nature of the variable.  The R brms package brm function handles ordered factor variables automatically in this way.  If doing traditional frequentist regression models, the best we usually have time to do is to treat the ordinal variable as quadratic, i.e., include $x$ and $x^2$ in the model, the latter term so as to not assume linearity.  We would use regression splines for continuous variables where knot location is not problematic due to excessive ties.
When an ordinal variable has less than, say, 4 levels, it is not too inefficient to treat it as categorical using the usual indicator variable approach.


Como fazer replace em string html somente nos textos dentro das(entre as) tags?

Question: Eu criei uma busca que marca o texto que foi encontrado.

OBS 1: A busca é feita numa string que é HTML.
OBS 2: Eu verifico se existe o texto dentro desse HTML através do
indexOf.
OBS 3: Se achar eu dou um replace em todas as ocorrências do texto,
substituindo o texto pelo proprio texto só que dentro de uma div que
faz a marcação com css (Exemplo: '
texto
'
no lugar de apenas 'texto').

O problema que me dei conta depois é que se eu busco a palavra html ou body, ou href, etc, eu acabo quebrando o html da página depois que faz o replace, pois estou mexendo em tags e atributos html dentro da minha string.
Logo, eu gostaria de contornar isso substituindo somente textos que estão dentro dessas tags. Mas não consegui ainda imaginar na cabeça alguma forma de fazer isso. Preciso de ajuda com idéias de soluções para isso, mesmo que não seja a explícita na pergunta.
Comment: Você pode utilizar o `innerText` ao invez do `innerHTML`. se não resolver, acredito que terá de fazer uma busca em profundidade.
Comment: O problema é que o `innerText`, dependendo do contexto em que ele estiver pesquisando, vai transformar as tags em apenas texto.
Answer: Se você está querendo pesquisar uma palavra específica e substituí-la, sem influenciar nas declarações das tags, tanto em nome quanto em atributos, você pode usar o seguinte exemplo, com o jQuery.

 $(function(){

     var filterWord = function(){
         var self = $(this),
             text = self.html();

         if (self.children().size()) {
             self.each(filterWord);
         } else {
           self.html(text.replace(/a|p|h1|texto/gi, 'p'))
         }

     };

     $('.container').find('*').each(filterWord);

     filterWord.call($('.container'));
 });

texto

texto que está na tag

    texto
    Meu texto

atualização
Adicionei a verificação para aplicarmos uma recursividade. Com o método children eu verifico se dentro do elemento atual tem uma tag. Se existir, ela aplica a recursividade no elemento filho de self. Se não, ele substitui o texto, certo de que não há tags a serem substituídas, e sim, apenas conteúdo.
Veja isso funcionando no JSFIDDLE
Comment: No seu fiddle, quando eu tento substituir 'h1' por 'p' ele fez o replace. A intenção é que não faça, somente faça no conteudo dentro de h1
Comment: Vou atualizar a solução
Comment: @JoaoPaulo, resposta atualizada. Agora não substitui mais `h1` por `p`. Pode testar a vontade :)
Answer: Se você quer substituir apenas o conteúdo das tags, você pode fazer assim

var html = $.parseHTML(' ola mundo\
 vem mundo \

 nao troque o mundo
\
 mundo nao mundo meu mundo ');

 var troca = ["mundo", "troll"];

 for (var tag in html) {
   $(html[tag]).text($(html[tag]).text().replace(new RegExp(troca[0], "g"), troca[1]));
 }

 for (var tag in html) {
   document.write($(html[tag]).text() + "
");
 }

Se você quiser fazer isso para todos os elementos da pagina, basta usar html = $("*")
se você estiver trabalhando no proprio DOM, pode usar essa função
function htmlReplace(html, stringA, stringB) {
    for ( var tag in html) {
    $(html[tag]).text($(html[tag]).text().replace(new RegExp(stringA, "g"),stringB));
    }
}

Answer: Você pode fazer uma busca em profundidade e verificar o tipo do Node:
var content = document.getElementById("content");
var txtFind = document.getElementById("txtFind");
var txtReplace = document.getElementById("txtReplace");
var btReplace = document.getElementById("btReplace");

var replaceText = function (elem, find, replace) {
    for (var indice in elem.childNodes) {
        var childNode = elem.childNodes[indice];
        if (childNode.nodeType == 3) {
            childNode.data = childNode.data.replace(find, replace);
        }

        if (childNode.nodeType == 1) {
            replaceText(childNode, find, replace);
        }
    }
}

btReplace.onclick = function () {
    var find = new RegExp(txtFind.value, 'g');
    var replace = txtReplace.value;

    replaceText(content, find, replace);
}

        Find:
        <input id="txtFind" type="text" />

        Replace:
        <input id="txtReplace" type="text" />

        <input id="btReplace" type="button" value="Substituir" />

    Teste - Lorem Ipsum

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce molestie urna dignissim justo iaculis aliquam. Ut auctor sit amet justo laoreet semper. Curabitur hendrerit ornare vulputate. In dictum dui et sem ultricies, id rhoncus nisi dignissim. Suspendisse ac enim sollicitudin, gravida leo eu, fringilla nisl. Suspendisse potenti. Aenean blandit ut purus eget varius. Fusce ornare pretium mauris, placerat viverra est facilisis in. Nunc elementum, leo ac tincidunt luctus, ipsum ipsum laoreet tortor, finibus pulvinar enim erat sit amet mi. Phasellus vulputate fringilla tortor, id tempus urna suscipit id. Vivamus ipsum libero, lacinia quis felis mollis, luctus viverra mi. Praesent id elementum metus, quis porttitor est. Integer condimentum rhoncus eros eget varius. Vestibulum vitae arcu libero.

Suspendisse ultrices neque ornare convallis posuere. Curabitur consectetur libero ut urna sodales, eget vehicula magna sodales. Sed a tincidunt lacus, non varius odio. Morbi mollis hendrerit mollis. Duis mauris libero, semper eu lectus ut, porta accumsan diam. Sed tristique tortor est, non luctus nulla cursus quis. Proin lacinia, leo vel mattis efficitur, turpis nulla finibus nulla, vel consectetur erat dui ut turpis. Curabitur sagittis elementum ante a rhoncus. In in lorem et turpis condimentum rutrum et at metus. Proin vitae tellus elementum, feugiat nulla ac, porta sapien. Donec dapibus nulla sit amet urna porta consectetur. Donec tristique massa justo, vel finibus turpis aliquam et. Ut nisl elit, fermentum et ultrices sit amet, rutrum a est. Proin vel varius neque. Integer bibendum porta neque, at vulputate ante bibendum vel.

Sed laoreet nisl in nisl tempor, vitae bibendum arcu porta. Vivamus feugiat felis euismod magna tincidunt, non cursus nunc ultrices. Interdum et malesuada fames ac ante ipsum primis in faucibus. Cras ac mi eu urna molestie vehicula vitae a quam. Morbi et eros nec libero auctor imperdiet. Nunc pharetra sapien sem, in molestie tellus pellentesque eu. Mauris sit amet ante placerat diam pulvinar tempus. Morbi mollis imperdiet tortor. Pellentesque mollis leo non tellus congue, non molestie quam condimentum. Mauris malesuada, felis nec faucibus faucibus, purus ante faucibus nulla, et hendrerit nisl tortor a turpis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Pellentesque tempus eros ut massa iaculis euismod. Morbi vestibulum enim nisl. Sed volutpat tristique consectetur.

Proin non commodo leo, non ornare mi. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nam egestas est non malesuada iaculis. Ut congue laoreet vehicula. Nunc velit enim, sollicitudin quis orci tristique, lacinia lacinia augue. Nam at mattis purus, eget pulvinar odio. Duis et dapibus eros. Praesent rhoncus vitae turpis non tempus. Sed semper sit amet ipsum ac interdum. Nunc pulvnisi, vitae aliquam est feugiat eu. Pellentesque scelerisque nisl et molestie malesuada. Maecenas ullamcorper sapien quis enim dictum, sed pellentesque risus consequat.

Donec porta turpis at est rutrum, sed interdum dui semper. Donec lectus ligula, egestas ut sagittis non, mattis eu dolor. Cras convallis sem non urna tristique, ac sagittis magna egestas. Maecenas imperdiet, nulla at mattis sodales, neque nibh ullamcorper enim, at sollicitudin eros sem at diam. Sed dui magna, pretium a lobortis id, accumsan ac nibh. Ut neque quam, elementum in fringilla elementum, scelerisque vel est. Etiam blandit, dolor eu suscipit pharetra, massa tellus facilisis sem, nec elementum eros est ac libero. Nam faucibus mattis ex, ac lacinia metus finibus eget. Cras sit amet turpis rutrum, volutpat tortor non, cursus nibh. Vestibulum congue justo nec elit fermentum, mattis sodales sem convallis.


What are the ABRSM graded examinations, and why would one want to take them?

Question: I have seen several questions here about the exams offered by the Associated Board of the Royal Schools of Music in the United Kingdom. Most questions are from the standpoint of people who are in the middle of the examination process. Here in the United States of America, I have never heard of these exams and don't understand their purpose.
I've been directed to this web site, http://us.abrsm.org/en/home/, but I have basic questions that I cannot seem to find answers to:
Is taking these exams something that a large number of musicians in the UK do? What are these exams and certificates used for? Who would want to earn them, and why? At what stage in a person's musical education does one start taking these examinations, and where do they lead? Is achieving a certain level of examination a prerequisite to doing something else as a musician? For instance, do they have something to do with getting admission to college, becoming a music teacher, or joining the musicians' union?
Comment: ABRSM is very useful and helped me. I took graded examinations and participated in other ways, and gained certification. It's good evidence that you're ready for an exam or competition. I gained new challenges and more experience to improve my ability. I panicked a lot in my exam, however I work very hard and strive to practice more (this year I have my first piano exam)
Answer: I'll quote Wikipedia for some background on the ABRSM:

The Associated Board of the Royal Schools of Music (ABRSM) is an examinations board and registered charity based in London, United Kingdom, which provides examinations in music at centres around over the world. The ABRSM is one of three examination boards accredited by Ofqual to award graded exams and diploma qualifications in music within the UK's National Qualifications Framework (along with the London College of Music and Trinity College London).
The Royal Schools referred to in the board's title are:

The Royal Academy of Music
The Royal College of Music
The Royal Conservatoire of Scotland
The Royal Northern College of Music

More than 650,000 candidates take the ABRSM examinations each year in over 93 countries. The board also provides a publishing house for music which produces syllabuses, sheet music and exam papers and runs professional development courses and seminars for teachers.

In the UK, most of Europe, and various other parts of the world, the ABRSM grading system, or something very like it (other examining bodies exist), is endemic to formal music training.
Like graded qualifications in any other field, they serve several purposes:

As a learner, it gives you a concrete measure of your own progress
As a learner, it allows you to communicate to others what your current abilities are in an objective manner.
As the parent of a learning child (or the funding body) it provides a concrete measure of the teacher's productivity and the pupil's attainment
As a teacher, it gives you an objective way to gauge potential new pupils' ability and aspirations
... and so on.

Of course, a number between one and eight is a very imprecise measure, but it's still useful:

"Smalltown Youth Orchestra welcomes members of grade 3 and above"
"Since you're grade 4, we'll put you in the 3rd Violin section"
"I'd like you to teach me to improve my piano - I'm currently grade 6, but I want to reach grade 8 by this time next year"
"I'd be a great teacher for your daughter. In the past year I've taken five pupils her age from complete beginner to grade 3 Distinctions"

In the UK, if you are taught classical music, you will almost certainly jump straight into the ladder of ABRSM grades - starting with grade 1 theory, then grade 1 practical, then grade 2 of each, eventually reaching grade 8.
The theory exams are written.
The practical exams involve playing to an examiner:

scales, arpeggios etc.
sight reading from a score.
performing a piece that has been practised.

If you are taught jazz performance, it's not quite so "automatic" that you'd enter the grade system - but many people do. There are versions of the exams for jazz which have improvisation components.
Learners of rock/pop performance are much more likely to ignore the grade system, although exams are available for them (and of course, classically trained musicians can play rock/pop!)
Grade 1 is very basic: it's something an 8-year-old would pass after a few months of study.
Grade 8 is the "top" grade, and (I gather) exceeds the abilities typically expected of a student starting music college in the USA. Beyond grade 8, there are more advanced diplomas, which fewer people aspire to tackle.
You don't need a license to be a music teacher - but a prospective customer would reasonably expect you to demonstrate your ability, and an exam certificate is one good way (accredited teaching certificates are also available).
You don't need necessarily need a grade to go to music college or to get a job, but it's a convenient way to demonstrate your ability (or potential ability) in advance of an audition.
As far as treating the grade as a "passport" goes, it depends on the situation.

For something like an amateur orchestra - a hobby for the players - it's not unusual that just telling them your grade is sufficient. You needn't really even have taken the exam -- "I haven't taken the exam, but I think can sight read orchestral cello parts at grade 6 level".
For more serious positions - professional jobs, or amateur groups with high standards, you'd typically still do an audition, but the grade is still useful: "Sorry, we don't really think it's worth you trying the audition if you're only at grade 5".

One other use of grades, is as a measure of difficulty for pieces. The grades provide a vocabulary of difficulty, so you can sensibly say things like "This piece is something a Grade 6 pianist would find challenging".
Comment: Superb answer, Slim, but the 'grade one theory then grade one practical' isn't necessarily true.In fact, grade 5 theory is often taken only as a passport to being allowed to take 6,7,8 practical.The playing involves 3 pieces often from different eras or genres, not just one.
Comment: Just a clarification: there's no sense in which the ABRSM grade system is "imposed on education" in the UK. Schools are required to teach the National Curriculum, which includes music, but this is not derived from or related to the ABRSM syllabus. The widespread adoption of the ABRSM system is wholly voluntary.
Comment: This is quite astonishing to me. We have nothing even remotely resembling this in my country, the USA. In this country, for any performing group, or school, you show up for an audition, play two or three pieces of music that you select that will demonstrate your skill level, they ask you some questions about your background, and then they invite you to join the group or matriculate at the university, or not. The idea of "what grade have you achieved" is inconceivable, because in this country we have no system in place to measure anything like that.
Comment: I agree with Tim - hardly anyone does any theory grades other than 5 and maybe 8. You have to do grade 5 theory to do 6, 7 and 8 practical, and some people might do 8 as it's the top one. Some people work up to grade 5, but not many, and lots of people jump straight to grade 5.
Comment: I can see already why we don't have such a system in the USA. It is cultural and political. We have 50 sovereign states that have their own separate educational systems, and states have historically resisted any national standards being imposed on education, particularly in childhood. In the professional realm, for instance, accreditations are established individually by each state, and one state usually will not recognize accreditation from another state. For such a system to work we would need a culture where national standards were accepted everywhere. We have quite few.
Comment: This matches with the Canadian [Royal Conservatory of Music](http://en.wikipedia.org/wiki/The_Royal_Conservatory_of_Music) (RCM) -- Grade 8 counts as a highschool credit, though there are a couple grades above that before ARCT (the most advanced diploma).
Comment: And of course Canada is in the British Commonwealth and the USA is very pointedly not. It seems to me to be a cultural thing. I think we could certainly benefit from a nationally-recognized system in the USA, but as far as I know, there is none.
Comment: The big problem with grade exams is that people don't realise that they don't test ensemble playing. Some amateur orchestras mistakenly believe that if someone has passed grade 8 but has no ensemble experience then they would make good members. This is not the case. I have seen numerous examples of people who have passed grade 8 but cannot count or sight read. Ensemble skills are completely different to those needed to pass grade exams.  I am trying to educate amateur orchestras not to use these exams as standards, because the exams don't teach any ensemble skills.
Comment: You can also watch and learn from some of the ABSRM teachers at http://www.artisttag.com/posts/
Answer: ABRSM grades are mainly for people who are first learning an instrument, and they're mainly to track progress and give students something to work towards, rather than as a qualification. Because students are tested on playing at sight, scales, and understanding of rhythm, not just technique on a prepared piece, they're a good way to get them to practise these areas that are often neglected.
As part of the exam, the candidate has to play a small number of pieces, which he chooses from a list set for each Grade by ABRSM (and collected and published in a book). The number you need and how many are on the list are different for each Grade. The list is revised every so often for variety (and so teachers have to buy the new book!), but the difficulty of the pieces is consistent, so it sets a clear idea of what's a "Grade 3 standard" piece. Because the list changes, and the student has some freedom of choice, you can't infer what pieces someone knows from what Grades they have passed. (If you have a rough idea of when they took the exam, you know they have any two or three from a set of a few dozen.)
Youth orchestras and ensembles will often say they welcome players of Grade 4 and above (for example), and easy pieces and arrangements are often classified as (say) Grade 3 standard, which gives an indication of how hard they are. Because they're a widely-known standard, they're used to refer to a particular level of skill and knowledge even if you haven't taken the exam. In addition, because music teachers tend to use the official Grade pieces for teaching all their pupils, if someone is in formal tuition and at a particular level, they'll probably have seen all the current pieces even if they don't know them all well enough to pass the exam.
A reasonable student should be able to improve by a grade each year, and a talented student by two grades a year. It's commonplace to skip a few grades (you don't have to have passed Grade 1 to take the Grade 2 exam, &c.) if you're progressing well or if you're learning a second or third instrument.
They're not directly relevant to professional or full-time musicians (other than in teaching contexts), just because they don't go up to a high enough standard of playing. If you learn an instrument throughout your school career, you should be Grade 8 by the time you leave, but that doesn't mean you're good enough to play professionally. Orchestras and groups for grown-ups don't tend to mention or require Grades, and there are many famous musicians with no Grades at all. Even so, most musicians in the UK (and many non-musicians) have at least one, because they're likely to have taken one while learning an instrument at school. Often their Grade(s) will be in completely unconnected instruments to what they play now. However, ABRSM does offer letter-bearing exams after Grade 8 the first of which is ARSM (Associate of Royal Schools of Music) and is a solo performance exam. Other professional exams such as Dip ABRSM and LRSM (teaching qualification) are available too.
To take myself as an example, I now play percussion in a brass band, and I've given piano recitals and sung in choirs, but my only ABRSM qualification is Grade 3 flute.
Comment: @WheatWilliams Usually you would select certain pieces from the set lists (there are different types) to learn during your study of that grade.  The examination for higher grades usually requires you to play one piece of your choosing from the "main" list and 2 others from 2 of 3 secondary lists, or something along those lines.
Comment: Just to add that although you don't need to have the previous Grades to attempt the next level, you now MUST have passed Grade 5 Theory before attempting any practical exams of Grade 6 and above.
Comment: I would not have done ABRSM if I did not think they were qualifications worth aspiring towards.
Answer: As a rough guide, many children start playing an instrument at about the age of 7.  Most students take about a year to pass each grade, with more enthusiastic pupils reaching grade three after just a couple of years.  Many sadly give up after only a few grades.  For those that push on to the higher grades, these often coincide with having to sit important school exams, e.g. GCSE's and A levels, demanding a lot of dedication to be successful in both.
Beyond grade 6, the pieces and especially the other requirements, such as sight-reading and aural tests get much harder.  There seems to be a huge leap between grade 7 and grade 8, where the pieces are much longer.  The rondo from Beethoven's  Pathetique Sonata has been used as a Grade 8 piece, just to give you an idea of the level expected.
Unfortunately, some professional musicians have a horribly patronising attitude towards people who have learned for fun.  Many pupils dutifully practice, because it's a hobby that their parents chose for them and they should be encouraged.  Sadly some of the professional musicians, who have chosen music as their career (rather than playing because their parents wanted them to learn) put down grade 8 players, as if they are merely beginners, which does nothing for their confidence or enthusiasm.  It's like an international professional footballer saying that a  club player is not in the same league - it simply doesn't need to be said, if someone is getting pleasure from what they do.  Very few people reach grade 8 on any instrument, it is a wonderful achievement.  Many of these people are encouraged to follow other careers instead of music, since it isn't well paid.  They have managed to achieve an extremely high level AND be talented in other areas too.
Answer: Similar system applies in Australia, called the AMEB, or Australian Music Examinations Board. I'm an amateur player, attend a once-a-school-term chamber music play-in for fun, and members are put into trios, quartets, etc, with similarly graded players. Not all have done exams so don't have a paper grade, but the chamber music society has developed its own questionnaire to provide us with a score to use for those days.
Answer: At grades 6, 7 & 8, UCAS points are given - this means that students applying for University can use their ABRSM results to bolster their other exam results ( A levels etc.) for a better chance of being chosen for a University place. This also happens with other exam. boards - LCM has Registry of Guitar Tutors exams in bass, classical, electric, rock and acoustic playing, so a lot of teachers use these syllabi because a graded system is easy to follow and gives good targets.
Having said all that, in 50 years, no-one has ever asked me  at an audition "and what grade are you......." But, it's something else to add to your c.v.
I'm surprised that these type of exams are apparently unknown in U.S., as ABRSM and RGT reach out to many other countries world-wide, and have done for many years.
Comment: There is a bit of confusion about education levels in the UK. The qualifications at each level are put together because they take roughly the same number of years to achieve.  However they aren't the same level in terms of education standard or employment. FRSM,FTCL,and FLCM are not equivalent in education standards or employment prospects of a doctorate. Professional classical performers do not take any diplomas because the standard of playing required to pass even the Fellowship ones is too low even for someone to teach instruments at a top conservatoire.
Comment: The number of UCAS tariffs allowed for ABRSM grades is given in this table: https://www.ucas.com/ucas/undergraduate/getting-started/entry-requirements/tariff/tariff-tables/1086 and appears to have reduced over the last 10 years. It's also worth note that most UK universities, especially the posher ones, do not use UCAS points but make offers subject to grades at specific exams (A levels or baccalaureate)
Comment: Further to my above answer, the qualifications go way beyond grade 8. After this, the exams split basically into performing or teaching.These diplomas take the candidates up in 3 or 4 stages,depending on the exam board, ending with a doctorate or fellowship award, equivalent to a University lecturer. However, one doesn't have to attend University to achieve this.It's also an attempt to align all instruments, as in a grade 5 flautist should be as good as a grade 5 violinist,etc.
Answer: Grade exams are short tests to make sure that a pupil has been learning what a teacher has been teaching.  Because they only test a very narrow aspect of music making they can't be used as a general music qualification.  They can only be used as a qualification in respect to each other as in grade 6 is better than grade 5 but not as good as grade 7.  The reason for this is because they only test what someone can play on one specific day with one examiner from the ABRSM.
It is quite possible to pass grade 8 and be unable to play very elementary ensemble music because they don't test ensemble playing with other players of the same standard as the person taking the exam. (Any accompanist is usually employed to play for the exam candidate and will not be the same standard of playing as the exam candidate.)  It is also possible to pass grade 8 without passing the sight reading section of the exam.
They are very useful for children learning an instrument as when a child passes an exam they get a certificate and often the children like to collect the certificates, much like a swimming badge that might be awarded for swimming a length of the swimming pool etc.
They are not really suitable for adults to take because most adults start an instrument in order to play in an ensemble and the grade exams do not test ensemble playing.
Some amateur orchestras advertise for certain grades for new members, in the mistaken belief that this will give then an idea of the standard of a new member, however it is quite possible to pass grade 8 the highest grade and be unable to play even in an elementary ensemble group.
Non of the grades are of a high enough standard to qualify someone as a teacher.
Some children pass grade 8 at age 10.  Potential music conservatoire students have usually passed grade 8 with distinction by the age of 14.  Music conservatoires use auditions for student selection.
These grade exams do not lead to anything except another grade exam or diploma.
Most people take them when they are at school.
Professional classical music players regard them as very elementary standards, tests that you take at school when you start an instrument.  From the perspective of a professional orchestral player grade 8 is an exam that very elementary players take, so you wouldn't join the musician's union after taking this exam as there would not be any point..
Comment: I've been a member for probably 30 years plus.I play semi-pro., and have never been asked for grade results.As it happens, I do have grade 8 pno., but joined as a guitarist, with NO grades.DJs are M.U. members - what grades may they have? Sorry, but there's no relationship between M.U. and music exam grades.
Comment: The MU represents people who make their living through music.  Because grade 8 is an elementary exam most professional musicians wouldn't mention it. Professional classical musicians generally take it at school when they are about 14. Most people don't mention tests they took at school age 14 in relation to what they do for a living.  You don't have to pass any grade exams to make a living in music. So there is no reason why anyone who makes a living playing music can't join the MU.  But grade 8 people won't make a living because they can't play well enough.
Comment: a 14-year-old playing at a grade 8 standard would be a once in a lifetime prodigy, how many of these have you really met. The grade 8 course is generally a two-year course with dedication and hard work.
Comment: Could you elaborate on the correlation between the Musicians' Union and passing a grade 8 exam, please? I see no relationship. (Musicians' Union is a U.K.organisation probably unknown to the rest of the world, e.g. U.S.)
Comment: Musicians' Union is trade union that represents professional musicians and supports them in payment agreements and working conditions.  There is also a Musicians' Union pay structure for hourly pay for session work. Someone whose highest playing standard would allow them to pass grade 8 won't get any work as a professional musician because they can't play at a high enough standard.  They would be unable to join the musicians' union because they wouldn't be earning their living through playing music.
Comment: Just spoken to M.U. and they confirmed that NO qualifications are necessary for membership.
Comment: Confused about these comments: the answer *says* that you **wouldn't** join the MU after doing grade 8. However I bet there's professional rock musician MU members who couldn't pass any exam that requires reading a score
Comment: By grade 8 people I mean someone whose music learning standard has just reached the point where with practise on the pieces they could pass the grade 8 exam. Professional classical musicians view grade 8 as an elementary exam that a beginner would take.  By beginner I mean someone who has been playing about 2 years.  From my own experience of my second instrument learnt as an adult I could have passed grade 8 less that 2 years after starting. But as an adult I have no use for exams which are designed to be taken at school.
Comment: There is certainly a musicians' union in the United States of America. It is called the AFM, or American Federation of Musicians. It also extends into Canada. It was formed in 1896.


how to hide widgets from blogger label search

Question: How do i hide element from showing in my label search result only.
I have tried all ways but the css i got to use will only hide on all the pages. I also used different article but it hide widget on specific pages, blog post and not label search result
I want some or all widget/element within my label search to be hidden without hiding all the elements or widgets that appear in home. Please note i don't want to hide widgets or element in home but label result. I want the label result to just have the list of post within the label
Here is the label link search result which shows all element in home before showing my label post. I just want the label post https://quickrecruitng.blogspot.com/search/label/Administrative%20Officer
Answer: To target label pages, use the following
<code><b:if cond='data:blog.searchLabel'>
  <!-- all label pages -->
</b:if>

<b:if cond='data:blog.searchLabel == "foo"'>
  <!-- for label 'foo' -->
</b:if>
</code>
Comment: Thanks a lot for your response but what do I do with the line of code you posted. How do I out it to work to achieve what i want
Comment: The challenge is that most of the things i want to hide are not widgets but elements covered with div. See the url i previously sent to see the front end or look at my back end code https://snag.gy/Z3Fsqr.jpg
Comment: To hide elements on label pages add them between ` your elements here ` note `!`


Como fazer o teste de Hosmer-Lemeshow no R?

Question: Tenho um conjunto de dados para fazer a regressão logística da variável dependente parto que é qualitativa binária.
Com o comando abaixo obtenho o modelo logístico multivariado no programa R:
GLM.1 <- glm(parto ~ trabalho + financiamento + consulta, family=binomial(logit), data=Dataset)

As variáveis independentes deste modelo também são qualitativas binárias.
Gostaria de saber qual comando do R devo usar para obter o teste de Hosmer-Lemeshow para verificar se este modelo está ajustado.
Caso seja necessário utilizar um pacote específico do R para isso, gostaria de saber qual seria este pacote e qual função usar.
Comment: Você poderia postar o seu conjunto de dados para efetuar os testes?
Answer: Com uma rápida pesquisa no Stack Overflow em inglês e com o comando RSiteSearch do próprio R encontrei 2 funções para tal teste. hoslem.test do pacote ResourceSelection e logitgof do pacote generalhoslem
Comment: Usando o pacote `ResourceSelection` com o comando `hoslem.test(Dataset$parto, fitted(GLM.1))` encontro o seguinte resultado: **X-squared = 455, df = 8, p-value < 2.2e-16**. No entanto, usando o pacote `generalhoslem` com o comando `logitgof(Dataset$parto, fitted(GLM.1))` , para os mesmos dados, encontro este outro resultado: **X-squared = 4.3539, df = 7, p-value = 0.7382**. Além disso, usando o programa SPSS, também para os mesmos dados, ainda encontro outro resultado **X-squared = 4.168, df = 8, p-value = 0.842**. Você poderia me explicar porque esses resultados são diferentes?
Comment: não faço ideia por que dessa diferença. Eu utilizei o exemplo dado no `help` da função `hoslem.test` e comparei o resultado de ambas as funções, e o resultado foi o mesmo.
Comment: Segue o link (https://www.dropbox.com/s/64jo0auqeowj8fh/teste.xlsx?dl=0). Comando para gerar o modelo: `GLM.1 <- glm(parto ~ trabalho + financiamento + consulta, family=binomial(logit), data=Dataset)`. Resultados atualizados com o que obtive nos testes para as variáveis: pacote `ResourceSelection` e comando `hoslem.test(Dataset$parto, fitted(GLM.1))` encontrei **X-squared = 455, df = 8, p-value < 2.2e-16**; pacote `generalhoslem` e comando `logitgof(Dataset$parto, fitted(GLM.1))` encontrei **X-squared = 2.2901, df = 3, p-value = 0.5144**. No SPSS **X-squared = 2,357; df = 5; p-valeu = 0.798**
Comment: acabei de rodar aqui, e a diferença que apareceu aqui foi nos graus de liberdade e no p-valor do teste. `GLM.1 <- glm(parto ~ trabalho + financiamento + consulta, family=binomial(logit), data=test`. O comando `hoslem.test(GLM.1$y, fitted(GLM.1))` resultou em `X-squared = 2.2901, df = 8, p-value = 0.9708` e o resultado do comando `logitgof(GLM.1$y, fitted(GLM.1))` foi `X-squared = 2.2901, df = 3, p-value = 0.5144` com um **warning** `In logitgof(GLM.1$y, fitted(GLM.1)) : Not possible to compute 10 rows. There might be too few observations.`
Comment: Coloquei o pacote `reshape` para rodar junto com o pacote `ResourceSelection` e rodei o comando `hoslem.test(Dataset$parto, fitted(GLM.1))`. Então, o resultado agora ficou igual ao do Rafael Cunha **X-squared = 2.2901, df = 8, p-value = 0.9708**. Com o pacote `generalhoslem` e comando `logitgof(Dataset$parto, fitted(GLM.1))` o resultado continua dando **X-squared = 2.2901, df = 3, p-value = 0.5144**, e também aparece a mesma mensagem **Warning in `logitgof(Dataset$parto, fitted(GLM.1))` :
Not possible to compute 10 rows. There might be too few observations.**
Comment: Talvez essa diferença seja devido a alguma diferença na implementação dos códigos...
Answer: O que eu sei, sobre o teste de hosmer e lemeshow que essa diferença pode ser em função do agrupamento dos dados, quando os dados não são múltiplos de dez ou da quantidade de grupo para o teste estatístico, que em geral é 10, os agrupamentos são diferente no spss e no teste do resourseselection no r. Por exemplo com 105 amostras no spss ele agrupa os 9 primeiros com 11 dados e o ultimo grupo com 6 enquanto no r com o pacote resourse selection ele tenta deixar do mesmo tamanho todos os grupos, entao alguns grupos ficarão com 11 outros com 10 amostras por grupo, o que da diferença no resultado. Particularmente nao sei identificar qual é o mais correto.


HttpUrlConnection redirection to other servlet is not happening

Question: I have the following code which will call the server through HttpUrlConnection.
String response = HttpUtil.submitRequest(json.toJSONString(), "http://ipaddr:port/SessionMgr/validateSession?sessionId=_78998348uthjae3a&showLoginPage=true");

The above lines will call the following code:
public static String submitRequest(String request, String **requestUrl**) {
    try {
        URL url = new URL(requestUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        OutputStream os = conn.getOutputStream();
        os.write(request.getBytes());
        os.flush();
        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(
                (conn.getInputStream())));
        String output;
        StringBuffer sb = new StringBuffer();
        while ((output = br.readLine()) != null) {
            sb.append(output);
        }
        conn.disconnect();
        return sb.toString();

    } catch (MalformedURLException e) {
    } catch (IOException e) {
    }
    return "";
}

The requestUrl will go to the servlet below:
public class ValidateSessionServlet extends HttpServlet {
    String session = req.getParameter(sessionId);
    if (session == null) {
    // redirect to servlet which will display login page.
    response.setContentType("text/html");
            String actionUrl = getIpPortUrl(request)
                            + PropertyConfig.getInstance().getFromIdPConfig(globalStrings.getCheckSSOSession());
            out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"> \n");
            out.write("\n");
            out.write("<form method=\"POST\" action=\"" + actionUrl + "\">\n");
            out.write("<input type=\"hidden\" name=\"locale\" value=\"" + locale + "\"/>\n");
            out.write("<input type=\"hidden\" name=\"Sessionrequest\" value=\"" + true + "\"/>\n");
            out.write("</form>\n\n\n");
     }
}

In the above code the form should go to the servlet as mentioned in the actionUrl, but it is again going to servlet which is in step(1).
1) May i know can we make this above html form in step(3) to submitted and redirect to the servlet in actionUrl.
As per the above code i am summarizing the requirement. If the session is null, I have to redirect the user to login page and validated against database and then the response should go to step(1), Is it possible?
Comment: Can some body please tell me whether it has solution or not?
Comment: You perform a server side post, what do you do with the POST's output? Btw I think you're following a dangerous way. If you want to make RPC like calls on HTTP, you should rely in having JSON responses too, the mixed mode (JSON or HTML) is prone to errors (can be done, but it will trigger all sorts of problems).
Comment: Are you doing kinds of automation on operating web sites, auto login, etc? If so please consider using selenium.
Answer: If you want your HttpUrlConnection to support redirections, you need to set your HttpUrlConnection like this:
...
conn.setRequestProperty("User-agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.215 Safari/535.1");
conn.setInstanceFollowRedirects(true);
...

Then if your server redirect your request somewhere else, conn will receiver the redirected response.
Answer: To clarify, setInstanceFollowRedirects(true) only dictates whether HTTP redirects should be automatically followed by the HttpURLConnection instance. In your particular case, it seems that you want to redirect to servlets based on whether session is null (or some other condition based on your specific application logic).
The correct (and more bug-proof solution) is to check for HTTP 3xx status code cases and manually handle the redirect. Here is a code snippet as an example:
if (responseStatusCode != HttpURLConnection.HTTP_OK) {
   switch(responseStatusCode){
      case HttpURLConnection.HTTP_MOVED_TEMP:
          // handle 302
      case HttpURLConnection.HTTP_MOVED_PERM:
          // handle 301
      case HttpURLConnection.HTTP_SEE_OTHER:
          String newUrl = conn.getHeaderField("Location");   // use redirect url from "Location" header field
          String cookies = conn.getHeaderField("Set-Cookie");       // if cookies are needed (i.e. for login)
          // manually redirect using a new connection
          conn = (HttpURLConnection) new URL(newUrl).openConnection();
          conn.setRequestProperty("Cookie", cookies);
          conn.addRequestProperty("User-agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.215 Safari/535.1");
      default:
          // handle default (other) case
   }
}

The above code is similar to what I use for my app's user login redirects, and I've found that it's very easy to debug. (In general, I handle HTTP status code cases manually in order to avoid bugs down the road.)
Finally, I would recommend using a good JSON lib, such as json.org, to parse your responses.


Consulta no webservice e populado uma grid com os dados

Question: A pergunta referente a "duplicada", é sobre consumir o webservice em delphi, e neste caso eu já consumi, porém agora preciso jogar os dados que o delphi pega do webservice e colocar em uma grid, portanto, um pergunta bem diferente.
tenho um webservice REST feito em Java que faz uma consulta em uma tabela Banco, primeiramente joguei os dados em um MEMO para testar o webservice, porém, agora eu preciso jogar esses dados da consulta em uma grid, pesquisei no google e não encontrei nada que puderia me ajudar, então resolvi peguntar aqui no forum.
basicamente estou fazendo uma app simples para testar o funcionamento do delphi + WS REST, estou tentando criar um WS que faz um insert, update, delete e select nessa tabela Banco, primeiramente estou testando apenas os GETs.
WS:
Obs.1: O método get em questão é o public String getBanco(@PathParam("nome") String nome) o resto são apenas testes.
Obs.2: Acho que não é necessário colocar a classe com os métodos que realiza a pesquisa no banco, se caso seja, editarei o post.
package ws;

import CTR.BancoCTR;
import com.google.gson.Gson;
import dao.BancoDAO;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;

/**
 * REST Web Service
 *
 * @author Vitor
 */
@Path("BancoWs")
public class BancoWs {

    @Context
    private UriInfo context;

    /**
     * Creates a new instance of BancoWs
     */
    public BancoWs() {
    }

    /**
     * Retrieves representation of an instance of ws.BancoWs
     * @return an instance of java.lang.String
     */
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getJson() {
        return "meu primeiro webservice restfull";
    }
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("Banco/get/{nome}")
    public String getBanco(@PathParam("nome") String nome){
        List<BancoCTR> lista = new ArrayList<BancoCTR>();
        BancoDAO banco = new BancoDAO();

        if (nome.equals("null")){
            lista = banco.listBanco(0, nome);
        }else{
            lista = banco.listBanco(1, nome);
        }

        Gson gson = new Gson();
        return gson.toJson(lista);
    }
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("Banco/list")
    public String listBancos(){

        List<BancoCTR> lista = new ArrayList<BancoCTR>();

        BancoCTR banco = new BancoCTR();
        banco.setBcoCodigo(1);
        banco.setBcoNome("Santander");

        lista.add(banco);

        banco.setBcoCodigo(2);
        banco.setBcoNome("Banco do Brasil");

        lista.add(banco);

        Gson gson = new Gson();
        return gson.toJson(lista);
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("Banco/listBd")
    public String listBdBancos(){

        List<BancoCTR> lista = new ArrayList<BancoCTR>();

        BancoDAO dao = new BancoDAO();
        lista = dao.listBanco(0, "");

        Gson gson = new Gson();
        return gson.toJson(lista);
    }

    /**
     * PUT method for updating or creating an instance of BancoWs
     * @param content representation for the resource
     */
    @PUT
    @Consumes(MediaType.APPLICATION_JSON)
    public void putJson(String content) {
    }
}

No Delphi:
procedure TForm1.btnPesquisarClick(Sender: TObject);
var
 filtro: String;

 http: TIdHTTP;
 AStrResponse: TStringStream;
 oSSL: TIdSSLIOHandlerSocketOpenSSL;
 FURL: String;
begin

  if edt3.Text <> '' then
    filtro := edt3.Text
  else
    filtro := 'null';

  http := TIdHTTP.Create(Nil);
  oSSL := TIdSSLIOHandlerSocketOpenSSL.Create(Nil);

    oSSL.SSLOptions.Method := sslvSSLv23;
    oSSL.SSLOptions.Mode := sslmUnassigned;
    oSSL.SSLOptions.VerifyMode := [];
    oSSL.SSLOptions.VerifyDepth := 0;
    oSSL.Host := '';

    http.IOHandler := oSSL;
    http.HandleRedirects := True;
    http.Request.ContentType := 'application/json';

    FURL := 'http://localhost:8080/bancoWS/webresources/BancoWs/Banco/get/'
      + filtro;

    AStrResponse := TStringStream.Create;
    http.Get(FURL, AStrResponse);

    mmo1.Clear;
    mmo1.Lines.Add(AStrResponse.DataString);

    FreeAndNil(AStrResponse);
    http.Disconnect;

    FreeAndNil(oSSL);
    FreeAndNil(http);
end;

Comment: Possível duplicata de [Consumir WebService no delphi](https://pt.stackoverflow.com/questions/273562/consumir-webservice-no-delphi)
Comment: creio que não, ja que ai eu pergunto sobre consumir webservice e não sobre carregar uma grid com os dados do webservice, o que fazer se as classes são as mesmas? kkk
Comment: tem um video aqui que mostra. Talves pode ajudar vc. https://www.youtube.com/watch?v=HJJSWMTpJvk
Comment: não me ajuda, pois, eu já estou consumindo o webservice e carregando os dados em uma MEMO (igual no vídeo) o meu problema agora é em vez de carregar esses dados em uma MEMO eu quero carrega-los em uma DBGrid.
Answer: Para este fim utilizo a biblioteca delphi-rest-client-api, com ela é possível carregar um JSON para um dataset.
Segue o exemplo do criador:
var
  vDataSet: TClientDataSet;
begin
  vDataSet := TClientDataSet.Create(nil);
  try
    TDataSetUtils.CreateField(vDataSet, ftInteger, 'id');
    TDataSetUtils.CreateField(vDataSet, ftString, 'name', 100);
    TDataSetUtils.CreateField(vDataSet, ftString, 'email', 100);
    vDataSet.CreateDataSet;

    RestClient.Resource(CONTEXT_PATH + 'persons')
              .Accept(RestUtils.MediaType_Json)
              .GetAsDataSet(vDataSet);
  finally
    vDataSet.Free;
  end;


Python post-processing

Question: i have to analyse/visualize results of simulations(Simulink, EES) in Python.
Averaged I have to import 40-100 variables (each variable is a vector with several thausend rows) from a result file: Each Variable has a appropriate path in result.data("path to varaible")
My workflow is the following (not really efficient):
Result = {}
Result["VariableA"] = result.data("moment1.p3.Temperatur")
Result["VariableB"] = result.data("moment2.p1.pressure")
..
..

At the end I have a code with around 100 lines - and every line is almost the same. So I assume that there is maybe a better way to do that.
I would be very grateful for suggestions
Comment: possibly relevant for you: https://github.com/kdavies4/ModelicaRes#see-also
Answer: You should define a dictionary with all the variable/path definitions like
paths = {"VariableA": "moment1.p3.Temperatur",
         "VariableB": "moment2.p1.pressure",
         ...
        }

Then you can do
Result = {key: result.data(paths[key]) for key in paths}

or (possibly faster)
Result = {key: result.data(value) for key, value in paths.items()}

(assuming Python 3, otherwise use paths.iteritems())

Python post-processing


Trying Cybersource with Hybris 6.1

Question: Hi i am new to hybris & i have hybris 6.1, Now i want to use Cybersource integration with my hybris. But it needs b2ccheckout addon which is not included in hybris package. I have commented the " -->" in cybersourceaddon/extensioninfo.xml.\,but while ant clean all it gives the error import de.hybris.platform.acceleratorfacades.order.impl.DefaultAcceleratorCheckoutFacade;
   [yjavac]            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   [yjavac] The import de.hybris.platform.acceleratorfacades.order.impl cannot be resolved
Answer: Cybersource extension is not part of the SAP Hybris commerce distribution anymore. Where did you find this extension ?
Deleting dependencies is not how you are going to fix this.
Have a look at the documentation.
Comment: Yeah, agree with that, you should now be using the payment extension
Answer: For integrating cybersource with Hybris, first you need to install the addon using the below command:
ant addoninstall -Daddonnames="**CyberSourceAddonName**" -DaddonStorefront.yacceleratorstorefront="**YourStoreFrontName**"

CyberSourceAddonName could be cybersourcepaymentaddon,cybersourceb2bpaymentaddon
Also add the extensions to localextensions.xml file:
<extension name='cybersourcepayment' />
<extension name='cybersourcepaymentaddon' />
<extension name='cybersourceb2bpaymentaddon' />
<extension name='cybersourcefulfilmentprocess' />

These should resolve your issues.

Trying Cybersource with Hybris 6.1


"apply map vector" idiom - How happens to be 2 functions?

Question: Here is a sample from my mini code where I copied from clojure docs site.
(apply map vector (vec jpgList))

I guess map and vector are both functions, but apply takes only one function. How come in here apply takes two functions?
Answer: Read the documentation of apply:
user=> (doc apply)
-------------------------
clojure.core/apply
([f args] [f x args] [f x y args] [f x y z args] [f a b c d & args])
  Applies fn f to the argument list formed by prepending intervening arguments to args.
nil

So, (apply map vector (vec jpgList)) corresponds to f x args, so map will be applied to the the function vector, followed by the elements of (vec jpgList). Unlike Haskell, Clojure's map supports multiple collections to operate on. (vec jpgList) presumably is a nested vector, or list, like in the following example:
user=> (apply map vector [[1 2 3] [4 5 6]])
([1 4] [2 5] [3 6])

What happened is, every element produced by map is the vector of each nth element of the elements of the nested vector. This function is also known as transpose in matrix operations.
Answer: apply accepts a function and its arguments. If called with more than two arguments, the middle arguments will be added as scalar arguments (like using partial). See the documentation for apply
In other words, all four of these are the same:
(apply (partial map vector) [[1 2 3 4] "abcd"])
(apply map [vector [1 2 3 4] "abcd"])
(apply map vector [[1 2 3 4] "abcd"])
(map vector [1 2 3 4] "a b c d")

All will return ([1 \a] [2 \b] [3 \c] [4 \d]).
Answer: Only map is being 'applied'. However the first argument to map is always itself a function. In this case vector is being prepended to the the sequence of arguments produced by (vec jpgList). vector here is not a second function being applied, it is the first argument in the sequence to which map is applied together with the rest.
You will see this idiom often when applying any higher order function that itself takes a function as an argument.
Answer: Consider this:
user=> (let [n1 1
  #_=>       n2 2
  #_=>       n-coll [n1 n2]]
  #_=>   (=
  #_=>    (apply + 999 n-coll)
  #_=>    (+ 999 n1 n2)))
true

'apply' applies + to the argument list formed by prepending 999 to n-coll. If you substitute map for + and vector for 999 when the collection in question is made of vectors:
user=> (let [r1 [1 2 3]
  #_=>       r2 [4 5 6]
  #_=>       r-coll [r1 r2]]
  #_=>   (=
  #_=>    (apply map vector r-coll)
  #_=>    (map vector r1 r2)))
true


sheaf of differentials definition

Question: I have a question about the definition of the sheaf of differentials:
If $\Delta$:X$\rightarrow$X$\times$X is the diagonal morphism then $\Delta$ is a locally closed immersion.
If we take $I$ to be the ideal sheaf of $\Delta$(X), we use $I/I^2$ to define sheaf of differentials.
What exactly do we mean by $I/I^2$?
Answer: It is not very clear what you are asking, but there is a point about which one can get easily confused: The sheaf of differentials is not $I/I^2$, but $\Delta^* (I/I^2)$ - indeed, the first thing is a sheaf on $X \times X$, not on $X$ itself.
Note that this is necessary for anything to be well-defined: As you noted correctly, $\Delta$ is not necessarily a closed immersion. This means that the ideal sheaf $I$ is not a sheaf on $X$, but rather on some open neighborhood of the diagonal, which you have to choose - this is not reflected in the notation, because the resulting sheaves become isomorphic after pulling them back to $X$.
As a final remark, differentials are fundamentally a relative notion - everything in your post and my answer should be taken as relative to a map $f: X \to Y$.
Comment: Thank you for your answer.Actually i did not say that the sheaf of differentials is $I$/$I^2$.I said we use this and as you mentioned i exactly mean what you said the :pullback of $I$/$I^2$.If i want to be more clear i want to know that by the sheaf $I$/$I^2$ we mean we the sheafification of a pre-sheaf which assign to each open set $U$ the quotient $I$($U$)/$I^2$($U$)? i know my question is a little strange but i asked this because i dont know if $I^2$ itself is sheaf or no!we consider $I^2$ as a pre-sheaf then we do sheafification or no $I^2$ is itself a sheaf?
Comment: Ah, it was unclear to me what you asking. You certainly get the right answer if you sheafify at each step. Whether the presheaf defined by $U \mapsto (I(U))^2$ is already sheaf or not is an interesting question though, you might want to put this explicitly in your OP.
Comment: So you mean it is correct to consider  $I$/$I^2$ as pre-sheaf and then do sheafificatio?
Comment: Yes. Note that the 'associated sheaf' functor from modules to quasi-coherent sheaves is exact, so this sheafification changes nothing on affine opens, only on non-affine ones. This is what makes the comparison with the module of differentials in the ring world easy.

sheaf of differentials definition


How to setup IPv6 with docker-compose

Question: I am using Ubuntu 18.04 on DigitalOcean, with IPv6 turned on:
PUBLIC IPV6 ADDRESS:
xxxx:xxxx:2:d0::216f:3001
PUBLIC IPV6 GATEWAY:
xxxx:xxxx:2:d0::1
CONFIGURABLE ADDRESS RANGE:
xxxx:xxxx:2:d0::216f:3000 - xxxx:xxxx:2:d0::216f:300f

According to this page: https://docs.docker.com/v17.09/engine/userguide/networking/default_network/ipv6/#docker-ipv6-cluster
Is it correct to put the 16 IPv6 addresses like this?
{
  "ipv6": true,
  "fixed-cidr-v6": "xxxx:xxxx:2:d0::216f:3000/124"
}

Or, is it just fine to use these (as if something like 192.168.0.x)?
{
  "ipv6": true,
  "fixed-cidr-v6": "2001:db8::c008/125"
}

Anyway I have tried the first one.
docker run -d --name ipv6test alpine ash -c "ping6 2606:4700:4700::1111"

I "docker inspect" for the IPv6 address. I make the NDP record:
ip -6 neigh add proxy xxxx:xxxx:2:d0::216f:3004 dev eth0

In this case, the container could communicate with the outside world.
Testing finished. I want to apply IPv6 to my project. It starts with docker-compose.
According to this page: https://docs.docker.com/compose/compose-file/#ipv4_address-ipv6_address
version: "3.7"

services:
  app:
    image: nginx:alpine
    networks:
      app_net:
        ipv6_address: xxxx:xxxx:2:d0::216f:3010

networks:
  app_net:
    ipam:
      driver: default
      config:
        - subnet: "xxxx:xxxx:2:d0::216f:3000/124"

Inside the container, no connection could be made:
# ping6 2606:4700:4700::1111
PING 2606:4700:4700::1111 (2606:4700:4700::1111): 56 data bytes
ping6: sendto: Address not available

Have I missed anything?
Thanks.
Answer: Might be a little bit late, but this is the setup that worked for me on DigitalOcean:

Create /etc/docker/daemon.json:

{
    "ipv6": true,
    "fixed-cidr-v6": "<Your IPv6 address range start in DO console>/124"
}

sudo systemctl restart docker

Add to your docker-compose.yml:

    sysctls:
      - "net.ipv6.conf.all.disable_ipv6=0"

Basically it seems the default is to disable IPv6 and we need to enable it in sysctl.
EDIT: Actually this allows the docker container to obtain an IPv6 address and perform IPv6 name resolution, but somehow it cannot send data (Network unreachable).
Although docker containers started with docker directly, which runs on the default bridge network, is able to access external IPv6 hosts, docker containers started by docker-compose runs in its dedicated network, so maybe one will need more routing work. My use case was actually limited (socat as IPv4 to IPv6 proxy) so I simply resorted to using the host network directly, with:
    network_mode: host

Answer: My personal setup, that works.
It uses docker's internal default bridge instead of users supplied networking.

/etc/docker/daemon.json

{
    "ipv6": true,
    "fixed-cidr-v6": "2a02:168:7a0e:11::/64"
}

docker-compose.yml

version: '3.3'

services:
  shell:
    networks:
      - bridge
    image: centos:8

networks:
  bridge:
    external: true

Testing

docker-compose run --rm shell

In container

[root@dfeb2fe7917d /]# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
218917: eth0@if218918: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
    link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 2a02:168:7a0e:11:0:242:ac11:2/64 scope global nodad
       valid_lft forever preferred_lft forever
    inet6 fe80::42:acff:fe11:2/64 scope link
       valid_lft forever preferred_lft forever
[root@dfeb2fe7917d /]# ping6 -c 3 google.ch
PING google.ch(zrh04s15-in-x03.1e100.net (2a00:1450:400a:803::2003)) 56 data bytes
64 bytes from zrh04s15-in-x03.1e100.net (2a00:1450:400a:803::2003): icmp_seq=1 ttl=114 time=0.774 ms
64 bytes from zrh04s15-in-x03.1e100.net (2a00:1450:400a:803::2003): icmp_seq=2 ttl=114 time=1.12 ms
64 bytes from zrh04s15-in-x03.1e100.net (2a00:1450:400a:803::2003): icmp_seq=3 ttl=114 time=1.13 ms

--- google.ch ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 4ms
rtt min/avg/max/mdev = 0.774/1.008/1.128/0.165 ms

Answer: ipv6_address: xxxx:xxxx:2:d0::216f:3010
does not look like being in the same
subnet: xxxx:xxxx:2:d0::216f:3000/124
Try with something like xxxx:xxxx:2:d0::216f:300[0-f].

How to setup IPv6 with docker-compose


Is Silverlight the only option for WP7 App development?

Question: Is silverlight the only option for developing WP7 applications? What about Java? Or is there anything else that WP7 supports?
Comment: Microsoft and Java don't play nice.
Comment: See this question: https://stackoverflow.com/questions/4539876/is-it-possible-to-program-for-windows-phone-7-in-standard-c-only
Answer: You have these options (as of now):

C# (Silverlight / XNA)
VB.NET (Silverlight)
F# (Silverlight)

Ultimately, any CLI-based language can be used to build WP7 applications as long as it allows building WP7-specific assemblies (given the restrictions). Unoficially, it is known that there are native hooks and it is possible to use COM inside a WP7 app, but this is not yet a part of the public SDK and an application that implements a native layer that is not directly authorized by Microsoft will not even get through the approval process.
Comment: You can also code parts of your app in IronRuby if you want to - although there are some limitations to this (see http://www.iron7.com for some examples).
Comment: Additionally, you can code parts of your app UI in HTML with javascript - but this really doesn't seem to give a good user experience within Metro at present.
Comment: Pure example of a CLI-based language. As I said, theoretically it can be any language as long as it compiles to MSIL and abides WP7 assembly rules.
Answer: You can implement applications and games for WP7 using Silverlight (C# or Visual Basic (though VB not fully supported yet)) or XNA (C#) only at this time.
Comment: VB.Net is fully supported (since Nov 2010) but requires a separate download http://www.microsoft.com/downloads/en/details.aspx?FamilyID=4e97ea70-e479-4c05-814f-639d71690e5d


SAP HANA - Some services not started

Question: SAP HANA was configured correct and SAP HANA Studio was connected to SAP HANA.
From one day to another SAP HANA is not reachable in the SAP HANA Studio.
The operational state is "Some services not started"
How to fix this?
(I have an systems operation account on the HANA server)
Answer: I solved the issue by restarting SAP HANA
/usr/sap/hostctrl/exe/sapcontrol -nr 00 -function RestartSystem ALL

Comment: there is a nuclear option for every problem, right ;-)
Answer: Since restarting the whole database is not always an option, there is a better way:
1) check which service exactly is not running (e.g., in SAP HANA Studio, right click the system --> Configuration and Monitoring --> Open Administration; there in the 'Landscape' tab you are usually able to see which services are not running)
2) start missing services (starting them from the 'Landscape' tab usually does not work, so you could do it from console of your server):

go to the folder of your instance, e.g. /usr/sap/XDB/XDB01/
su - <xdb>adm (where <xdb>adm is the admin user of your instance)
start missing service, e.g. exe/hdbnameserver &

SAP HANA - Some services not started


node-imap module fetch gmail list folders(labels)

Question: I'm trying to fetch Gmail folders list(labels actually).
I'm using node js and this module : https://github.com/mscdex/node-imap
i want to fetch all folders and sub folders.
the documentation that the author left is not so bright.
any idea about this?
Comment: thank's.. Note: With in imap-simple create tree folder children is connection.addBox("parents.children")
Answer: finally after hard working i found the answer,
this is how i get folders not only for google even for every email system that use imap standards
after connection to imap server
the get all folders by this function.
function getFolders(username, callback) {

var folders = [];
if (Connection[username]) {

    Connection[username].once('ready', function() {

        Connection[username].getBoxes(function (err, boxes) {

            if (err) {

                // TODO : parse some error here

            } else {

                folders = imapNestedFolders(boxes);

            }

            return callback(err, folders);
        });
    });

} else {

    return framework.httpError(500, self);
}
}

the parse the folder to a pretty nested tree json object by this function
function imapNestedFolders(folders) {

var FOLDERS = [];
var folder  = {};

for (var key in folders) {

    if (folders[key].attribs.indexOf('\\HasChildren') > -1) {

        var children = imapNestedFolders(folders[key].children);

        folder = {
            name        : key,
            children    : children
        };

    } else {

        folder = {
            name        : key,
            children    : null
        };
    }

    FOLDERS.push(folder);

}
return FOLDERS;
}

you might also  change the connection variable to what you wanted.
these functions work with multiple connection because of this the connection  variable is an array you can read more about this here,
i wrote how to use multiple connection in node imap here
How can i handle multiple imap connections in node.js?


Make div to continue to new line not jumping to new line

Question: I have 3 divs, I want to keep those side by side but if the text inside each div goes long, break the text to a new line and keep the next div beside that.

this is a text

Will continue in next div

and this will be beside that

I want to show above divs like this (the second div should have underline)
this is a text that will continue
in next div and this will be beside
that

Comment: I'm not getting the output you describe. As expected, the elements are next to each other horizontally, not vertically. Please clarify what your expected result looks like.
Comment: @connexo Sorry, I edited my question to make it clear. That is what I want to get.
Comment: Now your description above the code and the expectation you state under the code contradict each other.
Answer: By default, a div element has a display attribute value of block which will place it on its own line in the document. If you want them to be side-by-side, you can set the value to inline or inline-block (if you want to set a width/height).

div {
  font-size: 4rem;
  display: inline;
}

#second {
  text-decoration: underline;
}

This text is in the first div element and

continues into the second div element and

finishes in the third div element.

If all you need the separate elements for is to underline the text in the second div, then I'd suggest you use a span instead to avoid the headache of removing styles from the divs and remembering to exclude them from any future CSS selectors.

div {
  font-size: 4rem;
}

.underline-me {
  text-decoration: underline;
}

This text is all in one div element even though this part is underlined so it will flow without needing to change the display property


Nagios: check if folder size increases by at least 1kb

Question: Is there a way to check the size of a folder increases by at least 1kb every hour? I can't seem to find any plug-ins that do this out of the box.
My Nagios experience is very little I'm afraid so I'll be needing some step by step instructions.
Answer: This is not easy to do, you will need to store measured sizes somewhere, to compare them later. Since Nagios does not have any detailed state data that can be sent to the plugin on next execution.
Alternatively you could use a graphing solution and monitor the changes, but not that easy as well...
Answer: A tool like monit allows you to do that. If you want, use nagios to check if monit is active. monit can send you a mail if something is amiss.
Answer: What I ended up doing was writing a small C# console app that does the necessary checks and saves the state in a text file. Then use Nagios to run that app every hour.


Chord naming. 6ths, 13ths. What's the difference

Question: Is the chord of the notes C E G Bb A, a C7th add 6th or is it a 13th? The main point of my question is do you need the 9th and the 11th to diffrentiate?
And is that critical? In other words are music exams on these points very precise?
Greetings
Comment: This question is probably worth checking out - https://music.stackexchange.com/questions/65532/when-a-major-6th-or-an-octave-thereof-is-in-a-chord-when-is-the-chord-symbol?rq=1
Comment: It's really the _seventh_ that will indicate extensions above the octave make sense. But this question is a dup that has already been answered.
Answer: Short answer: in a music theory exam question asking what notes there are in a chord named "C13", a C13 has the notes 1,3,5,(flat)7,9,11,13, i.e. C, E, G, Bb, D, F, A. In other words, C13 is "C11add13", C11 is "C9add11", and C9 is "C7add9".
However if the music exam asks how a C13 chord might actually be played in practice, then I'd say that the importance order of the notes when a C13 is written to be used as a dominant or blues chord is, from most important to least important: 7, 3, 13, 1, 9, 11, 5.
It's somewhat subjective, but I think most people would agree on at least leaving out the 5th.  The importance order (of which some people may disagree in some situations) comes from the role and use of the chord. There are basically two essential things that define a chord's harmonic function:

(1) is it a major or a minor (or sus4), and
(2) if it's a major chord, does it have a dominant seventh or not. (as opposed to major-7th or no seventh at all)

The 13 is a "dominant chord" and it must have a flat 7th. And it's a major chord and has to have a major 3rd. The same applies to a 9 chord, it must have a flat 7th. You can use a 13 chord or a 9 chord as a thicker and jazzier dominant-seventh chord. The 13th can be thought of as the same note as 6th, but the chord is not a 13 if there's no 7th. If there's only a 6th, then it's a 6 chord. If there's a 6th and a 9th but no 7th, then it's a "69" chord which is a thing in itself.
Why do I say the 1 i.e. the root of the chord is only fourth-most important note? It's because the root can often be implied or imagined because of other things, and it's not a so important as a harmony changer. And as a starting point here we have been given a 13 chord! Depending on the style of music you're doing, you might as well consider the root as the most important note. Maybe in some very basic pop you would use just roots instead, but then you would not have 13 chords either.
Here's some rootless blues where 13 chords are played with only the first three notes from my priority list. Root notes are left out deliberately to demonstrate what it sounds like if you leave out root notes from dominant/blues chords.

(Is it "roots" music if roots are left out?)
Comment: In my experience, there seems to be a strong split between the Jazz and Classical approach to a 13(th) chord.  Jazz would just about literally never include the natural 11, only #11.  Classical musicians are taught that it includes all the notes by default and some are excluded, either for consonance or technical ability.  Jazz musicians are taught that it's a 7 chord with a 13 and probably a 9.
Answer: In real life, anything above a 7th chord must contain that 7th note - be it a major, minor or even diminished seventh. (Augmented don't count here!)
So, a 9th chord will basically be 1,3,5,7 and 9. If not, it'll be an 'add9' chord.
However, when it comes to 11th and 13th chords, things can get very muddy. Let's face it - a C13 could contain C,D, E, F, G, A and B/B♭! Which may be possible to voice nicely in an orchestra or bigband, possibly on piano, impossible on guitar.
So things can and do get left out. An obvious is the 5 (unless it's +5 or -5), but that still leaves potential clashes of other notes. With 11th and 13th chords, it's best to listen carefully to what voicings will work in each circumstance - and omit notes accordingly.
11th chords often miss the 9th note (and/or 5th), and 13th chords can miss the 9th and 11th notes, without losing their recognisable sound.
As far as exams are concerned, sometimes they're more concerned with theory rather than practice, so are occasionally in a parallel universe (!) so here, it makes sense to actually ask the question to the board in question. They are by and large very helpful - and there are example test books which will give clues, too.
Comment: For a theory exam things aren't muddy: 7:1,3,5,7, and 9:1,3,5,7,9, 11:1,3,5,7,9,11, and 13:1,3,5,7,9,11,13. But if the exam asks, which of the notes are more important and which of them can be left out ... Then you might take the often used guitar "C13" fingering 8-x-8-9-10-x, which only has four notes in it, even though a C13 is supposed to have seven. :)
Answer: Usually C7 excludes a 6th, while C also can be played as C6.
C713 = C-E-G-Bb-A
while C13 contains the b7 but not necessarily  the 9th or 11th. If they have to be played it might be notated.
Mind that that there is always a melody played that may contain an additional note and that this chord assignments are abbreviations also for analysis and not only indicating what may be played. Let your ear decide and play your preferred version.
In a music exam it is up to you to be precisely and you better don't let come up some doubts about anything even if you are redundant. You can still make a parenthesis or a footmark.
Comment: Never come across C713!
Comment: Oh, this was a typo! I forgot the B between G and b.
Comment: I missed that! But still never heard of C713.
Comment: This is very usual in church hymns and romantic pieces. Just imagine a V7 with a suspended 6th (13) in the melody: so,ti,fa ... miredo.
Comment: I understand the concept, just never seen it written C713. I tend to play this with only 6th (13th)  and b7 along with the basic triad, but still call it C13. I think the 9th and 11th are optional - in fact need leaving out in the majority of cases.
Comment: I am wondering why there should be a difference between jazz and classical?  Theory is theory, otherwise surely it doesn't work. If I may be cynical, 2+2=4. Keep well everyone
Answer: Generally speaking, the difference between a 6 and a 13 chord has to do with whether or not there is a 7 in the chord.  Below are a few examples of chord symbols with the notes of the chord.
C6 - CEGA
C13 - CEGBbA (further thoughts on this below)
Cmaj7 (13) - CEGBA
C69 - CEGDA
Cmin6 - CEbGA
Cmin13 - CEbGBbA
Notice how the symbols that include a 13 always have a 7 in the chord and those that include a 6 never do.
Generally speaking, if you don't see the 7 specified in the chord symbol, it indicates that it is a dominant chord (such as the C13 above).  This would also be the case for a chord symbol of 9, where C9 would be a C7 with a 9 and Cadd9 would exclude the 7 and wouldn't explicitly imply dominant functionality.
There is some dispute about chord symbols such as C13, where many are taught that they generally include all the notes below the 13, including 9 and 11.  Outside of Classical music, it is incredibly rare to find a natural 11 in a 13 chord, though #11 is common in Jazz.  I've also found that there is a distinction between a 13 chord and a 13th chord, where 13 is a dominant chord and the quality of a 13th chord is determined by its context.  For example, if we're in C major and you see an A13th chord symbol, this would indicate that we are playing or hearing an A minor chord with natural 9, natural 11 and flat 13 (built from Aeolian).  Unless you're studying/playing Classical music, you should basically always assume that seeing a chord symbol of 13 means you're playing a dominant chord and you should either avoid 11 or it should be #11.
Comment: Can you point to a source where "A13" should be taken as a minor chord if the prevailing key happened to be C? I think chord symbols should always be absolute and not in any key at all. If you see a chord symbol, you should be able to use the same guitar chord grip, regardless of key.
Comment: @piiperi - To be clear, this is not what I generally see and really only seems to apply to Classical music.  I can't really recall where I learned that and haven't really found a corroborating source in my limited search just now.  Perhaps I am incorrect, as what I have found in my limited search seems to show that 13 is always dominant and anything else will be specified.


How to synchronize fingers/notes in piano chords

Question: I'm getting back into piano (background: trained in classical from age 4 to 14; finished RCM 7) and am having some trouble synchronizing my solid chords, particularly with sharps/flats using my pinky.
I've searched on some forums and youtube about this, but I've only found info on basic fingering or syncing left and right hands.
Would anyone have tips on how to train or think about (strategically/philosophically) to improve this? (I've been also training with Hanons, though I've gathered from forums that Czerny may be better...?)

Are you having trouble making your solid chords not sound like they're being arpeggiated (slightly broken up)?

Yes, whenever I use my pinky on a black key, it tends to play before the rest of the chords. to be specific, I'm working on Chopin's prelude 4; it's most obvious in the first progression from G-B-E to F#-A-E
I can feel that my left pinky is still quite weak (pinky before or after the rest of the chord), but I've generally had trouble with (if not) syncing then over-voicing black keys. probably to do with lengths of fingers and how black keys are raised.
Comment: I can't pin down exactly what the problem is, can you make it more clear please?
Comment: See also [I'm having trouble hitting all keys of a chord together. Are there any methods that can help me learn that?](https://music.stackexchange.com/q/109435/70803), which addresses the problem more generally.
Answer: Maybe you can try doing some finger exercises? That might help.
https://pianowithjonny.com/piano-lessons/5-essential-piano-exercises
https://takelessons.com/blog/piano-finger-exercises-speed-z06
Pianote also has some finger exercises.
Comment: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/71459)
Answer: It's unlikely that your pinky is weak. If you can hold a glass of water, your pinky is plenty strong for playing the piano.
Pinkies often feel weak, but this is usually because our hands and fingers aren't being used efficiently, and likely there is unnoticed tension in your hand or arm.
To practicing synchronizing the notes in a chord:

touch your fingertips to the surface of the keys in the chord, and allow your other fingertips to rest on the keyboard wherever they're comfortable.
Relax all of your fingers as well as your palm, wrist, and arm so that there is slight pressure on your chord-note fingertips, but the keys don't start to go down. Your non-chord fingertips should remain in gentle contact with the keyboard.

This is the starting place for playing a chord (i.e., not dropping onto the keys from above the keyboard).

Press your palm gently downward, relaxing your arm so that it follows along. The fingers that play the chord will maintain their shape from step 2; the other fingers remain relaxed so as not to inadvertently press other keys.

Step 2 requires that all of your fingers are at the same starting height, regardless their relative lengths. By pressing with the palm, the fingers stay in that alignment. If instead one "plays with just the fingers", then the fingers are free to misalign themselves.


Array formula and MAX

Question: I'm trying to get peak/max equity from two columns A & B with an array formula. The reason I use the array formula is because I don't want just MAX as an answer in one cell. I want it to update automatically row after row with each new entry without overwriting previous entry. So far I got to this formula, but it gives me the same result in each row.
=ArrayFormula(if(AD3:AD="","",MAX("<="&row(AD3:AD),AD3:AD,AB2)))

And for clarification I would like it to look something like this:
  AB       AD
PEAK     CLOSED
Equity   Equity
 $1195    $1195
 $1195    $1090
 $1285    $1285
 $1285    $1180
 $1315    $1315
 $1315    $1210
 $1315    $1205

And now with the above formula ( it's in AB3 ) I get just MAX in each row, starting with row AB3 which is $1315.
It can also just give me MAX for column AD, just so it updates  on each new row and entry. And here's sample sheet.
sample doc
Thank you.
Answer: =ARRAYFORMULA(IF(A2:A>=B2:B, A2:A, B2:B))

Comment: Thank you for your help, but this just gives me bigger number of the 2 columns in each row. I updated my question with better example and sample doc.

Array formula and MAX


Amazon EC2 root defaults on EBS

Question: I'm trying to understand why when launching a new instance Amazon defaults to EBS (8gb root) instead of instance storage. Why do they sell instance storage then if it's not used also to boot the base system?
Is it safe to uncheck delete on termination, make it bigger (~50GiB) and keep all files on that EBS instead of creating a new one to make sure data will persist and it will also be usable by another instance?
Comment: possible duplicate of [EC2 drive not EBS volume size](http://serverfault.com/questions/414983/ec2-drive-not-ebs-volume-size)
Comment: @MichaelHampton sorry but I don't see them to be the same question. I'm asking if it's a valid option to keep data under a bigger root EBS partition, instead of creating/attaching/mounting a second EBS for this data.
Answer: EBS storage is persistent, the data will be kept even if you shutdown/terminate the instance. The local storage is not and the data is only kept whilst the instance is alive.
If you want to keep the data stored on EBS after the instance is terminated you should uncheck Delete on termination.
It is safe to change the size of an EBS, I believe it must be shutdown to make the change.
You can attach and detach an EBS drive from instances, so yes, you can move it between instances but it can only be attached to 1 instance at a time.
Comment: Thanks, so instead of creating a second EBS needing to mount it and move webserver/db files over the mounted partition, can I simply increase the root size and install it like I do on my phisical server without worrying about losing the data? Is it safe to do this or is it better to just keep webserver and db data on another EBS partition?
Comment: @CodeShining Have a look at this http://www.jonlloyd.co.uk/resize-ebs-volume-ec2/
Answer: I think the main question is that you have too few space on your EBS drive available. There are two ways to resolve this:
You can change the size of your root disk (provided it is an EBS backed instance) as described here:
http://alestic.com/2010/02/ec2-resize-running-ebs-root
I would suggest to test this on a throw-away instance first however...
The best (and easier) option is to give the desired space on instance launch - see the --block-device parameter on the launch call:
http://docs.amazonwebservices.com/AWSEC2/latest/CommandLineReference/ApiReference-cmd-RunInstances.html
Comment: If it's an identical question then use a comment to link and flag/vote as identical. If it's a different question then just tweak the answer text a bit and it shouldn't get picked up automagically.
Comment: Posting identical answers to multiple questions gets you noticed by the system really quickly as that's typical spambot activity.
Comment: Thanks Iain - what is the preferred way to deal with these cases? Linking to the other posting or commenting with "possible duplicate" (although the question is different, but same answer applies here)?

Amazon EC2 root defaults on EBS


Existe diferença entre usar barra invertida e simples?

Question: Quero saber se quando se trata de fazer upload de um arquivo, tipo assim:
$destino = 'imagens/' . $novoNome;

Existe diferença entre imagens/ e imagens\?
Answer: Depende do contexto. Se for para uso como separador de diretórios o PHP abstrai isto e usa o que for mais adequado para a plataforma que está rodando. Não quer dizer que sempre funcionará como o esperado, mas em geral é assim. Costuma-se preferir usar a barra normal e não a invertida. Há quem prefira usar DIRECTORY_SEPARATOR ou até mesmo criar funções para abstrair o uso de paths.
Se for apenas uma string normal faz muita diferença em alguns casos. A barra normal é só uma barra, a barra invertida é um indicar que o próximo caractere é especial, então um \n é pular uma linha, \t é uma tabulação ou \\ é quando deseja que a barra invertida seja usada como caractere normal. Mas isto depende se está usando aspas simples ou dupla, no caso da simples usada a única vez que a invertida faz algo diferente é quando usa \' para indicar que não está encerrando a string e sim quer que um apóstrofe seja usado.
Coloquei no GitHub para referência futura.