<commit_before>const got = require('got');
const request = require('request');
const Buffer = require('Buffer');

const crypto = require('crypto');
const companyCode = 88801;
const Oauth = require('client-oauth2');
const cID = '268b2069-b099-4fa2-8148-1f1c0327fe63';
const cS = 'b383c35d-3c11-4ce6-b631-8767f4c2084b';
const aK = '0dfb11cd-b140-40cd-b65a-220e9998a129';
const aS = '199505e4-9d5f-4ba9-bb96-a3ea8b2f69c1';

const auth = new Oauth({
  clientId: cID,
  clientSecret: cS,
  accessTokenUri: 'https://api.finhacks.id/api/oauth/token',
});

function getAccessToken () {

  let header = {
    Authorization: 'Basic ' + new Buffer(cID + ':' + cS).toString('base64'),
    'Content-Type': 'application/x-www-form-urlencoded'
  };

  let body = new Buffer([{ grant_type: 'client_credentials' }]);
  let options = {
    method: 'POST',
    url: 'https://api.finhacks.id/api/oauth/token',
    headers: header,
    body: body
  };

  got('https://api.finhacks.id/api/oauth/token', options)
	.then(response => {
		console.log(response);
		//=> '<!doctype html> ...'
	})
	.catch(error => {
		console.log(error);
		//=> 'Internal server error ...'
	});

}
// function gat () {
//   return auth.credentials.getToken()
//     .then(function(response){
//       return response;
//     })
// }
// function getAccessToken () {
//   return auth.credentials.getToken();
// }

function createHeader (data, body){
  let method = 'post'.toUpperCase();
  let url = encodeURI('/ewallet/customers');
  let accessToken = data.accessToken;
  let bd = crypto.createHash('SHA-256', body);
  bd = bd.toLowerCase();

  let dt = new Date();
  dt = dt.toISOString();

  let str = method + ':' + url + ':' + accessToken + ':' + bd + ':' + dt;

  let hash = crypto.createHmac('SHA_256', aS, str);

  var header = {
    'Authorization' : 'Bearer '+accessToken,
    'X-BCA-Key' : aK,
    'X-BCA-Signature' : hash,
    'X-BCA-Timestamp' : dT
  }

    return header;
}

function registerUser (req) {
  let body = {};

  body.CustomerName = req.customer_name;
  body.DateOfBirth = req.birth_date;
  body.PrimaryID = req.primary_id;
  body.MobileNumber = req.mobile_number;
  body.EmailAddress = req.email_address;
  body.IDNumber = req.id_number;
  body.CompanyCode = companyCode;
  let header = {};

  getAccessToken()
    .then(function (response) {
      header = createHeader(response, body);
    });
}

module.exports = {
  getAccessToken,
};
<commit_msg>try access token<commit_after>const got = require('got');
const request = require('request');
const Buffer = require('Buffer');

const crypto = require('crypto');
const companyCode = 88801;
const Oauth = require('client-oauth2');
const cID = '268b2069-b099-4fa2-8148-1f1c0327fe63';
const cS = 'b383c35d-3c11-4ce6-b631-8767f4c2084b';
const aK = '0dfb11cd-b140-40cd-b65a-220e9998a129';
const aS = '199505e4-9d5f-4ba9-bb96-a3ea8b2f69c1';

const auth = new Oauth({
  clientId: cID,
  clientSecret: cS,
  accessTokenUri: 'https://api.finhacks.id/api/oauth/token',
});

function getAccessToken () {

  let header = {
    Authorization: 'Basic ' + new Buffer(cID + ':' + cS).toString('base64'),
    'Content-Type': 'application/x-www-form-urlencoded',
  };

  let body = { grant_type: 'client_credentials' };
  let options = {
    method: 'POST',
    url: 'https://api.finhacks.id/api/oauth/token',
    headers: header,
  };
  request.post(options).form(body)
    .on('response', function(response) {
      console.log(response);
    })
    .on('error', function(error) {
      console.log(error);
    });
}
// function gat () {
//   return auth.credentials.getToken()
//     .then(function(response){
//       return response;
//     })
// }
// function getAccessToken () {
//   return auth.credentials.getToken();
// }

function createHeader (data, body){
  let method = 'post'.toUpperCase();
  let url = encodeURI('/ewallet/customers');
  let accessToken = data.accessToken;
  let bd = crypto.createHash('SHA-256', body);
  bd = bd.toLowerCase();

  let dt = new Date();
  dt = dt.toISOString();

  let str = method + ':' + url + ':' + accessToken + ':' + bd + ':' + dt;

  let hash = crypto.createHmac('SHA_256', aS, str);

  var header = {
    'Authorization' : 'Bearer '+accessToken,
    'X-BCA-Key' : aK,
    'X-BCA-Signature' : hash,
    'X-BCA-Timestamp' : dT
  }

    return header;
}

function registerUser (req) {
  let body = {};

  body.CustomerName = req.customer_name;
  body.DateOfBirth = req.birth_date;
  body.PrimaryID = req.primary_id;
  body.MobileNumber = req.mobile_number;
  body.EmailAddress = req.email_address;
  body.IDNumber = req.id_number;
  body.CompanyCode = companyCode;
  let header = {};

  getAccessToken()
    .then(function (response) {
      header = createHeader(response, body);
    });
}

module.exports = {
  getAccessToken,
};
<|endoftext|>


