text
stringlengths
7
3.69M
//scrolltotop //데스크탑 스크롤투탑 const $scrollToTop = document.querySelector("#scrollToTop"); //데스트탑일떄 스크롤투탑 기능 작성 $scrollToTop.addEventListener("click", function () { window.scroll({ top: 0, left: 0, behavior: "smooth", });}) // 윈도우에 스크롤 이벤트가 발생시, // 스크롤 위치에 따라 scrollToTop 아이콘 투명도 변경 window.addEventListener("scroll", function () { // 만약 스크롤 위치가 600 이상이라면, window.scrollY >= 600 ? ($scrollToTop.style.opacity = 1) // scrollToTop 버튼이 보이게 합니다 : ($scrollToTop.style.opacity = 0); // 아니라면 안보이게 합니다 });
const { exec } = require('child_process'); const semver = require('semver'); console.log(`executing 'ns plugin build'`); exec('ns plugin build', (err, stdout, stderr) => { if (err) { // node couldn't execute the command console.log(`${err}`); return; } });
// component/msgbox/msgbox.js const DEL_WIDTH = 150; const DEL_MOVEOFFSET = 75; var animation = wx.createAnimation({ // 动画持续时间,单位ms,默认值 400 duration: 50, /** * linear 动画一直较为均匀 * ease 从匀速到加速在到匀速 * ease-in 缓慢到匀速 * ease-in-out 从缓慢到匀速再到缓慢 * * step-start 动画一开始就跳到 100% 直到动画持续时间结束 一闪而过 * step-end 保持 0% 的样式直到动画持续时间结束 一闪而过 */ timingFunction: 'ease', // 延迟多长时间开始 delay: 10, /** * 以什么为基点做动画 效果自己演示 * left,center right是水平方向取值,对应的百分值为left=0%;center=50%;right=100% * top center bottom是垂直方向的取值,其中top=0%;center=50%;bottom=100% */ transformOrigin: 'left top 0', success: function (res) { } }); Component({ /** * 组件的属性列表 */ properties: { title: { type: String, value: '默认' }, content: { type: String, value: '默认' }, msgboxid: { type: String, value: '' } }, /** * 组件的初始数据 */ data: { openchat: false, del_state: 0, new_msgnum: 1, touchstartx: 0, touchstarty: 0, touchnowx: 0, touchnowy: 0, offsetX: 0, animationData: {} }, /** * 组件的方法列表 */ methods: { realdel: function (e) { if (this.data.del_state == 1) { this.triggerEvent('del_talkbox', { 'id': this.properties.msgboxid }, {}); this.setData({ del_state: 0 }); } }, triggerdel2: function (e) { if (this.data.del_state == 1) this.setData({ del_state: 2 }); else this.setData({ del_state: 0 }); }, triggerdel: function (e) { console.log('del'); this.setData({ del_state: 1 }); }, delstart: function (e) { this.setData({ openchat: true }) this.setData({ offsetX: 0 }); this.setData({ touchstartx: e.touches[0].clientX, touchstarty: e.touches[0].clientY }); }, delend: function (e) { if (this.data.offsetX > DEL_MOVEOFFSET) { animation.left('-' + DEL_WIDTH + 'rpx').step(); this.setData({ animationData: animation.export() }) } else { animation.left('0rpx').step(); this.setData({ animationData: animation.export() }) var that = this; setTimeout(function () { that.setData({ animationData: {} }) }, 60); } }, delmove: function (e) { this.setData({ openchat: false }) this.setData({ touchnowx: e.touches[0].clientX, touchnowy: e.touches[0].clientY }); if (e.touches[0].clientX > this.data.touchstartx) { this.setData({ touchstartx: e.touches[0].clientX }); } else if (e.touches[0].clientX < this.data.touchstartx - DEL_WIDTH) { this.setData({ touchstartx: e.touches[0].clientX + DEL_WIDTH }); }; var offset = this.data.touchstartx - e.touches[0].clientX; this.setData({ offsetX: offset }); }, goback: function (e) { animation.left('0rpx').step(); this.setData({ animationData: animation.export() }); }, openit: function (e) { console.log('in open end', this.data.openchat) if (this.data.openchat) { wx.navigateTo({ url: '../detailinfo/detailinfo', }) this.setData({ openchat: false }) } }, bindok: function (e) { console.log('ok') } } })
const mongoose = require('mongoose') const Schema = mongoose.Schema const userSchema = new Schema({ name: String, age: Number, size: String, park: Boolean, houers: TimeRanges, owner: { name: String, age: Number, smoke: Boolean, } })
var CustomersComponent = require('components/data/customers'); describe('Customer API', function() { it('makes a request to the server with search query'); it('broadcasts results from the server'); it('cancels pending request when performing a new one'); });
angular.module('portfolio-module') .controller('portfolioCtrl',['$scope',function($scope){ $scope.projects=[{ "name":"Surevelox,Inc", "picture":"images/s-img.png", "imgUrl":"http://www.surevelox.com/", "descripation":"Developed from Scratch using Orchard CMS, HTML, CSS, JavaScript, JQuery" },{ "name":"Hotel Classic", "picture":"images/HC_img.png", "imgUrl":"http://www.hotelclassicgandhinagar.com/", "descripation":"Developed from Scratch using Orchard CMS, HTML, CSS, JavaScript, JQuery" },{ "name":"Portfolio App", "picture":"images/portfolio-img.png", "imgUrl":"", "descripation":"Developed from Scratch using Ionic, AngularJS, HTML, CSS" }]; }]);
import { SET_REGISTRATION, GET_REGISTRATION_SAGA, } from '../constants'; // Added for Registration export function setRegistration(registration) { return { type: SET_REGISTRATION, payload: { registration, }, }; }
import { graphql } from 'react-relay' const getPxpsQuery = graphql` query getPxpsQuery { pxps { _id title content dateCreated dateModified } } ` export default getPxpsQuery
'use strict'; angular .module('sbAdminApp') .controller('listPeopleController', function ($scope, $filter, $mdDialog, RoleService, AlertService, Account, people, options, roles) { console.log('listPeopleController'); var vm = this; $scope.people = people; $scope.options = options; vm.display = false; vm.size = people.length; vm.numPerPage = 8; vm.maxSize = 5; vm.currentPage = 1; vm.addRoles = function (ev, id) { $mdDialog.show({ templateUrl: 'views/modals/role-assign-modal.html', controller: 'assignRoleModalController', controllerAs: 'ctrl', resolve: { patientId: function () { return id }, roles: function () { return roles; }, personRoles: function () { return RoleService.getRolesPerson(id); } }, parent: angular.element(document.body), targetEvent: ev, clickOutsideToClose: true }) .then(function () { console.log('Dialog closed'); }, function () { }); }; function search(people) { var offset = ((vm.currentPage - 1) * vm.numPerPage); var re = new RegExp(vm.filter || '' + '.*', 'i'); var pe = _.filter(people, function (a) { return a.persona.nombre.match(re) || a.persona.apellido.match(re); }); if (vm.filter) { vm.size = pe.length; pe = _.slice(pe, offset, offset + vm.numPerPage); } else { pe = _.slice(people, offset, offset + vm.numPerPage); vm.size = people.length; } vm.display = pe.length === 0; return pe; } vm.update = function () { $scope.people = search(people); }; vm.getLeft = function () { var size = $scope.people.length; return _.take($scope.people, Math.ceil(size / 2)); }; vm.getRight = function () { var size = $scope.people.length; return _.takeRight($scope.people, Math.floor(size / 2)); }; $scope.$watch('ctrl.currentPage + ctrl.numPerPage', function () { vm.update(); }); });
/* Copyright (c) 2017 Red Hat, Inc. */ var inherits = require('inherits'); var fsm = require('../fsm.js'); var fsm_messages = require('../fsm/messages.js'); function _State () { } inherits(_State, fsm._State); function _Enabled () { this.name = 'Enabled'; } inherits(_Enabled, _State); var Enabled = new _Enabled(); exports.Enabled = Enabled; function _Start () { this.name = 'Start'; } inherits(_Start, _State); var Start = new _Start(); exports.Start = Start; function _Disabled () { this.name = 'Disabled'; } inherits(_Disabled, _State); var Disabled = new _Disabled(); exports.Disabled = Disabled; _Enabled.prototype.onDisable = function (controller) { controller.changeState(Disabled); }; _Enabled.prototype.onDisable.transitions = ['Disabled']; _Enabled.prototype.onKeyDown = function(controller, msg_type, $event) { var scope = controller.scope; if ($event.key === 'd') { scope.setState({ showDebug: !scope.state.showDebug, }); return; } if ($event.key === 'h') { scope.setState({ showHelp: !scope.state.showHelp }); return; } else if ($event.key === 'p') { scope.setState({ showCursor: !scope.state.showCursor }); return; } else if ($event.key === 'b') { scope.setState({ showButtons: !scope.state.showButtons }); return; } else if ($event.key === ' ') { scope.first_channel.send("TogglePause", $event); return; } else if ($event.key === 'j') { scope.first_channel.send("StepBack", $event); return; } else if ($event.key === 'k') { scope.first_channel.send("StepForward", $event); return; } else if ($event.key === 'r') { scope.first_channel.send("Restart", $event); return; } else if ($event.key === 'l') { scope.first_channel.send("NewTransition", $event); return; } else if ($event.key === 't') { scope.first_channel.send("NewTransition", $event); return; } else if ($event.key === 'c') { scope.first_channel.send("NewChannel", $event); return; } else if ($event.key === 's') { scope.first_channel.send("NewState", $event); return; } else if ($event.key === 'f') { scope.first_channel.send("NewGroup", new fsm_messages.NewGroup("fsm")); return; } else if ($event.key === '0') { scope.setState({ panX: 0, panY: 0, current_scale: 1.0 }); } controller.delegate_channel.send(msg_type, $event); }; _Start.prototype.start = function (controller) { controller.changeState(Enabled); }; _Start.prototype.start.transitions = ['Enabled']; _Disabled.prototype.onEnable = function (controller) { controller.changeState(Enabled); }; _Disabled.prototype.onEnable.transitions = ['Enabled'];
(function(){ angular .module('weatherApp') .controller('homeCtrl', homeCtrl); function homeCtrl($http, weatherData){ var vm = this; vm.location = ""; vm.onSubmit = function(cityName){ weatherData .getByCity(cityName) .then(function(response){ vm.location = response.data; }, function(response){ console.log(response.e); }); }; }; })();
$(function() { $('#tmpSocial').share({ networks: ['facebook','twitter','pinterest','email'], theme: 'square' }); });
import { React } from 'react'; import { useHistory, Link } from 'react-router-dom'; function NavBar() { const history = useHistory(); const AdminPanelButton = () => { console.log('admin panel button initialized'); return ( <Link to={'/AdminPanel'} className="px-3 py-2 rounded-md text-sm font-medium text-white bg-gray-900 hover:text-white hover:bg-gray-700"> Admin Panel </Link> ); }; const ReviewShipmentsButton = () => { console.log('review shipments button initialized'); return ( <Link to={'/ReviewShipments'} className="px-3 py-2 rounded-md text-sm font-medium text-white bg-gray-900 hover:text-white hover:bg-gray-700"> Review Shipments </Link> ); }; return ( <div> <nav className="bg-gray-800"> <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8"> <div className="flex items-center justify-between h-16"> <div className="flex items-center"> <div className="hidden md:block"> <div className="ml-10 flex items-baseline space-x-4"> <p className="px-3 py-2 rounded-md text-lg font-medium text-gray-300"> LogisticsAPP </p> <Link to={'/'} className="px-3 py-2 rounded-md text-sm font-medium text-white bg-gray-900 hover:text-white hover:bg-gray-700"> Home </Link> <Link to={'/RequestShipment'} className="px-3 py-2 rounded-md text-sm font-medium text-white bg-gray-900 hover:text-white hover:bg-gray-700"> Request Shipment </Link> <Link to={'/EditProfile'} className="px-3 py-2 rounded-md text-sm font-medium text-white bg-gray-900 hover:text-white hover:bg-gray-700"> EditProfile </Link> {localStorage.getItem('roles').includes("ROLE_ADMIN") ? AdminPanelButton() : null} {localStorage.getItem('roles').includes("ROLE_OFFICE") ? ReviewShipmentsButton() : null} </div> </div> </div> <div> <button onClick={() => { localStorage.removeItem('accessToken'); localStorage.removeItem('userEmail'); localStorage.removeItem('username'); localStorage.removeItem('roles'); localStorage.removeItem('id'); history.push('/SignIn'); }} className="px-3 py-2 rounded-md text-sm font-medium text-white bg-gray-900 hover:text-white hover:bg-gray-700"> {'Switch Account'} </button> </div> </div> </div> </nav> </div> ); } export default NavBar;
$(document).ready(function() { // ADJUST THE TIME OF THE TWEET TO CLIENT'S LOCAL TIMEZONE function adjust_to_users_timezone (time) { var new_time = time * 1000 + utc_offset * 60000; // convert to miliseconds, get var new_date = new Date(new_time) return new_date.toLocaleString() } $.getJSON('/tweets.json', function(json, textStatus) { console.log(textStatus) var num_tweets = json.length var tweetArray = JSON.parse(json); run_graveyard(); }); });
describe('Block', function(){ var b = new Block(1,2,'specBlock'); it('has a width property that can be set', function(){ expect(b.width).toBe(1); }); it('has a height property that can be set', function(){ expect(b.height).toBe(2); }); it('has a id property that can be set', function(){ expect(b.id).toBe('specBlock'); }); });
module.exports = { plugins: [ require('autoprefixer')({ remove: false, browsers: [ 'ios >= 8', 'ie >= 10' ] }) ] };
import React from "react"; import {shallow} from "enzyme"; import Sample from "./sample"; console.debug = jest.genMockFunction(); console.log = jest.genMockFunction(); console.info = jest.genMockFunction(); console.warn = jest.genMockFunction(); console.error = jest.genMockFunction(); test('render a basic component', () => { const wrapper = shallow( <Sample /> ); expect(wrapper.length).toBe(1); });
export const storeProducts=[ { id:1, title:"abc", img:"../images/image.png", price:10, company:"Google", info: "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", inCart:false, count:0, total:0 }, { id:2, title:"abc", img:"images/image.png", price:10, company:"Google", info: "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", inCart:false, count:0, total:0 }, { id:3, title:"abc", img:"images/image.png", price:10, company:"Google", info: "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", inCart:false, count:0, total:0 }, { id:4, title:"abc", img:"images/image.png", price:10, company:"Google", info: "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", inCart:false, count:0, total:0 }, { id:5, title:"abc", img:"images/image.png", price:10, company:"Google", info: "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", inCart:false, count:0, total:0 }, { id:6, title:"abc", img:"images/image.png", price:10, company:"Google", info: "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", inCart:false, count:0, total:0 }, { id:7, title:"abc", img:"images/image.png", price:10, company:"Google", info: "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", inCart:false, count:0, total:0 }, { id:8, title:"abc", img:"images/image.png", price:10, company:"Google", info: "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", inCart:false, count:0, total:0 }, ] export const detailProduct={ id:2, title:"abc", img:"images/image.png", price:10, company:"Google", info: "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", inCart:false, count:0, total:0 }
require('babel/register')(require('./babelConfig')); require('source-map-support').install(); require('./gulpfile.jsx');
// Value store var transaction; $(document).ready(function () { // Global variables var pomodoro = 25, currentTime = Date.parse(new Date()), deadline, timeInterval, breakTime = 5, longBreakTime = 15, i = 0, reward = 5 // Clock setup var clock = document.getElementById("clock-timer"); var minutesSpan = clock.querySelector(".minutes"); var secondsSpan = clock.querySelector(".seconds"); minutesSpan.innerHTML = ("0" + pomodoro).slice(-2); secondsSpan.innerHTML = "00"; // Calculates the time remaining function getTimeLeft (end) { var total = Date.parse(end) - Date.parse(new Date()); var seconds = Math.floor((total/1000) % 60); var minutes = Math.floor((total/1000/60) % 60); return { "total": total, "minutes": minutes, "seconds": seconds }; } // Initializes the timer function startClock () { timeInterval = setInterval(function () { var t = getTimeLeft(deadline); minutesSpan.innerHTML = ("0" + t.minutes).slice(-2); secondsSpan.innerHTML = ("0" + t.seconds).slice(-2); if (t.total <= 0) { document.getElementById('coin-sound').play(); clearInterval(timeInterval); if (i === 7) { transaction = reward; updateCoins(); $(".reset, .start-pomodoro").addClass('hidden'); $(".start-break2").removeClass('hidden'); } else if ((i % 2) === 1) { transaction = reward; updateCoins(); $(".reset, .start-pomodoro").addClass('hidden'); $(".start-break1").removeClass('hidden'); } else { $(".start-pomodoro").removeClass('hidden'); } } }, 1000); } // Functions for pomodoro, breaks and reset function startPomodoro () { minutesSpan.innerHTML = ("0" + pomodoro).slice(-2); secondsSpan.innerHTML = "00"; $(".start-pomodoro, .start-break1, .start-break2").addClass('hidden'); $(".reset").removeClass('hidden'); deadline = new Date(Date.parse(new Date()) + (pomodoro * 60 * 1000)); i += 1; startClock(); $(".start-break1, .start-break2").removeClass('disabled'); $(".start-break1, .start-break2").prop("disabled", false); } function startBreak () { minutesSpan.innerHTML = ("0" + breakTime).slice(-2); secondsSpan.innerHTML = "00"; $(".start-break1").addClass('disabled'); $(".start-break1").prop("disabled", true); deadline = new Date(Date.parse(new Date()) + (breakTime * 60 * 1000)); //Set deadline i += 1; startClock(); } function startLongBreak () { minutesSpan.innerHTML = ("0" + longBreakTime).slice(-2); secondsSpan.innerHTML = "00"; $(".start-break2").addClass('disabled'); $(".start-break2").prop("disabled", true); deadline = new Date(Date.parse(new Date()) + (longBreakTime * 60 * 1000)); //Set deadline i = 0; startClock(); } function resetClock () { $(".btn-count").prop("disabled", false); $("body").css('background-color', '#F1C40F'); $(".start-pomodoro").removeClass('hidden'); $(".reset").addClass('hidden'); $(".minutes-count").html(pomodoro); $("title").html("Pomodoro") clearInterval(timeInterval); minutesSpan.innerHTML = ("0" + pomodoro).slice(-2); secondsSpan.innerHTML = "00"; i -= 1; } // Start Pomodoro $(".start-pomodoro").click(function() { startPomodoro(); }); // Start a break $(".start-break1").click(function () { startBreak(); }); $(".start-break2").click(function () { startLongBreak(); }); // Reset the clock $(".reset").click(function () { resetClock(); }); }); // CSRF token function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) { return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); // Update coins function updateCoins() { $.ajax({ method: "POST", url: "/coins/", data: {"coins": transaction}, success: function(data) { $(".status" ).contents()[0].textContent = "Balance: " + data.coins; $("#shopmodal").modal("hide"); } }) }; // Shop modal function modalPrice(itemPrice){ $("#broke").addClass("hidden"); transaction = itemPrice; document.getElementById("price").innerHTML = itemPrice; }; // Gets user's coin balance function fetchCoins(coinBalance) { if (coinBalance - transaction >= 0) { transaction = -transaction; updateCoins(); $("#shopModal").modal("hide"); } else { $("#broke").removeClass("hidden"); } }; function getCoins(coinFn) { var coins; $.ajax({ method: "GET", dataType: 'json', url: "/coins/", success: function(data) { coins = data.coins; coinFn(coins); } }) }; // Purchase an item function buyItem() { getCoins(fetchCoins); }; // Prevents modal from closing $('#prModal').modal({ backdrop: 'static', keyboard:false });
import React from "react"; import { Link } from 'react-router-dom'; import logo from "../images/hamburguesa.svg"; import "./styles/header.css"; class Header extends React.Component { render() { return ( <div className="Navbar"> <div className="container-fluid"> <a className="Navbar__brand" href="/"> <img className="Navbar__brand-logo" src={logo} alt="Logo" /> <span className="font-weight-light">Burger</span> <span className="font-weight-bold">Queen</span> </a> <Link className="Navbar-p" to="/desayunos">Desayunos</Link> <Link className="Navbar-p" to="/meseros">Principal</Link> </div> </div> ); } } export default Header;
/** @jsx jsx */ import { jsx, useColorMode } from "theme-ui" import { mapEdgesToNodes } from "../utils/mapEdgesToNodes" import { useEffect, useState } from "react" import { useFilterState, useGameState, useUserState } from "../state" import { graphql, navigate } from "gatsby" import { Spinner } from "@theme-ui/components" import { motion } from "framer-motion" import axios from "axios" import Layout from "../components/layout" import SEO from "../components/seo" import Board from "../components/fantasy/board" import Matches from "../components/fantasy/matches" import Players from "../components/fantasy/players" import Footer from "../components/footer" import Play from "../components/fantasy/play" import full from "../images/full.svg" import tooLate from "../images/tooLate.svg" import fullDark from "../images/full-dark.svg" import tooLateDark from "../images/tooLate-dark.svg" const sanityClient = require("@sanity/client") const client = sanityClient({ projectId: "0jt5x7hu", dataset: "main", useCdn: true, }) const months = [ "januari", "februari", "mars", "april", "maj", "juni", "juli", "augusti", "september", "oktober", "november", "december", ] const weekdays = ["Sön", "Mån", "Tis", "Ons", "Tors", "Fre", "Lör"] const FantasyPage = props => { const gameState = useGameState() const userState = useUserState() const filters = useFilterState() const [colorMode] = useColorMode() const [loading, setLoading] = useState(false) const [players, setPlayers] = useState([]) const [entries, setEntries] = useState([]) const matches = props.data.matchday.matches const initialState = mapEdgesToNodes(props.data.players) const initSlice = initialState.slice(0, 25) const logos = mapEdgesToNodes(props.data.logos) const date = new Date(props.data.matchday.start) const minutes = date.getMinutes() === 0 ? "00" : `${date.getMinutes()}` const hours = `${date.getHours()}` const day = `${date.getDate()}` const weekday = weekdays[date.getDay()] const month = months[date.getMonth()] const deadline = `${weekday} ${day} ${month} kl ${hours}:${minutes}` const now = Date.now() const start = Date.parse(props.data.matchday.start) const deadlineDay = now > start ? true : false useEffect(() => { setPlayers(initSlice) const sanityQuery = `*[_type == 'matchday' && status == 'current']{entries[]{user->{"name": name}}}` client.fetch(sanityQuery).then(x => { const userList = x[0].entries.map(x => x.user.name) setEntries(userList) }) // eslint-disable-next-line react-hooks/exhaustive-deps }, []) useEffect(() => { if (filters.length > 0) { setPlayers( initialState.filter( x => x.team._id === filters[0] || x.team._id === filters[1] ) ) } else setPlayers(initSlice) // eslint-disable-next-line react-hooks/exhaustive-deps }, [filters]) function showMore(increment) { const length = players.length + increment const slicer = initialState.slice(0, length) setPlayers(slicer) } function register() { setLoading(true) const squad = gameState && gameState.map(player => { const p = { id: player.id, name: player.name } return p }) const user = userState && { _id: userState._id, id: userState.id, name: userState.name, } const matchday = { id: props.data.matchday._id, index: props.data.matchday.index, date: deadline, } axios .post("/.netlify/functions/register", { params: { squad, user, matchday }, }) .then(res => { res.data === "OK" ? navigate("/thanks/") : navigate("/404/") }) .catch(error => { console.log(error) }) } return ( <Layout> <SEO title="Fantasy" description="Prova på ett annorlunda fantasy-spel" /> {loading ? ( <div sx={{ display: "flex", alignItems: "center", justifyContent: "center", my: 8, }} > <Spinner size={60} /> </div> ) : ( <div> <Board deadline={deadline} /> <div sx={{ display: "grid", }} > {gameState && gameState.length !== 3 ? null : deadlineDay ? ( <img sx={{ width: 200, height: 35, mx: "auto", my: 5, }} src={colorMode === "default" ? tooLate : tooLateDark} alt="Fantasy Football" /> ) : ( <div sx={{ textAlign: "center" }}> <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ delay: 0.3, duration: 0.4, }} > <img sx={{ width: 200, height: 35, mx: "auto", my: 5, }} src={colorMode === "default" ? full : fullDark} alt="Fantasy Football" /> </motion.div> </div> )} </div> {gameState && gameState.length < 3 ? ( <div sx={{ display: "grid", minHeight: 970 }}> <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ delay: 0.3, duration: 0.4, }} > <Matches matches={matches} /> <Players players={players} logos={logos} /> </motion.div> </div> ) : ( <Play entries={entries && entries} register={register} deadline={deadlineDay} /> // <button onClick={register}>hej</button> )} {filters && filters.length === 0 && gameState && gameState.length < 3 && ( <div sx={{ display: "flex", alignItems: "center", justifyContent: "center", }} > <button sx={{ fontSize: 5, width: 120, my: 7, px: 6, py: 4, bg: "primary", border: "solid 2px", borderColor: "primary", color: "background", borderRadius: 2, fontFamily: "heading", fontWeight: "heading", appearance: "none", cursor: "pointer", ":after": { color: "background", bg: "primary", }, ":active, :after": { color: "text", bg: "background", opacity: 1, transition: `0s`, }, }} onClick={() => showMore(40)} > Visa fler </button> </div> )} </div> )} <Footer /> </Layout> ) } export default FantasyPage export const query = graphql` query MatchesQuery { matchday: sanityMatchday(status: { eq: "current" }) { _id index start matches { start home { team { _id name fullName } } away { team { _id name fullName } } } } players: allSanityPlayer( filter: { team: { active: { eq: true } } } sort: { fields: points, order: DESC } ) { edges { node { _id name fullName goals assists team { _id name fullName active } } } } logos: allSanityTeam(filter: { active: { eq: true } }) { edges { node { _id logo { asset { fluid(maxWidth: 50) { ...GatsbySanityImageFluid } } } } } } } `
define(function(require, exports, module) { var getImageServerUrl = require("modules/yinyuetai/imageserverurl"), juicer = require("juicer"), ajax = require("ajax"), user = require("user"); juicer.register('getImageServerUrl', getImageServerUrl); //单个好友Model对象 var Friend = Backbone.Model; var Friends = Backbone.Collection.extend({ model : Friend, url : "http://i.yinyuetai.com/follow/attention", maxNumber : 10, getUserId : function() { return user.get("userId"); }, filterData : function(str) { var count = 0; this.results = []; this.each(function(model) { if ( count >= this.maxNumber ) return false; var user = model.toJSON(); if (user.userFullName.indexOf(str) !== -1) { this.results.push(user); count++; } }, this); this.appView.render(); }, fetch : function(str) { var self = this; ajax.get(this.url, 'userId=' + this.getUserId() + '&q=' + str + '&maxResults=' + this.maxNumber, function(data) { if (data.code == 1) { self.formateData(data.result.follows, str); } else if (!data.error) { self.formateData(data.follows, str); } }); }, formateData : function(follows, str) { if (follows.length <= 0) { return; } var i, len; for (i = 0, len = follows.length; i < len; i = i + 3) { var userId = follows[i], userFullName = follows[i + 1], userIconSrc = follows[i + 2], userName = userFullName.split(";")[0], userNameAndId = userName + "(" + userId + ")"; this.push({ userId : userId, userName : userName, userFullName : userFullName, userIconSrc : userIconSrc, userNameAndId : userNameAndId }); } this.filterData(str); }, prepareData : function(str) { if (this.length > 0) { this.filterData(str); return; } this.fetch(str); } }); //单个好友View对象 var FriendView = Backbone.View.extend({ tagName : "li", template : '<a txt="{{userName}}({{userId}})" href="javascript:;"><img width="20" height="20" src="{{userIconSrc|getImageServerUrl}}">{{userName}}({{userId}})</a>', render : function() { var html = juicer(this.template, this.friend); this.$el.html(html); return this; }, initialize : function(data) { this.friend = data.friend; } }); //好友下拉列表 var AppView = Backbone.View.extend({ className : "p_com_name user_name_down", tip : '<p class="popup_text">选择最近聊过天的好友或直接输入</p>', listsCtn : $("<ul></ul>"), listOn : false, hoverClass : "hover", countTime: null, initialize : function(param) { this.friends = param.friends; this.placeholderDiv = param.placeholderDiv; this.textareaView = param.textareaView; this.$el.appendTo(document.body); }, render : function() { this.$el.empty(); if (this.friends.results.length > 0) { this.listsCtn.empty(); this.$el.append(this.tip); this.listsCtn.appendTo(this.$el); _.each(this.friends.results, function(friend) { var view = new FriendView({friend : friend}); view.render().$el.appendTo(this.listsCtn); }, this); } else { this.$el.html('<p class="popup_text">没有匹配结果</p>'); } this.show(); }, show : function() { clearTimeout(this.countTime); this.currentIndex = 0; this.$el.find("li").removeClass().eq(this.currentIndex).addClass(this.hoverClass); this.listOn = true; this.$el.css(this.placeholderDiv.getPosition()).show(); }, hide : function() { var self = this; this.countTime = setTimeout(function() { self.listOn = false; self.$el.hide(); }, 300); }, events : { "click ul" : "itemSelect" }, itemSelect : function(e) { this.textareaView.insertValue($(e.target)); this.hide(); } }); var PlaceholderDiv = Backbone.View.extend({ className : "com_holder", flagChar : "@", selectionStart : 0, fontFamily : "Tahoma,宋体", initialize : function($ele) { var spans; this.$el.html('<span></span><span></span><span></span>'); spans = this.$el.find("span"); this.contEl = spans.eq(0); this.flagEl = spans.eq(1); this.contEndEl = spans.eq(2); this.flagEl.text(this.flagChar); this.$el.appendTo(document.body); this.$textarea = $ele; this.setData(); }, setData : function() { var fontSize = this.$textarea.css("font-size"), widthSize = this.$textarea.width(), heightSize = this.$textarea.height(), paddingLeftSize = this.$textarea.css("paddingLeft"), paddingTopSize = this.$textarea.css("paddingTop"); this.$el.css({ width : widthSize+"px", height : heightSize+"px", paddingLeft: paddingLeftSize, paddingTop: paddingTopSize, lineHeight : this.$textarea.css("line-height"), fontSize : fontSize, fontFamily : this.fontFamily, display : "block" }); this.$textarea.css("font-family", this.fontFamily); this.$el.css(this.$textarea.offset()); //初始定位 this.offsetDistance = parseInt(fontSize) + 5; }, fillCont : function() { if (this.selectionStart <= 0) { return; } var textareaVal = this.$textarea.val(), startVal = textareaVal.substring(0, this.selectionStart), endVal = textareaVal.substring(this.selectionStart + 1, textareaVal.length), regExp = { "<" : "&lt;", ">" : "&gt;", " " : '<span style="white-space:pre-wrap;' + this.fontFamily + '"> </span>', "(\r\n)|\n" : "<br>" }; for (var reg in regExp) { if (regExp.hasOwnProperty(reg)) { startVal = startVal.replace(new RegExp(reg, "ig"), regExp[reg]); endVal = endVal.replace(new RegExp(reg, "ig"), regExp[reg]); } } this.contEl.html(startVal); this.contEndEl.html(endVal); }, getPosition : function() { this.$el.css(this.$textarea.offset()); this.fillCont(); this.$el.scrollTop(this.$textarea.scrollTop()); var offset = this.flagEl.offset(); return { left : offset.left, top : offset.top + this.offsetDistance }; } }); var TextareaView = Backbone.View.extend({ flagChar : "@", flagStart : -1, selectionStart : 0, //当前光标位置 selectionRange : null, initialize : function($ele) { if ($ele.length <= 0) { return; } this.$el = $ele; this.placeholderDiv = new PlaceholderDiv($ele); this.friends = new Friends(); this.appView = new AppView({ friends : this.friends, placeholderDiv : this.placeholderDiv, textareaView : this }); this.friends.appView = this.appView; }, events : { "keyup" : "decideChange", "click" : "onChange", "blur" : "setAppViewHidden" }, setAppViewHidden: function() { this.appView.hide(); }, decideChange : function(e) { if (e.keyCode == 38 || e.keyCode == 40 || e.keyCode == 13) { this.selectItem(e); } else { this.onChange(); } }, selectItem : function(e) { if (!this.appView.listOn) { return; } switch (e.keyCode) { //向上 case 38: e.preventDefault(); if (this.appView.currentIndex === 0) { this.appView.currentIndex = this.friends.results.length - 1; } else { this.appView.currentIndex--; } this.appView.$el.find("li").removeClass().eq(this.appView.currentIndex).addClass(this.appView.hoverClass); break; //向下 case 40: e.preventDefault(); if (this.appView.currentIndex === this.friends.results.length - 1) { this.appView.currentIndex = 0; } else { this.appView.currentIndex++; } this.appView.$el.find("li").removeClass().eq(this.appView.currentIndex).addClass(this.appView.hoverClass); break; //回车事件 case 13: e.preventDefault(); this.insertValue(this.appView.$el.find("li").eq(this.appView.currentIndex).children("a")); this.appView.hide(); break; } }, getSelectionStart: function() { var textarea = this.$el[0], selectionStart = 0; //获取光标的当前位置 this.$el.focus(); if (document.selection) { //ie this.selectionRange = document.selection.createRange().duplicate(); if (this.selectionRange.parentElement() == textarea) { var beforeRange = document.body.createTextRange(); beforeRange.moveToElementText(textarea); beforeRange.setEndPoint('EndToStart', this.selectionRange); var beforeText, untrimmedBeforeText; beforeText = untrimmedBeforeText = beforeRange.text; while (beforeRange.compareEndPoints('StartToEnd', beforeRange) != 0) { beforeRange.moveEnd('character', -1); if (beforeText == beforeRange.text) { untrimmedBeforeText += '\r\n'; } } selectionStart = untrimmedBeforeText.length; } } else { selectionStart = textarea.selectionStart; } return selectionStart; }, setCursorStart: function(startPos) { var textarea = this.$el[0], start = startPos, end = startPos; if(textarea.createTextRange){ var oTextRange = textarea.createTextRange(); var LStart = start; var LEnd = end; var start = 0; var end = 0; var value = textarea.value; for(var i=0; i<value.length && i<LStart; i++){ var c = value.charAt(i); if(c!='\n'){ start++; } } for(var i=value.length-1; i>=LEnd && i>=0; i--){ var c = value.charAt(i); if(c!='\n'){ end++; } } oTextRange.moveStart('character', start); oTextRange.moveEnd('character', -end); oTextRange.select(); textarea.focus(); }else{ textarea.select(); textarea.selectionStart=start; textarea.selectionEnd=end; } }, onChange : function() { this.selectionStart = this.placeholderDiv.selectionStart = this.getSelectionStart(); var before = this.$el.val().substring(0, this.selectionStart); this.flagStart = before.lastIndexOf(this.flagChar); if (this.flagStart != -1) { //找到@的位置 var str = before.substring(this.flagStart + 1, this.selectionStart); if (str.indexOf(' ') == -1 && str.indexOf('\n') == -1) { this.friends.prepareData(str); } else { this.appView.hide(); } } else { this.appView.hide(); } }, autoChange: function() { var textareaVal = this.$el.val(), selectionStart = this.getSelectionStart(), before = this.$el.val().substring(0, selectionStart), lastChar = before.substring(selectionStart-1), pos = selectionStart; if (lastChar !== this.flagChar) { var startVal = textareaVal.substring(0, selectionStart), endVal = textareaVal.substring(selectionStart + 1, textareaVal.length); this.$el.val(startVal+this.flagChar+endVal).focus(); pos = startVal.length+1; } this.setCursorStart(pos); this.onChange(); }, insertValue : function($e) { var $link = $e; var input = this.$el[0], val = this.$el.val(); var before = val.substring(0, this.flagStart + 1); //加1是@ var after = val.substring(this.selectionStart, val.length); var middle = val.substring(this.flagStart + 1, this.selectionStart); var newMiddle = $link.attr("txt") + ' '; if (document.selection) { this.selectionRange.moveStart('character', -middle.length); this.selectionRange.text = newMiddle; this.selectionRange.select(); } else { input.focus(); var restoreTop = input.scrollTop; this.$el.val(before + newMiddle + after); if (restoreTop > 0) { input.scrollTop = restoreTop; } input.selectionEnd = input.selectionStart = this.flagStart + 1 + newMiddle.length; } } }); module.exports = TextareaView; });
import React, { useState } from "react"; import {inputStyle, inputWrapperStyle, buttonStyle} from './style' function LoginPage(props) { const [username, setUsername] = useState("") const [password, setPassword] = useState("") //Handles the event of the username input field changing const usernameInput = (ev) => { setUsername(ev.target.value) } //Handles the event of the password input field changing const passwordInput = (ev) => { setPassword(ev.target.value) } //Returns the login form return <div style={{ display: "flex", justifyContent: "center", alignItems: "center" }} > <div > <h2 style={{ marginBottom: "20px" }}>Login</h2> <div style={inputWrapperStyle} > <p style={{ marginRight: "5px" }} >Username</p> <input style={inputStyle} onChange={usernameInput} /> </div> <div style={inputWrapperStyle} > <p style={{ marginRight: "5px" }} >Password</p> <input style={inputStyle} onChange={passwordInput} /> </div> <button style={buttonStyle} onClick={() => props.tryLogin(username, password)}>Go</button> <h3 style={{color: "red"}}>{props.errorMessage}</h3> </div> </div> } export { LoginPage }
const todo = (state = {}, action) => { console.log("Todo: ", state) switch (action.type) { case 'ADD': return { ...action.payload } default: return state; } } export const todos = (state = [], action) => { console.log("Todos action: ", action) console.log("Todos: ", state) switch (action.type) { case 'SET': return action.payload case 'ADD': return [...state, todo(undefined, action)] case 'DELETE': return state.filter(todoItem => { return todo.id != todoItem.id }) default: return state } }
import a from './a'; const isFn = (f) => typeof f === 'function'; console.log('a', a); export default isFn;
console.log('it\'s working, it\'s working!'); console.log(document); window.addEventListener('DOMContentLoaded', (event) => { console.log('DOM fully loaded and parsed'); // Model // initialize localStorage // load stored values or empty string into html table // display or set player whose turn it is - x by default var gameStorage = window.localStorage; document.getElementById('one-one').innerHTML = gameStorage.getItem('one-one') || ''; document.getElementById('one-two').innerHTML = gameStorage.getItem('one-two') || ''; document.getElementById('one-three').innerHTML = gameStorage.getItem('one-three') || ''; document.getElementById('two-one').innerHTML = gameStorage.getItem('two-one') || ''; document.getElementById('two-two').innerHTML = gameStorage.getItem('two-two') || ''; document.getElementById('two-three').innerHTML = gameStorage.getItem('two-three') || ''; document.getElementById('three-one').innerHTML = gameStorage.getItem('three-one') || ''; document.getElementById('three-two').innerHTML = gameStorage.getItem('three-two') || ''; document.getElementById('three-three').innerHTML = gameStorage.getItem('three-three') || ''; gameStorage.getItem('playerTurn') ? console.log(`your move ${gameStorage.getItem('playerTurn')}`) : gameStorage.setItem('playerTurn', 'x'); // Controller // function to check for any winning combinations - could probably optimize this var tableChecker = function() { // diagonal one if ((document.getElementById('one-one').innerHTML !== '') && (document.getElementById('one-one').innerHTML === document.getElementById('two-two').innerHTML && document.getElementById('two-two').innerHTML === document.getElementById('three-three').innerHTML)) { return true; } // diagonal two if ((document.getElementById('one-three').innerHTML !== '') && (document.getElementById('one-three').innerHTML === document.getElementById('two-two').innerHTML && document.getElementById('two-two').innerHTML === document.getElementById('three-one').innerHTML)) { return true; } // each row if ((document.getElementById('one-one').innerHTML !== '') && (document.getElementById('one-one').innerHTML === document.getElementById('one-two').innerHTML && document.getElementById('one-two').innerHTML === document.getElementById('one-three').innerHTML)) { return true; } if ((document.getElementById('two-one').innerHTML !== '') && (document.getElementById('two-one').innerHTML === document.getElementById('two-two').innerHTML && document.getElementById('two-two').innerHTML === document.getElementById('two-three').innerHTML)) { return true; } if ((document.getElementById('three-one').innerHTML !== '') && (document.getElementById('three-one').innerHTML === document.getElementById('three-two').innerHTML && document.getElementById('three-two').innerHTML === document.getElementById('three-three').innerHTML)) { return true; } // each column if ((document.getElementById('one-one').innerHTML !== '') && (document.getElementById('one-one').innerHTML === document.getElementById('two-one').innerHTML && document.getElementById('two-one').innerHTML === document.getElementById('three-one').innerHTML)) { return true; } if ((document.getElementById('one-two').innerHTML !== '') && (document.getElementById('one-two').innerHTML === document.getElementById('two-two').innerHTML && document.getElementById('two-two').innerHTML === document.getElementById('three-two').innerHTML)) { return true; } if ((document.getElementById('one-three').innerHTML !== '') && (document.getElementById('one-three').innerHTML === document.getElementById('two-three').innerHTML && document.getElementById('two-three').innerHTML === document.getElementById('three-three').innerHTML)) { return true; } return false; // }; // click handler for filling rows var rowFiller = function(e) { e.preventDefault(); console.log(e.target); console.log(e.target.id); var cellNumber = e.target.id; //??????? var cell = document.getElementById(cellNumber) var currentPlayer = gameStorage.getItem('playerTurn'); if(cell.innerHTML === '') { // set element value equal to current player cell.innerHTML = currentPlayer; // add value to local storage gameStorage.setItem(cellNumber, currentPlayer); // if table checker is true if (tableChecker()) { document.getElementById('banner').innerHTML = `${currentPlayer} wins!`; } else { // else change current player in localStorage var nextPlayer = (currentPlayer === 'x' ? 'o' : 'x'); gameStorage.setItem('playerTurn', nextPlayer); } } else { console.error('please select an empty cell'); } }; let allCells = document.getElementsByClassName('cell'); var resetTable = function(e) { e.preventDefault(); // set value of every cell to '' for (let i = 0; i < allCells.length; i++) { allCells[i].innerHTML = ''; } //clear banner document.getElementById('banner').innerHTML = ''; // clear local storage gameStorage.clear(); // set player to x gameStorage.setItem('playerTurn', 'x'); } // add event listener to all cells for togglings pieces for (let i=0; i < allCells.length; i++) { allCells[i].addEventListener('click', rowFiller); } // add event listener for reset button to clear the board document.getElementById('reset').addEventListener('click', resetTable); });
new_element = document.createElement("script") new_element.setAttribute("type", "text/javascript"); new_element.setAttribute("src", "js/jsencrypt/bin/jsencrypt.min.js"); document.body.appendChild(new_element) var encrypt = new JSEncrypt({default_key_size: 1024}); public_key = encrypt.getPublicKey(); private_key = encrypt.getPrivateKey(); function getPublicKey() { return public_key } function getPrivateKey() { return private_key } var public_key var private_key function generateKey() { new_element = document.createElement("script") new_element.setAttribute("type", "text/javascript"); new_element.setAttribute("src", "js/jsencrypt/bin/jsencrypt.min.js"); document.body.appendChild(new_element) var encrypt = new JSEncrypt({default_key_size: 1024}); public_key = encrypt.getPublicKey(); private_key = encrypt.getPrivateKey(); }
import { createStore as reduxCreateStore } from 'redux'; import fire from '../fire'; import _ from 'lodash'; const reducer = (state, action) => { if (action.type === `INCREMENT`) { return Object.assign({}, state, { count: state.count + 1 }); } if (action.type === `SET_ENTRY_TYPE`) { return Object.assign({}, state, { currentEntryType: action.entryType }) } return state; }; const initialState = { userId: '', // userId will become deprecated.. caregiverId: '1stBAn853ARfEUgtxwdJ63lkDlK2', caregiverEmail: 'rva.christian91@gmail.com', caregiverFirst: 'Christian', caregiverLast: 'Bryant', activePatientId: '1', currentEntryType: false, patients: [ { patientId: '1', firstName: 'Maya', lastName: 'Lou', info: { birthday: '11/08/1991', street: '10 S. Crenshaw Ave.', city: 'Richmond', state: 'VA', zipcode: '23220', diagnosis: 'Austism', gender: 'F', profileImageURL: 'http://via.placeholder.com/100x100' } }, { patientId: '2', firstName: 'Sean', lastName: 'Schaeffer', info: { birthday: '06/26/1993', street: '3200 W. Clay St.', city: 'Richmond', state: 'VA', zipcode: '23221', diagnosis: 'Austism', gender: 'M', profileImageURL: 'http://via.placeholder.com/100x100' } }, ], rxEntries: [ { date: '12/2/2017', time: '7:34PM', productType: 'OTC', prescribedBy: 'Dr. Bob', productName: 'Valerian Root', strength: '200mg', dose: '10mg', timesPerDay: '2x a day, am and pm', numberOfDays: 30, purpose: 'get back on regular sleep schedule', sideEffects: 'moderate to severe nausea', helped: 'not really', myCost: 30, notes: 'some notes here lorem ipsum dolar set amit' }, { date: '12/1/2017', time: '8:43PM', productType: 'Rx', prescribedBy: '', productName: 'Advil', strength: 'Extra Strength', dose: '10mg', timesPerDay: 'As needed, no more than 4 tablets per day', numberOfDays: 0, purpose: 'Help ease muscle pain', sideEffects: 'none', helped: 'yes, a little bit', myCost: 30, notes: 'some notes here lorem ipsum dolar set amit' } ] }; const createStore = () => reduxCreateStore( reducer, initialState, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__() ); export default createStore;
const textContainerIndexCopy = { "en": { "INDEX": {} }, "kr": { "INDEX": {} }, "ch": { "INDEX": {} }, "jp": { "INDEX": {} } } export default textContainerIndexCopy;
/* Object oriented design is commonly used in video games. For this part of the assignment you will be implementing several classes with their correct inheritance heirarchy. In this file you will be creating three classes: GameObject, CharacterStats, Humanoid. At the bottom of this file are 3 objects that all inherit from Humanoid. Use the objects at the bottom of the page to test your classes. Each class has unique properites and methods that are defined in their block comments below: */ //GameState //Holds the current game state, principally characters. Initiates with a list of characters. Characters are Hero and Villain objects held in an array. GameState.heroes and GameState.counts keep class GameState { constructor() { this.characters = []; this.heroes = 0; this.villains = 0; } //Game Method that receives an initial array of characters and iterates through them, adding each to the GameSTate.characters array by calling GameState.addChar repeatedly. start(charArr) { for (let i = 0; i < charArr.length; i++) { this.addChar(charArr[i]) } console.log('Game has begun. Time is not on your side.'); } //adds a character to the characters array. It also increments the heroes or villains properties depending on which character type is added. addChar(char) { char.gameloc = this; this.characters.push(char); this.updateCharCounts(char, 1); } //removes a character from the characters array. If no villains left, declares victory. If no heroes left, declares loss. removeChar(char) { let charArr = this.characters; let index = -1; for (let i = 0; i < charArr.length; i++) { if (charArr[i] === char) { index = i; break; } } charArr.slice(index, 1); this.updateCharCounts(char, -1); this.checkContinue(); } // receives a character, and an inc Number to change the hero and villain counts of the GameState depending on whether character is a hero or villain. updateCharCounts(char, inc) { if (char instanceof Hero) { this.heroes += inc; } else if (char instanceof Villain) { this.villains += inc; } } //checks if there are still heroes or villains remaining. If one of these counts has gone to 0, then victory or defeat string is logged. checkContinue() { if (this.villains < 1) { console.log('Good has triumphed over evil! This time...'); } if (this.heroes < 1) { console.log('The prophecy has been fulfilled. You and your people are doomed. You see a black mist descend on the village. As you take your last breathe, you realize that death now can only be a mercy.'); } } } /* === GameObject === * createdAt * dimensions * destroy() // */ class GameObject { constructor(dataObj) { this.createdAt = dataObj.createdAt; this.dimensions = dataObj.dimensions; } //logs the string 'Object was removed from the game.' destroy() { if (this.name) { console.log(`${this.name} was removed from game`); } console.log(`${this.constructor.name} was removed from game`); } } /* === CharacterStats === * hp * name * takeDamage() // prototype method -> logs the string '<object name> took damage.' * should inherit destroy() from GameObject's prototype */ class CharacterStats extends GameObject { constructor(dataObj) { super(dataObj); this.hp = dataObj.hp; this.name = dataObj.name; } //Logs that object took damage. //Mutation Effect: Reduces Characters HP. takeDamage(dmgPts) { this.hp -= dmgPts; if (this.hp > 0) { console.log(`${this.name} took damage. ${this.hp} hit points remain.`); } else { if (this instanceof Hero) { console.log(`Alas, ${this.name} has died.`); } else { console.log(`${this.name} was slain!`); } this.gameloc.removeChar(this); } } } /* === Humanoid === * faction * weapons * language * greet() // prototype method -> logs the string '<object name> offers a greeting in <object language>.' * should inherit destroy() from GameObject through CharacterStats * should inherit takeDamage() from CharacterStats */ class Humanoid extends CharacterStats { constructor(dataObj) { super(dataObj); this.faction = dataObj.faction; this.weapons = dataObj.weapons; this.language = dataObj.language; } greet() { console.log(`${this.name} offers a greeting in ${this.language}.`); } } //Hero Constructor, descendent of Humanoid class Hero extends Humanoid { constructor(dataObj) { super(dataObj); } attack(target) { // See genericAttack() description genericAttack.call(this, target, 2); } } //Villain Constructor, descendent of Humanoid class Villain extends Humanoid { constructor(dataObj) { super(dataObj); } attack(target) { // See genericAttack() description genericAttack.call(this, target, 3); } } //Attack function, used by Hero and Villain classes for their attack methods. Logs a string stating that this attacked target and with what weapon. //NOTE: Loweres HP of target, and updates GameState if necessary let genericAttack = function (target, dmg) { console.log(`${this.name} attacked ${target.name} with ${this.weapons[0]}.`); target.takeDamage(dmg); } const mage = new Hero({ createdAt: new Date(), dimensions: { length: 2, width: 1, height: 1, }, hp: 5, name: 'Bruce', faction: 'Mage Guild', weapons: [ 'Staff of Shamalama', ], language: 'Common Toungue', }); const swordsman = new Villain({ createdAt: new Date(), dimensions: { length: 2, width: 2, height: 2, }, hp: 15, name: 'Sir Mustachio', faction: 'The Round Table', weapons: [ 'Giant Sword', 'Shield', ], language: 'Common Toungue', }); const archer = new Hero({ createdAt: new Date(), dimensions: { length: 1, width: 2, height: 4, }, hp: 10, name: 'Lilith', faction: 'Forest Kingdom', weapons: [ 'Bow', 'Dagger', ], language: 'Elvish', }); /* console.log(mage.createdAt); // Today's date console.log(archer.dimensions); // { length: 1, width: 2, height: 4 } console.log(swordsman.hp); // 15 console.log(mage.name); // Bruce console.log(swordsman.faction); // The Round Table console.log(mage.weapons); // Staff of Shamalama console.log(archer.language); // Elvish console.log(archer.greet()); // Lilith offers a greeting in Elvish. console.log(mage.takeDamage(6)); // Bruce took damage. console.log(swordsman.destroy()); // Sir Mustachio was removed from the game. */ let startingChars = [mage, swordsman, archer]; let game = new GameState(); game.start(startingChars); archer.attack(swordsman); swordsman.attack(archer); swordsman.attack(mage); archer.attack(swordsman); archer.attack(swordsman); mage.attack(swordsman); mage.attack(swordsman); swordsman.attack(mage); archer.attack(swordsman); archer.attack(swordsman); swordsman.attack(archer); swordsman.attack(archer); swordsman.attack(archer); //comment out for victory // archer.attack(swordsman); //uncomment for victory
function submitForm(id) { var formObject = document.getElementById(id); YAHOO.util.Connect.setForm(formObject, false); /*when using Yahoo.Connect to upload files, a different handler needs to be used. * 'success' is not used. instead, 'upload' is used. * http://developer.yahoo.com/yui/connection/#file */ var callback = { success: function(resp){handleFileLoad(resp);}, timeout: 10000 }; var url = "/servlet"; var cObj = YAHOO.util.Connect.asyncRequest('GET', url, callback); } function handleFileLoad(resp){ document.getElementById("textArea").value = resp.responseText; }
import React from 'react'; import styled, { css } from 'styled-components'; import { boldStyles, device, visuallyHidden } from '../../../theme'; import vars from '../../../vars'; import withFiletto from '../../../components/hoc/withFiletto'; import BaseLayout from '../../../components/layout/Base'; import Head from '../../../components/common/Head'; import Pager from '../../../components/ui/Pager'; import Bloglayout from '../BlogLayout'; import BlogMap from '../BlogMap'; import BlogMenu from '../BlogMenu'; import BlogPostList from '../BlogPostList'; import VerticalSpace from '../../../components/ui/VerticalSpace'; export default function BlogPage({ posts, postsCount, category, categories, route, pagination, }) { let title = 'Relazioni'; if (category) { title = category; } return ( <BaseLayout route={route} head={ <Head title={title} slogan={vars.siteName} description="L’elenco completo di tutte le relazioni, con la mappa e la ricerca" extraLinks={ <> <link rel="preconnect" href="https://assets.ctfassets.net" crossOrigin="anonymous" /> <link rel="preconnect" href="https://tile.thunderforest.com" crossOrigin="anonymous" /> </> } /> } > <Bloglayout topBar={ <BlogMenu category={category} categories={categories} /> } content={ <> <StyledPageTitle category={category}> {title} </StyledPageTitle> <BlogPostList posts={posts} /> <VerticalSpace size={4} /> <Pager pagination={pagination} /> {!category && ( <PostCount> <strong>{postsCount}</strong>{' '} <span>relazioni</span> </PostCount> )} </> } map={<BlogMap category={category} />} /> </BaseLayout> ); } const StyledPageTitle = withFiletto(styled.h1` text-transform: uppercase; ${boldStyles} margin-bottom: calc(var(--space-unit) * 1.5); ${(props) => !props.category && css` ${visuallyHidden} `} @media ${device.desktop} { ${visuallyHidden} } `); const PostCount = styled.p` margin-top: calc(var(--space-unit) * 2); strong { ${boldStyles} } `;
'use babel'; const path = require('path'); const fs = require('fs'); /** * Gets first root folder opened in Atom * * @todo Support multiple root folders etc. */ exports.getRootFolder = () => atom.project.getPaths()[0]; /** * Returns true if current project is RN */ exports.isRNProject = () => { const rootFolder = exports.getRootFolder(); if (!rootFolder) return false; return fs.existsSync(path.join(rootFolder, 'node_modules', 'react-native')); };
import React, { useEffect, useState, useContext } from "react"; import ProfileContext from "../../Context/ProfileContext"; import "./Navbar.scss"; import { Link } from "react-router-dom"; import DropdownList from "../DropdownList/DropdownList"; import DropdownMenu from "../DropdownMenu/DropdownMenu"; import api from "../../api/index"; const Navbar = () => { // TODO: when a profile is made to add to listOfProfiles. const [listOfProfiles, setListOfProfiles] = useState([]); const {profile, setProfile} = useContext(ProfileContext); const [isProfileDropdownActive, setIsProfileDropdownActive] = useState(false); const [isNewProfileDropdownActive, setIsNewProfileDropdownActive] = useState(false); useEffect(() => { getListOfProfiles(); }, []); const getListOfProfiles = () => api.getProfiles().then((res) => setListOfProfiles(res.data)); const handleProfileDropDownClick = () => setIsProfileDropdownActive(!isProfileDropdownActive); const handleNewProfileDropdownClick = () => setIsNewProfileDropdownActive(!isNewProfileDropdownActive); const handleDropdownListClick = (event) => { const choosenProfile = event.target.innerHTML; for (let i = 0; i < listOfProfiles.length; i++) { if (listOfProfiles[i].name === choosenProfile) { setProfile(listOfProfiles[i]); break; } } setIsProfileDropdownActive(false); }; return ( <nav className="navbarContainer"> <div className="brand-logo"> <Link to="/"> <h4>Sasquatchtory</h4> </Link> </div> <div className="nav-links"> <DropdownMenu buttonDisplay={<p>New Profile</p>} handleDropDownClick={handleNewProfileDropdownClick} value={isNewProfileDropdownActive} > {/* form goes here to add a new profile */} <div className="dropdown-content"> <p>Should be displaying.</p> </div> </DropdownMenu> <DropdownMenu activeProfile={profile} value={isProfileDropdownActive} handleDropDownClick={handleProfileDropDownClick} buttonDisplay={ <p> {profile?.name ? "Active profile: " + profile.name : "Choose Profile"} </p> } > {listOfProfiles.map((currentProfile) => { return ( <DropdownList profile={currentProfile} key={currentProfile._id} handleClick={handleDropdownListClick} /> ); })} </DropdownMenu> </div> </nav> ); }; export default Navbar;
let vertexShader = ` attribute vec4 a_Position; attribute vec4 a_Color; uniform mat4 u_Transform; uniform mat4 u_Projection; varying vec4 v_Color; void main(){ v_Color = a_Color; gl_Position = u_Projection * u_Transform * a_Position; }`; var fragmentShader = ` precision mediump float; varying vec4 v_Color; void main(){ gl_FragColor = v_Color; }`; var createTriangles = function(gl, program){ // vertices and their colors (arranged x1,y1,z1, r1,g1,b1, x2, y2, z2, r2,g2.b2, etc...) var vertices = new Float32Array([ -0.5, -0.3, -0.25, 1.0, 0.4, 0.4, // front face 0.5, -0.3, -0.25, 1.0, 0.4, 0.4, 0.5, 0.8, -0.25, 1.0, 0.4, 0.4, -0.5, -0.3, -0.25, 0.4, 1.0, 0.4, // back face 0.5, -0.3, -0.25, 0.4, 1.0, 0.4, 0.0, 0.8, -0.25, 0.4, 1.0, 0.4 ]); // calculate the number of vertices var n = vertices.length/6; // Push the vertex attributes down to the VBO var vertexBuffer = gl.createBuffer(); if (!vertexBuffer) { console.log('Failed to create the buffer object'); return -1; } gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer); gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW); var FSIZE = vertices.BYTES_PER_ELEMENT; // specify the association between the VBO and the a_Position attribute var a_Position = gl.getAttribLocation(program, 'a_Position'); if (a_Position < 0) { console.log('Failed to get storage location'); return -1; } gl.vertexAttribPointer(a_Position, 3, gl.FLOAT, false, FSIZE*6,0); gl.enableVertexAttribArray(a_Position); // specify the association between the VBO and the a_Color attribute var a_Color= gl.getAttribLocation(program, 'a_Color'); if (a_Color < 0) { console.log('Failed to get storage location'); return -1; } gl.vertexAttribPointer(a_Color, 3, gl.FLOAT, false, FSIZE*6, FSIZE*3); gl.enableVertexAttribArray(a_Color); // return the number of vertices return n; }; var render = function(gl, count, offsetEnabled){ // clear the canvas gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); // draw the first triangle gl.drawArrays(gl.TRIANGLES, 0, count/2); // check if we should enable the offset if (offsetEnabled){ gl.enable(gl.POLYGON_OFFSET_FILL); } // draw the second triangle gl.drawArrays(gl.TRIANGLES, count/2, count/2); // disable the offset gl.disable(gl.POLYGON_OFFSET_FILL); }; window.onload = function(){ let canvas = document.getElementById('canvas'); let gl; // catch the error from creating the context since this has nothing to do with the code try{ gl = middUtils.initializeGL(canvas); } catch (e){ alert('Could not create WebGL context'); return; } // don't catch this error since any problem here is a programmer error let program = middUtils.initializeProgram(gl, vertexShader, fragmentShader); // create the triangles let n = createTriangles(gl, program); let transform = mat4.create(); let eye = vec3.fromValues(1,1,2); let up = vec3.fromValues(0,1,0); let at = vec3.fromValues(0,.25,0); mat4.lookAt(transform, eye, at, up); let u_Transform = gl.getUniformLocation(program, 'u_Transform'); gl.uniformMatrix4fv(u_Transform, false, transform); let projection = mat4.create(); mat4.perspective(projection, Math.PI/7, 1, .5, 10); let u_Projection = gl.getUniformLocation(program, 'u_Projection'); gl.uniformMatrix4fv(u_Projection, false, projection); gl.enable(gl.DEPTH_TEST); gl.clearColor(0.0, 0.0, 0.0, 1.0); // set the polygon offset gl.polygonOffset(1.0, 1.0); // re-render the scene when the button is clicked toggle.onchange = function(){ on = toggle.checked; render(gl , n, on); } render(gl ,n, false); };
/* begin copyright text * * Copyright © 2016 PTC Inc., Its Subsidiary Companies, and /or its Partners. All Rights Reserved. * * end copyright text */ /* jshint node: true */ /* jshint strict: global */ 'use strict'; var debug = require('debug')('vxs:proxymgr'); var express = require('express'); var lodash = require('lodash'); var Q = require('q'); var url = require('url'); var Proxy = require('./proxy.js'); var proxyTableName = 'proxy'; var router = express.Router(); var dbHandler = null; var webProxies = []; var websocketProxies = []; function ProxyManager() {} ProxyManager.getRouter = function getRouter() { return router; }; ProxyManager.init = function init(appSettings) { if (!lodash.isPlainObject(appSettings)) { throw new Error("Invalid 'appSettings' object"); } if (!appSettings._dbHandler) { throw new Error("No database handler found"); } if (appSettings.allowProxyingRestrictedRoutes) { Proxy.allowRestrictedRoutes(); } if (!lodash.isNil(appSettings.proxies)) { if (!lodash.isPlainObject(appSettings.proxies)) { throw new Error("Invalid 'proxies' configuration object"); } lodash.forOwn(appSettings.proxies, function(properties, id) { properties.openidAuthentication = (appSettings.authentication.type === "openidUser"); webProxies.push(new Proxy(id, properties)); }); addWebProxies(); } if (!lodash.isNil(appSettings.websocketProxies)) { if (!lodash.isPlainObject(appSettings.websocketProxies)) { throw new Error("Invalid 'websocketProxies' configuration object"); } lodash.forOwn(appSettings.websocketProxies, function(properties, id) { websocketProxies.push(new Proxy(id, properties, true)); }); } dbHandler = appSettings._dbHandler; return loadFromDatabase(); }; ProxyManager.addWebsocketProxies = function addWebsocketProxies(onServer) { if (!onServer) { throw new Error('Cannot add websocket proxies without an active webserver instance'); } websocketProxies.forEach(function(proxy) { onServer.on('upgrade', function(req, socket, head) { proxy.middleware(req, socket, head); }, function(e) { console.error('Error upgrading request for proxy id: ' + proxy.id, e); } ); }); console.log('%s websocket proxies created', websocketProxies.length); }; ProxyManager.updateProxy = function updateProxy(id, properties, callback) { var deferred = Q.defer(); try { var updateHandler = updateAProxy(id, properties); storeToDatabase(id, properties) .then(function() { updateHandler.commit(); deferred.resolve(); }) .catch(function(err) { updateHandler.rollback(); deferred.reject(err); }) .done(); } catch(error) { deferred.reject(error); } return deferred.promise.nodeify(callback); }; ProxyManager.findProxy = findProxy; function addWebProxies() { var routes = {}; webProxies.forEach(function(proxy) { if (routes.hasOwnProperty(proxy.route)) { throw new Error('Route [' + proxy.route + '] for proxy id ' + proxy.id + ' conflicts with the route for id: ' + routes[proxy.route]); } router.use(proxy.route, function proxyMiddleware(req, res, next) { proxy.middleware(req, res, next); }); routes[proxy.route] = proxy.id; }); console.log('%s web proxy routes created', webProxies.length); } function updateAProxy(id, properties) { var proxy = null; var twxWebsocketProxy = null; var commit = function commit() { if (proxy) { proxy.commit(); } if (twxWebsocketProxy) { twxWebsocketProxy.commit(); } }; var rollback = function rollback() { if (proxy) { proxy.rollback(); } if (twxWebsocketProxy) { twxWebsocketProxy.rollback(); } }; try { proxy = findProxy(id); if (!proxy) { throw notFoundError('Cannot find a proxy with id: ' + id, true); } proxy.update(properties); if (proxy.isDefaultThingworx()) { twxWebsocketProxy = findProxy(proxy.id, true); if (twxWebsocketProxy) { var urlObject = url.parse(properties.target); var websocketTarget = (urlObject.protocol === 'http:' ? 'ws' : 'wss') + '://' + urlObject.host; twxWebsocketProxy.update({target: websocketTarget, disabled: properties.disabled}); } else { throw notFoundError('Cannot find websocket proxy for default Thingworx configuration'); } } return {commit: commit, rollback: rollback}; } catch(error) { rollback(); throw error; } } function storeToDatabase(id, properties) { var stringifiedProperties = JSON.stringify(properties); var attributes = { id: id, properties: stringifiedProperties, modifiedon: new Date(Date.now()).toUTCString() }; return dbHandler.insertOrUpdate(attributes, proxyTableName, 'properties'); } function findProxy(id, isWebsocket) { if (!lodash.isString(id)) { return null; } id = id.toLowerCase(); var collection = isWebsocket ? websocketProxies : webProxies; return lodash.find(collection, function(proxy) { return proxy.id === id; }); } function loadFromDatabase(callback) { var deferred = Q.defer(); dbHandler.selectWithParams(['id', 'properties'], proxyTableName) .then(function(rows) { var deletePromises = []; lodash.forEach(rows, function(row) { try { debug("proxy '%s' configuration from DB: ", row.id, row.properties); var properties = JSON.parse(row.properties); updateAProxy(row.id, properties).commit(); } catch(error) { if (error.status !== 404) { throw error; } else if (error.deletePersistedConfig) { deletePromises.push(deleteFromDatabase(row.id)); } } }); return Q.all(deletePromises); }) .done(deferred.resolve, deferred.reject); return deferred.promise.nodeify(callback); } function deleteFromDatabase(id) { return dbHandler.delete(proxyTableName, "id = ?", [id]) .tap(function() { console.warn("Deleted proxy configuration for id %s from the database since no" + " default configuration was found", id); }); } function notFoundError(message, deletePersistedConfig) { var error = new Error(message); error.status = error['http_code'] = 404; error.deletePersistedConfig = deletePersistedConfig; return error; } module.exports = ProxyManager;
import {CSSTransition} from "react-transition-group"; import React, {useEffect, useState} from "react"; import './NavBar.css'; const NavBar = () => { let d = new Date(); const months = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEPT", "OCT", "NOV", "DEC"]; const [fullTime, setTime] = useState(d.toLocaleTimeString()); const [fullDate, setDate] = useState(months[d.getMonth()] + " " + d.getDate() + " - " + d.getFullYear()); useEffect(() => { setInterval(() => { let d = new Date(); setTime(d.toLocaleTimeString()); setDate(months[d.getMonth()] + " " + d.getDate() + " - " + d.getFullYear()); }, 1000); }); const [menu, setMenu] = useState(false); function plusClick() { setMenu(!menu); } function handleClick() { alert("Button Clicked!") } return ( <div className={'navbar'}> {menu ? ( <a className={'plus'} onClick={plusClick}>-</a> ) : ( <a className={'plus'} onClick={plusClick}>+</a> )} <a className={'date'}>{fullDate}</a> <div className={'vector-2'} > <hr className={'vector-2-line'}/> </div> <a className={'time'}>IT IS CURRENTLY:</a> <a className={'time actual'}>{fullTime}</a> <CSSTransition in={menu} classNames="example" timeout={350} unmountOnExit > <a className={'popout'} > <a className={'about'} onClick={handleClick}>ABOUT</a> <a className={'work'} onClick={handleClick}>WORK</a> <a className={'contact'} onClick={handleClick}>CONTACT</a> </a> </CSSTransition> </div> ) } export default NavBar;
import React from "react"; import { StyleSheet, FlatList as EventList, View, Pressable, TouchableOpacity } from "react-native"; import { Searchbar } from "react-native-paper"; //components import { SafeArea } from "../../../components/utility/SafeArea"; import { EventCardExplore } from "../../Events/components/event-card-explore/EventCardExplore"; // check if there is StautusBar.currentHeight. It only exists for android // import { SafeAreaView, StatusBar } from 'react-native'; // import styled from 'styled-components/native' // const SafeArea = styled(SafeAreaView)` // ${StatusBar.currentHeight && `margin-top: ${StatusBar.currentHeight}px`}; // ` export const ExploreScreen = ({ navigation }) => { return ( <SafeArea> <View style={styles.search}> <Searchbar /> </View> <EventList data={[{ name: 1, id: 0 }, { name: 2, id: 1 }]} renderItem={({ item }) => ( <Pressable onPress={() => navigation.navigate('EventDetail', { screen: 'EventDetail', params: { itemId: 86, otherParam: 'anything you want here', } }) } > <EventCardExplore /> </Pressable> )} keyExtractor={(item) => item.name} // extract a key from the given data contentContainerStyle={{ padding: 0, marginBottom: 10 }} // apply style to each child /> </SafeArea> ); }; const styles = StyleSheet.create({ search: { padding: 0, marginBottom: 30, backgroundColor: "green" }, list: { flex: 1, padding: 0, backgroundColor: "#f1f1f1" }, searchText: { color: "#2e2e2e" }, searchbar: { borderRadius: 0 } });
require("../config/environment")(); const { generateKeyPair } = require("crypto"); const fs = require("fs"); const path = require("path"); function writeKey(fileName, key) { fs.writeFile( path.join(__dirname, `../config/keys/${fileName}`), key, { encoding: "utf8", flag: "w" }, err => { err ? console.log(`failed to write the ${fileName} keys`, err) : console.log(`wrote the ${fileName}`); } ); } generateKeyPair( "rsa", { modulusLength: 4096, publicKeyEncoding: { type: "spki", format: "pem" }, privateKeyEncoding: { type: "pkcs8", format: "pem" } }, (err, publicKey, privateKey) => { // Handle errors and use the generated key pair. if (err) { throw new Error("failed to generate keys", err); } writeKey("public_key", publicKey); writeKey("private_key", privateKey); } );
import { Contact } from './contact.js'; const romain = new Contact(); romain.hello();
/* Authorization: Check if user's role is the required roles or not (In this case, it must be admin role) */ const CustomError = require("../utils/custom-error"); const logger = require("../utils/logger")(__filename); module.exports = { isAdmin: (req, res, next) => { if (res.locals.roles.includes("admin")) { logger.audit(`User ${res.locals.id} is authorised as Admin`); next(); return; } throw new CustomError(403, "Error: Admin role is required for this action"); } };
(function() { var projectId = 0; var channels = [], nodes = [], nodeLookup = {}, transitions = []; var funnel = []; var popoverNode = null; var scales = {x:d3.scale.linear(), y:d3.scale.linear()}; var translation = {x:0, y:0, scale:1}; var zoom = d3.behavior.zoom() var settings = {}; window.landmark.action = { //------------------------------------------------------------------------------ // // Properties // //------------------------------------------------------------------------------ layout : { width:0, height:0 }, translation : function(value) { if(arguments.length == 0) return translation; translation = value; var transform = "translate(" + translation.x + "," + translation.y + ") scale(" + translation.scale + ")"; this.g.channels.attr("transform", transform); this.g.nodes.attr("transform", transform); this.g.transitions.attr("transform", transform); }, channels : function(value) { if(arguments.length == 0) return channels; channels = value; }, node : function(channel, resource, action, eos) { if(!nodeLookup[channel] || !nodeLookup[channel][resource] || !nodeLookup[channel][resource][action]) return null; return nodeLookup[channel][resource][action][eos]; }, nodes : function(value) { if(arguments.length == 0) return nodes; nodes = value; nodeLookup = {}; // Create lookup. for(var i=0; i<nodes.length; i++) { var node = nodes[i]; node.id = [node.channel, node.resource, node.action, node.eos].join("---"); if(!nodeLookup[node.channel]) nodeLookup[node.channel] = {}; if(!nodeLookup[node.channel][node.resource]) nodeLookup[node.channel][node.resource] = {}; if(!nodeLookup[node.channel][node.resource][node.action]) nodeLookup[node.channel][node.resource][node.action] = {}; nodeLookup[node.channel][node.resource][node.action][node.eos] = node } }, transitions : function(value) { if(arguments.length == 0) return transitions; transitions = value; for(var i=0; i<transitions.length; i++) { var transition = transitions[i]; transition.source = this.node(transition.prev_channel, transition.prev_resource, transition.prev_action, false); transition.target = this.node(transition.channel, transition.resource, transition.action, transition.eos); } }, //------------------------------------------------------------------------------ // // Public Methods // //------------------------------------------------------------------------------ //-------------------------------------- // Initialization //-------------------------------------- initialize : function(projectId) { var $this = this; this.projectId = projectId; $(document).on("click", function() { $this.document_onClick() }); $(document).on("click", ".show-next-actions", function() { $this.showNextActions_onClick(popoverNode) }); $(document).on("click", "#date-filter-apply-btn", function() { $this.dateFilterApplyBtn_onClick() }); $(document).on("click", ".funnel-step", function() { $this.funnelStep_onClick() }); $(document).on("click", "#clear-funnel-btn", function() { $this.clearFunnelBtn_onClick() }); this.chart = $("#chart")[0]; this.svg = {}; this.svg = d3.select(this.chart).append("svg").attr("class", "focus"); this.g = { root: this.svg.append("g") } zoom .scaleExtent([0.1, 1]) .on("zoom", function() { $this.translation({ x: d3.event.translate[0], y: d3.event.translate[1], scale: d3.event.scale }); }); this.g.root.append("rect") .call(zoom) .on("mousedown", function() { d3.event.preventDefault() }) this.g.channels = this.g.root.append("g"); this.g.transitions = this.g.root.append("g"); this.g.nodes = this.g.root.append("g"); this.update(); this.load(); var onresize = window.onresize; window.onresize = function() { landmark.action.onresize(); if(typeof(onresize) == "function") onresize(); } }, //-------------------------------------- // Data //-------------------------------------- load : function() { var $this = this; var startDate = $("#start-date").val() != "" ? moment($("#start-date").val()) : null; var endDate = $("#end-date").val() != "" ? moment($("#end-date").val()) : null; // Update filter description. if(startDate && endDate) { if(startDate.isSame(endDate)) { $("#filter-desc").text("On " + startDate.format("ll")); } else { $("#filter-desc").text("Between " + startDate.format("ll") + " and " + endDate.format("ll")); } } else if(startDate) { $("#filter-desc").text("Since " + startDate.format("ll")); } else if(endDate) { $("#filter-desc").text("On or before " + endDate.format("ll")); } else { $("#filter-desc").text(); } // Create query parameters. var data = {"funnel":funnel}; if(startDate) data.start_date = startDate.toISOString(); if(endDate) data.end_date = endDate.toISOString(); var xhr = d3.xhr("/api/v1/projects/" + this.projectId + "/actions/query"); xhr.header("Content-Type", "application/json"); xhr.post(JSON.stringify(data), function(error, req) { if(error) return console.warn(error); json = JSON.parse(req.response); $this.layout.width = json.width; $this.layout.height = json.height; $this.channels(json.channels); $this.nodes(json.nodes); $this.transitions(json.transitions); var w = $(this.chart).width(); var h = window.innerHeight - $(this.chart).offset().top - 40; var scale = Math.min(1, w/$this.layout.width); zoom.scale(scale); zoom.translate([(w/2)-($this.layout.width/2)*scale, 10*scale]) zoom.event($this.g.root.select("rect")) $this.update(); } ); }, //-------------------------------------- // Refresh //-------------------------------------- update : function() { var $this = this; this.updateBreadcrumb(); var w = $(this.chart).width(); var h = window.innerHeight - $(this.chart).offset().top - 40; this.svg.attr("height", h); this.g.root.select("rect") .attr("fill-opacity", 0) .attr("width", w) .attr("height", h) ; this.updateChannels(w, h); this.updateNodes(w, h); this.updateTransitions(w, h); }, updateBreadcrumb : function(w, h) { var $this = this; breadcrumb = $("#breadcrumb") breadcrumb.empty(); for(var i=0; i<funnel.length; i++) { var step = funnel[i]; var item = $('<li><a class="funnel-step" href="#"></a></li>'); if(i == funnel.length - 1) item.attr("class", "active"); item.find("a") .data("index", i) .text(step.resource); breadcrumb.append(item); } breadcrumb.append('<i id="clear-funnel-btn" class="pull-right fui-cross-inverted text-primary"></i>') if(funnel.length == 0) { breadcrumb.hide(); } else { breadcrumb.show(); } }, updateChannels : function(w, h) { var $this = this; this.g.channels.selectAll(".channel") .data(this.channels(), function(d) { return d.name; }) .call(function(selection) { var enter = selection.enter(), exit = selection.exit(); selection .transition() .attr("transform", function(d) { return "translate("+d.x+","+d.y+")"; }); enter.append("g") .attr("class", "channel") .attr("transform", function(d) { return "translate("+d.x+","+d.y+")"; }) .call(function() { this.append("rect"); this.append("text") .attr("class", "title") .attr("text-anchor", "middle") ; } ); selection.select("rect") .attr("width", function(d) { return d.width }) .attr("height", function(d) { return d.height }) ; selection.select("text.title") .attr("x", function(d) { return d.label_x - d.x }) .attr("y", function(d) { return d.label_y - d.y - 2 }) .text(function(d) { return d.name; }) ; exit.remove(); } ); }, updateNodes : function(w, h) { var $this = this; this.g.nodes.selectAll(".node") .data(this.nodes(), function(d) { return d.id; }) .call(function(selection) { var enter = selection.enter(), exit = selection.exit(); selection .transition() .attr("transform", function(d) { return "translate("+d.x+","+d.y+")"; }); enter.append("g") .attr("class", "node") .on("click", function(d) { $this.node_onClick(d) }) .attr("transform", function(d) { return "translate("+d.x+","+d.y+")"; }) .call(function() { this.append("rect"); this.append("text") .attr("class", "title") .attr("text-anchor", "middle") ; } ); selection.select("rect") .attr("visibility", function(d) { return d.eos == "true" ? "hidden" : "visible" }) .attr("width", function(d) { return d.width }) .attr("height", function(d) { return d.height }) ; selection.select("text.title") .attr("visibility", function(d) { return d.eos == "true" ? "hidden" : "visible" }) .attr("x", function(d) { return d.label_x - d.x }) .attr("y", function(d) { return d.label_y - d.y - 2 }) .text(function(d) { return d.resource; }) ; exit.remove(); } ); }, updateTransitions : function(w, h) { var $this = this; var interpolator = {}; interpolator.opacity = d3.interpolateNumber(0.3, 1); this.g.transitions.selectAll(".transition") .data(this.transitions(), function(d) { return d.source.id + "---" + d.target.id; }) .call(function(selection) { var enter = selection.enter(), exit = selection.exit(); enter.append("g") .attr("class", "transition") .call(function() { this.append("title"); this.append("path"); this.append("polygon").attr("class", "arrowhead"); }) ; selection .call(function() { this.select("path") .transition() .attr("d", function(d) { return d.d }) .attr("stroke", function(d) { return d.eos == "true" ? "#e74c3c" : "#333" }) .attr("stroke-opacity", function(d) { return interpolator.opacity(d.stroke_width) }) .attr("stroke-width", function(d) { return Math.max(1, d.stroke_width) }) ; this.select("polygon.arrowhead") .transition() .attr("stroke", function(d) { return d.eos == "true" ? "#e74c3c" : "#333" }) .attr("stroke-opacity", function(d) { return interpolator.opacity(d.stroke_width) }) .attr("fill", function(d) { return d.eos == "true" ? "#e74c3c" : "#333" }) .attr("fill-opacity", function(d) { return interpolator.opacity(d.stroke_width) }) .attr("points", function(d) { return d.arrowhead_points }) ; this.append("text") .attr("fill", function(d) { return d.eos == "true" ? "#e74c3c" : "#333" }) .attr("fill-opacity", function(d) { return interpolator.opacity(d.stroke_width) }) .attr("text-anchor", "middle") ; }) ; selection.select("text") .transition() .attr("x", function(d) { return d.label_x }) .attr("y", function(d) { return d.label_y }) .text(function(d) { return Humanize.intcomma(d.count); }) ; exit.remove(); } ); }, //-------------------------------------- // Utility //-------------------------------------- removePopover : function() { popoverNode = null; $(".popover").remove() $(".tooltip").remove() }, //-------------------------------------- // Events //-------------------------------------- onresize : function() { this.update(); }, document_onClick : function() { if($(event.target).attr("rel") == "popover") return; if($(event.target).parents(".popover").length > 0) return; this.removePopover(); }, node_onClick : function(d) { this.removePopover(); $(this).popover({ html: true, container:"body", trigger:"manual", placement: "left", template: '<div class="popover node-popover"><div class="popover-content"></div></div>', content: '<div class="dropdown open">' + ' <ul class="dropdown-menu dropdown-inverse">' + ' <li>' + ' <a class="show-next-actions" href="#">Show Next Actions</a>' + ' </li>' + ' </ul>' + '</div>' }); $(this).popover("show"); popoverNode = d; var popover = $(this).data("popover").$tip popover.css("left", d3.event.x + 10); popover.css("top", d3.event.y + 10); d3.event.stopPropagation(); }, showNextActions_onClick : function(d) { this.removePopover(); funnel.push({ channel:d.channel, resource:d.resource, action:d.action, eos:d.eos, }); this.load() }, funnelStep_onClick : function() { var index = $(event.toElement).data("index"); funnel = funnel.slice(0, index+1); this.load(); }, clearFunnelBtn_onClick : function() { funnel = []; this.load(); }, dateFilterApplyBtn_onClick : function() { this.load(); }, } })()
import React from 'react' import { StyleSheet } from 'quantum' import { PlusCircleIcon, QuestionIcon, DataIcon } from 'bypass/ui/icons' const styles = StyleSheet.create({ self: { transition: 'all 0.3s', background: '#546e7a', borderTop: '1px solid #ffffff', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', }, }) const icons = { future: ( <QuestionIcon width={17} fill='#f5f5f5' /> ), base_update: ( <DataIcon height={17} fill='#f5f5f5' /> ), soft_update: ( <PlusCircleIcon width={17} fill='#f5f5f5' /> ), } const type = { width: '40px', dataKey: 'type', flexShrink: 0, cellRenderer: cellData => ( <div className={styles()}> {icons[cellData]} </div> ), } export default type
import React from 'react'; import {compose, withHandlers, withState} from 'recompose'; import DateTimePicker from 'react-datepicker'; import "react-datepicker/dist/react-datepicker.css"; export const DatePicker = compose( withState('date', 'setDate', new Date()), withHandlers({ handleChange: ({setDate}) => value => setDate(value), }), )(({date, name, handleChange}) => ( <DateTimePicker selected={date} className={'form-control'} onChange={handleChange} showTimeSelect timeFormat="HH:mm" minDate={new Date()} name={name} showDisabledMonthNavigation dateFormat="dd/MM/YYYY HH:mm"/> ));
const { web3 } = require('../misc/ethereum'); const blocks = () => { const getBlock = async (blockNumber) => { return new Promise((resolve, reject) => { web3.eth.getBlock(blockNumber, (err, result) => { if(err) { reject(err); } else { resolve(result); } }); }); }; const getTransaction = async (txHash) => { return new Promise((resolve, reject) => { web3.eth.getTransaction(txHash, (err, result) => { if(err) { reject(err); } else { resolve(result); } }); }); }; const getTransactionReceipt = async (txHash) => { return new Promise((resolve, reject) => { web3.eth.getTransactionReceipt(txHash, (err, result) => { if(err) { reject(err); } else { resolve(result); } }); }); }; return { getBlock, getTransaction, getTransactionReceipt }; }; module.exports = blocks;
/** * Created by ThangLD5 on 12/27/2014. */ app.controller('KPIController', ['$scope', '$modal', 'ReportFactory', function ($scope, $modal, ReportFactory) { $scope.$watch(function () { return { UsedThemes: $scope.UsedThemes, UsedPerspectives: $scope.UsedPerspectives, UsedColors: $scope.UsedColors, UsedObjectives: $scope.UsedObjectives } }, function (value) { /// // Region KPI fileter /// $scope.KPIs = ReportFactory.GetKPIs(); var KPIsAfterFilter = []; for (var iKPI in $scope.KPIs) { var KPI = $scope.KPIs[iKPI]; var SelectedTheme = true; for (var iTheme in $scope.UsedThemes) { var Theme = $scope.UsedThemes[iTheme]; if (Theme) { SelectedTheme = false; if (iTheme == KPI.Objective.StrategicTheme1 || iTheme == KPI.Objective.StrategicTheme2) { SelectedTheme = true; break; } } } var SelectedPerspective = true; for (var iPerspective in $scope.UsedPerspectives) { var Perspective = $scope.UsedPerspectives[iPerspective]; if (Perspective) { SelectedPerspective = false; if (iPerspective == KPI.Objective.ObjectivePerspective) { SelectedPerspective = true; break; } } } var SelectedColor = true; for (var iColor in $scope.UsedColors) { var Color = $scope.UsedColors[iColor]; if (Color) { SelectedColor = false; if (Color == KPI.KPISummaryColorInPeriod) { SelectedColor = true; break; } } } var SelectedObjective = true; for (var iObjective in $scope.UsedObjectives) { var Objective = $scope.UsedObjectives[iObjective]; if (Objective) { SelectedObjective = false; if (iObjective == KPI.Objective) { SelectedObjective = true; break; } } } if (SelectedTheme && SelectedPerspective && SelectedColor && SelectedObjective) KPIsAfterFilter.push(KPI); } if (KPIsAfterFilter.length > 0) $scope.KPIs = KPIsAfterFilter; else $scope.KPIs = ReportFactory.GetKPIs(); }, true); //modal cho phan hien thi chart $scope.openKPIChart = function (value) { var modalInstance = $modal.open({ templateUrl: 'ModalKPIChart.html', controller: 'ModalInstanceCtrl', size: 'xs', resolve: { items: function () { return value; } } }); }; //modal cho phan xem chi tiet chi so $scope.openKPIIssue = function (value) { var modalInstance = $modal.open({ templateUrl: 'ModalKPIIssue.html', controller: 'ModalInstanceCtrl', size: '', resolve: { items: function () { return value; } } }); }; $scope.setPage = function (n) { $scope.currentPage = n; }; }]);
import { FIELD_GROUP, FIELD_ORDER, FIELD_UNICODE, FIELD_TOKENS, INDEX_GROUP_AND_ORDER, STORE_EMOJI, STORE_KEYVALUE, STORE_FAVORITES, INDEX_TOKENS, INDEX_COUNT, INDEX_SKIN_UNICODE, FIELD_SKIN_UNICODE } from './constants' function initialMigration (db) { function createObjectStore (name, keyPath, indexes) { const store = keyPath ? db.createObjectStore(name, { keyPath }) : db.createObjectStore(name) if (indexes) { for (const [indexName, [keyPath, multiEntry]] of Object.entries(indexes)) { store.createIndex(indexName, keyPath, { multiEntry }) } } return store } createObjectStore(STORE_KEYVALUE) createObjectStore(STORE_EMOJI, /* keyPath */ FIELD_UNICODE, { [INDEX_TOKENS]: [FIELD_TOKENS, /* multiEntry */ true], [INDEX_GROUP_AND_ORDER]: [[FIELD_GROUP, FIELD_ORDER]], [INDEX_SKIN_UNICODE]: [FIELD_SKIN_UNICODE, /* multiEntry */ true] }) createObjectStore(STORE_FAVORITES, undefined, { [INDEX_COUNT]: [''] }) } export { initialMigration }
import io from 'socket.io-client'; import React, { Component } from 'react'; class App extends Component { constructor (props) { super(props); this.state = { messages: ['hello', 'another msg'] } this.eventReceived = this.eventReceived.bind(this); } componentDidMount () { const socket = io(); socket.on('event', this.eventReceived); } eventReceived (event) { this.setState({ ...this.state, messages: [...this.state.messages, event.message] }); } render() { const msgs = this.state.messages.map(message => (<div>{message}</div>)); return ( <div> {msgs} </div> ); } } export default App;
function incluirProcesso() { var data = { "Identificador": $("#txt-identificador").val(), "TempoExecucao": $("#txt-tempo-execucao").val(), "CustoPorHora": $("#txt-custo-por-hora").val(), }; $.ajax({ type: "POST", url: "/api/GerenciadorFila/", data: JSON.stringify(data), contentType: "application/json", success: function (data) { carregarProcessos(); $("#frm-inclusao-processo").trigger("reset"); }, error: function (data) { alert(data.responseText); } }); } function carregarProcessos() { $.ajax({ type: "GET", url: "/api/GerenciadorFila/", contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { preencherTabela($("#tbl-menor-tempo tbody"), data.menor_tempo_espera); preencherTabela($("#tbl-menor-custo tbody"), data.menor_custo_espera); }, error: function (data) { alert(data.responseText); } }); } function preencherTabela(tabela, dados) { tabela.html(""); $.each(dados, function (i, item) { var row = "<tr>" + "<td>" + (i + 1) + ". " + item + "</td>" + "</tr>"; tabela.append(row); }); } $(document).ready(() => { carregarProcessos(); });
/* A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. */ 'use strict' // rangeByDigits :: Integer -> [Integer] const rangeByDigits = x => { const start = Math.pow(10, x - 1); const end = Math.pow(10, x) - 1; return range(start, end); }; //function itrRange(start, end) { // const array = []; // for (let i = start; i <= end; i++) { // array.push(i); // } // return array; //} // range :: (Integer, Integer) -> [Integer] const range = (start, end) => { if (start > end) return []; return [] .concat(start) .concat(range(start + 1, end)); }; // isPalindrome :: Integer -> Bool const isPalindrome = num => { const str = num.toString(); const strReversed = str.split('').reverse().join(''); if (str === strReversed) return true; return false; }; //function products(arr_x, arr_y) { // const array = []; // for (let i = 0; i < arr_x.length; i++) { // for (let j = 0; j < arr_y.length; j++) { // array.push(arr_x[i] * arr_y[j]); // } // arr_y.shift(); // } // return array; //} //function palProducts(arr_x, arr_y) { // const array = []; // for (let i = 0; i < arr_x.length; i++) { // for (let j = 0; j < arr_y.length; j++) { // const tmp = arr_x[i] * arr_y[j]; // if (isPalindrome(tmp)) // array.push(tmp); // } // arr_y.shift(); // } // return array; //} //function products2(arr_x, arr_y) { // return arr_x.reduce((acc, val) => { // const tmpArr = arr_y.map(y => val * y) // .filter(isPalindrome) // .filter(x => !acc.includes(x)); // arr_y.shift(); // return acc.concat(tmpArr); // }, []); //} // productsObj :: Integer -> [{obj}] const productsObj = (arr_x, arr_y = arr_x.concat([])) => { const array = arr_x.map(x => { return arr_y.map(y => ({ x: x, y: y, product: x * y })); }) .reduce((acc, part) => acc.concat(part), []) .filter(val => isPalindrome(val.product)); return array; }; // remDupes :: [Integer] -> [Integer] const remDupes = array => { return array.reduce((acc, x) => { if (!acc.includes(x.product)) return acc.concat(x.product); return acc; }, []); }; const composeTwo = (f, g) => (...args) => f(g(...args)); //const n = composeTwo(remDupes, productsObj)(arr_x, arr_y); //console.log(n.length); const palArr = composeTwo(productsObj, rangeByDigits)(2); const digPalLn = `The length of the palindromes array is ${palArr.length}`; console.log(digPalLn); const findMax = palArr.reduce((acc, x) => { if (x.product > acc.product) return x; return acc; }); const highestPal = `The highest Palindrome number is ${findMax.x} x ${findMax.y} = ${findMax.product}`; console.log(highestPal);
// Read configuration var config = JSON.parse(require("fs").readFileSync("config.json")); // Change names to threadIDs config.forward.forEach(function(f) { if(f instanceof Array) { for(var i = 0; i < 2; i++) if(!f[i].match(/^[0-9]{15}$/)) f[i] = config.users[f[i]]; } else { if(!f.from.match(/^[0-9]{15}$/)) f.from = config.users[f.from]; if(!f.to.match(/^[0-9]{15}$/)) f.to = config.users[f.to]; } }); // Make a list of threadIDs to listen var list = []; config.forward.forEach(function(f) { if(f instanceof Array) { for(var i = 0; i < 2; i++) if(list.indexOf(f[i]) < 0) list.push(f[i]); } else if(list.indexOf(f.from) < 0) { list.push(f.from); } }); console.log("Forward configuration:"); console.log(config.forward); // Login var login = require("facebook-chat-api"); login({ email: config.account.email, password: config.account.password }, function callback(err, api) { if(err) return console.error(err); api.listen(function callback(err, data) { if(err) return console.error(err); if(data.type == "message" && list.indexOf(data.threadID) > -1) { console.log(data); forward(api, data); } }); }); function forward(api, data) { var send = function(target) { api.sendMessage(data.body, target); console.log("(" + data.threadID + ") => (" + target + ") : " + data.body); } config.forward.forEach(function(f) { if(f instanceof Array) { if(f[0] == data.threadID) send(f[1]); else if(f[1] == data.threadID) send(f[0]); } else if(f.from == data.threadID) { send(f.to); } }); }
const mongoose = require("mongoose"); const LevelSchema = new mongoose.Schema({ name : { type : String, required : [true, 'Level is required'], unique : [true, 'Level already exist'] } }); module.exports = mongoose.model("Level",LevelSchema);
/*@ngInject*/ export default function cellMapController($log, $interval, Data, cellMapService) { const ctrl = this; ctrl.$onInit = () => { ctrl.data = cellMapService.getServiceData(); ctrl.state = { autoplay: false, autoGenerationIntervalMS: 1000, autoPlayInterval: null, stepCount: 0, mapSizeX: 100, mapSizeY: 100, repeatRangeX: range(100), repeatRangeY: range(100) } }; // Control functions /** * Erase current map data. */ const clear = () => ctrl.data.actualCellMap = {}; /** * * @param to */ const range = (to) => _.range(-1 * Math.ceil(to / 2), Math.ceil(to / 2)); /** * Activate/inactivate the cell. * @param x * @param y */ const toggle = (x, y) => { if (isCellActive(x, y)) { ctrl.data.actualCellMap = _.omit(ctrl.data.actualCellMap, x + '.' + y); if (_.isEmpty(ctrl.data.actualCellMap[x])) ctrl.data.actualCellMap = _.omit(ctrl.data.actualCellMap, x); } else { if (!ctrl.data.actualCellMap[x]) ctrl.data.actualCellMap[x] = {}; ctrl.data.actualCellMap[x][y] = 1; } }; /** * If data is represented in the cell map then it is alive. * @param x * @param y * @returns {boolean} */ const isCellActive = (x, y) => { return _.has(ctrl.data.actualCellMap, x + '.' + y); }; /** * Calls the server for the next generation and populates the new data. */ const getNextGeneration = () => { if (_.has(ctrl, 'data.actualCellMap') && !_.isEmpty(ctrl.data.actualCellMap)) { Data .nextGeneration({cellMap: ctrl.data.actualCellMap}) .$promise .then(data => { if (data.newGeneration) ctrl.data.actualCellMap = data.newGeneration; }); } }; /** * Flips the autoplay flag and starts/stops the loop. */ const toggleAutoPlay = () => { ctrl.state.autoplay = !ctrl.state.autoplay; if (ctrl.state.autoplay) startAutoPlayInterval(); else stopAutoPlayInterval(); }; /** * Resize the cell map size. */ const setCellMapSize = () => { ctrl.state.repeatRangeX = range(ctrl.state.mapSizeX); ctrl.state.repeatRangeY = range(ctrl.state.mapSizeY); }; // Private functions const startAutoPlayInterval = () => { ctrl.state.autoPlayInterval = $interval(() => { getNextGeneration(); }, ctrl.state.autoGenerationIntervalMS); }; const stopAutoPlayInterval = () => { $interval.cancel(ctrl.state.autoPlayInterval); }; ctrl.controlFunctions = { clear, toggle, range, isCellActive, getNextGeneration, toggleAutoPlay, setCellMapSize }; }
import React from 'react' import PropTypes from 'prop-types' import { Controlled as CodeMirror } from 'react-codemirror2' import 'codemirror/addon/hint/show-hint.css' import 'codemirror/addon/hint/show-hint.js' import 'codemirror/addon/hint/anyword-hint.js' import 'codemirror/addon/hint/javascript-hint' import 'codemirror/addon/hint/sql-hint' import 'codemirror/theme/dracula.css' import './code-editor.scss' function CodeEditor({ lang, onChange, value, autocomplete, dark }) { return ( <CodeMirror options={{ mode: lang, lineNumbers: true, theme: (dark) ? 'dracula' : 'default', tabSize: 2, }} value={value} onChange={() => {}} onKeyUp={((editor, event) => { if (event.keyCode > 64 && event.keyCode < 91) { editor.showHint({ completeSingle: false }) } })} onBeforeChange={(editor, data, value) => { if (data.origin) { onChange(value) } }} /> ) } CodeEditor.propTypes = { lang: PropTypes.oneOf(['text/javascript', 'application/json', 'text/x-sql', 'text/x-markdown']), autocomplete: PropTypes.bool, onChange: PropTypes.func, value: PropTypes.string, dark: PropTypes.bool, } CodeEditor.defaultProps = { lang: 'text/javascript', onChange: () => {}, autocomplete: false, value: '', dark: false, } export default CodeEditor
import React from 'react'; import LogoImage from "../../assets/voila_logo2.png"; import UserImage from "../../assets/user.png"; import { FiLogOut } from "react-icons/fi"; import { useHistory } from "react-router"; import { Header, Options, Title, User, UserSpan } from "./styles"; import { useDispatch, useSelector } from 'react-redux'; export default function HeaderRestaurant() { const dispatch = useDispatch(); const history = useHistory(); const user = useSelector(state => state.user); async function logout() { await dispatch({ type: 'LOGOUT' }); history.push('/restaurant/login'); } return ( <Header> <img alt="Imagem de logo" src={LogoImage}/> <Title>VOILÀ</Title> <User> <img alt="Imagem de logo" src={UserImage}/> <UserSpan>{user.username}</UserSpan> <Options> <FiLogOut size={32} color={'#fff'} onClick={() => logout()}/> </Options> </User> </Header> ); }
const express = require('express'); const postDb = require('../data/helpers/postDb'); const router = express.Router() // GET /api/posts/:userId router.get('/:userId', (req, res) => { const { userId } = req.params postDb .get(userId) .then(posts => { res.send(posts); }) .catch(err => { res.status(500) .send({ message: 'unable retrieve posts.' }); }); }); // CREATE /api/posts/create router.post('/create', (req, res) => { const post = req.body; if (post.text) { postDb .insert(post) .then(idInfo => { postDb.get(idInfo.id) .then(post => { res .status(201) .json(idInfo); }); }) .catch(err => { res .status(500) .json({ message: 'failed to insert post in db' }); }); } else { res .status(400) .json({ errorMessage: 'please provide text and postedBy for post' }); } }); module.exports = router;
/* globals describe it expect */ import { colorMiddleware, events, frame, motionPath, pause, plainShapeObject, play, shape, timeline, unitMiddleware } from '../src' describe('colorMiddleware', () => { it('should be exported', () => { expect(typeof colorMiddleware).toBe('object') expect(colorMiddleware).toHaveProperty('name') expect(colorMiddleware).toHaveProperty('input') expect(colorMiddleware).toHaveProperty('output') }) }) describe('events', () => { it('should be exported', () => { expect(typeof events).toBe('function') }) }) describe('frame', () => { it('should be exported', () => { expect(typeof frame).toBe('function') }) }) describe('motionPath', () => { it('should be exported', () => { expect(typeof motionPath).toBe('function') }) }) describe('pause', () => { it('should be exported', () => { expect(typeof pause).toBe('function') }) }) describe('plainShapeObject', () => { it('should be exported', () => { expect(typeof plainShapeObject).toBe('function') }) }) describe('play', () => { it('should be exported', () => { expect(typeof play).toBe('function') }) }) describe('shape', () => { it('should be exported', () => { expect(typeof shape).toBe('function') }) }) describe('timeline', () => { it('should be exported', () => { expect(typeof timeline).toBe('function') }) }) describe('unitMiddleware', () => { it('should be exported', () => { expect(typeof unitMiddleware).toBe('object') expect(unitMiddleware).toHaveProperty('name') expect(unitMiddleware).toHaveProperty('input') expect(unitMiddleware).toHaveProperty('output') }) })
(function (angular) { 'use strict'; function profile() { var $ctrl = this; } angular.module('profile', ['indexProfile', 'cretate', 'domicileService', 'chat', 'chatService']) .component('profile', { templateUrl: 'app/Profile/Templates/profile.html', $routeConfig: [ { path: '/lista', name: 'IndexProfile', component: 'indexProfile', useAsDefault: true }, { path: '/nuevo', name: 'Cretate', component: 'cretate' } ], $canActivate: function ($location) { var user = localStorage.getItem('user'); console.log("user in json" ,JSON.parse(user)); if (user == "null" || user == null) { $location.path('/'); } else { return true; } }, controller: profile }) })(window.angular);
import * as React from 'react'; import { connect } from 'react-redux'; import { getsearchSingleArtist } from '../../redux/actions/artist-actions'; class UIPlaylists extends React.Component { constructor() { super(...arguments); this.searchArtist = (query) => { this.props.getsearchSingleArtist(query); }; } render() { return (React.createElement(React.Fragment, null, React.createElement("div", { className: "collapse in", id: "playlists" }, React.createElement("a", { href: "#", className: "navigation__list__item", onClick: () => this.searchArtist('Beastie Boys') }, React.createElement("i", { className: "ion-ios-musical-notes" }), React.createElement("span", null, "Beastie Boys")), React.createElement("a", { href: "#", className: "navigation__list__item", onClick: () => this.searchArtist('Giorgio Moroder') }, React.createElement("i", { className: "ion-ios-musical-notes" }), React.createElement("span", null, "Giorgio Moroder")), React.createElement("a", { href: "#", className: "navigation__list__item", onClick: () => this.searchArtist('The Clash') }, React.createElement("i", { className: "ion-ios-musical-notes" }), React.createElement("span", null, "The Clash")), React.createElement("a", { href: "#", className: "navigation__list__item", onClick: () => this.searchArtist('Frankie Goes To Hollywood') }, React.createElement("i", { className: "ion-ios-musical-notes" }), React.createElement("span", null, "Frankie Goes To Hollywood")), React.createElement("a", { href: "#", className: "navigation__list__item", onClick: () => this.searchArtist('Joy Division') }, React.createElement("i", { className: "ion-ios-musical-notes" }), React.createElement("span", null, "Joy Division")), React.createElement("a", { href: "#", className: "navigation__list__item", onClick: () => this.searchArtist('Kaiser Chiefs') }, React.createElement("i", { className: "ion-ios-musical-notes" }), React.createElement("span", null, "Kaiser Chiefs")), React.createElement("a", { href: "#", className: "navigation__list__item", onClick: () => this.searchArtist('Herman Brood') }, React.createElement("i", { className: "ion-ios-musical-notes" }), React.createElement("span", null, "Herman Brood")), React.createElement("a", { href: "#", className: "navigation__list__item", onClick: () => this.searchArtist('Heaven 17') }, React.createElement("i", { className: "ion-ios-musical-notes" }), React.createElement("span", null, "Heaven 17")), React.createElement("a", { href: "#", className: "navigation__list__item", onClick: () => this.searchArtist('The English Beat') }, React.createElement("i", { className: "ion-ios-musical-notes" }), React.createElement("span", null, "The English Beat")), React.createElement("a", { href: "#", className: "navigation__list__item", onClick: () => this.searchArtist('The Specials') }, React.createElement("i", { className: "ion-ios-musical-notes" }), React.createElement("span", null, "The Specials")), React.createElement("a", { href: "#", className: "navigation__list__item", onClick: () => this.searchArtist('Sex Pistols') }, React.createElement("i", { className: "ion-ios-musical-notes" }), React.createElement("span", null, "Sex Pistols")), React.createElement("a", { href: "#", className: "navigation__list__item", onClick: () => this.searchArtist('Yazoo') }, React.createElement("i", { className: "ion-ios-musical-notes" }), React.createElement("span", null, "Yazoo"))))); } } const mapStateToProps = (state) => { return {}; }; const mapDispatchToProps = (dispatch) => { return { getsearchSingleArtist: (query) => dispatch(getsearchSingleArtist(query)) }; }; export default connect(mapStateToProps, mapDispatchToProps)(UIPlaylists);
import React from "react"; import Navbar from "react-bootstrap/Navbar"; import Nav from "react-bootstrap/Nav"; import Form from "react-bootstrap/Form"; import Col from "react-bootstrap/Col"; import { useDispatch } from "react-redux"; import { withRouter } from "react-router-dom"; import Button from "react-bootstrap/Button"; import logo from "../../assets/logo/logo.png"; import Input from "../input/Input"; import "./Header.scss"; import { asyncGet } from "../../store/actions/action"; const Header = (props) => { const dispatch = useDispatch(); const searchHandler = (event) => { event.preventDefault(); if (event.target[0].value.length > 2) { dispatch(asyncGet(event.target[0].value, 1)); } }; const goToPage = (page) => { props.history.push({ pathname: "/" + page }); }; return ( <Navbar bg="primary" variant="dark" expand="lg" className="rounded-bottom mb-2" > <Navbar.Brand onClick={() => goToPage("")} className="mr-0 pb-0 pt-0 d-none d-sm-block brandLogo" > <img src={logo} className="d-inline-block w-75" alt="movie db logo" /> </Navbar.Brand> <Navbar.Toggle aria-controls="basic-navbar-nav" /> <Navbar.Collapse id="basic-navbar-nav"> <Nav className="mr-auto"> <Nav.Link onClick={() => goToPage("")} className="navItem"> Home </Nav.Link> <Nav.Link href="https://www.opensubtitles.org/gr/el" target="_blank" className="navItem" > Subtitles </Nav.Link> <Nav.Link onClick={() => goToPage("about-us")} className="navItem"> About us </Nav.Link> </Nav> <Form onSubmit={searchHandler} inline> <Form.Group as={Col} md="12" controlId="validationFormik103"> <Input mode={{ type: "search", }} type="text" placeholder="Star Wars" className="mr-sm-2" required /> <Button className="d-none d-lg-block" variant="outline-success" type="submit" > Search </Button> </Form.Group> </Form> </Navbar.Collapse> </Navbar> ); }; export default withRouter(Header);
import bcrypt from 'bcrypt'; import dbOperations from '../database/dbOperations.js'; const userService = { async signInUser({email,password}){ try{ const hash = await dbOperations.getHash(email); if(await bcrypt.compare(password, hash)){ const user = await dbOperations.getUser(email); const leagues = await dbOperations.getLeagues(user.id); const teams = await dbOperations.getTeams(user.id); return {...user, leagues:leagues, teams:teams}; } }catch (err){ console.log("error signing in"); throw err; } }, async registerUser({email,password, ...rest}){ try{ const saltRounds = 10; const hash = await bcrypt.hash(password, saltRounds); await dbOperations.createUser({hash:hash, email:email}, rest); return; }catch(err){ console.log("error registering"); throw err; } } } export default userService;
import './styles.css'; import menuElement from './menu.json'; import menuTemplate from './templates/template-items.hbs'; const refs = { body: document.querySelector('body'), switch: document.querySelector('#theme-switch-toggle'), menu: document.querySelector('ul.js-menu') } const Theme = { LIGHT: 'light-theme', DARK: 'dark-theme', }; refs.menu.insertAdjacentHTML('beforeend', menuTemplate (menuElement)); refs.switch.addEventListener('change', setClassList); // refs.switch.addEventListener('change', setLocalStorage); function setClassList(e) { const check = refs.switch.checked; if (check) { changeTheme(Theme.DARK, Theme.LIGHT); localStorage.setItem('theme', Theme.DARK); } else { changeTheme(Theme.LIGHT, Theme.DARK); localStorage.removeItem('theme'); localStorage.setItem('theme', Theme.LIGHT); } } function changeTheme(addTheme, removeTheme) { refs.body.classList.add(addTheme); refs.body.classList.remove(removeTheme); } const themeLocal = localStorage.getItem('theme'); if (themeLocal === Theme.DARK) { refs.body.classList.add(Theme.DARK); refs.switch.checked = true; }
let gulp = require('gulp'); let sass = require('gulp-sass'); let browserSync = require('browser-sync'); let useref = require('gulp-useref'); let cleanCSS = require('gulp-clean-css'); let sourcemaps = require('gulp-sourcemaps'); let imagemin = require('gulp-imagemin'); gulp.task('sass', function(){ return gulp.src('resources/assets/scss/frontend/app.scss') .pipe(sass()) .pipe(gulp.dest('public/assets/css/app.css')) .pipe(browserSync.reload({ stream: true })) }); gulp.task('minify-css', function(){ return gulp.src('public/assets/css/app.css') .pipe(sourcemaps.init()) .pipe(cleanCSS({ compatibility: 'ie8' })) .pipe(sourcemaps.write()) .pipe(gulp.dest('public/assets/css/app1.css')) }); gulp.task('optimimages', function(){ return gulp.src('resources/assets/images/*.+(png|jpg|gif|svg)') .pipe(imagemin({ interlaced: true })) .pipe(gulp.dest('public/assets/img/')) }); gulp.task('browserSync', function(){ browserSync({ server:{ baseDir: './' }, }) }); gulp.task('watch', ['browserSync', 'sass'], function(){ gulp.watch('resources/assets/scss/**/*.scss', ['sass']); gulp.watch('public/*.php', browserSync.reload); }); gulp.task('build', ['optimimages', 'sass', 'minify-css'], function(){ console.log('Building files'); });
import React, { Component } from 'react'; import styled from 'styled-components'; export default class Item extends Component { render() { const { productUrl, image, name, priceShow, } = this.props; console.log(image); return( <ItemContainer> <Img src={image} alt="no image"/> <SubContainer> <ValueContainer> <Title><Label>Name: </Label> {name}</Title> </ValueContainer> <ValueContainer> <Title><Label>Price: </Label>{priceShow}</Title> </ValueContainer> <ValueContainer> <Title><Label>Product URL: </Label><a href={productUrl} target="_blank">{productUrl}</a></Title> </ValueContainer> </SubContainer> </ItemContainer> ) } } const ItemContainer = styled.div` width: 100%; height: 150px; display: flex; flex-direction: row; margin-bottom: 0.5em; border-bottom: 1px solid black; ` const Img = styled.img` max-width: 100px; max-height: 100px; object-fit: cover ` const SubContainer = styled.div` width: 100%; display: flex; flex-direction: column; ` const Label = styled.label` font-size: 14px; font-weight: bold; color: #6485CC; ` const Title = styled.div` font-size: 14px; ` const ValueContainer = styled.div` display: flex; flex-direction: column; `
"use strict"; exports.VirtualRow = exports.VirtualRowProps = exports.viewFunction = void 0; var _inferno = require("inferno"); var _vdom = require("@devextreme/vdom"); var _utils = require("../utils"); var _row = require("./row"); var _virtual_cell = require("./virtual_cell"); var _excluded = ["cellsCount", "children", "className", "height", "isHeaderRow", "leftVirtualCellCount", "leftVirtualCellWidth", "rightVirtualCellCount", "rightVirtualCellWidth", "styles"]; function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } var viewFunction = function viewFunction(_ref) { var classes = _ref.classes, _ref$props = _ref.props, leftVirtualCellCount = _ref$props.leftVirtualCellCount, leftVirtualCellWidth = _ref$props.leftVirtualCellWidth, rightVirtualCellCount = _ref$props.rightVirtualCellCount, rightVirtualCellWidth = _ref$props.rightVirtualCellWidth, style = _ref.style, virtualCells = _ref.virtualCells; return (0, _inferno.createComponentVNode)(2, _row.Row, { "styles": style, "className": classes, "leftVirtualCellWidth": leftVirtualCellWidth, "rightVirtualCellWidth": rightVirtualCellWidth, "leftVirtualCellCount": leftVirtualCellCount, "rightVirtualCellCount": rightVirtualCellCount, children: virtualCells.map(function (_, index) { return (0, _inferno.createComponentVNode)(2, _virtual_cell.VirtualCell, null, index.toString()); }) }); }; exports.viewFunction = viewFunction; var VirtualRowProps = _extends({}, _row.RowProps, { leftVirtualCellWidth: 0, rightVirtualCellWidth: 0, cellsCount: 1 }); exports.VirtualRowProps = VirtualRowProps; var VirtualRow = /*#__PURE__*/function (_BaseInfernoComponent) { _inheritsLoose(VirtualRow, _BaseInfernoComponent); function VirtualRow(props) { var _this; _this = _BaseInfernoComponent.call(this, props) || this; _this.state = {}; return _this; } var _proto = VirtualRow.prototype; _proto.render = function render() { var props = this.props; return viewFunction({ props: _extends({}, props), style: this.style, classes: this.classes, virtualCells: this.virtualCells, restAttributes: this.restAttributes }); }; _createClass(VirtualRow, [{ key: "style", get: function get() { var height = this.props.height; var style = this.restAttributes.style; return (0, _utils.addHeightToStyle)(height, style); } }, { key: "classes", get: function get() { var className = this.props.className; return "dx-scheduler-virtual-row ".concat(className); } }, { key: "virtualCells", get: function get() { var cellsCount = this.props.cellsCount; return _toConsumableArray(Array(cellsCount)); } }, { key: "restAttributes", get: function get() { var _this$props = this.props, cellsCount = _this$props.cellsCount, children = _this$props.children, className = _this$props.className, height = _this$props.height, isHeaderRow = _this$props.isHeaderRow, leftVirtualCellCount = _this$props.leftVirtualCellCount, leftVirtualCellWidth = _this$props.leftVirtualCellWidth, rightVirtualCellCount = _this$props.rightVirtualCellCount, rightVirtualCellWidth = _this$props.rightVirtualCellWidth, styles = _this$props.styles, restProps = _objectWithoutProperties(_this$props, _excluded); return restProps; } }]); return VirtualRow; }(_vdom.BaseInfernoComponent); exports.VirtualRow = VirtualRow; VirtualRow.defaultProps = _extends({}, VirtualRowProps);
var photos = new Array(); window.onload = function() { for (var i = 0; i < 10; i++) { photos.push(new Object()); } populate(); console.log(photos); for (i=0; i<10; i++){ var image = document.createElement("img"); image.id = i; image.setAttribute('src', photos[i].source); image.style.cssText = 'height:200px; margin: 10px;' document.querySelector("#thumbnails").appendChild(image); } }; document.getElementById('myInput').onkeypress = function(e) { var event = e || window.event; var charCode = event.which || event.keyCode; if ( charCode == '13' ) { search(); return false; } } function search(){ for (var i = 0; i < 10; i++) { document.getElementById(i).border = 0; } var myText = document.querySelector('#myInput').value.trim(); var pattern = new RegExp(myText, 'ig'); for (var i=0; i<10; i++){ if (photos[i].caption.match(pattern) || photos[i].tags.match(pattern)){ photos[i].search("" + i); } } } function populate() { photos[0] = { source: "1.jpg", caption: "Me at a conference", tags: "me,conference,suit,brasa,logo", search: function (query) { document.getElementById(query).border = 3; } } photos[1] = { source: "2.jpg", caption: "Me and BRASA's Tech team", tags: "pose,funny,people,friend,cool", search: function (query) { document.getElementById(query).border = 3; } } photos[2] = { source: "3.jpg", caption: "USC's BRASA", tags: "usc,tommy,trojan,campus,flag", search: function (query) { document.getElementById(query).border = 3; } } photos[3] = { source: "4.jpg", caption: "Me and the homies", tags: "friends,bbq,house,fun,awesome", search: function (query) { document.getElementById(query).border = 3; } } photos[4] = { source: "5.jpg", caption: "Friends at a conference", tags: "conference,people,group,awesome,suit", search: function (query) { document.getElementById(query).border = 3; } } photos[5] = { source: "6.jpg", caption: "Me and friends at Yosemite", tags: "yosemite,hiking,fun,outdoors,trees", search: function (query) { document.getElementById(query).border = 3; } } photos[6] = { source: "7.jpg", caption: "BRASA Members", tags: "members,fun,party,house,friends", search: function (query) { document.getElementById(query).border = 3; } } photos[7] = { source: "8.jpg", caption: "Me and friends", tags: "cool,friends,brotherhood,nice,california", search: function (query) { document.getElementById(query).border = 3; } } photos[8] = { source: "9.jpg", caption: "BRASA Retreat", tags: "retreat,fun,house,bonding,learning", search: function (query) { document.getElementById(query).border = 3; } } photos[9] = { source: "10.jpg", caption: "Baby me", tags: "baby,me,cute,cool,awesome", search: function (query) { document.getElementById(query).border = 3; } } }
// pages/chat/hat.js const { getTime } = require('./utils/formatTime'); const socket = require('./utils/rtcSocket').callSocket; const log = require('./utils/log'); const { seatLog } = require('./utils/request'); const app = getApp(); let heartbeatTimer = null; let callTimer = null; Page({ data: { imUserSig: null, videoCall: false, small: false, sdkAppId: null, userId: null, userInfo: {}, servingNum: null, callRoomId: null, callUserSig: null, callPrivateMapKey: null, callStatus: null, // socket 连接 relogin: false, socketFreq: 0, // IM 转视频 groupId: '', ivrFinish: false, callTime: 0, smallView: false }, onLoad: function () { wx.showLoading({ mask: true }) this.setData({ sdkAppId: app.globalData.sdkAppId, userId: app.globalData.openId, userInfo: app.globalData.userInfo, servingNum: app.globalData.servingNum, imUserSig: app.globalData.imUserSig }, () => { this.openSocket() }) }, onReady: function() {}, onShow: function() {}, onHide: function() { this.onHandleExitRoomEvent() }, onUnload: function () { socket.close() clearInterval(heartbeatTimer) this.onHandleExitRoomEvent() }, openSocket() { console.log('socket create') const { socketFreq } = this.data if(socketFreq === 2) { // 连续两次重连 停止5秒 console.log('socket open timeout') log.error('socket open count:', socketFreq) setTimeout(() => { this.setData({ socketFreq: 0 }, () => { this.openSocket() }) }, 3000) return } this.setData({ socketFreq: socketFreq + 1 }) socket.createSocket() .then(res => { console.log('socket create success', res) this.initSocket() }) .catch(err => { seatLog(err, 'socket create fail') console.log('socket create fail', err) }) }, initSocket() { socket.on('open', header => { console.log('socket open: ', header) this.socketLogin() }) socket.on('error', error => { console.error('socket error: ', error) seatLog(error, 'socket error') this.openSocket() }) socket.on('message', event => { console.log('socket event: ', event) const data = JSON.parse(event.data) this.onHandleSocketMessage(data) }) }, heartbeat() { this.setData({ socketFreq: 0 // 登录成功清零 }) if(heartbeatTimer) clearInterval(heartbeatTimer) heartbeatTimer = setInterval(() => { this.sendHeartbeat('heartbeat') }, 2000) }, sendHeartbeat(type) { const { userId, sdkAppId } = this.data return socket.request(type, { data: { staff: { userId, sdkAppId }, command: 'heartbeat' } }).then(e => { if (e.errorCode !== '0') { console.error('heartbeat error', e) log.error('heartbeat error', err) } return e }).catch(err => { log.error('heartbeat error', err) this.openSocket() // 错误重连 }) }, socketLogin() { const { userId, sdkAppId } = this.data const data = { staff: { userId, sdkAppId }, sessionKey: '', command: this.data.relogin ? 'relogin' : 'login' } socket.request('login', { data }) .then(event => { this.setData({ relogin: true }) if (event.errorCode === '-9') { wx.showToast({ title: '初始化失败!', success: () => { wx.navigateBack() }, }) } else if(event.errorCode === '-10') { wx.showToast({ title: '账号重复登录', icon: 'none' }) } else { this.sendHeartbeat('firstHeartbeat').then(msg => { console.log('first heartbeat', msg) this.heartbeat() }) } }).catch(e => { console.error('socket login error: ', e) wx.showToast({ title: '初始化失败!', success: () => { // wx.navigateBack() }, }) }) }, onHandleSocketMessage(data) { data.event && console.log('收到事件:', data.event) // IM 分配坐席 if (data.event === '2') this.onHandleCustomerEvent(data) // 客服进房 else if (data.event === '4') this.onHandleEnterRoomEvent(data) // 收到挂断事件 else if (['5', '6', '1051', '1052', '1055'].includes(data.event)) this.onHandleExitRoomEvent(data) else if (['2000'].includes(data.event)) { this.setData({ ivrFinish: true }) } else if (['2001'].includes(data.event)) { this.setData({ ivrFinish: false }) } // 视频通话 else if (data.event === '7') this.onHandleCallEvent(data) // 音频通话 else if (data.event === '9') this.onHandleCallEvent(data) }, onHandleCustomerEvent(data) { // 转入人工将与admin 消息设为已读 seatLog(data); const { staff } = data // wx.showToast({ // title: '正在转入人工服务,请稍后', // icon: 'none' // }) this.setData({ ivrFinish: true, staff }) }, // 结束通话 onHandleExitRoomEvent(data) { if(this.data.callStatus === '' || this.data.callStatus === null) return; let message; if(this.data.videoCall) { console.log('通话时长', this.data.callTime) message = '视频通话结束 ' + getTime(this.data.callTime); if (this.data.callTime === 0) message = '视频通话已取消' } else { message = '语音通话结束 ' + getTime(this.data.callTime); if (this.data.callTime === 0) message = '语音通话已取消' } console.log('结束通话') this.setData({ callRoomId: null, callUserSig: null, callPrivateMapKey: null, callStatus: null, videoCall: false, audioCall: false, callTime: 0 }) this.selectComponent('#chat').createMessage({ detail: { type: 'custom', message: { type: 'mediaMessage', data: { type: this.data.videoCall ? 'video' : 'radio', actions: 'finish', text: message } } } }); seatLog(data) // 挂断上报 this.selectComponent('#call').endCall() clearInterval(callTimer) }, // 开始通话 onHandleCallEvent(data) { seatLog(data); const { callInInfo } = data; this.setData({ callRoomId: callInInfo.roomId, callUserSig: callInInfo.userSig, callPrivateMapKey: callInInfo.privateMapKey, callStatus: 'calling' }) }, // 通话初始化 onHandleStartCall(event) { if (this.selectComponent('#call').data.roomStatus === 'needExit') { wx.showToast({ title: '初始化中...' }) return } if(event.detail.video) { this.setData({ videoCall: true, callStatus: 'ready' }) } else { this.setData({ audioCall: true, callStatus: 'ready' }) } }, // 进房通知 onHandleEnterRoomEvent(data) { seatLog(data); // 进房通知上报 console.error('进房') wx.showToast({ title: '坐席进房', }) this.setData({ callStatus: 'answering' }) callTimer = setInterval(() => { const { callTime } = this.data this.setData({ callTime: callTime + 1 }) }, 1000) }, onHandleViews(event) { this.setData({ smallView: event.detail.smallView }) }, onHandleZoomOutView() { this.setData({ smallView: false }) }, onHandleIvrEvent(event) { // 会话结束,隐藏视频通话 if(event.detail) { this.setData({ ivrFinish: event.detail.ivrFinish }) } } })
var appRouter = function(app) { //var mymodel = require("./../models/sampleModel.js"); /* mymodel.maluko('vei') app.get("/", function(req, res) { res.send("Hello World"); }); */ /* app.get("/account", function(req, res) { var accountMock = { "username": "nraboy", "password": "1234", "twitter": "@nraboy" } if(!req.query.username) { return res.send({"status": "error", "message": "missing username"}); } else if(req.query.username != accountMock.username) { return res.send({"status": "error", "message": "wrong username"}); } else { return res.send(accountMock); } });*/ app.post("/login", function(req, res) { return res.send(req.body); if(!req.body.level || !req.body.context) { return res.send({"status": "error", "message": "missing a parameter"}); } else { switch (req.body.context.toLowerCase()) { case 'free': //apenas salvar o 'token' break; case 'sms': //tentar pegar os dados do cliente e enviar sms break; case 'bot': //definir com o thiago se vai passar o id social ou cpf break; case 'social': // break; case 'sky': //passar usuario ou senha ou cpf break; default: } return res.send(req.body); } }); app.get("/getcountries", function(req, res) { return res.send({"status": "ok", "result": "br"}); }); } module.exports = appRouter;
import React from "react"; import { Helmet } from "react-helmet"; import Navigation from "./elements/Navigation"; const NotFound = () => { return ( <div> <Navigation /> <Helmet> <meta name="robots" content="noindex" /> </Helmet> <main className="page landing-page"> <section className="clean-block clean-hero"> <div className="text"> <h1> error 404 page was not found please click appropriate option from above </h1> </div> </section> {/*<section className="clean-block about-us"> <div className="container"> <div className="block-heading"> <h2 className="text-info">About Us</h2> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc quam urna, dignissim nec auctor in, mattis vitae leo. </p> </div> <div className="row justify-content-center"> <div className="col-sm-6 col-lg-4"> <div className="card clean-card text-center"> <img className="card-img-top w-100 d-block" src="assets/img/avatars/avatar1.jpg" /> <div className="card-body info"> <h4 className="card-title">John Smith</h4> <p className="card-text"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. </p> <div className="icons"> <a href="#"> <i className="icon-social-facebook" /> </a> <a href="#"> <i className="icon-social-instagram" /> </a> <a href="#"> <i className="icon-social-twitter" /> </a> </div> </div> </div> </div> <div className="col-sm-6 col-lg-4"> <div className="card clean-card text-center"> <img className="card-img-top w-100 d-block" src="assets/img/avatars/avatar2.jpg" /> <div className="card-body info"> <h4 className="card-title">Robert Downturn</h4> <p className="card-text"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. </p> <div className="icons"> <a href="#"> <i className="icon-social-facebook" /> </a> <a href="#"> <i className="icon-social-instagram" /> </a> <a href="#"> <i className="icon-social-twitter" /> </a> </div> </div> </div> </div> </div> </div> </section>*/} </main> </div> ); }; export default NotFound;
fbFilters.filter('reviewCycle', ['Util', function(Util) { return function(input, reviewCycleId) { if (!Array.isArray(input)) { return []; } else if (!reviewCycleId || !Util.isInteger(reviewCycleId)) { return input; } else { return input.filter(function (item) { return item.cycleId == reviewCycleId; }); } }; }]); fbFilters.filter('reportDisplay', function() { return function(input, filterToggle) { if (!Array.isArray(input)) { return []; } else if (filterToggle && (typeof filterToggle === 'string' || filterToggle instanceof String) && (filterToggle.toLowerCase() === 'current' || filterToggle.toLowerCase() === 'active')){ // return current reports return input.filter(function(item) { return item.cycle && item.cycle.active; }); } else if (filterToggle && (typeof filterToggle === 'string' || filterToggle instanceof String) && (filterToggle.toLowerCase() === 'inactive')) { return input.filter(function(item) { return item.cycle && !item.cycle.active; }); } else { return input; // return 'all' } }; });
/******************************************************************************************************* sertal.ch file upload operations twitter-bootstrap and Live HTML template for the following features - Template event handling for the file upload import operations Date: 18-June-2013 Author: ********************************************************************************************************/ var currentTenant; var currTenGroups; var otherTenGroups; var report = { columns: "success", total: "", upload: "", removed: "", description: [], update: "" }; var succ; var fail; Meteor.Router.add({ '/addContent': function() { succ = 0; fail = 0; update = 0 report = { columns: "success", upload: succ, total: "", removed: fail, description: [], update: update }; //console.log(this.request) try { var path = this.request.files.upload.path; } catch (err) { this.response.end("Please select a file"); } var resp; var collectionName = "usres"; var csvtype = this.request.body.csvtype; currentTenant = this.request.body.currentTenant; if (this.request.files.upload.type != "text/csv" && this.request.files.upload.type != "application/octet-stream" && this.request.files.upload.type != "application/vnd.ms-excel") this.response.end("Please select only csv files"); var encoding = this.request.body.encoding; var separator = this.request.body.separator; resp = fileUpload(collectionName, path, currentTenant, csvtype, encoding, separator); this.response.write(EJSON.stringify(report)); } }); fileUpload = function(collectionName, path, currentTenant, csvtype, encoding, separator) { var Iconv = Meteor.require('iconv').Iconv; //console.log(encoding); var data; var columns; var fs = Npm.require("fs"); var realColumns = []; var collectionColumns = []; var response; switch (encoding) { case 'UTF-8': data = fs.readFileSync(path, 'utf8'); data = data.split("\n"); if (data[0].indexOf("\r") != -1) { report['total'] = data.length - 1; report['columns'] = "fail"; report['upload'] = 0; report['removed'] = data.length - 1; return "completed"; } break; case 'UTF-16': data = fs.readFileSync(path, 'utf16le'); data = data.split("\n"); if (data[0].indexOf("\r") != -1) { report['total'] = data.length - 1; report['columns'] = "fail"; report['upload'] = 0; report['removed'] = data.length - 1; return "completed"; } break; case "Windows UTF-16": try { var iconv = Iconv("UTF-16", "UTF-8"); var content = fs.readFileSync(path); var buffer = iconv.convert(content) data = buffer.toString('utf8'); data = data.split("\r\n"); } catch (error) { report['total'] = 1; report['columns'] = "fail"; report['upload'] = 0; report['removed'] = 1; return "completed"; } if (data[0].indexOf("\r") != -1) { data = data[0].split("\r"); } if (data[0].indexOf("\n") != -1) { data = data[0].split("\n"); } break; case "Windows CP1250": var iconv = Iconv("cp1250", "UTF-8"); var content = fs.readFileSync(path); var buffer = iconv.convert(content) data = buffer.toString('utf8'); data = data.split("\r\n"); if (data[0].indexOf("\r") != -1) { data = data[0].split("\r"); } if (data[0].indexOf("\n") != -1) { report['total'] = data.length - 1; report['columns'] = "fail"; report['upload'] = 0; report['removed'] = data.length - 1; return "completed"; } break; default: data = fs.readFileSync(path, 'utf8'); data = data.split("\n"); if (data[0].indexOf("\r") != -1) { report['total'] = data.length - 1; report['columns'] = "fail"; report['upload'] = 0; report['removed'] = data.length - 1; return "completed"; } break; } switch (separator) { case ",": columns = data[0].split(separator); break; case ";": columns = data[0].split(separator); break; case "tab": separator = " " columns = data[0].split(separator); break; default: separator = "," columns = data[0].split(separator); break; } switch (csvtype) { case 'users': if (columns[0] = "username") { realColumns = ['username', 'description', 'email', 'password', 'language', 'groups']; } if (columns[0] = "ţ˙username") { realColumns = ['ţ˙username', 'description', 'email', 'password', 'language', 'groups']; } if (columns[0] = "username") { realColumns = ['username', 'description', 'email', 'password', 'language', 'groups']; } if (realColumns[0] == columns[0] && realColumns[1] == columns[1] && realColumns[2] == columns[2] && realColumns[3] == columns[3] && realColumns[4] == columns[4] && realColumns[5] == columns[5]) { collectionColumns = { username: "", userdes: "", emails: [], services: { password: {} }, language: "", groups: [] }; for (var i = 6; i < columns.length; i++) { if (columns[i].trim().length > 0) realColumns[i] = columns[i]; else { report['total'] = data.length - 1; report['columns'] = "fail"; report['upload'] = 0; report['removed'] = data.length - 1; return "completed"; break; } } data.shift(); report['total'] = data.length; response = storeUser(collectionColumns, data, realColumns, separator); } else { report['total'] = data.length - 1; report['columns'] = "fail"; report['upload'] = 0; report['removed'] = data.length - 1; return "completed"; } return response; break; case 'devices': realColumns = ['deviceId', 'group', 'owner', 'name', 'type']; if (realColumns[0] == columns[0] && realColumns[1] == columns[1] && realColumns[2] == columns[2] && realColumns[3] == columns[3] && realColumns[4] == columns[4]) { collectionColumns = { deviceId: "", group: "", owner: "", name: "", type: "" }; for (var i = 5; i < columns.length; i++) { if (columns[i].trim().length > 0) realColumns[i] = columns[i]; else { report['total'] = data.length - 1; report['columns'] = "fail"; report['upload'] = 0; report['removed'] = data.length - 1; return "completed"; break; } } data.shift(); report['total'] = data.length; response = storeDevices(collectionColumns, data, realColumns, separator); } else { report['total'] = data.length - 1; report['columns'] = "fail"; report['upload'] = 0; report['removed'] = data.length - 1; return "completed"; } return response; break; default: return "There is an error in your page.Please check value of input type hidden tag . "; break; } } storeUser = function(collectionCol, data, realColumns, separator) { var collectionColumns; var values = ""; var nullable; var groups = []; var group = "", user, missedUser; var subgroups = []; var tempgroup = ""; var breakRecord = false; var conflicts = ""; var exUnique = Tenants.findOne({ _id: currentTenant }).exIdUnique; for (var i = 0; i < data.length; i++) { group = ""; user = "", missedUser = ""; breakRecord = false; if (realColumns.length == data[i].split(separator).length) { collectionColumns = collectionCol; nullable = null; values = data[i].split(separator); for (var v = 0; v < 6; v++) { if (!values[v].trim().length) { nullable = true; report['description'][fail] = { recordnumber: i + 2, description: "'" + realColumns[v] + "' field contains null value" }; report['removed'] = ++fail; break; } } if (nullable) { continue; } else { conflicts = checkExConflicts(values[6], values[7], values[0], exUnique) if (conflicts) { insertConflictError(conflicts, i + 2) continue; } } user = Meteor.users.findOne({ $and: [{ 'emails.address': values[2] }, { username: values[0] }] }); missedUser = Meteor.users.findOne({ $or: [{ 'emails.address': values[2] }, { username: values[0] }] }); groups = values[5].split("|"); if (!user && missedUser) { report['description'][fail] = { recordnumber: i + 2, description: "User email and user exists in different accounts" }; report['removed'] = ++fail; } else { collectionColumns["groups"] = []; if (checkBreakRecord(groups)) { breakRecord = true; report['description'][fail] = { recordnumber: i + 2, description: "'" + values[5] + "' group field path miss matched or group field should not be empty" }; report['removed'] = ++fail; } if (!breakRecord) for (var j = 0; j < groups.length; j++) { subgroups = groups[j].split("/"); tempgroup = ""; if (!subgroups[0].trim()) subgroups.shift(); console.log("in function:" + JSON.stringify(subgroups)) for (var k = 0; k < subgroups.length; k++) { if (tempgroup) { if (!Groups.findOne({ 'groupname': subgroups[k], tenant: currentTenant })) tempgroup = Groups.insert({ groupname: subgroups[k], groupdes: "", groupperm: "", tenant: currentTenant, parent: tempgroup, users: [], adminGroup: "" }) else { tempgroup = Groups.findOne({ 'groupname': subgroups[k], parent: tempgroup, tenant: currentTenant }); if (tempgroup) tempgroup = tempgroup._id; } } else { tempgroup = Groups.findOne({ 'groupname': subgroups[k], tenant: currentTenant }); if (!tempgroup) tempgroup = Groups.insert({ groupname: subgroups[k], groupdes: "", groupperm: "", tenant: currentTenant, parent: "", users: [], adminGroup: "" }); else tempgroup = tempgroup._id; } } if (tempgroup) collectionColumns['groups'][collectionColumns['groups'].length] = { group: tempgroup }; } if (collectionColumns['groups'].length && !breakRecord) { collectionColumns['username'] = values[0]; collectionColumns['userdes'] = values[1]; collectionColumns['emails'] = [{ address: values[2], verified: false }]; collectionColumns['services']['password'] = { srp: SRP.generateVerifier(values[3]) }; collectionColumns['language'] = values[4]; collectionColumns["externalIds"] = [{ systemName: values[6], externalId: values[7] }]; if (!user) { userid = Meteor.users.insert(collectionColumns); if (userid) { report['upload'] = ++succ; userid = Meteor.users.findOne({ _id: userid }); for (var j = 0; j < userid.groups.length; j++) { Groups.update({ _id: userid.groups[j].group }, { $push: { users: { user: userid._id } } }); } } } else { Meteor.users.update({ _id: user._id }, { $pull: { externalIds: collectionColumns["externalIds"][0] } }); Meteor.users.update({ _id: user._id }, { $push: { externalIds: collectionColumns["externalIds"][0] } }); Meteor.users.update({ _id: user._id }, { $pullAll: { groups: collectionColumns["groups"] } }); Meteor.users.update({ _id: user._id }, { $pushAll: { groups: collectionColumns["groups"] } }); for (var k = 0; k < collectionColumns["groups"].length; k++) { Groups.update({ _id: collectionColumns["groups"][k]["group"] }, { $pull: { users: { user: user._id } } }); Groups.update({ _id: collectionColumns["groups"][k]["group"] }, { $push: { users: { user: user._id } } }); } report['update'] = ++update; } if (!user) user = userid; if (conflicts && !Tenants.findOne({ _id: currentTenant }).exIdUnique) { updateTenant(conflicts, user._id); } } else { if (!breakRecord) { report['description'][fail] = { recordnumber: i + 2, description: values[5] + "group field was empty" }; report['removed'] = ++fail; } } } } else { report['description'][fail] = { recordnumber: i + 2, description: "No of fields in columns and values does not match" }; report['removed'] = ++fail; } } return "success" } var checkBreakRecord = function(groups) { var temp = ""; var subgroups = ""; console.log(groups) for (var i = 0; i < groups.length; i++) { temp = ""; subgroups = groups[i].split("/"); if (!subgroups[0].trim()) subgroups.shift(); console.log(subgroups); for (var j = 0; j < subgroups.length; j++) { if (j == 0) { temp = Groups.findOne({ groupname: subgroups[j], tenant: currentTenant }); } else { if (temp && subgroups[j].trim().length) { if (!Groups.findOne({ groupname: subgroups[j], tenant: currentTenant }) || Groups.findOne({ groupname: subgroups[j], tenant: currentTenant }).parent == temp._id) temp = Groups.findOne({ groupname: subgroups[j], tenant: currentTenant }) else return true; } else { if (Groups.findOne({ groupname: subgroups[j], tenant: currentTenant }) || !subgroups[j].trim()) return true; } } } } return false; } storeDevices = function(collectionCol, data, realColumns, separator) { var CollectionColumns; var values = ""; var nullable; var tempgroup = ""; var subgroups = []; var breakRecord = false; var group = ""; for (var i = 0; i < data.length; i++) { tempgroup = ""; group = ""; breakRecord = false; if (realColumns.length == data[i].split(separator).length) { collectionColumns = collectionCol; nullable = null; tempgroup = ""; values = data[i].split(separator); for (var v = 0; v < 5; v++) { if (!values[v].trim().length) { nullable = true; report['description'][fail] = { recordnumber: i + 2, description: "'" + realColumns[v] + "' field contains null value" }; report['removed'] = ++fail; break; } } if (nullable) { continue; } subgroups = values[1].split("/"); if (checkBreakRecord([values[1]])) { breakRecord = true; } owner = Meteor.users.findOne({ 'emails.address': values[2] }); if (owner) { device = Devices.find({ $or: [{ deviceId: values[0] }, { name: values[3] }] }).fetch(); if (device.length > 0) { report['description'][fail] = { recordnumber: i + 2, description: " device id or device name are already exists " }; report['removed'] = ++fail; } else { if (!breakRecord) { if (!subgroups[0].trim()) subgroups.shift(); console.log("in function:" + JSON.stringify(subgroups)) for (var k = 0; k < subgroups.length; k++) { if (tempgroup) { if (!Groups.findOne({ 'groupname': subgroups[k], tenant: currentTenant })) tempgroup = Groups.insert({ groupname: subgroups[k], groupdes: "", groupperm: "", tenant: currentTenant, parent: tempgroup, users: [], adminGroup: "" }); else { tempgroup = Groups.findOne({ 'groupname': subgroups[k], parent: tempgroup, tenant: currentTenant }); if (tempgroup) tempgroup = tempgroup._id; } } else { tempgroup = Groups.findOne({ 'groupname': subgroups[k], tenant: currentTenant }); if (!tempgroup) tempgroup = Groups.insert({ groupname: subgroups[k], groupdes: "", groupperm: "", tenant: currentTenant, parent: "", users: [], adminGroup: "" }); else tempgroup = tempgroup._id; } } collectionColumns['deviceId'] = values[0]; collectionColumns['group'] = tempgroup; collectionColumns['owner'] = owner._id; collectionColumns['name'] = values[3]; collectionColumns['type'] = values[4]; collectionColumns['description'] = values[5]; if (Devices.insert(collectionColumns)) report['upload'] = ++succ; } else { report['description'][fail] = { recordnumber: i + 2, description: " '" + values[1] + "' path mis matched or group field should not empty" }; report['removed'] = ++fail; } } } else { report['description'][fail] = { recordnumber: i + 2, description: values[2] + " owner was not found" }; report['removed'] = ++fail; } } else { report['description'][fail] = { recordnumber: i + 2, description: "No of fields in columns and values does not match" }; report['removed'] = ++fail; } } } var checkExConflicts = function(systemName, externalId, username, exUnique) { console.log(exUnique) var groups = Groups.find({ tenant: currentTenant }, { _id: 1 }).fetch(); groups = _.pluck(groups, "_id"); var users = Meteor.users.findOne({ username: { $ne: username }, "groups.group": { $in: groups }, externalIds: { $elemMatch: { systemName: systemName, externalId: externalId } } }, { fields: { userdes: 1 } }); if (users && exUnique) { return "same tenant"; } var user = Meteor.users.findOne({ username: username }) if (user) { var tenants = Groups.find({ "users.user": user._id }, { fields: { tenant: 1 } }).fetch(); tenants = _.pluck(tenants, "tenant"); tenants = Tenants.find({ _id: { $in: tenants }, exIdUnique: true }).fetch(); tenants = _.pluck(tenants, "_id"); groups = Groups.find({ tenant: { $in: tenants } }, { fields: { _id: 1 } }).fetch(); groups = _.pluck(groups, "_id"); users = Meteor.users.findOne({ _id: { $ne: user._id }, "groups.group": { $in: groups }, externalIds: { $elemMatch: { systemName: systemName, externalId: externalId } } }); console.log(user) if (users) { console.log("other tenants") return "other tenants" } } } var insertConflictError = function(conflicts, recno) { report['description'][fail] = { recordnumber: recno, description: "extsysname and externalid fields has conflicts in " + conflicts }; report["removed"] = ++fail; }
import React, { useState, useEffect } from "react"; import "./Card.css"; import illus1 from "./../../assets/illus1.png"; import illus2 from "./../../assets/illus2.png"; import illus3 from "./../../assets/illus3.png"; function Card({ activeIndex }) { const content = [ { title: "Title1", description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 1 ", image: illus1, }, { title: "Title2", description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, description 2 ", image: illus2, }, { title: "Title3", description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, description 3 ", image: illus3, }, ]; return ( <div className="d-flex flex-column justify-content-around content"> <div className="imageWrapper"> <img src={content[activeIndex].image} /> </div> <div> <h2 className="title my-3 ">{content[activeIndex].title}</h2> <p className="description">{content[activeIndex].description}</p> </div> </div> ); } export default Card;
celebinoApp.controller('acessController', function (UserService, $scope, $state, $mdToast) { // Login user $scope.login = function(){ UserService.loginUser($scope.input) .then(function (response) { // Chamado quando a resposta contém status de sucesso. // Exibir toas com mensagem de sucesso ou erro. var toast = $mdToast.simple() .textContent('Logged.') .position('top right') .action('Ok') .hideDelay(6000); $mdToast.show(toast); //Save current user in session UserService.getByEmail($scope.input.email).then(function(response){ UserService.setCurrentUserByEmail(response.data); }); // Redirect to home page $state.go('home'); }) .catch(function (data) { var error = getError(data.status); // Handle error here var toast = $mdToast.simple() .textContent(error) .position('top right') .action('Ok') .hideDelay(6000); $mdToast.show(toast); }); }; $scope.signup = function(){ UserService.insertUser($scope.create) .then(function (response) { // Chamado quando a resposta contém status de sucesso. // Exibir toas com mensagem de sucesso ou erro. var toast = $mdToast.simple() .textContent('User created with sucess!') .position('top right') .action('Ok') .hideDelay(6000); $mdToast.show(toast); }) .catch(function (data) { var error = getError(data.status); // Handle error here var toast = $mdToast.simple() .textContent(error) .position('top right') .action('Ok') .hideDelay(6000); $mdToast.show(toast); }); }; // Get error status on login function getError(codeError){ if(codeError == "404"){ return "Email incorreto!" } else if(codeError == "401"){ return "Senha incorreta!" } return "Algo está errado!" } });
require("dotenv").config(); const mongoose = require("mongoose"); const host = process.env.DB_HOST; const username = process.env.DB_USER; const password = process.env.DB_PASSWORD; //mongodbのポートの読み込みと、mongoDBのコレクション名(task-manager-api)をつける mongoose.connect(`mongodb+srv://${username}:${password}@${host}/todoist`, { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false, }); // ToDoアプリを想定 const Task = mongoose.model("Task", { id: { type: Number, }, content: { type: String, }, layer: { type: Number, }, doneFlag: { type: Boolean, default: false, }, childIds: { type: [Number], }, }); exports.Task = Task;
// production keys //DEV.JS module.exports = { googleClientID:process.env.GOOGLE_CLIENT_ID, googleClientSecret: process.env.GOOGLE_CLIENT_SECRET, msidClientID: process.env.MSID_CLIENT_ID, msidClientSecret: process.env.MSID_CLIENT_SECRET, mongoURI:process.env.MONGO_URI, cookieKey: process.env.COOKIE_KEY };
import { Card, CardItem, Body, } from 'native-base'; import React, { Component } from 'react'; import { StyleSheet, Text, View, Image, TouchableOpacity } from 'react-native'; import { connect, useSelector } from 'react-redux'; import { SECONDARY_COLOR } from '../../utils/constants'; let UserProfile = (props) => { const {user} = props; return ( <View style={styles.container}> <View style={styles.header}></View> <Image style={styles.avatar} source={{uri: user?.photoUrl}}/> <View style={styles.body}> <View style={styles.bodyContent}> <Text style={styles.name}>{user?.name}</Text> <Text style={styles.info}>{user?.email}</Text> </View> </View> <View style={styles.addressCard}> <Card > <CardItem style={styles.addressCardHeader} header> <Text style={styles.addressCardHeaderText}>Manage Address</Text> </CardItem> <CardItem> <Body> <Text>Manage Address</Text> </Body> </CardItem> </Card> </View> </View> ); } const styles = StyleSheet.create({ container: { backgroundColor: '#fff', height: '100%' }, header:{ backgroundColor: SECONDARY_COLOR, height:75, }, avatar: { width: 130, height: 130, borderRadius: 63, borderWidth: 4, borderColor: "white", marginBottom:10, alignSelf:'center', position: 'absolute', marginTop:20 }, addressCard: { marginTop: 40, marginHorizontal: 10 }, addressCardHeader: { width: '100%', textAlign: 'center', alignItems: 'center', backgroundColor: '#00BFFF' }, addressCardHeaderText: { fontSize: 18, fontWeight: "bold", alignSelf: 'center', fontFamily: "PlayfairDisplay_500Medium" }, body:{ marginTop:40, }, bodyContent: { flex: 1, alignItems: 'center', padding:30, }, name:{ fontSize:28, color: "#696969", fontWeight: "600", fontFamily: "PlayfairDisplay_500Medium" }, info:{ fontSize:16, color: "#00BFFF", fontFamily: "PlayfairDisplay_400Regular" }, }); const mapStateToProps = (state) => ({ user: state.auth.user }) export default connect(mapStateToProps, {}) (UserProfile);
import React from 'react'; import styled, { css } from 'styled-components'; import { device, imagesStyles } from '../../../theme'; import PhotoDisclaimer from '../../../components/common/PhotoDisclaimer'; import Container from '../../../components/layout/Container'; import { postPhotoLink } from '../../../pages/post-photo'; export default function PostGallery({ post }) { const { gallery } = post; return ( <Container> <Wrapper> <StyledList> {gallery.map((photo, i) => ( <StyledListItem key={i}> <a href={postPhotoLink(photo)} title={photo.title}> <StyledImage src={`${photo.src}?w=240&h=240&fm=webp&fit=thumb&q=50`} title={photo.title} alt={photo.alt || photo.title} loading="lazy" /> </a> </StyledListItem> ))} </StyledList> <PhotoDisclaimer /> </Wrapper> </Container> ); } const Wrapper = styled.div` max-width: 65ch; `; const StyledList = styled.ul` display: grid; grid-gap: calc(var(--space-unit) / 1.5); grid-template-columns: repeat(auto-fit, 70px); @media ${device.desktop} { grid-template-columns: repeat(auto-fit, 120px); } margin-bottom: calc(var(--space-unit) * 2); `; const squareStyle = css` width: 70px; height: 70px; @media ${device.desktop} { width: 120px; height: 120px; } `; const StyledListItem = styled.li` ${squareStyle} transition: transform 0.2s ease-in-out; img { ${squareStyle}/* we need to override native image dimensions to force the square aspcet ratio */ } :hover { transform: translateY(-0.15em); } `; const StyledImage = styled.img` ${imagesStyles} `;
const env = process.env; // const url = env.APP_PROTOCOL; module.exports = { devServer: { proxy: { '/secure': { target: env.VUE_APP_SERVER_URL, ws: false, changeOrigin: true }, '/auth': { target: env.VUE_APP_SERVER_URL, ws: false, changeOrigin: true } } } };
var sendmail_8h = [ [ "mutt_invoke_sendmail", "sendmail_8h.html#a2d1312bbee49dda97d3c94837c4af6ab", null ] ];
import { dispatch } from '../dispatcher'; export default { create() { dispatch({type: 'sample/create'}); } }
import { expect } from 'chai'; import * as sinon from 'sinon'; import { Game } from '../../../../src/core'; describe('Game', () => { describe('General', () => { it('should be importable', () => { expect(Game).to.be.a('function'); }); it('should be constructable', () => { expect(new Game()).to.be.an.instanceof(Game); }); }); describe('Constructor', () => { it('should set up the initial state', () => { expect(new Game()._state).to.eql([ [null, null, null], [null, null, null], [null, null, null], ]); }); it('should set up the current player', () => { expect(new Game()._currentPlayer).to.eq(0); }); it('should set the `isComplete` property to `false`', () => { expect(new Game()._isComplete).to.be.false; }); it('should set the `wonBy` property to `false`', () => { expect(new Game()._wonBy).to.be.null; }); }); describe('Instance methods', () => { let game; beforeEach(() => { game = new Game(); }); describe('play()', () => { it('should apply the current player\'s identifier using the coordinates provided', () => { const row = 0; const column = 0; const coords = [row, column]; game.play(...coords); expect(game._state[row][column]).to.eq(0); }); it('should not apply the current player\'s identifier if the game is complete', () => { const row = 0; const column = 0; const coords = [row, column]; game._state = [[0]]; game._currentPlayer = 'Foo'; game._isComplete = true; game.play(...coords); expect(game._state[row][column]).to.eq(0); }); it('should not apply the current player\'s identifier if the target cell is occupied', () => { const row = 0; const column = 0; const coords = [row, column]; game._state = [[0]]; game._currentPlayer = 'Foo'; game.play(...coords); expect(game._state[row][column]).to.eq(0); }); it('should alternate between players', () => { const row1 = 0; const column1 = 0; const row2 = 0; const column2 = 1; const coords1 = [row1, column1]; const coords2 = [row2, column2]; game.play(...coords1); game.play(...coords2); expect(game._state[row1][column1]).to.eq(0); expect(game._state[row2][column2]).to.eq(1); }); it('should not alternate between players if the game is complete', () => { game._isComplete = true; game._currentPlayer = 'Foo'; game.play(0, 0); expect(game._currentPlayer).to.eq('Foo'); }); it('should not alternate between players if the target cell is occupied', () => { game._state = [[0]]; game._currentPlayer = 'Foo'; game.play(0, 0); expect(game._currentPlayer).to.eq('Foo'); }); it('should update the `isComplete` property using `checkWin`', () => { const checkWin = game.checkWin = sinon.spy(() => true); game._isComplete = false; game.play(0, 0); expect(checkWin.called).to.be.true; expect(game._isComplete).to.be.true; }); it('should set the `wonBy` property to the current player when the game is complete', () => { const currentPlayer = 'Foo'; game._currentPlayer = currentPlayer; game.checkWin = () => true; game.play(0, 0); expect(game._wonBy).to.eq(currentPlayer); }); it('should return `true` when the play is successful', () => { expect(game.play(0, 0)).to.be.true; }); it('should return `false` if the game is complete', () => { game._isComplete = true; expect(game.play(0, 0)).to.be.false; }); it('should return `false` if the target cell is occupied', () => { game._state = [[0]]; expect(game.play(0, 0)).to.be.false; }); }); describe('checkWin()', () => { it('should return `false` if the game has not been won', () => { expect(game.checkWin()).to.be.false; }); it('should check for a "row"-type win', () => { game._state = [[0, 0, 0], [], []]; expect(game.checkWin()).to.be.true; }); it('should check for a "column"-type win', () => { game._state = [[0], [0], [0]]; expect(game.checkWin()).to.be.true; }); it('should check for a "diagonal"-type win', () => { game._state = [ [0], [1, 0], [1, 1, 0], ]; expect(game.checkWin()).to.be.true; }); }); describe('isTaken()', () => { it('should return `true` if the target cell is occupied', () => { game._state = [[0]]; expect(game.isTaken(0, 0,)).to.be.true; }); it('should return `false` if the target cell contains a `null` value', () => { expect(game.isTaken(0, 0)).to.be.false; }); }); describe('reset()', () => { it('should reset the game state', () => { game._state = 'Foo'; game.reset(); expect(game._state).to.eql([ [null, null, null], [null, null, null], [null, null, null], ]); }); it('should reset the current player', () => { game._currentPlayer = 'Foo'; game.reset(); expect(game._currentPlayer).to.eq(0); }); it('should set the `isComplete` property to `false`', () => { game._isComplete = true; game.reset(); expect(game._isComplete).to.be.false; }); }); describe('getAllAvailableCoords()', () => { it('should return the coordinates of each unoccupied cell', () => { const coords = game.getAllAvailableCoords(); expect(coords.length).to.eq(9); expect(coords.every(([row, col]) => typeof row === 'number' && typeof col === 'number')).to.be.true; }); it('should exclude cells that are occupied', () => { game._state[0][0] = 0; const coords = game.getAllAvailableCoords(); expect(coords.length).to.eq(8); expect(coords[0]).to.eql([0, 1]); }); }); describe('getRandomAvailableCoords()', () => { it('should return a random pair of available coordinates', () => { const vals = [0, 1, 2]; const getAllAvailableCoords = game.getAllAvailableCoords = sinon.spy(() => vals); const coords = game.getRandomAvailableCoords(); expect(getAllAvailableCoords.called).to.be.true; expect(vals.includes(coords)).to.be.true; }); it('should return the only pair of available coordinates', () => { const vals = [0]; const getAllAvailableCoords = game.getAllAvailableCoords = sinon.spy(() => vals); const coords = game.getRandomAvailableCoords(); expect(getAllAvailableCoords.called).to.be.true; expect(vals[0]).to.eq(coords); }); it('should return `undefined` if there are no available coordinates', () => { const getAllAvailableCoords = game.getAllAvailableCoords = sinon.spy(() => []); const coords = game.getRandomAvailableCoords(); expect(getAllAvailableCoords.called).to.be.true; expect(coords).to.be.undefined; }); }); describe('getRows()', () => { it('should return a two-dimensional array of row data', () => { const rows = []; game._state = rows; expect(game.getRows()).to.eq(rows); }); }); describe('getColumns()', () => { it('should return a two-dimensional array of column data', () => { const col1 = new Array(3).fill(0); const col2 = new Array(3).fill(1); const col3 = new Array(3).fill(2); game._state = [ [0, 1, 2], [0, 1, 2], [0, 1, 2], ]; const result = game.getColumns(); const [a, b, c] = result expect(result.length).to.eq(3); expect(a).to.eql(col1); expect(b).to.eql(col2); expect(c).to.eql(col3); }); }); describe('getDiagonals()', () => { it('should return a two-dimensional arrow of diagonal data', () => { const diag1 = [0, 1, 2]; const diag2 = [2, 1, 0]; game._state = [ [0, 1, 2], [0, 1, 2], [0, 1, 2], ]; const result = game.getDiagonals(); const [a, b] = result; expect(result.length).to.eq(2); expect(a).to.eql(diag1); expect(b).to.eql(diag2); }); }); }); });
/* begin copyright text * * Copyright © 2016 PTC Inc., Its Subsidiary Companies, and /or its Partners. All Rights Reserved. * * end copyright text */ /* jshint node: true */ /* jshint strict: global */ 'use strict'; var graceTime; var dbHandler = null; var debug = require("debug")("vxs:billable"); var tableName = "billable"; function Billable(){} var dbCleanup = function cleanUp(){ return dbHandler.delete(tableName, "createdon < ?", [new Date(Date.now() - graceTime * 1.5)]); }; function getEventsNumberPromise (id, projectName, createdOn) { var where = "id = ? and projectname = ? and createdon >= ? and createdon < ? "; var values = [id, projectName, new Date(createdOn.valueOf() - graceTime), createdOn]; return dbHandler.selectWithParams(["count(*)"], tableName, where, values) .then(function(valuerows){ debug('valueRows:', valuerows); var eventsNumber = dbHandler.getCount(valuerows); debug('number of events:', eventsNumber); return eventsNumber; }); } Billable.tableName = tableName; Billable.init=function init(theDbHandler,theGraceTime){ graceTime = theGraceTime * 60 * 1000; // convert minutes to miliseconds dbHandler = theDbHandler; setInterval(dbCleanup, graceTime); }; Billable.isBillable = function isBillable(id, projectName, createdOn){ createdOn = createdOn || new Date(Date.now()); return getEventsNumberPromise(id, projectName, createdOn) .tap(function(numberOfViews){ if (numberOfViews < 1) { return dbHandler.insertWithParams({id:id, projectname:projectName, createdon:createdOn}, tableName, false); } }) .then(function(numberOfViews){ debug('number of views:', numberOfViews); return numberOfViews < 1; }); }; module.exports = Billable;
import { combineReducers } from "redux"; import QuizDataReducer from "./QuizDataReducer"; export const reducers = combineReducers({ quizData: QuizDataReducer });
const Blog = require('../models/Blog.js') module.exports = { index: (req,res) => { Blog.find({}, (err, blogs) => { if (err) return console.log(err) res.json(blogs) }) }, show: (req, res) => { Blog.findById(req.params.id, (err, blog) => { var comment = blog.comments.id(req.params.cId) res.json(comment) }) }, create: (req, res) => { Blog.findById(req.params.id, (err, blog) => { if (err) return console.log(err) var nueBlog = blog nueBlog.comments.push(req.body) nueBlog.save((err, blog) => { if (err) console.log("Saving error", err) res.json({success: true, message: "Comment added.", blog}) }) }) }, update: (req,res) => {}, destroy: (req,res) => {} }
require('./routine.buildWithWebpack')({minify: true});
DV.model.Document = function(viewer){ this.viewer = viewer; this.currentPageIndex = 0; this.offsets = []; this.baseHeightsPortion = []; this.baseHeightsPortionOffsets = []; this.paddedOffsets = []; this.originalPageText = {}; this.totalDocumentHeight = 0; this.totalPages = 0; this.additionalPaddingOnPage = 0; this.ZOOM_RANGES = [800, 1000, 1200]; var data = this.viewer.schema.data; this.state = data.state; this.baseImageURL = data.baseImageURL; this.canonicalURL = data.canonicalURL; this.additionalPaddingOnPage = data.additionalPaddingOnPage; this.pageWidthPadding = data.pageWidthPadding; this.totalPages = data.totalPages; this.onPageChangeCallbacks = []; var zoom = this.zoomLevel = this.viewer.options.zoom || data.zoomLevel; if (zoom == 'auto') this.zoomLevel = data.zoomLevel; // The zoom level cannot go over the maximum image width. var maxZoom = _.last(this.ZOOM_RANGES); if (this.zoomLevel > maxZoom) this.zoomLevel = maxZoom; }; DV.model.Document.prototype = { setPageIndex : function(index) { this.currentPageIndex = index; this.viewer.elements.currentPage.text(this.currentPage()); this.viewer.helpers.setActiveChapter(this.viewer.models.chapters.getChapterId(index)); _.each(this.onPageChangeCallbacks, function(c) { c(); }); return index; }, currentPage : function() { return this.currentPageIndex + 1; }, currentIndex : function() { return this.currentPageIndex; }, nextPage : function() { var nextIndex = this.currentIndex() + 1; if (nextIndex >= this.totalPages) return this.currentIndex(); return this.setPageIndex(nextIndex); }, previousPage : function() { var previousIndex = this.currentIndex() - 1; if (previousIndex < 0) return this.currentIndex(); return this.setPageIndex(previousIndex); }, zoom: function(zoomLevel,force){ if(this.zoomLevel != zoomLevel || force === true){ this.zoomLevel = zoomLevel; this.viewer.models.pages.resize(this.zoomLevel); this.viewer.models.annotations.renderAnnotations(); this.computeOffsets(); } }, computeOffsets: function() { var annotationModel = this.viewer.models.annotations; var totalDocHeight = 0; var adjustedOffset = 0; var len = this.totalPages; var diff = 0; var scrollPos = this.viewer.elements.window[0].scrollTop; for(var i = 0; i < len; i++) { if(annotationModel.offsetsAdjustments[i]){ adjustedOffset = annotationModel.offsetsAdjustments[i]; } var pageHeight = this.viewer.models.pages.getPageHeight(i); var previousOffset = this.offsets[i] || 0; var h = this.offsets[i] = adjustedOffset + totalDocHeight; if((previousOffset !== h) && (h < scrollPos)) { var delta = h - previousOffset - diff; scrollPos += delta; diff += delta; } this.baseHeightsPortion[i] = Math.round((pageHeight + this.additionalPaddingOnPage) / 3); this.baseHeightsPortionOffsets[i] = (i == 0) ? 0 : h - this.baseHeightsPortion[i]; totalDocHeight += (pageHeight + this.additionalPaddingOnPage); } // Add the sum of the page note heights to the total document height. totalDocHeight += adjustedOffset; // artificially set the scrollbar height if(totalDocHeight != this.totalDocumentHeight){ diff = (this.totalDocumentHeight != 0) ? diff : totalDocHeight - this.totalDocumentHeight; this.viewer.helpers.setDocHeight(totalDocHeight,diff); this.totalDocumentHeight = totalDocHeight; } }, getOffset: function(_index){ return this.offsets[_index]; }, resetRemovedPages: function() { this.viewer.models.removedPages = {}; }, addPageToRemovedPages: function(page) { this.viewer.models.removedPages[page] = true; }, removePageFromRemovedPages: function(page) { this.viewer.models.removedPages[page] = false; }, redrawPages: function() { _.each(this.viewer.pageSet.pages, function(page) { page.drawRemoveOverlay(); }); if (this.viewer.thumbnails) { this.viewer.thumbnails.render(); } }, redrawReorderedPages: function() { if (this.viewer.thumbnails) { this.viewer.thumbnails.render(); } } };
const issueLabelsHandler = require('./src/issueLabelsHandler'); const calculatePriority = require('./src/calculatePriority'); const addLabel = require('./src/addLabel'); module.exports = (robot) => { const events = ['issues.labeled', 'issues.unlabeled', 'issues.opened']; return robot.on(events, issueLabelsHandler.bind(null, addLabel, calculatePriority)); };
const ErrorModule = require('../error'); const AppError = ErrorModule.AppError; const AppErrorTypes = ErrorModule.AppErrorTypes; module.exports = {}; /** * Serialize a Sequalize Model with only the serializable fields * that the model exposes. * @param model - The model to serialize * @returns {Object} */ const serializeModel = function(model) { return mapInstanceToData(model); }; module.exports.serializeModel = serializeModel; /** * Serializes an array of Sequlize Models * @param models - An array of models to serialize * @returns {Array} */ const serializeModels = function(models) { let serializedData = []; let iterations = []; for (let i = 0; i < models.length; i++) { let model = models[i]; let fn = serializeModel(model) .then((data) => { serializedData.push(data); }); iterations.push(fn); } return Promise.all(iterations).then(() => { return serializedData; }); }; module.exports.serializeModels = serializeModels; const mapDataToEntity = function(entity, data) { return mapDataToInstance(entity.build(), data); }; module.exports.mapDataToEntity = mapDataToEntity; const mapDataToInstance = function(instance, data) { return new Promise((resolve, reject) => { if (instance == null) reject(new AppError("Cannot map null", AppErrorTypes.MAP_NULL_INSTANCE)); const map = instance.getMap().inMap; for (let property in map) { if (map.hasOwnProperty(property) && data.hasOwnProperty(property)) { let mappedProperty = map[property]; let type = 'STRING'; let translatedProperty = mappedProperty; if (typeof mappedProperty === 'object') { type = mappedProperty.Type; translatedProperty = mappedProperty.Value; } switch (type) { case 'STRING': instance[translatedProperty] = data[property]; break; case 'JSON': instance[translatedProperty] = JSON.stringify(data[property]); break; default: throw "Unknown type to map"; break; } } } resolve(instance); }); }; module.exports.mapDataToInstance = mapDataToInstance; const mapInstanceToData = function(instance) { return new Promise((resolve, reject) => { if (instance == null) reject(new AppError("Cannot map null", AppErrorTypes.MAP_NULL_INSTANCE)); const map = instance.getMap().outMap; const data = {}; for (let property in map) { if (map.hasOwnProperty(property)) { let mappedProperty = map[property]; let type = 'STRING'; let translatedProperty = mappedProperty; if (typeof mappedProperty === 'object') { type = mappedProperty.Type; translatedProperty = mappedProperty.Value; } switch (type) { case 'STRING': data[translatedProperty] = instance[property]; break; case 'JSON': data[translatedProperty] = JSON.parse(instance[property]); break; default: throw "Unknown type to map"; break; } } } resolve(data); }); }; module.exports.mapInstanceToData = mapInstanceToData;
import React from 'react' import { Button } from './Button' import './Header.css' import '../App.css' import cv from '../Rainie_CV.pdf' function Header () { const showCV = () => { window.open(cv) } return ( <div className='header-container'> <video src='/motionplaces fire-Oct2018.mp4' autoPlay loop muted /> <h1>Rainie Liu</h1> <p>Software Engineer based in Sydney</p> <p>The days break you are the days make you</p> <div className='header-btns'> <Button className='btns' buttonStyle='btn--outline' buttonSize='btn--large' > See My Projects </Button> <Button className='btns' buttonStyle='btn--primary' buttonSize='btn--large' onClick={showCV} > See My CV <i className='fas fa-file-alt' /> </Button> </div> </div> ) } export default Header
import * as GLOBALS from './globals'; import { settings } from './userData'; import * as utilities from './utilities'; class Ticker { constructor() { this.tickerWrapper = document.createElement('div'); this.tickerWrapper.classList.add('ticker-wrapper'); this.ticker = document.createElement('div'); this.ticker.classList.add('ticker'); this.tickerWrapper.appendChild(this.ticker); this.itemCollection = []; } createTickerItem = (content) => { const tickerItem = document.createElement('p'); tickerItem.classList.add('ticker__item'); tickerItem.innerText = content; this.itemCollection.push(tickerItem); } createItemSet = (dayData) => { const dayTime = new utilities.TimeFormatter( dayData.time * 1000, settings.language, ); let fullDay = dayTime.getFullDay(); fullDay = fullDay[0].toUpperCase() + fullDay.slice(1); this.createTickerItem(''); this.createTickerItem(`${fullDay} :`); this.createTickerItem(`${Math.round(dayData.temperatureLow)}° - ${Math.round(dayData.temperatureHigh)}°`); this.createTickerItem(dayData.summary.slice(0, -1)); this.createTickerItem( `${GLOBALS.dictionary.wind[settings.language]}: ${Math.round(dayData.windSpeed)} ${settings.units === 'si' ? GLOBALS.dictionary.speed.si[settings.language] : GLOBALS.dictionary.speed.us[settings.language]}`, ); this.createTickerItem( `${GLOBALS.dictionary.humidity[settings.language]}: ${Math.round(dayData.humidity * 100)}%`, ); this.createTickerItem(''); } createTickerContent = (weekData) => { for (let i = 1; i < 8; i++) { this.createItemSet(weekData[i]); } } drawTicker = (weatherData) => { this.ticker.innerHTML = ''; this.createTickerContent(weatherData.daily.data); this.itemCollection.forEach((item) => this.ticker.appendChild(item)); this.itemCollection = []; } } export const ticker = new Ticker();
var app = new PIXI.Application(800, 600, { backgroundColor: 0xEEEEEE }); document.body.appendChild(app.view); // create a background... var background = PIXI.Sprite.fromImage('./assets/2.jpg'); background.width = app.screen.width; background.height = app.screen.height; // add background to stage... app.stage.addChild(background); var isLineMode = false; if (location.search === '?line') { isLineMode = true; } app.stage.interactive = true; app.stage.buttonMode = true; app.stage .on('pointerdown', onDragStart) .on('pointerup', onDragEnd) .on('pointerupoutside', onDragEnd); var texture = PIXI.Texture.fromImage('assets/1.png'); var stamp = new PIXI.Sprite(texture); var ansNum; function getRandomInt(min, max) { ansNum = Math.floor(Math.random() * (max - min + 1)) + min; console.log('ansNum: ', ansNum); return ansNum; } getRandomInt(1, 16); var centerArr = []; var xd = app.screen.width / 8; var yd = app.screen.height / 8; var startx = 0, starty = 0, endx = 4, endy = 4; for (; startx < endx; startx++) { for (starty = 0; starty < endy; starty++) { var x = xd + starty * 2 * xd; var y = yd + startx * 2 * yd; console.log(x, y); centerArr.push({ x, y }); } } console.log('centerArr: ', centerArr); var ansPoint = centerArr[ansNum - 1]; console.log('ansPoint', ansPoint); var toloranceD = xd > yd ? xd : yd; console.log('toloranceD: ', toloranceD); renderStamp(ansPoint); var countingText = new PIXI.Text('倒數: 6', { fontWeight: 'bold', fontStyle: 'italic', fontSize: 60, fontFamily: 'Arvo', fill: '#3e1707', align: 'center', stroke: '#a4410e', strokeThickness: 7 }); countingText.x = app.screen.width / 2; countingText.y = 0; countingText.anchor.x = 0.5; app.stage.addChild(countingText); var count = 6; var isCanPlay = false; app.ticker.add(function() { count -= 0.02; // update the text with a new string countingText.text = '倒數: ' + Math.floor(count); if (Math.floor(count) === 0) { isCanPlay = true; app.stage.removeChild(countingText) } }); setTimeout(() => app.stage.removeChild(stamp), 5000); // 建立容器 var objContainer = new PIXI.Container(); app.stage.addChild(objContainer); if (isLineMode) { // 畫線 var objLine1 = new PIXI.Graphics(); objLine1.lineStyle(4, 0x000000, 1); objLine1.moveTo(0, 150); objLine1.lineTo(800, 150); var objLine2 = new PIXI.Graphics(); objLine2.lineStyle(4, 0x000000, 1); objLine2.moveTo(0, 300); objLine2.lineTo(800, 300); var objLine3 = new PIXI.Graphics(); objLine3.lineStyle(4, 0x000000, 1); objLine3.moveTo(0, 450); objLine3.lineTo(800, 450); var objLine4 = new PIXI.Graphics(); objLine4.lineStyle(4, 0x000000, 1); objLine4.moveTo(200, 0); objLine4.lineTo(200, 600); var objLine5 = new PIXI.Graphics(); objLine5.lineStyle(4, 0x000000, 1); objLine5.moveTo(400, 0); objLine5.lineTo(400, 600); var objLine6 = new PIXI.Graphics(); objLine6.lineStyle(4, 0x000000, 1); objLine6.moveTo(600, 0); objLine6.lineTo(600, 600); objContainer.addChild(objLine1); objContainer.addChild(objLine2); objContainer.addChild(objLine3); objContainer.addChild(objLine4); objContainer.addChild(objLine5); objContainer.addChild(objLine6); } function onDragStart(e) { var _touchPos = { x: Math.floor(e.data.global.x), y: Math.floor(e.data.global.y) } console.log('start touchPos: ', _touchPos); } var touchPos; function onDragEnd(e) { touchPos = { x: Math.floor(e.data.global.x), y: Math.floor(e.data.global.y) } console.log('end touchPos: ', touchPos); if (isCanPlay) { renderStamp(touchPos); } } function checkAns() { if (isCanPlay) { validateAns(touchPos); } } function validateAns(pos) { const distance = Math.sqrt(Math.pow(pos.x - ansPoint.x, 2) + Math.pow(pos.y - ansPoint.y, 2)); console.log('distance: ', distance); if (toloranceD >= distance) { console.log(true); alert(true); } else { console.log(false); alert(false); } } function renderStamp(target) { stamp.width = app.screen.height / 8; stamp.height = app.screen.height / 8; // console.log('stamp.width: ', stamp.width); // console.log('stamp.height: ', stamp.height); stamp.x = target.x; stamp.y = target.y; app.stage.addChild(stamp); }
frappe.provide("jasper"); jasper.show_banner = function(msg) { $banner = $('<div class="toolbar-banner">'+msg+'<a class="close">&times;</a></div>') .prependTo($('header .navbar')); $("body").css({"padding-top": "70px"}); $banner.find(".close").click(function() { $(".toolbar-banner").toggle(false); $("body").css({"padding-top": "36px"}); }); return $banner; } jasper.close_banner = function($banner){ $banner.find(".close").click(); }; show_banner_message = function(msg, where_ok, where_cancel, bckcolor, callback){ $banner = jasper.show_banner(msg); if (bckcolor != null) $banner.css({background: bckcolor, opacity: 0.9}); if (where_ok != null){ $banner.find(where_ok).click(function(){ callback($banner, "ok"); }); }; if(where_cancel != null){ $banner.find(where_cancel).click(function(){ callback($banner, "cancel"); }); }; } jasper.check_for_ask_param = function(rname, page, callback){ var robj = jasper.get_jasperdoc_from_name(rname, page); var ret; if (robj && robj.show_params_dialog && (robj.locale === "Ask" || (robj.params && robj.params.length > 0))){ ret = jasper.make_dialog(robj, rname + " parameters", callback); }else{ callback({abort: false}); } }; jasper.make_menu = function(list, key, skey){ var f = list[key].formats; var email = list[key].email; var mail_enabled = frappe.boot.jasper_reports_list.mail_enabled;//list.mail_enabled; var icon_file = []; var html = ""; for(var i=0; i < f.length; i++){ var type = f[i]; icon_file.push(repl('<i title="%(title)s" data-jr_format="%(f)s" data-jr_name="%(mykey)s" class="jasper-%(type)s"></i>', {title:key + " - " + type, mykey:key, f:f[i], type: jasper_report_formats[type]})); }; if (email === 1 && mail_enabled === 1){ icon_file.push(repl('<i title="%(title)s" data-jr_format="%(f)s" data-jr_name="%(mykey)s" class="%(type)s"></i>', {title: "send by email", mykey:key, f:"email", type: jasper_report_formats["email"]})); } html = html + '<li>' + repl('<a class="jrreports" href="#" data-jr_format="%(f)s" data-jr_name="%(mykey)s"',{mykey:key, f:"html"}) +' title="'+ key +' - html" >'+ icon_file.join(" ") + " " + skey + '</a>' +'</li>'; return html; }; jasper.make_dialog = function(doc, title, callback){ var fields = []; var params = doc.params; var docids = null; var doctype_id_fields = {}; //Only one doctype_id field. Means, this parameters has the name (id) of open document (Form) or the ids of the selected documents in List view var is_doctype_id = false; for (var i=0; i < params.length; i++){ var param = doc.params[i]; if (param.is_copy === "Is doctype id"){ is_doctype_id = true; if (param.jasper_field_doctype.trim() === "" && param.jasper_param_value.trim() === ""){ docids = jasper.getIdsFromList(); if(!docids) docids = cur_frm && cur_frm.doc.name; }else{ var route = frappe.get_route(); if (route[0] === "Form" && param.jasper_field_doctype.trim() !== ""){ docids = cur_frm.doc[param.jasper_field_doctype]; } } }; fields.push({label:param.name, fieldname:param.name, fieldtype:param.jasper_param_type==="String"? "Data": param.jasper_param_type, description:param.jasper_param_description || "", default: docids || param.jasper_param_value}); }; if(doc.jasper_report_origin === "LocalServer" && doc.locale !== "Do Not Use" && doc.locale !== "not Ask"){ var lang_default = frappe.defaults.get_user_default("lang"); var country = jasper.get_country_from_alpha3(lang_default); fields.push({label:__("Locale"), fieldname:"locale", fieldtype: "Select", description: __("Select the report language."), options: jasper.make_country_list(), default:[country]}); }; function ifyes(d){ if (callback){ callback({values: d.get_values(), abort: false, is_doctype_id: is_doctype_id}); } }; function ifno(){ if (callback){ callback({abort: true}); } }; var d = jasper.ask_dialog(title, doc.message, fields, ifyes, ifno); return d; } jasper.ask_dialog = function(title, message, fields, ifyes, ifno) { var html = {fieldtype:"HTML", options:"<p class='frappe-confirm-message'>" + message + "</p>"}; fields.splice(0,0,html); var d = new frappe.ui.Dialog({ title: __(title), fields: fields, primary_action: function() { d.hide(); ifyes(d); } }); d.show(); if(ifno) { d.$wrapper.find(".modal-footer .btn-default").click(ifno); } return d; };
import React from "react"; export default function NavBar({ setCuisine }) { return ( <h1 style={{ backgroundColor: "CornflowerBlue", fontSize: "4vh", border: "0px", margin: "0px", padding: "2px", textAlign: "center", }} > <ul style={{ fontSize: "4vh", border: "0px", margin: "0px", padding: "2px", paddingBottom: "50px", textAlign: "center", listStyle: "none", cursor: "pointer", textDecoration: "underline", }} > <li onClick={() => setCuisine("american")}>American</li> <li onClick={() => setCuisine("italian")}>Italian</li> <li onClick={() => setCuisine("mexican")}>Mexican</li> <li onClick={() => setCuisine("cafe")}>Cafes</li> </ul> </h1> ); }
/* * notFoundController.js * * Copyright (c) 2019 HEB * All rights reserved. * * This software is the confidential and proprietary information * of HEB. */ 'use strict'; /** * The controller for the Not found page. * * @author vn70529 * @since 2.29.0 */ (function () { angular.module('productMaintenanceUiApp').controller('NotFoundController', notFoundController); notFoundController.$inject = ["$stateParams"]; function notFoundController( $stateParams) { var self = this; const PAGE_NOT_ACCESS_MESSAGE = "User does not have access, please contact the service desk."; const PAGE_NOT_FOUND_MESSAGE = "User does not have access for module, please contact the service desk."; self.message = ''; self.$onInit = function() { if($stateParams && $stateParams.pageNotAccess){ self.message = PAGE_NOT_ACCESS_MESSAGE; } else{ self.message = PAGE_NOT_FOUND_MESSAGE; } } } })();
(function($){ $(document).ready(function() { function reloadScripts() { $("#research-book").empty(); var str = `<!-- Scripts for Flipbook --> <script type="text/javascript" src="./JS/lib/jquery.min.1.7.js"></script> <script type="text/javascript" src="./JS/lib/jquery-ui-1.8.20.custom.min.js"></script> <script type="text/javascript" src="./JS/lib/jquery.mousewheel.min.js"></script> <script type="text/javascript" src="./JS/lib/modernizr.2.5.3.min.js"></script> <script type="text/javascript" src="./JS/lib/turn.min.js"></script> <script type="text/javascript" src="./JS/lib/hash.js"></script> <div id="book-zoom"> <div class="flipbook-viewport"> <div class="container"> <div class="flipbook"> <!-- Cover Page --> <div class="hard"> <div style="height: 100%; width: 100%; background-image:url(https://live.staticflickr.com/4103/5032206759_e0b3c4f45a_b.jpg)"> <div style="height: 100%; display: flex; justify-content: center; align-items: center; background-color: rgba(255,255,255, 0.3)"> <div> <h3 style="color: black">Research Notebook</h3> <br><br> <h6>(Click the bottom corners of the book to read)</h6> </div> </div> </div> </div> <div class="hard"> <div style="height: 100%; width: 100%; background-image:url(https://live.staticflickr.com/4103/5032206759_e0b3c4f45a_b.jpg); -webkit-transform: rotate(180deg); background-color: rgba(255,255,255, 0.3)"></div> </div> <!-- Table of Content --> <div style="display: flex; align-items: center; justify-content: center"> <div class="pagecontent"> <h4>Table of Contents</h4> <br><br> <p style="text-align: left">UCLA Vision Cognition Learning and Autonomy</p> <br> <p style="text-align: left">Chinese University of Hong Kong</p> <br> <p style="text-align: left">Hong Kong Broadband Network</p> </div> </div> <!-- UCLA VCLA --> <div> <div style="height: 100%; display: flex; justify-content: center; align-items: center"> <div class="pagecontent"> <div class="pagegrid"> <div class="pagegridcell"> <img src="https://vcla.stat.ucla.edu/images/logo_v3%20-%20Small.png" style="width: 50%"> </div> <div class="pagegridcell"> <div> <h6>UCLA VCLA</h6> (June 2018 - Present) <p style="text-align: left"> <br> <b>Focus:</b> Virtual AI Agents (VRGym); Physics Simulation Environment (Bullet Physics Engine) <br><br> <button class="booklink" onclick="transitionToPage('./Projects/vcla.html')"><b>Click to learn more</b></button></p> </div> </div> </div> </div> </div> </div> <!-- CUHK --> <div> <div style="height: 100%; display: flex; justify-content: center; align-items: center"> <div class="pagecontent"> <div class="pagegrid"> <div class="pagegridcell"> <img src="https://upload.wikimedia.org/wikipedia/en/thumb/8/87/CUHK.svg/1200px-CUHK.svg.png" style="width: 80%"> </div> <div class="pagegridcell"> <div> <h6>CUHK Self Regulation Lab</h6> (June 2016 - August 2016) <p style="text-align: left"> <br> <b>Focus:</b> Exploring Emotion and Self Regulation in Mobile Usage <br><br> <button class="booklink" onclick="transitionToPage('./Projects/cuhk.html')"><b>Click to learn more</b></button></p> </div> </div> </div> </div> </div> </div> <!-- HKBN --> <div> <div style="height: 100%; display: flex; justify-content: center; align-items: center"> <div class="pagecontent"> <div class="pagegrid"> <div class="pagegridcells"> <img src="http://61.92.45.75/new/images/3.0/hkbn-logo.png" style="width: 80%"> </div> <div class="pagegridcell"> <div> <h6>HKBN IT Business Intern</h6> (June 2017 - August 2017) <p style="text-align: left"> <br> <b>Focus:</b> Exploring user experience with online transactions and customer service <br><br> <button class="booklink" onclick="transitionToPage('./Projects/hkbn.html')"><b>Click to learn more</b></button></p> </div> </div> </div> </div> </div> </div> <div class="hard"> <div style="height: 100%; width: 100%; background-image:url(https://live.staticflickr.com/4103/5032206759_e0b3c4f45a_b.jpg); background-color: rgba(255,255,255, 0.3)"></div> </div> <div class="hard"> <div style="height: 100%; width: 100%; background-image:url(https://live.staticflickr.com/4103/5032206759_e0b3c4f45a_b.jpg); -webkit-transform: rotate(180deg); background-color: rgba(255,255,255, 0.3)"></div> </div> </div> </div> </div>`; $("#research-book").append(str); }; function loadApp() { reloadScripts(); // Create the flipbook // Get Dimensions of Screen var w = window.innerWidth * .5; var h = w/2 * 1.3; $('.flipbook').css({marginLeft: w/4}); $('.flipbook').turn({ // Width width:w, // Height height:h, // Elevation elevation: 50, // Enable gradients gradients: true, // Auto center this flipbook autoCenter: false }); } // Load the HTML4 version if there's not CSS transform yepnope({ test : Modernizr.csstransforms, yep: ['./JS/lib/turn.js'], nope: ['./JS/lib/turn.html4.min.js'], both: ['./style.css'], complete: loadApp }); // Window Resize Event window.addEventListener("resize", loadApp); }) })(jQuery);
var _ = require("underscore"); var winston = require("winston"); var LastFmDao = (function () { var lastfmNode; function LastFmDao(lfmNode) { lastfmNode = lfmNode; } LastFmDao.prototype.getSession = function (token, callback) { if (!token) { callback("Invalid token", null); return; } lastfmNode.session({ token: token, handlers: { success: function(session) { callback(null, session); return; }, error: function(error) { winston.error('getSession error', error); callback(error, null); return; } } }); }; LastFmDao.prototype.getUserInfo = function (username, callback) { lastfmNode.request("user.getInfo", { user: username, handlers: { success: function(data) { var lastfmProfileImage = null; if (data && data.user) { _.each(data.user.image, function(image) { if (image.size == 'large') { lastfmProfileImage = image['#text']; return; } }); } callback(null, { lastfmProfileImage: lastfmProfileImage }); }, error: function(err) { winston.error('getUserInfo error', err); callback(err, null); } } }); }; var makeTrackData = function(data) { if (data) { var artist = data.artist ? data.artist['#text'] : null; var name = data.name; var url = data.url; var nowPlaying = data['@attr'] && data['@attr']['nowplaying'] == 'true'; var image = null; _.each(data.image, function(curImage) { if (curImage.size == 'small') { image = curImage['#text']; return; //break } }); if (artist && name) { return { artist: artist, name: name, image: image, url: url, nowPlaying: nowPlaying }; } } return null; }; // Returns 3 most recent tracks, not including duplicate now playing/last played LastFmDao.prototype.getRecentTracks = function (username, callback) { lastfmNode.request("user.getRecentTracks", { user: username, limit: "4", // 3 plus possible duplicate handlers: { success: function(data) { if (!data || !data.recenttracks || !data.recenttracks.track) { // Only log error, do not pass back error in callback so that async.map will continue with other requests winston.error('getRecentTracks invalid data', data); callback(null, null); return; } var tracks = []; _.each(data.recenttracks.track, function(track) { var trackData = makeTrackData(track); if (trackData) { tracks.push(trackData); } }); // remove duplicate e.g. if now playing is the same as the last scrobble if (tracks.length > 1 && tracks[0].artist == tracks[1].artist && tracks[0].name == tracks[1].name) { tracks.splice(1, 1); } callback(null, tracks); }, error: function(err) { // Only log error, do not pass back error in callback so that async.map will continue with other requests winston.error('getRecentTracks error', err); callback(null, null); } } }); }; LastFmDao.prototype.getTasteometer = function (users, callback) { lastfmNode.request("tasteometer.compare", { type1: 'user', type2: 'user', value1: users.user1, value2: users.user2, handlers: { success: function(data) { if (data && data.comparison && data.comparison.result) { callback(null, data.comparison.result.score); } else { callback(null, 0); } }, error: function(err) { // Only log error, do not pass back error in callback so that async.map will continue with other requests winston.error('getTasteometer error', err); callback(null, 0); } } }); }; return LastFmDao; })(); exports.LastFmDao = LastFmDao;
goog.provide('animatejs.Frame'); /** * Frame defines a state of properties at certain time * @param {number} at defines the time value from the beginning of the animation * @param {Object} properties current properties values (key=value pairs) * @param {Array.<string>} changedProperties names of properties changed from last frame * @param {animatejs.KeyFrame} nextKeyFrame * @param {animatejs.KeyFrame} prevKeyFrame * @constructor * @export */ animatejs.Frame = function(at, properties, changedProperties, nextKeyFrame, prevKeyFrame) { 'use strict'; /** * Time of frame (from the beginning of the animation) * @type {number} */ this['at'] = at; /** * Properties and their values at current time * @type {Object} * */ this['properties'] = properties; /** * List of property names which has changed comparing to last frame * @type {Array.<string>} */ this['changedProperties'] = changedProperties; /** * Next key frame * @type {animatejs.KeyFrame} */ this['nextKeyFrame'] = nextKeyFrame; /** * Previouse key frame * @type {animatejs.KeyFrame} */ this['prevKeyFrame'] = prevKeyFrame; };
import { compose } from 'react-apollo' import Component from './StoryGroupSelector.component.js' import query from '../../../apollo/queries/organization' import { withRouter } from 'next/router' import storyQuery from '../../../apollo/queries/story' import editStory from '../../../apollo/mutations/editStory' let ExportComponent = Component ExportComponent = compose(storyQuery, editStory, query)(ExportComponent) ExportComponent = withRouter(ExportComponent) export default ExportComponent
'use strict'; var lib = require('./lib'); var argSetMulti = function(opt, arg, key, map) { if(opt.multiArg) { let existing = map.get(key); if(!existing) { map.set(key, [arg]); } else if(existing instanceof Array) { existing.push(arg); } } else { map.set(key, arg); } } var optArgProcess = function(oStr, opt, cmd, res, incrArrCountFn, userInputArg) { let argSet = function(arg) { let map = cmd? res.optArg: res.goptArg; if(opt.short) { argSetMulti(opt, arg, opt.short, map); } if(opt.long) { argSetMulti(opt, arg, opt.long, map); } } let oArg = userInputArg(); if(oArg) { if(!oArg.startsWith('-')) { argSet(oArg); incrArrCountFn(); } else if(opt.defaultArg) { argSet(opt.defaultArg); } else { throw `Argument expected for option: ${oStr}.`; } } else if(opt.defaultArg) { argSet(opt.defaultArg); } else { throw `Argument expected for option: ${oStr}.`; } } module.exports = function(prg, arr) { var res = { cmd: null, gopts: new Set(), opts: new Set(), goptArg: new Map(), optArg: new Map(), args: [] }; var cmd = null; for(let i=0; i<arr.length; i++) { let item = arr[i]; let set = cmd? res.opts: res.gopts; let incrArrCountFn = function(){i++;} if(item.startsWith('--')) { // long option let oStr = lib.cleanOpt(item); let o = cmd? cmd.getOpt(oStr): prg.getOpt(oStr); if(o) { if(o.short) set.add(o.short); if(o.long) set.add(o.long); if(o.hasArg) { let userInputArg = function() { if((i+1)<arr.length) return arr[i+1]; return null; } optArgProcess(oStr, o, cmd, res, incrArrCountFn, userInputArg); } } else { if(cmd) throw `Unrecognized option ${item} for command ${res.cmd}.`; else throw `Unrecognized global option: ${item}.`; } } else if(item.startsWith('-')) { // short option let shortOpts = lib.cleanOpt(item).split(''); // each char in short opt represents a opt for(let j=0; j<shortOpts.length; j++) { let oStr = shortOpts[j]; let o = cmd? cmd.getOpt(oStr): prg.getOpt(oStr); if(o) { if(o.short) set.add(o.short); if(o.long) set.add(o.long); if(o.hasArg) { let userInputArg = function() { if(((j+1)==shortOpts.length) && ((i+1)<arr.length)) { return arr[i+1]; } return null; } optArgProcess(oStr, o, cmd, res, incrArrCountFn, userInputArg); } } else { if(cmd) throw `Unrecognized option ${oStr} for command ${res.cmd}.`; else throw `Unrecognized global option: ${oStr}.`; } } } else { // command || args if(!cmd && prg.cmds.length > 0) { cmd = prg.getCmd(item); if(cmd) { res.cmd = item; } else { throw `Unrecognized command: ${item}.`; } } else { res.args.push(item); } } } // isMandatory option check: // 1. Command opts: if(cmd) { lib.mandatoryOptCheck(cmd.opts, res.opts); } // 2. Global opts: // Global mandatory opts check need to be done only when the given command // has noMandatoryOptCheck set to false. if(cmd) { if(cmd.noMandatoryOptCheck === false) { lib.mandatoryOptCheck(prg.opts, res.gopts); } } else { lib.mandatoryOptCheck(prg.opts, res.gopts); } // Finally! return res; }