text
stringlengths
7
3.69M
const fs = require('fs'); const globby = require('globby'); const yazl = require('yazl'); const {getDestDir} = require('./paths'); const {createTask} = require('./task'); function archiveFiles({files, dest, cwd}) { return new Promise((resolve) => { const archive = new yazl.ZipFile(); files.forEach((file) => archive.addFile(file, file.startsWith(`${cwd}/`) ? file.substring(cwd.length + 1) : file)); archive.outputStream.pipe(fs.createWriteStream(dest)).on('close', () => resolve()); archive.end(); }); } async function archiveDirectory({dir, dest}) { const files = await globby(`${dir}/**/*.*`); await archiveFiles({files, dest, cwd: dir}); } async function zip({production}) { const dir = getDestDir({production}); const firefoxDir = getDestDir({production, firefox: true}); await archiveDirectory({dir, dest: 'build.zip'}); await archiveDirectory({dir: firefoxDir, dest: 'build-firefox.xpi'}); } module.exports = createTask( 'zip', zip, );
const { User } = require('../models'); // import the User model const userController = { // get all users getAllUser(req,res) { User.find({}) .then(dbUserData => res.json(dbUserData)) .catch(err=> { console.log(err); res.status(400).json(err); }); }, // get a single user by its _id and populated thought and friend data getUserById({params}, res) { User.findOne({_id:params.id}) .populate({ path:'thoughts' // select:'- __v' }) .populate({ path:'friends' }) .then(dbUserData => { if(!dbUserData){ res.status(404).json({message: 'No user found with this id!'}); return; } res.json(dbUserData); }) .catch(err=> { console.log(err); res.status(400).json(err); }); }, // create a new user createUser({body},res) { User.create(body) .then(dbUserData => res.json(dbUserData)) .catch(err => res.status(400).json(err)); }, // update user by id updateUser({params,body}, res){ User.findOneAndUpdate({_id:params.id}, body, {new:true, runvalidators:true}) .then(dbUserData => { if(!dbUserData){ res.status(404).json({message:'No user found with this id!'}); return; } res.json(dbUserData); }) .catch(err => res.status(400).json(err)); }, // delete a user deleteUser({params}, res){ User.findOneAndDelete({_id:params.id}) .then(dbUserData => { if(!dbUserData){ res.status(404).json({message: 'No user found with this id!'}); return; } res.json(dbUserData); }) .catch(err=>res.status(400).json(err)); }, // add a friend by Id addFriendById({params},res){ User.findOneAndUpdate( {_id: params.userId}, {$push:{friends:params.friendId}}, {new:true, runValidators:true} ) .then(dbUserData => { if(!dbUserData){ return res.status(404).json({message: 'No user with this id!'}); } res.json(dbUserData); }) .catch(err=>{ console.log(err); res.status(500).json(err); }); }, // remove a friend by Id deleteFriendById({params},res){ User.findOneAndUpdate( {_id: params.userId}, {$pull:{friends:params.friendId}}, {new:true} ) .then(dbUserData => res.json(dbUserData)) .catch(err => res.json(err)); } }; module.exports = userController;
/** *Ajax request to logout, *Sends to functions.php *Buttontype specifies request */ function logout() { var postreq = new XMLHttpRequest(); postreq.onreadystatechange = function() { if (postreq.readyState == 4) { if (postreq.status == 200 || window.location.href.indexOf("http") == -1) { location.reload(); } else { alert("An error has occured making the request"); } } } var buttontypeval = encodeURIComponent("logout"); var parameters = "buttontype=" + buttontypeval; postreq.open("POST", "http://www.alanguagebank.com/employeecenter/functions.php", true); postreq.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); postreq.send(parameters); } //Returns the width of browser window. function checkWidth() { var windowsize = $(window).width(); return windowsize; } /* *When called and given json from google sheets, returns the JSON in a much easier to use format, *row 1 titles must match the gsx values. */ function organizeJson() { var projectCount = 0; //Counter to find out how many projects we have. var projectJson; //variable to hold our finished JSON // Set the global configs to synchronous. $.ajaxSetup({ async: false }); //Sheets Url for projects. var JSONURL = 'https://spreadsheets.google.com/feeds/list/1MczO1YTq2FGCgaShFOwQUJfN0gRkafK_4ze6mXYB-iY/1/public/values?alt=json'; //Retrieve our JSON. $.getJSON(JSONURL, function(data) { var cells = data.feed.entry; //Our data var obj = '{ "projects": ['; //Obj will store our organized JSON. //For each row in our sheet we organize the content. $(cells).each(function() { //Count our projects. projectCount++; obj += ' { "project":' + JSON.stringify(this.gsx$project.$t) + ' , "title":' + JSON.stringify(this.gsx$title.$t) + ' , "description":' + JSON.stringify(this.gsx$description.$t) + ' , "department":' + JSON.stringify(this.gsx$department.$t) + ' , "turnaround":' + JSON.stringify(this.gsx$turnaround.$t) + ' , "active":' + JSON.stringify(this.gsx$active.$t) + ' , "startBy":' + JSON.stringify(this.gsx$startby.$t) + ' , "holdStart":' + JSON.stringify(this.gsx$holdstart.$t) + ' , "holdEnd":' + JSON.stringify(this.gsx$holdend.$t) + ' , "start":' + JSON.stringify(this.gsx$start.$t) + ' , "end":' + JSON.stringify(this.gsx$end.$t) + ' , "extensionDate":' + JSON.stringify(this.gsx$extensiondate.$t) + ' , "completionDate":' + JSON.stringify(this.gsx$completiondate.$t) + ' , "leader":' + JSON.stringify(this.gsx$leader.$t) + ' , "member1":' + JSON.stringify(this.gsx$member1.$t) + ' , "member2":' + JSON.stringify(this.gsx$member2.$t) + ' , "member3":' + JSON.stringify(this.gsx$member3.$t) + ' , "member4":' + JSON.stringify(this.gsx$member4.$t) + ' , "member5":' + JSON.stringify(this.gsx$member5.$t) + ' , "member6":' + JSON.stringify(this.gsx$member6.$t) + ' , "member7":' + JSON.stringify(this.gsx$member7.$t) + " }, "; }); //Remove the extra space and comma at end. obj = obj.substring(0, obj.length - 2); //Close Obj obj += " ]}"; //Parse JSON, put data in variable. projectJson = JSON.parse(obj); }); // Set the global configs back to asynchronous. $.ajaxSetup({ async: true }); // Return our finished JSON and Project Count. return { projectJson: projectJson, projectCount: projectCount }; } /* *When called and given json from google sheets, returns the JSON in a much easier to use format, *row 1 titles must match the gsx values. */ function employeeJson() { var employeeCount = 0; //Counter for amount of current employees in chart var employeeJson; //variable for current employee JSON data var oldEmployeeCount = 0; //Counter for amount of past employees in chart var oldEmployeeJson; //variable for past employee JSON data // Set the global configs to synchronous. $.ajaxSetup({ async: false }); //Sheets Url for projects. var JSONURL = 'https://spreadsheets.google.com/feeds/list/1MczO1YTq2FGCgaShFOwQUJfN0gRkafK_4ze6mXYB-iY/2/public/values?alt=json'; //Retrieve our JSON. $.getJSON(JSONURL, function(data) { var cells = data.feed.entry; //Our data var obj = '{ "employees": ['; //Obj will store our organized JSON. //For each row in our sheet we organize the content. $(cells).each(function() { if (this.gsx$employees.$t.length != 0) { //Count our employees. employeeCount++; obj += JSON.stringify(this.gsx$employees.$t) + ", "; } }); //Remove the extra space and comma at end. obj = obj.substring(0, obj.length - 2); //Close Obj obj += " ]}"; //Parse JSON, put data in variable. employeeJson = JSON.parse(obj); var obj = '{ "past_employees": ['; //Obj will store our organized JSON. $(cells).each(function() { if (this.gsx$pastemployees.$t.length != 0) { //Count our past employees. oldEmployeeCount++; obj += JSON.stringify(this.gsx$pastemployees.$t) + ", "; } }); //Remove the extra space and comma at end. obj = obj.substring(0, obj.length - 2); //Close Obj obj += " ]}"; //Parse JSON, put data in variable. oldEmployeeJson = JSON.parse(obj); }); // Set the global configs back to asynchronous. $.ajaxSetup({ async: true }); // Return our finished JSON and Project Count. return { employeeJson: employeeJson, employeeCount: employeeCount, oldEmployeeJson: oldEmployeeJson, oldEmployeeCount: oldEmployeeCount }; } function createProjectpanels(x, y) { var projectJson = x; //Json data var projectCount = y; //Amount of Projects. var counterPanels = 0; //Counter for panels examined for creation. var activePanels = 0; //Count for Panels created. var counterTabs = 0; //Counter for tabs examined for creation. var panelsperRow = 3; //Panels allowed in each row. var rows = 0; //How many rows of panels we created. var content = ""; //String of Html to be inserted on page. var mailTo = ""; //Strings that decide var mailCc = ""; //who will be var mailSubLead = ""; //mailed, var mailSubHelp = ""; //what the subjects, var mailLead = ""; //and mail content var mailHelp = ""; //will be. //Create our project content based on projectCount while (counterPanels < projectCount) { if (projectJson.projects[counterPanels].active.toLowerCase() == "true") { //Build panels for each project. content += '<a class="projectTabs proj' + (counterPanels + 1) + ' opens" href="#"><p class="projectTitle">' + projectJson.projects[counterPanels].title + '</p>'; //Check if there is a required start date, if so add it to panel. if (projectJson.projects[counterPanels].startBy) { content += '<p class="startBy">Must Start By: ' + projectJson.projects[counterPanels].startBy + '</p>'; } //Close panels. content += '</a>'; //Increment for each panel made. activePanels++; } //If the amount of panels we created are divisible by panels needed in a row, create the tabs for those panels. if ((activePanels) % panelsperRow === 0 || counterPanels + 1 === projectCount) { content += '<br>'; rows++; //Make tabs until we are caught up to panels in count. while (counterTabs <= counterPanels) { if (projectJson.projects[counterTabs].active.toLowerCase() == "true") { //Build content for our tabs. content += '<div class = "projectTabs proj' + (counterTabs + 1) + ' projectInfoTabs hideTab"><p class = "projectName" >' + projectJson.projects[counterTabs].title + '</p><p class="projectDescription">' + projectJson.projects[counterTabs].description + '</p><div><p class="projectType">' + projectJson.projects[counterTabs].department + '</p><p class="projectLength">' + projectJson.projects[counterTabs].turnaround + ' weeks</p>'; //If there is a start date, add it. if (projectJson.projects[counterTabs].startBy) { content += '<p class="projectStart">Start by: ' + projectJson.projects[counterTabs].startBy + '</p>'; } //Finish tabs. content += '</div>'; //Fill out variables, like who to mail to and what the subject/ message should be. mailTo = "Chrisc@alanguagebank.com"; mailCc = "Angeloc@alanguagebank.com"; mailSubLead = "I would like to lead a project!"; mailSubHelp = "I would like to help with a project!"; mailLead = "I would like to lead the project " + projectJson.projects[counterTabs].title + "."; mailHelp = "I would like to help with the project " + projectJson.projects[counterTabs].title + "."; //Add mail content/buttons. content += '<a class="mailto'; //Check if the leader button should be usable or not. if (projectJson.projects[counterTabs].leader) { content += ' beinglead'; } //More mail. content += '" href="mailto:' + mailTo + '?cc=' + mailCc + '&subject=' + escape(mailSubLead) + '&body=' + escape(mailLead) + '">Lead</a><a class="mailto'; /* //Check if status is full, if so make help button unusable too. if (projectJson.projects[counterTabs].full.toLowerCase() == "true") { content += ' beinglead' }*/ //Finish mail. content += '" href="mailto:' + mailTo + '?cc=' + mailCc + '&subject=' + escape(mailSubHelp) + '&body=' + escape(mailHelp) + '">Help</a></div>'; } //Increment for each tab made. counterTabs++; } //Add a line break after each tab. content += '<br>'; } //Increment for each project attempted to create. counterPanels++; } //Add our finished project content to the page. $('div.collapsible-panels.projects').css('min-height', rows * 200 + 500 + 'px'); $('div.collapsible-panels.projects').html(content); } function createProjectgantt(x, y) { var projectJson = x; //Json data var projectCount = y; //Amount of Projects. var counterProject = 0; //Count projects examined. var counterActive = 0; //Count projects active. var endDate = 0; //Latest end date var startDate = 0; //Earliest start date var dateVar = 0; //placeholder variable for var activeProjects = new Array(); //Store active projects. var activeMembers = new Array(); //Store active Members on projects. var shownMembers = new Array(); //Array for members currently supposed to be displayed. var chartData = new Array(); //Data used to build chart. var chartStructure = new Array(); //Data for chart structure. var endDateArray = new Array(); //End dates for active projects var i; //Counter for 'for' loop. var structureCounter = 0; var teamMembers = ""; //Project team members in string format for balloontext. var overdueStart = ""; //String representing start of overdue for balloontext. var overdueEnd = ""; //String representing end of overdue for balloontext. var displayedProj = 0; //Int var to check if a project as any members that are displayed. var chartDivHeight = 0; //get shownMembers shownMembers = employeesShown(); //Find out which of our projects are active, who is working on them, and earliest project start and end dates. while (counterProject < projectCount) { displayedProj = 0; //If a project has a start and end date it has begun. if (projectJson.projects[counterProject].start && projectJson.projects[counterProject].end) { if (contains(shownMembers, projectJson.projects[counterProject].leader)) { displayedProj = 1; //check if leader is listed in activeMember array, if not push them into the array. if (!contains(activeMembers, projectJson.projects[counterProject].leader) && projectJson.projects[counterProject].leader) { activeMembers.push(projectJson.projects[counterProject].leader); } } //check if member is listed in activeMember array, if not push them into the array. for (i = 1; i < 7; i++) { var memberNumber = "member" + i; if (contains(shownMembers, projectJson.projects[counterProject][memberNumber])) { displayedProj = 1; if (!contains(activeMembers, projectJson.projects[counterProject][memberNumber]) && projectJson.projects[counterProject][memberNumber]) { activeMembers.push(projectJson.projects[counterProject][memberNumber]); } } } //Check if those in activeMembers should be displayed. if (displayedProj === 1) { //Find the earliest date by comparing the date from the current activeProject to our current earliest date. dateVar = Date.parse(projectJson.projects[counterProject].start); if (startDate == 0 || Date.compare(dateVar, startDate) == -1) { startDate = dateVar; } //Find the latest date for the project based on completion, hold, extension, or current day. dateVar = Date.parse(projectJson.projects[counterProject].end); if (projectJson.projects[counterProject].extensionDate && Date.parse(projectJson.projects[counterProject].extensionDate) > dateVar) { dateVar = Date.parse(projectJson.projects[counterProject].extensionDate); } if (projectJson.projects[counterProject].holdEnd && Date.parse(projectJson.projects[counterProject].holdEnd) > dateVar) { dateVar = Date.parse(projectJson.projects[counterProject].holdEnd); } if (projectJson.projects[counterProject].completionDate) { if (Date.parse(projectJson.projects[counterProject].completionDate) > dateVar) { dateVar = Date.parse(projectJson.projects[counterProject].completionDate); } } else { if (Date.parse(Date.today()) > dateVar) { dateVar = Date.parse(Date.today()); } } if (endDate == 0 || Date.compare(dateVar, endDate) == 1) { endDate = dateVar; } console.log(activeProjects.length); if (activeProjects.length === 0) { alert("t"); endDateArray.push(dateVar); activeProjects.push(projectJson.projects[counterProject]); } else { i = 0; alert(i); alert(activeProjects.length); while (i < activeProjects.length) { alert(dateVar); alert(endDateArray[i]); alert(Date.compare(dateVar, endDateArray[i])); if (Date.compare(dateVar, endDateArray[i]) == -1) { endDateArray.splice(i, 0, dateVar); activeProjects.splice(i, 0, projectJson.projects[counterProject]); //alert("s"); } else { if (i == activeProjects.length-1) { alert("d"); endDateArray.push(dateVar); activeProjects.push(projectJson.projects[counterProject]); } } i++; alert(i); } } //Put active projects into seperate array to work with. // activeProjects.push(projectJson.projects[counterProject]); } } counterProject++; } /* If we have any active projects. Build our chart data, otherwise data will remain empty. */ if (activeProjects.length > 0) { //Create data for each active member. for (j = 0; j < activeMembers.length; j++) { //Add new empty object to data chartData.push({}); //Set name of current object (name of active member) chartData[j].name = activeMembers[j]; //For each active project that the current member is a member or leader of, add data. for (i = 0; i < activeProjects.length; i++) { if (activeMembers[j] == activeProjects[i].leader || activeMembers[j] == activeProjects[i].member1 || activeMembers[j] == activeProjects[i].member2 || activeMembers[j] == activeProjects[i].member3 || activeMembers[j] == activeProjects[i].member4 || activeMembers[j] == activeProjects[i].member5 || activeMembers[j] == activeProjects[i].member6 || activeMembers[j] == activeProjects[i].member7) { /* Record project start and end, and set project color(dark blue or light blue) depending on leader status. */ chartData[j]["startTime" + i] = Date.parse(activeProjects[i].start); chartData[j]["endTime" + i] = Date.parse(activeProjects[i].end); if (Date.parse(activeProjects[i].holdStart) < Date.parse(activeProjects[i].end) && Date.parse(activeProjects[i].holdEnd) > Date.parse(activeProjects[i].end)) { chartData[j]["endTime" + i] = Date.parse(activeProjects[i].holdStart); } if (activeMembers[j] == activeProjects[i].leader) { chartData[j]["color" + i] = "#587CAF"; } else { chartData[j]["color" + i] = "#A6C0E4"; } //Reset overdue Start and End values. overdueStart = ""; overdueEnd = ""; //Record project overdue start and end. //Make sure there isn't a hold without an end. if (!activeProjects[i].holdStart || activeProjects[i].holdEnd) { //Check for a hold that ends after projected end. if (activeProjects[i].holdEnd && Date.parse(activeProjects[i].holdEnd) > Date.parse(activeProjects[i].end)) { //If so set our overdue based on the holdEnd (does not account for possible hold starts after a project is already overdue). if (Date.parse(Date.today()) > Date.parse(activeProjects[i].holdEnd)) { overdueStart = Date.parse(activeProjects[i].holdEnd); overdueEnd = Date.parse(Date.today()); } if (activeProjects[i].completionDate && Date.parse(activeProjects[i].completionDate) > Date.parse(activeProjects[i].holdEnd)) { overdueStart = Date.parse(activeProjects[i].holdEnd); overdueEnd = Date.parse(activeProjects[i].completionDate); } } //Check for extension if (activeProjects[i].extensionDate && Date.parse(activeProjects[i].extensionDate) > Date.parse(activeProjects[i].end)) { //Keep our dates the same unless holdEnd doesn't exist or it ends before the extension does. if (!activeProjects[i].holdEnd || Date.parse(activeProjects[i].holdEnd) < Date.parse(activeProjects[i].extensionDate)) { //Otherwise use extension for our overdue dates. if (Date.parse(Date.today()) > Date.parse(activeProjects[i].extensionDate)) { overdueStart = Date.parse(activeProjects[i].extensionDate); overdueEnd = Date.parse(Date.today()); } if (activeProjects[i].completionDate && Date.parse(activeProjects[i].completionDate) > Date.parse(activeProjects[i].extensionDate)) { overdueStart = Date.parse(activeProjects[i].extensionDate); overdueEnd = Date.parse(activeProjects[i].completionDate); } } } //Check if there is no extension as well as no hold or the hold ends before projected end. if (!Date.parse(activeProjects[i].extensionDate) && (!activeProjects[i].holdEnd || Date.parse(activeProjects[i].holdEnd) < Date.parse(activeProjects[i].end))) { //Set project using projected end. if (Date.parse(Date.today()) > Date.parse(activeProjects[i].end)) { overdueStart = Date.parse(activeProjects[i].end); overdueEnd = Date.parse(Date.today()); } if (activeProjects[i].completionDate && Date.parse(activeProjects[i].completionDate) > Date.parse(activeProjects[i].end)) { overdueEnd = Date.parse(activeProjects[i].completionDate); } } } //Special cases //Hold in the middle of overdue, no extension. Or Hold after overdue, no extension. if (activeProjects[i].holdEnd && Date.parse(activeProjects[i].holdEnd) > Date.parse(activeProjects[i].end) && Date.parse(activeProjects[i].holdStart) > Date.parse(activeProjects[i].end) && !activeProjects[i].extensionDate) { overdueStart = Date.parse(activeProjects[i].end); overdueEnd = Date.parse(activeProjects[i].holdStart); if (Date.parse(Date.today()) > Date.parse(activeProjects[i].holdEnd)) { overdueEnd = Date.parse(Date.today()); } if (activeProjects[i].completionDate && Date.parse(activeProjects[i].completionDate) > Date.parse(activeProjects[i].holdEnd)) { overdueEnd = Date.parse(activeProjects[i].completionDate); } } //Hold in the middle of overdue with extension. Or Hold after overdue with extension. if (activeProjects[i].holdEnd && activeProjects[i].extensionDate && Date.parse(activeProjects[i].holdEnd) > Date.parse(activeProjects[i].extensionDate) && Date.parse(activeProjects[i].holdStart) > Date.parse(activeProjects[i].extensionDate)) { overdueStart = Date.parse(activeProjects[i].extensionDate); overdueEnd = Date.parse(activeProjects[i].holdStart); if (Date.parse(Date.today()) > Date.parse(activeProjects[i].holdEnd)) { overdueEnd = Date.parse(Date.today()); } if (activeProjects[i].completionDate && Date.parse(activeProjects[i].completionDate) > Date.parse(activeProjects[i].holdEnd)) { overdueEnd = Date.parse(activeProjects[i].completionDate); } } //Add to our activeProjects data for later use. activeProjects[i].overdueStart = overdueStart; activeProjects[i].overdueEnd = overdueEnd; //Add to our data chart. chartData[j]["startTimeOverdue" + i] = overdueStart; chartData[j]["endTimeOverdue" + i] = overdueEnd; chartData[j]["colorOverdue" + i] = "#CF4D4D"; /* Record project ext start and end, and set color for extensions. */ //chartData[j]["startTimeExt" + i] = Date.parse(activeProjects[i].end); if (activeProjects[i].extensionDate) { if (activeProjects[i].holdEnd && Date.parse(activeProjects[i].holdEnd) > Date.parse(activeProjects[i].end)) { if (Date.parse(activeProjects[i].extensionDate) > Date.parse(activeProjects[i].holdEnd)) { chartData[j]["startTimeExt" + i] = Date.parse(activeProjects[i].holdEnd); chartData[j]["endTimeExt" + i] = Date.parse(activeProjects[i].extensionDate); } if (Date.parse(activeProjects[i].extensionDate) < Date.parse(activeProjects[i].holdStart)) { chartData[j]["startTimeExt" + i] = Date.parse(activeProjects[i].end); chartData[j]["endTimeExt" + i] = Date.parse(activeProjects[i].extensionDate); } } else { chartData[j]["startTimeExt" + i] = Date.parse(activeProjects[i].end); chartData[j]["endTimeExt" + i] = Date.parse(activeProjects[i].extensionDate); } } chartData[j]["colorExt" + i] = "#8F9194"; /* Record project hold start and end, and set color for hold. End of a hold will be same as todays date unless hold end date is set. */ if (activeProjects[i].holdStart) { chartData[j]["startTimeHold" + i] = Date.parse(activeProjects[i].holdStart); if (activeProjects[i].holdEnd) { chartData[j]["endTimeHold" + i] = Date.parse(activeProjects[i].holdEnd); } else if (activeProjects[i].completionDate) { chartData[j]["endTimeHold" + i] = Date.parse(activeProjects[i].completionDate); activeProjects[i].holdEnd = activeProjects[i].completionDate; } else { chartData[j]["endTimeHold" + i] = Date.parse(Date.today()); activeProjects[i].holdEnd = Date.parse(Date.today()); } } chartData[j]["colorHold" + i] = "#EFE69F"; /* Record project completionDate, and set color for complete. End of a hold will be same as todays date unless hold end date is set. */ if (activeProjects[i].completionDate) { chartData[j]["startTimeCompletion" + i] = Date.parse(activeProjects[i].completionDate); chartData[j]["endTimeCompletion" + i] = Date.parse(activeProjects[i].completionDate).add(1).days(); } chartData[j]["colorComplete" + i] = "#333435"; } } } } //Structure for Completion date portions for (j = 0; j < activeProjects.length; j++) { chartStructure.push({}); if (j == 0) { chartStructure[structureCounter].newStack = true } chartStructure[structureCounter].colorField = "colorComplete" + j; chartStructure[structureCounter].fillAlphas = 1; chartStructure[structureCounter].lineAlpha = 0; chartStructure[structureCounter].openField = "startTimeCompletion" + j; chartStructure[structureCounter].type = "column"; chartStructure[structureCounter].valueField = "endTimeCompletion" + j; chartStructure[structureCounter].id = "AmGraph-Complete" + j; chartStructure[structureCounter].balloonText = "<b>" + activeProjects[j].title + "</b><br>Completed: " + activeProjects[j].completionDate; structureCounter++; } //Structure for on hold portions for (j = 0; j < activeProjects.length; j++) { chartStructure.push({}); if (j == 0) { chartStructure[structureCounter].newStack = true } chartStructure[structureCounter].colorField = "colorHold" + j; chartStructure[structureCounter].fillAlphas = 1; chartStructure[structureCounter].lineAlpha = 0; chartStructure[structureCounter].openField = "startTimeHold" + j; chartStructure[structureCounter].type = "column"; chartStructure[structureCounter].valueField = "endTimeHold" + j; chartStructure[structureCounter].id = "AmGraph-Hold" + j; chartStructure[structureCounter].balloonText = "<b>" + activeProjects[j].title + "</b><br>On Hold from: " + activeProjects[j].holdStart.toString("M/d/yyyy") + "<br>Until: " + activeProjects[j].holdEnd.toString("M/d/yyyy"); structureCounter++; } //Structure for Extensions for (j = 0; j < activeProjects.length; j++) { chartStructure.push({}); if (j == 0) { chartStructure[structureCounter].newStack = true } chartStructure[structureCounter].colorField = "colorExt" + j; chartStructure[structureCounter].fillAlphas = 1; chartStructure[structureCounter].lineAlpha = 0; chartStructure[structureCounter].openField = "startTimeExt" + j; chartStructure[structureCounter].type = "column"; chartStructure[structureCounter].valueField = "endTimeExt" + j; chartStructure[structureCounter].id = "AmGraph-Ext" + j; chartStructure[structureCounter].balloonText = "<b>" + activeProjects[j].title + "</b><br>Extended Until: " + activeProjects[j].extensionDate; structureCounter++; } //Structure for Overdue portions for (j = 0; j < activeProjects.length; j++) { chartStructure.push({}); if (j == 0) { chartStructure[structureCounter].newStack = true } chartStructure[structureCounter].colorField = "colorOverdue" + j; chartStructure[structureCounter].fillAlphas = 1; chartStructure[structureCounter].lineAlpha = 0; chartStructure[structureCounter].openField = "startTimeOverdue" + j; chartStructure[structureCounter].type = "column"; chartStructure[structureCounter].valueField = "endTimeOverdue" + j; chartStructure[structureCounter].id = "AmGraph-Overdue" + j; chartStructure[structureCounter].balloonText = "<b>" + activeProjects[j].title + "</b><br>Overdue from: " + activeProjects[j].overdueStart.toString("M/d/yyyy") + "<br>Until: " + activeProjects[j].overdueEnd.toString("M/d/yyyy"); structureCounter++; } //Structure for regular bars for (j = 0; j < activeProjects.length; j++) { chartStructure.push({}); if (j == 0) { chartStructure[structureCounter].newStack = true } //Build teammember list string. teamMembers = ""; //Ensure String is empty before we start. for (h = 1; h <= 7; h++) { if (activeProjects[j]["member" + h] && h > 1) { teamMembers += ', '; } teamMembers += activeProjects[j]["member" + h]; } chartStructure[structureCounter].colorField = "color" + j; chartStructure[structureCounter].fillAlphas = 1; chartStructure[structureCounter].lineAlpha = 0; chartStructure[structureCounter].openField = "startTime" + j; chartStructure[structureCounter].type = "column"; chartStructure[structureCounter].valueField = "endTime" + j; chartStructure[structureCounter].id = "AmGraph-" + j; chartStructure[structureCounter].balloonText = "<b>" + activeProjects[j].title + "</b><br>Lead By: " + activeProjects[j].leader + "<br>Team members: " + teamMembers + "<br>Begins: " + activeProjects[j].start + "<br>Ends: " + activeProjects[j].end; structureCounter++; } if (Date.parse(startDate) != null) { Date.parse(startDate).add(-14).days(); Date.parse(endDate).add(14).days() } chartDivHeight = activeProjects.length * activeMembers.length * 14; if (chartDivHeight > 500) { $('#chartdiv').css('height', chartDivHeight + 'px'); } AmCharts.useUTC = true; var chart = AmCharts.makeChart("chartdiv", { "type": "serial", "theme": "light", "period": "WW", "dataDateFormat": "MMM-DD-YYYY", // "period": "WW", // "dataDateFormat": "YYYY-MM-DD", // "balloonDateFormat": "JJ:NN", // "startDate": Date.january().first().monday(), "valueAxes": [{ "minimumDate": startDate, "maximumDate": endDate, "type": "date", "minPeriod": "WW", "period": "WW" }], "dataProvider": chartData, "guides": [], "trendLines": [], "allLabels": [], "balloon": {}, "titles": [], "startDuration": 0, "graphs": chartStructure, "rotate": true, //"columnWidth": 1, "categoryField": "name", "categoryAxis": { "gridPosition": "start", "axisAlpha": 0, "gridAlpha": 0.1, "position": "left" }, "export": { "enabled": true } }); } function addClicks() { /** *CODE TO MAKE COLLAPSIBLE PANELS WORK ON CLICK */ //Hide all div containers. $('div.collapsible-panels div').css('display', 'inline-block'); $('div.collapsible-panels div.hideTab').hide(); //Append click event to the a element. $('div.collapsible-panels a.opens').click(function() { //Declare our variables var clickedButton = $(this); //jquery object for the clicked button var collapsibleGroupClass = "." + clickedButton.attr('class').split(' ')[0]; //Class identifier for the clickedbutton's group of buttons and tabs var collapsibleTargetClass = "." + clickedButton.attr('class').split(' ')[1]; //Class identifier for the clickedbutton's tab identifier var targetTab = $("div.collapsible-panels div" + collapsibleGroupClass + collapsibleTargetClass); //Jquery object for targetted Tab var tabbedButton = $("div.collapsible-panels a.tabbed" + collapsibleGroupClass); //Jquery object for tabbed button var openTab = $("div.collapsible-panels div.open" + collapsibleGroupClass); //Jquery object for opened tab var openTargetTab = $("div.collapsible-panels div" + collapsibleGroupClass + collapsibleTargetClass + ".open"); //Jquery object for open targetted tab /** *Stop all previous animations *clear queue of animations *end immediately because new *animation is coming! */ $('div.collapsible-panels div').stop(true, true); //If no tab or only the target tab is open. if (openTab.length == 0 || openTargetTab.length != 0) { //Toggle clicked button to tabbed. clickedButton.toggleClass('tabbed'); //Toggle selected tab and open status. targetTab.first().slideToggle(100).toggleClass('open'); //Else (tab besides our target tab are open) } else { //Toggle tabbed buttons off. tabbedButton.toggleClass('tabbed'); //Toggle clicked button to tabbed. clickedButton.toggleClass('tabbed'); /** *Originally chose closing animation with callback, *however this has issues with fast and repeated clicks. *Tried other options and didn't like how they worked. *Decided upon instantly hide closing tabs and speeding *up all opening animations. */ //Hide open tabs and remove open class. openTab.hide().toggleClass('open'); //Toggle target tab and open status targetTab.first().slideToggle(100).toggleClass('open'); //End if/else statement } //return false to prevent default click event return false; //End click event }); } /** *contains function that searchs for a in array obj *and returns true if found, otherwise returns fals. */ function contains(a, obj) { var i = a.length; while (i--) { if (a[i] === obj) { return true; } } return false; } function employeesShown() { var rows = document.getElementsByName('employees'); var selectedRows = []; for (var i = 0, l = rows.length; i < l; i++) { if (rows[i].checked) { selectedRows.push(rows[i].value); } } if (document.getElementsByName('oldEmployees')[0].checked) { var employeeData = employeeJson(); console.log(employeeData); for (var i = 0, l = employeeData.oldEmployeeCount; i < l; i++) { selectedRows.push(employeeData.oldEmployeeJson.past_employees[i]); } } // alert(rows[3].value); // alert(selectedRows.length); //alert(JSON.stringify(selectedRows)); return selectedRows; } function update() { createProjectgantt(jsonData.projectJson, jsonData.projectCount); } var jsonData; $(document).ready(function() { //checkWidth(); /** *Organize Json, which then builds our project panel content, *and adds appropriate click events GetJSON is asynchronous, *so I have each function call each other to prevent click events *getting added before building content. Order is organizeJson(), *createProjectpanels(), addClicks(). **/ jsonData = organizeJson(); createProjectpanels(jsonData.projectJson, jsonData.projectCount); createProjectgantt(jsonData.projectJson, jsonData.projectCount); //Add click events to everything after content is added addClicks(); //End self-initiating function });
import React from 'react'; import { useState, useEffect, useCallback } from 'react'; import QuantityCounter from 'components/QuantityCounter/QuantityCounter'; import Button from 'components/UI/Button'; import MySelect from 'components/UI/MySelect'; import WithLabel from 'components/WithLabel/WithLabel'; import VertoPrice from 'components/VertoPrice/VertoPrice'; import { ReactComponent as MultiplyIconActive } from 'static/icons/Close_square_active.svg'; import { ReactComponent as MultiplyIconDiactive } from 'static/icons/Close_square_diactive.svg'; import { ReactComponent as IncreaseIcon } from 'static/icons/increase.svg'; import { ReactComponent as DecreaseIcon } from 'static/icons/decrease.svg'; import { ReactComponent as EqualIcon } from 'static/icons/equalIcon.svg'; import { ReactComponent as EquanIconDiactive } from 'static/icons/equal_diactive.svg'; import styles from './_barter-item.module.scss'; import { calcSubPrice } from 'utils/helpers'; const BarterItem = ({ product, list, setBarterItem, index }) => { const [totalPrice, setTotalPrice] = useState(calcSubPrice(product.price, product.quantity)); const [price, setPrice] = useState(product.price); const [quantity, setQuantity] = useState(product.quantity); useEffect(() => { setTotalPrice(calcSubPrice(price, quantity)); }, [product, price, quantity]); const handlePrice = useCallback( (value) => { setPrice(value); setTotalPrice(calcSubPrice(value, quantity)); console.log(calcSubPrice(value, quantity)); }, [product] ); const handleQuantity = useCallback( (value) => { setQuantity(value); setTotalPrice(calcSubPrice(value, price)); }, [product] ); const handleSelectChange = (id) => { setBarterItem(id, index); }; return ( <div className={styles.wrapper}> <WithLabel label="Выберите товар из списка размещенных"> <MySelect bordered={true} dropdownClassName="selector" maxTagTextLengt={40} data={list} onSelect={handleSelectChange} /> </WithLabel> {product.active ? <MultiplyIconActive /> : <MultiplyIconDiactive />} <WithLabel label="Цена за единицу" type="center"> <QuantityCounter controls={true} count={product.price} noLimit={true} onChange={handlePrice} unit={product.price} increaseComponent={ <Button className={styles.btn} type="rounded"> <IncreaseIcon /> </Button> } decreaseComponent={ <Button className={styles.btn} type="rounded"> <DecreaseIcon /> </Button> } /> </WithLabel> {product.active ? <MultiplyIconActive /> : <MultiplyIconDiactive />} <WithLabel label="Кол-во (шт.)" type="center"> <QuantityCounter controls={true} count={product.quantity} onChange={handleQuantity} unit={product.quantity} noLimit={true} increaseComponent={ <Button className={styles.btn} type="rounded"> <IncreaseIcon /> </Button> } decreaseComponent={ <Button className={styles.btn} type="rounded"> <DecreaseIcon /> </Button> } /> </WithLabel> {product.active ? <EqualIcon /> : <EquanIconDiactive />} <WithLabel label="Общая цена"> <VertoPrice price={totalPrice} width="130px" active={product.active} /> </WithLabel> </div> ); }; export default BarterItem;
import React from "react" import { Link } from "gatsby" import { Form, Formik, useField } from "formik" import * as Yup from "yup" import Layout from "../components/layout" import SEO from "../components/seo" import { localizedNavigate } from "../components/LocalizedLink" import { css } from "@emotion/core" import { useTranslation } from "react-i18next" import BtnNext from "../components/BtnNext" import Steps from "../components/Steps" import logoGrey from "../images/logoGrey.png" import ContactForm from "../components/ContactForm" import BtnSendForm from "../components/BtnSendForm" import { sendIndividualEmail } from "../emails" const MyMessageInput = ({ ...props }) => { const [field, meta] = useField(props) return ( <div css={css` width: 100%; display: flex; flex-direction: column; `} > <textarea {...field} {...props} css={css` width: 100%; height: 300px; background: #ffffff; border: 1px solid #d6d6d6; color: #444444; padding: 20px; outline: none; resize: none; ::-webkit-input-placeholder { font-size: 16px; color: #9d9d9d; } :focus { border: 2px solid #c4c4c4; } `} /> {meta.touched && meta.error ? ( <div css={css` width: 141px; height: 35px; background: #a74444; border-radius: 3px; color: white; color: #ffffff; font-size: 12px; line-height: 14px; text-align: center; `} > {meta.error} </div> ) : null} </div> ) } export default props => { const [step, setStep] = React.useState(1) const T = useTranslation() if (T.i18n.language !== props.pageContext.langKey) { T.i18n.changeLanguage(props.pageContext.langKey) } const t = key => (typeof key === "string" ? T.t(key) : key[T.i18n.language]) const steps = [ t("requestType"), t("requestOrderCreate"), t("requestPersonal"), ] return ( <Layout> <SEO title={t("individualOrder")} /> <Link css={css` background: url(${logoGrey}) center center no-repeat; width: 190px; height: 66px; background-size: cover; position: absolute; top: 10px; left: 30px; `} to="/" ></Link> <Steps steps={steps} activeStep={step} /> <h1 css={css` font-weight: 500; font-size: 36px; text-align: center; `} > {t("individualOrder")} </h1> <Formik initialValues={{ message: "", name: "", company: "", city: "", email: "", phone: "", }} validationSchema={Yup.object({ name: Yup.string().required("Required"), email: Yup.string().required("Required"), phone: Yup.string().required("Required"), })} onSubmit={async values => { try { await sendIndividualEmail(values) localizedNavigate("/thanxrequest", props.pageContext.langKey) } catch (e) { alert("Error!") } }} > {({ isSubmitting }) => ( <Form css={css` width: 90vw; max-width: 780px; margin: 0 auto; `} > {step === 1 && ( <> <div css={css` width: 100%; max-width: 780px; margin: 0 auto; font-size: 16px; line-height: 27px; `} > <ul> {t("individualRequestText")} <li>{t("envelopeSize")}</li> <li>{t("paperParam")}</li> <li>{t("windowParam")}</li> <li>{t("printParam")}</li> </ul> </div> <div css={css` width: 100%; max-width: 780px; display: flex; flex-direction: column; `} > <MyMessageInput name="message" type="textarea" placeholder={t("placeholderPrintform")} /> </div> <div css={css` width: 100%; max-width: 780px; margin: 20px 0 7px 0; display: block; text-align: center; `} > <BtnNext type="button" onClick={() => setStep(2)} /> </div> </> )} {step === 2 && ( <> <ContactForm /> <BtnSendForm disabled={isSubmitting} className={isSubmitting && "progress"} /> </> )} </Form> )} </Formik> </Layout> ) }
$(function(){ var ww=$(window).width(); var wh=$(window).height(); $(".dnav").click(function(){ $(".slide_nav").css({display:"block"}).siblings().css({display:"none"}); }); $(".close").click(function(){ $(".slide_nav").css({display:"none"}).siblings().css({display:"block"}); }); $(".sfooter>li>h3").click(function(){ $(this).next().slideToggle(); }) /*轮播图*/ var currentNum=0; var nextNum=0; var currentTime=0; var flag=true; function move(type){ type=type||"right"; if(type=="right"){ nextNum++; if(nextNum==3){ nextNum=0; flag=false; } $(".list:eq("+currentNum+")").animate({width:"80%",height:"80%"},1000).css("zIndex",0); $(".list:eq("+nextNum+")").animate({left:0},1000,function(){ $(".list:eq("+currentNum+")").css({ left:"100%",width:"100%",height:"100%" }) currentNum=nextNum; currentTime=0; flag=true; }).css("zIndex",1); }else if(type=="left"){ nextNum--; if(nextNum==-1){ nextNum=$(".list").length-1; flag=false; } $(".list:eq("+currentNum+")").animate({left:"100%"},1000).css("zIndex",1); $(".list:eq("+nextNum+")").css({width:"80%",height:"80%",left:0}).animate({width:"100%",height:"100%"},1000,function(){ currentNum=nextNum; currentTime=0; flag=true; }).css("zIndex",0); } } function move1(){ currentTime+=50; var bili=currentTime/3000; if(bili>1){ bili=1; } $(".progress").eq(currentNum).css({width:bili*100+"%"}); if(flag===false){ $(".progress").css("width",0); } } function btnmove(){ $(".btn-list").find(".progress").css("width", 0); $(".btn-list").eq(nextNum).find(".progress").css("width", "100%"); } var t2=setInterval(move1,50); var t1=setInterval(move,4000);; $(window).focus(function(){ t1=setInterval(move,3000); t2=setInterval(move1,50); }); $(window).blur(function(){ clearInterval(t1); clearInterval(t2); }); $(".leftbtn").mouseover(function(){ clearInterval(t1); clearInterval(t2); }); $(".rightbtn").mouseover(function(){ clearInterval(t1); clearInterval(t2); }); $(".leftbtn").click(function(){ move("left"); btnmove(); }); $(".rightbtn").click(function(){ move("right"); btnmove(); }); $(".btn-list").click(function(){ nextNum=$(this).index(".btn-list"); stop(); }); // //$(".leftbtn").click(function(){ // nextNum--; // if(nextNum==-1){ // nextNum=2; // } // stop(); //}); //$(".rightbtn").click(function(){ // nextNum++; // if(nextNum==3){ // nextNum=0; // } // stop(); //}) // // function stop() { /* * 定时器停掉 * */ clearInterval(t1); clearInterval(t2); /*按钮的变化*/ $(".btn-list").find(".progress").css("width", 0); $(".btn-list").eq(nextNum).find(".progress").css("width", "100%"); /*轮播图发生变化*/ if (nextNum > currentNum) { $(".list:eq(" + currentNum + ")").animate({width: "80%", height: "80%"},1000).css("zIndex", 0); $(".list:eq(" + nextNum + ")").animate({left: 0},1000,function () { $(".list:eq(" + currentNum + ")").css({ left: "100%", width: "100%", height: "100%" }) currentNum = nextNum; }).css("zIndex", 1) } else { $(".list:eq(" + currentNum + ")").animate({left: "100%"},1000).css("zIndex", 1); $(".list").eq(nextNum).css({ width: "80%", height: "80%", left: 0 }).animate({width: "100%", height: "100%"},1000,function () { currentNum = nextNum; }) } } })
export const findNReplaceHash = (txt) => { if (txt) { return txt.replace( /\B(#[a-zA-Z]+\b)(?!;)/g, `<span class="hashtag">$1</span>` ); } };
var searchData= [ ['name_0',['name',['../classAIEngine.html#a2acddd6323b1daed0ecad0eba3f1e892',1,'AIEngine']]], ['node_5fsize_1',['node_size',['../classAIStatefulTaskMutex.html#ae3b45aae60eaa67cabaffe97222e5345',1,'AIStatefulTaskMutex']]] ];
import moment from 'moment'; import db from '../database'; export const getPrayerTime = () => { return dispatch => { db.open().then(async db => { const times = await db.prayerTimes.get(moment().format('YYYY[-]MM')) const data = times.data.filter(time => { const prayerTime = moment(time.date, 'DD[-]MM[-]YYYY') const yesterday = moment().subtract(1, 'd').format('YYYY[-]MM[-]DD') const afterTomorrow = moment().add(2, 'd').format('YYYY[-]MM[-]DD') return prayerTime.isBetween(yesterday, afterTomorrow) }) dispatch({ type: 'GET-TIME', data: data }) }) } }
import React, { useContext, useEffect, useState } from 'react'; import { makeStyles } from '@material-ui/core/styles'; import { useHistory } from 'react-router-dom'; import Select from 'react-select'; import Input from '../../shared/components/FormElements/Input'; import ErrorModal from '../../shared/components/UIElements/ErrorModal'; import LoadingSpinner from '../../shared/components/UIElements/LoadingSpinner'; import ImageUpload from '../../shared/components/FormElements/ImageUpload'; import { VALIDATOR_REQUIRE, VALIDATOR_NUMBER, } from '../../shared/util/validators'; import { useForm } from '../../shared/hooks/form-hook'; import { useHttpClient } from '../../shared/hooks/http-hook'; import { AuthContext } from '../../shared/context/auth-context'; import { Button, Card, CardContent, Typography } from '@material-ui/core'; import FileUpload from '../components/FileUpload'; import './NewSaber.css'; const useStyles = makeStyles({ root: { minWidth: 275, maxWidth: 500, }, bullet: { display: 'inline-block', margin: '0 2px', transform: 'scale(0.8)', }, title: { fontSize: 18, }, pos: { marginBottom: 12, }, }); const NewSaber = () => { const classes = useStyles(); const auth = useContext(AuthContext); const [selectedValue, setSelectedValue] = useState(); const [colors, setColors] = useState(); const [readXmlData, setReadXmlData] = useState(); const { isLoading, error, sendRequest, clearError } = useHttpClient(); const [formState, inputHandler] = useForm( { id: { value: '', isValid: false, }, name: { value: '', isValid: false, }, available: { value: '', isValid: false, }, image: { value: null, isValid: false, }, }, false ); const history = useHistory(); useEffect(() => { const fetchCrystals = async () => { try { const responseData = await sendRequest( process.env.REACT_APP_BACKEND_URL + '/crystal' ); const result = responseData.crystals.map((crystal) => ({ value: crystal.id, label: `${crystal.name} [${crystal.color}]`, })); setColors(result); } catch (err) {} }; fetchCrystals(); }, []); const handleChange = (e) => { setSelectedValue(e.value); }; const saberSubmitHandler = async (event) => { event.preventDefault(); try { const formData = new FormData(); formData.append('id', formState.inputs.id.value); formData.append('name', formState.inputs.name.value); formData.append('available', formState.inputs.available.value); formData.append('image', formState.inputs.image.value); formData.append('crystalId', selectedValue); await sendRequest( process.env.REACT_APP_BACKEND_URL + '/saber/createItem', 'POST', formData, { Authorization: 'Bearer ' + auth.token, } ); history.push(`/`); } catch (err) {} }; const saveXmlData = async () => { const responseSaveXmlData = null; try { responseSaveXmlData = await sendRequest( process.env.REACT_APP_BACKEND_URL + '/saber', 'POST', JSON.stringify({ sabers: readXmlData, }), { 'Content-Type': 'application/json', Authorization: 'Bearer ' + auth.token, } ); } catch (error) {} }; const readFile = (datas) => { setReadXmlData(datas.sabers); console.log('calcualte read file func', datas.sabers); }; return ( <React.Fragment> <ErrorModal error={error} onClear={clearError} /> <div className='price-info'> <Card> <CardContent> <FileUpload readFile={readFile} /> </CardContent> </Card> </div> <div className='hr-sect'>or</div> <div className='data-container'> {readXmlData && ( <div > <Typography variant='h5' component='h5'> Preview </Typography> <div className='saber-item-container'> {readXmlData.saber.map((item) => ( <Card className={classes.root} key={item.id}> <CardContent> <Typography color='textSecondary' component='p' gutterBottom > ID : {item.id} </Typography> <Typography color='textSecondary' component='p' gutterBottom > Name : {item.name} </Typography> <Typography color='textSecondary' component='p' gutterBottom > Available : {item.available} </Typography> <Typography color='textSecondary' component='p' gutterBottom > Name : {item.crystal.name} </Typography> <Typography color='textSecondary' component='p' gutterBottom > Color : {item.crystal.color} </Typography> </CardContent> </Card> ))} </div> <Button onClick={saveXmlData} type='submit' variant='contained' color='secondary' > Save all sabers </Button> </div> )} </div> {!readXmlData && ( <form className='place-form' onSubmit={saberSubmitHandler}> {isLoading && <LoadingSpinner asOverlay />} <Input id='id' element='input' type='text' label='ID' fullWidth validators={[VALIDATOR_REQUIRE()]} errorText='Please enter a valid id.' onInput={inputHandler} /> {colors && ( <Select options={colors} className='select-product-option' value={colors.find((obj) => obj.value === selectedValue)} onChange={handleChange} /> )} <Input id='name' element='textarea' label='Product Name' fullWidth validators={[VALIDATOR_REQUIRE()]} errorText='Please enter a valid name.' onInput={inputHandler} /> <Input id='available' element='number' label='Available' fullWidth validators={[VALIDATOR_NUMBER()]} errorText='Please enter a valid number.' onInput={inputHandler} /> <ImageUpload id='image' onInput={inputHandler} errorText='Please provide an image.' /> <Button type='submit' variant='contained' color='secondary' disabled={!formState.isValid} > ADD SABER </Button> </form> )} </React.Fragment> ); }; export default NewSaber;
import React from 'react'; import { storiesOf } from '@storybook/react'; import { action } from '@storybook/addon-actions'; import { linkTo } from '@storybook/addon-links'; import { default as CreateProjectView } from '../ui/components/create-project-view'; const branch = 'default'; const branches = [{ _id: '1', branch: 'default', activeWorld: true }, { _id: '2', branch: 'simulation', activeSim: true }, { _id: '3', branch: 'tutorial' }]; storiesOf('UI Components|Create Project View', module) .add('Create', () => ( <CreateProjectView branch={ branch } branches={ branches } /> )) .add('Download', () => ( <CreateProjectView branch={ branch } branches={ branches } projectPath={ '/some/project/path' } projectPathLabel={ 'Project folder path' } projectPathReadonly={ true } downloadReadonly={ true } submitBtn={ 'Download' } /> ));
export const categories = [ { name: 'Databases', color: '#3896e2', }, { name: 'Frameworks / Libraries', color: '#64cb7b', }, { name: 'Javascript', color: '#d75858', }, { name: 'Languages', color: '#6968b3', }, { name: 'Other', color: '#c3423f', }, { name: 'Python', color: '#37b1f5', }, { name: 'Test Automation', color: '##e47272', }, { name: 'Tools', color: '#40494e', }, { name: 'Web Development', color: '#cc7b94', }, ]; export const skills = [ { title: 'Javascript', compentency: 5, category: ['Web Development', 'Languages', 'Javascript'], }, { title: 'React', compentency: 4, category: ['Web Development', 'Frameworks / Libraries', 'Javascript'], }, { title: 'Angular', compentency: 3, category: ['Web Development', 'Frameworks / Libraries', 'Javascript'], }, { title: 'Knockout', compentency: 2, category: ['Web Development', 'Frameworks / Libraries', 'Javascript'], }, { title: 'Vue.js', compentency: 2, category: ['Web Development', 'Frameworks / Libraries', 'Javascript'], }, { title: 'SQL', compentency: 4, category: ['Databases'], }, { title: 'Matlab', compentency: 3, category: ['Languages'], }, { title: 'D3', compentency: 3, category: ['Web Development', 'Frameworks / Libraries', 'Javascript'], }, { title: 'jQuery', compentency: 3, category: ['Web Development', 'Frameworks / Libraries', 'Javascript'], }, { title: 'three.js', compentency: 3, category: ['Web Development', 'Frameworks / Libraries', 'Javascript'], }, { title: 'Grunt', compentency: 2, category: ['Web Development', 'Tools'], }, { title: 'Webpack', compentency: 2, category: ['Web Development', 'Tools'], }, { title: 'Git', compentency: 4, category: ['Tools'], }, { title: 'Numpy', compentency: 4, category: ['Python'], }, { title: 'Jupyter', compentency: 4, category: ['Python'], }, { title: 'Typescript', compentency: 3, category: ['Web Development', 'Languages'], }, { title: 'HTML', compentency: 5, category: ['Web Development', 'Languages'], }, { title: 'CSS', compentency: 5, category: ['Web Development', 'Languages'], }, { title: 'SASS/SCSS', compentency: 3, category: ['Web Development', 'Languages'], }, { title: 'LESS', compentency: 3, category: ['Web Development', 'Languages'], }, { title: 'Python', compentency: 5, category: ['Languages', 'Python'], }, { title: 'Canopy', compentency: 4, category: ['Python'], }, { title: 'Java', compentency: 3, category: ['Languages'], }, { title: 'C#', compentency: 5, category: ['Languages'], }, { title: 'Matplotib', compentency: 4, category: ['Python'], }, { title: 'Selenium Webdriver', compentency: 5, category: ['Test Automation'], }, { title: 'Protractor', compentency: 2, category: ['Test Automation', 'Javascript'], }, { title: 'Cypress', compentency: 3, category: ['Test Automation', 'Javascript'], }, { title: 'Jest', compentency: 3, category: ['Frameworks / Libraries', 'Javascript'], }, { title: 'Mocha', compentency: 3, category: ['Frameworks / Libraries', 'Javascript'], }, { title: 'TeamCity', compentency: 2, category: ['Other'], }, { title: 'Windows', compentency: 5, category: ['Other'], }, { title: 'MacOS', compentency: 5, category: ['Other'], }, { title: 'Jira', compentency: 5, category: ['Other'], }, ];
import React, { Component, PropTypes } from 'react'; import { Meteor } from 'meteor/meteor'; import { createContainer } from 'meteor/react-meteor-data'; //import { Lists } from '../../api/lists/lists.js'; class AppLayout extends Component { render() { return ( <div className="container"> <h1>This is the main layout!</h1> {this.props.children} </div> ); } } AppLayout.propTypes = { }; export default createContainer(() => { return { } }, AppLayout);
(function () { 'use strict'; /* @ngdoc object * @name courses * @description * */ angular .module('courses', [ 'ui.router' ]); }());
/* * Copyright 2014 Jabil */ sap.ui.jsview("com.jabil.maestro.mob.view.Home", { getControllerName : function() { return "com.jabil.maestro.mob.view.Home"; }, createContent : function(oController) { //Pge element var page = new sap.m.Page({showHeader: true, showNavButton: false, alignItems:"center", }); //Set page header with logo and logoff button page.setCustomHeader(new sap.m.Bar({contentMiddle: new sap.ui.core.HTML({content:"<div class='headerLogoStyle'>Jabil <span>Maestro</div>"}), contentRight:new sap.m.Image({src:"img/logout.png", press: oController.handleLogoff}) })); page.getCustomHeader().addStyleClass("appHeaderStyle"); //Add page Style page.addStyleClass("mainPageStyle"); //Load the navigation button in home screen var list = new sap.m.List("homeButtonList"); //Add OTD Link var otdListItem = new sap.m.CustomListItem("otd",{press:oController.handleTilePress,type: sap.m.ListType.Active}); var item1 = new sap.m.HBox(); item1.addItem(new sap.ui.core.HTML({content:"<div class='homeListItemIconStyleOtd'><img src='img/home/icon-otd.png'/></div>"})); //item1.addItem(new sap.m.Image({src:"img/home/bg-btn-otd.png"})); item1.addItem(new sap.ui.core.HTML({content:"<div class='homeListItemTextStyle'><div class='homeBtHd1TxtStyle'>On Time Delivery</div><div class='homeBtnDetTxtStyle'>Fill-rate measurement describing the percentage of orders filled by the requested date.</div></div>"})); otdListItem.insertContent(item1); otdListItem.addStyleClass("homeListItemStyle"); list.addItem(otdListItem); if(isInternalUser){ //Add Material Shortages Link var msListItem = new sap.m.CustomListItem("ms",{press:oController.handleTilePress,type: sap.m.ListType.Active}); var item2 = new sap.m.HBox(); item2.addItem(new sap.ui.core.HTML({content:"<div class='homeListItemIconStyleMs'><img src='img/home/icon-ms.png'/></div>"})); //item2.addItem(new sap.m.Image({src:"img/home/bg-btn-ms.png"})); item2.addItem(new sap.ui.core.HTML({content:"<div class='homeListItemTextStyle'><div class='homeBtHd2TxtStyle'>Material Shortages</div><div class='homeBtnDetTxtStyle'>The loss or impending loss of items or suppliers of items or raw materials.</div></div>"})); msListItem.insertContent(item2); msListItem.addStyleClass("homeListItemStyle"); list.addItem(msListItem); } //Add Order Status Link var osListItem = new sap.m.CustomListItem("os",{press:oController.handleTilePress,type: sap.m.ListType.Active}); var item3 = new sap.m.HBox(); item3.addItem(new sap.ui.core.HTML({content:"<div class='homeListItemIconStyleOs'><img src='img/home/icon-os.png'/></div>"})); //item3.addItem(new sap.m.Image({src:"img/home/bg-btn-os.png"})); item3.addItem(new sap.ui.core.HTML({content:"<div class='homeListItemTextStyle'><div class='homeBtHd3TxtStyle'>Order Status</div><div class='homeBtnDetTxtStyle'>This function enables you to check on the current processing stage of your order.</div></div>"})); osListItem.insertContent(item3); osListItem.addStyleClass("homeListItemStyle"); list.addItem(osListItem); //Add Order Status Link var ltcListItem = new sap.m.CustomListItem("ltc",{press:oController.handleTilePress,type: sap.m.ListType.Active}); var item4 = new sap.m.HBox(); item4.addItem(new sap.ui.core.HTML({content:"<div class='homeListItemIconStyleLtc'><img src='img/home/icon-ltc.png'/></div>"})); //item4.addItem(new sap.m.Image({src:"img/home/bg-btn-ltc.png"})); item4.addItem(new sap.ui.core.HTML({content:"<div class='homeListItemTextStyle'><div class='homeBtHd4TxtStyle'>Lead Time Completion</div><div class='homeBtnDetTxtStyle'>The amount of time that elapses between when a process starts and when it is completed.</div></div>"})); ltcListItem.insertContent(item4); ltcListItem.addStyleClass("homeListItemStyle"); list.addItem(ltcListItem); //add content to page page.addContent(list); //Add copyright text page.setFooter(new sap.m.Toolbar({content:new sap.ui.core.HTML({content:"<div id='copyrightText' class='copyrightStyle'>Copyright 2014 Jabil</div>"})}).addStyleClass("footerStyle")); return page; } });
import React from 'react'; import PropTypes from 'prop-types'; import './SearchResult.scss'; class SearchResult extends React.Component { componentWillReceiveProps(prevProps, nextProps) { console.log(prevProps, nextProps, 'component recieved new props'); } componentWillUnmount() { console.log('component unmounted'); } render() { const { props } = this; const { searchedResult } = props; if (!searchedResult) { return <div className="no-content">Data is not available</div>; } return ( <div className="search-result"> <h3>{searchedResult.name}</h3> <div className="location"> <div className="latitude"> <span className="label">Latitude</span> <span>{searchedResult.coord && searchedResult.coord.lat}</span> </div> <div className="longitude"> <span className="label">Longitude</span> <span>{searchedResult.coord && searchedResult.coord.lon}</span> </div> </div> </div> ); } } SearchResult.defaultProps = { searchedResult: null, }; SearchResult.propTypes = { searchedResult: PropTypes.object, }; export default SearchResult;
$(document).ready(function() { var funcion = ""; var tipo_usuario = $('#txtTipoUsuario').val(); buscar_avatar(); buscarServicios(); function buscar_avatar() { var id = $('#id_usuario').val(); funcion = 'buscarAvatar'; $.post('../../Controlador/usuario_controler.php', { id, funcion }, (response) => { const usuario = JSON.parse(response); $('#avatar4').attr('src', usuario.avatar); }); } $('#form_crear_servicio').submit(e => { e.preventDefault(); let nombre = $('#txtNombreServ').val(); let descrip = $('#txtDescServ').val(); funcion = 'crear_servicio'; $.post('../../Controlador/servicio_controler.php', { funcion, nombre, descrip }, (response) => { if (response == 'creado') { $('#divCreate').hide('slow'); $('#divCreate').show(1000); $('#divCreate').hide(2000); $('#form_crear_servicio').trigger('reset'); buscarServicios(); } else { $('#divNoCreate').hide('slow'); $('#divNoCreate').show(1000); $('#divNoCreate').hide(2000); $('#divNoCreate').html(response); } }); }); $(document).on('keyup', '#TxtBuscarServicio', function() { let consulta = $(this).val(); if (consulta != "") { buscarServicios(consulta); } else { buscarServicios(); } }); function buscarServicios(consulta) { var funcion = "buscar_servicio"; $.post('../../Controlador/servicio_controler.php', { consulta, funcion }, (response) => { const objetos = JSON.parse(response); num = 0; let template = `<div class="col-md-12"> <div class="card"> <div class="card-body"> <table class="table table-bordered center-all"> <thead notiHeader> <tr> <th style="width: 2px">#</th> <th style="width: 8px">Estado</th> <th style="width: 20px">Nombre</th> <th style="width: 60x">Descripción</th> <th style="width: 10px">Acción</th> </tr> </thead> <tbody>`; objetos.forEach(objeto => { num += 1; template += ` <tr idServicio=${objeto.id}> <td style="width: 2px">${num}</td> <td style="width: 8px">${objeto.estado_servicio}</td> <td style="width: 20px">${objeto.nombre_servicio}</td> <td style="width: 60px">${objeto.descripcion}</td> <td style="width: 10px"> <button class='editServicio btn btn-sm btn-primary mr-1' type='button' data-bs-toggle="modal" data-bs-target="#ModalEditar_servicio"> <i class="fas fa-pencil-alt"></i> </button> <button class='addImage btn btn-sm btn-info mr-1' type='button' data-bs-toggle="modal" data-bs-target="#fotosServicio"> <i class="fas fa-image"></i> </button>`; if (objeto.estado_servicio == "Activo") { template += `<button class='actServicio btn btn-sm btn-danger mr-1' type='button' title='Inactivar'> <i class="fas fa-lock"></i> </button>`; } else { template += `<button class='actServicio btn btn-sm btn-warning mr-1' type='button' title='Activar'> <i class="fas fa-lock-open"></i> </button>`; } template += ` </td> </tr>`; }); template += ` </tbody> </table> </div> </div> ` $('#busquedaServicio').html(template); }); } $(document).on('click', '.editServicio', (e) => { const elemento = $(this)[0].activeElement.parentElement.parentElement; const id = $(elemento).attr('idServicio'); $('#txtId_ServicioEd').val(id); funcion = 'cargarServicio'; $.post('../../Controlador/servicio_controler.php', { id, funcion }, (response) => { const obj = JSON.parse(response); $('#txtNombreServ2').val(obj.nombre_servicio); $('#txtDescServ2').val(obj.descripcion); }); }); $(document).on('click', '.addImage', (e) => { const elemento = $(this)[0].activeElement.parentElement.parentElement; const id = $(elemento).attr('idServicio'); $('#txtIdServImage').val(id); buscarFotosServicios(); }); $('#form_editar_servicio').submit(e => { let id = $('#txtId_ServicioEd').val(); let nombre = $('#txtNombreServ2').val(); let desc = $('#txtDescServ2').val(); funcion = 'editar_servicio'; $.post('../../Controlador/servicio_controler.php', { funcion, id, nombre, desc }, (response) => { if (response == 'update') { $('#updateObj').hide('slow'); $('#updateObj').show(1000); $('#updateObj').hide(2000); buscarServicios(); } else { $('#noUpdateObj').hide('slow'); $('#noUpdateObj').show(1000); $('#noUpdateObj').hide(2000); $('#noUpdateObj').html(response); } }); e.preventDefault(); }); $(document).on('click', '.actServicio', (e) => { const elemento = $(this)[0].activeElement.parentElement.parentElement; const id = $(elemento).attr('idServicio'); funcion = 'changeEstadoServicio'; $.post('../../Controlador/servicio_controler.php', { id, funcion }, (response) => { buscarServicios(); }); }); $("#form_crear_foto").on("submit", function(e) { e.preventDefault(); var f = $(this); var formData = new FormData(document.getElementById("form_crear_foto")); formData.append("dato", "valor"); var peticion = $('#form_crear_foto').attr('action'); $.ajax({ url: '../../Controlador/servicio_controler.php', type: 'POST', data: formData, cache: false, processData: false, contentType: false }).done(function(response) { if (response == 'creado') { $('#divCreateFoto').hide('slow'); $('#divCreateFoto').show(1000); $('#divCreateFoto').hide(2000); $('#form_crear_foto').trigger('reset'); $('#divCreateFoto').html('Foto registrada'); buscarFotosServicios(); } else { $('#divNoCreateFoto').hide('slow'); $('#divNoCreateFoto').show(1000); $('#divNoCreateFoto').hide(2000); $('#divNoCreateFoto').html(response); } }); }); function buscarFotosServicios() { var id_servicio = $('#txtIdServImage').val(); var funcion = "buscar_foto_servicio"; $.post('../../Controlador/servicio_controler.php', { funcion, id_servicio }, (response) => { const objetos = JSON.parse(response); let template = ""; num = 0; objetos.forEach(obj => { num += 1; template += `<div fotoId="${obj.id}" class="col-12 col-sm-4 align-items-stretch"> <div class="card bg-light"> <div class="card-header border-bottom-0 notiHeader"> Foto ${num}`; if (tipo_usuario <= 2 || (cargo == 1 || cargo == 7 || cargo == 8 || cargo == 12)) { template += `<button class='delFoto btn btn-sm btn-danger mr-1 float-right' style='display: flex;' type='button' > <i class="fas fa-trash mr-1"></i> </button>`; } template += `</div> <div class="card-body pt-0"> <div class="row"> <div class="col-12">`; template += `<img class='' src='${obj.archivo}' style='width: 100%'> <ul class="ml-4 mb-0 fa-ul text-muted"> <li class="small"><span class="fa-li"></span>${obj.descripcion}</li> </ul>`; template += ` </div> </div> </div>`; template += `</div></div>`; }); $('#divFotosServicio').html(template); }); } $(document).on('click', '.delFoto', (e) => { const elemento = $(this)[0].activeElement.parentElement.parentElement.parentElement; const id = $(elemento).attr('fotoId'); funcion = 'eliminarFotoServicio'; $.post('../../Controlador/servicio_controler.php', { id, funcion }, (response) => { if (response == 'eliminado') { $('#divCreateFoto').hide('slow'); $('#divCreateFoto').show(1000); $('#divCreateFoto').hide(2000); $('#divCreateFoto').html('Foto eliminada'); buscarFotosServicios(); } else { $('#divNoCreateFoto').hide('slow'); $('#divNoCreateFoto').show(1000); $('#divNoCreateFoto').hide(2000); $('#divNoCreateFoto').html(response); } }); }); });
import React, { useEffect } from 'react'; import { connect } from 'react-redux'; // Custom Styling import StyledButton from '../common/Button/StyledButton'; import StyledTitle from '../common/Title/StyledTitle'; import PopCart from '../Cart/PopCart'; import classes from './OrderChoice.module.css'; import { setMenu, setPopCart } from '../../actions/menu'; import { clearUserHistory, getUserHistory } from '../../actions/database'; import { clearPizza } from '../../actions/pizza'; // OrderChoice: displayed for logged-in customer only, page 2 // - Title sub-component // - History button // - Create order button // - Simple text // - *BackButton component is displayed but rendered outside (don't render in component) const OrderChoice = (props) => { //Gets user history data useEffect(() => { props.clearUserHistory(); if (props.user !== null) { props.getUserHistory(props.user.customer_id); } props.setPopCart(false); }, [props.user]); const handleOrderHistory = (e) => { e.preventDefault(); return props.setMenu(2); }; const handleCreateOrder = (e) => { e.preventDefault(); props.clearPizza(); return props.setMenu(9); }; return ( <div className={classes.Body}> {props.popCart ? <PopCart /> : null} {/* <br></br> */} {/* <div className={classes.Title}> title </div> */} <div className={classes.orderChoiceTitleContainer}> <StyledTitle divClassName="titleBox" text={`WELCOME BACK${props.user ? ',' : ''}`} className="orderChoiceTitle" /> {props.user !== null && ( <StyledTitle divClassName="titleBox" text={`${props.user.first_name[0].toUpperCase() + props.user.first_name.slice(1)} ${props.user.last_name[0].toUpperCase() + props.user.last_name.slice(1)}`} className="cursiveTitle" /> )} </div> <div className={classes.OrderChoice}> <StyledTitle className="orderChoiceSubtitle " text="What would you like to do today?" ></StyledTitle> <div className={classes.ButtonGroup}> {/* <br></br> */} {/* <Button onClick={handleOrderHistory}>See my order History</Button> */} <StyledButton type="button" onClick={handleOrderHistory} text="See My Order History" variant="orderChoiceButton" /> <StyledButton type="button" onClick={handleCreateOrder} text="Make a new order" variant="orderChoiceButton" /> {/* <Button onClick={handleCreateOrder}>Make a new order</Button> */} </div> </div> </div> ); }; OrderChoice.propTypes = {}; const mapStateToProps = (state) => ({ user: state.auth.user, isAuthenticated: state.auth.isAuthenticated, popCart: state.menu.popCart }); export default connect(mapStateToProps, { setMenu, setPopCart, clearUserHistory, getUserHistory, clearPizza, })(OrderChoice);
import React from 'react'; import { Router, Route } from 'react-router'; import Home from './pages/Homepage'; import Work from './pages/Workpage'; import Contact from './pages/Contact'; import Library from './pages/Componentpage'; const Routes = (props) => ( <Router {...props}> <Route path="/" component={Home} /> <Route path="/Work" component={Work} /> <Route path="/Library" component={Library} /> <Route path="/Contact" component={Contact} /> </Router> ); export default Routes;
var friendController = require('./ff.friend.controller.js'); var friendService = require('./ff.friend.service.js'); /** * Responsible for friends information and representation * * @ngdoc module * @name ff.friendModule */ angular.module('ff.friendModule', []) .config(require('./ff.friend.routes.js')) .factory(friendService.name, friendService.service) .controller(friendController.name, friendController.controller)
import h from 'mithril/hyperscript' import req from 'mithril/request' import {Intents} from '../../../../src/store.js' const module = { namespace: 'Auth', initialModel: { needsLogin: true }, state (model) { return { needsLogin: model.needsLogin, email: model.email, password: model.password, isValid: model.email && model.password ? true : false, token: model.token } }, acceptor (model) { return data => { if (data.email !== undefined) { model.email = data.email } if (data.password !== undefined) { model.password = data.password } if (data.token !== undefined) { model.token = data.token model.needsLogin = false } if (data.logOut === true) { model.email = null model.password = null model.token = null model.needsLogin = true } return model } } } const actions = { logIn (present, data) { return req.request({ method: 'POST', url: 'https://reqres.in/api/login', data }).then(resp => { present(resp) }) }, logOut (present) { present({logOut: true}) }, setEmail (present, email) { present({email}) return true }, setPassword (present, password) { present({password}) return true } } export function login (state) { return h('div.container', h('h2', 'Login'), h('form', h('div.row', h('div.six.columns', h('label[for="email"]', 'Email'), h('input.u-full-width[type="text"][name="email"]', { oninput: e => { Intents('Auth', 'setEmail', e.target.value) } }) ), h('div.six.columns', h('label[for="password"]', 'Password'), h('input.u-full-width[type="password"][name="password"]', { oninput: e => { Intents('Auth', 'setPassword', e.target.value) } }) ), h('input.button-primary[value="Login"][type="button"]', { onclick: () => { Intents('Auth', 'logIn', { email: state.email, password: state.password }) }, disabled: !state.isValid }) ) ) ) } export default { module, actions, login }
import React, { useState } from "react"; import "./App.css"; let emojiData = { "😄": "Grinning Face with Smiling Eyes", "😂": "Face with Tears of Joy", "😍": "Smiling Face with Heart-Eyes", "😩": "Weary Face", "😡": "Angry Face ", "😉": "Winking Face", }; let emojis = Object.keys(emojiData); function App() { const [meaning, setMeaning] = useState("Start Typing to Know Meaning"); let emojiMeans; /////////////////////////////////////////////////// Getting Emoji meaning from Database let getMeaning = (input) => { let meaningFromDB = emojiData[input]; if (meaningFromDB) { return (emojiMeans = meaningFromDB); } return (emojiMeans = "Sorry Currently this is Not available in our Database"); }; ///////////////////////////////////////////////////////// Taking Input let inputHandler = (event) => { let input = event.target.value; console.log(input); getMeaning(input); setMeaning(emojiMeans); }; return ( <div className="App"> <div className="content"> <div className="header"> <h1 className="logo"> Emo<span className="logo_col">Preter</span> </h1> </div> <h3 className="title">Type any Emoji to find out its real meaning</h3> <input className="input" onChange={inputHandler} placeholder="Type 😀 here" /> <h5 className="meaning">{meaning}</h5> <h5 className="text">These are the Emojis in our Database</h5> <h6 className="text-sm">(Click on them to know there meaning)</h6> <div className="emojiBox"> {emojis.map((emoji) => { return ( <span className="emoji" onClick={(event) => { getMeaning(event.target.innerHTML); setMeaning(emojiMeans); }} > {emoji} </span> ); })} </div> </div> <footer className="footer"> <h4 class="foot-text">Made with ❤ by Atishay</h4> <h5 class="copy">© 2020</h5> </footer> </div> ); } export default App;
form1 = document.getElementById("b1") sol1=["turned","down","the"] sol2=["make","up","for"] sol3=["held","up"] sol4=["made","her","mind","up"] sol5=["let","his","family","down"] sol6=["had","not","turned","up"] sol7=["see","mary","off"] const solutions = [sol1,sol2,sol3,sol4,sol5,sol6,sol7] const correct = () => { let mark = 0 let mark2 = mark let mistakes = new Array(0) let s1 = document.exercise.s1.value let s2 = document.exercise.s2.value let s3 = document.exercise.s3.value let s4 = document.exercise.s4.value let s5 = document.exercise.s5.value let s6 = document.exercise.s6.value let s7 = document.exercise.s7.value let answers1 = [s1,s2,s3,s4,s5,s6,s7] let answers2 = answers1.map ( e => e.trim()) let answers4 = answers2.map ( e => e.toLowerCase()) let anwers3 let answers5 = answers4.map( e => e.split(' ')) console.log(answers4) let answers = answers5.map( e => { for ( let x = 0;x<e.length;x++){ if (e[x][e[x].length-3]+e[x][e[x].length-2]+e[x][e[x].length-1] == "n't"){ for(let c = 0;c<3;c++){ e[x] = e[x].replace("n't","") } e.splice(x+1,0,"not") } if (e[x][e[x].length-3]+e[x][e[x].length-2]+e[x][e[x].length-1] == "'ve"){ for(let c = 0;c<3;c++){ e[x] = e[x].replace("'ve","") } e.splice(x+1,0,"have") } if (e[x] == "has" && x != 0){ e[x-1] = e[x-1]+"'as" e.splice(x,1) } if (e[x] == "is" && x != 0){ e[x-1] = e[x-1]+"'is" e.splice(x,1) } if (e[x] == "us" && x != 0 && e[x-1] == "let"){ e[x-1] = "let's" e.splice(x,1) } } return e }) let check = 0 let l = 0 for(let i = 0;i<answers.length;i++){ check = 0 mark2 = mark answers3 = answers[i].filter((e) => { return e != "" }) for(let j = 0;j<solutions[i].length;j++){ l = j if (solutions[i].length!=answers3length && solutions[i].length!=answers3.length-1 ){ break } if (solutions[i][j] != answers3[l] ){ break } check ++ } if (check == solutions[i].length){ mark+= (10/7) } if ( mark2 != mark){ mistakes.push("Right answer") } else{ mistakes.push("Wrong answer : "+answers[i]+" The solution is : "+solutions[i][0]) } } for( let k = 0;k< 7;k++){ if (mistakes[k] != "Right answer"){ document.getElementById("sol"+String(k+1)).innerHTML = "<button onclick=ss"+(k+1)+"()>Show solutions</button> <img src='https://icon2.cleanpng.com/20190228/bre/kisspng-red-x-stock-photography-image-letter-portable-netw-5c7878899969a0.1754724515513990496284.jpg' height=20vh width=20vh>" } else{ document.getElementById("sol"+String(k+1)).innerHTML ="<img src='https://image.freepik.com/premium-photo/green-tick-mark-white-background_172429-560.jpg' height=20vh width=20vh>" } } document.getElementById("mark").innerHTML = "VOTO : "+ mark.toFixed(2) } function ss1 () { document.getElementById("sol1").innerHTML= sol1[0]+" "+sol1[1]+" "+sol1[2] } function ss2 () { document.getElementById("sol2").innerHTML= sol2[0]+" "+sol2[1]+" "+sol2[2] } function ss3 () { document.getElementById("sol3").innerHTML= sol3[0]+" "+sol3[1] } function ss4 () { document.getElementById("sol4").innerHTML= sol4[0]+" "+sol4[1]+" "+sol4[2]+" "+sol4[3] } function ss5 () { document.getElementById("sol5").innerHTML= sol5[0]+" "+sol5[1]+" "+sol5[2]+" "+sol5[3] } function ss6 () { document.getElementById("sol6").innerHTML= sol6[0]+" "+sol6[1]+" "+sol6[2]+" "+sol6[3] } function ss7 () { document.getElementById("sol7").innerHTML= sol7[0]+" "+sol7[1]+" "+sol7[2] }
var img1 = document.getElementById('img1'); var img2 = document.getElementById('img2'); var ordinal1 = document.getElementById('odrinal1'); var ordinal2 = document.getElementById('odrinal2'); var btn1 = document.getElementById('btn1'); var btn2 = document.getElementById('btn2'); var imgArr1 = ['1', '2', '3', '4', '5']; var imgArr2 = ['6', '7', '8', '9']; var num1 = 0; var num2 = 0; /*这里打包复用是不是有更简单的方法?*/ var model1_1 = function() { console.log(imgArr1.length); num1++; if(num1 > imgArr1.length - 1) { num1 = 0; } img1.src = 'img/' + imgArr1[num1] + '.jpg'; ordinal1.innerHTML = num1 + 1; } var model2_1 = function() { num2++; if(num2 > imgArr2.length - 1) { num2 = 0; } img2.src = 'img/' + imgArr2[num2] + '.jpg'; ordinal2.innerHTML = num2 + 1; } var model1_2 = function() { num1--; if(num1 < 0) { num1 = imgArr1.length - 1; } img1.src = 'img/' + imgArr1[num1] + '.jpg'; ordinal1.innerHTML = num1 + 1; } var model2_2 = function() { num2--; if(num2 < 0) { num2 = imgArr2.length - 1; } img2.src = 'img/' + imgArr2[num2] + '.jpg'; ordinal2.innerHTML = num2 + 1; } img1.onclick = function() { model1_1(); } img2.onclick = function() { model2_1(); } btn1.onclick = function() { model1_2(); model2_2(); } btn2.onclick = function() { model1_1(); model2_1(); }
/* jshint indent: 2 */ module.exports = function(sequelize, DataTypes) { return sequelize.define('acc_condition_default', { acc_condition_default_id: { type: DataTypes.INTEGER(5).UNSIGNED, allowNull: false, primaryKey: true, autoIncrement: true }, pfl_operator_id: { type: DataTypes.INTEGER(3).UNSIGNED, allowNull: true }, number_of_times: { type: DataTypes.INTEGER(5).UNSIGNED, allowNull: true }, number_of_periods: { type: DataTypes.INTEGER(5).UNSIGNED, allowNull: true }, period: { type: DataTypes.STRING(10), allowNull: true }, acc_environment_id: { type: DataTypes.INTEGER(5).UNSIGNED, allowNull: false } }, { tableName: 'acc_condition_default' }); };
import React from "react"; import "./PlayerDetails.css"; import { Card } from "react-bootstrap"; import { Button } from "react-bootstrap"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faUserPlus } from "@fortawesome/free-solid-svg-icons"; const PlayerDetails = (props) => { const { name, img, salary } = props.playerDetails; return ( <div className="card-container"> <div className="card-decoration"> <Card style={{ width: "18rem" }}> <Card.Img src={img} /> <Card.Body> <Card.Title>{name}</Card.Title> <Card.Text>Salary: {salary}</Card.Text> <Button onClick={() => props.handleAddPlayer(props.playerDetails)} variant="primary" > <FontAwesomeIcon icon={faUserPlus} /> Add Me </Button> </Card.Body> </Card> </div> </div> ); }; export default PlayerDetails;
import React from 'react' import me from '../assets/imgs/me2.jpg' import { Element } from 'react-scroll' export function About() { return ( <div className="about"> <div className="container flex justify-center align-center text-center col"> <Element id='about' name='about'> <div> <img className="me" src={me} alt="" srcSet="" /> <div className="txt-container"> <div className="title-container"> <h1> אופיר אלבז יועץ נדל"ן <span className="relative">מוסמך <hr className="gold-hr absolute" /></span> </h1> </div> <span className="subtitle">ראשון לציון</span> <p>בחרתי להצטרף לחברת קלר וויליאמס בשל היותה החברה הגדולה בעולם בעלת הטכנולוגיות המתקדמות ביותר בתחום הנדל"ן כיום.</p> <p>בחרתי לעבוד במקצוע זה מתוך תשוקה גדולה לעולם הנדל"ן, זהו תחום שמעניין אותי מאוד מאז שאני זוכר את עצמי. יחד עם זאת להיות שותף דרך ולקחת חלק באחת מההחלטות הגדולות והחשובות ביותר בחיי לקוחותיי ולהגשים להם את החלום לגור בבית חלומותיהם. </p> </div> </div> </Element> </div> </div> ) }
import EmberRouter from '@ember/routing/router'; import config from './config/environment'; const Router = EmberRouter.extend({ location: config.locationType, rootURL: config.rootURL }); Router.map(function() { this.route('/', function() { this.route('index', { path: '/'}); }); this.route('coins', function() { this.route('show', { path: '/:symbol' }); }); this.route('about'); this.route('faq'); this.route('disclaimer'); this.route('policy'); this.route('donation'); // No need for HOF (Only handle one coin for now) // this.route('hall-of-fame', function() { // this.route('show', { path: '/:range/:date' }); // }); }); export default Router;
// // Soldier // function Soldier() {} // // Viking // function Viking() {} // // Saxon // function Saxon() {} // // War // function War() {} // Soldier // Soldier //function Soldier() {} class Soldier { constructor(health, strength){ this.health = health this.strength = strength } attack (){ return this.strength } receiveDamage(damage){ this.health -= damage } } // Viking //function Viking() {} class Viking extends Soldier { constructor(name, health, strength){ super (health, strength) this.name = name } // attack (){ // return super.attack() // } receiveDamage(damage){ super.receiveDamage(damage) if(this.health > 0){ return this.name + " has received " + damage + " points of damage" } else return this.name + " has died in act of combat" } battleCry(){ return "Odin Owns You All!" } } // Saxon //function Saxon() {} class Saxon extends Soldier { constructor(health, strength){ super (health, strength) } attack (){ return super.attack() } receiveDamage(damage){ super.receiveDamage(damage) if (this.health > 0){ return "A Saxon has received " + damage + " points of damage" } else { return "A Saxon has died in combat" } } } class War { constructor(){ this.vikingArmy = [] this.saxonArmy = [] } addViking(Viking){ this.vikingArmy.push(Viking) } addSaxon(Saxon){ this.saxonArmy.push(Saxon) } vikingAttack(){ var randSaxonIndex = Math.floor(Math.random() * this.saxonArmy.length) var randVikingIndex = Math.floor(Math.random() * this.vikingArmy.length) var damageMessage = this.saxonArmy[randSaxonIndex].receiveDamage(this.vikingArmy[randVikingIndex].attack()) if(this.saxonArmy[randSaxonIndex].health < 1) { this.saxonArmy.splice(randSaxonIndex ,1) } return damageMessage } saxonAttack(){ var randSaxonIndex = Math.floor(Math.random() * this.saxonArmy.length) var randVikingIndex = Math.floor(Math.random() * this.vikingArmy.length) var damageMessage = this.vikingArmy[randVikingIndex].receiveDamage(this.saxonArmy[randSaxonIndex].attack()) if(this.vikingArmy[randVikingIndex].health < 1) { this.vikingArmy.splice(randVikingIndex,1) } return damageMessage } showStatus(){ if (this.saxonArmy.length < 1) { return 'Vikings have won the war of the century!' } if (this.vikingArmy.length < 1) { return 'Saxons have fought for their lives and survive another day...' } else return 'Vikings and Saxons are still in the thick of battle.' } }
import { ACTIVE } from '../constants'; $('.js-form').on('submit', e => { e.preventDefault(); var data = { name: $('#name').val(), email: $('#email').val(), message: $('#message').val() }; $.ajax({ type: 'POST', url: '../send-email.php', data: data, success: function() { $('.js-form-success').addClass(ACTIVE); } }); });
/** * Old Twitter-like Notification * * MIT License * * Ashit Vora (a.k.vora@gmail.com) * Tested on jQuery 1.5.1 * * Usage * * $.notify.show({ * msg: "Message to display", * sticky: if TRUE, don't auto hide. else hide after 10 seconds * }); * */ (function($, undefined){ var container = $("<div class='notify'>"), timeOut = 10000; $.notify = {}; $.notify.init = function(){ $("body").append(container); container.click(function(){ $.notify.hide(); }); }; $.notify.show = function(config){ var msg = config.msg !== "undefined" ? $.trim(config.msg) : "", sticky = config.sticky !== "undefined" && config.sticky === true; if( msg.length > 0 ){ container.html(msg).slideDown(); if(! sticky){ setTimeout(function(){ $.notify.hide(); }, timeOut); } } }; $.notify.hide = function(){ container.slideUp(); }; $("document").ready(function(){ $.notify.init(); }); })(jQuery);
import PIXI from 'expose-loader?PIXI!phaser-ce/build/custom/pixi.js'; import p2 from 'expose-loader?p2!phaser-ce/build/custom/p2.js'; import Phaser from 'expose-loader?Phaser!phaser-ce/build/custom/phaser-split.js'; export default class GameOver extends Phaser.State { constructor(game, gameManager) { super(game); this.gameManager = gameManager; } preload(game) { } create(game) { console.log('game over state'); let status = ''; if (this.gameManager.gameState == 'draw') { status = 'Draw. Rematch ?'; } else if (this.gameManager.winner == this.gameManager.playerId) { status = 'Congratulations!'; } else { status = 'Game over!'; } this.statusText = this.game.add.text( this.game.world.centerX, this.game.world.centerY, status, {font: '50px', fill: '#de0000', align: 'center'}); this.statusText.anchor.set(0.5, 0.5); // this.playText = this.game.add.text( // this.game.world.centerX, 600, // 'Play', // {font: '50px', fill: '#9eff63', align: 'center'}); // this.playText.anchor.set(0.5, 0.5); // this.playText.inputEnabled = true; // this.playText.events.onInputDown.add(() => { // this.game.state.start('Game'); // }, this); }; update(game) { }; };
// Copyright (C) 2020 to the present, Crestron Electronics, Inc. // All rights reserved. // No part of this software may be reproduced in any form, machine // or natural, without the express written consent of Crestron Electronics. // Use of this source code is subject to the terms of the Crestron Software License Agreement // under which you licensed this source code. /*jslint es6 */ /*global CrComLib webkit JSInterface */ // This function is temporary until CrComLib.isCrestronTouchscreen is added to the CrComLib library. (function () { 'use strict'; if (CrComLib.isCrestronTouchscreen === undefined) { console.log('CrComLib.isCrestronTouchscreen polyfill added'); CrComLib.isCrestronTouchscreen = function () { if (window.navigator.userAgent.toLowerCase().includes("crestron")) { return true; } if (typeof(JSInterface) !== "undefined" && typeof(JSInterface.bridgeSendBooleanToNative) !== "undefined") { return true; } if (typeof(webkit) !== "undefined" && typeof(webkit.messageHandlers) != "undefined" && typeof(webkit.messageHandlers.bridgeSendBooleanToNative) !== "undefined") { return true; } return false; } } }());
var searchData= [ ['reading_20and_20writing_20midi_20data_888',['Reading and writing MIDI data',['../group__MIDIAPI.html',1,'']]] ];
'use strict'; describe('LoremPixel', function () { var React = require('react/addons'); var LoremPixel, component; beforeEach(function () { LoremPixel = require('components/lib/LoremPixel.js'); component = React.createElement(LoremPixel); }); it('should create a new instance of LoremPixel', function () { expect(component).toBeDefined(); }); });
//获取地址栏参数 //url为空时为调用当前url地址 //调用方法为 var params = getPatams(); function getParams(url) { var theRequest = new Object(); if (!url) url = location.href; if (url.indexOf("?") !== -1) { var str = url.substr(url.indexOf("?") + 1) + "&"; var strs = str.split("&"); for (var i = 0; i < strs.length - 1; i++) { var key = strs[i].substring(0, strs[i].indexOf("=")); var val = strs[i].substring(strs[i].indexOf("=") + 1); theRequest[key] = val; } } return theRequest; /** * * @param text * @param type primary,success,warning,danger */ function commonNotify(text, type) { new PNotify({title: "提示", text: text,type: type, styling: 'fontawesome'}); } }
var TableTable_Bang_exchange = { map: function() { if (!this._map) this._map = pi.JsonLoader.getInstance().load_dict("map/Table_Bang_exchange_Auto.js") if (!this._map) PILogE("Table_Bang_exchange: load map fail"); return this._map; }, info: function(id) { var map = this.map(); if (!map) return null; var val = map[id]; if (!val) PILogE("Table_Bang_exchange: id not found"); return val; }, getDec: function(id, translate) { var info = this.info(id); if (!info) return; return translate ? _V(info["dec"]) : info["dec"]; }, getPrice: function(id) { var info = this.info(id); return info ? info["price"] : null; }, getRewardType: function(id) { var info = this.info(id); return info ? info["rewardType"] : null; }, getSociatyLevel: function(id) { var info = this.info(id); return info ? info["sociatyLevel"] : null; }, getNum: function(id) { var info = this.info(id); return info ? info["num"] : null; }, getImageId: function(id) { var info = this.info(id); return info ? info["imageId"] : null; }, getRefId: function(id) { var info = this.info(id); return info ? info["refId"] : null; }, _map : null, _cache_sign : null, _cache_mark : null, _cache_name : null }
var webdriver = require('selenium-webdriver'); var fs = require('fs'); var chrome = require('chromedriver'); var driver = null; const delayFactor = 1; const travelInsurance = 'Circle Cover'; var site = require ('./' + travelInsurance); var params = require('./' + travelInsurance + '/Data.js').data; const filePath = travelInsurance + '.csv'; var currentParams = undefined; console.log('running travel insurance website: ' + travelInsurance); function LoopingParams(){ console.log('Looping Params'); if(params.length < 1){ console.log("There is no test cases left in Data.js File | All Params Have been passed"); return; } currentParams = params.shift(); ExecuteTestCases(); } function ExecuteTestCases(){ driver = new webdriver.Builder() .forBrowser('chrome') .build(); console.log('running : '+ JSON.stringify(currentParams)); var _groupType = currentParams.ages.length === 1 ? 'individual' : currentParams.ages.length === 2? 'couple' :'family'; site.Run( currentParams.tripType, currentParams.location, _groupType, currentParams.tripDays, currentParams.ages, delayFactor, driver, function(results){ console.log("Results from Index file " + JSON.stringify(results)); for (var i = 0; i < results.length; i++) { AppendResultsToCSVFILE(results[i]); } driver.quit(); LoopingParams(); } ); } function AppendResultsToCSVFILE(result){ fs.appendFileSync(filePath,'' + result.tripType + ',' + result.location + ',' + result.groupType + ',' + result.tripDays + ',' + result.ages.join('&') + ',' + result.Name + ',' + result.Price + ', \n ' ); } LoopingParams();
import API from '@/store/api'; import { getLink } from '@/store/links' const actions = { setAccountDataValue({ commit }, data) { commit("setAccountData", data); }, setAccountSearchParams({ commit }, params) { commit("setAccountSearchParamsValue", params); }, searchAccounts( {commit, getters}, params ){ params.queries.size = getters.getAmountOfDataItem API.get( getLink( 'getAccounts', params), null ).then( ( tenderData) => { commit("setAccountData", tenderData.data); commit("setAccountPageInfo", tenderData); } ).catch( (err) => { console.log(err) }) }, changeAccountState( { commit, dispatch }, accountStateObject ){ API.post( getLink( 'changeAccountState', {}), accountStateObject).then( ( ) => { commit("setAccountError", { type: 'accountChangeSuccess' }) const searchQueries = { query : true, queries: { size : 12, } } dispatch('searchAccounts', searchQueries); } ).catch( ( error ) => { var errorObj = {} for (var key in error.response.data){ errorObj[ key ] = error.response.data[key].msg; } errorObj['type'] = 'accountChangeError'; commit("setAccountError", errorObj) }) }, deleteAccount( { commit, dispatch }, accountStateParam ){ API.delete( getLink( 'deleteAccount', accountStateParam), null ).then( ( ) => { commit("setAccountError", { type: 'accountDeleteSuccess' }) const searchQueries = { query : true, queries: { size : 12, } } dispatch('searchAccounts', searchQueries); } ).catch( ( error ) => { var errorObj = {} for (var key in error.response.data){ errorObj[ key ] = error.response.data[key].msg; } errorObj['type'] = 'accountDeleteError'; commit("setAccountError", errorObj) }) }, } export default actions;
import { computed } from '@ember/object'; import Component from '@ember/component'; import { alias } from '@ember/object/computed'; export default class AmountComponent extends Component { @alias('amount.value') value @alias('amount.unit') unit tagName = "" @computed('unit', 'value') get unitString(){ const unit = this.unit; if( unit == "C62" ) return this.value == 1 ? "stuk" : "stuks"; if( unit == "KGM" ) return "kg"; if( unit == "GRM" ) return "gr"; return "---"; } @computed('value', 'unitString') get outputString(){ const value = this.value; return `${value} ${this.unitString}`; } }
prev_event = time = ""; margin = eventPos = prevEvent = prevOppositeEvent = 0; side = "left"; today = new Date(); global_events = []; //Ready $(document).ready(function(){ function addEvent(events){ $.each(events, function(index){ time = (this.future ? "future" : "past"); var cur_event = this; $.each(global_events, function(index){ if(cur_event.begin_date <= this.begin_date) eventPos = index; }); // Add event to eventPos index global_events.splice(eventPos, 0, cur_event); organizeEvents(cur_event); }); }; function organizeEvents(event){ var elementIndex = 0; // Always add do left side if there's no space at right? if(0) side = (side == "left" ? "right" : "left"); // Last position Last position in future // if(!eventPos || global_events[eventPos-1].future !== global_events[eventPos+1].future){ // If not empty // if(global_events.length - 1){ // If there is available space add to left if(checkSpace()){ event.side = side; if(!prevEvent){ // if elem right.length == 0 appendTo if(!$("#"+time+" .events."+event.side).children().length) createEventElement(event).css("display", "").appendTo("#"+time+" .events."+event.side); else{ // insertBefore index 1 createEventElement(event).css("display", "").insertBefore( $($("#"+time+" .events."+event.side).children()[0])); } } else{ elementIndex = getEventsCount( global_events.slice(eventPos, global_events.length), event.side); createEventElement(event).css("display", "").insertAfter( $($("#"+time+" .events."+event.side).children()[elementIndex])); } } else{ event.side = (side == "left" ? "right" : "left"); if(!prevOppositeEvent){ // if elem right.length == 0 appendTo if(!$("#"+time+" .events."+event.side).children().length) createEventElement(event).css("display", "").appendTo("#"+time+" .events."+event.side); else{ // insertBefore index 1 createEventElement(event).css("display", "").insertBefore( $($("#"+time+" .events."+event.side).children()[0])); } } else{ elementIndex = getEventsCount( global_events.slice(eventPos, global_events.length), event.side); createEventElement(event).css("display", "").insertAfter( $($("#"+time+" .events."+event.side).children()[elementIndex])); } } // } // if(side=="left"){ // var eltemp = $('#events_box_left').clone(); // $(eltemp).css("display", "").appendTo("#"+time+" .events.left"); // } // else{ // var eltemp = $('#events_box_right').clone(); // $(eltemp).css("display", "").appendTo("#"+time+" .events.right"); // } // position += $(eltemp).height() + (cur_event.image ? ($(eltemp).find('img').last().height() < 40 ? cur_event.imageHeight.height : 0) : // 0) + parseInt($(eltemp).css("margin-top")); // position += $(eltemp).height() + parseInt($(eltemp).css("margin-top")); // if(position >= limit || limit - position < 20){ // side = (side == "left" ? "right" : "left"); // margin = (limit ? (position - limit) : 80); // if(margin > 100) // margin = 80; // else if(margin < 20) // margin = 50; // limit = position - limit; // if(time == "future"){ // $(".events.center .event_line_future").css("height", line+130); // $(".events.center hr").css("display",""); // line = 0; // time = "past"; // margin +=50; // } // line += limit; // position = 0; // } // else{ // margin = 50; // } } // Check if there's space to add an event on the same side function checkSpace(){ prevEvent = getPrevEventIndex(); prevOppositeEvent = getPrevOppositeEventIndex(); var oppSide = (side == "left" ? "right" : "left"); if(global_events[eventPos].future){ var prevEventsCount = getEventsCount( global_events.slice( (prevEvent !== false && prevOppositeEvent !== false ? prevEvent : getLastPastEvent() +1), global_events.length ), side); var prevOppositeEventsCount = getEventsCount( global_events.slice( (prevEvent !== false && prevOppositeEvent !== false ? prevOppositeEvent : getLastPastEvent() +1), global_events.length ), oppSide); } else{ var prevEventsCount = getEventsCount( global_events.slice( (prevEvent !== false && prevOppositeEvent !== false ? prevEvent : 0), getLastPastEvent() ), side); var prevOppositeEventsCount = getEventsCount( global_events.slice( (prevEvent !== false && prevOppositeEvent !== false ? prevOppositeEvent : 0), getLastPastEvent() ), oppSide); } // If height of opposite side since previous event is bigger than // the height of same side since previous event than add event to same side var totalHeightLeft = 0; var totalHeightRight = 0; $("#"+time+" .events."+side+" #events_box_"+side).slice(0, prevEventsCount).each(function(index, el) { totalHeightLeft += $(el).height(); //+ margins? }); $("#"+time+" .events."+oppSide+" #events_box_"+oppSide).slice(0, prevOppositeEventsCount).each(function(index, el) { totalHeightRight += $(el).height(); //+ margins? }); // if(totalHeightLeft == totalHeightRight){ // $("#"+time+" .events."+side+" #events_box_"+side).each(function(index, el) { // totalHeightLeft += $(el).height(); // }); // $("#"+time+" .events."+oppSide+" #events_box_"+oppSide).each(function(index, el) { // totalHeightRight += $(el).height(); //+ margins? // }); // if(totalHeightLeft > totalHeightRight) // return false; // return true // } // else if(totalHeightLeft > totalHeightRight) return false; return true; } function getEventsCount(events, side){ return events.filter(function(object){ return object.side==side; }).length; } function getLastPastEvent(){ var lastPast = ""; global_events.forEach(function(el, index) { if(!el.future) lastPast = index; }); if(lastPast) return lastPast; else return 0; // Returns false if there's no past event } // Get previous event on same side function getPrevEventIndex(){ i=1; while(!!global_events[eventPos+i]){ if(global_events[eventPos+i].future == global_events[eventPos].future && global_events[eventPos+i].side === global_events[eventPos].side) return eventPos+i; i++; } return false; } // Get previous event on opposite side function getPrevOppositeEventIndex(){ i=1; while(!!global_events[eventPos+i]){ if(global_events[eventPos+i].future == global_events[eventPos].future && global_events[eventPos+i].side !== global_events[eventPos].side) return eventPos+i; i++; } return false; } function createEventElement(event){ var eltemp = $('#events_box_'+event.side).clone(); // Margin between events $(eltemp).css("margin-top", margin + "px"); // Event details $(eltemp).find(".event_title").text(event.title); $(eltemp).find(".event_date").text(event.begin_date.toDateString()); $(eltemp).find(".event_description").text(event.description); if(!event.image) $(eltemp).find('img').last().css("display", "none"); else $(eltemp).find('img').last().attr('src', event.image); return $(eltemp); } $(".menu form").on("submit", function(event) { // Prevents the form from being submited event.preventDefault(); var errors = []; $("#errors").slideUp(); // Hide errors if(!this.title.value) errors.push("Event title cannot be empty."); if(!this.begin_date.value) errors.push("Invalid begin date."); else if(new Date(this.begin_date.value) > new Date(this.end_date.value)){ errors.push("Begin date can't be higher than end date."); } if(!errors.length){ event = [ { future: (new Date(this.begin_date.value) > today ? true : false), side: "left", title: this.title.value, begin_date: new Date(this.begin_date.value), end_date: new Date(this.end_date.value), description: this.description.value, image: false, } ]; addEvent(event); } else{ $("#errors").empty(); // Remove previous errors $.each(errors, function(index){ // Add errors $("#errors").append("<span>"+errors[index]+"</span>"); }); $("#errors").slideDown(); // Show errors } }); addEvent([{ future: true, side: "left", title: 'World Peace', begin_date: new Date(new Date(today).setDate(today.getDate() + 1)), end_date: new Date(new Date(today).setDate(today.getDate() + 1)), description: 'Make the world a better place!', image: false, }]); });
import { useContext } from 'react'; import { GameContext } from '../../contexts/useGameContext'; const useHandsController = () => { const { gameState } = useContext(GameContext); const { winner, handsData, scores } = gameState; const { id: winnerId } = winner || {}; return { winnerId, handsData, scores, }; }; export default useHandsController;
import Header from './header/index' import Footer from './footer/index' export { Header, Footer }
import { Component } from 'react'; import Router from 'next/router' import styled from 'styled-components' import { Header, Editor } from './../Components/snip' import Tags from './../Components/snip/tags' import { getUser, addSnip, updatesnip, removeSnip } from './../config/localstorage' class New extends Component { constructor(props) { super(props); this.state = { user: {}, snip: { title: 'untitled', code: '', tags: [], language: 'java', trash: false, theme:'tomorrow_night' } }; if (Router.router !== null) { const id = Router.router.query.id; if (id !== undefined) { const { user } = getUser(); const { snips } = user; var snip = {}; snips.map((s) => { if (s.id === id) { snip = s } }); this.state.snip = snip ; } else { this.state.new = true ; } } } componentDidMount() { const theme = localStorage.getItem('theme'); this.setState({theme:theme}) } changeTitle = (title) => { const snip = this.state.snip; if(title.length === 0) title = 'untitled' if (title !== ' ') { snip.title = title; this.setState({ snip: snip }); } } onSave = async () => { if (this.state.new) { await addSnip(this.state.snip).then(() => Router.push('/home')); } else { updatesnip({ id: this.state.snip.id, newsnip: this.state.snip }).then(() => { Router.push('/home') }); } } removeSnip = ()=>{ removeSnip(this.state.snip.id).then(()=>{ alert('snippet deleted'); Router.push('/home'); }); } render() { return ( <Wrapper> <Header title={this.state.snip.title} changeTitle={this.changeTitle} onSave={this.onSave} removeSnip={this.removeSnip} new={this.state.new} /> <Tags onChangeTag={(tags) => { const { snip } = this.state; snip.tags = tags; this.setState({ snip: snip }) }} tags={this.state.snip.tags} /> <Editor code={this.state.snip.code} theme = {this.state.theme} language={this.state.snip.language} onDataChange={(code, language) => { var snip = this.state.snip; snip.language = language; snip.code = code; this.setState({ snip: snip }); }} /> </Wrapper> ); } } export default New; //#25282c const Wrapper = styled.div` background:${props => props.theme.primary} ; height: 100%; width: 100%; color: ${props => props.theme.color}; display:flex; flex-direction:column; `
import React from "react"; import { Col } from "react-bootstrap"; import AboutItem from "./AboutItem.jsx"; const AboutList = props => ( <Col> {props.teamMembers.map((teamMember, index) => ( <AboutItem teamMember={teamMember} index={teamMember.id} /> ))} </Col> ); export default AboutList;
/** * @author vincent voyer * vincent.voyer@gmail.com */ (function($){ $.fn.ajaxChat = function(params){ var params = $.extend({ refresh:5, nick:"cocina" },params); var chat = function (jElt) { //jElt is the jQuery object where the function starts var chatContainer=jElt.find('.chat'); var chat=chatContainer.find('div'); // this is div containing the messages var writeInput=jElt.find('.writeInput'); var chooseNickname=jElt.find('.chooseNickname'); var ajaxStatus=jElt.find('.ajaxStatus'); //ISAAC $("#eliminar").mousedown(function(){ var cantidad=$("#pedidosTable .white .cantidad").html(); var nombre=$("#pedidosTable .white .nombre").html(); var numComanda=$("#pedidosTable .white .numComanda").html(); if (cantidad != null)writeInput.find(':input').val('Listo '+cantidad+' '+nombre+' de '+numComanda).parent().trigger('submit'); }); //END ISAAC // handle the submit message function var activateKeyboard = function(){ writeInput.submit(function(){ var input = $(this).find(':input'); var message = input.val(); if ($.trim(message).length > 0) { // need to have something to say ! ajaxStatus.show(); input.val(''); input.blur(); input.attr("disabled", "disabled"); // we have to this so there'll be less spam messages $.post("/restbar/Presentacion/serverchat.php", { //this is the url of your server side script that will handle write function msg: message }, function(data){ input.removeAttr("disabled"); input.focus(); if (data) chat.append('<p><small>('+ data.time +')</small> ' + data.nickname + ' &gt; <strong>' + data.msg + '</strong></p>'); var objDiv = document.getElementById("chatCocina"); objDiv.scrollTop = objDiv.scrollHeight; ajaxStatus.hide(); }, 'json'); } return false; }); } // handle the read messages function var readMessages = function(){ $.getJSON("/restbar/Presentacion/serverchat.php", function(data){ $.each(data, function(i,msg){ chat.append('<p><small>('+ msg.time +')</small> '+msg.nickname+' &gt; <strong>'+msg.msg+'</strong></p>'); }); var objDiv = document.getElementById("chatCocina"); objDiv.scrollTop = objDiv.scrollHeight; if (data)sound2Play(); setTimeout(readMessages,params.refresh*1000); }); } chooseNickname.submit(function(){ var tryNickname=$(this).find(':input:first').val(); $.post("/restbar/Presentacion/serverchat.php", { //this is the url of your server side script that will handle write function nickname: tryNickname }, function(data){ if (data) { chooseNickname.remove(); chatContainer.show(); writeInput.show(); readMessages(); writeInput.find(':input').val('hello i\'m there !').parent().trigger('submit'); } else { alert('bad nickname, try something else !'); } }, 'json'); return false; }); chatContainer.hide(); writeInput.hide(); ajaxStatus.hide(); activateKeyboard(); } return this.each(function(){ chat($(this)); }); }; })(jQuery)
import React,{ Fragment } from 'react'; import { Link } from 'react-router-dom'; import './Navbar.css'; import logImg from '../Header/headerImgs/logo.svg'; const Navbar = () =>{ function navBut(){ let navScreen = document.getElementById('nav-screen'); navScreen.classList.toggle('active-nav'); } return( <Fragment> <div className="navbar"> <div className="logo"> <Link to="/"> <img src = { logImg } alt="robita" height="70" width="300" /> </Link> </div> <ul> <li><a href="/#">Features <i className="fas fa-angle-down"></i></a></li> <li><Link to="/plan">Plans & Pricing</Link></li> <li><a href="/#">Resources <i className="fas fa-angle-down"></i></a></li> </ul> <div className="sign"> <div> <a className="signIn" href="/#"><h4>Sign In</h4></a> <a className="start" href="/#"><h4>Start For Free</h4></a> </div> </div> <div> <div className="screen-but" onClick={ navBut } id="screenBut"> <div className="line1"></div> <div className="line2"></div> <div className="line3"></div> </div> </div> </div> <div className="nav-screen" id="nav-screen"> <ul> <li><a href="/#">Features <i className="fas fa-angle-down"></i></a></li> <li><Link to="/plan">Plans & Pricing</Link></li> <li><a href="/#">Resources <i className="fas fa-angle-down"></i></a></li> </ul> </div> </Fragment> ) } export default Navbar;
require('dotenv').config() const express = require('express'), massive = require('massive'), cors = require('cors'), session = require('express-session'), chalk = require('chalk'), bodyParser = require('body-parser'), socket = require('socket.io') const authCTRL = require('./controllers/authController') const prodCTRL = require('./controllers/productControllers') const { SERVER_PORT, CONNECTION_STRING, SESSION_SECRET } = process.env const app = express(), io = socket( app.listen(SERVER_PORT, ()=> console.log(chalk.cyan("Server is on mLord") )) ) app.use(express.json()) app.use(cors()) app.use(session({ resave: false, saveUninitialized: true, secret: SESSION_SECRET, cookie: { maxAge: 6000 } })) // ENDPOINTS // REGISTER N LOGIN N LOGOUT app.post('/auth/register', authCTRL.register) app.post('/auth/login', authCTRL.login) app.delete('/auth/logout', authCTRL.logout) // GET app.get('/api/helmet', prodCTRL.getHelmets) app.get('/api/shoulders', prodCTRL.getShoulders) app.get('/api/shafts' ,prodCTRL.getShafts) app.get('/api/heads', prodCTRL.getHeads) app.get('/api/gloves', prodCTRL.getGloves) app.get('/api/elbows', prodCTRL.getElbows) // Post app.post('/api/helmet',prodCTRL.postHelmets) app.post('api/shoulders', prodCTRL.postShoulder) app.post('/api/shafts', prodCTRL.postShafts) app.post('/api/heads', prodCTRL.postHeads) app.post('/api/gloves', prodCTRL.postGloves) app.post('/api/elbows' , prodCTRL.postElbows) // PUT app.put('/api/helmet/:id', prodCTRL.updateHelmets) app.put('/api/shoulders/:id', prodCTRL.updateShoulders) app.put('/api/shafts/:id', prodCTRL.updateShafts) app.put('/api/heads/:id', prodCTRL.updateHeads) app.put('/api/gloves/:id',prodCTRL.updateGloves) app.put('/api/elbows/:id', prodCTRL.updateElbows) // DELETE app.delete('/api/heads/:id', prodCTRL.deleteHeads) app.delete('/api/shoulders/:id', prodCTRL.deleteShoulder) app.delete('/api/gloves/:id', prodCTRL.deleteGloves) app.delete('/api/helmet/:id', prodCTRL.deleteHelmets) app.delete('/api/shafts/:id',prodCTRL.deleteShafts) app.delete('/api/elbows/:id',prodCTRL.deleteElbows) // TO HOST app.use( express.static( `${__dirname}/../build` ) ); massive(CONNECTION_STRING) .then(db =>{ app.set('db', db); console.log(chalk.cyan('database is connected')); }) .catch(error=> console.log(chalk.red('database connection severed')) ) io.on("connection", socket => { console.log("User Connected"); socket.on("join room", async data => { const { room } = data; const db = app.get("db"); console.log("Room joined", room); let existingRoom = await db.sessions.check_room({ id: room }); !existingRoom.length ? db.sessions.create_room({ id: room }) : null; let messages = await db.sessions.fetch_message_history({ id: room }); socket.join(room); io.to(room).emit("room joined", messages); }); socket.on("message sent", async data => { const { room, message } = data; const db = app.get("db"); await db.sessions.create_message({ id: room, message }); let messages = await db.sessions.fetch_message_history({ id: room }); io.to(data.room).emit("message dispatched", messages); }); socket.on("disconnect", () => { console.log("User Disconnected"); }); })
export * from './responsive'; export * from './constant'; export * from './helper'; export * from './ignore-warnings'; export * from './storage'; export * from './device'; export * from './date-time-format'; export * from './common-function';
export const inputStyles = { input: { width: "80%", borderWidth: 0.5, borderRadius: 2, padding: 8, } }
import React, { Component } from 'react' import { Link } from "react-router-dom"; import 'antd/dist/antd.css'; import { Table, Icon, Button, Tooltip } from 'antd'; import axios from 'axios'; import ContactForm from './model' import './../styles/style.css' class Contacts extends React.Component { constructor(props) { super(props); this.state = { contacts : [], columns: [], isOpen: false } this.rowSelection = { onChange: (selectedRowKeys, selectedRows) => { console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows); }, getCheckboxProps: record => ({ disabled: record.name === 'Disabled User', // Column configuration not to be checked name: record.name, }), }; this.handleClick = this.handleClick.bind(this); this.addContact = this.addContact.bind(this); this.deleteContact = this.deleteContact.bind(this); } componentDidMount() { axios .get('http://127.0.0.1:8000/users/') .then(({ data })=> { console.log(data); const columns =[{ title: 'SKU', dataIndex: 'SKU', }, { title: 'NAME', dataIndex: 'NAME', }, { title: 'LOCATION', dataIndex: 'LOCATION', }, { title: 'DEPARTMENT', dataIndex: 'DEPARTMENT', }, { title: 'CATEGORY', dataIndex: 'CATEGORY', }, { title: 'SUBCATEGORY', dataIndex: 'SUBCATEGORY', }, { title: 'Action', key: 'action', render: (text, record) => ( <Tooltip title="Delete a Contact"> <span> <a><Icon type="delete" className="font_25" className="delete_contact" onClick={()=>{this.deleteContact(record)}}/></a> </span> </Tooltip> ), } ] this.setState({ contacts: data, columns: columns }); }) .catch((err)=> {}) } handleClick() { this.setState({ isOpen: !this.state.isOpen }); } addContact(props, cb) { let { contacts } = this.state; props['Id'] = this.state.contacts.length; contacts.push(props); axios({ method: 'post', url: 'http://127.0.0.1:8000/users/', data: contacts, config: { headers: {'Content-Type': 'multipart/form-data' }} }) .then(function (response) { //handle success console.log(response); }) .catch(function (response) { //handle error console.log(response); }); this.setState({contacts: contacts}, function() { cb(); }); } deleteContact(record) { let { contacts, details, } = this.state; axios({ method: 'delete', url: 'http://127.0.0.1:8000/del/record.Id', data: contacts, config: { headers: {'Content-Type': 'multipart/form-data' }} }) .then(function (response) { //handle success console.log(response); }) .catch(function (response) { //handle error console.log(response); }); this.setState(contacts); } render() { console.log(this.state.isOpen,"isOpennnnnn"); return( <div> {this.state.isOpen ? <ContactForm addContact={this.addContact} isOpen={this.state.isOpen} handleClick={this.handleClick}/> : '' } <Button className="add_contact" type="primary" onClick={this.handleClick}>Add SKU</Button> <Table columns={this.state.columns} dataSource={this.state.contacts} /> </div> ); } } export default Contacts
import React from "react"; import { Box, Container, Typography, Link } from "@material-ui/core"; import makeStyles from "../../../styles/styles"; function Footer() { const styles = makeStyles(); return ( <Box className={styles.footer}> <Container className={styles.flexRowBetween}> <Typography display="inline" className={styles.textWhite}> <Link href="https://github.com/eskaine/fgo-grandmaster" className={`${styles.textWhite} ${styles.cursor}`}> eskaine </Link> &nbsp;© FGO Grandmaster 2020 </Typography> <Typography display="inline" className={styles.textWhite}> <Link href="https://www.fate-go.jp/" className={`${styles.textWhite} ${styles.cursor}`}> Fate/Grand Order </Link> &nbsp;© TYPE-MOON </Typography> </Container> </Box> ); } export default Footer; //
const Crypto = require('crypto') const { SHOPPY_SECRET } = process.env const validateShoppy = () => async (req, res, next) => { const hmac = Crypto.createHmac('sha512', SHOPPY_SECRET) hmac.update(req.rawBuf.toString()) const hash = hmac.digest('hex') if (!(req.headers['x-shoppy-signature'] === hash)) { console.log('Invalid shoppy signature!!!') res.status(500) return res.send() } return next() } module.exports = validateShoppy
import Vue from 'vue'; import router from 'components/routes'; import ElementUI from 'element-ui' Vue.use(ElementUI); export default new Vue({ router });
import InformationView from "../view/information.js"; import CostView from "../view/cost.js"; import RouteView from "../view/route.js"; import AbstractPointsPresenter from "./abstract-points.js"; import {render, RenderPosition, append, replace} from "../utils/render.js"; import {EventType} from "../const.js"; export default class InformationPresenter extends AbstractPointsPresenter { constructor(informationContainer, pointsModel, filtersModel) { super(pointsModel, filtersModel); this._container = informationContainer; this._updateViews = this._updateViews.bind(this); this._pointsModel.addObserver(this._updateViews); this._filtersModel.addObserver(this._updateViews); } init() { this._informationComponent = new InformationView(); this._routeComponent = new RouteView(this._getAllPoints()); this._costComponent = new CostView(this._getPoints()); append(this._informationComponent, this._routeComponent); append(this._informationComponent, this._costComponent); render( this._container, this._informationComponent, RenderPosition.AFTERBEGIN ); } _updateViews(eventType) { if (eventType === EventType.POINT) { this._updateRoute(); } this._updateCost(); this._updateRoute(); } _updateCost() { let prevCostComponent = this._costComponent; this._costComponent = new CostView(this._getPoints()); replace(this._costComponent, prevCostComponent); prevCostComponent = null; } _updateRoute() { let prevRouteComponent = this._routeComponent; this._routeComponent = new RouteView(this._getAllPoints()); replace(this._routeComponent, prevRouteComponent); prevRouteComponent = null; } }
export const DUMMY = { DUMMY_SUCCESS: "DUMMY_SUCCESS", }
const Sequelize = require('sequelize'); module.exports = function(sequelize, DataTypes) { return sequelize.define('QueueMessage', { id: { autoIncrement: true, type: DataTypes.BIGINT.UNSIGNED, allowNull: false, primaryKey: true, comment: "Message ID" }, topic_name: { type: DataTypes.STRING(255), allowNull: true, comment: "Message topic" }, body: { type: DataTypes.TEXT, allowNull: true, comment: "Message body" } }, { sequelize, tableName: 'queue_message', timestamps: false, indexes: [ { name: "PRIMARY", unique: true, using: "BTREE", fields: [ { name: "id" }, ] }, ] }); };
define([], function () { return { // spring boot endpoints ENDPOINT_INFO: "/info", ENDPOINT_CONFIG_PROPS: "/configprops", ENDPOINT_DUMP: "/dump", ENDPOINT_HEALTH: "/health", ENDPOINT_MAPPINGS: "/mappings", ENDPOINT_METRICS: "/metrics", ENDPOINT_BEANS: "/beans", ENDPOINT_ENVIRONMENT: "/env", ENDPOINT_AUTO_CONFIG: "/autoconfig", ENDPOINT_TRACE: "/trace", // measurement units UNIT_BYTE: 'BYTE', UNIT_KB: 'KB', UNIT_MB: 'MB', UNIT_GB: 'GB' } }) ;
function F(a, b) { return a + b; } var a = "one"; var b = 1; var c = a + "two"; var arr = [b, 2 + b, 3 - 1]; var x, y = true, z = "False"; x = y; y = z; z = 5; var d = F(b, z); var e = F(a, c);
import React, { Component } from 'react'; import 'bootstrap/dist/css/bootstrap.min.css'; import FullName from './component/profile/FullName'; import Address from './component/profile/Address'; import PhotoProfil from './component/profile/PhotoProfil'; import NavBar from './component/profile/NavBar'; import './App.css'; class App extends Component{ render(){ return( <div style={{border: '5px solid red', maxWidth:''}}> <NavBar/> <FullName/> <Address/> <PhotoProfil/> </div> ); } } export default App;
function integerToString(number) { const LETTER_DIGITS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; var total = ''; var digit = number; do { digit = number % 10; total = (LETTER_DIGITS[digit]) + total; number = Math.floor(number / 10); } while (number >= 1) return total } console.log(integerToString(4321)); // "4321" console.log(integerToString(0)); // "0" console.log(integerToString(5000)); // "5000" console.log(integerToString(123)); // "123"
const chai = require("chai"); const assert = chai.assert; const parBalance = require("../app.js").parBalance; describe("Testing if Given a string including parentheses, write a function that returns true if every opening parenthesis has a closing parenthesis.", function() { it ("Should be true", function() { assert.isTrue(parBalance("()()"), true) }) it ("Should be true", function() { assert.isTrue(parBalance("(())"), true) }) it ("Should be false", function() { assert.isFalse(parBalance("()))"), false) }) it ("Should be false", function() { assert.isFalse(parBalance(")()("), false) }) it ("Should be false", function() { assert.isFalse(parBalance("())("), false) }) })
// Written by Yujie Chen, Summer 2019 $(document).ready(function() { "use strict"; var av_name = "BSTCheckCON"; var av = new JSAV(av_name, {animationMode: "none"}); // Setup the init location of tree var btTop = 0; var btLeft = 180 + 150; var cirOpt = {fill: "white"}; var bt = av.ds.binarytree({nodegap: 15, left: btLeft, top: btTop}); bt.root("20"); var rt = bt.root(); rt.right("50"); rt.right().left("40"); rt.right().right("75"); rt.right().left().left(""); // the covered leaf node //adding the leaf node "20 to 40" av.label("20 to 40", {visible: true, left: 325, top: 147}); av.g.ellipse(350, 173, 35, 16, cirOpt); bt.layout(); av.displayInit(); av.recorded(); });
function checkLength(){ let length = document.getElementById("myText").value.length; let lengthEL = document.createElement('p'); lengthEL.innerHTML = "Length: " + length; document.getElementById("elementlol").innerHTML = "Length: " + length; }
// before hook => sets initial gamestate on game creation module.exports = function(hook) { // default game owner: currently logged in user const creator = hook.params.user const board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '] // set the game's creator to player one hook.data.playerOneId = creator._id // set the current turn to player one hook.data.turn = 1 // set the board hook.data.board = board }
import { Box, Container } from '@material-ui/core' import React from 'react' import WindowBody from './WindowBody' import WindowHead from './WindowHead' export default function Window(props) { return <Container maxWidth={props.maxWidth}> <WindowHead title={props.title} Icon={props.Icon} /> <Box p={2}> <WindowBody> {props.children} </WindowBody> </Box> </Container> }
const digits = n => { if (n === 0) return [0]; let i = Math.abs(Math.floor(n)); const digits = []; while (i > 0) { digits.unshift(i % 10); i = Math.floor(i / 10); } return digits; }; module.exports = digits;
/* Ejercicio 66 Crear un documento con el nombre ej66.js Mostrar en consola los números del 0 al 10 utilizando la estructura while */ let numero = 0; while(numero <= 10) { console.log('Numero: ', numero); numero ++; }
/* global console, SLang, PLutils */ (function() { "use strict"; var CallByValVsRef = { init: function() { var SL = SLang; var A = SL.absyn; var E = SL.env; var vs = "xyz"; var fs = "fgh"; var exp, expStr; var value, value2, rnd, iterations; var globalEnv = E.update(E.createEmptyEnv(), ["x","y","z"], [E.createNum(1), E.createNum(2), E.createNum(3)]); function headsOrTails() { return A.getRnd(0,1)===0; } function getRandomPrimApp(variables) { // assumes that variables.length >= 2 var v = variables.split(""); PLutils.shuffle(v); var body; var incr = A.createPrimApp1Exp("add1",A.createVarExp(v[0])); var addition1 = A.createPrimApp2Exp(headsOrTails() ? "+" : "-", A.createVarExp(v[0]), A.createVarExp(v[1])); var addition2 = A.createPrimApp2Exp(headsOrTails() ? "+" : "-", A.createIntExp(A.getRnd(3,10)), A.createVarExp(v[2])); var addition3 = A.createPrimApp2Exp(headsOrTails() ? "+" : "-", A.createVarExp(v[1]), A.createIntExp(A.getRnd(3,10))); var mult1 = A.createPrimApp2Exp("*", A.createVarExp(v[0]), A.createVarExp(v[1])); var mult2 = A.createPrimApp2Exp("*", A.createIntExp(A.getRnd(3,10)), A.createVarExp(v[2])); var mult3 = A.createPrimApp2Exp("*", A.createVarExp(v[1]), A.createIntExp(A.getRnd(3,10))); PLutils.shuffle(v); switch (A.getRnd(0,22)) { case 0: body = incr; break; case 1: body = addition1; break; case 2: body = addition2; break; case 3: body = addition3; break; case 4: body = mult1; break; case 5: body = mult2; break; case 6: body = mult3; break; case 7: body = A.createPrimApp2Exp(headsOrTails() ? "+" : "-", A.createVarExp(v[0]), mult1 ); break; case 8: body = A.createPrimApp2Exp(headsOrTails() ? "+" : "-", A.createVarExp(v[0]), mult2 ); break; case 9: body = A.createPrimApp2Exp(headsOrTails() ? "+" : "-", A.createVarExp(v[0]), mult3 ); break; case 10: body = A.createPrimApp2Exp(headsOrTails() ? "+" : "-", mult1, A.createVarExp(v[0]) ); break; case 11: body = A.createPrimApp2Exp(headsOrTails() ? "+" : "-", mult2, A.createVarExp(v[0]) ); break; case 12: body = A.createPrimApp2Exp(headsOrTails() ? "+" : "-", mult3, A.createVarExp(v[0]) ); break; case 13: body = A.createPrimApp2Exp(headsOrTails() ? "+" : "-", incr, A.createVarExp(v[0]) ); break; case 14: body = A.createPrimApp2Exp(headsOrTails() ? "+" : "-", A.createVarExp(v[0]), incr ); break; case 15: body = A.createPrimApp2Exp("*", incr, A.createVarExp(v[0]) ); break; case 16: body = A.createPrimApp2Exp("*", A.createVarExp(v[0]), incr ); break; case 17: body = A.createPrimApp2Exp("*", A.createVarExp(v[0]), addition1 ); break; case 18: body = A.createPrimApp2Exp("*", A.createVarExp(v[0]), addition2 ); break; case 19: body = A.createPrimApp2Exp("*", A.createVarExp(v[0]), addition3 ); break; case 20: body = A.createPrimApp2Exp("*", addition1, A.createVarExp(v[0]) ); break; case 21: body = A.createPrimApp2Exp("*", addition2, A.createVarExp(v[0]) ); break; case 22: body = A.createPrimApp2Exp("*", addition3, A.createVarExp(v[0]) ); break; } return body; }// getRandomPrimApp function function getRandomAssignment() { // returns: // a_or_b = random_func_of_a_and_b // var LHS = headsOrTails() ? "a" : "b"; var RHS; // in order to not have to change the original function // from which getRandomPrimApp was copied, which uses 3 // vars, even though we have only tw vars (a and b)... RHS = headsOrTails() ? getRandomPrimApp("aba") : getRandomPrimApp("abb"); return A.createAssignExp(LHS,RHS); } function getRandomBody() { // returns: between 3 and 5 copies of the following // a_or_b = random_func_of_a_and_b // var body = [ ]; var i, rnd = A.getRnd(3,5); var aModified = false, bModified = false; var assignment; for(i=0; i<rnd; i++) { assignment = getRandomAssignment(); body.push( assignment ); if (A.getAssignExpVar(assignment) === "a") { aModified = true; } else { bModified = true; } } if (! aModified) { while (true) { assignment = getRandomAssignment(); if (A.getAssignExpVar(assignment) === "a") { break; } } body[ A.getRnd(0,body.length) ] = assignment; } if (! bModified) { while (true) { assignment = getRandomAssignment(); if (A.getAssignExpVar(assignment) === "b") { break; } } body[ A.getRnd(0,body.length) ] = assignment; } return body; } function assignmentToCppSyntax(assignment) { function isAtomic(exp) { return A.isIntExp(exp) || A.isVarExp(exp); } function arithmeticToString(exp) { var op, left, right; if (A.isIntExp(exp)) { return A.getIntExpValue(exp) + ""; } else if (A.isVarExp(exp)) { return A.getVarExpId(exp); } else if (A.isPrimApp2Exp(exp)) { op = A.getPrimApp2ExpPrim(exp); left = A.getPrimApp2ExpArg1(exp); right = A.getPrimApp2ExpArg2(exp); if (isAtomic(left)) { if (isAtomic(right)) { return arithmeticToString(left) + op + arithmeticToString(right); } else { return arithmeticToString(left) + op + "(" + arithmeticToString(right) +")"; } } else { if (isAtomic(right)) { return "(" + arithmeticToString(left) + ")" + op + arithmeticToString(right); } else { return "(" + arithmeticToString(left) + ")"+ op + "(" + arithmeticToString(right) +")"; } } } else { // add1 case return arithmeticToString(A.getPrimApp1ExpArg(exp)) + "+1"; } } var LHS = A.getAssignExpVar(assignment); return " " + LHS + " = " + arithmeticToString(A.getAssignExpRHS(assignment)); } function convertToCppSyntax(exp) { var xVal = A.getIntExpValue( A.getAppExpArgs(exp)[0] ); var yVal = A.getIntExpValue( A.getAppExpArgs(exp)[1] ); var body = A.getFnExpBody( A.getAppExpArgs(exp)[2] ); var i; var code = [ "#include &lt;iostream&gt;", "using namespace std;", "", "void by_value(int a, int b) {"]; var shared = []; for(i = 0; i<body.length; i++) { shared.push( assignmentToCppSyntax(body[i]) + ";" ); } code = code.concat(shared); code.push( "}" ); code.push( "void by_reference(int &a, int &b) {" ); code = code.concat(shared); code.push( "}" ); code.push( "" ); code.push("int main() {"); code.push(" int x,y;"); code.push(" x = " + xVal + "; y = " + yVal + ";"); code.push(" by_value(" + exp.v1 + "," + exp.v2 + ");"); if (exp.v1 === exp.v2) { code.push(" cout &lt;&lt; " + exp.v1 + " &lt;&lt; endl;"); } else { code.push(" cout &lt;&lt; x &lt;&lt; endl &lt;&lt; y &lt;&lt; endl;"); } code.push(" "); code.push(" x = " + xVal + "; y = " + yVal + ";"); code.push(" by_reference(" + exp.v1 + "," + exp.v2 + ");"); if (exp.v1 === exp.v2) { code.push(" cout &lt;&lt; " + exp.v1 + " &lt;&lt; endl;"); } else { code.push(" cout &lt;&lt; x &lt;&lt; endl &lt;&lt; y &lt;&lt; endl;"); } code.push( "}" ); return code; } function getRndExpCallByValVsRef() { // structure of exp: // let x =<int> y = <int> // f = fn (a,b) => let notUsed=-1 in body1 end // in // (f x y); // this is body below // print x; // print y // end // that is: // (fn (x,y,f) =>(fn(_)=>body -1) <int> <int> fn(a,b)=>body1 ) // where body = (f v1 v2); print v1; print v2 // or body = (f v v); print v // and body assigns a and b using between 2 and 4 assignments var xVal = A.getRnd(4,10); var yVal = A.getRnd(4,10); var innerApp, innerFunc, body = [], args; var fVarExp = A.createVarExp("f"); var v1 = headsOrTails() ? "x" : "y"; var v2 = headsOrTails() ? "x" : "y"; var v1VarExp = A.createVarExp(v1); var v2VarExp = A.createVarExp(v2); var output; body.push(A.createAppExp(fVarExp,["args",v1VarExp,v2VarExp])); if (v1 !== v2) { body.push(A.createPrintExp(A.createVarExp("x"))); body.push(A.createPrintExp(A.createVarExp("y"))); } else { body.push(A.createPrintExp(v1VarExp)); } innerFunc = A.createFnExp(["notUsed"],body); innerApp = A.createAppExp(innerFunc, ["args",A.createIntExp(-1)]); innerApp.comesFromLetBlock = true; // to avoid call by ref args = ["args", A.createIntExp(xVal),A.createIntExp(yVal)]; args.push( A.createFnExp(["a","b"], getRandomBody() ) ); output= SL.absyn.createAppExp( SL.absyn.createFnExp(["x","y","f"],[ innerApp ]), args); output.comesFromLetBlock = true; // to avoid call by ref output.v1 = v1; output.v2 = v2; return output; }// getRndExpCallByValVsRef function function callByValueCallByValVsRef(exp,envir) { var f = evalExpCallByValVsRef(A.getAppExpFn(exp),envir); var args = evalExpsCallByValVsRef(A.getAppExpArgs(exp),envir); if (E.isClo(f)) { if (E.getCloParams(f).length !== args.length) { throw new Error("Runtime error: wrong number of arguments in " + "a function call (" + E.getCloParams(f).length + " expected but " + args.length + " given)"); } else { var values = evalExpsCallByValVsRef(E.getCloBody(f), E.update(E.getCloEnv(f), E.getCloParams(f),args)); return values[values.length-1]; } } else { throw f + " is not a closure and thus cannot be applied."; } } function callByReferenceCallByValVsRef(exp,envir) { var f = evalExpCallByValVsRef(A.getAppExpFn(exp),envir); var args = A.getAppExpArgs(exp).map( function (arg) { if (A.isVarExp(arg)) { return E.lookupReference(envir,A.getVarExpId(arg)); } else { throw new Error("The arguments of a function called by-ref must all be variables."); } } ); if (E.isClo(f)) { if (E.getCloParams(f).length !== args.length) { throw new Error("Runtime error: wrong number of arguments in " + "a function call (" + E.getCloParams(f).length + " expected but " + args.length + " given)"); } else { var values = evalExpsCallByValVsRef(E.getCloBody(f), E.updateWithReferences( E.getCloEnv(f), E.getCloParams(f),args)); return values[values.length-1]; } } else { throw new Error(f + " is not a closure and thus cannot be applied."); } } function evalExpsCallByValVsRef(list,envir) { return list.map( function(e) { return evalExpCallByValVsRef(e,envir); } ); } function evalExpCallByValVsRef(exp,envir) { if (A.isIntExp(exp)) { return E.createNum(A.getIntExpValue(exp)); } else if (A.isVarExp(exp)) { return E.lookup(envir,A.getVarExpId(exp)); } else if (A.isPrintExp(exp)) { SL.output += JSON.stringify( evalExpCallByValVsRef( A.getPrintExpExp(exp), envir )); } else if (A.isPrint2Exp(exp)) { SL.output += A.getPrint2ExpString(exp) + (A.getPrint2ExpExp(exp) !== null ? " " + JSON.stringify( evalExpCallByValVsRef( A.getPrint2ExpExp(exp), envir ) ) : ""); } else if (A.isAssignExp(exp)) { var v = evalExpCallByValVsRef(A.getAssignExpRHS(exp),envir); E.lookupReference( envir,A.getAssignExpVar(exp))[0] = v; return v; } else if (A.isFnExp(exp)) { return E.createClo(A.getFnExpParams(exp), A.getFnExpBody(exp),envir); } else if (A.isAppExp(exp)) { if (exp.comesFromLetBlock) { return callByValueCallByValVsRef(exp,envir); } else { switch (SL.ppm) { case "byval" : return callByValueCallByValVsRef(exp,envir); case "byref" : return callByReferenceCallByValVsRef(exp,envir); } } } else if (A.isPrimApp1Exp(exp)) { return SL.applyPrimitive(A.getPrimApp1ExpPrim(exp), [evalExpCallByValVsRef(A.getPrimApp1ExpArg(exp),envir)]); } else if (A.isPrimApp2Exp(exp)) { return SL.applyPrimitive(A.getPrimApp2ExpPrim(exp), [evalExpCallByValVsRef(A.getPrimApp2ExpArg1(exp),envir), evalExpCallByValVsRef(A.getPrimApp2ExpArg2(exp),envir)]); } else if (A.isIfExp(exp)) { if (E.getBoolValue(evalExpCallByValVsRef(A.getIfExpCond(exp),envir))) { return evalExpCallByValVsRef(A.getIfExpThen(exp),envir); } else { return evalExpCallByValVsRef(A.getIfExpElse(exp),envir); } } else { throw "Error: Attempting to evaluate an invalid expression"; } }// evalExpCallByValVsRef function iterations = 0; while(true) { exp = undefined; iterations++; exp = getRndExpCallByValVsRef(); expStr = convertToCppSyntax(exp); value = null; try { expStr = undefined; SL.output = ""; SL.ppm = "byval"; value = evalExpCallByValVsRef(exp,globalEnv); SL.ppm = "byref"; value2 = evalExpCallByValVsRef(exp,globalEnv); expStr = convertToCppSyntax(exp); } catch (e) { //console.log("My exception: ",e); } if (value !== null && value2 !== null && SL.output.match(/-?\d+/g).filter( function (s) { return s.length > 6; } ) .length === 0) { // no printed number is longer than 6 digits this.answer = SL.output.match(/-?\d+/g).join(" "); break; } if (iterations > 500) { // not needed locally but might be needed on Canvas // when the files do not load appropriately??? expStr = ["Something went wrong...", "Please, reload the page."]; break; } } this.expression = expStr.join("<br />"); this.hint3 = "</br><span style=\"font-family: 'Courier New'\">" + SL.output.match(/-?\d+/g).join("</br>") + "</span>"; },// init function validateAnswer: function (guess) { return this.answer.replace(/\s+/g,"") === guess.replace(/\s+/g,""); }// validateAnswer function }; window.CallByValVsRef = window.CallByValVsRef || CallByValVsRef; }());
class Pluto { constructor() { const geom = new THREE.SphereGeometry(0.16, 40, 40); const mat = new THREE.MeshPhongMaterial({ map: new THREE.TextureLoader().load("./assets/img/pluto.jpg") }); this.mesh = new THREE.Mesh(geom, mat); } animate() { this.mesh.rotation.y += 0.01; let date = Date.now() * -0.0000000004; this.mesh.position.set(Math.cos(date) * 3670, 0, Math.sin(date) * 3670); } } export default Pluto;
import React, { useState, useEffect } from "react"; import MenuOpenIcon from "@material-ui/icons/MenuOpen"; import img from "./img/net.png" const Nav = () => { const [show, setshow] = useState(false); useEffect(() => { window.addEventListener("scroll", () => { if (window.scrollY > 200) { setshow(!show); } else { setshow(show); } }); }, []); return ( <div className={`nav ${show && "show"} `}> <div className="nav_info p-3 d-flex justify-content-between"> <img src={img} alt="logo" /> <MenuOpenIcon className="nav_icon" /> </div> </div> ); }; export default Nav;
class CarFactoryMethod { constructor () { this.cheap = 'cheap'; this.fast = 'fast'; } create (type) { return this.makeCar(type); } } module.exports = CarFactoryMethod;
import * as actionTypes from '../actions/actionTypes'; import { updateObject } from '../utility'; const initialState = { fetchedIngredients: null, chosenIngredients: null, totalIgCount: 0, error: false, }; const addIngredient = (state, action) => { return updateObject(state, { error: false, totalIgCount: state.totalIgCount + 1, chosenIngredients: { ...state.chosenIngredients, [action.payload.ingredient]: state.chosenIngredients[action.payload.ingredient] + 1, }, }); }; const removeIngredient = (state, action) => { return action.payload.currentQuantity > 0 ? updateObject(state, { totalIgCount: state.totalIgCount - 1, error: false, chosenIngredients: { ...state.chosenIngredients, [action.payload.ingredient]: state.chosenIngredients[action.payload.ingredient] - 1, }, }) : state; }; const setIngredients = (state, action) => { return updateObject(state, { fetchedIngredients: action.payload.ingredients, chosenIngredients: action.payload.ingredients, error: false, }); }; const resetOrder = (state, action) => { return updateObject(state, { chosenIngredients: { ...state.fetchedIngredients }, totalIgCount: 0, error: false, }); }; const ingredientsReducer = (state = initialState, action) => { switch (action.type) { case actionTypes.SET_INGREDIENTS: return setIngredients(state, action); case actionTypes.FETCH_INGREDIENTS_FAILED: return updateObject(state, { error: true }); case actionTypes.ADD_INGREDIENT: return addIngredient(state, action); case actionTypes.REMOVE_INGREDIENT: return removeIngredient(state, action); case actionTypes.RESET_ORDER: return resetOrder(state, action); default: return state; } }; export default ingredientsReducer;
import { Mongo } from 'meteor/mongo'; const gizmos = new Mongo.Collection('gizmos'); export default gizmos;
import React, { Component } from "react"; import { data } from "./data.js"; import ReactTable from "react-table"; import "react-table/react-table.css"; class App extends Component { constructor() { super(); this.state = { data: [], }; } componentDidMount() { this.setState({ data: data() }); } render() { const { data } = this.state; const alphabet = "ABCEFGHIJKLMNOPQRSTUVWXYZ".split(""); return ( <div className="App"> <header className="App-header"> <h1 className="App-title">Genesis Report</h1> </header> <p className="App-intro"> Please hold shift the sub-headers when multi sorting! </p> <div className="table"> <ReactTable data={data} filterable defaultFilterMethod={(filter, row) => String(row[filter.id]) === filter.value } columns={[ { Header: "Table", columns: [ ////////// Row # ////////// { Header: "Row #", id: "id", accessor: d => data.indexOf(d) + 1, width: 100 }, ////////// First Name ////////// { Header: "First Name", id: "firstName", accessor: d => d.firstName[0].toUpperCase() + d.firstName.slice(1), filterMethod: (filter, row) => row[filter.id].startsWith(filter.value) }, ////////// Last Name ////////// { Header: "Last Name", id: "lastName", accessor: d => d.lastName[0].toUpperCase() + d.lastName.slice(1), Filter: ({ filter, onChange }) => ( <select onChange={event => onChange(event.target.value)} style={{ width: "100%", height: "30px" }} value={filter ? filter.value : "all"} > <option value="all">Show All</option> {alphabet.map(a => ( <option key={alphabet.indexOf(a)} value={a}> Start with {a} </option> ))} </select> ), filterMethod: (filter, row) => { // if() row[filter.id].toString()[0] === filter.value[0] if (filter.value === "all") return true; return row[filter.id].startsWith(filter.value); } }, ////////// Age Range ////////// { Header: "Age Option 1", accessor: "age", filterMethod: (filter, row) => { console.log(filter, row); if (filter.value === "50") return row[filter.id]; else if (filter.value.length === 1) return ( row[filter.id].toString()[0] === filter.value.toString()[0] ); else return row[filter.id].toString() === filter.value; }, Filter: ({ filter, onChange }) => ( <div className="specific-age"> <input className="rangeBar" onChange={event => onChange(event.target.value)} type="range" min="20" max="50" value={filter ? filter.value : "all"} /> <span className="selectedNumber"> { filter && filter.value } </span> </div> ) }, ////////// Age Selection ////////// { Header: "Age Option2", accessor: "age", Filter: ({ filter, onChange }) => ( <select onChange={event => onChange(event.target.value)} style={{ width: "100%", height: "30px" }} value={filter ? filter.value : "50"} > <option value="50">Show All</option> <option label="20~29 yrs old" value="2" /> <option label="30~39 yrs old" value="3" /> <option label="40~49 yrs old" value="4" /> </select> ) }, ////////// Status ////////// { Header: "Status", accessor: "status", filterMethod: (filter, row) => { if (filter.value === "all") return true; else if (filter.value === "true") return row[filter.id] === "Employed"; else return row[filter.id] === "Unemployed"; }, Filter: ({ filter, onChange }) => ( <select onChange={event => onChange(event.target.value)} style={{ width: "100%", height: "30px" }} value={filter ? filter.value : "all"} > <option value="all">Show All</option> <option value="true">Employed</option> <option value="false">Unemployed</option> </select> ) }, ////////// Marital Status ////////// { Header: "Marital Status", accessor: "marital", filterMethod: (filter, row) => { if (filter.value === "all") return true; else if (filter.value === "true") return row[filter.id] === "Married"; else return row[filter.id] === "Single"; }, Filter: ({ filter, onChange }) => ( <select onChange={event => onChange(event.target.value)} style={{ width: "100%", height: "30px" }} value={filter ? filter.value : "all"} > <option value="all">Show All</option> <option value="true">Married</option> <option value="false">Single</option> </select> ) } ] } ]} style={{ height: "480px" }} defaultPageSize={20} className="-striped -highlight" /> <br /> </div> </div> ); } } export default App;
/** * Alexander McCaleb * CMPS 179 - Summer 2013 * Prototype2 - Thumper * * Dancer.js * * Represents a dancer in Thumper * * Animation code courtesy of: * http://stemkoski.github.io/Three.js/Model-Animation.html * * Based on Robot.js from Shift Escape * */ var Dancer = function(position) { var that = this; //// A Dancer is a game object // Default position if unspecified is at square 0, 0 this.boardPosition = position || { x : 0, y : 0 }; this.boardPosition.z = 0; this.type = 'dancer'; this.object = null; // Initialize animation properties // the following code is from http://catchvar.com/threejs-animating-blender-models // starting frame of animation this.animOffset = 0; this.walking = false; // milliseconds to complete animation this.duration = 1000; // total number of animation frames this.keyframes = 20; // milliseconds per frame this.interpolation = this.duration / this.keyframes; // previous keyframe this.lastKeyframe = 0; this.currentKeyframe = 0; // State booleans to maintain the status of this dancer this.isLoaded = false; // true when the callback following the JSONLoader completes this.isLive = false; // true when the dancer is part of the active scene // Load up the animation for our dancer //TODO: Put Zombie model back in var jsonLoader = new THREE.JSONLoader(); jsonLoader.load("models/android/android-animated.js", function(geometry, materials) { // for preparing animation for (var i = 0; i < materials.length; i++) materials[i].morphTargets = true; var material = new THREE.MeshFaceMaterial(materials); that.object = new THREE.Mesh(geometry, material); that.object.scale.set(10, 10, 10); that.object.rotation.set(Math.PI / 2, Math.PI, 0); // A mesh is an Object3D, change its position to move that.object.position = board_to_world(that.boardPosition); that.isLoaded = true; }); }; /** * Makes the dancer dance */ Dancer.prototype.animate = function() { // Alternate morph targets var time = new Date().getTime() % this.duration; this.keyframe = Math.floor(time / this.interpolation) + this.animOffset; if (this.keyframe != this.currentKeyframe) { this.object.morphTargetInfluences[this.lastKeyframe] = 0; this.object.morphTargetInfluences[this.currentKeyframe] = 1; this.object.morphTargetInfluences[this.keyframe] = 0; this.lastKeyframe = this.currentKeyframe; this.currentKeyframe = this.keyframe; } this.object.morphTargetInfluences[this.keyframe] = (time % this.interpolation ) / this.interpolation; this.object.morphTargetInfluences[this.lastKeyframe] = 1 - this.object.morphTargetInfluences[this.keyframe]; };
const ServerErrors = require('./ServerErrors'); const { Comment } = require('../schemas/Comment'); const ClientErrors = require('./ClientErrors'); const axios = require('axios'); const { API } = process.env; // 搜尋有無該評論且該評論屬於目前登入的使用者 async function findCommitBelongToCertainUser(args) { try { const result = await Comment.findOne({ where: { id: args.comment_id, uid: args.user.id }, raw: true }); if (!result) return Promise.reject(new ClientErrors.CommentNotFound()); return Promise.resolve(); } catch (err) { return Promise.reject(new ServerErrors.MySQLError(err.stack)); } }; // 從 API 取得資料 async function getDataFromAPI() { try { const { data } = await axios.get(API); return Promise.resolve(data.retVal); } catch (err) { console.log(err); return Promise.reject(new ServerErrors.GetDataFromAPI(err.stack)); } } module.exports = { findCommitBelongToCertainUser, getDataFromAPI };
var searchData= [ ['opcoes_5fmenu_321',['opcoes_menu',['../group__menu.html#ga102ddb81f11b0a2562aae64e5e2c1fe9',1,'opcoes_menu():&#160;menu.c'],['../group__menu.html#ga102ddb81f11b0a2562aae64e5e2c1fe9',1,'opcoes_menu():&#160;menu.c']]] ];
const mongoose = require('mongoose'); const dotenv = require('dotenv'); dotenv.config({ path: './config.env' }); // this error handler can be before server starts before this errors are not catched async. // we define it before app js to catch errors inside that module. // uncaught exceptions: errors occur in synchronous code: process.on('uncaughtException', (err) => { console.log('UNCAUGHT EXCEPTION!! Shutting down...'); console.log(err.name, err.message); process.exit(1); }); const app = require('./app'); const db = process.env.DATABASE_LOCAL; const started = new Date(); console.info(`Connecting to Mongoose: ${started.toLocaleTimeString()}`); const tm = function (startTime, failVal) { const end = new Date() - startTime; const fail = end <= failVal ? 'pass' : 'fail'; return `${new Date().toLocaleTimeString()}: ${end .toString() .padStart(5, ' ')} ms : ${fail}`; }; mongoose .connect(db, { useNewUrlParser: true, useCreateIndex: true, useFindAndModify: false, useUnifiedTopology: true, }) .then(() => { console.log('DB connection successful!!', tm(started, 20000)); }); const port = process.env.PORT || 3000; const server = app.listen(port, () => { console.log(`App listening on port ${port}...`); }); process.on('unhandledRejection', (err) => { console.log('UNHANDLER REJECTION!! Shutting down...'); console.log(err.name, err.message); server.close(() => { process.exit(1); }); }); // the way that Heroku does this is by sending the so-called "sick term signal" // to our note application, and the application will then basically shut down immediately. // SIGTERM is an event that can be emitted and that our application receives and can then respond to. process.on('SIGTERM', () => { console.log('SIGTERM RECEIVED. Shutting down gracefully'); server.close(() => { console.log('Process terminated'); }); });
(function ($) { var hideEffect = { opacity: 0 }; var showEffect = { opacity: 1 }; if (!$.support.opacity) { hideEffect = { }; showEffect = { }; } var Orbiter = function ($sourceElement, options) { this.$sourceElement = $sourceElement; this.options = options; this.$sourceElement .css({ cursor: this.options.loadTrigger === 'click' ? 'pointer' : undefined }) .disableSelection(); this.$container = $(document.createElement('div')) .addClass('orbiter') .css({ display: 'inline-block', position: 'relative' }) .disableSelection() .data('orbiter', this); this.$featureBoxContainer = $(document.createElement('div')) .css({ display: 'block', position: 'absolute', left: 0, right: 0, top: 0, bottom: 0 }) .hide() .css(hideEffect) .gxInit({ queue: 'cancel' }) .appendTo(this.$container); this.rotationCount = options.rotationCount; this.rotationsPerFrame = options.rotationsPerFrame; this.pixelsPerRotation = options.pixelsPerRotation; this.features = this.options.features; this.frameImages = [ ]; this.featureBoxes = { }; this.isLoaded = false; this.bind(); }; Orbiter.prototype = { updateViewer: function () { throw 'Implement updateViewer in a subclass'; }, getViewer$: function () { throw 'Implement getViewer$ i na subclass'; }, bind: function () { var orbiter = this; function isLeftMouseButton(e) { return e.which === 1; } function onDown(e) { if (isLeftMouseButton(e)) { orbiter.down(e.screenX, e.screenY); $(document).one('mouseup', onUp); $(document).bind('mousemove', onMove); } } function onMove(e) { if (isLeftMouseButton(e)) { orbiter.move(e.screenX, e.screenY); } } function onUp(e) { if (isLeftMouseButton(e)) { orbiter.up(e.screenX, e.screenY); $(document).unbind('mousemove', onMove); } } function onTouchDown(e) { // No, this isn't American football e.preventDefault(); orbiter.down(e.targetTouches[0].screenX, e.targetTouches[0].screenY); return true; } function onTouchMove(e) { e.preventDefault(); orbiter.move(e.targetTouches[0].screenX, e.targetTouches[0].screenY); return true; } function onTouchUp(e) { // FIXME what if they're still touching? e.preventDefault(); orbiter.up(e.changedTouches[0].screenX, e.changedTouches[0].screenY); return true; } this.$container.bind('mousedown', onDown); // jQuery binding doesn't work for some reason // TODO Submit a bug report... this.$container[0].ontouchstart = onTouchDown; this.$container[0].ontouchmove = onTouchMove; this.$container[0].ontouchend = onTouchUp; // This is required for some reason... if (document.addEventListener != undefined && document.addEventListener != null) { document.addEventListener('touchstart', function() {}, false); } this.$container.bind('mouseenter', function () { orbiter.$featureBoxContainer .show() .gx(showEffect, orbiter.options.featureMouseInTime, orbiter.options.featureMouseInEasing); }); this.$container.bind('mouseleave', function () { orbiter.$featureBoxContainer .gx(hideEffect, orbiter.options.featureMouseOutTime, orbiter.options.featureMouseOutEasing, function () { orbiter.$featureBoxContainer.hide(); }); }); }, load: function () { if (this.isLoaded) { return; } this.showLoading(); var orbiter = this; this.loadAllFrames(function () { orbiter.isLoaded = true; orbiter.setRotation(0); var $viewer = orbiter.getViewer$() .appendTo(orbiter.$container); orbiter.$container.css({ width: orbiter.$sourceElement.width(), height: orbiter.$sourceElement.height() }); orbiter.hideLoading(function () { orbiter.$sourceElement.replaceWith(orbiter.$container); }); }); }, showLoading: function () { // TODO Maybe split this into its own class or something if (!this.options.showLoading) { return; } var orbiter = this; this.$sourceElement.css({ cursor: 'wait' }); this.loadingTimeout = window.setTimeout(function () { var region = orbiter.$sourceElement.offset(); region.width = orbiter.$sourceElement.width(); region.height = orbiter.$sourceElement.height(); var loaderImageSize = { width: 32, height: 32 }; orbiter.$sourceElement.animate({ opacity: 0.5 }, 500); orbiter.$loading = $(document.createElement('img')) .attr('src', 'images/loader.gif') .css({ position: 'absolute', left: region.left + (region.width - loaderImageSize.width ) / 2, top: region.top + (region.height - loaderImageSize.height) / 2 }) .appendTo(document.body); }, 0); }, hideLoading: function (callback) { if (!this.options.showLoading) { callback(); return; } if (this.loadingTimeout) { window.clearTimeout(this.loadingTimeout); } this.$sourceElement .css({ cursor: '' }) .animate({ opacity: 1 }, 200, callback); if (this.$loading) { this.$loading.remove(); this.$loading = null; } }, loadAllFrames: function (callback) { var totalFrames = Math.ceil(this.rotationCount / this.rotationsPerFrame); var framesRemaining = totalFrames; function frameLoaded() { --framesRemaining; if (framesRemaining <= 0) { callback(); } } var frame; for (frame = 0; frame < totalFrames; ++frame) { this.loadFrameImage(frame, frameLoaded); } }, wrapRotation: function (rotation) { var rotationCount = this.rotationCount; if (rotationCount === 0) { // We could be here a while... return 0; } while (rotation >= rotationCount) { rotation -= rotationCount; } while (rotation < 0) { rotation += rotationCount; } return rotation; }, setRotation: function (rotation) { if (parseInt(rotation, 10) != rotation) { // (Loose comparison intentional) alert ("rotation: " + rotation); throw 'Rotation number must be an integer'; } rotation = parseInt(rotation, 10); if (rotation < 0 || rotation >= this.rotationCount) { throw 'Rotation number out of range'; } if (rotation === this.currentRotation) { return; } this.currentRotation = rotation; this.updateViewer(); this.updateFeatureBoxes(); }, updateFeatureBoxes: function (rotation) { var orbiter = this; var currentFeatures = this.getFeatures(this.currentRotation); var currentFeatureNames = $(currentFeatureNames).map(function () { return this.name; }).get(); // Hide inactive boxes $.each(this.featureBoxes, function (text, $element) { if ($(currentFeatureNames).index(text) < 0) { if ($element.isFadingOut) { return; } $element.gx(hideEffect, orbiter.options.featureFadeOutTime, orbiter.options.featureFadeOutEasing, function () { delete orbiter.featureBoxes[text]; $element.hide(); }); $element.isFadingOut = true; } }); $(currentFeatures).each(function () { var $element = orbiter.featureBoxes[this.name]; if ($element) { $element.isFadingOut = false; $element.show(); $element.gx($.extend({ }, showEffect, this.position), orbiter.options.featureFadeInTime, orbiter.options.featureFadeInEasing); } else { $element = $(document.createElement('div')) .addClass('orbiter-feature') .css(this.position) .css({ position: 'absolute' }) .css(hideEffect) .attr('title', this.name) .gxInit({ queue: 'cancel' }) .gx(showEffect, orbiter.options.featureFadeInTime, orbiter.options.featureFadeInEasing) .appendTo(orbiter.$featureBoxContainer); toolTipIt$($element) .addClass('feature-tool-tip'); } orbiter.featureBoxes[this.name] = $element; }); }, getFeatures: function (rotation) { // jQuery is retarded and won't let us filter on an object. =| var features = [ ]; $.each(this.features, function (key, value) { if (value[rotation]) { features.push({ name: key, position: value[rotation] }); } }); return features; }, loadFrameImage: function (frame, callback) { var img = this.frameImages[frame]; if (img) { if (img.data('callbacks')) { img.data('callbacks').push(callback); } else { callback(img); } return; } var img = this.options.frameImage; var imgSrc; if (typeof img === 'function') { img = img(this.$sourceElement, frame); } if (typeof img === 'string') { imgSrc = img; img = new Image(); } if (img.tagName && img.tagName === 'IMG') { img = $(img); } if (!(img instanceof $)) { throw 'image should be a jQuery object'; } this.frameImages[frame] = img; img.data('callbacks', [ callback ]); img.load(function () { $(img.data('callbacks')).each(function () { this(img); }); }); // IE needs src to be set after the load handler is attached // else cached images do not fire the load event. if (imgSrc) { img.attr('src', imgSrc); } }, down: function (x, y) { this.isDown = true; this.startX = x; this.startY = y; this.startTick = this.getTimeTick(); this.startRotation = this.currentRotation; this.endMomentum(); }, move: function (x, y) { if (!this.isDown) { return; } var dx = this.startX - x; var rotations = Math.round(dx / this.pixelsPerRotation); this.setRotation(this.wrapRotation(this.startRotation + rotations)); }, up: function (x, y) { if (!this.isDown) { return; } this.isDown = false; this.startMomentum((this.startX - x) / (this.getTimeTick() - this.startTick)); }, getTimeTick: function () { return (new Date()).getTime(); }, startMomentum: function (force) { if (force === 0) { return; } var rotation = this.currentRotation; var speed = Math.min(2.5, Math.abs(force)); var direction = Math.abs(force) / force; if (speed < 1) { return; } var orbiter = this; function nextTick() { speed -= 0.05; if (speed < 0) { orbiter.endMomentum(); return; } rotation += direction; orbiter.setRotation(orbiter.wrapRotation(rotation)); var time = 20 / speed; if (time > 400) { return; } orbiter.momentumTimer = window.setTimeout(nextTick, time); } nextTick(); }, endMomentum: function () { window.clearTimeout(this.momentumTimer); } }; function CssOrbiter($sourceElement, options) { var orbiter = new Orbiter($sourceElement, options); var $div = null; orbiter.getViewer$ = function () { if ($div) { return $div; } $div = $(document.createElement('div')) .width(this.$sourceElement.width()) .height(this.$sourceElement.height()); return $div; }; orbiter.updateViewer = function () { var $div = this.getViewer$(); var rotation = this.currentRotation; var frame = Math.floor(rotation / this.rotationsPerFrame); var rotationInFrame = rotation % this.rotationsPerFrame; var x = 0; var y = rotationInFrame * $div.height(); var $frameImage = this.frameImages[frame]; $div.css({ backgroundImage: 'url(' + escape($frameImage.attr('src')) + ')', backgroundPosition: '0 ' + y + 'px' }); }; return orbiter; } function CanvasOrbiter($sourceElement, options) { var orbiter = new Orbiter($sourceElement, options); var $canvas = null; orbiter.getViewer$ = function () { if ($canvas) { return $canvas; } var canvas = document.createElement('canvas'); canvas.width = this.$sourceElement.width(); canvas.height = this.$sourceElement.height(); $canvas = $(canvas); return $canvas; }; orbiter.updateViewer = function () { var rotation = this.currentRotation; var frame = Math.floor(rotation / this.rotationsPerFrame); var rotationInFrame = rotation % this.rotationsPerFrame; var context = this.getViewer$()[0].getContext('2d'); var width = context.canvas.width; var height = context.canvas.height; var x = 0; var y = rotationInFrame * height; var $frameImage = this.frameImages[frame]; context.drawImage( $frameImage[0], // image x, y, width, height, // source 0, 0, width, height // destination ); }; return orbiter; } function toolTipIt$($element) { var $toolTip = $(document.createElement('div')) .gxInit({ queue: 'cancel' }) .css({ position: 'absolute' }) .css(hideEffect) .hide(); $element .data('toolTipIt', { title: $element.attr('title'), $toolTip: $toolTip, hideTimer: null }) .attr('title', '') .bind('mouseenter', toolTipIt$.enter) .bind('mouseleave', toolTipIt$.leave); return $toolTip; } toolTipIt$.enter = function () { var $element = $(this); var data = $element.data('toolTipIt'); var offset = $element.offset(); if (data.hideTimer) { window.clearTimeout(data.hideTimer); data.hideTimer = null; } data.$toolTip .text(data.title) .show() .gx(showEffect, 300, 'Quad:Out'); // Append before applying CSS because // outerHeight doesn't exist until the // element is added to the DOM data.$toolTip .appendTo($element) .css({ top: -data.$toolTip.outerHeight() - 1 // Fix off-by-one pixel error }) }; toolTipIt$.leave = function () { var $element = $(this); var data = $element.data('toolTipIt'); if (data.hideTimer) { window.clearTimeout(data.hideTimer); data.hideTimer = null; } data.hideTimer = window.setTimeout(function () { data.hideTimer = null; data.$toolTip .gx(hideEffect, 300, 'Sine', function () { data.$toolTip .css({ top: 0 }) .remove(); }); }, 500); }; function getOrbiterClass() { // Prefer canvas; fall back to plain CSS try { if (document.createElement('canvas').getContext) { return CanvasOrbiter; } } catch (e) { return CssOrbiter; } return CssOrbiter; } var orbit = function (options) { options = $.extend({ }, orbit.defaultOptions, options); this.each(function () { var $orbitee = $(this); try { var OrbiterClass = getOrbiterClass(); var orbiter = new OrbiterClass($orbitee, options); switch (options.loadTrigger) { case 'now': default: orbiter.load(); break; case 'click': $orbitee.one('mousedown', function () { orbiter.load(); }); break; case 'hover': $orbitee.one('mouseenter', function () { orbiter.load(); }); break; } $orbitee.data('orbiter', orbiter); } catch (e) { console.log('Exception in $.fn.orbit: '); console.log(e); } }); }; orbit.defaultOptions = { rotationCount: 32, frameImage: function ($sourceElement, frame) { var url = $sourceElement.attr('src'); url = url.replace('-thumb', '-' + frame); url = url.replace(/#.*$/, ''); return url; }, features: { }, featureFadeInTime: 300, featureFadeOutTime: 600, featureFadeInEasing: 'Sine:Out', featureFadeOutEasing: 'Sine:Out', featureMouseInTime: 500, featureMouseOutTime: 1000, featureMouseInEasing: 'Expo', featureMouseOutEasing: 'Expo', rotationsPerFrame: 1, pixelsPerRotation: 10, showLoading: false, loadTrigger: 'now' // now, hover, click }; $.fn.orbit = orbit; $.fn.disableSelection = function () { return this .bind('selectstart.disableSelection mousedown.disableSelection', function (e) { e.preventDefault(); }) .attr('unselectable', 'unselectable'); // IE }; $(function () { $('img.auto-orbit').each(function () { var $image = $(this); var json = $image.attr('src').replace(/^[^#]*#/, ''); var options = $.parseJSON(json); $image.orbit(options); }); }); }(jQuery));
'use strict'; /* global angular */ describe('ng-json2js preprocessor', () => { beforeEach(module('test/fixtures/empty.json')); beforeEach(module('test/fixtures/complex.json')); it('should work on an empty object', () => { let testFixturesEmpty; inject(_testFixturesEmpty_ => { testFixturesEmpty = _testFixturesEmpty_; }); expect(testFixturesEmpty).toEqual({}); }); const checkComplexObject = testFixturesComplex => { expect(testFixturesComplex).toEqual({ field: 'property', subObject: [ 'arrayElem1', 'arrayElem2', ], anotherSubObject: { subSubObject: { field: 'property', }, }, }); }; it('should work on a complex object', () => { let testFixturesComplex; inject(_testFixturesComplex_ => { testFixturesComplex = _testFixturesComplex_; }); checkComplexObject(testFixturesComplex); }); it('should allow accessing the json during configuration phase', () => { let injectedDuringConfig; angular.module('testModule', ['test/fixtures/complex.json']) .config(_testFixturesComplex_ => { injectedDuringConfig = _testFixturesComplex_; }); inject(module('testModule')); checkComplexObject(injectedDuringConfig); }); });
import React from 'react'; import { Switch, Route } from 'react-router-dom'; import BoardDisplayer from './BoardDisplayer'; import boardsId from './index.js'; import ProductRow from './index.js'; // The Board component matches one of two different routes // depending on the full pathname // either it will display the boards index for /boards // or the BoardDisplayer component for /boards/:boardParamId // Keep note of the matcher `:boardParamId` this will be used // by our BoardDisplayer component. class BoardsRouter extends React.Component { render() { return( <Switch> <Route exact path='/boards' component={boardsId} /> <Route path='/boards/:boardParamId' component={BoardDisplayer} /> </Switch> ); } } export default BoardsRouter;
import React from 'react'; import Chat from '../Chat/Chat'; import './chats.css'; function Chats() { return ( <div className="chats"> <Chat name="Sonya Booker" message="hii" timestamp="40 seconds ago" profilePic="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxAQEBAQEBAPEA8QDxAQDw8PEA8PDw8PFRUWFhUVFRUYHSggGBolGxUVITEhJSkrLi4uFx8zODMtNygtLisBCgoKDg0OGhAQGi0mHx4tLS0tLS0rLSsrLS0tLS0tLS0tLS0tKystLSstLSstLS0rLS0tLS0tLS0tLS0tLSstK//AABEIALcBEwMBIgACEQEDEQH/xAAcAAABBQEBAQAAAAAAAAAAAAACAAEDBAUGBwj/xAA9EAACAQIDBQUFBgYBBQEAAAABAgADEQQhMQUGEkFRYXGBkaETIlKx0QcUMkJiwRUjgpLh8HJjssLi8ST/xAAZAQADAQEBAAAAAAAAAAAAAAAAAQMCBAX/xAAjEQEBAAICAgMAAwEBAAAAAAAAAQIRAxIhMQQTQSIyUZEU/9oADAMBAAIRAxEAPwD04CEBHAhATs28/QQIQEICPaGxoNo9oVo9obGg2j2hWj2hsw2itDtFaGwG0VodorRbAbRWh2itDYBaK0VWoqKWdlVVF2ZiFUDtJnKbW+0DB0Mk9pXPWmLJ/cdfAGK5Se2scMsvUdXaK083q/akfy4RQP11iT5BYNP7Umvnh08Gf6TP2YqfRyf49KtGtOP2b9omGqZVEamefCQ4HyPpOowG0qGIF6NRX6gGzDvU5iOZy+qxlxZ4+4sWitDtGtNbYBaNaSWjWj2AWjWh2jWj2AWjEQ7RrQ2WkZEYiSEQSIbCMiMRJCIJEWwjIgkSQiCRDYR2ihWjw2AtjFHORvtBRznnz7dqH/7IX2lVb81u6R+xf6q9C/ia9ZJT2iDznnAxVT4jJ6GPqL+Ynvmfsp/U9NpYkGWFYGcHgtuaBsp0OD2oDzm5ntO4WN60e0q0cUDzllXBmtsnijRWjBxCtBAhrFQa0oba2rSwlJqtU2A0Ufic9BLmLrrSRnbIKPM8h3k5Tw7frbNetiHFQ/hJ4EB91FB90AepPMzNuo3hh2uk+39562MYtUNqSn+XRUngHafiPbOcx1UjPU9TylenVPudBLbUPaJYC50v9Zy55ed16fHjOuox3e+tz35CWsPwnJiBpzP0h1NlvYd0z6mGK5tfLW4i3K11sbRwZAuCSO4HyN5Y2fjKlJgyOQQcsyPJuUztjY4KeG+R5aek28Rhg38xBY6uvZ1EnllZfKuMmUd5u3vwSAuIBYDWoBaonay/mHaJ3lKorqGUhlYXVgbgjsngoVlIZTZhmpHnb/E6/c7eY0TZ7+xLWrU9fZMfzr+k8xLcfP8AmTj5/iTXbD/j020a0JSCAQQQRcEaEGPade3nAtGtDtBtHsAtGIhmRtUENgrQSJHUxIErVMcBzi7Q9LhEEiUDtFesH+JL1h2haXyIJEpjaC9YX31esOw0s2jSD72sUNjTypRJVEEQrzmdo4QkYMMRAYMnoYp00MriEIbGm/gduEfiym9htrg85wohpUZTcGamVid45XpdHGg85bSqDPOsJtllNjOgwW2AbZyszRuFjqQYQmbh8cDzl6nUvN72ypbwOBQd2bhWmDUJ7V08f3tPn7aNQ1ajuxJZmJuxudes9W+03a1qa4ZSBxkPUPPhGg88/CeWcQJsNJHOurgx/TYfC8U3dn7PIz0j7Ow2Qm7haYnPk7carfcQRp4yri9ihlNhr2TpadMSylEdJC2z0tK8i2psapSNwp7jNfd3GGoPZtk4/ASdf0nqJ3G19mrUQ5Zzz77uaGJUaBmt/VyPnaa7dsRJq7jaFIEG1wVJYDmBfMf0n0MjYezZXUZHJl5EaETRxOTpVH4XF2HLi0b0PzkWIp2Vk6HLuOY9PlIS+VXc7k7Yuv3dzcBeKgx50/h8PlOqNYTx3ZWKZLFTZqZ4l8DmP96zqjvNkL3vbOd/Dy7x1fx5XyuDrlufrtzXEgqYsDnOMbeYW1Mz8VvEx/DeW+xyzCu0xO01HOY+K2+o/MPOcdX2lUfU2lUm+sxc6pOL/XRYveTpczKrbdqHSZlQyHii3W5hIvvtir8UD+M1filBoBja6xprt2qOcsLvDU/0zCjxWl1jfG8dTp6xTn+KKLdHSNaOFggyVYrWjqsO0YGEJnZFaEojiOI9mUV4zQQ0ZDtCS40JEEQgYyaGF2k6a5zao7w2S17HtnLcUixlbhQnsjmVZuErA3v2q9Sq124mOV/hHQTI2XmwHK/mZX2nVux5kw9lVLVEXt9dYrXRjNR2+DGU1MOJjUaoGZNhNDC7RpfGPOTzVwblBZaRZSwuKRtGU9xBl5GB0nPVoVRbiefb4USp4hyII8J6C1QAZmcZvfURlbMadRHh7P8AA1qvFQHYeIdxsfk0VWtdKT8yoVvkPlKWEq8VBbZjIH+0j6Qr/wD57dCfMEGT15b34LC1uGoexr+BAP8AmXqvTpl4TFepnrbiA8jcS/Tr3I/UvqAD9ZbDxUeWdsUkYiGRGJl3EiYRAx2MjJgAVDIhJGgx7CJo14brAAi2ZjGIhGIRbPSG0UltFDsNNRaRhhDL/sI4oSnSp9oqLTMlWkZbSjJVpRdKfaKQomSrQMupRlhKIi6UdoyHw5jLhpsGhDXDiPrS7RinDwDTm82GEhbBw60doxShmNtzE29wa8zOtr4YKpY6AEzzbeDGHjy/E2nYItabw8snEtYlm1/KP3kmwyWrKel/lM/E1NLnqZsbt0x7QHsiVddS4B7z2PfoBIcXtTBH3WybQW4QfIm8W0cA1RbKxAOvDr58pQw2763UNSJA1Ivc53zN9Y7J+tS38XcLilp5034lPnO02O7VFuNLTlK2ApqqhUK2QIFBHCbCwJyvftvOn3YBWnw35SOcnXcVm96qht7HcN1vbqdLThcXjsIbguWa/PitfvndbyYEMD7pJ4rmxtcdD2Tz3bOywWLcJBJuel4cMxs3T5O09NrZbD2Hu6DhI8Gv8pZJtRYdHB8DxA/KU9gJeiy/pFvUfSSGp/LqD/pq48Gz+clf7VSf1Z+Nq8Nj+g+YYX+ctUa1mA6BT8wZk7Ta4HU3HnY/tEMT74z6DwylZEsq7anRJUGA9AzR2MA9FDz0PfLL4eUjksm2A1AyJqc3K2HmfiaJmpNl4Z7CRG8umkYPsDfSPqNqhBtACzR9gYkw/ZM9TZroYIQzUOG7IYwsWjZQSPNP7t2RRaPTWj3gcBi4DO7bg0kDSRWkIQw1pmLY0nV5MryBKZkyUzDY0lV5KrQEpGTpShtkgYQENaUlFKGw57eatw0+Easc+7/b+U8t22L1j0VRPSd57+07gT6ETzzHJxVKh6uFHh/onNye3fwz+Ln8etj4Tf3fRg6MM1IGfTLnOf2k93PS81tgbWVAlJgblwFYWsbkWvF+KS+XpeAIsLzT9mLZATDwb5zapv7snmthrTLx9gflNjYlM8PS85zaVdgxsL5G3YYexsTWAAYgknIqCAemV9YZf1GN/k6rEUgSVNtMjOP3iwJS/S06HZqYklhVKlL3VgpQjszJvIduUuKmb6iQwvWr+K43YbgNwHmp/wC4/wCPOHiUs5XkwZfBxb0aZ1Sp7N+LkrC//Fsj+3nNLGuHF/zDpz/3L06wymstj805vGNdQelge8GxkCKXqIBq5AA6k2t85bxqe+6/H7w/q/8AYSnhqnCUbmjAjrcGWxc+T0jcrFBk4DcG5yI56/WdM1KcFsHGD7waiHKoFqlRop4rN6k+Yno5E6+KSx5/yLZltnVKEr1MJearLI2WU6xz96yDhIJw01GWRlY9Q+9Zpw8EUJolYBSHWH9lUTSj8EuFIJSLpD+2qfBHlrhih0h/bUnsovZSWPHpLaMU5ItOOIaw0NnRJOiyNZKsei2lRZKokSmSKY9DaZRDtIwYYMROP3xQhrgZhWPZa5v6N6TzmobKD2O3r9PlPXt48D7RQymzLcdhB5GeSbUoFA6cxYW7LG85uXHy7/j57xctiDdvGNSfhZG+F1byIMVQZxlXOZiletYVtDebGGfKcZuptD2tEKfx0rIe0WyPl8p1GGrAgqcriYzWxqTEGlf3iJZwtfD2FmsVIJymBV2Qhe5aqR/zOXlLVPZWHy/mVQRy4zMZeva/HhL5djRxtJx7rA9nOZm1gCrWlBNi0TYo1YH4uNvrHxVIUFYBnYEaO3Fn3yGpK3ZJ6ef7ayZh1RwPAEj5SvhceeFCeYCtfkdAfmP7ekj29iwKoP6hfuOUo01sCh+C39Qz+cvZ4R7fyaO0DcB11U59bH/I+cqWBfPRwCew9ZNg6nGneCD3i3+PWNSXzH0hCvltbkUwMQab86FXg+En3W+Q9J6wpyHcJ5duXgnq4lHOQphiRfUHIZeM9QJnbw+nm/K/sFoBhEyNjKuUDSMw2MjJgAmCY5MEmBmMYxyYJMAaKNeKMJrx7wbx7xEIQwZFeEDAJ1MkUyBTJFMAnUyRTIFMMGMLKmGpldWkgaLQSMAQQcwdROH3u3SNS9Sjc/En5tCL9us7YGMYssZfbWGdxu48HTd6ozkMrC2ehz6jvlt916gvU9m4pDNsvfUcsjrPaRTW9+EXOuUapRDAgjUWMx9S3/oryDd3BPRarcEBirIeTDPSdBSryztjBLRfhXtbzJmZac+WOnXhlubb2Dqg6zaoUEbpOLp1ysvUttFRIZ4unB19SmqLynHb2bVWmjXIuchK+1d7SFsoJblfId84HamKqVWLVGueQ0C+Ezhx23dayz1PCjiKxq1LnmchNKlm/FysT55mZ1BPey1/eX3HCptzUKPHX0lc/wDEcJ52k2RqPP1ltSFLHmDl0g4OkEW51I9IWCptUawBuTlz7pj3VZ4dN9nnF94ctckq1z5Zek9EJnO7pbHOHQs4s7cug6TfJnocc1i8j5GUyzujEwCY5MjJlETMZGTHYwCYgRMAmOTAJjBEwSYiYJMDPeKDeKMJeKOGkPFCDQ0SYGEDIA0MNFoJgZIrSANDVoBYVpIGldWhq0AsAww0gDQg0CWA0K8r8dpk43ezA0SVfEJxDVUvUI/tgcjcMXFOHxf2i0+LhoUWqcgzngBJ0y1hHbVeqLOVF9QgsO7rFbpvHjypbdxAqVmI00HcJmiSvmYwScuVd+E1NIXEhq6GXGWVqtOSsXjnsVck5EnqNZmVsOb9O/Mzpq2EuZH/AAZjmL+AAmLuNzWUc/Rw/D3nl0EmFPO50HWbmG2KzEC3COrZmXsNuPVquTVqqtIaKguzfSPHDLKlnnhhPbnFcMeEMCTYADNrnTKembtbATDIC3vVWALMeR6CV9i7o4bDP7QAuwzBextOh4p18XDMfNefz/J7+MfQyYBaCWgFpdxiLSMmMWgFoGcmATBZoBaPQETAJgloJMDETGJgFoJaAHeKR8UUDSXj3kPFCDRklDQg0hBhBoBOGkitKwaGGgSyrQzUAFyQANScgJg7Y2/Sw2Ru1Qi4Qf8AkeU4Pa2362IPvMeG+SLkg8OffE3jha9Cx+9mFo3AY1W6U8x/dpOcxn2gVjcUqVNOhe7n9hONLE6wTF2VnFF7am28RiD/ADarsPhB4U/tGUy7yW0bgmdqSSGoVCrBhyII8J6Bgqq1EV10YeXZOA4Zvbq7QFN/ZObI5yJ0V/oZjP01j7dQKckVJd9hCWhOa1eTTPelB9jNdcLF91mNqaZlLB3Ok1cNhAOUnpUJbppaTyrcVhghrbOW6VC0lAkqCOZVm4qWIwzn8FRkPcrL5GYuPqbTpXKU8PiVHIcVKp4Akg+c6jghLTlZz5z9Sy+PhfxwNLflFPBiKFWjU5qdL+M1cPvJhnNuPgbo4K+ukPejZNKsWDoD7utswZ5q9P2ZKXvwMVF9eHpOri5ezm5PjyenrAqgi4II6g3EEtPM8DtKrRa6OQPhOanwnb7L2otdARk4HvL9OyXc2WFxaJaAWgloBaDIy0EtALQCYAZaCWgEwS0DScUUh4oozTBoQaQcUINAk4aOGkHFH4oBYDSPGYtaVNqjaKL955CCGnNb7YyyU6QP4iWPcMh6n0gJN3TmdoYxq1R3Y+8xv4SqBBBzvDMla6pCtFEvfFfl6xNFlEbRRGBGtrCWMR3xwIB6BuftgVl9jVP81B7hOtRPqJ04oTyChVZGV0JVlNwRqCJ6buxt5cSlmsKygca9f1L2fKc3LhrzHTx578VrBIxTOWbRhTnMujVZMiQlpyZVmTMtOShYgI9oyPwxoQMQjJg7cqBRUY6Kv7TyarU42LdSWnefaFtLgBpKfecgH/jYXnngOROnKdnBjqbc3LfwRqZ8tZcwGLamwYGxBmbS1J6C8lV850SoWPR8HixVQOOevYZIWnObsYvJkPh3zfLSjmymqItG4oBaAWgSQtALQC0EtA0l4pFxRQNJeErR4oAV4rxRQIQM4LerFGpiHH5adkHhr63iimc/SnHPLITO4hxRSax4riKKAPeOBFFGBWitFFAyEs4TFPSYVKZKspuCNR9R2RRRB6VuxvEuKHAw4ayrcgA8LDqDy7p0iCKKcXNjMcvDr47bj5SAQxHikmyERMUURkokWLrBELHkCYoo4y8X2/tI4iu9TkSQo6KJRf8ACO6KKelJqacVu6ipD8XdCU5iKKAaWya/BUF9Aw8tJ2fFFFK4+kOSeQkwSYoo2DEyMmKKBmvFFFAP/9k=" /> <Chat name="Mark Ruffalo" message="hello there" timestamp="10 seconds ago" profilePic="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR_YRKVyxv0tAIH0kyzapOGHvuCENou4BYUqQ&usqp=CAU" /> <Chat name="Brenda Song" message="yooo whats up" timestamp="20 seconds ago" profilePic="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSkWm-hMmPyzdDP6M8LzB1RlaGJkZ1om8zRkg&usqp=CAU" /> </div> ) } export default Chats
const Maze = require ('../Maze'); class EnchantedMaze extends Maze { constructor() { super(); } } module.exports = EnchantedMaze;
import React from 'react'; import AppNavigator from './client/AppNavigator' import { library } from '@fortawesome/fontawesome-svg-core' import { fab } from '@fortawesome/free-brands-svg-icons' import { faCoffee, faStar, faChevronLeft, faChevronRight, faSearch, faMap, faUser, faList, faFilter, faNotesMedical, faUserCircle, faHome, faCommentAlt, faListAlt, faAddressBook } from '@fortawesome/free-solid-svg-icons' import {StyleSheet} from 'react-native' library.add(fab, faStar, faChevronLeft, faChevronRight, faSearch, faCoffee, faUser, faMap, faList, faFilter, faNotesMedical, faUserCircle, faChevronLeft, faHome, faCommentAlt, faListAlt, faAddressBook ) const styles = StyleSheet.create({ // appNav: { // backgroundColor: 'blue' // } }); export default function App() { return ( <AppNavigator/> ); }
import * as bc from './BotConstants' export function defaultUserInput() { return { label: null, type: 'disabledFieldText', placeholder: 'Please wait...', }; } export function userMessage(message, type = 'text') { return { from: 'user', bubbles: [ { content: message, type, }, ], }; } export function botMessage(message, type = "text", varName = "") { return { from: 'bot', bubbles: [ { content: message, varName: varName, type, }, ], }; } export function optionCards(optionCardsValues){ const optionCardsInput = { label: 'These are option cards!', type: 'optionCards', optionCards: [ { title: 'Design', description: 'I need someone to help with branding, UI/UX, web, or product design.No coding. Just Design.', }, { title: 'Design', description: 'I need someone to help with branding, UI/UX, web, or product design.No coding. Just Design.', }, { title: 'Design', description: 'I need someone to help with branding, UI/UX, web, or product design.No coding. Just Design.', }, ], }; return optionCardsInput } export function selectField(optionsValues){ const options = optionsValues.map((optionValue) => { return { label: optionValue, value: optionValue }; } ) const selectInput = { label: null, type: 'select', options, }; return selectInput; } export function tagsField(tagValues){ const tags = tagValues.map((tagValue) => { return { label: tagValue, value: tagValue }; } ) const tagsInput = { label: 'Choose all that apply: ', type: 'tags', tags, }; return tagsInput; } export function textField(textFieldValue){ const fieldTextInput = { label: null, type: 'fieldText', placeholder: 'Type Something', }; return fieldTextInput; } export function disabledFieldText(){ const fieldTextInput = { type: 'disabledFieldText', placeholder: 'Please wait...', }; return fieldTextInput; } export function endOfConversation(){ const fieldTextInput = { type: 'endOfConversation', placeholder: '– ' + bc.name + ' left the conversation –', }; return fieldTextInput; }
var LoginView = Backbone.View.extend({ el: "#main", events: { "submit .login": "submit", "click .register": "goToRegister" }, render: function() { var template = _.template($('#login').html()); this.$el.html(template()); }, submit: function(e) { e.preventDefault(); // Get form values var loginValues = _.object($(".login").serializeArray().map(function(v) {return [v.name, v.value];})); $.ajax({ method: "POST", url: "/users/sign_in", dataType: "json", contentType: "application/json; charset=utf-8", data: JSON.stringify({ user: loginValues }) }) .fail(function(response) { $('.info').html(new ErrorsView({ model: ["Wrong Email or Password."] }).render()); }) .success(function(response) { localStorage.auth_token = response.auth_token; localStorage.admin = response.admin; localStorage.email = response.email; app.navigate('tickets', {trigger: true}); }); }, goToRegister: function(e) { e.preventDefault(); e.stopPropagation(); app.navigate('register', {trigger: true}); } });
/* * The Ship is moving to any space. * ivan.zenteno@zentenoit.com * copyright 2013 */ var Ship : GameObject; var speed : float = 10.0; var positionX : int = 0; var positionY : int = 0; function Start () { positionX = transform.position.x; positionY = transform.position.y; } function Update () { /* var vertical : float = Input.GetAxis ("Vertical") * speed; var horizontal : float = Input.GetAxis ("Horizontal") * speed; vertical *= Time.deltaTime; horizontal *= Time.deltaTime; transform.Translate (0, vertical,0); transform.Translate (horizontal,0,0); */ } function OnGUI () { // // if (GUI.RepeatButton (Rect (30, Screen.height - 100, 50,40), " 1")) // { // //position = positionY; // position = positionY - 1; // transform.Translate(positionY, 0, 0); // print("POSICION en Y del 1: "+positionY); // } // // if (GUI.RepeatButton (Rect (170,Screen.height - 100,50,40), " 2")) // { // //position = positionY; // position = positionY + 1; // transform.Translate(positionY, 0, 0); // print("POSICION en Y del 2: "+positionY); // } // // if (GUI.RepeatButton (Rect (100,Screen.height - 50,50,40), " 3")) // { // //position = positionX; // positionX = positionX - 1; // transform.Translate(0, positionX, 0); // print("POSICION en Y del 3: "+positionX); // } // // if (GUI.RepeatButton (Rect (100,Screen.height - 150,50,40), " 4")) // { // //position = positionX; // position = positionX + 1; // transform.Translate(0,position ,0); // print("POSICION en Y del 4: "+positionX); // } // // // // if (GUI.Button (Rect (Screen.width -200,Screen.height - 75,50,40), " 5")) { // // } // if (GUI.Button (Rect (Screen.width -100,Screen.height - 75,50,40), " 6")) { // // } }
import RouterHelper from '../RouteHelper'; const title = '档案管理'; const prefix = '/config'; const children = [ require('./institution').default, require('./department').default, require('./user').default, require('./corporation').default, require('./bank').default, require('./customersArchives').default, require('./customerContact').default, require('./customerFactory').default, require('./customerTax').default, require('./customerCost').default, require('./customerService').default, require('./customerInvoice').default, require('./customerTask').default, require('./suppliersArchives').default, require('./supplierContact').default, require('./supplierCar').default, require('./supplierDriver').default, require('./carManager').default, require('./supplierSupervisor').default, require('./supplierCost').default, require('./supplierTax').default, require('./insideFactory').default, require('./insideCar').default, require('./insideDriver').default, require('./insideSupervisor').default, require('./rate').default, require('./chargeItem').default, require('./customerPrice').default, require('./customerPriceDetail').default, require('./supplierPrice').default, require('./supplierPriceDetail').default, require('./position').default ]; export default RouterHelper(prefix, title, children);
const ResultItem = ( props ) => { const fields = props.fields; return ( <div className="block block__sub block__border-bottom block__padded-bottom"> <h3>{ props.item.name }</h3> <dl> { props.item.type !== 'Tribal Government' && <div> <dt>{ fields.state }:</dt> <dd> { props.item.state } </dd> </div> } <div> <dt>{ fields.name }:</dt> <dd> { props.item.program } </dd> </div> <div> <dt>{ fields.type }:</dt> <dd> { props.item.type } </dd> </div> { ( props.item.url || props.item.phone ) && <div> <dt>{ fields.contact }:&nbsp;</dt> <dd> { props.item.url && <a href={ props.item.url } rel='noreferrer' target='_blank'> { props.item.url } </a> } { props.item.phone && <span>{ props.item.phone }</span> } </dd> </div> } </dl> </div> ) }; export default ResultItem;
/** * Created by Ratnesh on 13/09/2019. */ export {default as Login} from "./login"; export {default as DashBoard} from "./dashboard";
var auto=setInterval(function(){ $.ajax({ headers:{ 'X-CSRF-TOKEN':$('meta[name="csrf-token"]').attr('content') }, type:'GET', url:'start', success: function(data){ if(data==='exam started' || data==='no exam scheduled to be started') { clearInterval(auto); end(); } console.log(data); } }); return false; },10000);
import Banner from "./components/Banner"; import CourseList from "../../components/CourseList"; import Different from "./components/Different"; import Terminal from "./components/Terminal"; import Gallery from "./components/Gallery"; import Action from "./components/Action"; import PopUpVideo from "../../components/PopUpVideo"; import { useEffect, useState } from "react"; import { useParams } from "react-router-dom"; import userApi from "../../api/userApi"; import Loading from "../../components/Loading"; export default function Home() { const initialValue = { online: [], offline: [], loading: true, review: [], gallery: {}, }; let dataLocal = JSON.parse(localStorage.getItem("localHome")); let [state, setState] = useState(dataLocal || initialValue); useEffect(async () => { let res = await userApi.getDataHome(); localStorage.setItem("localHome", JSON.stringify(res)); setState({ ...res, loading: false, }); }, []); if (state.loading) return <Loading />; return ( <main className="homepage" id="main"> <Banner /> <CourseList online={state.online} offline={state.offline} /> <Different /> <Terminal review={state.review} loading={state.loading} /> <Gallery gallery={state.gallery} loading={state.loading} /> <Action /> <PopUpVideo /> </main> ); }
import _ from 'lodash'; import React, { Component } from 'react'; import { Step, Stepper, StepLabel, StepContent } from 'material-ui/Stepper'; import RaisedButton from 'material-ui/RaisedButton'; import FlatButton from 'material-ui/FlatButton'; import WIZARD_STEPS from './wizardSteps'; class SurveyStepper extends Component { state = { finished: false, stepIndex: 0 }; handleNext = () => { const { stepIndex } = this.state; this.setState({ stepIndex: stepIndex + 1, finished: stepIndex >= WIZARD_STEPS.length - 1 }); }; handlePrev = () => { const { stepIndex } = this.state; if (stepIndex > 0) { this.setState({ stepIndex: stepIndex - 1 }); } }; renderStepActions(step) { const { stepIndex } = this.state; return ( <div style={{ margin: '12px 0' }}> <RaisedButton label={stepIndex === WIZARD_STEPS.length - 1 ? 'Finish' : 'Next'} disableTouchRipple={true} disableFocusRipple={true} primary={true} onTouchTap={this.handleNext} style={{ marginRight: 12 }} /> {step > 0 && <FlatButton label="Back" disabled={stepIndex === 0} disableTouchRipple={true} disableFocusRipple={true} onTouchTap={this.handlePrev} />} </div> ); } renderSteps() { return _.map(WIZARD_STEPS, ({ label, content }, index) => { return ( <Step key={index}> <StepLabel> {label} </StepLabel> <StepContent> <p> {content} </p> {this.renderStepActions(index)} </StepContent> </Step> ); }); } render() { const { finished, stepIndex } = this.state; return ( <div style={{ maxWidth: 380, maxHeight: 400, margin: 'auto' }}> <Stepper activeStep={stepIndex} orientation="vertical"> {this.renderSteps()} </Stepper> {finished && <p style={{ margin: '20px 0', textAlign: 'center' }}> <a href="#" onClick={event => { event.preventDefault(); this.setState({ stepIndex: 0, finished: false }); }} > Click here </a>{' '} to start again. </p>} </div> ); } } export default SurveyStepper;
import styled from "styled-components"; import React, { Component } from "react"; const Title = styled.h1` font-size: 1.5em; text-align: center; color: blue; `; const Wrapper = styled.section` padding: 3em; background: papayawhip; `; export default class StyledComponent extends Component { render() { return ( <div> <Title>Styled Component Lib</Title> <Wrapper> <p> Nothing change</p> </Wrapper> </div> ); } }
/*jslint browser: true, undef: true, white: false, laxbreak: true *//*global Ext*/ Ext.define('MyRetirement.store.Enumeration', { extend: 'Ext.data.Store' ,requires: [ 'MyRetirement.model.Enumeration' ,'Ext.data.proxy.Memory' ,'Ext.data.reader.Json' ] ,model: 'MyRetirement.model.Enumeration' ,sorters: [{ property: 'sortOrder' ,direction: 'ASC' }] ,proxy: { type: 'memory' ,reader: { type: 'json' ,root: 'enumerations' } } });
import React, { useState } from 'react' import css from './VidModal.module.css' import ReactDOM from 'react-dom'; const VidModal = (props) => { const index = props.videos.findIndex(item => item.id === props.vidModal.id); const [videoIndex, setVideoIndex] = useState(index) return ReactDOM.createPortal ( <div className={css.vidModal_container}> <div className={css.wrapper}> <iframe title="video" src={props.videos[videoIndex].vid} allowFullScreen={true} width="160" height="90" frameBorder="0" > </iframe> <div className={css.vidModal_overlay} onClick={props.clicked}></div> </div> {/* next prev button */} <button onClick={() => setVideoIndex((videoIndex + props.videos.length - 1) % props.videos.length)} type="button" className={[css.btn, css.btn_back].join(' ')}></button> <button onClick={() => setVideoIndex((videoIndex + 1) % props.videos.length)} type="button" className={[css.btn, css.btn_next].join(' ')}></button> {/* toolbar */} <div className={css.vidModal_toolbar_container}> <ul className={css.vidModal_toolbar}> <li className={css.vidModal_toobar_items}> <button onClick={props.clicked} className={css.toolbar_close_btn} type="button"></button> </li> </ul> </div> </div>, document.getElementById('vidModalPortal') ) } export default VidModal
import React, { useState } from 'react' import styles from './AddObjectiveForm.module.css' function ObjectiveForm({ addObjective }) { const [objectiveValue, setObjectiveValue] = useState('') const [objectiveStatus, setObjectiveStatus] = useState('On track') function handleObjectiveChange(event) { setObjectiveValue(event.target.value) } function handleObjectiveStatusChange(event) { setObjectiveStatus(event.target.value) } function handleSubmit(event) { event.preventDefault() if (!objectiveValue) return addObjective(objectiveValue, objectiveStatus) // reset the form setObjectiveValue('') setObjectiveStatus('On track') } return ( <form onSubmit={handleSubmit} className={styles.formContainer}> <input placeholder="Enter your objective" value={objectiveValue} onChange={handleObjectiveChange} className={styles.objectiveInput} /> <div className={styles.objectiveStatusInput}> <label> <input type="radio" value="On track" checked={objectiveStatus === 'On track'} onChange={handleObjectiveStatusChange} /> On track </label> <label> <input type="radio" value="Behind" checked={objectiveStatus === 'Behind'} onChange={handleObjectiveStatusChange} /> Behind </label> <label> <input type="radio" value="At risk" checked={objectiveStatus === 'At risk'} onChange={handleObjectiveStatusChange} /> At risk </label> <label> <input type="radio" value="Complete" checked={objectiveStatus === 'Complete'} onChange={handleObjectiveStatusChange} /> Complete </label> </div> <button type="submit" className={styles.objectiveFormSubmitBtn}> Add New Objective </button> </form> ) } export default ObjectiveForm
var React = require('react'); var BenchStore = require('../stores/bench.js'); var Index = React.createClass({ getInitialState: function () { return { benches: BenchStore.all() }; }, componentDidMount: function () { var that = this; this.listener = BenchStore.addListener(function () { that.setState({ benches: BenchStore.all() }); }); }, componentWillUnmount: function () { this.listener.remove(); }, benches: function () { return this.state.benches.map(function (obj) { return obj.bench.description; }); }, render: function () { return <ul>{this.state.benches.map(function (obj) { return <li>{obj.bench.description}</li>; })}</ul>; } }); module.exports = Index;
var tokki = angular.module('directives').directive('despacho', ["ventasService", function(ventasService){ return { restrict: 'E', templateUrl: 'pages/ventas/despacho/despacho.html', controller: ["$scope", "$filter", "$rootScope", function($scope, $filter, $rootScope) { $scope.check = function(selected){ if(selected == $scope.currentWindow.traslados[4]){ $scope.currentWindow.despacho = $scope.currentWindow.despachos[1]; $scope.currentWindow.hideForma = true; } else{ $scope.currentWindow.hideForma = false; } } }] } } ])