<commit_before>{"1":{"department":"ESF","number":"1","title":"Education as Self-Fashioning: The Active, Inquiring, Beautiful Life","description":"Moving through history from the Rome of the Emperor Hadrian, to the city-states of Renaissance Italy, to the 18th century republic of the United States, we will examine how self-made men fashioned themselves and their surroundings by educating themselves broadly.  We will ask how a liberal education made their active careers richer and more transformational. We will also take up the great debate on whether a liberal education or vocational training is the surest path to advancement.  We will engage this debate through the works of W.E.B. Du Bois and Booker T. Washington but consider today's struggle over the same issues ¿ a struggle that engrosses both highly industrialized and developing societies.","min_units":7,"max_units":7,"gers":["WAY-ER","Writing 1"],"id":214530,"primary":[[{"instructors":[],"meeting-times":[{"days":[false,false,true,false,false],"start":"2:15:00 PM","end":"3:30:00 PM","location":"160-326"}],"id":38320}],[],[]],"primary_type":"Seminar","secondary":[[{"instructors":[],"meeting-times":[{"days":[false,true,false,true,false],"start":"11:00:00 AM","end":"12:50:00 PM","location":"60-119"}],"id":56901},{"instructors":[],"meeting-times":[{"days":[false,true,false,true,false],"start":"3:15:00 PM","end":"5:05:00 PM","location":"160-330"}],"id":56900}],[],[]],"secondary_type":"Discussion"},
"1A":{"department":"ESF","number":"1A","title":"Education as Self-Fashioning: The Active, Inquiring, Beautiful Life","description":"Moving through history from the Rome of the Emperor Hadrian, to the city-states of Renaissance Italy, to the 18th century republic of the United States, we will examine how self-made men fashioned themselves and their surroundings by educating themselves broadly.  We will ask how a liberal education made their active careers richer and more transformational. We will also take up the great debate on whether a liberal education or vocational training is the surest path to advancement.  We will engage this debate through the works of W.E.B. Du Bois and Booker T. Washington but consider today's struggle over the same issues ¿ a struggle that engrosses both highly industrialized and developing societies.","min_units":7,"max_units":7,"gers":["WAY-ER","Writing 1"],"id":214531,"primary":[[{"instructors":[],"meeting-times":[{"days":[false,false,true,false,false],"start":"4:15:00 PM","end":"5:30:00 PM","location":"160-326"}],"id":38321}],[],[]],"primary_type":"Seminar","secondary":[[{"instructors":[],"meeting-times":[{"days":[false,true,false,true,false],"start":"3:15:00 PM","end":"5:05:00 PM","location":""}],"id":56902},{"instructors":[],"meeting-times":[{"days":[false,true,false,true,false],"start":"11:00:00 AM","end":"12:50:00 PM","location":""}],"id":56903}],[],[]],"secondary_type":"Discussion"},
"2":{"department":"ESF","number":"2","title":"Education as Self-Fashioning: The German Tradition of Bildung or How to Become a Global Citizen","description":"This course considers education not as training in external knowledge or skills but as a lifelong process of development and growth in which an individual cultivates her or his spiritual, cultural and social sensibilities. This concept of education¿education as a formative and transformative process in the development of the self¿is called Bildung in German and has a long tradition reaching back to the Middle Ages. The term first appears in the writings of the mystic Meister Eckhart who defines it as self-composure which he regards as a crucial stage in our spiritual development. The concept of Bildung takes on a secular meaning in the Reformation, when Ulrich von Hutten first coined the phrase that has become Stanford¿s motto: ¿Die Luft der Freiheit weht¿ (The wind of freedom is blowing.¿). What he meant is that the cultivation of oneself leads to the freedom of thought, freedom to act, freedom to assert oneself as an individual, freedom to access knowledge, and freedom to determine one¿s own role in society. This idea of education as an internal and transformative process is central to debates in the nineteenth century¿both in Germany and the United States¿in which self-reflection is seen as key to the cultivation of an individual¿s identity and to her or his role as a member of society. In this course we will read reflections on education as self-fashioning by some of the greatest German thinkers spanning from the Middle Ages to the present. We will also enjoy some contemporary parodies of such reflections. These readings and our discussions will help us to understand Stanford undergraduate education as a transformative process of self-realization in our global society.","min_units":7,"max_units":7,"gers":["WAY-A-II","Writing 1"],"id":214532,"primary":[[{"instructors":[],"meeting-times":[{"days":[false,false,false,true,false],"start":"11:30:00 AM","end":"12:45:00 PM","location":"260-244"}],"id":38322}],[],[]],"primary_type":"Seminar","secondary":[[{"instructors":[],"meeting-times":[{"days":[true,false,true,false,false],"start":"11:00:00 AM","end":"12:50:00 PM","location":""}],"id":56904},{"instructors":[],"meeting-times":[{"days":[false,true,false,true,false],"start":"9:00:00 AM","end":"10:50:00 AM","location":"Meyer 142"}],"id":56905}],[],[]],"secondary_type":"Discussion"},
"2A":{"department":"ESF","number":"2A","title":"Education as Self-Fashioning: The German Tradition of Bildung or How to Become a Global Citizen","description":"This course considers education not as training in external knowledge or skills but as a lifelong process of development and growth in which an individual cultivates her or his spiritual, cultural and social sensibilities. This concept of education¿education as a formative and transformative process in the development of the self¿is called Bildung in German and has a long tradition reaching back to the Middle Ages. The term first appears in the writings of the mystic Meister Eckhart who defines it as self-composure which he regards as a crucial stage in our spiritual development. The concept of Bildung takes on a secular meaning in the Reformation, when Ulrich von Hutten first coined the phrase that has become Stanford¿s motto: ¿Die Luft der Freiheit weht¿ (The wind of freedom is blowing.¿). What he meant is that the cultivation of oneself leads to the freedom of thought, freedom to act, freedom to assert oneself as an individual, freedom to access knowledge, and freedom to determine one¿s own role in society. This idea of education as an internal and transformative process is central to debates in the nineteenth century¿both in Germany and the United States¿in which self-reflection is seen as key to the cultivation of an individual¿s identity and to her or his role as a member of society. In this course we will read reflections on education as self-fashioning by some of the greatest German thinkers spanning from the Middle Ages to the present. We will also enjoy some contemporary parodies of such reflections. These readings and our discussions will help us to understand Stanford undergraduate education as a transformative process of self-realization in our global society.","min_units":7,"max_units":7,"gers":["WAY-A-II","Writing 1"],"id":214533,"primary":[[{"instructors":[],"meeting-times":[{"days":[false,false,false,true,false],"start":"1:15:00 PM","end":"2:30:00 PM","location":"260-244"}],"id":38323}],[],[]],"primary_type":"Seminar","secondary":[[{"instructors":[],"meeting-times":[{"days":[true,false,true,false,false],"start":"11:00:00 AM","end":"12:50:00 PM","location":"160-331"}],"id":56906},{"instructors":[],"meeting-times":[{"days":[false,true,false,true,false],"start":"9:00:00 AM","end":"10:50:00 AM","location":""}],"id":56907}],[],[]],"secondary_type":"Discussion"},
"3":{"department":"ESF","number":"3","title":"Education as Self-Fashioning: How to be a Public Intellectual","description":"Can education impart more than bookish learning?  This is the question that critics have posed since the European Renaissance.  Through their reflections, these critics posited an alternative ideal of education that prepared the student for life outside the academy.  Over the centuries, this ideal would evolve into what we would today call an ¿intellectual¿ ¿ but this modern concept only captures a part of what earlier writers thought learning could achieve.  In this course, we will focus on how education can prepare students to engage in public debates and the role that the university can play in public learning.","min_units":7,"max_units":7,"gers":["WAY-A-II","Writing 1"],"id":214534,"primary":[[{"instructors":[],"meeting-times":[{"days":[false,false,true,false,false],"start":"11:00:00 AM","end":"12:15:00 PM","location":"260-001"}],"id":38324}],[],[]],"primary_type":"Seminar","secondary":[[{"instructors":[],"meeting-times":[{"days":[false,true,false,true,false],"start":"11:00:00 AM","end":"12:50:00 PM","location":""}],"id":56909},{"instructors":[],"meeting-times":[{"days":[false,true,false,true,false],"start":"9:00:00 AM","end":"10:50:00 AM","location":"160-321"}],"id":56908}],[],[]],"secondary_type":"Discussion"},
"3A":{"department":"ESF","number":"3A","title":"Education as Self-Fashioning: How to be a Public Intellectual","description":"Can education impart more than bookish learning?  This is the question that critics have posed since the European Renaissance.  Through their reflections, these critics posited an alternative ideal of education that prepared the student for life outside the academy.  Over the centuries, this ideal would evolve into what we would today call an ¿intellectual¿ ¿ but this modern concept only captures a part of what earlier writers thought learning could achieve.  In this course, we will focus on how education can prepare students to engage in public debates and the role that the university can play in public learning.","min_units":7,"max_units":7,"gers":["WAY-A-II","Writing 1"],"id":214535,"primary":[[{"instructors":[],"meeting-times":[{"days":[false,false,true,false,false],"start":"1:15:00 PM","end":"2:30:00 PM","location":"School of Education 229"}],"id":38325}],[],[]],"primary_type":"Seminar","secondary":[[{"instructors":[],"meeting-times":[{"days":[false,true,false,true,false],"start":"9:00:00 AM","end":"10:50:00 AM","location":""}],"id":56910},{"instructors":[],"meeting-times":[{"days":[false,true,false,true,false],"start":"11:00:00 AM","end":"12:50:00 PM","location":"160-321"}],"id":56911}],[],[]],"secondary_type":"Discussion"},
"4":{"department":"ESF","number":"4","title":"Education as Self-Fashioning: Learning to Change","description":"Does education entail changing the self? How much? Why should I change my life? How do I discover that I need to change? Who can rightly tell me how to change? What difference does it make? These and related questions have been around for a long time, yet that makes them no easier to answer today than 2500 years ago. In the 5th century BCE, Socrates found that his answers--based on his own will to change--proved troublesome, and ultimately fatal. His follower, the philosopher Plato, transformed the Socratic exploration into idiosyncratic utopian visions that sought to change the conditions of life--and so make Socrates' fate unrepeatable. Plato's own followers, from Aristotle onward, found new ways to explain, enact, or evade change. Not until the end of antiquity, however, do we find, in Augustine of Hippo (354-430 CE), someone as explicitly and passionately committed to personal change as the early Greek thinker. Bookended by the major figures of the Athenian seeker and the North African, this course will lead students to analyze and compare their own tentative answers with the ideas on self-fashioning that can be found in a range of ancient texts. Students will demonstrate their grasp of the material through a variety of exercises, including a research paper, discourse analyses, and responses in persona.","min_units":7,"max_units":7,"gers":["WAY-A-II","WAY-ER","Writing 1"],"id":214536,"primary":[[{"instructors":[],"meeting-times":[{"days":[false,true,false,false,false],"start":"9:00:00 AM","end":"10:15:00 AM","location":"School of Education 313"}],"id":38326}],[],[]],"primary_type":"Seminar","secondary":[[{"instructors":[],"meeting-times":[{"days":[true,false,true,false,false],"start":"9:00:00 AM","end":"10:50:00 AM","location":""}],"id":56913},{"instructors":[],"meeting-times":[{"days":[false,true,false,true,false],"start":"11:00:00 AM","end":"12:50:00 PM","location":""}],"id":56912}],[],[]],"secondary_type":"Discussion"},
"4A":{"department":"ESF","number":"4A","title":"Education as Self-Fashioning: Learning to Change","description":"Does education entail changing the self? How much? Why should I change my life? How do I discover that I need to change? Who can rightly tell me how to change? What difference does it make? These and related questions have been around for a long time, yet that makes them no easier to answer today than 2500 years ago. In the 5th century BCE, Socrates found that his answers--based on his own will to change--proved troublesome, and ultimately fatal. His follower, the philosopher Plato, transformed the Socratic exploration into idiosyncratic utopian visions that sought to change the conditions of life--and so make Socrates' fate unrepeatable. Plato's own followers, from Aristotle onward, found new ways to explain, enact, or evade change. Not until the end of antiquity, however, do we find, in Augustine of Hippo (354-430 CE), someone as explicitly and passionately committed to personal change as the early Greek thinker. Bookended by the major figures of the Athenian seeker and the North African, this course will lead students to analyze and compare their own tentative answers with the ideas on self-fashioning that can be found in a range of ancient texts. Students will demonstrate their grasp of the material through a variety of exercises, including a research paper, discourse analyses, and responses in persona.","min_units":7,"max_units":7,"gers":["WAY-A-II","Writing 1"],"id":214537,"primary":[[{"instructors":[],"meeting-times":[{"days":[false,false,false,true,false],"start":"9:00:00 AM","end":"10:15:00 AM","location":"250-201"}],"id":38327}],[],[]],"primary_type":"Seminar","secondary":[[{"instructors":[],"meeting-times":[{"days":[true,false,true,false,false],"start":"9:00:00 AM","end":"10:50:00 AM","location":"160-331"}],"id":56915},{"instructors":[],"meeting-times":[{"days":[false,true,false,true,false],"start":"11:00:00 AM","end":"12:50:00 PM","location":"260-012"}],"id":56914}],[],[]],"secondary_type":"Discussion"},
"5":{"department":"ESF","number":"5","title":"Education as Self-Fashioning: Thinking Like a Philosopher","description":"The Ancient Greek aphorism ¿Know thyself¿ is a centerpiece of wisdom. But  knowing one¿s own mind is not easy, in part because it is not a matter of simply looking inward to find one¿s proclivities and beliefs; it seems one must look outward to the issues and questions the world presents, and know what one thinks about them. Knowing oneself is in part a matter of knowing one¿s way around as a thinker, where that is a matter of knowing how to think about issues, when to trust one¿s judgment and when to withhold it. Fashioning or making oneself into a better (more acute, more sensitive, more judicious) reasoner is something philosophy as a discipline holds out as a promise. In this course, we will take up the first task of becoming better reasoners about a select handful of persistent problems; we will at the same time reflect on what it is that philosophical thinking is, and how it might shape us as thinkers.","min_units":7,"max_units":7,"gers":["WAY-A-II","WAY-ER","Writing 1"],"id":214538,"primary":[[{"instructors":[],"meeting-times":[{"days":[false,true,false,false,false],"start":"2:15:00 PM","end":"3:30:00 PM","location":"School of Education 229"}],"id":38328}],[],[]],"primary_type":"Seminar","secondary":[[{"instructors":[],"meeting-times":[{"days":[false,true,false,true,false],"start":"4:15:00 PM","end":"6:05:00 PM","location":"Meyer 142"}],"id":56917},{"instructors":[],"meeting-times":[{"days":[true,false,true,false,false],"start":"11:00:00 AM","end":"12:50:00 PM","location":""}],"id":56916}],[],[]],"secondary_type":"Discussion"},
"50":{"department":"ESF","number":"50","title":"Education as Self-Fashioning Lecture Series","description":"One-unit lecture series featuring prominent intellectuals lecturing on the nature and meaning of liberal education (associated with Education as Self-Fashioning.)  NOTE: students enrolled in the 7-unit ESF course should NOT add this course to their study list; this 1-unit course is only for non-ESF students who wish to enroll in the lecture series only.  Lectures will constitute an ongoing, campus-wide conversation about the aims of liberal education that extends the ''First Lecture'' featured in New Student Orientation.","min_units":1,"max_units":1,"gers":[],"id":214872,"primary":[[{"instructors":[],"meeting-times":[{"days":[false,false,false,false,true],"start":"12:00:00 PM","end":"1:30:00 PM","location":"Annaud"}],"id":57014}],[],[]],"primary_type":"Lecture"},
"5A":{"department":"ESF","number":"5A","title":"Education as Self-Fashioning: Thinking Like a Philosopher","description":"The Ancient Greek aphorism ¿Know thyself¿ is a centerpiece of wisdom. But  knowing one¿s own mind is not easy, in part because it is not a matter of simply looking inward to find one¿s proclivities and beliefs; it seems one must look outward to the issues and questions the world presents, and know what one thinks about them. Knowing oneself is in part a matter of knowing one¿s way around as a thinker, where that is a matter of knowing how to think about issues, when to trust one¿s judgment and when to withhold it. Fashioning or making oneself into a better (more acute, more sensitive, more judicious) reasoner is something philosophy as a discipline holds out as a promise. In this course, we will take up the first task of becoming better reasoners about a select handful of persistent problems; we will at the same time reflect on what it is that philosophical thinking is, and how it might shape us as thinkers.","min_units":7,"max_units":7,"gers":["WAY-A-II","WAY-ER","Writing 1"],"id":214539,"primary":[[{"instructors":[],"meeting-times":[{"days":[false,false,false,true,false],"start":"2:15:00 PM","end":"3:30:00 PM","location":"School of Education 229"}],"id":38329}],[],[]],"primary_type":"Seminar","secondary":[[{"instructors":[],"meeting-times":[{"days":[true,false,true,false,false],"start":"11:00:00 AM","end":"12:50:00 PM","location":"School of Education 36"}],"id":56918},{"instructors":[],"meeting-times":[{"days":[false,true,false,true,false],"start":"4:15:00 PM","end":"6:05:00 PM","location":""}],"id":56919}],[],[]],"secondary_type":"Discussion"},
"6":{"department":"ESF","number":"6","title":"Education as Self-Fashioning: The Wind of Freedom","description":"Stanford's unofficial motto, \"the wind of freedom blows,\" engraved in German on the university seal, invites us the ponder freedom in the context of education.  What is the relation between freedom and the \"liberal\" arts?  Does studying free your mind?  Does free will even exist?  If so, how does education help you develop its potential?  This course will look at various authors -- from antiquity through the 20th century -- who have thought about the blessings, burdens, and obligations of human freedom.  Beginning with Eve in the Garden of Eden, we will explore how exercising freedom in your personal choices and conduct not only determines your fate as an individual but carries with it a measure of responsibility for the world.  We will place special emphasis on the implications of such responsibility in our own time.","min_units":7,"max_units":7,"gers":["WAY-A-II","WAY-ER","Writing 1"],"id":214540,"primary":[[{"instructors":[],"meeting-times":[{"days":[true,false,false,false,false],"start":"11:00:00 AM","end":"12:15:00 PM","location":"School of Education 210"}],"id":38330}],[],[]],"primary_type":"Seminar","secondary":[[{"instructors":[],"meeting-times":[{"days":[false,true,false,true,false],"start":"3:15:00 PM","end":"5:05:00 PM","location":""}],"id":56921},{"instructors":[],"meeting-times":[{"days":[false,true,false,true,false],"start":"11:00:00 AM","end":"12:50:00 PM","location":""}],"id":56920}],[],[]],"secondary_type":"Discussion"},
"6A":{"department":"ESF","number":"6A","title":"Education as Self-Fashioning: The Wind of Freedom","description":"Stanford's unofficial motto, \"the wind of freedom blows,\" engraved in German on the university seal, invites us the ponder freedom in the context of education.  What is the relation between freedom and the \"liberal\" arts?  Does studying free your mind?  Does free will even exist?  If so, how does education help you develop its potential?  This course will look at various authors -- from antiquity through the 20th century -- who have thought about the blessings, burdens, and obligations of human freedom.  Beginning with Eve in the Garden of Eden, we will explore how exercising freedom in your personal choices and conduct not only determines your fate as an individual but carries with it a measure of responsibility for the world.  We will place special emphasis on the implications of such responsibility in our own time.","min_units":7,"max_units":7,"gers":["WAY-A-II","WAY-ER","Writing 1"],"id":214541,"primary":[[{"instructors":[],"meeting-times":[{"days":[true,false,false,false,false],"start":"1:15:00 PM","end":"2:30:00 PM","location":"School of Education 229"}],"id":38331}],[],[]],"primary_type":"Seminar","secondary":[[{"instructors":[],"meeting-times":[{"days":[false,true,false,true,false],"start":"11:00:00 AM","end":"12:50:00 PM","location":"Thornt211"}],"id":56922},{"instructors":[],"meeting-times":[{"days":[false,true,false,true,false],"start":"3:15:00 PM","end":"5:05:00 PM","location":"50-51P"}],"id":56923}],[],[]],"secondary_type":"Discussion"}}<commit_msg>Delete ESF.js<commit_after><|endoftext|>


