PhantomJS can't read any tag in body on Nightwatch and Vue.js

Question: I'd like to UI test with Nightwatch for my Vue.js project.
I wanna use PhantomeJS for CI.
But PhantomeJS seems to read no element under body tag.
How do you assert any element with PhantomJS?
I caught this error:
√ Element  was visible after 47 milliseconds.
√ Testing if the page title equals "frontend".
× Testing if element
 contains text: "section 1". Element could not be located.  - expected "section 1" but got: "null"

My test source:
module.exports = {
  'toppage': browser => {
    browser
      .url(browser.launchUrl)
      // .assert.containsText('body', 'dummy')
      .waitForElementVisible('body', 1000)
      .assert.title('frontend')
      .assert.containsText('h2', 'section 1')
      .end()
  },

Then I confirmed body innerHTML was "".
Testing if element  contains text: "dummy".  - expected "dummy" but got: ""

nightwatch.config.js:
  desiredCapabilities: {
    // TODO chrome can cover these tests
    // browserName: 'chrome',
    // javascriptEnabled: true,
    // acceptSslCerts: true,
    // TODO but phantomJS can't
    browserName: 'phantomjs',
    javascriptEnabled: true,
    acceptSslCerts: true,
    'phantomjs.binary.path': 'node_modules/webdriver-manager/selenium/phantomjs.exe',
    'phantomjs.cli.args': ['--ignore-ssl-errors=true'],
  },

In case of Chrome, my test source run well.
versions:
nightwatch 0.9.20
webdriver-manager 12.0.6
selenium-server-standalone-2.53.1.jar
phantomjs.exe 2.1.1
//////// added Mar.29 2018 ////////
I tried text.to.equal.
new test source:
  toppage: browser => {
    browser
      .url(browser.launchUrl)
      .waitForElementVisible('body', 1000)
      .expect.element('h2')
      .text.to.equal('section 1')
    // .assert.title('frontend') // TypeError: browser.url(...).expect.element(...).text.to.equal(...).assert.title is not a function
    // .containsText('h2', 'section 1') // TypeError: browser.url(...).expect.element(...).text.to.equal(...).containsText is not a function
    // .end() // TypeError: browser.url(...).waitForElementVisible(...).expect.element(...).text.to.equal(...).end is not a function
  },

new error message:
 √ Element  was visible after 46 milliseconds.
 × Expected element
 text to equal: "section 1" - element was not found  - expected "present" but got: "not present"

Answer: While you invoke an url as url(browser.launchUrl) the Web Client requires a certain amount of time to render the WebElements within the HTML DOM. Hence you need to induce wait in the form of expect-api preferably an expect-attribute with respect to the attribute .text as follows :
browser.expect.element('#element_id').text.to.equal('dummy');

Next you can perform the Assertion as assert.containsText('body', 'dummy')
Comment: Thnx DebanjanB. It doesn't resolve it. I also add  .waitForElementVisible('h2', 60000) before .assert.containsText('h2'... It, too.
Comment: @isexxx `waitForElementVisible` won't suffice to your requirement. You need a waiter for the **text to be present**.
Comment: I get the message: Expected element  text to equal: "section 1" - element was not found  - expected "present" but got: "not present" via browser.url(browser.launchUrl).expect.element('h2').text.to.equal('section 1') . browser.url(browser.launchUrl).expect.element('h2').to.be.present, too.
Comment: @isexxx Seems you are pretty closer now. can you update the question with your current code block & the error where you see the error and error log please?
Comment: I added new source and message. please refer to // added Mar.29 2018 //


Mixin and interface implementation

Question: According to http://www.thinkbottomup.com.au/site/blog/C%20%20_Mixins_-_Reuse_through_inheritance_is_good

But hang on a minute, none of this helps us plug into our Task
  Manager framework as the classes do not implement the ITask interface.
  This is where one final Mixin helps - a Mixin which introduces the
  ITask interface into the inheritance hierarchy, acting as an adapter
  between some type T and the ITask interface:
template< class T >
class TaskAdapter : public ITask, public T
{
public:
    virtual void Execute()
    {
        T::Execute();
    }

    virtual std::string GetName()
    {
        return T::GetName();
    }
};

Using the TaskAdapter is simple - it's just another link in the chain
  of mixins.
// typedef for our final class, inlcuding the TaskAdapter<> mixin
typedef public TaskAdapter<
                    LoggingTask<
                        TimingTask<
                            MyTask > > > task;

// instance of our task - note that we are not forced into any heap allocations!
task t;

// implicit conversion to ITask* thanks to the TaskAdapter<>
ITask* it = &t;
it->Execute();

Why is TaskAdapter needed, when ITask is implemented by MyTask? Also if ITask is not abstract, it may lead to diamond problem.
Answer: That's a very cool and interesting article.
In the final Mixin example, the MyTask class is not derived from ITask.  Which means it can't be cast to an ITask pointer which is being done at the very end.
In that example, I believe you could derive MyTask from ITask.  But I think the author wanted to illustrate that you can even decouple the MyTask class by using the TaskAdapter.
Comment: Hey! I wrote that article and stumbled across this post accidentally.  Your comments are spot on - I wanted to demonstrate that run-time polymorphism was an opt-in concept and that you can add it when needed with a reusable mixin.

Mixins are awesome.
Comment: ah, I missed that `MyTask` was not derived from `ITask`. Thanks!

Mixin and interface implementation


onchange Select não funciona - jQuery

Question: Olá pessoal estou fazendo o onchange na tag select mas não esta funcionando, estou usando o plugin JS do Google para cidades e estados, exemplo:
JSFIDDLE: http://jsfiddle.net/fn7c57ag/1/
Comment: Você quer que execute a função de popular a cidade mas também execute sua função?
Comment: Aqui está funcionando Chrome47
Answer: o seu script cidadesEstados.js está setando o evento .onchange() no seguinte trecho:
this.estado.onchange=function(){this.dgCidadesEstados.run()};

com isto o que você definiu no HTML é sobrescrito, então te aconselho a usar um eventListener:

var model = {};
document.addEventListener("readystatechange", function () {
  if (document.readyState == "interactive") {
    model = {
      estado: document.getElementById('estado'),
      cidade: document.getElementById('cidade'),
      change: true
    };
    new dgCidadesEstados(model);

    //preste atenção no addEventListener;
    model.estado.addEventListener("change", myfunction);
  }
});

var myfunction = function (event) {
  alert(event);
}

Estado
<input id="estado" name="estado">
Cidade
<input id="cidade" name="cidade">

desta forma você poderá ter mais de um evento ocorrendo no change do select estado.
também aconselho que modifique o cidadesEstados.js para usar um eventListener sempre que possível:
this.estado.addEventListener("change", function(event) {
    this.dgCidadesEstados.run()
};

Comment: Obrigado @Toby, deu certo
Answer: Tente adicionar o change com jquery:
$(document).ready(function(){
   $("#estado").change(function(){
      alert(123);
   });
});
Answer: O evento .onchange está funcionando corretamente.
Ele está sendo atribuído na linha 91 do arquivo cidadesEstados.js
this.estado.onchange= function() { this.dgCidadesEstados.run() };

No HTML você tenta atribuir a função myfunction()" no evento onchange, só é possível adicionar uma função por evento (mas você pode chamar várias funções dentro de uma). Se você quer deixar a sua função no onchange, recomendo refatorar o código e criar um select pois não existe o evento onchange em campo de texto.

onchange Select não funciona - jQuery


Prevent knockout from calling subscribe when the observable is set

Question: I have two inputs that are binded to their own observable. Both have a subscribe function that starts an ajax call. There are some other fields that will be filled out from the ajax result. I want to be able to get data when the companyName is typed. I also want to get the companyName (and more) when the cardNumber is typed, but giving companyName a value will trigger its subscibe function which will start another ajax call. I want to prevent this from happening.
cardNumber = ko.observable();
companyName = ko.observable();

cardNumber.subscribe(function () {
        getDataFromCardNumber(cardNumber());
});
companyName.subscribe(function () {
        getDataFromCompanyName(companyName());
});

getDataFromCardNumber = function (cardNr) {
    $.ajax({
        type: 'GET',
        data: { number: cardNr },
        url: '/Home/GetCardInfo',
        success: function (data) {
           companyName(data.Company.CompanyName);
           //some other fields
        }
    });
};
//getDataFromCompanyName(name) contains another ajax call to fill out some other fields aswell

Answer: I see two options:

You could dispose the subscription before writing from the callback, and then re-attach it when the new value is set.

const obsA = ko.observable("a");
const obsB = ko.observable("b");

const updateA = newVal => setTimeout(
  () => {
    subA.dispose();
    obsA("reset by B");
    subA = obsA.subscribe(updateB);
  }, 500);

const updateB = newVal => setTimeout(
  () => {
    subB.dispose();
    obsB("reset by A");
    subB = obsB.subscribe(updateA);
  }, 500);

let subA = obsA.subscribe(updateB);
let subB = obsB.subscribe(updateA);

ko.applyBindings({ obsA, obsB });

A: <input data-bind="value: obsA" />
B: <input data-bind="value: obsB" />

You can create separate UI observables that call updates in their write logic:

const obsA = ko.observable("a");
const obsB = ko.observable("b");

const uiObsA = ko.computed({
  read: obsA,
  write: val => {
    obsA(val);
    updateB();
  }
});

const uiObsB = ko.computed({
  read: obsB,
  write: val => {
    obsB(val);
    updateA();
  }
});

const updateB = newVal => setTimeout(
  () => obsB("reset by A"), 500);

const updateA = newVal => setTimeout(
  () => obsA("reset by B"), 500);

ko.applyBindings({ obsA, obsB });

A: <input data-bind="value: uiObsA" />
B: <input data-bind="value: uiObsB" />
Comment: The writeable computed functions is what I was looking for. This helped me solve my problem :)
Answer: You could always just check to see if a card number or company name exists already before you call the ajax request.
cardNumber.subscribe(function () {
    if (!companyName()){
       getDataFromCardNumber(cardNumber());
    }
});

companyName.subscribe(function () {
    if (!cardNumber()){
        getDataFromCompanyName(companyName());
    }
});


Eclipse Subversive commit changelist?

Question: I just created an ignore-on-commit changelist as described in SVN: Is there a way to mark a file as "do not commit"? and it's awesome on the command line, making it much easier to view the changes I care about in the command line.
Having all this power and organization now I select all my projects in eclipse and go to Team > Commit and there is no notion of changelists in the commit dialog and I still have to go through all the changes and tediously select which files to commit.
Am I missing something in Eclipse' Subversive that would allow me to use changelists in the commit dialog?
I found the following setting, but it doesn't seem to change anything...
Comment: Extremely interested to know how to get ignore-on-commit to work in Eclipse as well, using Subversive.
Comment: Obviously I've had no answer yet.  Because of that I'm doing most of my svn through command line these days.
Answer: I see two possibilities here:
1. Using svn:ignore
The easiest solution would be to add the files you don't want to commit to your svn:ignore list.
You can do it in Subversive through the Team>Add to svn:ignore... menu:

2. Using change sets
The alternative is to :

go in the Synchronize view
click the Show Change Sets button
you can then add changed files to change sets (and create new change sets) from the right-click menu.

You can find more information in the Subversive documentation.
Comment: Wouldn't adding to svn:ignore require it to be checked in with the svn:ignore property set in order for it to take effect?  If so, that pretty much defeats the purpose.  I might have a look at the change sets.  Does that mean it uses its own change set mechanism instead of the one built in to svn?
Comment: Concerning `svn:ignore` you're right, but it could be an option if your are working on your own branch. You may consider using `global-ignores` also... For Subversive's Change sets, I don't know how they are handled internally, but I've seen them be used this way in the past...
Comment: Since the files I do not want to commit have changes local to my machine, but are still under source control, adding to svn:ignore isn't going to do my any good.  The changesets in the plugin are interesting, it's sad they don't appear to integrate with the svn built-in change lists.

Eclipse Subversive commit changelist?


Is there a way to completely flush cached AD credentials on a user workstation?

Question: An AD user updated their AD password, but a couple applications on their workstation appear to still be using their old AD credentials.  Is there an easy way to flush out cached AD credentials on Windows (short of logging out or rebooting)?
A few google searches hinted at "gpupdate /force" but I wasn't sure if that would encompass stuff like NTLM credentials and AD passwords.
Answer: You'd be looking for the "Credential Manager" which can really only be run locally:
You can start it from the command line:
<code>control userpasswords2
</code>
Then go to the second tab (Advanced) then select "Manage Passwords", this will let you modify saved network passwords for the current user on that computer.
Comment: If the user is not an administrator they will not be able to access this; and unable to clear their stored passwords.


How to know which is a suitable octave?

Question: Given a piano music sheet, is there any way to know which (suitable) octave should I start, or I just pick up any as long as it fits all notes?
Sorry if this is a dumb question! Thanks
Answer: Standard sheet music specifies the octaves quite precisely.  The lowest line in the treble clef, for example, is E4 (the E in the fourth octave):

Ledger lines can also be added above and below the staves to extend their range, and you might sometimes see 8va written above or below certain notes to indicate that they should be played an octave higher or lower.
Comment: Thanks! The link does help. Especially this [picture](https://en.wikipedia.org/wiki/Octave#/media/File:Common_Octave_Naming_Systems.png)
Comment: Also, in some music, an 8 is written at the beginning. Above the clef for an octave higher, below for an octave lower. Sometimes written as 8vb. Guitar music should be written as such, because guitars play an octave lower than the written pitch.
Answer: Generally, the pitch is fixed.  However, if you are playing music for other instruments, there may be some justification for adjusting pitches.  For example, guitar is usually written one octave higher than it is played (when written correctly, an 8 below the clef indicates the shift).  However, its bass notes tend to have an "unmuddier" sound than that of the piano, so there is some sense in playing it as if it were not written transposed.
Similarly, a soprano recorder (flute) tends to be written one octave lower than it is actually played (with tenor recorders (flutes) being written in-pitch if I remember correctly).  Again, the sound quality of the piano may make it advisable to play the music as if it were not written transposed.
Music written for piano, however, is always to be played at pitch.  The "middle C" C4 between treble and bass clef is pretty much in the middle for pianos.  If your piano has a lock, it will be rather close to middle C.
Comment: I think you mean "recorder" for "flute" here- are you German?  Cheers aus sonnigem Wien, Scott

How to know which is a suitable octave?


CSS não funcionando no meu HTML

Question: O meu background feito em CSS, simplesmente, não está funcionando no meu HTML. A ideia era ter um background preto atrás do logo "World". Mas não está aparecendo. Já tentei ver se o problema era a cor. Até mudei ela, mas também não mudou nada. Também mudei a pasta onde está o arquivo HTML e CSS e também não consegui. O que há de errado com o meu código?
logotipo

.header-1 {
    background-color:#252323;
}

   <link rel="stylesheet" href="styles.css">
   <Title> Primeiro Projeto </Title>

Comment: Como disse que a resposta do Jonas Lima não o atende está difícil de entender o que quer. Veja se é isso, no css troque `.header-1 { background-color:#252323;}` por `header { background-color:#252323;}`
Comment: Também de uma conferida no caminho passado em `` e o caminho do css.
Answer: Você está fechando a div na linha onde se encontra sua classe 'header-1'. Para aplicar esse style, você deve manter os elementos filhos dentro da div onde está a class.
Ficando da seguinte forma

.header-1 {
    background-color:#252323;
}

   <link rel="stylesheet" href="styles.css">
   <Title> Primeiro Projeto </Title>

Comment: O problema continua :/. Copiei e colei o seu código e não funcionou. Executei em outro browser e também naõ foi.
Comment: Verifique o caminho do seu arquivo css
Answer: A div header-1 estava fechando na mesma linha e dentro dela não tinha conteúdo algum.
basta fechar a div após o fechando da div logo.
Espero ter ajudado! ;)

.header-1 {
    background-color:#252323;
}

   <link rel="stylesheet" href="styles.css">
   <Title> Primeiro Projeto </Title>

Answer: Tente checar o caminho do arquivo style.css se está correto.
Uma "solução temporária e rápida" até que consiga corrigir esse problema seria codar seu CSS dentro do HTML segue o exemplo abaixo:

   <Title> Primeiro Projeto </Title>

Answer: Parece que você está tentando adicionar uma cor de fundo ao elemento "div" com a classe "header-1", mas ela não está aparecendo no seu HTML. Alguns possíveis problemas que podem estar causando esse comportamento incluem:

Verifique se você está chamando o arquivo CSS corretamente no HTML. Certifique-se de que o caminho para o arquivo CSS está correto e que o arquivo CSS realmente existe na pasta especificada.

Verifique se você está aplicando a classe "header-1" corretamente no elemento "div". Certifique-se de que a classe está escrita corretamente e que está sendo aplicada ao elemento "div" correto.

Verifique se o seu código CSS está sendo escrito corretamente. Certifique-se de que você está usando o seletor correto para o elemento "div" e que a sintaxe do código CSS está correta.

Verifique se o seu navegador está atualizado. Às vezes, problemas de visualização podem ser causados por problemas de compatibilidade com navegadores mais antigos.

Se você verificou todos esses itens e ainda está tendo problemas, tente adicionar um "height" e um "width" ao seu elemento "div" para garantir que ele tenha dimensões visíveis. Isso pode ajudar a mostrar o fundo na tela.
.header-1 {
background-color:#252323;
height: 100px;
width: 100%;

}
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).
Answer: As vezes acontece comigo e o problema está no cache do navegador, tenta ir nas configurações e limpar os dados de navegação.

CSS não funcionando no meu HTML