<commit_before>// $.pjax fallback tests should run on both pushState and
// non-pushState compatible browsers.
$.each([true, false], function() {

var disabled = this == false
var s = disabled ? " (disabled)" : ""

module("$.pjax fallback"+s, {
  setup: function() {
    var self = this
    stop()
    this.loaded = function(frame) {
      self.frame  = frame
      self.loaded = $.noop
      start()
    }
    window.iframeLoad = function(frame) {
      setTimeout(function() {
        if (disabled && frame.$ && frame.$.pjax) frame.$.pjax.disable()
        self.loaded(frame)
      }, 0)
    }
    $("#qunit-fixture").append("<iframe src='home.html'>")
  },
  teardown: function() {
    delete window.iframeLoad
  }
})

asyncTest("sets new url"+s, function() {
  var frame = this.frame

  this.loaded = function() {
    equal(frame.location.pathname, "/hello.html")
    start()
  }

  frame.$.pjax({
    url: "hello.html",
    container: "#main"
  })
})

asyncTest("sets new url for function"+s, function() {
  var frame = this.frame

  this.loaded = function() {
    equal(frame.location.pathname, "/hello.html")
    start()
  }

  frame.$.pjax({
    url: function() { return "hello.html" },
    container: "#main"
  })
})

asyncTest("updates container html"+s, function() {
  var frame = this.frame

  this.loaded = function(frame) {
    equal(frame.$("#main p").html(), "Hello!")
    start()
  }

  frame.$.pjax({
    url: "/hello.html",
    container: "#main"
  })
})

asyncTest("sets title to response <title>"+s, function() {
  var frame = this.frame

  this.loaded = function(frame) {
    equal(frame.document.title, "Hello")
    start()
  }

  frame.$.pjax({
    url: "/hello.html",
    container: "#main"
  })
})

asyncTest("sends correct HTTP referer"+s, function() {
  var frame = this.frame

  this.loaded = function(frame) {
    var referer = frame.document.getElementById("referer").textContent
    ok(referer.match("/home.html"), referer)
    start()
  }

  frame.$.pjax({
    url: "/referer.html",
    container: "#main"
  })
})

asyncTest("adds entry to browser history"+s, function() {
  var frame = this.frame
  var count = 0

  frame.onpopstate = function() {
    window.iframeLoad(frame)
  }

  this.loaded = function() {
    count++

    if (count == 1) {
      equal(frame.location.pathname, "/hello.html")
      ok(frame.history.length > 1)
      frame.history.back()
    } else if (count == 2) {
      equal(frame.location.pathname, "/home.html")
      frame.history.forward()
      start()
    }
  }

  frame.$.pjax({
    url: "hello.html",
    container: "#main"
  })
})

asyncTest("scrolls to top of the page"+s, function() {
  var frame = this.frame

  frame.window.scrollTo(0, 100)
  equal(frame.window.scrollY, 100)

  this.loaded = function(frame) {
    equal(frame.window.scrollY, 0)
    start()
  }

  frame.$.pjax({
    url: "/long.html",
    container: "#main"
  })
})

asyncTest("scrolls to anchor at top page"+s, function() {
  var frame = this.frame

  equal(frame.window.scrollY, 0)

  this.loaded = function(frame) {
    setTimeout(function() {
      equal(frame.window.scrollY, 8)
      start()
    }, 10)
  }

  frame.$.pjax({
    url: "/anchor.html#top",
    container: "#main"
  })
})

asyncTest("empty anchor doesn't scroll page"+s, function() {
  var frame = this.frame

  equal(frame.window.scrollY, 0)

  this.loaded = function(frame) {
    setTimeout(function() {
      equal(frame.window.scrollY, 0)
      start()
    }, 10)
  }

  frame.$.pjax({
    url: "/anchor.html#",
    container: "#main"
  })
})

asyncTest("scrolls to anchor at bottom page"+s, function() {
  var frame = this.frame

  equal(frame.window.scrollY, 0)

  this.loaded = function(frame) {
    setTimeout(function() {
      equal(frame.window.scrollY, 10008)
      start()
    }, 10)
  }

  frame.$.pjax({
    url: "/anchor.html#bottom",
    container: "#main"
  })
})

asyncTest("sets GET method"+s, function() {
  var frame = this.frame

  this.loaded = function() {
    equal(frame.location.pathname, "/env.html")
    var env = JSON.parse(frame.$("#env").text())
    equal(env['REQUEST_METHOD'], "GET")
    start()
  }

  frame.$.pjax({
    type: 'GET',
    url: "env.html",
    container: "#main"
  })
})

asyncTest("sets POST method"+s, function() {
  var frame = this.frame

  this.loaded = function() {
    equal(frame.location.pathname, "/env.html")
    var env = JSON.parse(frame.$("#env").text())
    equal(env['REQUEST_METHOD'], "POST")
    start()
  }

  frame.$.pjax({
    type: 'POST',
    url: "env.html",
    container: "#main"
  })
})

asyncTest("sets PUT method"+s, function() {
  var frame = this.frame

  this.loaded = function() {
    equal(frame.location.pathname, "/env.html")
    var env = JSON.parse(frame.$("#env").text())
    equal(env['REQUEST_METHOD'], "PUT")
    start()
  }

  frame.$.pjax({
    type: 'PUT',
    url: "env.html",
    container: "#main"
  })
})

asyncTest("sets DELETE method"+s, function() {
  var frame = this.frame

  this.loaded = function() {
    equal(frame.location.pathname, "/env.html")
    var env = JSON.parse(frame.$("#env").text())
    equal(env['REQUEST_METHOD'], "DELETE")
    start()
  }

  frame.$.pjax({
    type: 'DELETE',
    url: "env.html",
    container: "#main"
  })
})

asyncTest("GET with data object"+s, function() {
  var frame = this.frame

  this.loaded = function() {
    equal(frame.location.pathname, "/env.html")
    equal(frame.location.search, "?foo=bar")

    var env = JSON.parse(frame.$("#env").text())
    equal(env['REQUEST_METHOD'], "GET")
    equal(env['rack.request.query_hash']['foo'], 'bar')

    start()
  }

  frame.$.pjax({
    type: 'GET',
    url: "env.html",
    data: {foo: 'bar'},
    container: "#main"
  })
})

asyncTest("POST with data object"+s, function() {
  var frame = this.frame

  this.loaded = function() {
    equal(frame.location.pathname, "/env.html")
    equal(frame.location.search, "")

    var env = JSON.parse(frame.$("#env").text())
    equal(env['REQUEST_METHOD'], "POST")
    equal(env['rack.request.form_hash']['foo'], 'bar')

    start()
  }

  frame.$.pjax({
    type: 'POST',
    url: "env.html",
    data: {foo: 'bar'},
    container: "#main"
  })
})

asyncTest("GET with data string"+s, function() {
  var frame = this.frame

  this.loaded = function() {
    equal(frame.location.pathname, "/env.html")
    equal(frame.location.search, "?foo=bar")

    var env = JSON.parse(frame.$("#env").text())
    equal(env['REQUEST_METHOD'], "GET")
    equal(env['rack.request.query_hash']['foo'], 'bar')

    start()
  }

  frame.$.pjax({
    type: 'GET',
    url: "env.html",
    data: "foo=bar",
    container: "#main"
  })
})

asyncTest("POST with data string"+s, function() {
  var frame = this.frame

  this.loaded = function() {
    equal(frame.location.pathname, "/env.html")
    equal(frame.location.search, "")

    var env = JSON.parse(frame.$("#env").text())
    equal(env['REQUEST_METHOD'], "POST")
    equal(env['rack.request.form_hash']['foo'], 'bar')

    start()
  }

  frame.$.pjax({
    type: 'POST',
    url: "env.html",
    data: "foo=bar",
    container: "#main"
  })
})

})
<commit_msg>Give it more time<commit_after>// $.pjax fallback tests should run on both pushState and
// non-pushState compatible browsers.
$.each([true, false], function() {

var disabled = this == false
var s = disabled ? " (disabled)" : ""

module("$.pjax fallback"+s, {
  setup: function() {
    var self = this
    stop()
    this.loaded = function(frame) {
      self.frame  = frame
      self.loaded = $.noop
      start()
    }
    window.iframeLoad = function(frame) {
      setTimeout(function() {
        if (disabled && frame.$ && frame.$.pjax) frame.$.pjax.disable()
        self.loaded(frame)
      }, 0)
    }
    $("#qunit-fixture").append("<iframe src='home.html'>")
  },
  teardown: function() {
    delete window.iframeLoad
  }
})

asyncTest("sets new url"+s, function() {
  var frame = this.frame

  this.loaded = function() {
    equal(frame.location.pathname, "/hello.html")
    start()
  }

  frame.$.pjax({
    url: "hello.html",
    container: "#main"
  })
})

asyncTest("sets new url for function"+s, function() {
  var frame = this.frame

  this.loaded = function() {
    equal(frame.location.pathname, "/hello.html")
    start()
  }

  frame.$.pjax({
    url: function() { return "hello.html" },
    container: "#main"
  })
})

asyncTest("updates container html"+s, function() {
  var frame = this.frame

  this.loaded = function(frame) {
    equal(frame.$("#main p").html(), "Hello!")
    start()
  }

  frame.$.pjax({
    url: "/hello.html",
    container: "#main"
  })
})

asyncTest("sets title to response <title>"+s, function() {
  var frame = this.frame

  this.loaded = function(frame) {
    equal(frame.document.title, "Hello")
    start()
  }

  frame.$.pjax({
    url: "/hello.html",
    container: "#main"
  })
})

asyncTest("sends correct HTTP referer"+s, function() {
  var frame = this.frame

  this.loaded = function(frame) {
    var referer = frame.document.getElementById("referer").textContent
    ok(referer.match("/home.html"), referer)
    start()
  }

  frame.$.pjax({
    url: "/referer.html",
    container: "#main"
  })
})

asyncTest("adds entry to browser history"+s, function() {
  var frame = this.frame
  var count = 0

  frame.onpopstate = function() {
    window.iframeLoad(frame)
  }

  this.loaded = function() {
    count++

    if (count == 1) {
      equal(frame.location.pathname, "/hello.html")
      ok(frame.history.length > 1)
      frame.history.back()
    } else if (count == 2) {
      equal(frame.location.pathname, "/home.html")
      frame.history.forward()
      start()
    }
  }

  frame.$.pjax({
    url: "hello.html",
    container: "#main"
  })
})

asyncTest("scrolls to top of the page"+s, function() {
  var frame = this.frame

  frame.window.scrollTo(0, 100)
  equal(frame.window.scrollY, 100)

  this.loaded = function(frame) {
    equal(frame.window.scrollY, 0)
    start()
  }

  frame.$.pjax({
    url: "/long.html",
    container: "#main"
  })
})

asyncTest("scrolls to anchor at top page"+s, function() {
  var frame = this.frame

  equal(frame.window.scrollY, 0)

  this.loaded = function(frame) {
    setTimeout(function() {
      equal(frame.window.scrollY, 8)
      start()
    }, 100)
  }

  frame.$.pjax({
    url: "/anchor.html#top",
    container: "#main"
  })
})

asyncTest("empty anchor doesn't scroll page"+s, function() {
  var frame = this.frame

  equal(frame.window.scrollY, 0)

  this.loaded = function(frame) {
    setTimeout(function() {
      equal(frame.window.scrollY, 0)
      start()
    }, 10)
  }

  frame.$.pjax({
    url: "/anchor.html#",
    container: "#main"
  })
})

asyncTest("scrolls to anchor at bottom page"+s, function() {
  var frame = this.frame

  equal(frame.window.scrollY, 0)

  this.loaded = function(frame) {
    setTimeout(function() {
      equal(frame.window.scrollY, 10008)
      start()
    }, 10)
  }

  frame.$.pjax({
    url: "/anchor.html#bottom",
    container: "#main"
  })
})

asyncTest("sets GET method"+s, function() {
  var frame = this.frame

  this.loaded = function() {
    equal(frame.location.pathname, "/env.html")
    var env = JSON.parse(frame.$("#env").text())
    equal(env['REQUEST_METHOD'], "GET")
    start()
  }

  frame.$.pjax({
    type: 'GET',
    url: "env.html",
    container: "#main"
  })
})

asyncTest("sets POST method"+s, function() {
  var frame = this.frame

  this.loaded = function() {
    equal(frame.location.pathname, "/env.html")
    var env = JSON.parse(frame.$("#env").text())
    equal(env['REQUEST_METHOD'], "POST")
    start()
  }

  frame.$.pjax({
    type: 'POST',
    url: "env.html",
    container: "#main"
  })
})

asyncTest("sets PUT method"+s, function() {
  var frame = this.frame

  this.loaded = function() {
    equal(frame.location.pathname, "/env.html")
    var env = JSON.parse(frame.$("#env").text())
    equal(env['REQUEST_METHOD'], "PUT")
    start()
  }

  frame.$.pjax({
    type: 'PUT',
    url: "env.html",
    container: "#main"
  })
})

asyncTest("sets DELETE method"+s, function() {
  var frame = this.frame

  this.loaded = function() {
    equal(frame.location.pathname, "/env.html")
    var env = JSON.parse(frame.$("#env").text())
    equal(env['REQUEST_METHOD'], "DELETE")
    start()
  }

  frame.$.pjax({
    type: 'DELETE',
    url: "env.html",
    container: "#main"
  })
})

asyncTest("GET with data object"+s, function() {
  var frame = this.frame

  this.loaded = function() {
    equal(frame.location.pathname, "/env.html")
    equal(frame.location.search, "?foo=bar")

    var env = JSON.parse(frame.$("#env").text())
    equal(env['REQUEST_METHOD'], "GET")
    equal(env['rack.request.query_hash']['foo'], 'bar')

    start()
  }

  frame.$.pjax({
    type: 'GET',
    url: "env.html",
    data: {foo: 'bar'},
    container: "#main"
  })
})

asyncTest("POST with data object"+s, function() {
  var frame = this.frame

  this.loaded = function() {
    equal(frame.location.pathname, "/env.html")
    equal(frame.location.search, "")

    var env = JSON.parse(frame.$("#env").text())
    equal(env['REQUEST_METHOD'], "POST")
    equal(env['rack.request.form_hash']['foo'], 'bar')

    start()
  }

  frame.$.pjax({
    type: 'POST',
    url: "env.html",
    data: {foo: 'bar'},
    container: "#main"
  })
})

asyncTest("GET with data string"+s, function() {
  var frame = this.frame

  this.loaded = function() {
    equal(frame.location.pathname, "/env.html")
    equal(frame.location.search, "?foo=bar")

    var env = JSON.parse(frame.$("#env").text())
    equal(env['REQUEST_METHOD'], "GET")
    equal(env['rack.request.query_hash']['foo'], 'bar')

    start()
  }

  frame.$.pjax({
    type: 'GET',
    url: "env.html",
    data: "foo=bar",
    container: "#main"
  })
})

asyncTest("POST with data string"+s, function() {
  var frame = this.frame

  this.loaded = function() {
    equal(frame.location.pathname, "/env.html")
    equal(frame.location.search, "")

    var env = JSON.parse(frame.$("#env").text())
    equal(env['REQUEST_METHOD'], "POST")
    equal(env['rack.request.form_hash']['foo'], 'bar')

    start()
  }

  frame.$.pjax({
    type: 'POST',
    url: "env.html",
    data: "foo=bar",
    container: "#main"
  })
})

})
<|endoftext|>


<commit_before>// ERPNext - web based ERP (http://erpnext.com)
// Copyright (C) 2012 Web Notes Technologies Pvt Ltd
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.	If not, see <http://www.gnu.org/licenses/>.

cur_frm.add_fetch('employee', 'company', 'company');
cur_frm.add_fetch('employee','employee_name','employee_name');

cur_frm.cscript.onload = function(doc,cdt,cdn){
	if(!doc.approval_status)
		cur_frm.set_value("approval_status", "Draft")

	if (doc.__islocal) {
		cur_frm.set_value("posting_date", dateutil.get_today());
		if(doc.amended_from)
			cur_frm.set_value("approval_status", "Draft");
		cur_frm.cscript.clear_sanctioned(doc);
	}

	cur_frm.call({
		method:"get_approver_list",
		callback: function(r) {
			cur_frm.set_df_property("exp_approver", "options", r.message);
		}
	});
}

cur_frm.cscript.clear_sanctioned = function(doc) {
	var val = getchildren('Expense Claim Detail', doc.name,
		'expense_voucher_details', doc.doctype);
	for(var i = 0; i<val.length; i++){
		val[i].sanctioned_amount ='';
	}

	doc.total_sanctioned_amount = '';
	refresh_many(['sanctioned_amount', 'total_sanctioned_amount']);
}

cur_frm.cscript.refresh = function(doc,cdt,cdn){
	cur_frm.set_intro("");
	if(doc.__islocal && !in_list(user_roles, "HR User")) {
		cur_frm.set_intro("Fill the form and save it")
	} else {
		if(doc.approval_status=="Draft") {
			if(user==doc.exp_approver) {
				if(doc.approval_status=="Draft") {
					cur_frm.set_intro("You are the Expense Approver for this record. Please Update the 'Status' and Save");
					cur_frm.set_df_property("approval_status", "permlevel", 0);
				}
			} else {
				cur_frm.set_intro("Expense Claim is pending approval. Only the Expense Approver can update status.");
			}
		} else {
			if(doc.approval_status=="Approved") {
				cur_frm.set_intro("Expense Claim has been approved.");
			} else if(doc.approval_status=="Rejected") {
				cur_frm.set_intro("Expense Claim has been rejected.");
			}
		}
	}

	if(doc.approval_status=="Approved" && doc.docstatus==0) {
		cur_frm.savesubmit()
	}}

cur_frm.cscript.validate = function(doc) {
	cur_frm.cscript.calculate_total(doc);
}

cur_frm.cscript.calculate_total = function(doc,cdt,cdn){
	doc.total_claimed_amount = 0;
	doc.total_sanctioned_amount = 0;
	$.each(wn.model.get("Expense Claim Detail", {parent:doc.name}), function(i, d) {
		doc.total_claimed_amount += d.claim_amount;
		if(d.sanctioned_amount==null) {
			d.sanctioned_amount = d.claim_amount;
		}
		doc.total_sanctioned_amount += d.sanctioned_amount;
	});

	refresh_field("total_claimed_amount");
	refresh_field('total_sanctioned_amount');

}

cur_frm.cscript.calculate_total_amount = function(doc,cdt,cdn){
	cur_frm.cscript.calculate_total(doc,cdt,cdn);
}
cur_frm.cscript.claim_amount = function(doc,cdt,cdn){
	cur_frm.cscript.calculate_total(doc,cdt,cdn);
}
cur_frm.cscript.sanctioned_amount = function(doc,cdt,cdn){
	cur_frm.cscript.calculate_total(doc,cdt,cdn);
}

cur_frm.cscript.on_submit = function(doc, cdt, cdn) {
	if(cint(wn.boot.notification_settings.expense_claim)) {
		cur_frm.email_doc(wn.boot.notification_settings.expense_claim_message);
	}
}<commit_msg>message updates in Leave / Expense, catch localstorage error<commit_after>// ERPNext - web based ERP (http://erpnext.com)
// Copyright (C) 2012 Web Notes Technologies Pvt Ltd
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.	If not, see <http://www.gnu.org/licenses/>.

cur_frm.add_fetch('employee', 'company', 'company');
cur_frm.add_fetch('employee','employee_name','employee_name');

cur_frm.cscript.onload = function(doc,cdt,cdn){
	if(!doc.approval_status)
		cur_frm.set_value("approval_status", "Draft")

	if (doc.__islocal) {
		cur_frm.set_value("posting_date", dateutil.get_today());
		if(doc.amended_from)
			cur_frm.set_value("approval_status", "Draft");
		cur_frm.cscript.clear_sanctioned(doc);
	}

	cur_frm.call({
		method:"get_approver_list",
		callback: function(r) {
			cur_frm.set_df_property("exp_approver", "options", r.message);
		}
	});
}

cur_frm.cscript.clear_sanctioned = function(doc) {
	var val = getchildren('Expense Claim Detail', doc.name,
		'expense_voucher_details', doc.doctype);
	for(var i = 0; i<val.length; i++){
		val[i].sanctioned_amount ='';
	}

	doc.total_sanctioned_amount = '';
	refresh_many(['sanctioned_amount', 'total_sanctioned_amount']);
}

cur_frm.cscript.refresh = function(doc,cdt,cdn){
	cur_frm.set_intro("");
	if(doc.__islocal && !in_list(user_roles, "HR User")) {
		cur_frm.set_intro("Fill the form and save it")
	} else {
		if(doc.approval_status=="Draft") {
			if(user==doc.exp_approver) {
				if(doc.approval_status=="Draft") {
					cur_frm.set_intro("You are the Expense Approver for this record. Please Update the 'Status' and Save");
					cur_frm.set_df_property("approval_status", "permlevel", 0);
				}
			} else {
				cur_frm.set_intro("Expense Claim is pending approval. Only the Expense Approver can update status.");
			}
		} else {
			if(doc.approval_status=="Approved") {
				cur_frm.set_intro("Expense Claim has been approved.");
			} else if(doc.approval_status=="Rejected") {
				cur_frm.set_intro("Expense Claim has been rejected.");
			}
		}
	}

	if(doc.approval_status=="Approved" && doc.docstatus==0) {
		cur_frm.savesubmit()
	}}

cur_frm.cscript.validate = function(doc) {
	cur_frm.cscript.calculate_total(doc);
}

cur_frm.cscript.calculate_total = function(doc,cdt,cdn){
	doc.total_claimed_amount = 0;
	doc.total_sanctioned_amount = 0;
	$.each(wn.model.get("Expense Claim Detail", {parent:doc.name}), function(i, d) {
		doc.total_claimed_amount += d.claim_amount;
		if(d.sanctioned_amount==null) {
			d.sanctioned_amount = d.claim_amount;
		}
		doc.total_sanctioned_amount += d.sanctioned_amount;
	});

	refresh_field("total_claimed_amount");
	refresh_field('total_sanctioned_amount');

}

cur_frm.cscript.calculate_total_amount = function(doc,cdt,cdn){
	cur_frm.cscript.calculate_total(doc,cdt,cdn);
}
cur_frm.cscript.claim_amount = function(doc,cdt,cdn){
	cur_frm.cscript.calculate_total(doc,cdt,cdn);
}
cur_frm.cscript.sanctioned_amount = function(doc,cdt,cdn){
	cur_frm.cscript.calculate_total(doc,cdt,cdn);
}

cur_frm.cscript.on_submit = function(doc, cdt, cdn) {
	if(cint(wn.boot.notification_settings && wn.boot.notification_settings.expense_claim)) {
		cur_frm.email_doc(wn.boot.notification_settings.expense_claim_message);
	}
}<|endoftext|>


<commit_before>/**
 * @file CursorPopoverProvider component
 */

import React, {Component, cloneElement, createRef} from 'react';
import PropTypes from 'prop-types';

// components
import CursorPopover from '../CursorPopover';

// statics
import Theme from '../Theme';
import Position from '../_statics/Position';

// vendors
import {findDOMNode} from 'react-dom';
import Util from '../_vendors/Util';
import ComponentUtil from '../_vendors/ComponentUtil';

class CursorPopoverProvider extends Component {

    static Position = Position;
    static Theme = Theme;

    static getDerivedStateFromProps(props, state) {
        return {
            prevProps: props,
            visible: ComponentUtil.getDerivedState(props, state, 'visible')
        };
    }

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.trigger = createRef();
        this.triggerEl = null;

        this.state = {
            visible: props.visible
        };

    }

    componentDidMount() {
        this.triggerEl = findDOMNode(this.trigger?.current);
    }

    /**
     * public
     */
    show = () => {

        if (this.state.visible) {
            return;
        }

        this.setState({
            visible: true
        }, () => this.props.onRequestOpen?.());

    };

    /**
     * public
     */
    hide = () => {

        if (!this.state.visible) {
            return;
        }

        this.setState({
            visible: false
        }, () => this.props.onRequestClose?.());

    };

    /**
     * public
     */
    toggle = () => {
        this.setState({
            visible: !this.state.visible
        }, () => {
            if (!this.state.visible) {
                this.props.onRequestClose?.();
            } else {
                this.props.onRequestOpen?.();
            }
        });
    };

    handleMouseEnter = e => {
        this.props?.children?.props?.onMouseEnter?.(e);
        this.show();
    };

    render() {

        const {

            children, popoverContent,

            // not passing down these props
            // eslint-disable-next-line no-unused-vars
            onRequestOpen, onRequestClose,

            ...restProps

        } = this.props;
        const {visible} = this.state;

        if (!popoverContent) {
            return children;
        }

        return (
            <>

                {
                    cloneElement(children, {
                        ref: this.trigger,
                        onMouseEnter: this.handleMouseEnter
                    })
                }

                <CursorPopover {...restProps}
                               triggerEl={this.triggerEl}
                               visible={visible}
                               onRequestClose={this.hide}>
                    {popoverContent}
                </CursorPopover>

            </>
        );
    }

}

CursorPopoverProvider.propTypes = {

    children: PropTypes.any,

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * The CSS class name of the content element.
     */
    contentClassName: PropTypes.string,

    modalClassName: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    parentEl: PropTypes.object,

    /**
     * This is the DOM element that will be used to set the position of the popover.
     */
    triggerEl: PropTypes.object,

    /**
     * If true,the popover is visible.
     */
    visible: PropTypes.bool,

    /**
     * The popover theme.Can be primary,highlight,success,warning,error.
     */
    theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * The popover alignment.The value can be CursorPopover.Position.LEFT or CursorPopover.Position.RIGHT.
     */
    position: PropTypes.oneOf(Util.enumerateValue(Position)),

    /**
     * If true, popover will have animation effects.
     */
    isAnimated: PropTypes.bool,

    enterable: PropTypes.bool,

    /**
     * The depth of Paper component.
     */
    depth: PropTypes.number,

    shouldFollowScroll: PropTypes.bool,
    scrollEl: PropTypes.object,

    resetPositionWait: PropTypes.number,

    popoverContent: PropTypes.any,

    /**
     * The function of popover render.
     */
    onRender: PropTypes.func,

    /**
     * The function of popover rendered.
     */
    onRendered: PropTypes.func,

    /**
     * The function of popover destroy.
     */
    onDestroy: PropTypes.func,

    /**
     * The function of popover destroyed.
     */
    onDestroyed: PropTypes.func,

    /**
     * Callback function fired when the popover is requested to be opened.
     */
    onRequestOpen: PropTypes.func,

    /**
     * Callback function fired when the popover is requested to be closed.
     */
    onRequestClose: PropTypes.func,

    /**
     * Callback function fired when wrapper wheeled.
     */
    onWheel: PropTypes.func,

    onCursorMove: PropTypes.func,
    onTargetChange: PropTypes.func

};

CursorPopoverProvider.defaultProps = {

    parentEl: document.body,

    visible: false,
    theme: Theme.DEFAULT,
    position: Position.BOTTOM_LEFT,
    isAnimated: true,
    enterable: false,

    shouldFollowScroll: false,
    resetPositionWait: 250

};

export default CursorPopoverProvider;
<commit_msg>update CursorPopoverProvider<commit_after>/**
 * @file CursorPopoverProvider component
 */

import React, {Component, cloneElement, createRef} from 'react';
import PropTypes from 'prop-types';

// components
import CursorPopover from '../CursorPopover';

// statics
import Theme from '../Theme';
import Position from '../_statics/Position';

// vendors
import {findDOMNode} from 'react-dom';
import Util from '../_vendors/Util';
import ComponentUtil from '../_vendors/ComponentUtil';

class CursorPopoverProvider extends Component {

    static Position = Position;
    static Theme = Theme;

    static getDerivedStateFromProps(props, state) {
        return {
            prevProps: props,
            visible: ComponentUtil.getDerivedState(props, state, 'visible')
        };
    }

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.trigger = createRef();
        this.triggerEl = null;

        this.state = {
            visible: props.visible
        };

    }

    componentDidMount() {
        this.triggerEl = findDOMNode(this.trigger?.current);
    }

    /**
     * public
     */
    show = () => {

        if (this.state.visible) {
            return;
        }

        this.setState({
            visible: true
        }, () => this.props.onRequestOpen?.());

    };

    /**
     * public
     */
    hide = () => {

        if (!this.state.visible) {
            return;
        }

        this.setState({
            visible: false
        }, () => this.props.onRequestClose?.());

    };

    /**
     * public
     */
    toggle = () => {
        this.setState({
            visible: !this.state.visible
        }, () => {
            if (!this.state.visible) {
                this.props.onRequestClose?.();
            } else {
                this.props.onRequestOpen?.();
            }
        });
    };

    handleMouseOver = e => {
        this.props?.children?.props?.onMouseOver?.(e);
        this.show();
    };

    render() {

        const {

            children, popoverContent,

            // not passing down these props
            // eslint-disable-next-line no-unused-vars
            onRequestOpen, onRequestClose,

            ...restProps

        } = this.props;
        const {visible} = this.state;

        if (!popoverContent) {
            return children;
        }

        return (
            <>

                {
                    cloneElement(children, {
                        ref: this.trigger,
                        onMouseOver: this.handleMouseOver
                    })
                }

                <CursorPopover {...restProps}
                               triggerEl={this.triggerEl}
                               visible={visible}
                               onRequestClose={this.hide}>
                    {popoverContent}
                </CursorPopover>

            </>
        );
    }

}

CursorPopoverProvider.propTypes = {

    children: PropTypes.any,

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * The CSS class name of the content element.
     */
    contentClassName: PropTypes.string,

    modalClassName: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    parentEl: PropTypes.object,

    /**
     * This is the DOM element that will be used to set the position of the popover.
     */
    triggerEl: PropTypes.object,

    /**
     * If true,the popover is visible.
     */
    visible: PropTypes.bool,

    /**
     * The popover theme.Can be primary,highlight,success,warning,error.
     */
    theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * The popover alignment.The value can be CursorPopover.Position.LEFT or CursorPopover.Position.RIGHT.
     */
    position: PropTypes.oneOf(Util.enumerateValue(Position)),

    /**
     * If true, popover will have animation effects.
     */
    isAnimated: PropTypes.bool,

    enterable: PropTypes.bool,

    /**
     * The depth of Paper component.
     */
    depth: PropTypes.number,

    shouldFollowScroll: PropTypes.bool,
    scrollEl: PropTypes.object,

    resetPositionWait: PropTypes.number,

    popoverContent: PropTypes.any,

    /**
     * The function of popover render.
     */
    onRender: PropTypes.func,

    /**
     * The function of popover rendered.
     */
    onRendered: PropTypes.func,

    /**
     * The function of popover destroy.
     */
    onDestroy: PropTypes.func,

    /**
     * The function of popover destroyed.
     */
    onDestroyed: PropTypes.func,

    /**
     * Callback function fired when the popover is requested to be opened.
     */
    onRequestOpen: PropTypes.func,

    /**
     * Callback function fired when the popover is requested to be closed.
     */
    onRequestClose: PropTypes.func,

    /**
     * Callback function fired when wrapper wheeled.
     */
    onWheel: PropTypes.func,

    onCursorMove: PropTypes.func,
    onTargetChange: PropTypes.func

};

CursorPopoverProvider.defaultProps = {

    parentEl: document.body,

    visible: false,
    theme: Theme.DEFAULT,
    position: Position.BOTTOM_LEFT,
    isAnimated: true,
    enterable: false,

    shouldFollowScroll: false,
    resetPositionWait: 250

};

export default CursorPopoverProvider;
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import Chart from 'chart.js';
import { Line } from 'react-chartjs-2';

import fetchWcl from 'common/fetchWclApi';

import ManaStyles from 'Interface/Others/ManaStyles.js';

const formatDuration = (duration) => {
  const seconds = Math.floor(duration % 60);
  return `${Math.floor(duration / 60)}:${seconds < 10 ? `0${seconds}` : seconds}`;
};

const CLASS_CHART_LINE_COLORS = {
  DeathKnight: 'rgba(196, 31, 59, 0.6)',
  Druid: 'rgba(255, 125, 10, 0.6)',
  Hunter: 'rgba(171, 212, 115, 0.6)',
  Mage: 'rgba(105, 204, 240, 0.6)',
  Monk: 'rgba(45, 155, 120, 0.6)',
  Paladin: 'rgba(245, 140, 186, 0.6)',
  Priest: 'rgba(255, 255, 255, 0.6)',
  Rogue: 'rgba(255, 245, 105, 0.6)',
  Shaman: 'rgba(36, 89, 255, 0.6)',
  Warlock: 'rgba(148, 130, 201, 0.6)',
  Warrior: 'rgba(199, 156, 110, 0.6)',
  DemonHunter: 'rgba(163, 48, 201, 0.6)',
};

class Graph extends React.PureComponent {
  static propTypes = {
    reportCode: PropTypes.string.isRequired,
    actorId: PropTypes.number.isRequired,
    start: PropTypes.number.isRequired,
    end: PropTypes.number.isRequired,
  };

  constructor() {
    super();
    this.state = {
      data: null,
    };
  }

  componentWillMount() {
    this.load(this.props.reportCode, this.props.actorId, this.props.start, this.props.end);
  }
  componentWillReceiveProps(newProps) {
    if (newProps.reportCode !== this.props.reportCode || newProps.actorId !== this.props.actorId || newProps.start !== this.props.start || newProps.end !== this.props.end) {
      this.load(newProps.reportCode, newProps.actorId, newProps.start, newProps.end);
    }
  }

  load(reportCode, actorId, start, end) {
    return fetchWcl(`report/tables/resources/${reportCode}`, {
      start,
      end,
      abilityid: 1000,
    })
      .then(json => {
        console.log('Received player health', json);
        this.setState({
          data: json,
        });
      });
  }

  render() {
    const data = this.state.data;
    if (!data) {
      return (

          Loading...

      );
    }

    const { start, end } = this.props;

    const series = data.series;
    const players = series.filter(item => !!CLASS_CHART_LINE_COLORS[item.type]);

    const entities = [];

    players.forEach(series => {
      const newSeries = {
        ...series,
        lastValue: 100, // fights start at full hp
        data: {},
      };

      series.data.forEach((item) => {
        const secIntoFight = Math.floor((item[0] - start) / 1000);

        const health = item[1];
        newSeries.data[secIntoFight] = Math.min(100, health);
      });
      entities.push(newSeries);
    });

    const deathsBySecond = {};
    if (this.state.data.deaths) {
      this.state.data.deaths.forEach((death) => {
        const secIntoFight = Math.floor((death.timestamp - start) / 1000);

        if (death.targetIsFriendly) {
          deathsBySecond[secIntoFight] = true;
        }
      });
    }

    const fightDurationSec = Math.ceil((end - start) / 1000);
    const labels = [];
    for (let i = 0; i <= fightDurationSec; i += 1) {
      labels.push(i);

      entities.forEach((series) => {
        series.data[i] = series.data[i] !== undefined ? series.data[i] : series.lastValue;
        series.lastValue = series.data[i];
      });
      deathsBySecond[i] = deathsBySecond[i] !== undefined ? deathsBySecond[i] : undefined;
    }

    const chartData = {
      labels,
      datasets: [
        ...entities.map((series, index) => ({
          label: series.name,
          ...ManaStyles['Boss-0'],
          backgroundColor: CLASS_CHART_LINE_COLORS[series.type],
          borderColor: CLASS_CHART_LINE_COLORS[series.type],
          data: Object.keys(series.data).map(key => series.data[key]),
        })),
        {
          label: `Deaths`,
          ...ManaStyles.Deaths,
          data: Object.keys(deathsBySecond).map(key => deathsBySecond[key]),
        },
      ],
    };

    const gridLines = ManaStyles.gridLines;

    const options = {
      responsive: true,
      scales: {
        yAxes: [{
          gridLines: gridLines,
          ticks: {
            callback: (value, index, values) => {
              return `${value}%`;
            },
            min: 0,
            max: 20 * 100,
            fontSize: 14,
          },
          stacked: true,
        }],
        xAxes: [{
          gridLines: gridLines,
          ticks: {
            callback: (value, index, values) => {
              if (value % 30 === 0) {
                return formatDuration(value);
              }
              return null;
            },
            fontSize: 14,
          },
        }],
      },
      animation: {
        duration: 0,
      },
      hover: {
        animationDuration: 0,
      },
      responsiveAnimationDuration: 0,
      tooltips: {
        enabled: false,
      },
      legend: ManaStyles.legend,
    };

    Chart.plugins.register({
      id: 'specialEventIndiactor',
      afterDatasetsDraw: (chart) => {
        const ctx = chart.ctx;

        chart.data.datasets.forEach(function (dataset, i) {
          const meta = chart.getDatasetMeta(i);
          if (dataset.label === 'Deaths' && !meta.hidden) {
            meta.data.forEach(function (element, index) {
              const position = element.tooltipPosition();
              if (!isNaN(position.y)) {
                ctx.strokeStyle = element._view.borderColor;
                ctx.beginPath();
                ctx.lineWidth = ManaStyles.Deaths.borderWidth;
                ctx.moveTo(position.x, chart.chartArea.top);
                ctx.lineTo(position.x, chart.chartArea.bottom);
                ctx.stroke();
              }
            });
          }
        });

      },
    });

    return (

        <Line
          data={chartData}
          options={options}
          width={1100}
          height={400}
        />

    );
  }
}

export default Graph;

<commit_msg>scale chart with group / raid size<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import Chart from 'chart.js';
import { Line } from 'react-chartjs-2';

import fetchWcl from 'common/fetchWclApi';

import ManaStyles from 'Interface/Others/ManaStyles.js';

const formatDuration = (duration) => {
  const seconds = Math.floor(duration % 60);
  return `${Math.floor(duration / 60)}:${seconds < 10 ? `0${seconds}` : seconds}`;
};

const CLASS_CHART_LINE_COLORS = {
  DeathKnight: 'rgba(196, 31, 59, 0.6)',
  Druid: 'rgba(255, 125, 10, 0.6)',
  Hunter: 'rgba(171, 212, 115, 0.6)',
  Mage: 'rgba(105, 204, 240, 0.6)',
  Monk: 'rgba(45, 155, 120, 0.6)',
  Paladin: 'rgba(245, 140, 186, 0.6)',
  Priest: 'rgba(255, 255, 255, 0.6)',
  Rogue: 'rgba(255, 245, 105, 0.6)',
  Shaman: 'rgba(36, 89, 255, 0.6)',
  Warlock: 'rgba(148, 130, 201, 0.6)',
  Warrior: 'rgba(199, 156, 110, 0.6)',
  DemonHunter: 'rgba(163, 48, 201, 0.6)',
};

class Graph extends React.PureComponent {
  static propTypes = {
    reportCode: PropTypes.string.isRequired,
    actorId: PropTypes.number.isRequired,
    start: PropTypes.number.isRequired,
    end: PropTypes.number.isRequired,
  };

  constructor() {
    super();
    this.state = {
      data: null,
    };
  }

  componentWillMount() {
    this.load(this.props.reportCode, this.props.actorId, this.props.start, this.props.end);
  }
  componentWillReceiveProps(newProps) {
    if (newProps.reportCode !== this.props.reportCode || newProps.actorId !== this.props.actorId || newProps.start !== this.props.start || newProps.end !== this.props.end) {
      this.load(newProps.reportCode, newProps.actorId, newProps.start, newProps.end);
    }
  }

  load(reportCode, actorId, start, end) {
    return fetchWcl(`report/tables/resources/${reportCode}`, {
      start,
      end,
      abilityid: 1000,
    })
      .then(json => {
        console.log('Received player health', json);
        this.setState({
          data: json,
        });
      });
  }

  render() {
    const data = this.state.data;
    if (!data) {
      return (

          Loading...

      );
    }

    const { start, end } = this.props;

    const series = data.series;
    const players = series.filter(item => !!CLASS_CHART_LINE_COLORS[item.type]);

    const entities = [];

    players.forEach(series => {
      const newSeries = {
        ...series,
        lastValue: 100, // fights start at full hp
        data: {},
      };

      series.data.forEach((item) => {
        const secIntoFight = Math.floor((item[0] - start) / 1000);

        const health = item[1];
        newSeries.data[secIntoFight] = Math.min(100, health);
      });
      entities.push(newSeries);
    });

    const deathsBySecond = {};
    if (this.state.data.deaths) {
      this.state.data.deaths.forEach((death) => {
        const secIntoFight = Math.floor((death.timestamp - start) / 1000);

        if (death.targetIsFriendly) {
          deathsBySecond[secIntoFight] = true;
        }
      });
    }

    const fightDurationSec = Math.ceil((end - start) / 1000);
    const labels = [];
    for (let i = 0; i <= fightDurationSec; i += 1) {
      labels.push(i);

      entities.forEach((series) => {
        series.data[i] = series.data[i] !== undefined ? series.data[i] : series.lastValue;
        series.lastValue = series.data[i];
      });
      deathsBySecond[i] = deathsBySecond[i] !== undefined ? deathsBySecond[i] : undefined;
    }

    const chartData = {
      labels,
      datasets: [
        ...entities.map((series, index) => ({
          label: series.name,
          ...ManaStyles['Boss-0'],
          backgroundColor: CLASS_CHART_LINE_COLORS[series.type],
          borderColor: CLASS_CHART_LINE_COLORS[series.type],
          data: Object.keys(series.data).map(key => series.data[key]),
        })),
        {
          label: `Deaths`,
          ...ManaStyles.Deaths,
          data: Object.keys(deathsBySecond).map(key => deathsBySecond[key]),
        },
      ],
    };

    const gridLines = ManaStyles.gridLines;

    const options = {
      responsive: true,
      scales: {
        yAxes: [{
          gridLines: gridLines,
          ticks: {
            callback: (value, index, values) => {
              return `${value}%`;
            },
            min: 0,
            max: players.length * 100,
            fontSize: 14,
          },
          stacked: true,
        }],
        xAxes: [{
          gridLines: gridLines,
          ticks: {
            callback: (value, index, values) => {
              if (value % 30 === 0) {
                return formatDuration(value);
              }
              return null;
            },
            fontSize: 14,
          },
        }],
      },
      animation: {
        duration: 0,
      },
      hover: {
        animationDuration: 0,
      },
      responsiveAnimationDuration: 0,
      tooltips: {
        enabled: false,
      },
      legend: ManaStyles.legend,
    };

    Chart.plugins.register({
      id: 'specialEventIndiactor',
      afterDatasetsDraw: (chart) => {
        const ctx = chart.ctx;

        chart.data.datasets.forEach(function (dataset, i) {
          const meta = chart.getDatasetMeta(i);
          if (dataset.label === 'Deaths' && !meta.hidden) {
            meta.data.forEach(function (element, index) {
              const position = element.tooltipPosition();
              if (!isNaN(position.y)) {
                ctx.strokeStyle = element._view.borderColor;
                ctx.beginPath();
                ctx.lineWidth = ManaStyles.Deaths.borderWidth;
                ctx.moveTo(position.x, chart.chartArea.top);
                ctx.lineTo(position.x, chart.chartArea.bottom);
                ctx.stroke();
              }
            });
          }
        });

      },
    });

    return (

        <Line
          data={chartData}
          options={options}
          width={1100}
          height={400}
        />

    );
  }
}

export default Graph;

<|endoftext|>


<commit_before>casper.on('remote.message', function(message) {
    this.echo('Message: '+ JSON.stringify(message));
});

casper.on('page.error', function(message, trace) {
    this.echo('Page error: ' + message);
    this.echo(JSON.stringify(trace));
});

casper.on('page.initialized', function() {
    this.evaluate(function() {
        if (!Function.prototype.bind) {
            Function.prototype.bind = function(oThis) {
                if (typeof this !== 'function') {
                    // closest thing possible to the ECMAScript 5
                    // internal IsCallable function
                    throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
                }

                var aArgs   = Array.prototype.slice.call(arguments, 1),
                    fToBind = this,
                    fNOP    = function() {},
                    fBound  = function() {
                        return fToBind.apply(this instanceof fNOP
                                             ? this
                                             : oThis,
                                             aArgs.concat(Array.prototype.slice.call(arguments)));
                    };

                if (this.prototype) {
                    // native functions don't have a prototype
                    fNOP.prototype = this.prototype;
                }
                fBound.prototype = new fNOP();

                return fBound;
            };
        }
        console.log("RegExp.prototype.bind has been polyfilled");
    });
});

casper.test.begin('Test the project-m-staging', 19, function suite(test) {
    casper.start('https://project-m-staging.herokuapp.com/', function() {
        test.assertTitle("Pirate Party Membership");
        var js = this.evaluate(function() {
            return document;
        });
        this.echo('Here is the DOM: ' + js.all[0].outerHTML);
    });

    casper.then(function () {
        test.assertSelectorHasText('h1.form-title', 'Membership Type');  //find the title
    });

    casper.then(function () {
        //test for not enrolled Australian citizen to vote in Australia
        this.click('input[name="isEnrolled"][value="No"]');
        this.click('input[name="residentialStatus"][value="I am an Australian citizen."]');
        this.click('input[name="isMemberOfOtherParty"][value="Yes"]');

        test.assertExist('div.validationErrors');
    });

     // test for supporter membership type
    casper.then(function() {
        this.click('input[name="isEnrolled"][value="Yes"]');

        test.assertExist('div.info-box');
        test.assertSelectorHasText('h3', 'You are entitled to a Supporter Membership.');
    });

    casper.then(function() {
        this.click('input[name="isEnrolled"][value="No"]');
        this.click('input[name="residentialStatus"][value="I have a Permanent Resident visa."]');

        test.assertExist('div.info-box');
        test.assertSelectorHasText('h3', 'You are entitled to a Supporter Membership.');
    });

    //test for full membership type
    casper.then(function() {
        this.click('input[name="isEnrolled"][value="Yes"]');
        this.click('input[name="residentialStatus"][value="I am an Australian citizen."]');
        this.click('input[name="isMemberOfOtherParty"][value="No"]');

        test.assertExist('div.info-box');
        test.assertSelectorHasText('h3', 'You are entitled to a Full Membership.');
    });

    //test for permanent resident membership type
    casper.then(function() {
       this.click('input[name="isEnrolled"][value="No"]');
       this.click('input[name="residentialStatus"][value="I have a Permanent Resident visa."]');

       test.assertExist('div.info-box');
       test.assertSelectorHasText('h3', 'You are entitled to a Permanent Resident Membership.');
    });

    //test for international membership type
    casper.then(function() {
       this.click('input[name="residentialStatus"][value="I am an international citizen or have a Temporary visa."]');

       test.assertExist('div.info-box');
       test.assertSelectorHasText('h3', 'You are entitled to an International Membership.');
    });

    casper.then(function() {
       this.click('input[name="isMemberOfOtherParty"][value="No"]');

       test.assertExist('div.info-box');
       test.assertSelectorHasText('h3', 'You are entitled to an International Membership.');
    });

    //test for jump to second page
    casper.then(function() {
        this.click('button');
        casper.then(function() {
            test.assertSelectorHasText('h1.form-title', 'Details');
        });
    });

// Details page tests

    //Residential Address = Postal Address

    casper.then(function() {
      this.sendKeys('input[id=firstName]', 'Connor');
      this.sendKeys('input[id=lastName]', 'Melbourne');
      this.sendKeys('input[id=dateOfBirth]', '12/08/2014');
      this.sendKeys('input[id="residentialAddress[address]"]', 'Laboriosam at inventore unde quo iure adipisicing ut voluptas sed soluta ut');
      this.sendKeys('input[id="residentialAddress[suburb]"]', 'Incidunt modi necessitatibus rem vitae modi eiusmod voluptatem numquam corporis laboriosam consequatur Eos reprehenderit');
      this.evaluate(function () {
        return document.getElementById("residentialAddress[country]").selectedIndex = 38;
      });

      this.evaluate(function () {
        return document.getElementById("residentialAddress[state]").selectedIndex = 1;
      });

      this.sendKeys('input[id="residentialAddress[postcode]"]', '35191');
      this.sendKeys('input[id=email]', 'qoku@gmail.com');
      this.sendKeys('input[id=primaryPhoneNumber]', '0412345678');

      //jump to the Confirm page
      this.click('button');

      casper.then(function() {
          this.capture('screenshots/screenshot-click.png');
          test.assertSelectorHasText('h1.form-title', 'Confirm');
      });

     //go back to the Details page

      casper.then(function() {
           this.click('a#go-back');
           test.assertSelectorHasText('h1.form-title', 'Details');
      });

    //check the postal address not same as residential address

    casper.then(function() {
           this.click('input[type="checkbox"]', 'Yes');
    });
    //fill in the postal address
    casper.then(function() {
      this.evaluate(function () {
        return document.getElementById("residentialAddress[country]").selectedIndex = 38;
      });

      this.evaluate(function () {
        return document.getElementById("residentialAddress[state]").selectedIndex = 1;
      });
      this.sendKeys('input[id="postalAddress"]', '1 Margaret Street');
      this.sendKeys('input[id="postalAddress[suburb]"]', 'Cambridge');
      this.evaluate(function () {
        return document.getElementById("postalAddress[country]").selectedIndex = 13;
      });
      this.evaluate(function () {
        return document.getElementById("postalAddress[state]").selectedIndex = 7;
      });
      this.sendKeys('input[id="postalAddress[postcode]"]', '3001');

      this.click('button');

      casper.then(function() {
          this.capture('screenshots/screenshot-click.png');
          test.assertSelectorHasText('h1.form-title', 'Confirm');
      });
    });
    });

    casper.run(function () {
        test.done();
    });
});
<commit_msg>added Confirm page tests to acceptance test<commit_after>casper.on('remote.message', function(message) {
    this.echo('Message: '+ JSON.stringify(message));
});

casper.on('page.error', function(message, trace) {
    this.echo('Page error: ' + message);
    this.echo(JSON.stringify(trace));
});

casper.on('page.initialized', function() {
    this.evaluate(function() {
        if (!Function.prototype.bind) {
            Function.prototype.bind = function(oThis) {
                if (typeof this !== 'function') {
                    // closest thing possible to the ECMAScript 5
                    // internal IsCallable function
                    throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
                }

                var aArgs   = Array.prototype.slice.call(arguments, 1),
                    fToBind = this,
                    fNOP    = function() {},
                    fBound  = function() {
                        return fToBind.apply(this instanceof fNOP
                                             ? this
                                             : oThis,
                                             aArgs.concat(Array.prototype.slice.call(arguments)));
                    };

                if (this.prototype) {
                    // native functions don't have a prototype
                    fNOP.prototype = this.prototype;
                }
                fBound.prototype = new fNOP();

                return fBound;
            };
        }
        console.log("RegExp.prototype.bind has been polyfilled");
    });
});

casper.test.begin('Test the project-m-staging', 20, function suite(test) {
    casper.start('https://project-m-staging.herokuapp.com/', function() {
        test.assertTitle("Pirate Party Membership");
        var js = this.evaluate(function() {
            return document;
        });
        this.echo('Here is the DOM: ' + js.all[0].outerHTML);
    });

    casper.then(function () {
        test.assertSelectorHasText('h1.form-title', 'Membership Type');  //find the title
    });

    casper.then(function () {
        //test for not enrolled Australian citizen to vote in Australia
        this.click('input[name="isEnrolled"][value="No"]');
        this.click('input[name="residentialStatus"][value="I am an Australian citizen."]');
        this.click('input[name="isMemberOfOtherParty"][value="Yes"]');

        test.assertExist('div.validationErrors');
    });

     // test for supporter membership type
    casper.then(function() {
        this.click('input[name="isEnrolled"][value="Yes"]');

        test.assertExist('div.info-box');
        test.assertSelectorHasText('h3', 'You are entitled to a Supporter Membership.');
    });

    casper.then(function() {
        this.click('input[name="isEnrolled"][value="No"]');
        this.click('input[name="residentialStatus"][value="I have a Permanent Resident visa."]');

        test.assertExist('div.info-box');
        test.assertSelectorHasText('h3', 'You are entitled to a Supporter Membership.');
    });

    //test for full membership type
    casper.then(function() {
        this.click('input[name="isEnrolled"][value="Yes"]');
        this.click('input[name="residentialStatus"][value="I am an Australian citizen."]');
        this.click('input[name="isMemberOfOtherParty"][value="No"]');

        test.assertExist('div.info-box');
        test.assertSelectorHasText('h3', 'You are entitled to a Full Membership.');
    });

    //test for permanent resident membership type
    casper.then(function() {
       this.click('input[name="isEnrolled"][value="No"]');
       this.click('input[name="residentialStatus"][value="I have a Permanent Resident visa."]');

       test.assertExist('div.info-box');
       test.assertSelectorHasText('h3', 'You are entitled to a Permanent Resident Membership.');
    });

    //test for international membership type
    casper.then(function() {
       this.click('input[name="residentialStatus"][value="I am an international citizen or have a Temporary visa."]');

       test.assertExist('div.info-box');
       test.assertSelectorHasText('h3', 'You are entitled to an International Membership.');
    });

    casper.then(function() {
       this.click('input[name="isMemberOfOtherParty"][value="No"]');

       test.assertExist('div.info-box');
       test.assertSelectorHasText('h3', 'You are entitled to an International Membership.');
    });

    //test for jump to second page
    casper.then(function() {
        this.click('button');
        casper.then(function() {
            test.assertSelectorHasText('h1.form-title', 'Details');
        });
    });

// Details page tests

    //Residential Address = Postal Address

    casper.then(function() {
      this.sendKeys('input[id=firstName]', 'Connor');
      this.sendKeys('input[id=lastName]', 'Melbourne');
      this.sendKeys('input[id=dateOfBirth]', '12/08/2014');
      this.sendKeys('input[id="residentialAddress[address]"]', 'Laboriosam at inventore unde quo iure adipisicing ut voluptas sed soluta ut');
      this.sendKeys('input[id="residentialAddress[suburb]"]', 'Incidunt modi necessitatibus rem vitae modi eiusmod voluptatem numquam corporis laboriosam consequatur Eos reprehenderit');
      this.evaluate(function () {
        return document.getElementById("residentialAddress[country]").selectedIndex = 38;
      });

      this.evaluate(function () {
        return document.getElementById("residentialAddress[state]").selectedIndex = 1;
      });

      this.sendKeys('input[id="residentialAddress[postcode]"]', '35191');
      this.sendKeys('input[id=email]', 'qoku17@gmail.com');
      this.sendKeys('input[id=primaryPhoneNumber]', '0412345678');

      //jump to the Confirm page
      this.click('button');

      casper.then(function() {
          this.capture('screenshots/screenshot-click.png');
          test.assertSelectorHasText('h1.form-title', 'Confirm');
      });
    });
     //go back to the Details page

      casper.then(function() {
           this.click('a#go-back');
           test.assertSelectorHasText('h1.form-title', 'Details');
      });

    //check the postal address not same as residential address

    casper.then(function() {
           this.click('input[type="checkbox"]', 'Yes');
    });
    //fill in the postal address

    casper.then(function() {
      this.evaluate(function () {
        return document.getElementById("residentialAddress[country]").selectedIndex = 38;
      });

      this.evaluate(function () {
        return document.getElementById("residentialAddress[state]").selectedIndex = 1;
      });
      this.sendKeys('input[id="postalAddress"]', '1 Margaret Street');
      this.sendKeys('input[id="postalAddress[suburb]"]', 'Cambridge');
      this.evaluate(function () {
        return document.getElementById("postalAddress[country]").selectedIndex = 13;
      });
      this.evaluate(function () {
        return document.getElementById("postalAddress[state]").selectedIndex = 7;
      });
      this.sendKeys('input[id="postalAddress[postcode]"]', '3001');

      this.click('button');

      casper.then(function() {
          this.capture('screenshots/screenshot-click.png');
          test.assertSelectorHasText('h1.form-title', 'Confirm');
      });
    });

    // Confirm page tests

    casper.then(function() {
        this.click('input[type="checkbox"]', 'circumstance');

        this.click('button');

      casper.then(function() {
        this.wait(1000,function() {

        this.capture('screenshots/screenshot-click.png');
        test.assertSelectorHasText('h1.form-title', 'Pay What You Want');
        });
      });
    });

    casper.run(function () {
        test.done();
    });

});
<|endoftext|>


<commit_before>(function (exports) {
    exports.loadTabPickers = function ($scope) {
        $scope.scannedCode = '';
        if ($scope.ready) {
            $scope.stopPicker();
        } else {
            document.addEventListener('deviceready', $scope.stopPicker);
        }
        var pickers = document.getElementById("pickerchoices");
        pickers.children[0].onclick = function () { customPicker(0, 0, 0, 0); };
        pickers.children[1].onclick = function () { customPicker(40, 40, 40, 40); };
        pickers.children[2].onclick = function () { customPicker(40, 0, 40, 0); };
        pickers.children[3].onclick = function () { customPicker(1, 60, 1, 60); };
    }

    exports.pickerOpen = false;
    exports.canClose = false;

    exports.customPicker = function (marginLeft, marginTop, marginRight, marginBottom) {
        if (pickerOpen) {
	    return;
	}
        var scope = angular.element(document.body).scope();
        scope.$apply(function () {
            scope.setMargin(marginLeft, marginTop, marginRight, marginBottom);
            scope.setLandscapeMargin(marginLeft, marginTop, marginRight, marginBottom);
            scope.startPicker();

            scope.setCallback(function (session, manual) {
                if (manual) {
                    scope.scannedCode = session;
                } else {
                    var code = session.newlyRecognizedCodes[0];
                    scope.scannedCode = '(' + code.symbology.toUpperCase() + ') ' + code.data;
                }
                scope.stopPicker();
                scope.$digest();
            });
        });

	if (marginLeft > 0 || marginTop > 0 || marginRight > 0 || marginBottom > 0) {
	    pickerOpen = true;
            var buttons = document.getElementById("pickerchoices");
            for (i = 0; i < buttons.length; i++) {
                buttons[i].disabled = true;
            }
	    setTimeout(function(){canClose = true}, 2000);
	}
    }

    exports.hide = function () {
	if(canClose) {
	    var scope = angular.element(document.body).scope();
            scope.$apply(function () {
                scope.stopPicker();
	    });
	    pickerOpen = false;
	    canClose = false;
	}
    }
})(this);
<commit_msg>some more fixes for the extended sample on windows<commit_after>(function (exports) {

    exports.pickerOpen = false;
    exports.canClose = false;

    exports.loadTabPickers = function ($scope) {
        $scope.scannedCode = '';
        if ($scope.ready) {
            $scope.stopPicker();
            exports.pickerOpen = false;
        } else {
            document.addEventListener('deviceready', function () {
                $scope.stopPicker();
                exports.pickerOpen = false;
            });
        }
        var pickers = document.getElementById("pickerchoices");
        pickers.children[0].onclick = function () { customPicker(0, 0, 0, 0); };
        pickers.children[1].onclick = function () { customPicker(40, 40, 40, 40); };
        pickers.children[2].onclick = function () { customPicker(40, 0, 40, 0); };
        pickers.children[3].onclick = function () { customPicker(1, 60, 1, 60); };
    }

    exports.customPicker = function (marginLeft, marginTop, marginRight, marginBottom) {
        if (exports.pickerOpen) {
	        return;
	    }
        var scope = angular.element(document.body).scope();
        scope.$apply(function () {
            scope.setMargin(marginLeft, marginTop, marginRight, marginBottom);
            scope.setLandscapeMargin(marginLeft, marginTop, marginRight, marginBottom);
            scope.startPicker();

            scope.setCallback(function (session, manual) {
                if (manual) {
                    scope.scannedCode = session;
                } else {
                    var code = session.newlyRecognizedCodes[0];
                    scope.scannedCode = '(' + code.symbology.toUpperCase() + ') ' + code.data;
                }
                scope.stopPicker();
                scope.$digest();
            });
        });

	    if (marginLeft > 0 || marginTop > 0 || marginRight > 0 || marginBottom > 0) {
	        exports.pickerOpen = true;
            var buttons = document.getElementById("pickerchoices");
            for (i = 0; i < buttons.length; i++) {
                buttons[i].disabled = true;
            }
            setTimeout(function () {
                exports.canClose = true
            }, 2000);
	    }
    }

    exports.hide = function () {
	    if(exports.canClose) {
	        var scope = angular.element(document.body).scope();
                scope.$apply(function () {
                    scope.stopPicker();
	        });
	        exports.pickerOpen = false;
	        exports.canClose = false;
	    }
    }
})(this);
<|endoftext|>


<commit_before>import React, {Component, PropTypes} from 'react'

class VisualizationName extends Component {
  constructor(props) {
    super(props)
  }

  handleInputBlur = e => {
    this.props.onCellRename(e.target.value)
  }

  render() {
    const {defaultName} = this.props

    return (

        <input
          type="text"
          className="form-control input-md"
          defaultValue={defaultName}
          onBlur={this.handleInputBlur}
          placeholder="Name this Cell..."
        />

    )
  }
}

const {string, func} = PropTypes

VisualizationName.propTypes = {
  defaultName: string.isRequired,
  onCellRename: func,
}

export default VisualizationName
<commit_msg>Use enter and escape to stage changes to the cell name<commit_after>import React, {Component, PropTypes} from 'react'

class VisualizationName extends Component {
  constructor(props) {
    super(props)

    this.state = {
      reset: false,
    }
  }

  handleInputBlur = reset => e => {
    console.log(reset, this.props.defaultName)
    this.props.onCellRename(reset ? this.props.defaultName : e.target.value)
    this.setState({reset: false})
  }

  handleKeyDown = e => {
    if (e.key === 'Enter') {
      this.inputRef.blur()
    }
    if (e.key === 'Escape') {
      this.inputRef.value = this.props.defaultName
      this.setState({reset: true}, () => this.inputRef.blur())
    }
  }

  render() {
    const {defaultName} = this.props
    const {reset} = this.state

    return (

        <input
          type="text"
          className="form-control input-md"
          defaultValue={defaultName}
          onBlur={this.handleInputBlur(reset)}
          onKeyDown={this.handleKeyDown}
          placeholder="Name this Cell..."
          ref={r => (this.inputRef = r)}
        />

    )
  }
}

const {string, func} = PropTypes

VisualizationName.propTypes = {
  defaultName: string.isRequired,
  onCellRename: func,
}

export default VisualizationName
<|endoftext|>