text
stringlengths
7
3.69M
import React from 'react'; import Helmet from 'react-helmet'; import BgImage from '../components/BgImage'; export default function Template({ data }) { const projects = data.projects.edges.map(project => { let image = project.node.childMarkdownRemark.frontmatter.projectId; return ( <article className="container--projects__project" key={project.node.childMarkdownRemark.frontmatter.path}> <BgImage css={{ top: 0, left: 0, right: 0, zIndex: -1 }} style={{ position: `absolute` }} sizes={data[image].sizes} /> <a title={project.node.childMarkdownRemark.frontmatter.title} href={project.node.childMarkdownRemark.frontmatter.path}> <h3 className="container--projects__project__title"><span>{project.node.childMarkdownRemark.frontmatter.title}</span></h3> </a> </article> ); }); return ( <main className="container container--projects"> <Helmet title={`Jen Downs - Projects`} /> {projects} </main> ); } export const pageQuery = graphql` query Projects { projects: allFile( filter: { sourceInstanceName: { eq: "projects" }, extension: { eq: "md" } } ) { edges { node { childMarkdownRemark { frontmatter { title path projectId } } } } } cah: imageSharp(id: { regex: "/cah/" }){ sizes( maxWidth: 900, quality: 100, duotone: { highlight: "#edfafa", shadow: "#4a00e0" } ) { ...GatsbyImageSharpSizes } } wam: imageSharp(id: { regex: "/mammoth/" }){ sizes( maxWidth: 900, quality: 100, duotone: { highlight: "#edfafa", shadow: "#4a00e0" } ) { ...GatsbyImageSharpSizes } } gallery: imageSharp(id: { regex: "/ogre/" }){ sizes( maxWidth: 900, quality: 100, duotone: { highlight: "#edfafa", shadow: "#4a00e0" } ) { ...GatsbyImageSharpSizes } } } `;
function myOpenFunction() { document.getElementById("open").click(); } function colorChangeFunction() { document.getElementById("color").click(); } function bgColorChangeFunction() { document.getElementById("bg-color").click(); }
import { SYMBOL, OBJECT } from "reshow-constant"; import typeIs from "./getTypeOf"; const _typeof = (o) => (SYMBOL === typeIs(o) ? SYMBOL : typeIs(o, OBJECT)); export default _typeof;
import React from "react"; import Landing from './Landing'; import Navigation from "./Navigation"; import About from './About'; import { BrowserRouter, Route, Switch, Link } from "react-router-dom"; const NotFoundPage = () => ( <div> 404 - <Link to="/">Go home</Link> </div> ); const AppRouter = () => ( <BrowserRouter> <div> <Navigation /> <Switch> <Route path="/" exact={true} component={Landing} /> <Route path="/" component={About} /> {/* <Route path="/home/blog" component={Blog} /> */} {/* <Route path="/home" component={Blog} /> <Route path="/about" exact={true} component={About} /> */} <Route component={NotFoundPage} /> </Switch> </div> </BrowserRouter> ); export default AppRouter;
let element; let context; let imageFromCanvas; let resetButton; let trainButton; const model = tf.sequential(); const out = tf.tensor2d([[1, 0, 0, 0, 0, 0, 0, 0, 0, 0]]); function setup() { let x = createCanvas(28, 28); element = x.canvas; context = element.getContext("2d"); background(0); resetButton = createButton("Reset"); trainButton = createButton("Train"); resetButton.position(0, 100); trainButton.position(50, 100); resetButton.mousePressed(resetFunction); trainButton.mousePressed(trainFunction); model.add( tf.layers.conv2d({ inputShape: [28, 28, 3], kernelSize: 5, filters: 8, strides: 1, activation: "relu", kernelInitializer: "VarianceScaling" }) ); model.add( tf.layers.maxPooling2d({ poolSize: [2, 2], strides: [2, 2] }) ); model.add( tf.layers.conv2d({ kernelSize: 5, filters: 16, strides: 1, activation: "relu", kernelInitializer: "VarianceScaling" }) ); model.add( tf.layers.maxPooling2d({ poolSize: [2, 2], strides: [2, 2] }) ); model.add(tf.layers.flatten()); model.add( tf.layers.dense({ units: 10, kernelInitializer: "VarianceScaling", activation: "softmax" }) ); const LEARNING_RATE = 0.15; const optimizer = tf.train.sgd(LEARNING_RATE); model.compile({ optimizer: optimizer, loss: "categoricalCrossentropy", metrics: ["accuracy"] }); } function resetFunction() { imageFromCanvas = tf.reshape(tf.fromPixels(element),[1,28,28,3]); imageFromCanvas.dtype = "float32"; imageFromCanvas.div(tf.scalar(255)); model.predict(imageFromCanvas).print() background(0) } function trainFunction() { imageFromCanvas = tf.reshape(tf.fromPixels(element),[1,28,28,3]); imageFromCanvas.dtype = "float32"; imageFromCanvas.div(tf.scalar(255)); model.fit(imageFromCanvas,out,{epochs:1}).then((his)=>{ console.log(his.history.loss); background(0); }) } function draw() {} function mouseDragged() { stroke(255); strokeWeight(2); line(mouseX, mouseY, pmouseX, pmouseY); }
var macros________8h____8js__8js_8js = [ [ "macros____8h__8js_8js", "macros________8h____8js__8js_8js.html#adcdb6ad4e664399360f9af834012a172", null ] ];
import { Typography } from "@material-ui/core"; import { Container, Divider } from "@material-ui/core"; import React from "react"; import LoginButton from "./LoginButton"; function PleaseLogin() { return ( <Container maxWidth="sm" justify="center" align="center"> <Container style={{ marginTop: "20vh" }}> <Typography variant="h2" gutterBottom> Noki.ai </Typography> <Typography variant="body" gutterBottom> Please log in to continue using the app. <Divider/> {/* Below is for testing backend comm */} </Typography> <Divider style={{ margin: 20 }} /> <LoginButton color="primary" variant="contained" /> </Container> </Container> ); } export default PleaseLogin;
import { LitElement, html, css, customElement, } from 'lit-element'; @customElement('lilac-overlay-actions') class OverlayActions extends LitElement { static get styles() { return css` :host { width: 100%; } .actions { display: flex; flex-direction: column; align-items: stretch; } ::slotted(:not(:first-child)) { margin-top: 1rem; } `; } render() { return html` <div class="actions"> <slot></slot> </div> `; } } export { OverlayActions };
#!/usr/bin/env node var cli = require('commander'); var Promise = require('bluebird'); var invariant = require('invariant'); var converter = require('../lib').default; var templates = require('../lib/templates'); cli .version('0.0.1') .option('-i, --input <path>', 'input path to your SVG files') .option('-o, --output <path>', 'output path for your generated React components') .option('-t, --template [value]', 'template that you want to generate [reactDefault, reactFunction]') .parse(process.argv); var template = cli.template || 'reactDefault'; var component = template === 'reactDefault' ? true : false; invariant(cli.input, 'You need to specify an input path'); invariant(cli.output, 'You need to specify an output path'); invariant(templates[template], 'Specify a valid template, one of [reactDefault, reactFunction]'); Promise.resolve(converter(cli.input, cli.output, templates[template], component));
import React from "react"; import AfegeixParticipants from "./AfegeixParticipants"; import AfegeixTaulell from "./AfegeixTaulell"; import LlistaParticipants from "./LlistaParticipants"; class Formulari extends React.Component { state = {open: 'hidden'}; openModal (value){ const modalState = value ? 'visible' : 'hidden'; this.setState({open: modalState}); }; render() { return ( <div> <div className="boto-afegir" onClick={() => this.openModal(true)}>Afegir</div> <div className="my-modal" style={{visibility: this.state.open}}> <div className="my-modal-overlay"></div> <div className="my-modal-content"> <div className="modal-header"></div> <div className="modal-content"> <AfegeixTaulell addImage={this.props.settings.addTaulell}></AfegeixTaulell> <AfegeixParticipants addPlayer={this.props.settings.addPlayer}></AfegeixParticipants> <LlistaParticipants settings={this.props.settings}></LlistaParticipants> </div> <div className="modal-actions"> <button onClick={() => this.openModal(false)}>Close</button> </div> </div> </div> </div> ) } } export default Formulari;
/** * Created by Ratnesh on 13/09/2019. */ import React from "react"; import BaseComponent from '../baseComponent' import LoginComponent from './loginComponent' import Utils, {dispatchAction} from "../../utility"; import {eventConstants, pathConstants, stringConstants} from "../../constants"; import {history} from "../../managers/history"; import {UserService} from "../../services"; import connect from "react-redux/es/connect/connect"; import Parser from "../../utility/parser"; class Login extends BaseComponent { constructor(props) { super(props); this.state = { email: "", emailError: "", password: "", passwordError: "", isPasswordVisible: false, } } componentDidMount() { } onChangeEvent = (event) => { this.setState({[event.target.id]: event.target.value}); }; togglePassword = (event) => { this.setState({isPasswordVisible: !this.state.isPasswordVisible}); }; validateLoginForm = () => { this.setState({ emailError: Utils.validateEmail(this.state.email) ? "" : stringConstants.INVALID_EMAIL, passwordError: Utils.isPasswordValid(this.state.password) ? "" : stringConstants.PASSWORD_VALIDATION }); return Utils.validateEmail(this.state.email) && Utils.isPasswordValid(this.state.password); }; onLoginClicked = async (event) => { event.preventDefault(); if (!this.validateLoginForm()) return; this.props.dispatchAction(eventConstants.SHOW_LOADER); /** * Login API Call */ /*let requestData = {}; requestData.emailID = this.state.email; requestData.password = this.state.password; requestData.deviceID = this.props.user.deviceID; let [error, response] = await Utils.parseResponse(UserService.loginUser(requestData)); this.props.dispatchAction(eventConstants.HIDE_LOADER); if (error) { Utils.consoleLogger("error", error); return } this.props.dispatchAction(eventConstants.LOGIN_SUCCESS, response);*/ /** * Dummy Login Success action dispatch! * Saves User Data and hides Loader. */ this.props.dispatchAction(eventConstants.LOGIN_SUCCESS, Utils.generateDummyUserDataWithSessionToken()); history.push(pathConstants.DASHBOARD); //TODO Keep track on history methods }; render() { return ( <LoginComponent state={this.state} onChangeEvent={this.onChangeEvent} togglePassword={this.togglePassword} onLoginClicked={this.onLoginClicked}/> ); } } const mapStateToProps = (state) => { return {user: state.user} }; export default connect(mapStateToProps, {dispatchAction})(Login);
import * as action_types from './action_types'; import {console_log} from "../utils/helper"; export const addChannelHistory = (channels) => { return { type: action_types.ADD_HISTORY_CHANNEL, data: channels } }; export const addVideoHistory = (videos) => { return { type: action_types.ADD_HISTORY_VIDEO, data: videos } }; export const addShowHistory = (shows) => { return { type: action_types.ADD_HISTORY_SHOW, data: shows } }; export const clearHistory = () => { return { type: action_types.CLEAR_HISTORY } };
var faker = require('faker'); const db = require('../database'); var fakeArr =[] for (let i=0;i<=99;i++) { var fakeObj= {}; fakeObj.textContent = faker.lorem.sentence(); fakeObj.dateCreated = new Date().toISOString().slice(0, 19).replace('T', ' '); fakeObj.user = faker.random.word() + faker.random.number({min:1,max:999}); fakeObj.idParentComment = 0; fakeArr.push(fakeObj); } // var storeManyFakeData = function(commentArr) { db.AddMany(commentArr, (err,comment)=> { if (err) {console.log(err);throw err;} else {console.log('they got added');} } ) } storeManyFakeData(fakeArr);
var MongoClient = require('mongodb').MongoClient; module.exports = function(url) { return function(callback) { MongoClient.connect(url, callback); }; };
const sum = require('./join') test('joins "apple" and "banana" to be "applebanana"', () => { expect(sum('apple', 'banana')).toBe('applebanana') }) // This test will fail. test('joins "Na" and "Cl" to be "salt"', () => { expect(sum('Na', 'Cl')).toBe('salt') })
(function () { angular .module('myApp') .controller('uploadListController', uploadListController) uploadListController.$inject = ['$state', '$scope', '$rootScope']; function uploadListController($state, $scope, $rootScope) { $rootScope.setData('showMenubar', true); $rootScope.setData('backUrl', 'teacherGroup'); $scope.init = function () { $rootScope.setData('loadingfinished', false); $scope.fields = ["No", "Email", "Group", "Tutorial Set", "Tutorial", "Team Set", "Team", "Result", "Gender", "Institution", "Age", "Language", "Nationality", "Other"]; $scope.resultFields = ["Email", "Group", "Tutorial Set", "Tutorial", "Team Set", "Team"]; $scope.list = []; $scope.getUsers(); } $scope.getUsers = function () { var usersRef = firebase.database().ref('Users').orderByChild('Usertype').equalTo('Student'); usersRef.on('value', function (snapshot) { $scope.users = {}; if (snapshot.val()) { snapshot.forEach(function (childsnapshot) { $scope.users[childsnapshot.key] = childsnapshot.val(); }); } $scope.getGroups(); }); } $scope.getGroups = function () { var groupdata = firebase.database().ref('Groups').orderByChild('teacherKey').equalTo($rootScope.settings.userId); groupdata.on('value', function (snapshot) { $scope.groups = snapshot.val() || {}; $scope.getSharedGroups(); }); } $scope.getSharedGroups = function () { var shareRef = firebase.database().ref('SharedList/' + $rootScope.settings.userId); shareRef.once('value', function (snapshot) { var count = 0; if (snapshot.val()) { for (var fromKey in snapshot.val()) { var fromTeacher = snapshot.val()[fromKey]; for (var groupKey in fromTeacher) { count++; var groupRef = firebase.database().ref('Groups/' + groupKey); groupRef.on('value', function (snapshot) { count--; if (snapshot.val()) { $scope.groups[groupKey] = snapshot.val(); $scope.groups[groupKey].teacherId = fromKey; } if (count <= 0) { $scope.getStudentGroups(); } }); } } } if (count <= 0) { $scope.getStudentGroups(); } }); } $scope.getStudentGroups = function () { var groupRef = firebase.database().ref('StudentGroups'); groupRef.once('value', function (studentGroups) { $scope.studentsInGroup = studentGroups.val() || {}; $rootScope.setData('loadingfinished', true); $rootScope.safeApply(); }) } $scope.showUploadModal = function () { $('#uploadModal').modal({ backdrop: 'static', keyboard: false }); } $scope.file_changed = function (element) { $scope.uploadData = {}; var file = element.files[0]; $scope.filename = file.name; var uploader = document.getElementById('uploader'); uploader.value = 10; var reader = new FileReader(); reader.readAsBinaryString(file); uploader.value = 20; reader.onload = function (evt) { $scope.$apply(function () { uploader.value = 50; var data = evt.target.result; var workbook = XLSX.read(data, { type: 'binary' }); $scope.default_group = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]])[0]; uploader.value = 70; var headerNames = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[1]], { header: 1 })[0]; $scope.list = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[1]]); $scope.fields = []; headerNames.forEach(function (h) { $scope.fields.push(h); }); $scope.resultList = undefined; uploader.value = 100; }); }; } $scope.applyUpload = function () { // if (!confirm("Are you sure want to apply this table data?")) return; var updates = {}; $scope.resultList = []; for (var i = 0; i < $scope.list.length; i++) { var student = $scope.list[i]; student.Result = "Failed"; var result = { Email: { result: '-', class: 'Failed', }, Group: { result: '--', class: 'Failed' }, 'Tutorial Set': { result: '--', class: 'Failed' }, 'Tutorial': { result: '--', class: 'Failed' }, 'Team Set': { result: '--', class: 'Failed' }, 'Team': { result: '--', class: 'Failed' } } //============================================================================= // check email //============================================================================ if (!student.Email) { result.Email.result = 'Email Missed !'; $scope.resultList.push(result); continue; } student['Email'] = student['Email'].trim(); result.Email.result = "Unregistered!"; for (var key in $scope.users) { var user = $scope.users[key]; if (user.ID == student['Email']) { student.userKey = key; result.Email = { result: "Checked!", class: 'Success' } } } if (result.Email.result == 'Checked!') { if (student.Gender) updates['Users/' + student.userKey + '/gender'] = student.Gender if (student.Institution) updates['Users/' + student.userKey + '/institution'] = student.Institution if (student.Age) updates['Users/' + student.userKey + '/age'] = student.Age if (student.Language) updates['Users/' + student.userKey + '/countrylanguage'] = student.Language if (student.Nationality) updates['Users/' + student.userKey + '/country'] = student.Nationality if (student.Other) updates['Users/' + student.userKey + '/other'] = student.Other } if (result.Email.class == 'Failed') { $scope.resultList.push(result); continue; } //============================================================================= // check group //============================================================================ var groupName = student.Group ? student.Group : $scope.default_group['Group']; // check group name if (!groupName) { result.Group.result = 'Unspecified!'; $scope.resultList.push(result); continue; } groupName = groupName.trim(); // check group exist var existGroup = false; var group = undefined; for (key in $scope.groups) { group = $scope.groups[key]; if (group.groupname == groupName) { student.groupKey = key; existGroup = true; break; } } if (!existGroup) { result.Group.result = 'Unknown Group!'; $scope.resultList.push(result); continue; } // check if joined to group $scope.studentsInGroup[student.userKey] = $scope.studentsInGroup[student.userKey] || {}; var userGroups = $scope.studentsInGroup[student.userKey]; if (Object.values(userGroups).indexOf(student.groupKey) > -1) { result.Group.result = 'Already Joined to "' + groupName + '"!'; result.Group.class = 'Success'; } else { var ref = firebase.database().ref('/StudentGroups/' + student.userKey); var refKey = ref.push().key; userGroups[refKey] = student.groupKey; updates['/StudentGroups/' + student.userKey + '/' + ref.push().key] = student.groupKey; result.Group.result = 'Join success to "' + groupName + '"!'; result.Group.class = 'New'; } //============================================================================= // check groupset //============================================================================ var teacherKey = group.teacherId ? group.teacherId : $rootScope.settings.userId; var setName = student['Tutorial Set'] ? student['Tutorial Set'] : $scope.default_group['Tutorial Set']; if (!setName) { result['Tutorial Set'].result = 'Unspecified!'; $scope.resultList.push(result); continue; } setName = setName.trim(); // check groupset exist group.groupsets = group.groupsets || {}; var groupset = undefined; var existGroupset = false; for (key in group.groupsets) { groupset = group.groupsets[key]; if (groupset.name == setName) { student.setKey = key; existGroupset = true; break; } } if (!existGroupset) { result['Tutorial Set'].result = 'Unknown GroupSet!'; $scope.resultList.push(result); continue; } // check if joined to groupset var setData = groupset.data; setData.members = setData.members || []; // check set index var childGroup = undefined; var joinedTutorialIndex = -1; var setIndex = 'auto'; if (student['Tutorial']) { student['Tutorial'] = student['Tutorial'].trim(); setIndex = undefined; for (var gi = 0; gi < setData.groups.length; gi++) { if (setData.groups[gi].name == undefined) { setData.groups[gi].name = groupset.name + ' ' + (gi + 1); } if (setData.groups[gi].name == student['Tutorial']) { setIndex = gi; } } } // get joined groupset for (var gi = 0; gi < setData.groups.length; gi++) { setData.groups[gi].members = setData.groups[gi].members || []; if (setData.groups[gi].members.indexOf(student.userKey) > -1) { joinedTutorialIndex = gi; break; } } if (setData.members.indexOf(student.userKey) > -1) {//********** if joined subgroup result['Tutorial Set'].result = 'Already Joined to "' + setName + '"!'; result['Tutorial Set'].class = 'Success'; switch (setIndex) { case undefined: result['Tutorial'].result = 'Unknown Tutorial Name!'; break; case 'auto': setIndex = joinedTutorialIndex childGroup = setData.groups[setIndex]; result['Tutorial'].result = 'Already joined to "' + setData.groups[setIndex].name + '"'; result['Tutorial'].class = 'Success'; break; default: if (setData.groups[setIndex].members.indexOf(student.userKey) > -1) { childGroup = setData.groups[setIndex]; result['Tutorial'].result = 'Already joined to "' + setData.groups[setIndex].name + '"'; result['Tutorial'].class = 'Success'; } else { if (groupset.exclusive) { result['Tutorial'].result = 'Already joined to "' + setData.groups[joinedTutorialIndex].name + '"'; } else { if (groupset.max_member > setData.groups[setIndex].member_count) { setData.groups[setIndex].member_count++; setData.groups[setIndex].members.push(student.userKey); childGroup = setData.groups[setIndex]; updates['/Groups/' + teacherKey + '/' + student.groupKey + '/groupsets/' + student.setKey + '/data/groups/' + setIndex + '/member_count'] = childGroup.member_count; updates['/Groups/' + teacherKey + '/' + student.groupKey + '/groupsets/' + student.setKey + '/data/groups/' + setIndex + '/members'] = childGroup.members; result['Tutorial'].result = 'Joined to "' + setData.groups[setIndex].name + '"'; result['Tutorial'].class = 'New'; } else { result['Tutorial'].result = '"' + setData.groups[setIndex].name + '" is full.'; } } } break; } if (!childGroup) { $scope.resultList.push(result); continue; } } else { // if************ unjoined subgroup switch (setIndex) { case undefined: result['Tutorial'].result = 'Unknown Tutorial Name!'; break; case 'auto': for (var gi = 0; gi < setData.groups.length; gi++) { if (groupset.max_member > setData.groups[gi].member_count) { setIndex = gi; childGroup = setData.groups[gi]; childGroup.member_count++; childGroup.members = setData.groups[gi].members || []; childGroup.members.push(student.userKey); updates['/Groups/' + teacherKey + '/' + student.groupKey + '/groupsets/' + student.setKey + '/data/groups/' + gi + '/member_count'] = childGroup.member_count; updates['/Groups/' + teacherKey + '/' + student.groupKey + '/groupsets/' + student.setKey + '/data/groups/' + gi + '/members'] = childGroup.members; result['Tutorial'].result = 'Joined to "' + setData.groups[setIndex].name + '"'; result['Tutorial'].class = 'New'; break; } } if (!childGroup) { result['Tutorial'].result = 'All tutorials are fulled!'; result['Tutorial'].class = 'Failed'; } break; default: //specified index if (groupset.max_member > setData.groups[setIndex].member_count) { setData.groups[setIndex].member_count++; setData.groups[setIndex].members.push(student.userKey); childGroup = setData.groups[setIndex]; updates['/Groups/' + teacherKey + '/' + student.groupKey + '/groupsets/' + student.setKey + '/data/groups/' + setIndex + '/member_count'] = childGroup.member_count; updates['/Groups/' + teacherKey + '/' + student.groupKey + '/groupsets/' + student.setKey + '/data/groups/' + setIndex + '/members'] = childGroup.members; result['Tutorial'].result = 'Joined to (' + setData.groups[setIndex].name + ')'; result['Tutorial'].class = 'New'; } else { result['Tutorial'].result = '"' + setData.groups[setIndex].name + '" is full.'; } break; } if (!childGroup) { result['Tutorial Set'].result = 'Join Failed!'; $scope.resultList.push(result); continue; } else { setData.member_count++; setData.members.push(student.userKey); updates['/Groups/' + teacherKey + '/' + student.groupKey + '/groupsets/' + student.setKey + '/data/member_count'] = setData.member_count; updates['/Groups/' + teacherKey + '/' + student.groupKey + '/groupsets/' + student.setKey + '/data/members'] = setData.members; result['Tutorial Set'].result = 'Joined to "' + setData.groups[setIndex].name + '"'; result['Tutorial Set'].class = 'New'; } } //============================================================================= // check sub groupset //============================================================================ var subsetName = student['Team Set'] ? student['Team Set'] : $scope.default_group['Team Set']; if (!subsetName) { result['Team Set'].result = 'Unspecified!'; $scope.resultList.push(result); continue; } subsetName = subsetName.trim(); // check subgroupset exist groupset.subgroupsets = groupset.subgroupsets || {}; var subgroupset = undefined; var existSubGroupset = false; for (key in groupset.subgroupsets) { subgroupset = groupset.subgroupsets[key]; if (subgroupset.name == subsetName) { student.subSetKey = key; existSubGroupset = true; break; } } if (!existSubGroupset) { result['Team Set'].result = 'Team Set Name!'; $scope.resultList.push(result); continue; } // check if joined to subgroupset // childGroup is joined subgroup var subSetData = childGroup.subgroupsets[student.subSetKey]; subSetData.members = subSetData.members || []; // check Tutorial var childSubGroup = undefined; var joinedSubGroupsetIndex = -1; var subSetIndex = 'auto'; if (student['Team']) { student['Team'] = student['Team'].trim(); subSetIndex = undefined; for (var gi = 0; gi < subSetData.groups.length; gi++) { if (subSetData.groups[gi].name == undefined) { subSetData.groups[gi].name = groupset.name + ' ' + (gi + 1); } if (subSetData.groups[gi].name == student['Team']) { subSetIndex = gi; } } } // get joined subgroupset for (var gi = 0; gi < subSetData.groups.length; gi++) { subSetData.groups[gi].members = subSetData.groups[gi].members || []; if (subSetData.groups[gi].members.indexOf(student.userKey) > -1) { joinedSubGroupsetIndex = gi; break; } } if (subSetData.members.indexOf(student.userKey) > -1) {//********** if joined secondsubgroup result['Team Set'].result = 'Already Joined to "' + subsetName + '"!'; result['Team Set'].class = 'Success'; switch (subSetIndex) { case undefined: result['Team'].result = 'Unknown team name!'; break; case 'auto': subSetIndex = joinedSubGroupsetIndex childSubGroup = subSetData.groups[subSetIndex]; result['Team'].result = 'Already joined to "' + subSetData.groups[subSetIndex].name + '"'; result['Team'].class = 'Success'; break; default: if (subSetData.groups[subSetIndex].members.indexOf(student.userKey) > -1) { childSubGroup = subSetData.groups[subSetIndex]; result['Team'].result = 'Already joined to "' + subSetData.groups[subSetIndex].name + '"'; result['Team'].class = 'Success'; } else { if (subgroupset.exclusive) { result['Team'].result = 'Already joined to "' + subSetData.groups[joinedSubGroupsetIndex].name + '"'; } else { if (subgroupset.max_member > subSetData.groups[subSetIndex].member_count) { subSetData.groups[subSetIndex].member_count++; subSetData.groups[subSetIndex].members.push(student.userKey); childSubGroup = subSetData.groups[subSetIndex]; updates['/Groups/' + teacherKey + '/' + student.groupKey + '/groupsets/' + student.setKey + '/data/groups/' + setIndex + '/subgroupsets/' + student.subSetKey + '/groups/' + subSetIndex + '/member_count'] = childSubGroup.member_count; updates['/Groups/' + teacherKey + '/' + student.groupKey + '/groupsets/' + student.setKey + '/data/groups/' + setIndex + '/subgroupsets/' + student.subSetKey + '/groups/' + subSetIndex + '/members'] = childSubGroup.members; result['Team'].result = 'Joined to "' + subSetData.groups[subSetIndex].name + '"'; result['Team'].class = 'New'; } else { result['Team'].result = '"' + subSetData.groups[subSetIndex].name + '" is full.'; } } } break; } if (!childSubGroup) { $scope.resultList.push(result); continue; } } else { // if************ unjoined subgroup switch (subSetIndex) { case undefined: result['Team'].result = 'Unknown team name!'; break; case 'auto': for (var gi = 0; gi < subSetData.groups.length; gi++) { if (groupset.max_member > subSetData.groups[gi].member_count) { subSetIndex = gi; childSubGroup = subSetData.groups[gi]; childSubGroup.member_count++; childSubGroup.members = subSetData.groups[gi].members || []; childSubGroup.members.push(student.userKey); updates['/Groups/' + teacherKey + '/' + student.groupKey + '/groupsets/' + student.setKey + '/data/groups/' + setIndex + '/subgroupsets/' + student.subSetKey + '/groups/' + gi + '/member_count'] = childSubGroup.member_count; updates['/Groups/' + teacherKey + '/' + student.groupKey + '/groupsets/' + student.setKey + '/data/groups/' + setIndex + '/subgroupsets/' + student.subSetKey + '/groups/' + gi + '/members'] = childSubGroup.members; result['Team'].result = 'Joined to "' + subSetData.groups[subSetIndex].name + '"'; result['Team'].class = 'New'; break; } } if (!childSubGroup) { result['Team'].result = 'All teams are fulled!'; result['Team'].class = 'Failed'; } break; default: //specified index if (subgroupset.max_member > subSetData.groups[subSetIndex].member_count) { subSetData.groups[subSetIndex].member_count++; subSetData.groups[subSetIndex].members.push(student.userKey); childSubGroup = subSetData.groups[subSetIndex]; updates['/Groups/' + teacherKey + '/' + student.groupKey + '/groupsets/' + student.setKey + '/data/groups/' + setIndex + '/subgroupsets/' + student.subSetKey + '/groups/' + subSetIndex + '/member_count'] = childSubGroup.member_count; updates['/Groups/' + teacherKey + '/' + student.groupKey + '/groupsets/' + student.setKey + '/data/groups/' + setIndex + '/subgroupsets/' + student.subSetKey + '/groups/' + subSetIndex + '/members'] = childSubGroup.members; result['Team'].result = 'Joined to "' + subSetData.groups[subSetIndex].name + '"'; result['Team'].class = 'New'; } else { result['Team'].result = '"' + subSetData.groups[subSetIndex].name + '" is full.'; } break; } if (!childSubGroup) { result['Team Set'].result = 'Join Failed!'; $scope.resultList.push(result); continue; } else { subSetData.member_count++; subSetData.members.push(student.userKey); updates['/Groups/' + teacherKey + '/' + student.groupKey + '/groupsets/' + student.setKey + '/data/groups/' + setIndex + '/subgroupsets/' + student.subSetKey + '/member_count'] = setData.member_count; updates['/Groups/' + teacherKey + '/' + student.groupKey + '/groupsets/' + student.setKey + '/data/groups/' + setIndex + '/subgroupsets/' + student.subSetKey + '/members'] = setData.members; result['Team Set'].result = 'Joined to "' + setName + '"!'; result['Team Set'].class = 'New'; } } if (childSubGroup) { student.Result = "Success"; } $scope.resultList.push(result); } firebase.database().ref().update(updates).then(function () { $rootScope.success('Upload finished!'); }); $rootScope.safeApply(); } $scope.getClass = function (field, user) { if (field != 'Result') return ''; return user['Result']; } $scope.getRowSpan = function (index) { if (!$scope.resultList) return 1; if (index > 0 && index < $scope.fields.length - 1) return 1; return 2; } } })();
var mainConfig = exports.mainConfig = function(){ var mainConfig = new Object(); mainConfig.production = true; mainConfig.revision = "1.0.6"; return mainConfig; } var mailConfig = exports.mailConfig = function(){ var mailConfig = new Object(); mailConfig.sendGridApiKey = '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'; mailConfig.fromName = 'Simple Bike'; mailConfig.from = 'hello@simple.bike'; mailConfig.adminEmail = 'shiweifong@gmail.com'; return mailConfig; }
var Stack = require('./stack').Stack; // Implement Queue using two Stacks var Queue = (function() { function Queue () { this.inbox = new Stack(); this.outbox = new Stack(); } Queue.prototype = { constructor: Queue, enqueue: function(entry) { if (entry === null || entry === undefined) { return false; } this.inbox.push(entry); return true; }, dequeue: function() { return (this.peek() === null ? null : this.outbox.pop()); }, peek: function() { if (this.isEmpty()) { return null; } if (this.outbox.isEmpty()) { while(!this.inbox.isEmpty()) { this.outbox.push(this.inbox.pop()); } } return this.outbox.peek(); }, isEmpty: function() { return (this.outbox.isEmpty() && this.inbox.isEmpty()); } }; return Queue; })(); exports.Queue = Queue;
remark.create({ sourceUrl: 'slides.md', ratio: '16:9', countIncrementalSlides: false });
//Call, Apply, Bind help us to pass object as argument function test(a,b){ console.log(this.x+this.y+a+b) } // test(10,20) //NaN //--------------Call--------------- test.call({x:5,y:6},10,20) //--------------Apply------------- test.apply({x:50,y:60},[100,200]) //-------------Bind------------- //Bind help us to store result //Process 01 let result=test.bind({x:500,y:600},1000,2000) result() //Process 02 let result2=test.bind({x:500,y:600}) result2(5000,4000)
const config = require('config'); const fs = require('fs'); const _ = require('lodash'); //console.log(config); const jsonname = './json/colors.json'; let outputObj ={}; outputObj.colors = config.colorCode.colors; _.each(outputObj.colors,(ele,idx,ary)=>{ //console.log(idx + ' : ' + ele.color); ele.no = idx + 1 }); const output = JSON.stringify(outputObj,null,'\t'); //console.log(output); fs.writeFileSync(jsonname,output);
<!-- Preloader --> $(window).load(function() { // makes sure the whole site is loaded $('#status').delay(350).fadeOut('slow'); // will first fade out the loading animation $('#preloader').delay(350).fadeOut('slow'); // will fade out the white DIV that covers the website. $('body').delay(350).css({'overflow':'visible'}); }) $(document).ready(function(){ $('.materialboxed').materialbox(); }); (function($){ $(function(){ $('.button-collapse').sideNav(); $('.parallax').parallax(); }); // end of document ready })(jQuery); // end of jQuery name space
var StellarSdk = require('stellar-sdk'); var express = require('express'); var router = express.Router(); StellarSdk.Network.usePublicNetwork(); var server = new StellarSdk.Server('https://horizon.stellar.org'); router.post('/makeTrust',async function(req,res,next){ var sourceKey = "x"; //owner public key var ResponseCode = 200; var ResponseMessage = ``; var ResponseData = null; try { if(req.body) { var ValidationCheck = true; if (!req.body.investor_key) { ResponseMessage = "Investor key is missing \n"; ValidationCheck = false; } if(ValidationCheck == true) { // account which is making trust with the token var investorkey = req.body.investor_key;//investor private key var receivingKeys = StellarSdk.Keypair.fromSecret(investorkey); var mkj = new StellarSdk.Asset('L2L', sourceKey); // change trust and submit transaction await server.loadAccount(receivingKeys.publicKey()) .then(function(receiver) { var transaction = new StellarSdk.TransactionBuilder(receiver) .addOperation(StellarSdk.Operation.changeTrust({ asset: mkj, })) .build(); transaction.sign(receivingKeys); return server.submitTransaction(transaction); }) .then(function(result) { ResponseMessage = "Completed"; ResponseCode = 200; ResponseData = "Trust Generated"; //console.log('Success! Results:', result); }) .catch(function(error) { ResponseMessage = `Trust Not Generated with the error ${error}`; ResponseCode = 400; }); } else { ResponseCode = 206 } } else { ResponseMessage = "Transaction cannot proceeds as request body is empty"; ResponseCode = 204 } } catch (error) { ResponseMessage = `Transaction stops with the error ${error}`; ResponseCode = 400 } finally { return res.status(200).json({ code : ResponseCode, data : ResponseData, msg : ResponseMessage }); } }); module.exports = router;
// Write your code here! let element = document.createElement('div') // let pTag = document.querySelector('p#greeting') // pTag.innerHTML = `"hello mendel"` // element.innerHTML =` <p>hello mendel</p>` document.body.appendChild(element) let ul = document.createElement('ul') for (let i = 0; i< 3; i++){ let li = document.createElement('li') li.innerHTML = (i + 1).toString() ul.appendChild(li) } element.appendChild(ul) element.style.textAlign = 'center'; ul.style.textAlign = 'left' // removing elements ul.removeChild(ul.querySelector('body > div > ul > li:nth-child(2)')) ul.remove() /////////////////////////////////////// let removeMain = document.querySelector('main#main') removeMain.remove() const newHeader = document.createElement("h1") newHeader.id = 'victory' newHeader.innerHTML = `"f is the champion!"` newHeader.append() // let h1Victory = document.querySelector('div') // h1Victory.innerHTML = `<h1 id="victory"></h1>`
const isPrime = test => { if(test === 2){return true} else if (test < 2) {return false} else if(test % 2 === 0 || test < 2){return false} else{ for(let i = 3; i <= Math.sqrt(test); i = i+2){ if(test % i === 0){ return false } } return true } } const permutations = list => { let output = [] if(list.length === 2){return [list,[list[1], list[0]]]} else{ list.forEach(digit => { let results = permutations(list.filter(e => e != digit)) results.forEach(result => output.push([digit, ...result])) }) return output } } const pandigitalPrimes = () => { let digits = [1,2,3] let greatest = 0 for(let i = 4; i < 10; i++){ digits.push(i) let perms = permutations(digits) perms.forEach(perm => { perm = Number(perm.join("")) if(perm > greatest && isPrime(perm)){ greatest = perm } }) } return greatest } console.log(pandigitalPrimes())
/* This is a multi-line comment for a simple adder function. */ // A simple function to add two number function add (a, b) { console.log(a + b); // to console log the sum of the numbers console.log('Hello') } add(10, 5);
import React, {useRef, useState, useEffect, useMemo} from 'react'; import styled from 'styled-components'; // import style from '../../assets/global-style'; import { debounce } from './../../api/utils'; import imgSearch from '../../assets/images/搜索.png'; const SearchBoxstyle = styled.div ` position: fixed; top: 0; width: 100%; display: flex; padding: .1759rem/* 19/108 */; height: .815rem/* 88/108 */; background-color: white; .server-search-input { position: relative; /* height: 0.9629rem; */ height: .81rem/* 77/108 */ ; width: 8.38rem/* 905/108 */ ; background-color: #f5f6fa; border-radius: 30px; .server-search-place { position: absolute; width: 8.1944rem/* 885/108 */ ; padding: .093rem/* 10/108 */ ; display: flex; line-height: .4167rem; font-size: 0; .server-search-border { /* display: inline-block; */ width: .6759rem/* 73/108 */ ; height: .3704rem/* 40/108 */ ; margin-left: .222rem/* 24/108 */ ; padding-top: .18rem/* 8/108 */ ; .server-search-img { width: 0.3703rem; /* height: 0.3703rem; */ } } } input { border: none; height: .715rem/* 55/108 */; width:6.74rem; color: #848c99; background-color: #f5f6fa; font-size: 0.3rem !important; } .icon-delete{ margin-top:0.1rem; color:gray; } } .button{ width: 1.3rem; height: .9rem; line-height: .9rem; text-align: center; font-size: .37rem; color: #e5484a; } `; const SearchBox = (props) => { const queryRef = useRef(); const [query, setQuery] = useState(''); // //接受父级传过来的搜索内容 const { newQuery } = props; // //handleQuery 是执行函数 被封装在节流中 const { handleQuery } = props; let handleQueryDebounce = useMemo(() => { //返回一个接受参数的函数 return debounce(handleQuery, 500); }, [handleQuery]); useEffect(() => { //当点击搜索图标 进入这个页面 将焦点获取到输入框 queryRef.current.focus(); }, []); useEffect(() => { //传入参数 执行返回的函数 handleQueryDebounce(query); // eslint-disable-next-line //当这个依赖改变的时候执行此函数 }, [query]); useEffect(() => { let curQuery = query; //判断现在输入框中的内容是否与现在点击的内容是否一样 if(newQuery !== query){ //不一样的时候使用点击的内容 curQuery = newQuery; //将点击的内容覆盖输入框里面的内容 queryRef.current.value = newQuery; } setQuery(curQuery); // eslint-disable-next-line //当父组件传过来值 改变则执行此函数 }, [newQuery]); const handleChange = (e) => { //获取输入框的值 let val = e.currentTarget.value //存储输入框的值(state) setQuery(val); }; const clearQuery = () => { // 清空state中的值 setQuery(''); //清空输入框 queryRef.current.value = ''; //输入框获取焦点 queryRef.current.focus(); } const displayStyle = query ? {display: 'block'}: {display: 'none'}; return ( <> <SearchBoxstyle> <div className="server-search-input"> <div className="server-search-place"> <p className='server-search-border'> <img className='server-search-img' src={imgSearch}></img> </p> <input type="text" placeholder='擦玻璃' style={{fontSize:"11px"}} ref={queryRef} onChange={handleChange}/> <i className="iconfont icon-delete" onClick={clearQuery} style={displayStyle}>&#xe640;</i> </div> </div> <div className="button" onClick={() => props.back()}>取消</div> </SearchBoxstyle> </> // <SearchBoxWrapper> // <i className="iconfont icon-back" onClick={() => props.back()}>&#xe655;</i> // <input ref={queryRef} className="box" placeholder="搜索歌曲、歌手、专辑" onChange={handleChange}/> // <i className="iconfont icon-delete" onClick={clearQuery} style={displayStyle}>&#xe600;</i> // </SearchBoxWrapper> ) }; export default React.memo(SearchBox);
// function() { //repoNamePaths defined in caller's eval() context // var args = process.argv.slice(2); //console.log("gitHubForksUpdater.js arguments: "); //console.log(args); //console.log(process.cwd()); //process.exit(-1); var fs = require('fs'); var path = require('path'); var http = require('http'); var https = require('https'); //https://github.com/blog/1509-personal-api-tokens //https://github.com/settings/tokens var ACCESSTOKEN = "f9ec367b2aa8eb2842272ff2cbafc447febb1c75"; var USERAGENT = "Readium-GitHub"; var httpGet = function(info, callback) { try { (info.ssl ? https : http).get(info.url, function(response) { try { // console.log("statusCode: ", response.statusCode); // console.log("headers: ", response.headers); response.setEncoding('utf8'); response.on('error', function(error) { console.log(info.url); console.log(error); callback(info, undefined); }); var allData = '' response.on('data', function(data) { allData += data; }); response.on('end', function() { //console.log(allData); callback(info, allData); }); } catch(err) { callback(info, undefined); } }); } catch(err) { callback(info, undefined); } }; var checkDiff = function(depSource, upstream, ID) { var depSource_ = depSource; var iSlash = depSource_.indexOf('/'); if (iSlash >= 0) { depSource_ = depSource_.substr(0,iSlash); } var url = { hostname: 'api.github.com', port: 443, path: "/repos/" + upstream + "/compare/" + ID + "..." + depSource_ + ":" + ID + "?access_token=" + ACCESSTOKEN, method: 'GET', headers: { "User-Agent": USERAGENT } }; httpGet( {ssl: true, url: url, depSource: depSource, upstream: upstream, ID: ID}, function(info, res) { if (!res) return; var gitData = JSON.parse(res); if (!gitData) return; console.log("+++++++ " + info.depSource + " >> " + info.upstream + " [" + info.ID + "]"); //console.log(info.url); //console.log(res); if (gitData.message) console.log(gitData.message); //if (gitData.url) console.log(gitData.url); //if (gitData.html_url) console.log(gitData.html_url); //if (gitData.permalink_url) console.log(gitData.permalink_url); if (gitData.behind_by) { console.log("!!!!!! NEEDS UPDATING"); console.log(gitData.status); console.log(gitData.behind_by); console.log("Code diff URLs:"); var depSource_ = depSource; var iSlash = depSource_.indexOf('/'); if (iSlash >= 0) { depSource_ = depSource_.substr(0,iSlash); } var upstream_ = info.upstream; iSlash = upstream_.indexOf('/'); if (iSlash >= 0) { upstream_ = upstream_.substr(0,iSlash); } console.log("https://github.com/" + info.upstream + "/compare/" + info.ID + "..." + depSource_ + ":" + info.ID); console.log("https://github.com/" + info.depSource + "/compare/" + info.ID + "..." + upstream_ + ":" + info.ID); console.log("(open with web browser to visualize code changes, to and from the fork)"); console.log(".........."); console.log("---------------------------------"); console.log("Recommended steps (command line):"); console.log("---------------------------------"); console.log("git clone git@github.com:"+info.depSource+".git"); console.log("git remote add upstream git@github.com:"+info.upstream+".git"); console.log("git checkout " + info.ID); console.log("git fetch upstream"); console.log("git merge upstream/" + info.ID); console.log("git commit -a"); console.log("git push"); console.log("---------------------------------"); //process.exit(1); } else if (gitData.url) { console.log("Up to date."); } else { console.log("GitHub API error?!"); console.log(res); } }); }; var alreadyScannedDeps = []; var scanDeps = function(deps) { for (var depName in deps) { var depSource = deps[depName]; depSource = depSource.replace("github:", ""); if (depSource.indexOf("/") == -1) continue; if (alreadyScannedDeps[depSource]) continue; alreadyScannedDeps[depSource] = true; console.log(depSource); var ID = "master"; var iHash = depSource.indexOf('#'); if (iHash >= 0) { ID = depSource.substr(iHash+1); depSource = depSource.substr(0,iHash); } console.log("[["); console.log(depSource); console.log(ID); console.log("]]"); var url = { hostname: 'api.github.com', port: 443, path: "/repos/" + depSource + "?access_token=" + ACCESSTOKEN, method: 'GET', headers: { "User-Agent": USERAGENT } }; httpGet( {ssl: true, url: url, depSource: depSource, ID: ID}, function(info, res) { if (!res) return; var gitData = JSON.parse(res); if (!gitData) return; if (!gitData.source && !gitData.parent) { if (gitData.message) console.log(res); return; } //console.log("++++++++"); //console.log(info.url); //console.log(res); if (gitData.source) { //console.log("SOURCE: " + gitData.source.full_name); checkDiff(info.depSource, gitData.source.full_name, info.ID); } if (gitData.parent && (gitData.parent.full_name != gitData.source.full_name)) { //console.log("PARENT: " + gitData.parent.full_name); checkDiff(info.depSource, gitData.parent.full_name, info.ID); } }); } }; var repoPath = process.cwd(); var repoPackageFile = path.join(repoPath, 'package.json'); var repoPackageFileContents = fs.readFileSync(repoPackageFile, 'utf-8'); var repoPackage = JSON.parse(repoPackageFileContents); scanDeps(repoPackage.dependencies); scanDeps(repoPackage.devDependencies); // // // for (var repoName in repoNamePaths) { // var repoPath = repoNamePaths[repoName]; // // // console.log("====================="); // console.log(repoName); // console.log(repoPath); // // console.log("---------------"); // // // console.log("---------------"); // } // }
/** * Created by Administrator */ var CONSTANT = { DATA_TABLES: { DEFAULT_OPTION: { //DataTables初始化选项 language: { "sProcessing": "处理中...", "sLengthMenu": "", "sZeroRecords": "没有匹配结果", "sInfo": "", "sInfoEmpty": "当前显示第 0 至 0 项,共 0 项", "sInfoFiltered": "(由 _MAX_ 项结果过滤)", "sInfoPostFix": "", "sSearch": "搜索:", "sUrl": "", "sEmptyTable": "表中数据为空", "sLoadingRecords": "载入中...", "sInfoThousands": ",", "oPaginate": { "sFirst": "首页", "sPrevious": "上页", "sNext": "下页", "sLast": "末页", "sJump": "跳转" }, "oAria": { "sSortAscending": ": 以升序排列此列", "sSortDescending": ": 以降序排列此列" } }, "ordering": true, "dom": "ft<'row-fluid'<'fl'i> <'fl'l><'fr'p>>", "lengthMenu": [10, 20, 30], autoWidth: false, //禁用自动调整列宽 stripeClasses: [], //为奇偶行加上样式,兼容不支持CSS伪类的场合 order: [], //取消默认排序查询,否则复选框一列会出现小箭头 processing: false, //隐藏加载提示,自行处理 serverSide: true, //启用服务器端分页 searching: false, //禁用原生搜索 bLengthChange: false }, COLUMN: { CHECKBOX: { //复选框单元格 className: "td-checkbox", "orderable": false, width: "30px", data: null, render: function(data, type, row, meta) { return '<input type="checkbox" class="iCheck">'; } } }, RENDER: { //常用render可以抽取出来,如日期时间、头像等 ELLIPSIS: function(data, type, row, meta) { data = data || ""; return '<span title="' + data + '">' + data + '</span>'; } } } }; function subFuntion(form2,zTree,treeNode,addTreeUrl,fixTreeUrl){} function subFuntion2(form2,zTree,treeNode,addTreeUrl,fixTreeUrl){} function validation(obj,zTree,addTreeUrl,fixTreeUrl) { // for more info visit the official plugin documentation: // http://docs.jquery.com/Plugins/Validation var form2 = obj; form2.validate({ errorElement: 'span', //default input error message container errorClass: 'help-block help-block-error', // default input error message class focusInvalid: true, // do not focus the last invalid input ignore: "", // validate all fields including form hidden input rules: { name: { minlength: 2, required: true }, email: { email: true }, url: { required: true, url: true }, number: { required: true, number: true }, digits: { required: true, digits: true }, creditcard: { required: true, creditcard: true }, password: { maxlength:10, required: true }, newpassword: { minlength:6, maxlength:10, required: true, alnum: true, samepassword: true }, newpasswordrepeat: { minlength:6, maxlength:10, equalTo: "#newpassword", alnum: true, samepassword: true } }, messages: { newpasswordrepeat: { equalTo: "两次密码输入不一致" } }, errorPlacement: function(error, element) { // render error placement for each input type var icon = $(element).parent('.input-icon').children('i'); icon.removeClass('fa-check').addClass("fa-warning"); icon.attr("data-original-title", error.text()).tooltip({ 'container': 'body' }); }, highlight: function (element) { // hightlight error inputs $(element).closest('.form-group').removeClass("has-success").addClass('has-error'); // set error class to the control group }, success: function (label, element) { var icon = $(element).parent('.input-icon').children('i'); $(element).closest('.form-group').removeClass('has-error').addClass('has-success'); // set success class to the control group icon.removeClass("fa-warning").addClass("fa-check"); }, submitHandler: function () { subFuntion(form2,zTree,addTreeUrl,fixTreeUrl) subFuntion2(form2,zTree,addTreeUrl,fixTreeUrl) } }); } function scrollTable(height) { return { DATA_TABLES: { DEFAULT_OPTION: { //DataTables初始化选项 language: { "sProcessing": "处理中...", "sLengthMenu": "", "sZeroRecords": "没有匹配结果", "sInfo": "", "sInfoPostFix": "", "sUrl": "", "sEmptyTable": "表中数据为空", "sLoadingRecords": "载入中...", "sInfoThousands": ",", }, "scrollCollapse": true, "scrollY": height, "ordering": true, "dom": "ft<'row-fluid'<'fl'i> <'fl'l><'fr'p>>", autoWidth: false, //禁用自动调整列宽 processing: false, //隐藏加载提示,自行处理 serverSide: false, //启用服务器端分页 searching: false, //禁用原生搜索 bLengthChange: false }, COLUMN: { CHECKBOX: { //复选框单元格 className: "td-checkbox", "orderable": false, width: "30px", data: null, render: function(data, type, row, meta) { return '<input type="checkbox" class="iCheck">'; } } }, RENDER: { //常用render可以抽取出来,如日期时间、头像等 ELLIPSIS: function(data, type, row, meta) { data = data || ""; return '<span title="' + data + '">' + data + '</span>'; } } } }; } function drawcallback(ele, tableele) {} function callbacka(ele, tableele) {} function delFun() {} function tableshow(ele, inputcolumns, tableele, url, deleteDom, userManage, delUrl) { var $table = ele; tableele = $table.dataTable($.extend(true, {}, CONSTANT.DATA_TABLES.DEFAULT_OPTION, { ajax: function(data, callback, settings) { //封装请求参数 var param = userManage.getQueryCondition(data); $.ajax({ type: "GET", url: url, cache: false, //禁用缓存 data: param, //传入已封装的参数 dataType: "json", success: function(result) { //异常判断与处理 if(result.errorCode) { alert("查询失败"); return; } //封装返回数据 var returnData = {}; returnData.draw = data.draw; //这里直接自行返回了draw计数器,应该由后台返回 returnData.recordsTotal = result.total; //总记录数 returnData.recordsFiltered = result.total; //后台不实现过滤功能,每次查询均视作全部结果 returnData.data = result.pageData; //调用DataTables提供的callback方法,代表数据已封装完成并传回DataTables进行渲染 //此时的数据需确保正确无误,异常判断应在执行此回调前自行处理完毕 callback(returnData); }, error: function(XMLHttpRequest, textStatus, errorThrown) { layer.msg("查询失败"); } }); }, "destroy": true, columns: inputcolumns, destroy: true, "drawCallback": function(settings) { drawcallback(ele, tableele); //清空全选状态 ele.find(":checkbox[name='cb-check-all']").prop('checked', false); if(ele.hasClass("select-table")) { selecttablecallback(ele, tableele); }; if(ele.hasClass("select-file")) { selectfilecallback(ele, tableele); }; //渲染完毕后的回调 ele.find("td span").unbind("click"); ele.find("td span").click(function(event) { event.stopPropagation(); callbacka($(this), tableele); }) } })).api(); ele.on("change", ":checkbox", function() { if($(this).is("[name='cb-check-all']")) { $(":checkbox", ele).prop("checked", $(this).prop("checked")); ele.find("tr").removeClass("active"); ele.find("tbody input").change(); } else { //一般复选 var checkbox = $("tbody :checkbox", ele); $(":checkbox[name='cb-check-all']", ele).prop('checked', checkbox.length == checkbox.filter(':checked').length); ele.find("tr").removeClass("active"); } }); if(deleteDom != "undefined") { deleteDom.unbind("click") deleteDom.click(function() { var arrItemId = []; ele.find("tbody :checkbox:checked").each(function(i) { var item = tableele.row($(this).closest('tr')).data(); if(!!item.oid) { arrItemId.push(item.oid); } else { arrItemId.push(item.id); } }); console.log(arrItemId); if(arrItemId && arrItemId.length) { layer.confirm('确定要删除吗?', { btn: ['确定', '取消'] }, function(index) { $.ajax({ url: delUrl, type: "post", traditional: true, data: { arr: JSON.stringify(arrItemId) }, dataType: "json", success: function(data) { if(data != "haschild") { layer.msg("删除成功!"); tableele.ajax.reload(); layer.close(index); } delFun(data); } }) }); } else { layer.msg('请先选中要操作的行'); } }); } // 搜索按钮触发效果 ele.find(".tablesearch").click(function() { tableele.draw(); }); ele.find(".upsearch").unbind("keyup"); ele.find(".upsearch").keyup(function(){ $(this).closest("tr").find(".tablesearch").trigger("click"); }) $table.on("click", ".btn-edit", function() { //编辑按钮 var item = tableele.row($(this).closest('tr')).data(); userManage.editItemInit(item); }).on("click", ".btn-del", function() { //删除按钮 var item = tableele.row($(this).closest('tr')).data(); userManage.deleteItem(item); }); } function singaltree_click(id, treeId, name) {} function hiddenValue(treeNode, treeId) {} function treeTable(treeDom, url, tableurl, tableDom, msg, table, delDom, userManage, delUrl, flag) { var view = null; var enable; if(flag) { view = { expandSpeed: "", addHoverDom: addHoverDom, removeHoverDom: removeHoverDom, selectedMulti: false }; enable = flag; } else { view = { selectedMulti: false }; enable = flag; } var setting = { view: view, data: { simpleData: { enable: true //是否采用简单数据模式 } }, edit: { enable: enable, showRemoveBtn: showRemoveBtn, showRenameBtn: showRenameBtn, renameTitle: "编辑", removeTitle: "删除", drag: { isCopy: false, isMove: false } }, async: { enable: true, type: 'GET', url: url, /* autoParam:[], otherParam:{"zTreeIsLoad":true},*/ dataFilter: filter, autoParam: ["id","level=lv","lvs","marked=md"] }, treeNodeKey: "id", //在isSimpleData格式下,当前节点id属性 treeNodeParentKey: "pId", //在isSimpleData格式下,当前节点的父节点id属性 callback: { onAsyncSuccess: function() { }, onCollapse: function() { $(".curSelectedNode").prev().addClass("selectnode"); }, onExpand: function() { $(".curSelectedNode").prev().addClass("selectnode"); }, beforeRemove: beforeRemove, //beforeRename: beforeRename, beforeEditName: zTreeBeforeEditName, onClick: function(event, treeId, treeNode, clickFlag) { $(".selectnode").removeClass("selectnode"); $(".curSelectedNode").prev().addClass("selectnode"); if(tableurl.indexOf("?") > 0) { newtableurl = tableurl + '&id=' + treeNode.id; } else { newtableurl = tableurl + '?id=' + treeNode.id; } if($("#eid") != "undefined") { $("#eid").val(treeNode.id); $("#pid").val(treeNode.id); $("#op").show(); } hiddenValue(treeNode, treeId) tableshow(tableDom, msg, table, newtableurl, delDom, userManage, delUrl); singaltree_click(treeNode.id, treeId, treeNode); } } }; function filter(treeId, parentNode, childNodes) { if(!childNodes) return null; for(var i = 0, l = childNodes.length; i < l; i++) { childNodes[i].name = childNodes[i].name.replace(/\.n/g,'.'); } return childNodes; } $.fn.zTree.init(treeDom, setting); // $('.tree_box').niceScroll({ // cursorcolor: "#ccc", //#CC0071 光标颜色 // cursoropacitymax: 1, //改变不透明度非常光标处于活动状态(scrollabar“可见”状态),范围从1到0 // touchbehavior: true, //使光标拖动滚动像在台式电脑触摸设备 // cursorwidth: "5px", //像素光标的宽度 // cursorborder: "0", // 游标边框css定义 // cursorborderradius: "5px", //以像素为光标边界半径 // autohidemode: false, //是否隐藏滚动条 // horizrailenabled: true, // nicescroll可以管理水平滚动 // cursordragontouch: true, // 使用触屏模式来实现拖拽 // }); } function treeShow(url, treele, flag) { var view = null; var enable; if(flag) { view = { expandSpeed: "", addHoverDom: addHoverDom, removeHoverDom: removeHoverDom, selectedMulti: false }; enable = flag; } else { view = { selectedMulti: false }; enable = flag; } var setting = { view: view, data: { simpleData: { enable: true //是否采用简单数据模式 } }, edit: { enable: enable, showRemoveBtn: showRemoveBtn, showRenameBtn: showRenameBtn, renameTitle: "编辑", removeTitle: "删除" }, async: { enable: true, type: 'GET', url: url, //autoParam: ["id", "name=n", "level=lv"], autoParam: ["id","level=lv","lvs","marked=md"], otherParam: { "otherParam": "zTreeAsyncTest" }, dataFilter: filter }, callback: { beforeRemove: beforeRemove, beforeEditName: zTreeBeforeEditName, onClick: function(event, treeId, treeNode, clickFlag) { singaltree_click(treeNode.id, treeId, treeNode); } } }; function filter(treeId, parentNode, childNodes) { if(!childNodes) return null; for(var i = 0, l = childNodes.length; i < l; i++) { childNodes[i].name = childNodes[i].name.replace(/\.n/g,'.'); } return childNodes; } $.fn.zTree.init(treele, setting); } Array.prototype.indexOf = function(val) { for(var i = 0; i < this.length; i++) { if(this[i] == val) return i; } return -1; }; Array.prototype.remove = function(val) { var index = this.indexOf(val); if(index > -1) { this.splice(index, 1); } }; function ajaxSub(form2, url) { form2.ajaxSubmit({ type: "post", url: url, //beforeSubmit: showRequest, success: function() { } }); return false; } function isAdd(treeId, treeNode) { return true } function showRemoveBtn(treeId, treeNode) { return true } function showRenameBtn(treeId, treeNode) { return true } function treeRmove(treeId, treeNode) {} function addTree(zTree, treeNode) {} var treedele = null; function beforeRemove(treeId, treeNode) {} function addHoverDom(treeId, treeNode) { /*判断是否有增加图标*/ var isadd = isAdd(treeId, treeNode); if(!isadd) { return isadd; } var sObj = $("#" + treeNode.tId + "_span"); if(treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return; var addStr = "<span class='button add' id='addBtn_" + treeNode.tId + "' title='增加' onfocus='this.blur();'></span>"; sObj.after(addStr); var btn = $("#addBtn_" + treeNode.tId); if(btn) btn.bind("click", function() { var zTree = $.fn.zTree.getZTreeObj(treeId); addTree(zTree, treeNode); return false; }); }; function removeHoverDom(treeId, treeNode) { $("#addBtn_" + treeNode.tId).unbind().remove(); }; function zTreeBeforeEditName(treeId, treeNode) {} function setselect(ele, data) { if(ele.size() > 0) { for(i = 0; i < ele.size(); i++) { var optionhtml = ''; $.each(data, function(key, val) { optionhtml += '<option value="' + data[key] + '">' + key + '</option>'; }) ele.eq(i).append(optionhtml) } } } function sortall(obj) { for(var i = 0; i < obj.length; i++) { obj[i].orderable = true; } } function nosortall(obj) { for(var i = 0; i < obj.length; i++) { obj[i].orderable = false; } } //滚动条 function scroll(dom) { dom.niceScroll({ cursorcolor: "#ddd", // 改变滚动条颜色,使用16进制颜色值 cursoropacitymin: 1, // 当滚动条是隐藏状态时改变透明度, 值范围 1 到 0 cursoropacitymax: 1, // 当滚动条是显示状态时改变透明度, 值范围 1 到 0 cursorwidth: "5px", // 滚动条的宽度,单位:便素 cursorborder: "3px solid #ddd", // CSS方式定义滚动条边框 cursorborderradius: "5px", // 滚动条圆角(像素) zindex: "auto", // 改变滚动条的DIV的z-index值 scrollspeed: 60, // 滚动速度 mousescrollstep: 40, // 鼠标滚轮的滚动速度 (像素) autohidemode: 'scroll', railoffset: true, // 可以使用top/left来修正位置 railpadding: { top: 0, right: -25 }, horizrailenabled: false }); } // 时间格式化 start function Format(now, mask) { var d = now; var zeroize = function(value, length) { if(!length) length = 2; value = String(value); for(var i = 0, zeros = ''; i < (length - value.length); i++) { zeros += '0'; } return zeros + value; }; return mask.replace(/"[^"]*"|'[^']*'|\b(?:d{1,4}|m{1,4}|yy(?:yy)?|([hHMstT])\1?|[lLZ])\b/g, function($0) { switch($0) { case 'd': return d.getDate(); case 'dd': return zeroize(d.getDate()); case 'ddd': return ['Sun', 'Mon', 'Tue', 'Wed', 'Thr', 'Fri', 'Sat'][d.getDate()]; case 'dddd': return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][d.getDate()]; case 'M': return d.getMonth() + 1; case 'MM': return zeroize(d.getMonth() + 1); case 'MMM': return ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][d.getMonth()]; case 'MMMM': return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][d.getMonth()]; case 'yy': return String(d.getFullYear()).substr(2); case 'yyyy': return d.getFullYear(); case 'h': return d.getHours() % 12 || 12; case 'hh': return zeroize(d.getHours() % 12 || 12); case 'H': return d.getHours(); case 'HH': return zeroize(d.getHours()); case 'm': return d.getMinutes(); case 'mm': return zeroize(d.getMinutes()); case 's': return d.getSeconds(); case 'ss': return zeroize(d.getSeconds()); case 'l': return zeroize(d.getSeconds(), 3); case 'L': var m = d.getMilliseconds(); if(m > 99) m = Math.round(m / 10); return zeroize(m); case 'tt': return d.getHours() < 12 ? 'am' : 'pm'; case 'TT': return d.getHours() < 12 ? 'AM' : 'PM'; case 'Z': return d.toString().match(/[A-Z]+$/); // Return quoted strings with the surrounding quotes removed default: return $0.substr(1, $0.length - 2); } }); }; // 时间格式化 end function layerShow(title, w, dom, formDom) { if(typeof w == 'string') { var area = [w, 'auto']; } else { var area = w; }; index = layer.open({ type: 1, title: title, area: area, scrollbar: false, shadeClose: false, content: dom, btnAlign: 'c', success: function() { // for(var i = 0; i < dom.find("table th input[type='text']").size(); i++) { // dom.find("table th input[type='text']").eq(i).val(""); // } $(".layclose,.cancle").on('click', function() { $(this).closest(".layui-layer").find(".layui-layer-setwin a").trigger("click"); }) } }); if(typeof formDom == "undefined") { $("form").find("input[type='text'],textarea,select").val(''); $("form").find("input[type='checkbox']").prop("checked", false); $(".form-group").removeClass("has-success").removeClass('has-error'); $(".input-icon").find('i').removeClass().addClass("fa"); } else { if(formDom.is("form")) { formDom.find("input[type='text'],textarea,select").val(''); formDom.find("input[type='checkbox']").prop("checked", false); formDom.find(".form-group").removeClass("has-success").removeClass('has-error'); formDom.find('.input-icon i').removeClass().addClass("fa"); } } } function layerMsg(title) { layer.msg(title, { time: 800 }); } //左侧导航跟随滚动条的滑动 start window.onscroll = function() { $(".main_head").css({ "left": $(document).scrollLeft() * -1 }); var scrolltop = $(this).scrollTop(); if(scrolltop > 0) { $(".returnBox").show(); } else { $(".returnBox").hide(); } }; //左侧导航跟随滚动条的滑动 end // 表单信息的序列化获取 function getformval(formId){ var values = {}; formId.find("input,select,textarea").each(function(){ var name = $(this).attr("name"); values[name] = $(this).val(); }); return(values); } function closeLayer(){ $(".layui-layer-close").trigger("click"); } //初始化select function setselect(ele, data) { // data: [ // { // "key": "建筑类型一", // "value": "1" // }, { // "key": "建筑类型二", // "value": "2" // }, { // "key": "建筑类型三", // "value": "3" // } // ] if(ele.size() > 0) { for(i = 0; i < ele.size(); i++) { var optionhtml = ''; for(var j = 0; j < data.length; j++) { optionhtml += '<option value="' + data[j].value + '">' + data[j].key + '</option>'; } ele.eq(i).append(optionhtml) } } } //上传文件 function getMessage() {} function uploadFile(pathsrc, ele,socketport) { debugger; var uploadpoint = ele; var oidStr = ''; var nameStr = ''; var objData = {}; //###################socket方式访问start var url = 'http://localhost:' + socketport + ""; $.ajax({ url: url, type: "get", data: { "methodName": "uploadAndCreateFO", "userName": userName }, cache: false, dataType: "jsonp", jsonp: "callback", jsonpCallback: "getMessage", success: function(data) { objData = data; if(data.fileobjectoid == "null") { layer.msg("找不到该文件 " + '<br/>' + "请检查文件名是否正确,然后重试!"); } else { $.ajax({ type: "post", data: { "newfileobjoid": data.fileobjectoid, }, url: pathsrc + "blm/file!createNewFileObj.action", dataType: "json", success: function(data) { if(data.data.length != 0) { oidStr =''; $.each(data.data, function(index, value) { var tname = '<em data-id="'+value.oid+'"><input type="" value="' + value.filename + '" /><span class="fa fa-remove ml6 emRemove"></span></em>'; uploadpoint.closest("form").find(".filegroup .filecont").append(tname); }) $(".emRemove").unbind("click"); $(".emRemove").click(function() { var that = $(this); $.ajax({ type: "post", data: { "fileobjoid": that.closest("em").attr("data-id") }, url: pathsrc + "blm/file!delfileobject.action", dataType: "json", success: function() { that.closest("em").remove(); } }) }) } else { layer.msg("上传失败"); } } }) } }, error: function() { alert("发生错误"); } }); } function loading(){ $("body").append("<div class='loading'></div>") } function closeloading(){ $("body .loading").remove(); }
const Command = require('../../structures/Command'); const { MessageEmbed } = require('discord.js'); const moment = require("moment"); const excludeChannels = require("../../constants/exclude_channels.js"); module.exports = class AvatarCommand extends Command { constructor(client) { super(client, { name: 'last-seen', group: 'info', aliases: ['lastseen'], hidden: true, memberName: 'last-seen', description: 'Responds with a user\'s last-seen date.', args: [ { key: 'user', prompt: 'Which user would you like to get the know about?', type: 'user', default: msg => msg.author } ] }); } async run(msg, { user }) { let color, lastSeen, description, lastSeenIn, lastSeenAt, lastSeenInChannel; const DiscordUser = this.client.orm.Model('DiscordUser'); // const User = client.orm.Model("User"); let discordUserModel = await DiscordUser.find(user.id); if (discordUserModel) { lastSeenIn = discordUserModel.last_seen_in; lastSeenInChannel = msg.guild.channels.get(lastSeenIn); lastSeenAt = discordUserModel.last_seen_at; if (lastSeenAt) { const lastSeenDate = moment(lastSeenAt); lastSeen = lastSeenDate.fromNow(); color = "#000000"; description = `${user} was last seen ${lastSeen}`; if (!excludeChannels.includes(lastSeenIn)) { description = `${description} in ${lastSeenInChannel}.` } else { description = `${description}.`; } // const lastSeenInPermissionsForAuthor = msg.author.permissionsIn(lastSeenIn); } else { color = "#FF0000"; description = `${user} has not been seen yet.`; } } // const embed = new MessageEmbed() // .setTitle(`Last time I saw ${user.username}...`) // .setDescription(description) // .setThumbnail(user.displayAvatarURL()) // .setColor(color); return msg.channel.send(description); } };
/** * Tasks: Server * * Runs a server, serving up the contents in paths.webroot.root on port 1337 * It also supports the History API for SPA's */ // Dependencies const historyApiFallback = require('connect-history-api-fallback') // Task module.exports = (paths, browserSync) => () => { browserSync.init({ ghostMode: false, middleware: [historyApiFallback()], notify: true, port: 1337, server: { baseDir: paths.dist.root, directory: false } }) }
/* EXAMPLE HTTP POST FOR ORGANISATIONS: { "name": "My Organisation", "singleStore": false, "isDeleted": false, "isPaid": true, "storeName": "First Store", "location": [ { "lat":"latitude" }, { "lgn":"longitude" } ], "firstName":"Adrian", "lastName":"Gabardo", "email":"imtesting@mail.com" } */ const Organisation = require('../models/organisations.model'); const User = require('../models/users.model'); const Store = require('../models/stores.model'); async function orgUser(req, res, orgID, storeID) { const user = new User({ userRole: "owner", firstName: req.body.firstName, lastName: req.body.lastName, email: req.body.email, organisationID: orgID, storeID: storeID, allStores: true, isDeleted: false }); user.save() .then(data => { //console.log('gets here') res.send(data); }).catch(err => { res.status(500).send({ message: err.message || "There was an error saving the user." }); }); } async function orgStore(req, res, orgID) { const store = new Store({ storeName: req.body.storeName, lat: req.body.lat, lgn: req.body.lgn, creationDate: Date.now(), organisationID: orgID, isDeleted: false }); store.save() .then(data => { orgUser(req, res, orgID, data._id) }).catch(err => { res.status(500).send({ message: err.message || "There was an error saving the store." }); }); } exports.create = (req, res) => { const organisation = new Organisation({ name: req.body.name, singleStore: req.body.singleStore, isDeleted: false, isPaid: req.body.isPaid }); organisation.save() .then(data => { orgStore(req, res, data._id) }).catch(err => { res.status(500).send({ message: err.message || "There was an error saving the organisation." }); }); }; exports.findAll = (req, res) => { Organisation.find() .then(organisation => { res.send(organisation); console.log(organisation) }).catch(err => { res.status(500).send({ message: err.message || "There was an error getting all organisations." }); }); }; exports.findOne = (req, res) => { Organisation.findById(req.params.id) .then(organisation => { if(!organisation) { return res.status(404).send({ message: "Organisation not found " + req.params.id }); } res.send(organisation); }).catch(err => { if(err.kind === 'ObjectId') { return res.status(404).send({ message: "Organisation not found " + req.params.id }); } return res.status(500).send({ message: "Error fetching organisation " + req.params.id }); }); }; exports.update = (req, res) => { Organisation.findByIdAndUpdate(req.params.id, { name: req.body.name, singleStore: req.body.singleStore, isDeleted: req.body.isDeleted, isPaid: req.body.isPaid }, {new: true}) .then(organisation => { if(!organisation) { return res.status(404).send({ message: "Organisation not found " + req.params.id }); } res.send(organisation); }).catch(err => { if(err.kind === 'id') { return res.status(404).send({ message: "Organisation not found " + req.params.id }); } return res.status(500).send({ message: "Error updating organisation " + req.params.id }); }); }; exports.delete = (req, res) => { Organisation.findByIdAndRemove(req.params.id) .then(organisation => { if(!organisation) { return res.status(404).send({ message: "Organisation not found " + req.params.id }); } res.send({message: "Organisation deleted!"}); }).catch(err => { if(err.kind === 'id' || err.name === 'NotFound') { return res.status(404).send({ message: "Organisation not found " + req.params.id }); } return res.status(500).send({ message: "Organisation not deleted " + req.params.id }); }); };
import React from 'react'; import CalendarDateListStyled from './CalendarDateList.styled'; // import {CalendarDateItem} from './CalendarDateItem'; const CalendarDateList = ({children}) => { return ( <CalendarDateListStyled> {children} </CalendarDateListStyled> ) } export default CalendarDateList
export * from './array'; export * from './context'; export * from './sequelize'; export * from './graphql';
/* 🤖 this file was generated by svg-to-ts*/ export const EOSIconsPreview = { name: 'preview', data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M19 3H5a2 2 0 00-2 2v14a2 2 0 002 2h14c1.1 0 2-.9 2-2V5a2 2 0 00-2-2zm0 16H5V7h14v12zm-5.5-6c0 .83-.67 1.5-1.5 1.5s-1.5-.67-1.5-1.5.67-1.5 1.5-1.5 1.5.67 1.5 1.5zM12 9c-2.73 0-5.06 1.66-6 4 .94 2.34 3.27 4 6 4s5.06-1.66 6-4c-.94-2.34-3.27-4-6-4zm0 6.5a2.5 2.5 0 010-5 2.5 2.5 0 010 5z"/></svg>` };
require.config({ baseUrl: "./", paths: { 'jquery': 'http://code.jquery.com/jquery-1.11.1.min', 'angular':'http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular', 'angular-route': 'http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular-route.min', 'angularAMD': 'bower_components/angularAMD/angularAMD.min' }, shim: { 'angularAMD': ['angular'], 'angular-route': ['angular'], 'angular': ['jquery'] }, deps: ['mega_todo'] });
import React, { Component } from "react"; import { Container, Row, Col, ListGroup, ListGroupItem, InputGroup, FormControl, Button, Form, Badge } from 'react-bootstrap'; class InputComp extends Component { constructor(props) { super(props); this.state = { userInput:"", // type:'todolist', selectedBucket:"", selectedBucketId:"" } } componentDidMount() { // this.setState({ // type:this.props.type // }) } //update the filed on change updateUserInput = (data) => { this.setState({ userInput: data }) } //select the bucket selectBucket = (id,event) => { console.log(id,event.target.options[event.target.options.selectedIndex].label) this.setState({selectedBucketId: id,selectedBucket:event.target.options[event.target.options.selectedIndex].label}) console.log(id) } render() { return ( <Form.Row> {this.props.type != 'bucket' ? <> <Form.Group as={Col} md="8" controlId="validationCustom01"> <Form.Label>Add Items</Form.Label> <Form.Control required type="text" placeholder="add items to the list" onChange={(event) => { this.updateUserInput(event.target.value) }} /> <Form.Control.Feedback>Looks good!</Form.Control.Feedback> </Form.Group> <Form.Group as={Col} md="3" controlId="exampleForm.ControlSelect1"> <Form.Label>select Bucket</Form.Label> <Form.Control as="select" custom onChange={(event) => { this.selectBucket(event.target.value,event) }} > <option>select Bucket</option> {this.props.bucketlist.map((data,index)=>{ return(<option key = {data.id} value={data.id} bucketid = {data.id}> {data.description} </option>) }) } </Form.Control> </Form.Group> <Form.Group as={Col} md="2"> <Button variant="primary" onClick={() => { this.props.addTask( this.state.userInput, this.state.selectedBucket, this.state.selectedBucketId, this.props.type ) }}>Add Items</Button> </Form.Group> </> : <> <Form.Group as={Col} md="9" controlId="validationCustom01"> <Form.Label>Add Buckets</Form.Label> <Form.Control required type="text" placeholder="Add buckets" onChange={(event) => { this.updateUserInput(event.target.value) }} /> </Form.Group> <Form.Group as={Col} md="3"> <Form.Label>Add Bucket</Form.Label> <div> <Button variant="primary" onClick={() => { this.props.addBucket( this.state.userInput, this.props.type ) }}>Submit</Button> </div> </Form.Group> </> } </Form.Row> ) } } export default InputComp;
"use strict"; var GAME = GAME || {}; GAME.util = { rand: function(min, max){ return Math.floor(Math.random() * (max - min + 1)) + min; }, touch: function(obj, collection, padding){ var isTouching = false; var padding = padding || 0; $.each(collection, function(idx, colObj){ if (obj !== colObj){ var dist = Math.sqrt( Math.pow(obj.posX - colObj.posX, 2) + Math.pow(obj.posY - colObj.posY, 2) ); if (dist + padding < obj.size + colObj.size) { isTouching = true; return false; } } }); return isTouching; } }; GAME.Asteroid = function(posX, posY, size, velX, velY){ this.posX = posX || GAME.util.rand(10,490); this.posY = posY || GAME.util.rand(10,490); this.size = size || GAME.util.rand(35,45); this.velX = velX || GAME.util.rand(-0.5,1) || GAME.util.rand(-1,0.5); this.velY = velY || GAME.util.rand(-0.5,1) || GAME.util.rand(-1,0.5); }; GAME.Asteroid.prototype.tic = function(){ this.posX += this.velX; this.posY += this.velY; }; GAME.Asteroid.prototype.draw = function(){ GAME.canvas.ctx.beginPath(); GAME.canvas.ctx.arc(this.posX, this.posY, this.size, 0, 2 * Math.PI); GAME.canvas.ctx.stroke(); }; GAME.Ship = function(){ this.posX = 250; this.posY = 250; this.size = 35; this.vel = 0.5; this.angle = 270; this.rotateLeft = false; this.rotateRight = false; this.accel = false; }; GAME.Ship.prototype.tic = function(){ if (this.rotateLeft) { this.angle -= 10; } else if (this.rotateRight) { this.angle += 10; } else if (this.accel) { if ( this.vel < 2 ){ this.vel += 0.1; } } var radians = this.angle * Math.PI/180; this.posX += Math.cos(radians) * this.vel; this.posY += Math.sin(radians) * this.vel; }; GAME.Ship.prototype.draw = function(){ var ctx = GAME.canvas.ctx; ctx.save(); ctx.fillStyle = '#00f'; ctx.translate(this.posX, this.posY ); ctx.rotate(this.angle * Math.PI/180); ctx.beginPath(); ctx.moveTo(44, 0); ctx.lineTo(0, 16); ctx.lineTo(0, -16); ctx.closePath(); ctx.fill(); ctx.restore(); }; GAME.Ship.prototype.fire = function(){ GAME.model.pewpews.push(new GAME.Pewpew()); }; GAME.Pewpew = function(){ this.size = 2; this.vel = GAME.model.ship.vel + 1 * 2; this.angle = GAME.model.ship.angle; var radians = this.angle * Math.PI/180; this.posX = GAME.model.ship.posX + (Math.cos(radians) * 44); this.posY = GAME.model.ship.posY + (Math.sin(radians) * 44); }; GAME.Pewpew.prototype.tic = function(){ var radians = this.angle * Math.PI/180; this.posX += Math.cos(radians) * this.vel; this.posY += Math.sin(radians) * this.vel; }; GAME.Pewpew.prototype.draw = function(){ GAME.canvas.ctx.fillStyle = '#f00'; GAME.canvas.ctx.beginPath(); GAME.canvas.ctx.arc(this.posX, this.posY, this.size, 0, 2 * Math.PI); GAME.canvas.ctx.fill(); }; GAME.model = { init: function(numAsteroids){ GAME.model.score = 0; GAME.model.lives = 10; GAME.model.ship = new GAME.Ship(); GAME.model.asteroids = []; GAME.model.pewpews = []; GAME.model.newRandAsteroid(numAsteroids); }, newRandAsteroid: function(numAsteroids){ numAsteroids = numAsteroids || 1; for (var i=0; i<numAsteroids; i++){ var astr = new GAME.Asteroid(); while( GAME.util.touch(astr, GAME.model.asteroids, 10) || GAME.util.touch(astr, [GAME.model.ship], 100) ){ astr = new GAME.Asteroid(); } GAME.model.asteroids.push(astr); } } }; GAME.controller = { init: function(){ GAME.controller.bindKeys(); GAME.controller.startGame(); }, startGame: function(){ GAME.model.init(3); GAME.view.init(); GAME.canvas.init(); GAME.controller.playLoop(); }, bindKeys: function(){ $('body').on("keydown", function(event){ if (event.which === 37){ GAME.model.ship.rotateLeft = true; } else if (event.which === 39){ GAME.model.ship.rotateRight = true; } else if (event.which === 38){ GAME.model.ship.accel = true; } }); $('body').on("keyup", function(event){ if (event.which === 37){ GAME.model.ship.rotateLeft = false; } else if (event.which === 39){ GAME.model.ship.rotateRight = false; } else if (event.which === 32){ GAME.model.ship.fire(); } else if (event.which === 38){ GAME.model.ship.accel = false; GAME.model.ship.vel = 0.5; } }); }, playLoop: function(){ GAME.controller.moveAsteroids(); GAME.controller.moveShip(); GAME.controller.movePewpews(); GAME.controller.explodeAsteroids(); if (GAME.controller.shipHurt()){ GAME.model.lives -= 1; GAME.controller.updateStats(); } if (GAME.controller.gameOver()){ window.cancelAnimationFrame(GAME.controller.loopID); GAME.controller.startGame(); return false; } GAME.canvas.draw(); GAME.controller.loopID = window.requestAnimationFrame(GAME.controller.playLoop, 200); }, moveShip: function(){ GAME.model.ship.tic(); }, movePewpews: function(){ $.each(GAME.model.pewpews, function(idx, pewpew){ pewpew.tic(); }); }, moveAsteroids: function(){ $.each(GAME.model.asteroids, function(idx, astr){ astr.tic(); //bounce off sides of canvas if (astr.posY < -50 || astr.posY > 550) { astr.velY = -astr.velY; } if (astr.posX < -50 || astr.posX > 550) { astr.velX = -astr.velX; } }); }, explodeAsteroids: function(){ var explodeAstr = []; var explodePewpew = []; var newAsteroids = []; $.each(GAME.model.asteroids, function(idx, astr){ if (GAME.util.touch(astr, GAME.model.asteroids)) { explodeAstr.push(idx); } }); $.each(GAME.model.asteroids, function(astrIdx, astr){ $.each(GAME.model.pewpews, function(pewpewIdx, pewpew){ if ( GAME.util.touch(astr, [pewpew]) && !(explodeAstr.includes(astrIdx)) ) { GAME.model.score += 10; GAME.controller.updateStats(); explodeAstr.push(astrIdx); explodePewpew.push(pewpewIdx); } }); }); if (GAME.util.rand(0,200) > 199){ GAME.model.newRandAsteroid(); } for( var i=explodePewpew.length - 1; i >= 0; i--){ GAME.model.pewpews.splice(explodePewpew[i], 1); } for( var i=explodeAstr.length - 1; i >= 0; i--){ var astr = GAME.model.asteroids.splice(explodeAstr[i], 1)[0]; if (astr && astr.size > 15){ newAsteroids.push(new GAME.Asteroid( astr.posX - astr.size/2, astr.posY - astr.size/2, astr.size/2 ) ); newAsteroids.push(new GAME.Asteroid( astr.posX + astr.size/2, astr.posY + astr.size/2, astr.size/2 )); } } GAME.model.asteroids = GAME.model.asteroids.concat(newAsteroids); }, updateStats: function(){ GAME.view.updateLives(GAME.model.lives); GAME.view.updateScore(GAME.model.score); }, shipHurt: function(){ var isShipHurt = false; var vaporizeAstroids = []; //vaporize astr if it touches ship's "shield" $.each(GAME.model.asteroids, function(idx, astr){ if ( GAME.util.touch(GAME.model.ship, [astr]) ){ isShipHurt = true; vaporizeAstroids.push(idx); } }); for( var i=vaporizeAstroids.length - 1; i >= 0; i--){ GAME.model.asteroids.splice(vaporizeAstroids[i], 1); } if (GAME.model.ship.posX > 490 || GAME.model.ship.posX < 10 || GAME.model.ship.posY > 490 || GAME.model.ship.posY < 10 ){ isShipHurt = true; } return isShipHurt; }, gameOver: function(){ if (GAME.model.lives === 0){ return true; } } }; GAME.canvas = { init: function(){ GAME.canvas.ctx = $('#space')[0].getContext('2d'); }, draw: function(){ GAME.canvas.ctx.clearRect(0,0,500,500); $.each(GAME.model.asteroids, function(i, astr){ astr.draw(); }); $.each(GAME.model.pewpews, function(i, pewpew){ pewpew.draw(); }); GAME.model.ship.draw(); } }; GAME.view = { init: function(){ GAME.view.score = $('#score'); GAME.view.lives = $('#lives'); GAME.view.updateScore(GAME.model.score); GAME.view.updateLives(GAME.model.lives); }, updateScore: function(newScore){ GAME.view.score.text(newScore); }, updateLives: function(newLives){ GAME.view.lives.text(newLives); } }; $( document ).ready(function(){ GAME.controller.init(); }); // GAME.AsteroidInst = function(posX, posY){ // this.posX = posX; // this.posY = posY; // this.velX = GAME.util.rand(-10,10); // this.velY = GAME.util.rand(-10,10); // this.tic = function(){ // this.posX += this.velX; // this.posY += this.velY; // }; // }; // var protos = []; // for (var i=0; i<1000; i++){ // var posX = GAME.util.rand(1,100); // var posY = GAME.util.rand(1,100); // protos.push(new GAME.AsteroidProto(posX, posY)); // } // var insts = []; // for (var i=0; i<1000; i++){ // var posX = GAME.util.rand(1,100); // var posY = GAME.util.rand(1,100); // insts.push(new GAME.AsteroidInst(posX, posY)); // } // console.log("Proto Asteroid Benchmark"); // var startTime = new Date(); // for (var i=0; i<protos.length; i++){ // for (var j=0; j<100000; j++){ // protos[i].tic(); // } // } // var endTime = new Date(); // console.log(endTime.getTime() - startTime.getTime()); // console.log("Instance Asteroid Benchmark"); // var startTime = new Date(); // for (var i=0; i<insts.length; i++){ // for (var j=0; j<100000; j++){ // insts[i].tic(); // } // } // var endTime = new Date(); // console.log(endTime.getTime() - startTime.getTime());
export default { command : 'removeLayer', execute: function (editor) { editor.selection.itemsByIds(editor.selection.ids).forEach(item => { item.remove(); }) editor.selection.empty(); editor.emit('refreshArtboard') } }
const mysql = require('mysql'); const inquirer = require('inquirer'); const cTable = require('console.table'); const promptQuestions = { viewAllEmployees: "View All Employees", viewByDepartment: "View All Employees By Department", viewByManager: "View All Employees By Manager", addEmployee: "Add An Employee", addDepartment: "Add a department", addRole: "Add a role", removeEmployee: "Remove An Employee", updateRole: "Update Employee Role", viewAllRoles: "View All Roles", exit: "Exit" }; const connection = mysql.createConnection({ host: 'localhost', port: '3306', user: 'root', password: 'password', database: 'employee_tracker' }); connection.connect((err) => { if (err) throw err; runSearch(); }); const runSearch = () => { inquirer .prompt({ name: 'action', type: 'list', message: 'What would you like to do?', choices: [ promptQuestions.viewAllEmployees, promptQuestions.viewByDepartment, promptQuestions.viewByManager, promptQuestions.viewAllRoles, promptQuestions.addEmployee, promptQuestions.addDepartment, promptQuestions.addRole, promptQuestions.removeEmployee, promptQuestions.exit ] }) .then(answer => { console.log('answer', answer); switch (answer.action) { case promptQuestions.viewAllEmployees: viewAllEmployees(); break; case promptQuestions.viewByDepartment: viewByDepartment(); break; case promptQuestions.viewByManager: viewByManager(); break; case promptQuestions.addEmployee: addEmployee(); break; case promptQuestions.addDepartment: inquirer .prompt([ { name: "Department", type: "input", message: "Please enter the department you would like to add?", validate: answer => { if (answer !== "") { return true; } return "Please enter at least one character."; } }, ]).then(answers => { // Adds department to database addDepartment(answers.Department); }) break; case promptQuestions.addRole: inquirer .prompt([ { name: "role", type: "input", message: "Please enter the role's title.", }, { name: "salary", type: "input", message: "Please enter the role's salary.", }, { name: "department_id", type: "input", message: "Please enter the department id.", } ]).then(answers => { // Adds role to database addRole(answers.role, answers.salary, answers.department_id); }) break; case promptQuestions.removeEmployee: remove('delete'); break; case promptQuestions.viewAllRoles: viewAllRoles(); break; case promptQuestions.exit: connection.end(); break; } }); } function viewAllEmployees() { const query = `SELECT employee.id, employee.first_name, employee.last_name, role.title, department.d_name AS department, role.salary, CONCAT(manager.first_name, ' ', manager.last_name) AS manager FROM employee LEFT JOIN employee manager on manager.id = employee.manager_id INNER JOIN role ON (role.id = employee.role_id) INNER JOIN department ON (department.id = role.department_id) ORDER BY employee.id;`; connection.query(query, (err, res) => { if (err) throw err; console.log('\n'); console.log('VIEW ALL EMPLOYEES'); console.log('\n'); console.table(res); runSearch(); }); }; function viewByDepartment() { const query = `SELECT department.d_name AS department, role.title, employee.id, employee.first_name, employee.last_name FROM employee LEFT JOIN role ON (role.id = employee.role_id) LEFT JOIN department ON (department.id = role.department_id) ORDER BY department.d_name;`; connection.query(query, (err, res) => { if (err) throw err; console.log('\n'); console.log('VIEW EMPLOYEE BY DEPARTMENT'); console.log('\n'); console.table(res); runSearch(); }); }; function viewByManager() { const query = `SELECT CONCAT(manager.first_name, ' ', manager.last_name) AS manager, department.d_name AS department, employee.id, employee.first_name, employee.last_name, role.title FROM employee LEFT JOIN employee manager on manager.id = employee.manager_id INNER JOIN role ON (role.id = employee.role_id && employee.manager_id != 'NULL') INNER JOIN department ON (department.id = role.department_id) ORDER BY manager;`; connection.query(query, (err, res) => { if (err) throw err; console.log('\n'); console.log('VIEW EMPLOYEE BY MANAGER'); console.log('\n'); console.table(res); runSearch(); }); }; function viewAllRoles() { const query = `SELECT role.title, employee.id, employee.first_name, employee.last_name, department.d_name AS department FROM employee LEFT JOIN role ON (role.id = employee.role_id) LEFT JOIN department ON (department.id = role.department_id) ORDER BY role.title;`; connection.query(query, (err, res) => { if (err) throw err; console.log('\n'); console.log('VIEW EMPLOYEE BY ROLE'); console.log('\n'); console.table(res); runSearch(); }); }; async function addEmployee() { const addname = await inquirer.prompt(askName()); connection.query('SELECT role.id, role.title FROM role ORDER BY role.id;', async (err, res) => { if (err) throw err; const { role } = await inquirer.prompt([ { name: 'role', type: 'list', choices: () => res.map(res => res.title), message: 'What is the employee role?: ' } ]); let roleId; for (const row of res) { if (row.title === role) { roleId = row.id; continue; } } connection.query('SELECT * FROM employee', async (err, res) => { if (err) throw err; let choices = res.map(res => `${res.first_name} ${res.last_name}`); choices.push('none'); let { manager } = await inquirer.prompt([ { name: 'manager', type: 'list', choices: choices, message: 'Choose the employee Manager: ' } ]); let managerId; let managerName; if (manager === 'none') { managerId = null; } else { for (const data of res) { data.fullName = `${data.first_name} ${data.last_name}`; if (data.fullName === manager) { managerId = data.id; managerName = data.fullName; console.log(managerId); console.log(managerName); continue; } } } console.log('Employee has been added. Please view all employees to verify...'); connection.query( 'INSERT INTO employee SET ?', { first_name: addname.first, last_name: addname.last, role_id: roleId, manager_id: parseInt(managerId) }, (err, res) => { if (err) throw err; runSearch(); } ); }); }); } function addDepartment(department) { var department = connection.query( "INSERT INTO department SET d_name = ?", [department], function (error, department) { if (error) throw error }) departmentTable(); } function departmentTable() { var depTable = connection.query("SELECT d_name FROM department;", function (error, depTable) { if (error) throw error; console.log('\n'); console.table(depTable); runSearch(); }) } function addRole(title, salary, department_id) { var role = connection.query( "INSERT INTO role SET title = ?, salary = ?, department_id = ?", [title, salary, department_id], function (error, role) { if (error) throw error; }) roleTable(); } function roleTable() { var roleT = connection.query("SELECT title, salary, department_id FROM role;", function (error, roleT) { if (error) throw error console.log('\n') console.table(roleT); runSearch(); }) } function remove(input) { const promptQ = { yes: "yes", no: "no I don't (view all employees on the main option set to find ID)" }; inquirer.prompt([ { name: "action", type: "list", message: "In order to update an employee, an employee ID must be entered. View all employees to get" + " the employee ID. Do you know the employee ID?", choices: [promptQ.yes, promptQ.no] } ]).then(answer => { if (input === 'delete' && answer.action === "yes") removeEmployee(); else if (input === 'role' && answer.action === "yes") updateRole(); else if (input === 'manager' && answer.action === "yes") updateManager(); else viewAllEmployees(); }); }; async function removeEmployee() { const answer = await inquirer.prompt([ { name: "first", type: "input", message: "Enter the employee ID you want to remove: " } ]); connection.query('DELETE FROM employee WHERE ?', { id: answer.first }, function (err) { if (err) throw err; }); console.log('Employee has been removed on the system!'); runSearch(); }; function askName() { return ([ { name: "first", type: "input", message: "Enter the first name: " }, { name: "last", type: "input", message: "Enter the last name: " } ]); }
var NAS_IP = "localhost"; exports.NAS_IP = NAS_IP;
var fs = require("fs"); const { curly } = require("node-libcurl"); const { Curl } = require("node-libcurl"); async function try1() { const curl = new Curl(); curl.setOpt("URL", "www.google.com"); curl.setOpt("FOLLOWLOCATION", true); curl.on("end", function (statusCode, data, headers) { console.info(statusCode); console.info("---"); console.info(data.length); console.info("---"); console.info(this.getInfo("TOTAL_TIME")); this.close(); }); curl.on("error", curl.close.bind(curl)); curl.perform(); } async function try2({MP3File, TranscriptFileNameToUse, txtFileNameToWrite}) { const curl = new Curl(); const close = curl.close.bind(curl); curl.setOpt( Curl.option.URL, "http://localhost:8765/transcriptions?async=false" ); curl.setOpt(Curl.option.HTTPPOST, [ { name: "audio", file: "./ep375-purechimp_tc.mp3", type: "audio/mpeg" }, { name: "transcript", file: "./Pure_Chimp_Transcript.txt", type: "text/plain", }, ]); curl.on("end", function (statusCode, data, headers) { console.info(statusCode); console.info("---"); fs.writeFile("alinger_data.json", data, function (err) { if (err) { return console.log(err); } console.log("alinger_data.json " + " was saved!"); }); console.info("---"); }); curl.on("error", function () { console.log("error"); console.log(curl); }); curl.perform(); } try2({MP3File: "20201013_bullseye_bullseye20201013-richard_jenkins.mp3_10c286183260e081a5a5d7c573213b48_26188872.mp3", file:}); /Users/davidelliott/Desktop/shopify/shopify-podcast-translator/data_files/masters/Bullseye-Ep.-10.13.20_Final-Draft.pdf { MP3File, MP3FileNameToUse, txtFileNameToWrite }
import React, { useContext, useEffect, useState } from "react"; import { View, Text, ScrollView, StyleSheet, RefreshControl, FlatList, Image, Button, } from "react-native"; import { getFocusedRouteNameFromRoute, useFocusEffect } from "@react-navigation/native"; // APIs import { CreateAPI, DeleteAPI, ReadAPI } from "../../API"; // Contexts import { DimensionContext } from "contexts/DimensionContext"; import { UserContext } from "contexts/UserContext"; // Custom Components import NotificationCard from "components/NotificationCard"; import Header from "components/Header"; // Images/Assets import AppStyles from "../../AppStyles"; /*------- testing --------*/ // temorary test data to simulate backend notification data const pic = require("assets/profilePic.jpg"); const gradient = require("assets/gradients/right.png"); // function buildTestHugData( // hugId, // completed, // dateTime, // img, // receiverDescription, // receiverId, // senderDescription, // senderId // ) { // return { // hugId: hugId, // completed: completed, // dateTime: dateTime, // images: img, // receiverDescription: receiverDescription, // receiverId: receiverId, // senderDescription: senderDescription, // senderId: senderId, // }; // } // const testDes1 = // "are you ready kids, aye aye captain, i cant hear you, aye aye captin"; // const testDes2 = // "ohhhhhhhhhhhhhhhhh who lives in a pineapple under the sea spongebb squarepants"; // const testData = [ // buildTestData("Alex Chow", "April 20, 2020", img, "hug", '1', '1'), // buildTestData("Evan Chow", "April 20, 2020", img, "friend", '2', '2'), // buildTestData("Alex Suong", "April 20, 2020", img, "hug", '3', '3'), // buildTestData("Alex Evan", "April 20, 2020", img, "hug", '4', '4'), // buildTestData("Alex Chow", "April 20, 2020", img, "hug", '5', '5'), // buildTestData("Suong Chow", "April 20, 2020", img, "friend", '6', '6'), // buildTestData("Alex Chow", "April 20, 2020", img, "friend", '7', '7'), // buildTestData("Alex Song", "April 20, 2020", img, "hug", '8', '8'), // buildTestData("Evan Alex", "April 20, 2020", img, "hug", '9', '9'), // ]; // const testHugData = [ // buildTestHugData(1, true, "April 20, 2020", img, testDes1, "@Evan", testDes2, "@Alex",), // buildTestHugData(3, true, "April 22, 2020", img, testDes1, "@Alex", testDes2, "@Tyus",), // buildTestHugData(5, true, "April 22, 2020", img, testDes1, "@Vicki", testDes2, "@AlexChow",), // buildTestHugData(6, true, "April 22, 2020", img, testDes1, "@Vivian", testDes2, "@TyusLiu",), // buildTestHugData(7, true, "April 22, 2020", img, testDes1, "@Alana", testDes2, "@VickiChen",), // ]; // // ( only if type is hug) notification_id: notif_id}]} // function buildTestData(name, date_time, friendpfp, type, call_id, notification_id) { // return { // name: name, // date_time: date_time, // friendpfp: friendpfp, // type: type, // call_id: call_id, // notification_id: notification_id, // } // } /*------- end of testing --------*/ export default function NotificationPage({ navigation, route, refresh }) { // States // stores whether the user is on this page (true) or not (false) const [isFocused, setIsFocused] = useState(false) // Contexts const { windowWidth, windowHeight } = useContext(DimensionContext) const [notifications, setNotifications] = useState([]) const { userData } = useContext(UserContext); // Misc const { uid } = userData; const routeName = route.name; // check whether the user is on the page (true) // or navigates away from the page (false) useFocusEffect(() => { setIsFocused(true) return () => { setIsFocused(false) } }, []); // add a filler item to move the list down useEffect(() => { getNotifications(); }, [refresh]); function getTimeElapsed(date_time) { let notifDate = new Date(date_time).getTime() / 1000 let today = parseInt(new Date().getTime() / 1000) let t = Math.floor(parseInt(today - notifDate) / 86400); if (t < 1) { return 'today' } else { return t.toString() + ' days ago'; } } function getNotifications() { console.log('getting notifciations notificationpage 141') ReadAPI.getNotifications(uid) .then(response => { let notifications = response.data.notifications.notifs; notifications = notifications.map(notif => { return Object.assign( {}, {...notif, date_time: getTimeElapsed(notif.date_time)} ) }); setNotifications(notifications) }) } function catchHug(hugId, id) { let data = notifications.filter((item) => item.callback_id === hugId)[0]; navigation.navigate('Hug Info', { data: { hug_id: data.callback_id, notification_id: id, clearFunction: clearNotification, pinned: false }, }) // clearNotification(id) // signify hug as caught to the database } function dropHug(hugId, id) { clearNotification(hugId) // remove hug from database } function acceptFriendRequest(friendId, id) { let friend = notifications.filter((item) => item.callback_id === friendId)[0] CreateAPI.addFriend(uid, friendId).then(); clearNotification(id) let data = { status: 'Friend', profile_pic: friend.friendPfp, name: friend.friendName, username: friend.friend_username, otheruser_id: friend.callback_id, } navigation.navigate('Friend Profile', { page: 'friendProfile', data: data }) // add friend to user friend list in database } function declineFriendRequest(friendId, id) { clearNotification(friendId) // remove friend reauest fron database } function clearNotification(id, type) { // turn this into a backend call that removes the notif DeleteAPI.deleteNotification(uid, id).then() const newList = notifications.filter((item) => item.notification_id !== id); setTimeout(() => { setNotifications(newList); }, 400); } const renderCards = notification => { let data = notification.item; return ( data.type === 'friend' ? <NotificationCard key={data.notification_id} callId={data.friendId} notificationData={data} isFocused={isFocused} handleAccept={acceptFriendRequest} handleDecline={declineFriendRequest} /> : data.type === 'f' ? <View key={'filler'} style={styles.filler}></View> : <NotificationCard key={data.notification_id} callId={data.hugId} notificationData={data} isFocused={isFocused} handleAccept={catchHug} handleDecline={dropHug} /> ) } // notification list styles const styles = StyleSheet.create({ notificationList: { marginHorizontal: 5, display: 'flex', flexShrink: 1, alignItems: 'center', marginTop: windowHeight * .14, }, filler: { height: windowHeight / 7, }, items: { alignItems: 'center', paddingTop: 10, width: windowWidth * .95 } }) // map every notification entry to a notification panel element return ( <View style={AppStyles.navPageContainer}> {/* background */} <Image source={gradient} style={AppStyles.background} /> <Header routeName={'Notifications'} navigation={navigation} onMainNav={true} > Notifications </Header> <View style={styles.notificationList}> {/* actual list */} <FlatList contentContainerStyle={styles.items} data={notifications} keyExtractor={item => item.callback_id} onRefresh={getNotifications} refreshing={false} renderItem={renderCards} /> </View> </View> ) }
/* dp 青蛙一次可以跳1级或2级台阶。跳n级台阶有多少种跳法。 */ // f(n) = f(n - 1) + f(n - 2), f(1) = 1, f(2) = 2, 故[1, 1, 2, 3] function jumpFloor(number) { if (number <= 1) return number var one = 1 var two = 1 var f = 2 for (var i = 2; i <= number; i++) { f = one + two one = two two = f } return f } // console.log(jumpFloor(5)) // 15ms 5212k
var images = ['jpg', 'png', 'jpeg', 'gif']; Ext.apply(Ext.form.field.VTypes, { imageFilter: function (val, field) { var type = val.split('.')[val.split('.').length - 1].toLocaleLowerCase(); for (var i = 0; i < images.length; i++) { if (images[i] == type) { return true; } } return false; }, imageFilterText: '文件格式錯誤', }); editFunction = function (row, store, fatherid, fathername) { //前台分類store var frontCateStore = Ext.create('Ext.data.TreeStore', { autoLoad: true, proxy: { type: 'ajax', url: '/ProductList/GetFrontCatagory', actionMethods: 'post' }, root: { expanded: true, children: [] } }); frontCateStore.load(); var editFrm = Ext.create('Ext.form.Panel', { id: 'editFrm', frame: true, plain: true, constrain: true, defaultType: 'textfield', autoScroll: true, layout: 'anchor', labelWidth: 45, url: '/ProductCategory/ProductCategorySave', items: [ { xtype: 'textfield', fieldLabel: CATEGORYID, id: 'category_id', name: 'category_id', submitValue: true, hidden: true, width: 300 }, { xtype: 'combotree', id: 'comboFrontCage', name: 'category_father_name', hiddenname: 'category_father_name', editable: false, submitValue: false, colName: 'category_father_name', store: frontCateStore, fieldLabel: FATHERCATE, width: 300, labelWidth: 100, allowBlank: false }, { hidden: true, xtype: 'textfield', id: 'comboFrontCage_hide', name: 'category_father_id', width: 10 }, { xtype: 'textfield', fieldLabel: CATEGORYNAME, id: 'category_name', name: 'category_name', submitValue: true, hidden: false, width: 300, allowBlank: false }, { xtype: 'numberfield', fieldLabel: SORT, allowBlank: false, id: 'category_sort', name: 'category_sort', minValue: 0, value: 0, allowDecimals: false, submitValue: true, width: 300, maxValue: 9999 }, { xtype: 'radiogroup', hidden: false, id: 'category_display', name: 'category_display', fieldLabel: ISSHOW, colName: 'category_display', anchor: '100%', defaults: { name: 'category_display', margin: '0 8 0 0' }, columns: 2, vertical: true, items: [ { boxLabel: SHOWSTATUS, id: 'isShow', inputValue: '1', checked: true }, { boxLabel: HIDESTATUS, id: 'noShow', inputValue: '0' } ] } , { xtype: 'radiogroup', hidden: false, id: 'category_link_mode', name: 'category_link_mode', fieldLabel: LINKMODE, colName: 'category_link_mode', anchor: '100%', defaults: { name: 'category_link_mode', margin: '0 8 0 0' }, columns: 2, vertical: true, items: [ { boxLabel: OLDWIN, id: 'ls', inputValue: '1', checked: true }, { boxLabel: NEWWIN, id: 'lm', inputValue: '2' } ] }, { xtype: 'textfield', vtype: 'url', fieldLabel: CATELINKURL, id: 'category_link_url', name: 'category_link_url', submitValue: true, hidden: false, width: 300 }, {//Banner xtype: 'filefield', name: 'photo', id: 'photo', fieldLabel: CATEBANNER, msgTarget: 'side', buttonText: SELECT_IMG, submitValue: true, allowBlank: true, fileUpload: true, hidden: false, width: 300, vtype: 'imageFilter' }, { xtype: 'filefield', name: 'image_in', id: 'image_in', fieldLabel: CATEBANNERIN, msgTarget: 'side', buttonText: SELECT_IMG, submitValue: true, allowBlank: true, fileUpload: true, hidden: false, width: 300, vtype: 'imageFilter' }, { xtype: 'filefield', name: 'image_out', id: 'image_out', fieldLabel: CATEBANNEROUT, msgTarget: 'side', buttonText: SELECT_IMG, submitValue: true, allowBlank: true, fileUpload: true, hidden: false, width: 300, vtype: 'imageFilter' }, { xtype: 'filefield', name: 'category_image_app', id: 'category_image_app', fieldLabel: CATEAPP, msgTarget: 'side', buttonText: SELECT_IMG, submitValue: true, allowBlank: true, fileUpload: true, hidden: false, width: 300, vtype: 'imageFilter' }, { xtype: 'radiogroup', hidden: false, id: 'banner_status', name: 'banner_status', fieldLabel: BANNERSTATUS, colName: 'banner_status', defaults: { name: 'banner_status', margin: '0 8 0 0' }, columns: 2, vertical: true, items: [ { boxLabel: ACTIVE, id: 'isStatus', inputValue: '1', checked: true }, { boxLabel: NOTACTIVE, id: 'noStatus', inputValue: '2' } ] } , { xtype: 'radiogroup', hidden: false, id: 'banner_link_mode', name: 'banner_link_mode', fieldLabel: BANNERLINKMODE, colName: 'banner_link_mode', defaults: { name: 'banner_link_mode', margin: '0 8 0 0' }, columns: 2, vertical: true, items: [ { boxLabel: OLDWIN, id: 'link_mode1', inputValue: '1', checked: true, width: 150 }, { boxLabel: NEWWIN, id: 'link_mode12', inputValue: '2' } ] } , { xtype: 'textfield', fieldLabel: BANNERLINKURL, id: 'banner_link_url', name: 'banner_link_url', submitValue: true, hidden: false, width: 300, vtype: 'url' }, { xtype: "datetimefield", fieldLabel: BANNERSTART, editable: false, id: 'startdate', name: 'start_date', format: 'Y-m-d H:i:s', width: 300, allowBlank: false, submitValue: true, time: { hour: 00, min: 00, sec: 00 }, listeners: { select: function (a, b, c) { var start = Ext.getCmp("startdate"); var end = Ext.getCmp("enddate"); if (start.getValue() > end.getValue() && end.getValue() != null) { Ext.Msg.alert(INFORMATION, "開始時間不能大於結束時間"); end.setValue(""); } } } }, { xtype: "datetimefield", fieldLabel: BANNEREND, editable: false, id: 'enddate', name: 'end_date', format: 'Y-m-d H:i:s', width: 300, allowBlank: false, submitValue: true, // time: { hour: 23, min: 59, sec: 59 }, listeners: { select: function (a, b, c) { var start = Ext.getCmp("startdate"); var end = Ext.getCmp("enddate"); if (end.getValue() < start.getValue()) { Ext.Msg.alert(INFORMATION, TIMETIP); end.setValue(""); } } } }, { xtype: 'textareafield', fieldLabel: '短文字說明 (300字內)', id: 'short_description', name: 'short_description', width: 300, maxLength: 300 } ], buttons: [{ formBind: true, disabled: true, text: SAVE, handler: function () { var form = this.up('form').getForm(); if (form.isValid()) { var myMask = new Ext.LoadMask(Ext.getBody(), { msg: "loading..." }); myMask.show(); form.submit({ params: { comboFrontCage: Ext.getCmp('comboFrontCage_hide').getValue() == '' ? '' : Ext.htmlEncode(Ext.getCmp('comboFrontCage_hide').getValue()), category_id: Ext.htmlEncode(Ext.getCmp('category_id').getValue()), category_name: Ext.htmlEncode(Ext.getCmp('category_name').getValue()), category_sort: Ext.htmlEncode(Ext.getCmp('category_sort').getValue()), category_display: Ext.htmlEncode(Ext.getCmp('category_display').getValue()), categorylinkmode: Ext.htmlEncode(Ext.getCmp('category_link_mode').getValue().category_link_mode), category_link_url: Ext.htmlEncode(Ext.getCmp('category_link_url').getValue()), photo: Ext.htmlEncode(Ext.getCmp('photo').getValue()), banner_status: Ext.htmlEncode(Ext.getCmp('banner_status').getValue().banner_status), banner_link_mode: Ext.htmlEncode(Ext.getCmp('banner_link_mode').getValue().banner_status), banner_link_url: Ext.htmlEncode(Ext.getCmp('banner_link_url').getValue()), startdate: Ext.htmlEncode(Ext.getCmp('startdate').getRawValue()), enddate: Ext.htmlEncode(Ext.getCmp('enddate').getRawValue()), short_description: Ext.htmlEncode(Ext.getCmp('short_description').getValue()), image_in: Ext.htmlEncode(Ext.getCmp('image_in').getValue()), image_out: Ext.htmlEncode(Ext.getCmp('image_out').getValue()), category_image_app: Ext.htmlEncode(Ext.getCmp('category_image_app').getValue()) }, success: function (form, action) { myMask.hide(); var result = Ext.decode(action.response.responseText); if (result.success) { Ext.Msg.alert(INFORMATION, SAVESUCCESS); ProductCategoryStore.load({ params: { father_id: Ext.getCmp('comboFrontCage_hide').getValue() == '' ? '' : Ext.htmlEncode(Ext.getCmp('comboFrontCage_hide').getValue()) } }); editWin.close(); } else { Ext.Msg.alert(INFORMATION, SAVEFILURE); ProductCategoryStore.load(); editWin.close(); } }, failure: function (form, action) { myMask.hide(); var result = Ext.decode(action.response.responseText); Ext.Msg.alert(INFORMATION, SAVEFILURE); ProductCategoryStore.load(); editWin.close(); } }); } } }] }); var editWin = Ext.create('Ext.window.Window', { title: CATEEDIT, iconCls: 'icon-user-edit', id: 'editWin', width: 400, height: 400, y: 100, layout: 'fit', items: [editFrm], constrain: true, closeAction: 'destroy', modal: true, resizable: false, labelWidth: 60, bodyStyle: 'padding:5px 5px 5px 5px', closable: false, tools: [ { type: 'close', qtip: ISCLOSE, handler: function (event, toolEl, panel) { Ext.MessageBox.confirm(CONFIRM, IS_CLOSEFORM, function (btn) { if (btn == "yes") { Ext.getCmp('editWin').destroy(); } else { return false; } }); } } ], listeners: { 'show': function () { if (row != null) { editFrm.getForm().loadRecord(row); if (row.data.banner_link_url == "0" || row.data.banner_link_url == null || row.data.banner_link_url == "") { Ext.getCmp("banner_link_url").setValue(""); } if (row.data.category_link_url == "0" || row.data.category_link_url == null || row.data.category_link_url == "") { Ext.getCmp("category_link_url").setValue(""); } //switch (row.data.category_display) { // case 1: // Ext.getCmp("isShow").setValue(true); // break; // case 0: // Ext.getCmp("noShow").setValue(true); // break; //} switch (row.data.category_display) { case 1: Ext.getCmp("isShow").setValue(true); break; case 0: Ext.getCmp("noShow").setValue(true); break; }; switch (row.data.category_link_mode) { case 1: Ext.getCmp("ls").setValue(true); break; case 2: Ext.getCmp("lm").setValue(true); break; default: Ext.getCmp("lm").setValue(true); break; }; switch (row.data.banner_status) { case 1: Ext.getCmp("isStatus").setValue(true); break; case 2: Ext.getCmp("noStatus").setValue(true); break; default: Ext.getCmp("noStatus").setValue(true); break; }; switch (row.data.banner_link_mode) { case 1: Ext.getCmp("link_mode1").setValue(true); break; case 2: Ext.getCmp("link_mode12").setValue(true); break; default: Ext.getCmp("link_mode12").setValue(true); break; }; Ext.getCmp('photo').setRawValue(row.data.banner_image); //Ext.getCmp('comboFrontCage_hide').setValue(row.data.category_father_id); Ext.getCmp('comboFrontCage').setValue(row.data.category_father_name); Ext.getCmp('comboFrontCage_hide').setValue(row.data.category_father_id); Ext.getCmp('image_in').setRawValue(row.data.category_image_in); Ext.getCmp('image_out').setRawValue(row.data.category_image_out); Ext.getCmp('category_image_app').setRawValue(row.data.category_image_app); } else { Ext.getCmp('comboFrontCage').setValue(fathername); Ext.getCmp('comboFrontCage_hide').setValue(fatherid); } } } }); editWin.show(); //時間 function Tomorrow() { var d; d = new Date(); // 创建 Date 对象。 d.setDate(d.getDate() + 1); return d; } }
import React from 'react' import './Sidenavright.css' import rightSideArray from './Datarightside' import {BrowserRouter as Router , Switch,Route,Link} from 'react-router-dom' const Sidenavright = () => { return ( <Router> <div className="sideRightNavContainer"> <Link to="" className="btn heading"> Diwali Preparation Sale </Link> { rightSideArray.map((item)=>{ const {id,image,name} = item; return( <div className="rightWrapper"> <div className="rightTitle"> <p>{name}</p> <Link to="" className="btn source"> Source Now </Link> </div> <div className="rightImg"> <img src={image} alt=""/> </div> </div> ) }) } </div> </Router> ) } export default Sidenavright
// Change to your lambda endpoint here var lambdaurl = 'https://private.covcough.com'; // Temporary redirect when the app is still in development. if (document.location.origin.indexOf("localhost") == -1 && document.location.origin.indexOf("192.168") == -1 && document.location.origin.indexOf("surge.sh") == -1){ // document.location = "./underconstruction.html"; }
import { getPortfolioItemById } from "../../lib/portfolio"; import PortfolioItemHeader from "../../components/pages/Portfolio/PortfolioItemHeader"; const itemId = "ddb9da7e-5031-11eb-ae93-2342397afsdf"; const PortfolioPage = ({ portfolioItem }) => { const [galleryShowing, setGalleryShowing] = React.useState(false); const { title, subtitle, tech, roles } = portfolioItem; return ( <section id="PortfolioArticle"> <PortfolioItemHeader {...portfolioItem} video="/video/cummins_laptop.mp4" smallText /> <div className="container"> <div className="row mt-5"> <div className="col"> <h4>App Overview</h4> <p> This app was developed utilizing primarily Backbone and jQuery and built to serve as an information portal for various components of Cummins training. The application also leveraged LESS CSS preprocessing to allow for quick rebranding and theming of the “emag”. Overall, we developed 5-7 versions of these resources’ libraries utilizing my framework to facilitate different training initiatives. </p> <p> This app came early in the life-cycle of the eMag development, so is slightly not as polished as future versions (similar to the one in my Roche sample). I didn’t get much budget for these, but I’d work my tail off to have a little extra time to add one new feature, or one new area of polish each time we sold one of these. </p> <p> LESS variables would allow rebranding of the entire application in seconds, allowing us to focus on custom content creation for each version of the application. </p> <p> Not the sexiest thing in the world, but with the routing, bookmark ability, subtle animation, and other various components, it was something that would help sell projects as a value add, in that we could create them for a few days of dev effort. </p> {/* <img src="/images/pages/portfolio/jhu/search.png" alt="search" className="img-thumbnail img-fluid" style={{ width: "100%" }} /> */} </div> </div> </div> </section> ); }; export async function getStaticProps(context) { const portfolioItem = getPortfolioItemById(itemId); return { props: { portfolioItem, }, }; } export default PortfolioPage;
$(document).ready(function() { /* mouseover - mouse on the object mouseout - out of the mouse from the object click - click by mouse on the object dblclick - double click by the mouse on the object mousemove - moving of the mouse mousedown - moment of clicking by mouse on the object mouseup - moment of leaving mouse from the object submit - sending form focus - moment of receiving the object focus blur - moment of leaving the object focus change - changing the form reset - reseting the form keypress - press the key on the keyboard keydown - moment of pressing the key keyup - moment of leaving the pressed key load - full loading of the page resize - changing the size of the browser scroll - scrolling the browser window unload - leaving the page */ }); // End of ready
/// <autosync enabled="true" /> /// <reference path="js/common/loadingdirective.js" /> /// <reference path="js/login/constants.js" /> /// <reference path="js/login/login.js" /> /// <reference path="js/login/services.js" /> /// <reference path="lib/angular/angular.js" /> /// <reference path="lib/angular-bootstrap/ui-bootstrap-tpls.js" /> /// <reference path="lib/angular-translate/angular-translate.js" /> /// <reference path="lib/bootstrap/dist/js/bootstrap.js" /> /// <reference path="lib/jquery/dist/jquery.js" />
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; // Displayed Components across the app import AppNavbar from '../AppNavbar/AppNavbar'; import BackButton from '../BackButton/BackButton'; // Page Views import Home from '../Home/Home'; import OrderChoice from '../OrderChoice/OrderChoice'; import OrderHistory from '../OrderHistory/OrderHistory'; import CreatePizza from '../CreatePizza/CreatePizza'; import Cart from '../Cart/Cart'; import Confirmation from '../Confirmation/Confirmation'; import Register from '../Register/Register'; import SpecialtyPizzas from '../SpecialtyPizzas/SpecialtyPizzas'; import SizeQuantityPrompt from '../SpecialtyPizzas/SizeQuantityPrompt'; import MenuChoice from '../MenuChoice/MenuChoice' import { loadCustomer } from '../../actions/auth'; import { getAllToppings } from '../../actions/database'; import classes from './App.module.css'; // This example is for how to use graphql to persist data to backend. // import Example from "./example"; class App extends Component { constructor(props) { super(props); this.getViewState = this.getViewState.bind(this); } componentDidMount() { // Check user token in local storage and load authenticated user this.props.loadCustomer(); //Get all possible toppings this.props.getAllToppings(); } /* Render Home, Main, or a preferred component based on the step of the menu */ getViewState() { switch (this.props.step) { case 1: return this.props.isAuthenticated ? <OrderChoice /> : <Home />; case 2: return <OrderHistory />; case 3: return <CreatePizza />; case 4: return <Cart />; case 5: return <Confirmation />; case 6: return <Register />; case 7: return <SpecialtyPizzas/>; case 8: return <SizeQuantityPrompt/>; case 9: return <MenuChoice />; default: return null; } } render() { return ( <div data-test="component-App" className={classes.main}> <div className={classes.header}> <AppNavbar /> <BackButton /> </div> <div className={classes.container}> {/* code to see example connection to send data to db */} {/* <Example></Example> */} {/* Render Home, Main, or a preferred component based on the step of the menu */} {this.getViewState()} </div> </div> ); } } const mapStateToProps = (state) => ({ step: state.menu.step, isAuthenticated: state.auth.isAuthenticated, }); App.propTypes = { step: PropTypes.number.isRequired, isAuthenticated: PropTypes.bool.isRequired, loadCustomer: PropTypes.func.isRequired, }; export default connect(mapStateToProps, { loadCustomer, getAllToppings })(App);
function setup() { createCanvas(600 , 600); img = createCapture(VIDEO); img.hide(); img.size(600,600); } function draw() { background(255); img.loadPixels(); for (var y=50;y<=img.height ; y++/i) { for (var x=100;x<img.width; x+=50) { var i = y * width + (img.width-x-1); const darkness = (20 - img.pixels[i * 4]) / 125; const radius = 256 * darkness; fill(255); ellipse(x, y, radius, radius); } } }
import React from 'react' import { renderToString } from 'react-dom/server' import { StaticRouter, Route, matchPath } from 'react-router-dom' import { Helmet } from 'react-helmet' import { Provider } from 'react-redux' import { renderRoutes } from 'react-router-config' import Loadable from 'react-loadable' import { getBundles } from 'react-loadable/webpack' import stats from '../../public/react-loadable.json'; export const render = (req, store, Routes, context) => { let modules = [] const content = renderToString(( <Provider store={store}> <Loadable.Capture report={moduleName => modules.push(moduleName)}> <StaticRouter location={req.path} context={context}> <div> {renderRoutes(Routes)} </div> </StaticRouter> </Loadable.Capture> </Provider> )) const helmet = Helmet.renderStatic(); let bundles = getBundles(stats, modules); const css = context.css.length ? context.css.join('\n') : '' return ( ` <html> <head> ${helmet.title.toString()} ${helmet.meta.toString()} <style>${css}</style> </head> <body> <div id="root">${content}</div> <script> window.context = { state: ${JSON.stringify(store.getState())} } </script> ${bundles.map(bundle => { return `<script src="${bundle.file}"></script>` }).join('\n')} <script src='./index.js'></script> </body> </html> ` ) }
import React from 'react'; import styled from 'styled-components'; import { Button } from '../Other/Button'; import MenuPopup from './MenuPopup'; import { Login as PopupLogin, CustomLink as CustomPopupLink, Signup as PopupSignup } from './MenuPopup'; import logo from '../../assets/images/logo-header.svg'; import menu from '../../assets/icons/menu.svg'; import closeMenu from '../../assets/icons/close-menu.svg'; import { colors } from '../../styles/colors'; import { desktop } from '../../styles/responsive'; const Header = ({ onClick, menuVisible, width }) => { return ( <Container> <Logo src={logo} alt="Shortly Home Logo" onClick={() => window.location.reload()} /> {width < 1024 ? <MenuBtn type="button" menuVisible={menuVisible} onClick={() => onClick('menu')} /> : <> <Links> <CustomLink href="#root">Features</CustomLink> <CustomLink href="#root">Pricing</CustomLink> <CustomLink href="#root">Resources</CustomLink> </Links> <Signup> <Login href="#root">Login</Login> <SignupBtn type="button" whileTap={{ scale: 0.96 }}>Sign Up</SignupBtn> </Signup> </> } {width < 1024 && <MenuPopup isMounted={menuVisible} />} </Container> ); } export default Header; const Container = styled.header` height: 5rem; width: 86%; max-width: 30rem; margin: 0 auto; display: flex; justify-content: space-between; align-items: center; @media ${desktop} { width: 80%; max-width: 64rem; height: 7rem; justify-content: flex-start; } `; export const Logo = styled.img` width: 6rem; cursor: pointer; @media ${desktop} { width: 7rem; } `; const MenuBtn = styled.button` border: none; outline: none; background-color: transparent; cursor: pointer; width: 1.5rem; height: 1.5rem; position: relative; transition: transform 0.4s; transform: ${({ menuVisible }) => `rotate(${menuVisible * 360}deg)`}; &::before { content: ''; position: absolute; top: 0.125rem; left: 0.125rem; display: block; width: 1.25rem; height: 1.25rem; background: url(${closeMenu}) no-repeat center; transition: opacity 0.2s ease-out; transition-delay: ${({ menuVisible }) => `${menuVisible * 0.2}s`}; opacity: ${({ menuVisible }) => +menuVisible}; } &::after { content: ''; position: absolute; top: 0; left: 0; display: block; width: 1.5rem; height: 1.5rem; background: url(${menu}) no-repeat center; transition: opacity 0.2s ease-out; transition-delay: ${({ menuVisible }) => `${(1 - menuVisible) * 0.2}s`}; opacity: ${({ menuVisible }) => +!menuVisible}; } `; const Links = styled.div` margin-left: 2rem; `; const CustomLink = styled(CustomPopupLink)` color: ${colors['grayish-violet']}; margin: 0 0.75rem; transition: color 0.3s; &:hover { color: ${colors['very-dark-blue']}; } &:focus { color: ${colors['very-dark-blue']}; outline: 0.125rem dashed ${colors['very-dark-blue']}; } `; const Signup = styled(PopupSignup)` flex-direction: row; margin-left: auto; `; const Login = styled(PopupLogin)` color: ${colors['grayish-violet']}; margin-right: 1.5rem; &:focus { outline: 0.125rem dashed ${colors['grayish-violet']}; } `; const SignupBtn = styled(Button)` width: 6.8rem; height: 2.4rem; border-radius: 1.2rem; @media ${desktop} { width: 7rem; height: 2.6rem; border-radius: 1.3rem; } `;
// Components import ShowsListItem from '@/components/ShowsListItem.vue' // Utilities import { appInit } from './app-init' import { createLocalVue, shallowMount } from '@vue/test-utils' const localVue = appInit(createLocalVue()) describe('ShowsListItem.vue', () => { let wrapper const mountFunction = options => { return shallowMount(ShowsListItem, { localVue, propsData: { item: { id: 1, name: 'Test', }, }, ...options, }) } beforeEach(() => { wrapper = mountFunction() }) afterEach(() => { wrapper.destroy() }) it('should be a Vue instance and be called ShowsListItem', () => { expect(wrapper.isVueInstance()).toBeTruthy() expect(wrapper.name()).toMatch('ShowsListItem') }) })
import { connect } from '../../../lib/wechat-weapp-redux' import { clearError } from '../../../store/actions/loader' import { alertError } from '../../../utils' import { categorymerchandise } from '../../../api/homePage' import regeneratorRuntime from '../../../lib/regenerator-runtime' import { USER_ROLE } from '../../../constants' const mapStateToData = (state, options) => { return { isFetching: state.loader.isFetching, displayError: state.loader.displayError, id: state.global.group && state.global.group.id, location: state.global.location, profile: state.mine.profile } } const mapDispatchToPage = dispatch => ({ clearError: _ => dispatch(clearError()) }) const pageConfig = { data:{ USER_ROLE, page: 1, limit: 10, completed: false, goodsList: [] }, async onLoad (options) { const { id } = this.data const { categoryId } = options const { page, limit } = this.data this.setData({ categoryId }) try{ wx.showLoading() const { data: goodsList} = await categorymerchandise({ id, provinceId: this.data.location.province.id, categoryId, page, limit }) this.setData({ goodsList }) } catch(err) { alertError(err) } finally { wx.hideLoading() } }, // Tab async changeTab (event) { const { id, page, limit } = this.data let { completed } = this.data const { categoryId } = event.target.dataset this.setData({ categoryId }) wx.showLoading() try{ const { totalCount, totalPages, data: goodsList} = await categorymerchandise({ id, cityId: this.data.location.city.id, provinceId: this.data.location.province.id, categoryId: categoryId, page, limit }) if(page >= totalPages) { completed = true } this.setData({ goodsList, categoryId }) } catch (err) { alertError(err) } finally { wx.hideLoading() } }, // onReachBottom async onReachBottom (options) { console.log("jiazai...") const { id } = this.data const { categoryId } = this.data console.log(categoryId) const { limit, goodsList } = this.data let { page, completed } = this.data if(completed) return this.setData({ page: ++page }) wx.showLoading() try { const { totalCount, totalPages, data: goodsLists } = await categorymerchandise({ id, provinceId: this.data.location.province.id, categoryId: categoryId, page, limit }) if(page >= totalPages) { completed = true } this.setData({completed, goodsList: [...goodsList, ...goodsLists]}) } catch (err) { alertError(err) } finally { wx.hideLoading() } }, selectThing () { console.log("搜索商品") wx.navigateTo({ url:'/pages/group/merchSearch/merchSearch' }) }, gotoMerchShow (event) { console.log("商品详情页") const { id } = event.currentTarget.dataset wx.navigateTo({ url: `/pages/group/merchShow/merchShow?id=${id}` }) }, reload () { this.clearError() this.onShow(this.options) }, onUnload () { this.clearError() } } Page( connect( mapStateToData, mapDispatchToPage )(pageConfig) )
/** * @license * * Copyright IBM Corp. 2020 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; const path = require('path'); const acceptLanguageParser = require('accept-language-parser'); const Handlebars = require('handlebars'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const rtlDetect = require('rtl-detect'); const templateCache = {}; const reCssBundle = /\.css\.js$/i; const devServer = { contentBase: path.resolve(__dirname, 'src'), setup(app, server) { app.get('/', (req, res) => { const { fileSystem, waitUntilValid } = server.middleware; waitUntilValid(async () => { // Determins user's preferred language const { code, region } = acceptLanguageParser.parse(req.headers['accept-language'])[0]; const dir = !rtlDetect.isRtlLang(code) ? 'ltr' : 'rtl'; // Renders the Handlebars template from the data const filename = path.resolve(__dirname, 'dist/index.hbs'); if (!templateCache[filename]) { templateCache[filename] = Handlebars.compile(fileSystem.readFileSync(filename).toString()); } res.setHeader('Content-Type', 'text/html'); res.setHeader('Cache-Control', 'public, max-age=0'); res.send( templateCache[filename]({ dir, lang: !region ? code : `${code}-${region}`, }) ); res.end(); }); }); }, }; function getConfig(dir) { return { output: { filename: `bundle-${dir}.js`, }, plugins: [ // Puts `.hbs` file into WebPack Dev Server's virtual file system. // If you have other means to load `.hbs` file, this is not needed. new HtmlWebpackPlugin({ template: 'index.hbs', filename: 'index.hbs', inject: false, }), // Uses `.rtl.css.js` instead of `.css.js` for RTL bundle new webpack.NormalModuleReplacementPlugin(reCssBundle, resource => { if (dir === 'rtl') { resource.request = resource.request.replace(reCssBundle, '.rtl.css.js'); } }), ], }; } module.exports = [Object.assign(getConfig('ltr'), { devServer }), getConfig('rtl')];
// ==UserScript== // @name Ogame Alert Notifier // @namespace // @description Ogame Alert Notifier // @author Lidmaster & Eigna // @version 1 // @include http://*.ogame.*/* // @copyright Copyright (C) 2013 by Lidmaster (Italian translation by BoGnY | www.worldoftech.it) // ==/UserScript== var version = '1'; // ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### // ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### // ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### {// ##OAN3## Variables var p,h,n1,n2,n3; var a = 1; var b = 1; var body = document; var url = location.href; var serveur = url.split('/')[2]; var s_h_timer = getVar("s_h_timer",1); var sMIN = getVar("sMIN",60); var sMAX = getVar("sMAX",180); var swt_stt = getVar("swt_stt",1); var cnt_time = (parseInt(sMIN) + Math.round(Math.random() * (sMAX - sMIN))); var snd_spy = getVar("snd_spy",'OFF'); var snd_atak = getVar("snd_atak",'OFF'); var snd_mess = getVar("snd_mess",'OFF'); var bodyId = document.getElementsByTagName("body")[0].id; var page_exclu = (bodyId != 'messages')&&(bodyId != 'resources')&&(bodyId != 'highscore')&&(bodyId != 'alliance')&&(bodyId != 'galaxy')&&(bodyId != 'preferences')&&(bodyId != 'traderOverview')&&(bodyId != 'fleet1')&&(bodyId != 'fleet2')&&(bodyId != 'fleet3'); var sp = document.getElementById("planetList"); var count = sp.getElementsByTagName('div').length; var metas = document.getElementsByTagName('META'); }// ##OAN3## Variables {// ##OAN3## Selection de la langue + Variable de texte var i;for (i = 0; i < metas.length; i++) if (metas[i].getAttribute('NAME') == "ogame-universe")break; var meta_uni = metas[i].getAttribute('CONTENT'); var act_meta_uni= meta_uni; var lang = 'fr'; if( lang == 'fr'){ var txt_1 = 'Activer/Désactiver les alertes sonore des message'; var txt_2 = 'Activer/Désactiver les alertes sonore des espionnages'; var txt_3 = 'Activer/Désactiver les alertes sonore des attaque'; var txt_4 = 'Afficher/Masquer réglages de l\'auto-refresh'; var txt_5 = 'Temps de refresh'; var txt_6 = 'sec (min)'; var txt_7 = 'sec (max)'; var txt_8 = 'Sauvegarder'; var txt_9 = 'Pas de refresh'; var txt_10 = 'Refresh sur la planète active'; var txt_11 = 'Refresh sur la planète suivante'; var txt_12 = 'Refresh in '; var txt_13 = 'No Refresh'; } else if( lang == 'it'){ var txt_1 = 'Attiva/Disattiva avviso sonoro messaggio ricevuto'; var txt_2 = 'Attiva/Disattiva avviso sonoro spiata ricevuta'; var txt_3 = 'Attiva/Disattiva avviso sonoro attacco in corso'; var txt_4 = 'Mostra/Nascondi impostazioni auto-refresh'; var txt_5 = 'Impostazioni refresh'; var txt_6 = 'sec (min)'; var txt_7 = 'sec (max)'; var txt_8 = 'Salva'; var txt_9 = 'Disattiva auto-refresh'; var txt_10 = 'Attiva auto-refresh sul pianeta'; var txt_11 = 'Attiva auto-refresh sul pianeta successivo'; var txt_12 = 'Refresh in '; var txt_13 = 'No Refresh'; } else { var txt_1 = 'Enable/Disable sound alert for message'; var txt_2 = 'Enable/Disable sound alert for spy'; var txt_3 = 'Enable/Disable sound alert for attack'; var txt_4 = 'Show/Hide settings for auto-refresh'; var txt_5 = 'Refresh settings'; var txt_6 = 'sec (min)'; var txt_7 = 'sec (max)'; var txt_8 = 'Save'; var txt_9 = 'Disable auto-refresh'; var txt_10 = 'Enable auto-refresh on planet'; var txt_11 = 'Enable auto-refresh on next planet'; var txt_12 = 'Refresh in '; var txt_13 = 'No Refresh'; } }// ##OAN3## Selection de la langue + Variable de texte // ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### // ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### // ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### {// ##OAN3## Division - MaxiOAN p = document.getElementById('rechts');//rechts//myPlanets h = p.insertBefore(document.createElement("div" ),p.firstChild); h.id = "maxi_oan"; }// ##OAN3## Division - MaxiOAN {// ##OAN3## Division - Switch Sound p = document.getElementById("maxi_oan"); h = document.createElement("div"); h.id = "div_switch"; h.setAttribute('style',';width:150px;height:30px;margin:0px 0px 0px 0px;text-align:center;color: #8ECEFF;background:url("http://imageshack.com/scaled/medium/15/aau6.png") no-repeat;background-size:150px 30px;'); p.appendChild(h); }// ##OAN3## Division - Switch {// ##OAN3## Division - Switch - Boutton - Messages p = document.getElementById("div_switch"); h = document.createElement("a"); h.id = "div_switch_bt_message"; n1 = ''; if( snd_mess == 'ON' ){ n1 += '<img title="'+txt_1+'" class="tooltip" style="display:inline;" width="25px" height="25px" src="http://imageshack.com/scaled/large/268/c3yc.png">';} else{ n1 += '<img title="'+txt_1+'" class="tooltip" style="display:inline;" width="25px" height="25px" src="http://imageshack.com/scaled/large/194/meza.png">';} n1 += '<input type="hidden" id="snd_mess" value="'+snd_mess+'">'; h.innerHTML = n1; h.addEventListener("click",function(){m_a_snd_mess();},false); p.appendChild(h); }// ##OAN3## Division - Switch - Boutton - Messages {// ##OAN3## Division - Switch - Boutton - Espionnages p = document.getElementById("div_switch"); h = document.createElement("a"); h.id = "div_switch_bt_spy"; n1 = ''; if( snd_spy == 'ON' ){ n1 += '<img title="'+txt_2+'" class="tooltip" style="display:inline;" width="25px" height="25px" src="http://imageshack.com/scaled/large/849/3iyo.png">'; } else{ n1 += '<img title="'+txt_2+'" class="tooltip" style="display:inline;" width="25px" height="25px" src="http://imageshack.com/scaled/large/5/9i2v.png">';} n1 += '<input type="hidden" id="snd_spy" value="'+snd_spy+'">'; h.innerHTML = n1; h.addEventListener("click",function(){m_a_snd_spy();},false); p.appendChild(h); }// ##OAN3## Division - Switch - Boutton - Espionnages {// ##OAN3## Division - Switch - Boutton - Attaques p = document.getElementById("div_switch"); h = document.createElement("a"); h.id = "div_switch_bt_atak"; n1 = ''; if( snd_atak == 'ON' ){ n1 += '<img title="'+txt_3+'" class="tooltip" style="display:inline;" width="25px" height="25px" src="http://imageshack.com/scaled/large/11/a92e.png">'; } else{ n1 += '<img title="'+txt_3+'" class="tooltip" style="display:inline;" width="25px" height="25px" src="http://imageshack.com/scaled/large/845/p3bk.png">';} n1 += '<input type="hidden" id="snd_atak" value="'+snd_atak+'">'; h.innerHTML = n1; h.addEventListener("click",function(){m_a_snd_atak();},false); p.appendChild(h); }// ##OAN3## Division - Switch - Boutton - Attaques {// ##OAN3## Division - Switch - Boutton - Reglage Timer p = document.getElementById("div_switch"); h = document.createElement("a"); h.id = "div_switch_bt_timeset"; n1 = ''; n1 += '<img title="'+txt_4+'" class="tooltip" style="display:inline;" width="25px" height="25px" src="http://imageshack.com/scaled/large/24/5lth.png">'; h.innerHTML = n1; h.addEventListener("click",function(){f_s_h_timer();},false); p.appendChild(h); }// ##OAN3## Division - Switch - Boutton - Reglage Timer {// ##OAN3## Division - Timer if ( s_h_timer == 1 ){ p = document.getElementById("maxi_oan"); h = document.createElement("div"); h.id = "div_timer"; h.setAttribute('style',';width:150px;height:100px;background:url("http://imageshack.com/scaled/medium/15/aau6.png") no-repeat;background-size:150px 100px;'); n1 = ''; // n1 += '<div style="text-align:center;line-height:15px;font-family:Verdana,Arial,SunSans-Regular,Sans-Serif;font-size:10px;color: #FF9900;"><b>'+txt_5+'</b></div>'; n1 += '<span style="padding:0px 0px 0px 10px;"><input id="Smin" name="Smin" type="input" size="1" value="'+sMIN+'"> '+txt_6+'<br></span>'; n1 += '<span style="padding:0px 0px 0px 10px;"><input id="Smax" name="Smax" type="input" size="1" value="'+sMAX+'"> '+txt_7+'<br></span>'; n1 += '<div style="text-align:center;margin: 3px 0px 3px 0px;" id="bt_save"><input type="button" value="'+txt_8+'" title="" ></div>'; n1 += '<div style="text-align:center;line-height:15px;font-family:Verdana,Arial,SunSans-Regular,Sans-Serif;font-size:10px;color: #FF9900;"><b>'+txt_5+'</b></div>'; h.innerHTML = n1 ; p.appendChild(h); n2 = document.getElementById("bt_save"); n2.addEventListener("click",function(){save_timer();},false);} }// ##OAN3## Division - Timer {// ##OAN3## Division - Switch Refresh p = document.getElementById("maxi_oan"); h = document.createElement("div"); h.id = "maxi_swt"; h.setAttribute('style',';width:150px;height:25px;padding:2px 0px 0px 0px;text-align:center;color: #8ECEFF;background:url("http://imageshack.com/scaled/medium/15/aau6.png") no-repeat;background-size:150px 27px;'); n1 = ''; n1 += '<span id="swt_1"></span>'; n1 += '<span id="swt_2"></span>'; n1 += '<span id="swt_3"></span>'; h.innerHTML = n1; p.appendChild(h); }// ##OAN3## Division - maxi_swt {// ##OAN3## Division - ins_swt_1 p = document.getElementById("swt_1"); h = document.createElement("a"); h.id = "ins_swt_1"; n1 = '<img title="'+txt_9+'" class="tooltip" width="20px" height="20px" style="display:inline;" src="http://imageshack.us/a/img513/5736/e0p.png">'; h.innerHTML = n1; h.addEventListener("click",function(){set_stt_1();},false); p.appendChild(h); function set_stt_1(){ setVar("swt_stt",1); window.location.replace( unescape(window.location) ); } }// ##OAN3## Division - ins_swt_1 {// ##OAN3## Division - ins_swt_2 p = document.getElementById("swt_2"); h = document.createElement("a"); h.id = "ins_swt_2"; n1 = '<img title="'+txt_10+'" class="tooltip" width="20px" height="20px" style="display:inline;" src="http://imageshack.us/a/img96/1693/dtik.png">'; h.innerHTML = n1; h.addEventListener("click",function(){set_stt_2();},false); p.appendChild(h); function set_stt_2(){ setVar("swt_stt",2); window.location.replace( unescape(window.location) ); } }// ##OAN3## Division - ins_swt_2 {// ##OAN3## Division - ins_swt_3 p = document.getElementById("swt_3"); h = document.createElement("a"); h.id = "ins_swt_3"; n1 = ''; n1 += ''; n1 += '<img title="'+txt_11+'" class="tooltip" width="20px" height="20px" style="display:inline;" src="http://img27.imageshack.us/img27/7018/2ww1.png">'; n1 += ''; n1 += ''; h.innerHTML = n1; h.addEventListener("click",function(){set_stt_3();},false); p.appendChild(h); function set_stt_3(){ setVar("swt_stt",3); window.location.replace( unescape(window.location) ); } }// ###OAN3## Division - ins_swt_3 {// ##OAN3## Division - CountDown if ( (swt_stt == 2)&&(page_exclu == true ) ){ var interval = setInterval(function() {document.getElementById('count').innerHTML = --cnt_time;if (cnt_time <= 0){clearInterval(interval);}},1000); p = document.getElementById('maxi_oan'); h = document.createElement('div'); h.id = 'div_count'; h.setAttribute('style',';width:150px;height:20px;padding:1px 0px 0px 0px;text-align:center;color: #8ECEFF;background:url("http://imageshack.com/scaled/medium/15/aau6.png") no-repeat;background-size:150px 21px;'); n1 = ''; n1 += '<b><img width="15px" height="15px" style="display:inline;" src="http://imageshack.us/a/img96/1693/dtik.png">'+txt_12+'<span id="count"></span>s <img width="15px" height="15px" style="display:inline;" src="http://imageshack.us/a/img96/1693/dtik.png"></b>'; h.innerHTML = n1 ; p.appendChild(h); } else if ( (swt_stt == 3)&&(page_exclu == true ) ){ var interval = setInterval(function() {document.getElementById('count').innerHTML = --cnt_time;if (cnt_time <= 0){clearInterval(interval);}},1000); p = document.getElementById('maxi_oan'); h = document.createElement('div'); h.id = 'div_count'; h.setAttribute('style',';width:150px;height:20px;padding:1px 0px 0px 0px;text-align:center;color: #8ECEFF;background:url("http://imageshack.com/scaled/medium/15/aau6.png") no-repeat;background-size:150px 21px;'); n1 = ''; n1 += '<b><img width="15px" height="15px" style="display:inline;" src="http://img27.imageshack.us/img27/7018/2ww1.png">'+txt_12+' <span id="count"></span>s <img width="15px" height="15px" style="display:inline;" src="http://img27.imageshack.us/img27/7018/2ww1.png"></b>'; h.innerHTML = n1 ; p.appendChild(h); } else if ( (swt_stt == 1)&&(page_exclu == true ) ){ p = document.getElementById('maxi_oan'); h = document.createElement('div'); h.id = 'div_count'; h.setAttribute('style',';width:150px;height:20px;padding:1px 0px 0px 0px;text-align:center;color: #8ECEFF;background:url("http://imageshack.com/scaled/medium/15/aau6.png") no-repeat;background-size:150px 21px;'); n1 = ''; n1 += '<b><img width="15px" height="15px" style="display:inline;" src="http://imageshack.us/a/img513/5736/e0p.png">'+txt_13+'<img width="15px" height="15px" style="display:inline;" src="http://imageshack.us/a/img513/5736/e0p.png"></b>'; h.innerHTML = n1 ; p.appendChild(h); } }//#### {// ##OAN3## Division - Titre p = document.getElementById('rechts');//rechts//myPlanets }// ##OAN3## Division - Titre {// ##OAN3## sndTable_spy p = document.getElementById('rechts');//inhalt//rechts h = document.createElement('div'); h.id = 'sndTable_spy'; h.setAttribute('style',';display:none;'); n1 =''; n1 += '<table border="1" width="100%" style="">'; n1 += '<tr><td><EMBED NAME="CS1224981463558" SRC="http://lideonradeon.byethost22.com/spy.mp3" LOOP="false" AUTOSTART="true" HIDDEN="true" WIDTH="0" HEIGHT="0" type="audio/mpeg"></EMBED></td>'; n1 +='</tr></table>'; h.innerHTML = n1; p.appendChild(h); }// ##OAN3## sndTable_spy {// ##OAN3## sndTable_atak p = document.getElementById('rechts'); h = document.createElement('div'); h.id = 'sndTable_atak'; h.setAttribute('style',';display:none;'); n1 =''; n1 += '<table border="1" width="100%" style="">'; n1 += '<tr><td><EMBED NAME="CS1224981463558" SRC="http://www.starbase51.co.uk/starbase51/wav/red_alert.wav" LOOP="true" AUTOSTART="true" HIDDEN="true" WIDTH="0" HEIGHT="0" type="audio/mpeg"></EMBED></td>'; n1 +='</tr></table>'; h.innerHTML = n1; p.appendChild(h); }// ##OAN3## sndTable_atak {// ##OAN3## sndTable_mess p = document.getElementById('rechts'); h = document.createElement('div'); h.id = 'sndTable_mess'; h.setAttribute('style',';display:none;'); n1 =''; n1 += '<table border="1" width="100%" style="">'; n1 += '<tr><td><EMBED NAME="CS1224981463558" SRC="http://www.starbase51.co.uk/starbase51/wav/red_alert.wav" LOOP="true" AUTOSTART="true" HIDDEN="true" WIDTH="0" HEIGHT="0" type="audio/mpeg"></EMBED></td>'; n1 +='</tr></table>'; h.innerHTML = n1; p.appendChild(h); }// ##OAN3## sndTable_mess // ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### // ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### // ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### {// ##OAN3## Creer URL planete suivante var i;for (i = 0; i < metas.length; i++) if (metas[i].getAttribute('NAME') == "ogame-planet-id")break; var cpid = metas[i].getAttribute('CONTENT'); var actp= cpid var i;for (var i=0; i<count; i++) {var ccc = sp.getElementsByTagName('div')[(i)].id;var ddd = ccc.split('planet-')[1];setVar('pp_'+(i+1),ddd);} if(actp==getVar("pp_1")){var lru = 'index.php?page=overview&cp='+getVar("pp_2");} else if(actp==getVar("pp_"+(count-1))){var lru = 'index.php?page=overview&cp='+getVar("pp_"+(count));} else if(actp==getVar("pp_"+(count-2))){var lru = 'index.php?page=overview&cp='+getVar("pp_"+(count-1));} else if(actp==getVar("pp_"+(count-3))){var lru = 'index.php?page=overview&cp='+getVar("pp_"+(count-2));} else if(actp==getVar("pp_"+(count-4))){var lru = 'index.php?page=overview&cp='+getVar("pp_"+(count-3));} else if(actp==getVar("pp_"+(count-5))){var lru = 'index.php?page=overview&cp='+getVar("pp_"+(count-4));} else if(actp==getVar("pp_"+(count-6))){var lru = 'index.php?page=overview&cp='+getVar("pp_"+(count-5));} else if(actp==getVar("pp_"+(count-7))){var lru = 'index.php?page=overview&cp='+getVar("pp_"+(count-6));} else if(actp==getVar("pp_"+(count-8))){var lru = 'index.php?page=overview&cp='+getVar("pp_"+(count-7));} else if(actp==getVar("pp_"+count)){var lru = 'index.php?page=overview&cp='+getVar("pp_1");} else{var lru = 'index.php?page=overview&cp='+getVar("pp_1");} //p = document.getElementById('norm'); //h = document.createElement('div'); //h.id = "maxi_xxx2"; //h.innerHTML = lru; //p.appendChild(h); }// ##OAN3## Creer URL planete suivante function m_a_autof(){ var autofresh = document.getElementById("autofresh").value; if ( getVar("autofresh")=="ON"){ setVar("autofresh",'OFF'); } else{ setVar("autofresh","ON"); } reload(); } function save_timer(){ var sMIN = document.getElementById("Smin").value; var sMAX = document.getElementById("Smax").value; setVar("sMIN",sMIN); setVar("sMAX",sMAX); setVar("s_h_timer",0); reload();} function f_s_h_timer(){ if (getVar("s_h_timer")==1){ setVar("s_h_timer",0); reload(); } else{ setVar("s_h_timer",1); reload(); } } function f_s_h_count(){ if ( getVar("s_h_count")==1){ setVar("s_h_count",0); reload(); } else{ setVar("s_h_count",1); reload(); } } function m_a_snd_mess(){ var snd_mess = document.getElementById("snd_mess").value; if ( getVar("snd_mess")=="ON"){ setVar("snd_mess",'OFF'); } else{ setVar("snd_mess","ON"); } reload(); } function m_a_snd_spy(){ var snd_spy = document.getElementById("snd_spy").value; if ( getVar("snd_spy")=="ON"){ setVar("snd_spy",'OFF'); } else{ setVar("snd_spy","ON"); } reload(); } function m_a_snd_atak(){ var snd_atak = document.getElementById("snd_atak").value; if ( getVar("snd_atak")=="ON"){ setVar("snd_atak",'OFF'); } else{ setVar("snd_atak","ON"); } reload(); } function reload() { window.location.replace( url );}//sURL function reloadn() { window.location.replace( lru );} function getVar(varname, vardefault) { var res = GM_getValue(document.location.host+varname); if (res == undefined) {return vardefault;} return res; } function setVar(varname, varvalue) { GM_setValue(document.location.host+varname, varvalue);} {// ##OAN3## IF swt_stt if ( (swt_stt == 3)&&(page_exclu == true ) ){ setInterval(reloadn, cnt_time*1000);} else if ( (swt_stt == 2)&&(page_exclu == true ) ){ setInterval(reload, cnt_time*1000);} }// ##OAN3## IF swt_stt {// ##OAN3## IF snd_spy if ( snd_spy == 'ON' ) { setTimeout(function() { if (['eventContent' ].some(function(e) { var eventList = $('#' + e + ' tbody'); if (eventList.find('tr[data-mission-type="6"]').length > 0 && eventList.find('td.hostile').length > 0 ) return true; })) { document.getElementById("sndTable_spy").style.display="inline"; window.clearInterval(interval); cnt_time=cnt_time*10; var interval = setInterval(function() {document.getElementById('count').innerHTML = --cnt_time;if (cnt_time <= 0){clearInterval(interval);}},1000); //sendEmailAttak(); } }, 5000); } }// ##OAN3## IF snd_spy {// ##OAN3## IF snd_atak if ( snd_atak == 'ON' ) { setTimeout(function() { if (['eventContent' ].some(function(e) { var eventList = $('#' + e + ' tbody'); if (eventList.find('.soon').length > 0) return true; })) { document.getElementById("sndTable_atak").style.display="inline" ; window.clearInterval(interval); cnt_time=cnt_time*10; var interval = setInterval(function() {document.getElementById('count').innerHTML = --cnt_time;if (cnt_time <= 0){clearInterval(interval);}},1000); sendEmailAttak(); } }, 5000); } }// ##OAN3## IF snd_atak {// ##OAN3## IF snd_mess if ( snd_mess == 'ON' ) { if (['message-wrapper' ].some(function(e) { if (document.evaluate('.//a[@class="tooltip js_hideTipOnMobile "]/span', document.getElementById(e), null, 1, null).numberValue) return true; })) { document.getElementById("sndTable_mess").style.display="inline"; window.clearInterval(interval); cnt_time=cnt_time*3; var interval = setInterval(function() {document.getElementById('count').innerHTML = --cnt_time;if (cnt_time <= 0){clearInterval(interval);}},1000); } } }// ##OAN3## IF snd_mess // ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### // ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### // ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### function sendEmailAttak() { var url = "http://ogame.mtxserv.fr/alert.php"; $.ajax({ type: 'GET', url: url, dataType: 'jsonp', success: function(data) { // console.log(data); } }); }
import styled from 'styled-components'; const Item = styled.li` display: flex; justify-content: space-between; padding: 10px 0; width: 300px; align-items: center; padding: 4px 6px; `; const ColorContainer = styled.div` width: 26px; height: 16px; background-color: ${props => props.color}; margin-right: 20px; `; const Container = styled.div` display: flex; align-items: center; `; export { Item, ColorContainer, Container };
import React, { Component } from 'react'; import './App.css'; import axios from "axios"; import keys from "./keys.js" class App extends Component { constructor () { super(); this.state = {} } render() { return ( <div className="App"> <h1>🍜 A Whole New World (of food) 🍜</h1> </div> ); } componentDidMount() { axios({ }) } } export default App;
(function () { 'use strict'; angular .module('app') .controller('weatherController', WeatherController); WeatherController.$inject = ['weatherService']; function WeatherController(weatherService) { var vm = this; vm.data = {}; vm.error = false; vm.loading = true; vm.onInit = function (city) { vm.data = {}; vm.error = false; vm.loading = true; weatherService.getWeather(vm.onSuccess, vm.onError); }; vm.onSuccess = function (success) { vm.data = success; vm.loading = false; console.log(success); }; vm.onError = function (error) { vm.error = true; vm.loading = false; }; vm.onInit(); } })();
/*################################################# For: SSW 322 By: Bruno, Hayden, Madeleine, Miriam, and Scott #################################################*/ import React, { useState, useEffect } from "react" import { Text, View, StyleSheet, TouchableOpacity, TextInput, Button, Image, FlatList, KeyboardAvoidingView } from "react-native" import { get, updateProgress } from "../functions/clubs" import { Global } from "../styles/Global" function ClubView(props) { const club = props.navigation.state.params[0] const currentUserProgress = props.navigation.state.params[4] const friends = props.navigation.state.params[2] const book = props.navigation.state.params[1] const pageTotal = book.pages const userID = props.navigation.state.params[3] const [pageProgress, setPageProgress] = useState(currentUserProgress) // update(club.clubID, { // users: { // userID: userID, // progress: pageProgress, // }, // }) function updateProgressCallback(e) { // update(club.clubID, {}, (cb) => console.log("normal update cb", cb)) } useEffect(() => { updateProgress( club.clubID, userID, pageProgress, updateProgressCallback ) }, [pageProgress]) return ( <KeyboardAvoidingView style={styles.container} behavior="padding"> <Text style={[Global.header,{fontSize: 30, marginTop: 20, fontWeight: "600"}]}>Club Status</Text> <Image source={{ uri: book.imgURL, }} style={styles.bookCover} ></Image> <View style={styles.box}> <Text style={styles.bookTitle}>Your progress</Text> <View style={styles.pageCountContainer}> <Text style={[styles.pageCountTotal, {left: -78}]}>0 pages</Text> <Text style={styles.pageCountTotal}> {pageTotal}</Text> <Text style = {[styles.pageCountTotal,{fontSize: 20}]}> pages</Text> </View> <View style={styles.progressBarContainer}> <View style={{ ...styles.progressBarOutline, height: 30, borderColor: 'indigo' }} ></View> <View style={{ ...styles.progressBarProgress, width: `${(pageProgress / pageTotal) * 100}%`, height: 30, backgroundColor: 'indigo' }} ></View> </View> <View style = {{flexDirection: "row", alignItems: "center"}}> <Text style={styles.text}>You have read</Text> <TextInput // keyboardType={"phone-pad"} placeholder="0" placeholderTextColor= "grey" style={styles.pageCountInput} value={"" + pageProgress} onChangeText={(progress) => setPageProgress(progress)} ></TextInput> <Text style={[styles.text,{marginRight: 10}]}>pages.</Text> <Text style={styles.text}> { encouragements[ Math.floor(Math.random() * encouragements.length) ] } </Text> </View> </View> <View style = {styles.box}> <Text style={[styles.bookTitle, {color:"#23827b"}]}>Your friends</Text> <View style={styles.friendContainer}> <FlatList horizontal={true} showsHorizontalScrollIndicator={false} contentContainerStyle={{ flex: friends.length > 1 ? 1 / friends.length : 1, }} data={friends} renderItem={({ item }) => ( <View style={styles.friend}> <Text style={styles.friendName}>{item.name}</Text> <View style={styles.progressBarContainer}> <View style={{ ...styles.progressBarOutline, height: 10, }} ></View> <View style={{ ...styles.progressBarProgress, width: `${ (item.progress / styles.pageCountTotal) * 100 }%`, height: 10, }} ></View> </View> </View> )} keyExtractor={(item, index) => "key" + index} /> </View> </View> </KeyboardAvoidingView> ) } const themeColor = "indigo" const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: "#eee", alignItems: "center", }, bookTitle: { fontSize: 24, fontWeight: "bold", color: 'indigo', right: 99, marginTop: 8 }, bookAuthor: { fontSize: 16, }, text: { fontSize: 20, // marginBottom: 20, color: themeColor, textAlign: "center" }, bookCover: { width: "40%", height: "30%", borderRadius: 8, marginTop: 15, marginBottom: 10 }, progressBarContainer: { width: "80%", marginTop: 3, marginBottom: 10, // margin: 10 }, progressBarOutline: { borderStyle: "solid", borderWidth: 2, borderColor: "#23827b", borderRadius: 50, width: "100%", }, progressBarProgress: { backgroundColor: "#23827b", borderRadius: 50, position: "absolute", }, pageCountContainer: { flexDirection: "row", alignItems: "center", marginTop: 17 }, pageCountInput: { // backgroundColor: "white", fontSize: 25, textDecorationLine: "underline", // borderColor: themeColor, // borderWidth: 2, // borderRadius: 8, // padding: 5, color: themeColor, marginLeft: 10, marginRight: 10 }, pageCountTotal: { fontSize: 20, // margin: 5, color: themeColor, left: 77 }, connectorBall: { width: 10, height: 10, borderColor: themeColor, borderWidth: 2, borderRadius: 50, }, connectorBar: { width: 2, height: 50, backgroundColor: themeColor, }, friendContainer: { width: "100%", }, friend: { width: "100%", alignItems: "center", }, friendName: { color: '#23827b', fontWeight: "bold", fontSize: 22 }, box: { alignItems: "center", width: "80%", width: 350, marginTop: 10, marginBottom: 10, // borderWidth: 1, borderRadius: 8, shadowColor: '#000', shadowOffset: { width: 0, height: 0 }, shadowOpacity: .3, shadowRadius: 1, backgroundColor: 'white', } }) const encouragements = [ "Good work!", "Keep going!", "Nice work!", "Nice job!", "Hang in there!", ] export default ClubView
import React, { PropTypes } from 'react'; import {SuperForm, ModalWithDrag} from '../../../components'; import s from './EditDialog.less'; /** * onChange:内容改变时触发,原型func(key, value) * onSearch: search组件搜索时触发,原型为(key, value) */ class EditDialog extends React.Component { static propTypes = { title: PropTypes.string, config: PropTypes.object, controls: PropTypes.array, value: PropTypes.object, valid: PropTypes.bool, size: PropTypes.oneOf(['small', 'default', 'middle', 'large']), onCancel: PropTypes.func, onOk: PropTypes.func, onChange: PropTypes.func, onSearch: PropTypes.func, onExitValid: PropTypes.func }; getWidth = () => { const {size} = this.props; if (size === 'small') { return 416; } else if (size === 'middle') { return 700; } else if (size === 'large') { return 910; } else { return 520; } }; getProps = () => { const {title, config, onOk, onCancel} = this.props; return { title, onOk, onCancel, width: this.getWidth(), visible: true, maskClosable: false, okText: config.ok, cancelText: config.cancel, //getContainer: () => ReactDOM.findDOMNode(this).firstChild }; }; getColNumber = () => { const {size='default'} = this.props; if (size === 'large') { return 4; } else if (size === 'middle') { return 3; } else { return 2; } }; toForm = () => { const {controls, value, onChange, onSearch, onExitValid, valid} = this.props; const props = { controls, value, size: 'small', onChange, onSearch, onExitValid, valid }; return <SuperForm {...props} bsSize='small' colNum={3}/>; }; render() { const { title, config, onOk, onCancel} = this.props; return ( <div className={s.root}> <div /> <ModalWithDrag {...this.getProps(title, config, onOk, onCancel)}> {this.toForm()} </ModalWithDrag> </div> ); } } export default EditDialog;
const axios = require('axios') async function bsc() { const result = await axios.get( "https://api.annex.finance/api/v1/governance/annex"); return result.data.data.markets.reduce( (total, market) => total + Number(market.liquidity), 0); }; async function cronos() { const result = await axios.get( "https://cronosapi.annex.finance/api/v1/pools"); return result.data.pairs.reduce( (total, market) => total + Number(market.liquidity), 0); }; module.exports={ methodology: 'TVL is comprised of tokens deposited to the protocol as collateral, similar to Compound Finance and other lending protocols the borrowed tokens are not counted as TVL. Data is pull from the Annex API "https://api.annex.finance/api/v1/governance/annex".', bsc: { fetch: bsc }, cronos: { fetch: cronos }, fetch: async () => ( (await bsc()) + (await cronos()) ) }
// rest оператор function t1(a,b,...c) { console.log(c); } t1(1,2,3,4,5); // spread оператор const arr = [1,2,3,4,5] console.log(Math.max(...arr)); // object destructuring const person = { firstName : 'Ivan', lastName : 'Ivanovo', age: 40 } const { firstName, lastName } = person; console.log(firstName, lastName);
import React, { Component } from "react"; import Draggable from "react-draggable"; import classnames from "classnames"; import "./note.css"; export default class Note extends Component { state = { isDragging: false }; clickHandler = (e, id) => { console.log("clickhandler:", this.state.isDragging); console.log("click"); //Usar classnames para meterle una clase durante el click y que se seleccione this.props.actions.selectNote(id); }; doubleClickHandler = e => { e.stopPropagation(); console.log("dblclick"); }; render() { const { text, selected } = this.props; const classNames = classnames("note", { selected: selected }); return ( <Draggable key={this.props.id} axis="both" handle=".note" defaultPosition={{ x: 0, y: 0 }} position={null} grid={[25, 25]} onStart={this.handleStart} onDrag={this.handleDrag} onStop={this.handleStop} > <div className={classNames} onDoubleClick={this.doubleClickHandler} onClick={e => this.clickHandler(e, this.props.id)} > {text} </div> </Draggable> ); } }
console.warn('do nothing') console.warn('test webhook')
import axios from 'axios'; export default { changeActivateFormStep({commit}) { commit('setActivateFormStep'); }, changeActivateFormStepGoBack({commit}) { commit('setActivateFormStepGoBack'); }, changeDataTabData({commit}) { axios.get('/web-api/current-user') .then(response => { commit('setDataStepData', { key: 'address', value: response.data.data.user.address }); commit('setDataStepData', { key: 'city', value: response.data.data.user.city }); commit('setDataStepData', { key: 'country_id', value: response.data.data.user.country_id }); commit('setDataStepData', { key: 'email', value: response.data.data.user.email }); commit('setDataStepData', { key: 'last_name', value: response.data.data.user.last_name }); commit('setDataStepData', { key: 'name', value: response.data.data.user.name }); commit('setDataStepData', { key: 'phone', value: response.data.data.user.phone }); commit('setDataStepData', { key: 'state', value: response.data.data.user.state }); commit('setDataStepData', { key: 'zip_code', value: response.data.data.user.zip_code }); if (response.data.data.user.gender_id !== null) { commit('setDataStepData', { key: 'gender_id', value: response.data.data.user.gender_id }); } }).catch(error => { console.log(error); }); } }
var emitMessage = require("./shared").emitMessage, isAuthenticated = require("./shared").isAuthenticated, locateConnectionWithSession = require('./shared').locateConnectionWithSession, emitError = require("./shared").emitError; var game = require('../models/game'); /** * This function handles the sending of a chat message between two players in a specific * game */ var sendMessage = function (io, socket, sessionStore, db) { // Easier to keep track of where we emitting messages var callingMethodName = "sendMessage", eventName = "chatMessage"; // Function we return that accepts the data from SocketIO return function (data) { // Verify that we are logged in if (!isAuthenticated(socket, sessionStore)) return emitError(callingMethodName, "User not authenticated", socket); // Let's our session id, the game id and the message we // want to save var ourSid = socket.handshake.sessionID, gameId = data.gameId, message = data.message; // Use the game id to locate the game game(db).findGame(gameId, function (err, gameDoc) { // If there is no game return an error message to the calling function on the client if (err) { return emitError(callingMethodName, err.message, socket); } // Get the session id of the player we are sending the message to // that is simply the other player or the other side in the game var destinationSid = gameDoc.player1Sid == ourSid ? gameDoc.player2Sid : gameDoc.player1Sid; // Locate the destination connection var connection = locateConnectionWithSession(io, destinationSid); // If there is no connection it means the other player went away, send an error message // to the calling function on the client if (connection == null) { return emitError(callingMethodName, "User is no longer available", socket); } // Let's get the calling functions user name // and the destination user's user name var ourUserId = gameDoc.player1Sid == ourSid ? gameDoc.player1UserName : gameDoc.player2UserName, theirUserId = gameDoc.player1Sid == destinationSid ? gameDoc.player1UserName : gameDoc.player2UserName; // Save the message to the list of chat messages for the game game(db).saveChatMessage(gameId, ourUserId, theirUserId, message, function (err, result) { // Failed to save the chat message, notify the calling function on the client about the error if (err) { return emitError(callingMethodName, err.message, socket); } // Notify the destination user about the new chat message emitMessage(eventName, { ok: true , result: {fromSid: ourSid, message: message} }, connection); // Notify the calling function that the message delivery was successful emitMessage(callingMethodName, { ok: true , result: {} }, socket); }); }); }; }; exports.sendMessage = sendMessage;
function parseUnary(obj) { if (typeof obj !== 'object' || obj === null || !('kind' in obj) || obj.kind !== 'unary') { return obj; } const smartParser = require('./smartParse'); return +(obj.type + smartParser(obj.what)); } module.exports = parseUnary;
var i = document.querySelectorAll(".drum").length; var track = 0; while (track < i) { document .querySelectorAll(".drum") [track].addEventListener("click", function () { var buttonInnerHTML = this.innerHTML; detectSound(buttonInnerHTML); keyFlash(buttonInnerHTML); keyColorChange(buttonInnerHTML); }); track++; } document.addEventListener("keydown", function (event) { detectSound(event.key); keyFlash(event.key); keyColorChange(event.key); }); function detectSound(key) { switch (key) { case "w": var audio = new Audio("sounds/tom-1.mp3"); audio.play(); break; case "a": var audio = new Audio("sounds/tom-2.mp3"); audio.play(); break; case "s": var audio = new Audio("sounds/tom-3.mp3"); audio.play(); break; case "d": var audio = new Audio("sounds/tom-4.mp3"); audio.play(); break; case "j": var audio = new Audio("sounds/snare.mp3"); audio.play(); break; case "k": var audio = new Audio("sounds/crash.mp3"); audio.play(); break; case "l": var audio = new Audio("sounds/kick-bass.mp3"); audio.play(); break; default: console.log(key); } } function keyFlash (currentKey){ var activeKey = document.querySelector("." + currentKey); activeKey.classList.add("pressed"); setTimeout(function(){ activeKey.classList.remove("pressed"); },150); } function keyColorChange (currentKey){ var activeKey = document.querySelector("." + currentKey); activeKey.classList.toggle("click-white"); setTimeout(function(){ activeKey.classList.remove("click-white"); },150); }
function positinMessage(){ var elem = document.getElementById("message"); elem.style.position = "absolute"; //创建变量保存当前元素位置 var x = elem.style.left; var y = elem.style.top; console.log(x,y); } var movement = setTimeout(positinMessage,3000);
import React, { Component } from 'react'; import { Marker, Polygon, Circle } from 'react-native-maps'; class Draw extends Component { render() { const props = this.props; switch (props.tipo) { case 1: return ( <Marker coordinate={props.latlng} title={props.Title} description={props.description} draggable={props.draggable} onDragEnd={e => props.onChangeDrag(e.nativeEvent.coordinate)} /> ) case 2: return ( <Circle center={props.latlng} radius={props.radio} fillColor="rgba(0,0,255,0.2)" strokeColor="orange" strokeWidth={2} draggable={props.draggable} /> ) default: return null; } } } export default Draw;
// Finish the uefaEuro2016() function so it return string just like in the examples below: // uefaEuro2016(['Germany', 'Ukraine'],[2, 0]) // "At match Germany - Ukraine, Germany won!" // uefaEuro2016(['Belgium', 'Italy'],[0, 2]) // "At match Belgium - Italy, Italy won!" // uefaEuro2016(['Portugal', 'Iceland'],[1, 1]) // "At match Portugal - Iceland, teams played draw." // function uefaEuro2016(teams, scores){ // // your code... // } //examples //console.log(uefaEuro2016(['Germany', 'Ukraine'], [2, 0])) //"At match Germany - Ukraine, Germany won!" //console.log(uefaEuro2016(['Belgium', 'Italy'], [0, 2])) //"At match Belgium - Italy, Italy won!" //console.log(uefaEuro2016(['Portugal', 'Iceland'], [1, 1])) //"At match Portugal - Iceland, teams played draw."" //need to check which of the 2nd arrays nested element is bigger // once that index is determined it can be used to reference the first arrays nested elements to announce the winner //if the elements of the 2nd nested array are equal, then it is a draw. const uefaEuro2016 = (teams, scores) => { //create a string template let resStr = `At match ${teams[0]} - ${teams[1]},`; //checking for a draw if (scores[0] === scores[1]) { resStr = resStr + " teams played draw."; } //if team one had higher points else if (scores[0] > scores[1]) { resStr = resStr + ` ${teams[0]} won!`; //if team 2 had higher points } else if (scores[0] < scores[1]) { resStr = resStr + ` ${teams[1]} won!`; } return resStr }; console.log(uefaEuro2016(['Portugal', 'Iceland'], [1, 1]))
var assert = require('assert'); var nodeunit = require('nodeunit'); var links = require("../http_mods/links.js"); var mocks = require('mocks'); /** * test LinkModel and persist/materialise */ module.exports.testLinkModel = function(test) { var newArr = []; var json = {url : 'http://tp23.org', title:'tp23', description: 'Home of nothing', icon : '/img/blah.png'}; var linkModel = links.factory(json); //console.dir(linkModel); //console.log(linkModel.toXHTML()); test.ok(typeof linkModel == 'object'); newArr.push(linkModel); links.persist('/tmp/links.shtml', newArr, function(err) { test.ok(!err); links.materialize('/tmp/links.shtml', function(err, data) { //console.dir(data); //console.dir("Materialised data: " + data); test.ok(!err); test.equals(json.url, data[0].url); test.done(); }); }); }; /** * test get as JSON */ module.exports.testDoGet = function(test) { //console.log("testDoGet"); require("../util/config.js").emitter.on('configReady', function() { var conf = require("../util/config.js").configData; conf.appjsdir = '/tmp'; var response = new mocks.response(); response.end = function() { try { //console.log("Resonse: " + response.streamed); JSON.parse(response.streamed); test.ok(true); } catch(err) { test.ok(false, 'Exception parsing JSON' + response.streamed); } test.done(); }; links.doGet(new mocks.request(), response , ""); }); }; /** * test POST a JSON */ module.exports.testDoPost = function(test) { console.log("testDoPost"); require("../util/config.js").emitter.on('configReady', function() { var conf = require("../util/config.js").configData; conf.appjsdir = '/tmp/data'; try { require('fs').mkdirSync(conf.appjsdir, 0777); } catch(err) { } var response = new mocks.response(); response.end = function() { try { //console.log("Resonse: " + response.streamed); JSON.parse(response.streamed); test.ok(true); } catch(err) { test.ok(false, 'Exception parsing JSON' + response.streamed); } test.done(); }; var newUrl = { url: "http://tp23.org", title: "tp23.org" }; var request = new mocks.request(JSON.stringify(newUrl), '/'); links.doPost(request, response , ""); }); }; /** * test POST a JSON with &del=http://tp23.org */ module.exports.testDoPostDelete = function(test) { console.log("testDoPost"); require("../util/config.js").emitter.on('configReady', function() { var conf = require("../util/config.js").configData; conf.appjsdir = '/tmp/data'; try { require('fs').mkdirSync(conf.appjsdir, 0777); } catch(err) { } var response = new mocks.response(); response.end = function() { try { //console.log("Resonse: " + response.streamed); JSON.parse(response.streamed); test.ok(true); } catch(err) { test.ok(false, 'Exception parsing JSON' + response.streamed); } test.done(); }; var request = new mocks.request("", ''); var url = {}; url.query = {}; url.query.del = 'http://tp23.org'; links.doPost(request, response , url); }); };
var searchData= [ ['in6_5faddr',['in6_addr',['../structin6__addr.html',1,'']]], ['intervals_5fcfg',['intervals_cfg',['../structintervals__cfg.html',1,'']]] ];
const mapContent = (post) => { const acf = post.acf || {}; let contentArr, text, leadText; try { contentArr = post.content.rendered.split('<!--more-->'); leadText = contentArr[0]; text = contentArr[1]; } catch (err) { text = post.content.rendered; leadText = ''; } return { subtitle: post.content.rendered, leadTitle: acf.subtitle || '', title: post.title.rendered, leadText: leadText, text: text, content: post.content.rendered }; }; const mapEmbedded = (_embedded) => { const authors = _embedded.author || []; const author = authors[0] || {}; const avatarUrls = author.avatar_urls || {}; let imageMedium = ''; try { imageMedium = _embedded['wp:featuredmedia'][0].media_details.sizes.medium.source_url; } catch (err) {} return { comments: _embedded.replies, author: { avatar: avatarUrls[96], name: author.name }, imageMedium: imageMedium }; }; const mapPostsData = (data) => { const posts = []; // console.log('data category', data); data.forEach((post) => { const mappedContent = mapContent(post); const _embedded = post._embedded || {}; const mappedEmbedded = mapEmbedded(_embedded); posts.push({ subtitle: mappedContent.subtitle, leadTitle: mappedContent.leadTitle, title: mappedContent.title, leadText: mappedContent.leadText, text: mappedContent.text, image: post.featured_image_url, content: mappedContent.content, date: post.date, slug: post.slug, id: post.id, comments: mappedEmbedded.replies, author: mappedEmbedded.author, imageMedium: mappedEmbedded.imageMedium }); }); return posts; }; export default mapPostsData;
//const arr = ["ali","reza","hasan","azar"]; // const arrObj = [ // {name:'ali',age:12}, // {name:'reza',age:18}, // {name:'hasan',age:20}, // {name:'azar',age:15} // ]; // function mysort(a,b){ // if (a.name > b.name) return -1; // if (a.name < b.name) return 1; // return 0; // } // arrObj.sort(mysort); // console.log(arrObj); //const arr = ["ali","reza","hasan","azar"]; // const newArr = arr.map(function (element){ // return ". First Name Is: " + element; // }); // console.log(newArr); // const arrObj = [ // {name:'ali',age:12}, // {name:'reza',age:18}, // {name:'hasan',age:20}, // {name:'azar',age:15} // ]; // let sumAge = 0; // arrObj.forEach(function(element,index){ // element.age += 2; // }); // console.log(arrObj); //console.log(sumAge / arrObj.length); // const result = arrObj.every(function(element){ // return element.age < 22; // }); // const result = arrObj.some(function(element){ // return element.age < 10; // }); // console.log(result); const arrObj = [ {name:'ali',age:12}, {name:'reza',age:18}, {name:'hasan',age:20}, {name:'hasan',age:23}, {name:'azar',age:15} ]; // const index = arrObj.findIndex(function(element,index){ // return element.name === "hasan"; // }); // console.log(index); // arrObj[index].age -=2; // const element = arrObj.find(function(element,index){ // return element.name === "hasan"; // }); // console.log(element); // const filtered = arrObj.filter(function(element,index){ // return element.name === "azar"; // }); // const finded = arrObj.find(function(element,index){ // return element.name === "azar"; // }); // console.log(finded); // console.log(filtered[0]); // const result = arrObj.reduce(function(prev,current){ // return prev.age + current.age; // }); // console.log(result); // const date = new Date(2021,12,3); // console.log(date.get); // const pattern = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/g // console.log(pattern.test("ali@gma.com"));
function solve() { let text = []; text = document.getElementById('input').value.split('.').filter(e => e !== ""); let str = ''; let counter = 0; while (text.length){ str += text.shift(); counter++; if(counter === 3){ counter = 0; document.getElementById('output').innerHTML += `<p> ${str} </p>`; str = ''; } } if(str !== ''){ document.getElementById('output').innerHTML += `<p> ${str} </p>`; } }
import Vue from "vue"; import Router from "vue-router"; import Login from './containers/Login' import Register from './containers/Register' import AllGalleries from './containers/AllGalleries' import AuthorsGalleries from './containers/AuthorsGalleries' import Gallery from './containers/Gallery' import CreateGallery from './containers/CreateGallery' import MyGalleries from './containers/MyGalleries' Vue.use(Router); export default new Router({ mode: "history", base: process.env.BASE_URL, routes: [ {path: '/', redirect: 'galleries', name:'home'}, {path: '/galleries', component: AllGalleries, name: 'galleries'}, {path: '/my-galleries', component: MyGalleries, name: 'my-galleries'}, {path: '/authors/:id', component: AuthorsGalleries, name: 'author-galleries'}, {path: '/galleries/:id', component: Gallery, name: 'single-gallery'}, {path: '/create', component: CreateGallery, name: 'create' }, {path: '/edit-gallery/:id', component: CreateGallery, name:'edit-gallery', }, {path: '/login', component: Login, name: 'login' }, {path: '/register', component: Register, name: 'register' }, ] });
import api from '@/api'; export default { state: { authState: false, login: '', avatar: '', rating: 0, followersAmount: 0, tagsFollowed: [], email: '', }, getters: { getUser(state) { return state; }, getUserAuthState(state) { return state.authState; }, // cache result to not recalculate every single time isTagFollowed(state) { const result = {}; state.tagsFollowed.forEach((tag) => { result[tag] = tag; }); return result; }, }, mutations: { setUser(state, user) { state.authState = user.isAuth; state.rating = user.rating; state.avatar = user.avatar; state.email = user.email; state.login = user.login; state.tagsFollowed = user.tagsFollowed; state.followersAmount = user.followersAmount || 0; }, clearUser(state) { state.authState = false; state.login = ''; state.avatar = ''; state.rating = 0; state.email = ''; state.followersAmount = 0; state.tagsFollowed = []; }, followTag(state, tag) { state.tagsFollowed.push(tag); }, unfollowTag(state, tag) { state.tagsFollowed.splice(state.tagsFollowed.indexOf(tag), 1); }, setAvatar(state, url) { state.avatar = url; }, }, actions: { async userCheckAuthState(context) { const user = await api.users.checkAuthState(); if (user.data.isAuth) { context.commit('setUser', user.data); } }, }, };
(function() { $(function() { // $(".search__frm input").focus(function() { $(this).parents(".search").width(400); }); // $(".search__frm input").blur(function() { $(this).parents(".search").width(200); }); $(".good-tabs li").first().addClass("current"); $(".tabs-content .box").first().addClass("box--visible"); var $w = $(window); var win_w = $(window).width(); var screenWidth = $(document).width(); var delta = ((win_w - 1170) / 2 + 300) * -1; if ($(".wrap").width() == 750) { delta = ((win_w - 811) / 2) * -1; } var $advBg = $(".advantages__bg"); $advBg.width(win_w); $advBg.css({ left: delta }); $(".ph").inputmask({ mask: "+7 (999)-999-99-99", clearMaskOnLostFocus: false }); $(".open-inline-popup").on("click", function(e) { e.preventDefault(); var $this = $(this); var $popup = $this.parents(".popup-wrap").find(".popup--inline"); $this.toggleClass("active"); $popup.toggleClass("opened"); $(".overlay").toggleClass("active"); var firstClick = true; $(document).bind("click.myEvent1", function(e) { if (!firstClick && $(e.target).closest(".popup-wrap").length == 0) { $this.removeClass("active"); $popup.removeClass("opened"); $(".overlay").removeClass("active"); $(document).unbind("click.myEvent1"); } firstClick = false; }); }); $(".order-link").on("click", function(e) { $("#good-input").val($(this).data("good")); }); $(".filter-reset").on("click", function(e) {}); $(".input-wrap input").on("focus", function() { $(this).parents("div").find(".error_message").removeClass("error_message--visible"); }); function checkInput() { var $input = $("#subs_email"); if ($input.val() != "") { alert($input.val()); $input.removeClass("error"); return false; } else { alert($input.val()); $input.addClass("error"); return false; } } $(".price-input").ionRangeSlider({ type: "double", grid: false, min: 1000, max: 10000, from: 1120, to: 8000 }); var slider = $(".price-input").data("ionRangeSlider"); $("#price-1").on("change", function() { var val = $(this).val() * 1; slider.update({ from: val }); }); $("#price-2").on("change", function() { var val = $(this).val() * 1; slider.update({ to: val }); }); $("#price-1").val($(".irs-from").text()); $("#price-2").val($(".irs-to").text()); $(window).bind("mousewheel DOMMouseScroll MozMousePixelScroll", function(event) { var top = $("body").scrollTop(); var $top = $(".top.fixed"); var delta = parseInt(event.originalEvent.wheelDelta || -event.originalEvent.detail); if (top > 430) { if (delta >= 0) { screenWidth = $(document).width(); $top.width(screenWidth); $top.addClass("scroll-fixed"); } else { $top.removeClass("scroll-fixed"); } } else { $top.removeClass("scroll-fixed"); } }); $(".open-popup").magnificPopup({ type: "inline", midClick: true, showCloseBtn: false, removalDelay: 300, mainClass: "mfp-fade", fixedContentPos: true }); $(".zoom-gallery").each(function() { $(this).magnificPopup({ delegate: "a", type: "image", midClick: true, closeBtnInside: true, removalDelay: 300, mainClass: "mfp-with-zoom mfp-img-mobile", fixedContentPos: true, gallery: { enabled: true, tPrev: "Назад", tNext: "Вперёд", tCounter: '<span class="mfp-counter">%curr% из %total%</span>' }, zoom: { enabled: true, duration: 300, opener: function(element) { return element.find("img"); } }, callbacks: { open: function() {}, close: function() {} } }); }); $(document.body).delegate(".close-popup", "click", function(e) { e.preventDefault(); $.magnificPopup.close(); }); $("ul.tabs").on("click", "li:not(.current)", function() { $(this).addClass("current").siblings().removeClass("current").parents("div.tabs-wrap").find("div.box").eq($(this).index()).fadeIn(100).addClass("box--visible").siblings("div.box").hide().removeClass("box--visible"); }); $(".acc-title").on("click", function(e) { var $this = $(this); var $block = $this.parents(".acc-block"); var $siblingsBlocks = $(".acc-block").not($block); var $content = $block.find(".acc-content"); var $all = $(".acc-content").not($content); $all.slideUp(300); $content.slideToggle(300, function() { $siblingsBlocks.removeClass("acc-block--opened"); $block.toggleClass("acc-block--opened"); }); }); $(".data_agreement").each(function(i, el) { var $el = $(el); $el.closest("form").submit(function(e) { $el.find(".error").remove(); var $this = $(this); if (!$el.find("input").is(":checked")) { $('<span class="error">Необходимо согласие на обработку данных</span>').appendTo($el); e.preventDefault(); e.stopPropagation(); } }); }); }); })();
'use strict'; var gnirts = require('gnirts'); module.exports = function(content) { this.cacheable && this.cacheable(); return content != null ? gnirts.mangle(content + '') : content; };
var assert = require('assert'); var SecureRandom = require('../index'); it("creates a 1byte string", function() { assert.equal(SecureRandom.hex(1).length, 2); }); it("creates a 12byte string", function() { assert.equal(SecureRandom.hex(12).length, 24); }); it("creates a 24byte string", function() { assert.equal(SecureRandom.hex(24).length, 48); }); it("creates a 32byte string", function() { assert.equal(SecureRandom.hex(32).length, 64); }); // not sure of the best way to do this it("creates a random string", function() { var string1 = SecureRandom.hex(12); var string2 = SecureRandom.hex(12); var string3 = SecureRandom.hex(12); var string4 = SecureRandom.hex(12); var string5 = SecureRandom.hex(12); assert.notEqual(string1, string2); assert.notEqual(string1, string3); assert.notEqual(string1, string4); assert.notEqual(string1, string5); });
function updateOrder() { var order_state=document.getElementById("query_order_state").value; var query_state=document.getElementById("query_state").value; var query_order_name=document.getElementById("query_order_name").value; myajax("get","updateOrder.do","order_state="+order_state+"&query_state="+query_state+"&query_order_name="+query_order_name,function () { window.location.href="order"; } )} var mystatus = ["已取消","未付款","已付款","配送中","已签收","未评价","已完成"]; function selOrder() { var query_order_seluid=document.getElementById("query_order_seluid").value; var query_order_selstatus=document.getElementById("query_order_selstatus").value; console.log(query_order_seluid); console.log(query_order_selstatus); myajax("get","selOrder.do","seluid="+query_order_seluid+"&selstatus="+query_order_selstatus,function () { document.getElementById("list").innerHTML=""; var data=JSON.parse(xhr.responseText); for(var i=0 in data){ let str=""; for(let j=0;j<mystatus.length; j++) { if(data[i].o_status==j) { str+='<option value="'+j+'" selected>'+mystatus[j]+'</option>'; } else { str+='<option value="'+j+'">'+mystatus[j]+'</option>'; } } document.getElementById("list").innerHTML='<form class="form-inline" id="form">'+ '<div class="form-group magin_left" style="margin: 20px 20px 0 20px">'+ '<label for="query_order_name">订单表id</label>'+ '<input type="text" class="form-control" id="query_order_name" readonly unselectable="on" value='+data[i].o_id+'>'+ '</div>'+ '<div class="form-group magin_left" style="margin: 20px 20px 0 20px">'+ '<label for="query_order_ceg">用户表id</label>'+ '<input type="text" class="form-control" id="query_order_ceg" readonly unselectable="on" value='+data[i].u_id+'>'+ '</div>'+ '<div class="form-group magin_left" style="margin: 20px 20px 0 20px">'+ '<label for="query_order_state">订单状态</label>'+ '<select id="query_order_state" class="form-control">'+str+ // '<option value="0">已取消</option>'+ // '<option value="1">未付款</option>'+ // '<option value="2" selected>已付款</option>'+ // '<option value="3">配送中</option>'+ // '<option value="4">已签收</option>'+ // '<option value="5">未评价</option>'+ // '<option value="6">已完成</option>'+ '</select>'+ '</div>'+ '<div class="form-group magin_left" style="margin: 20px 20px 0 20px">'+ '<label for="query_order_money">订单金额</label>'+ '<input type="text" class="form-control" id="query_order_money" readonly unselectable="on" value='+data[i].o_price+'>'+ '</div>'+ '<div class="form-group magin_left" style="margin: 20px 20px 0 20px">'+ '<label for="query_order_remark">订单备注</label>'+ '<input type="text" class="form-control" id="query_order_remark" readonly unselectable="on" value='+data[i].o_remark+'>'+ '</div>'+ '<div class="form-group magin_left" style="margin: 20px 20px 0 20px">'+ '<label for="query_order_addr">订单地址</label>'+ '<input type="text" class="form-control" id="query_order_addr" readonly unselectable="on" value='+data[i].addr_id+'>'+ '</div>'+ '<div class="form-group magin_left" style="margin: 20px 20px 0 20px">'+ '<label for="query_order_createtime">创建时间</label>'+ '<input type="text" class="form-control" id="query_order_createtime" readonly unselectable="on" value='+data[i].createtime+'>'+ '</div>'+ '<div class="form-group magin_left" style="margin: 20px 20px 0 20px">'+ '<label for="query_order_paytime">付款时间</label>'+ '<input type="text" class="form-control" id="query_order_paytime" readonly unselectable="on" value='+data[i].paytime+'>'+ '</div>'+ '<div class="form-group magin_left" style="margin: 20px 20px 0 20px">'+ '<label for="query_order_logis">物流单号</label>'+ '<input type="text" class="form-control" id="query_order_logis" readonly unselectable="on" value='+data[i].o_logis+'>'+ '</div>'+ '<div class="form-group magin_left" style="margin: 20px 20px 0 20px">'+ '<label for="query_state">订单是否启用</label>'+ '<select id="query_state" class="form-control">'+ '<option value="1">启用</option>'+ '<option value="0">禁止</option>'+ '</select>'+ '</div>'+ '<div class="form-group magin_left" style="margin: 20px 20px 0 20px">'+ '<label for="query_state"> <a href="orderGoods">订单商品详情</a></label>'+ '<div class="btn btn-success" style="margin-left: 30px" id="save">保存</div>'+ '</div>'+ '</form>'; } }) } $("#form").on('click','save',function () { updateOrder(); });
import React from "react"; import styled from "@emotion/styled"; import { green, red, blue, deepPurple } from "@mui/material/colors"; import Link from "next/link"; import { Button, Container, Grid, Typography, Box } from "@mui/material"; import { spacing } from "@mui/system"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faDesktop, faLaptop, faBrain, faDatabase, faCog, faFlask, faSquareFull, } from "@fortawesome/free-solid-svg-icons"; const Wrapper = styled.div` padding-top: 3.5rem; padding-bottom: 1rem; position: relative; text-align: center; overflow: hidden; `; const Title = styled(Typography)` line-height: 1.2; font-size: 1.75rem; font-weight: 700; text-align: center; ${(props) => props.theme.breakpoints.up("sm")} { font-size: 2.7rem; } background: linear-gradient(to right, #fc466b, #3f5efb); -webkit-background-clip: text; -webkit-text-fill-color: transparent; `; const SubTitle = styled.div` height: auto; padding-top: 15px; padding-bottom: 35px; font-size: 1.2em; font-weight: 700; text-align: center; `; const SubText = styled.div` height: auto; display: inline; padding-top: 10px; padding-bottom: 5px; font-size: 1.2em; margin-left: 10px; > a { color: white; padding-left: 10px; } `; const GradientButton = styled(Button)` border-radius: 50px; color: inherit; box-shadow: 0 0 6px 0 rgba(157, 96, 212, 0.5); border: solid 1px transparent; background-image: linear-gradient( rgba(255, 255, 255, 0), rgba(255, 255, 255, 0) ), linear-gradient(to right, #fc466b, #3f5efb); background-origin: border-box; background-clip: content-box, border-box; box-shadow: 2px 1000px 1px ${(props) => props.theme.palette.background.default} inset; &:hover { box-shadow: none; color: white; border: solid 1px transparent; } `; const FixedIcon = styled(FontAwesomeIcon)` position: absolute; font-size: ${(props) => (props.sizept ? props.sizept : 20)}pt; left: ${(props) => props.l}px; top: ${(props) => props.t}px; color: ${(props) => props.color}; `; const GradientIcon = styled(FontAwesomeIcon)` position: absolute; font-size: ${(props) => (props.sizept ? props.sizept : 20)}pt; left: ${(props) => props.l}px; top: ${(props) => props.t}px; color: ${(props) => props.theme.palette.background.default}; background: linear-gradient(to right, #fc466b, #3f5efb); `; function IntroGraph() { return ( <div style={{ position: "relative", margin: "auto", }} > <svg style={{ minHeight: 250, minWidth: 350, }} > <defs> <marker id="arrowhead" markerWidth="7" markerHeight="7" refX="0" refY="3.5" orient="auto" fill="#b39ddb" > <polygon points="0 0, 6 3, 0 6" /> </marker> </defs> <path d="M 40 160 C 40 60, 120 30, 130 30" stroke="#b39ddb" strokeWidth="2" fill="transparent" markerEnd="url(#arrowhead)" /> <path d="M 240 30 C 300 30, 340 100, 340 150" stroke="#b39ddb" strokeWidth="2" fill="transparent" markerEnd="url(#arrowhead)" /> <path d="M 300 180 C 250 180, 190 130, 190 80" stroke="#b39ddb" strokeWidth="2" fill="transparent" markerEnd="url(#arrowhead)" /> <rect x="60" y="150" rx="16" ry="20" width="140" height="32" fill={blue[400]} /> <text x="70" y="170" fill="white"> I shared new data :) </text> <rect fill={blue[400]} x="50" y="156" width="0" height="16"> <animate attributeName="x" values="65 ; 192 ; 192 ; 192 ; 192 ; 192" dur="6s" repeatCount="indefinite" /> <animate attributeName="width" values="128; 0; 0; 0; 0; 0" dur="6s" repeatCount="indefinite" /> </rect> <rect x="150" y="190" rx="16" ry="20" width="160" height="32" fill={blue[400]} /> <text x="160" y="210" fill="white"> I found a better model! </text> <rect fill={blue[400]} x="150" y="194" width="0" height="16"> <animate attributeName="x" values="160 ; 160 ; 300 ; 300 ; 300 ; 300" dur="6s" repeatCount="indefinite" /> <animate attributeName="width" values="140; 140; 0; 0 ; 0; 0" dur="6s" repeatCount="indefinite" /> </rect> <text x="165" y="62" fill="#ab47bc" fontWeight="bold"> OpenML </text> </svg> <FixedIcon color={deepPurple[200]} icon={faDesktop} l="0" t="170" sizept="45" /> <FixedIcon color={deepPurple[200]} icon={faLaptop} l="300" t="170" sizept="45" /> <GradientIcon mask={faSquareFull} icon={faBrain} l="167" t="0" sizept="35" suppressHydrationWarning={true} /> <FixedIcon color={green[500]} icon={faDatabase} l="40" t="40" sizept="20" /> <FixedIcon color={green[500]} icon={faDatabase} l="320" t="40" sizept="20" /> <FixedIcon color={blue[500]} icon={faCog} l="200" t="80" sizept="20" /> <FixedIcon color={red[500]} icon={faFlask} l="225" t="110" sizept="20" /> </div> ); } function Introduction() { return ( <Wrapper> <Container> <Grid container direction="column" alignItems="center" justifyContent="center" spacing={10} > <Grid item> <Title>Machine learning, better, together</Title> <SubTitle> OpenML is an open science platform for easily sharing machine learning data, models, and benchmarks to make machine learning more transparent, reproducible, and collaborative. </SubTitle> </Grid> <Grid item> <IntroGraph /> </Grid> <Grid item> <GradientButton component={Link} href="/auth/sign-up" variant="outlined" > Sign Up </GradientButton> <SubText>OpenML is open and free.</SubText> </Grid> </Grid> </Container> </Wrapper> ); } export default Introduction;
'use strict'; const logger = require('tracer').colorConsole(), fs = require('fs'), request = require('request'), // util = require('../helpers/util'), path = require('path'); let express = require('express'), router = express.Router(); router.get('/:id?', function(req, res) { try{ if(req.params.id){ let id = req.params.id; if(util.isOnlyNumber(id)){ let fullpath = path.join(root_dir,'app','public','avatar', id); fullpath+='.jpg'; if(fs.existsSync(fullpath)){ res.sendFile(fullpath); } else{ fullpath = path.join(root_dir, config.no_avatar); res.sendFile(fullpath); } } else{ res.send('vcc'); } } else{ res.send('vcc'); } } catch(e){ logger.error(e.stack); } }); module.exports = router;
describe('ToonsController', function() { beforeEach(module('myApp')); it('should instantiate a toons model', inject(function($controller) { var scope = {}, controller = $controller('ToonsController', {$scope: scope}); expect(scope.toons.length).toBe(2); })); });
angular.module('ngApp.eCommerce') .controller("eCommerceCommunicationController", function ($scope, $interval, AppSpinner, UtilityService, DateFormatChange, eCommerceBookingService, SessionService, toaster, $translate) { //set translate code start var setMultilingualOptions = function () { $translate(['FrayteError', 'FrayteWarning', 'Frayte_Success', 'ErrorSavingDataPleaseTryAgain', 'CommunicationAddedSuccessfully', 'EmailSentSuccessfully', 'CorrectValidationError', 'SavingCommunication', 'SendingEmail']).then(function (translations) { $scope.FrayteWarning = translations.FrayteWarning; $scope.Frayte_Success = translations.Frayte_Success; $scope.FrayteError = translations.FrayteError; $scope.ErrorSavingDataPleaseTryAgain = translations.ErrorSavingDataPleaseTryAgain; $scope.CommunicationAddedSuccessfully = translations.CommunicationAddedSuccessfully; $scope.EmailSentSuccessfully = translations.EmailSentSuccessfully; $scope.CorrectValidationError = translations.CorrectValidationError; $scope.SendingEmail=translations.SendingEmail; $scope.SavingCommunication = translations.SavingCommunication; }); }; $scope.GetCorrectFormattedDate = function (date, time) { // Geting Correct Date Format if (date !== null && date !== '' && date !== undefined) { var newDate = new Date(date); var newTime; if (time !== undefined && time !== null) { newTime = time; } var days = ["SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY"]; //var monthNames = ["January", "February", "March", "April", "May", "June","July", "August", "September", "October", "November", "December" ]; //var dformat = days[newDate.getDay()] + ', ' + monthNames[newDate.getMonth()] + ' ' + newDate.getDate() + ', ' + newDate.getFullYear(); var dformat = days[newDate.getDay()] + ', ' + DateFormatChange.DateFormatChange(newDate); if (time !== undefined && time !== null) { //dformat = days[newDate.getDay()] + ', ' + monthNames[newDate.getMonth()] + ' ' + newDate.getDate() + ', ' + newDate.getFullYear() + ':' + newTime; dformat = days[newDate.getDay()] + ', ' + DateFormatChange.DateFormatChange(newDate) + ':' + newTime; } return dformat; } else { return; } }; $scope.save = function (valid, form) { if (valid) { AppSpinner.showSpinnerTemplate($scope.SavingCommunication, $scope.Template); eCommerceBookingService.CreateCommunication($scope.invoiceCommunication).then(function (response) { if (response.data.Status) { getScreenInitials(); toaster.pop({ type: 'success', title: $scope.Frayte_Success, body: $scope.CommunicationAddedSuccessfully, showCloseButton: true }); form.$setPristine(); form.$setUntouched(); $scope.submitted1 = false; $scope.invoiceCommunication.Description = ""; } else { toaster.pop({ type: 'error', title: $scope.FrayteError, body: $scope.ErrorSavingDataPleaseTryAgain, showCloseButton: true }); } AppSpinner.hideSpinnerTemplate(); }, function () { AppSpinner.hideSpinnerTemplate(); toaster.pop({ type: 'error', title: $scope.FrayteError, body: $scope.ErrorSavingDataPleaseTryAgain, showCloseButton: true }); }); } else { toaster.pop({ type: 'warning', title: $scope.FrayteWarning, body: $scope.CorrectValidationError, showCloseButton: true }); } }; $scope.SaveEmail = function (valid, form) { if (valid) { AppSpinner.showSpinnerTemplate($scope.SendingEmail, $scope.Template); eCommerceBookingService.SaveEmailCommunication($scope.emailCommunication).then(function (response) { if (response.data.Status) { getemailCommunications(); toaster.pop({ type: 'success', title: $scope.Frayte_Success, body: $scope.EmailSentSuccessfully, showCloseButton: true }); form.$setPristine(); form.$setUntouched(); $scope.submitted = false; $scope.emailCommunication.EmailBody = ""; $scope.emailCommunication.EmailSubject = ""; } else { toaster.pop({ type: 'error', title: $scope.FrayteError, body: $scope.ErrorSavingDataPleaseTryAgain, showCloseButton: true }); } AppSpinner.hideSpinnerTemplate(); }, function () { AppSpinner.hideSpinnerTemplate(); toaster.pop({ type: 'error', title: $scope.FrayteError, body: $scope.ErrorSavingDataPleaseTryAgain, showCloseButton: true }); }); } else { toaster.pop({ type: 'warning', title: $scope.FrayteWarning, body: $scope.CorrectValidationError, showCloseButton: true }); } }; $scope.ResendMail = function (emailCommunication) { $scope.emailCommunication = { eCommerceEmailCommunicationId: 0, ShipmentId: $scope.$parent.ShipmentId, CreatedBy: $scope.createdBy, EmailSentOnDate: emailCommunication.EmailSentOnDate, EmailSentTime: emailCommunication.EmailSentTime, EmailSubject: emailCommunication.EmailSubject, EmailBody: emailCommunication.EmailBody, CC: emailCommunication.CC, BCC: emailCommunication.BCC, SentTo: emailCommunication.SentTo }; }; var getemailCommunications = function () { eCommerceBookingService.GetEmailCommunication($scope.createdBy, $scope.$parent.ShipmentId).then(function (response) { $scope.emailCommunications = response.data; }, function () { }); }; var getScreenInitials = function () { eCommerceBookingService.GetCommunications($scope.createdBy, $scope.$parent.ShipmentId).then(function (response) { $scope.communications = response.data; }, function () { }); }; $scope.callAtInterval = function () { getScreenInitials(); }; $scope.stop = function () { // $interval.cancel($scope.promise); }; $scope.$on('$destroy', function () { // $scope.stop(); }); function init() { $scope.Template = 'directBooking/ajaxLoader.tpl.html'; // $scope.promise = $interval(function () { $scope.callAtInterval(); }, 20000); var userInfo = SessionService.getUser(); if (userInfo) { $scope.createdBy = userInfo.EmployeeId; } else { $scope.createdBy = 0; } $scope.options = [ { key: "Private", value: "Private" }, { key: "Public", value: "Public" } ]; $scope.invoiceCommunication = { ShipmentId: $scope.$parent.ShipmentId, CreatedBy: $scope.createdBy, Description: "", AccessType: "Public" }; $scope.emailCommunication = { eCommerceEmailCommunicationId: 0, ShipmentId: $scope.$parent.ShipmentId, CreatedBy: $scope.createdBy, EmailSentOnDate: new Date(), EmailSentTime: "", EmailSubject: "", EmailBody: "", CC: "", BCC: "", SentTo: "" }; if ($scope.$parent.Status !== "Draft") { getScreenInitials(); getemailCommunications(); } setMultilingualOptions(); } init(); });
const assert = require('assert'); class TraitSet { static fromKeys( obj ) { return TraitSet.fromStrings( Object.keys(obj) ); } static fromStrings( names ) { const obj = {}; names.forEach( name=>{ obj[name] = Symbol(name); } ); return new TraitSet(obj); } constructor( traitSet={} ) { for( let key in traitSet ) { const sym = traitSet[key]; if( typeof sym === 'symbol' ) { this[key] = sym; } } } // the following will be implemented later, as an alias for `Object.prototype.*traitsToFreeFunctions` //asFreeFunctions() {} } const traits = TraitSet.fromStrings([ // traits for `Symbol` to aid its usage as traits `impl`, // sym( target, implementation ) => this `implDefault`, // sym( implementation ) => this `asFreeFunction`, // sym() => {fn} // traits for `Object` to aid its usage as trait sets // stuff to add new traits to `this` `addSymbol`, // obj( name, sym ) => symbol `defineTrait`, // obj( name ) => symbol `borrowTraits`, // obj( traitSet, names=undefined ) => this // stuff to create wrappers for traits from `this` `traitsToFreeFunctions`, // obj() => {fn} // stuff to implement many traits at once (and maybe define them too) `implTraits`, // obj( target, implementationObj ) => this `defineAndImplTraits`, // obj( target, implementationObj ) => this `defineAndImplMethodsAsTraits`, // obj( target, source, methodList ) => this `defineAndImplMemberFreeFunctionsAsTraits`, // obj( target, functionObj ) => this ]); use traits * from traits; // we'll use `Symbol['@straits']` to store everything we want to be globally available // i.e. available to other packages we might be unaware of (including different versions of `@straits/utils`) const namespace = (()=>{ if( Symbol['@straits'] ) { return Symbol['@straits']; } return Symbol['@straits'] = { defaultImpls: new Map() // NOTE: a WeakMap would be better here, but: https://github.com/tc39/ecma262/issues/1194 }; })(); TraitSet.namespace = namespace; // implementing traits for traits for `Symbol` { // set `target[ this ]` to `implementation` Symbol.prototype.*impl = function( target, implementation ) { Object.defineProperty( target, this, {value:implementation, configurable:true} ); return this; }; // set `implementation` as the default implementation for `this` trait // it will be used if `this` trait is called (as a method or free function) on something that doesn't implement `this` trait Symbol.prototype.*implDefault = function( implementation ) { namespace.defaultImpls.set( this, implementation ); return this; }; // create and return a free function wrapping `this` Symbol.prototype.*asFreeFunction = function() { const symName = String(this).slice(7, -1); const sym = this; return function( target, ...args ) { if( target === undefined || target === null ) { const {defaultImpls} = namespace; if( defaultImpls.has(sym) ) { return defaultImpls.get(sym)( target, ...args ); } throw new Error(`.*${symName} called on ${target}`); } if( ! target[sym] ) { const {defaultImpls} = namespace; if( defaultImpls.has(sym) ) { return defaultImpls.get(sym)( target, ...args ); } throw new Error(`.*${symName} called on ${target} that doesn't implement it.`); } return target[sym]( ...args ); }; }; } // implementing traits for trait sets on `Object` { // add `symbol` to `this` with key `name` Object.prototype.*addSymbol = function( name, sym ) { assert( ! this.hasOwnProperty(name), `Trying to re-define trait \`${name}\`` ); assert.equal( typeof sym, `symbol`, `Trying to add \`${name}\`, but it's not a symbol` ); return this[name] = sym; }; // add a new trait called `name` to `this` Object.prototype.*defineTrait = function( name ) { return this.*addSymbol( name, Symbol(name) ); }; // add to `this` trait set all the symbols from `traitSet` specified by `names` Object.prototype.*borrowTraits = function( traitSet, names ) { if( ! names ) { for( let key in traitSet ) { const sym = traitSet[key]; if( typeof sym === 'symbol' ) { this.*addSymbol( key, sym ); } } return this; } names.forEach( name=>{ this.*addSymbol( name, traitSet[name] ); }); return this; }; // `this` is treated as a trait set: return a free function wrapping each trait Object.prototype.*traitsToFreeFunctions = function() { const result = {}; for( let key in this ) { const sym = this[key]; if( typeof sym === 'symbol' ) { result[key] = sym.*asFreeFunction(); } } return result; }; // `implementationObj` is an object whose keys are names of traits in `this` trait set // for each `key, value` entry of `implementationObj`, set `target[ this[key] ]` to `value` Object.prototype.*implTraits = function( target, implementationObj ) { for( let name in implementationObj ) { const sym = this[name]; assert( typeof sym === 'symbol', `No trait \`${name}\`` ); sym.*impl( target, implementationObj[name] ); } return this; }; // for each `key, value` entry of `implementationObj`, // create a new symbol called `key` in `this` trait set, and set `target[ this[key] ]` to `value` Object.prototype.*defineAndImplTraits = function( target, implementationObj ) { for( let name in implementationObj ) { const value = implementationObj[name]; this.*defineTrait( name ).*impl( target, value ); } return this; }; // `methodList` is a list of method names in `source` // for each method name `m` in `methodList`, create a new trait in `this` trait set, // and set `target[ this[m] ]` to a function wrapping `::source.m()` Object.prototype.*defineAndImplMethodsAsTraits = function( target, source, methodList ) { methodList.forEach( (methodName)=>{ this .*defineTrait( methodName ) .*impl( target, ({[methodName](){ return source[methodName]( this, ...arguments ); }})[methodName] ); }); return this; }; // `functionObj` is an object whose values are free functions // for each `key, value` entry in `methodList`, create a new trait in `this` trait set, // and set `target[ this[key] ]` to a function wrapping `::source.m()` Object.prototype.*defineAndImplMemberFreeFunctionsAsTraits = function( target, functionObj ) { for( let fnName in functionObj ) { const fn = functionObj[fnName]; if( typeof fn !== 'function' ) { continue; } this .*defineTrait( fnName ) .*impl( target, ({[fnName](){ return fn( this, ...arguments ); }})[fnName] ); } return this; }; } // finalizing and exporting { // adding missing methods to TraitSet's prototype TraitSet.prototype.asFreeFunctions = Object.prototype.*traitsToFreeFunctions; // adding our traits to `TraitSet` TraitSet.*borrowTraits( traits ); // adding functions to convert TraitSet's traits into free functions and methods TraitSet.prototype.asFreeFunctions = Object.prototype.*traitsToFreeFunctions; // exporting TraitSet module.exports.TraitSet = TraitSet; }
import React from "react"; //import PropTypes from "prop-types"; import { makeStyles } from "@material-ui/core/styles"; import { DataGrid } from "@material-ui/data-grid"; import GroupIcon from "@material-ui/icons/Group"; import DashboardIcon from "@material-ui/icons/Dashboard"; const useStyles = makeStyles({ root: { "& .MuiDataGrid-columnsContainer": { backgroundColor: "#35384F", }, "& .MuiDataGrid-root .MuiDataGrid-columnSeparator ": { display: "none", }, "& .MuiDataGrid-root .MuiDataGrid-columnHeaderTitle ": { color: "wheat", fontSize: "0.9rem", fontFamily: ["Roboto", "Helvetica", "Arial", "sans-serif"], fontWeight: "400", lineHeight: "1.5", letterSpacing: "0.00938em", }, "& .MuiDataGrid-root .MuiDataGrid-window ": { overflowY: "hidden !important", }, }, }); const CustomizedTables = (props) => { const { data, columns, disableColumnMenu, disableColumnFilter, pageSizeChange, pageSize, iconType } = props; const classes = useStyles(); const CustomNoRowsOverlay = (icon) => { return ( <div> {icon === "usersIcon" && ( <div style={{ marginTop: "5rem" }}> <div> <GroupIcon style={{ color: "wheat", fontSize: 34 }} /> </div> <small style={{ marginTop: "3rem" }}>No Users Found</small> </div> )} {icon === "eventIcon" && ( <div style={{ marginTop: "5rem" }}> <div> <DashboardIcon style={{ color: "wheat", fontSize: 34 }} /> </div> <small style={{ marginTop: "3rem" }}>No Event's Found</small> </div> )} </div> ); }; return ( <div style={{ height: 250, width: "100%" }} className={classes.root}> {console.log(props)} <DataGrid columns={columns ? columns : []} rows={data ? data : []} disableColumnMenu={disableColumnMenu} disableColumnFilter={disableColumnFilter} pageSize={pageSize} onPageChange={(newPageSize) => pageSizeChange(newPageSize)} rowsPerPageOptions={[5, 10, 20]} pagination components={{ NoRowsOverlay: () => CustomNoRowsOverlay(iconType), }} /> </div> ); }; export default CustomizedTables;
import React, { useState, useEffect } from "react"; import { Jumbotron, Container, Row, Col, Button, Form } from 'react-bootstrap'; import { Analytics } from '../Analytics/Analytics' import { addScore, getAverageScore } from '../../requests/requests' import './SubmitScore.scss' export const SubmitScore = ({userScores, setScreen, skipSubmit}) => { const [userName, setUserName] = useState("") const [showForm, setShowForm] = useState(false) const [showAnalytics, setshowAnalytics] = useState(false) const [metrics, setMetrics] = useState([]) useEffect(() => { if(skipSubmit) { async function getAverageScores() { const metric = await getAverageScore() setMetrics(metric.data) setshowAnalytics(true) } getAverageScores() } }, [skipSubmit]); const finalScore = (userScores.reduce((a, b) => a + b, 0) / userScores.length).toFixed(2) const createUserScores = () => { return ( <Row className="py-3"> {userScores.map((score, index) => <Col key={index} xs={4}><span className='text-header'>Mini-Game {index + 1}:</span>{score}</Col> )} </Row> ) } const handleSetUserName = (e) => { const username = e.target.value setUserName(username) } const handleShowForm = (e) => { e.preventDefault(); setShowForm(!showForm); } const handleSubmit = async (e) => { e.preventDefault(); const req = { username: userName, score: userScores } await addScore(req) const metric = await getAverageScore() setMetrics(metric.data) setshowAnalytics(true) } return ( <div id="SubmitScore"> <Jumbotron className="justify-content-center"> <Container> <Row> <Col> <h1 className='display-4'>Your Final Score is: <span className='text-header'>{finalScore}</span></h1> <div className='lead'> <p> Here is a break down for your individual scores: </p> {createUserScores()} </div> </Col> </Row> {showForm && !showAnalytics && <Form> <Row> <Col xs={6}> <Form.Group controlId="formUsername" className='py-3' > <Form.Label>Username</Form.Label> <Form.Control type="text" placeholder="Enter username" value={userName} onChange={handleSetUserName} /> <Form.Text className="text-muted"> Your score will be saved under this username </Form.Text> </Form.Group> </Col> </Row> </Form> } {!showAnalytics && (!showForm ? ( <Row className="py-3"> <Col xs={4}> <Button size="lg" className="btn-score w-100" onClick={handleShowForm}> Click here to submit your score </Button> </Col> </Row> ) : ( <Row className=""> <Col xs={4}> <Button size="lg" className="btn-score w-100" onClick={handleSubmit}> Submit score </Button> </Col> </Row> ) )} </Container> </Jumbotron> {showAnalytics && ( <Analytics userScores={userScores} metrics={metrics}/> ) } </div> ); }
import React, { Component } from 'react'; import Exercise from './exercise'; import Search from './search'; import Container from './container'; import Heading from './heading'; import Controls from './controls' type State = { work: Array<exercises>, step: string, counter: number, gender: boolean, infoToggle: boolean, searchToggle: boolean, searchTerm: string, imageStatus: string, userSearchActive: boolean, userSearchFound: { name: string, transcript: string, female: string, male: string } } class MainApp extends Component<Props, State> { state = { work: this.props.work.exercises ? this.props.work.exercises : [], step: 'start', counter: 1, gender: true, infoToggle: true, searchToggle: true, searchTerm: '', imageStatus: '', error: null, errorInfo: null, userSearchActive: false, userSearchFound: { name: '', transcript: '', female: '', male: '' } }; componentDidMount() { if ((this.state.work === undefined) || (this.state.work.length === 0)) { this.setState({ step: 'error' }) } else { this.setState({ step: 'start' }) } } componentDidCatch(error, errorInfo) { // Catch errors in any components below and re-render with error message this.setState({ error: error, errorInfo: errorInfo }) // You can also log error messages to an error reporting service here } toggleGender = (event: SyntheticEvent<HTMLInputElement>) => { event.preventDefault(); this.setState({ gender: !this.state.gender }) } closeAll = (event: SyntheticEvent<HTMLInputElement>) => { event.preventDefault(); this.setState({ searchToggle: true, infoToggle: true }) } toggleSearch = (event: SyntheticEvent<HTMLInputElement>) => { event.preventDefault(); this.setState({ searchToggle: false, infoToggle: true }) } toggleInfo = (event: SyntheticEvent<HTMLInputElement>) => { event.preventDefault(); this.setState({ searchToggle: true, infoToggle: false }) } counterIncrease = (event: SyntheticEvent<HTMLInputElement>) => { event.preventDefault(); this.setState({ userSearchActive: false }) if (this.state.counter === (this.state.work.length - 1)) { this.setState({ counter: 0 }) } else { this.setState({ counter: this.state.counter + 1 }) } } counterDecrease = (event: SyntheticEvent<HTMLInputElement>) => { event.preventDefault(); if (this.state.counter === 0) { this.setState({ counter: (this.state.work.length - 1) }) } else { this.setState({ counter: this.state.counter - 1 }) } } getSearchValue = (event: SyntheticEvent<HTMLInputElement>) => { var search = event.target.value; this.setState({ searchTerm: search }) } updateCard = (event: SyntheticEvent<HTMLInputElement>) => { var exerciseSelected = event.currentTarget.innerHTML; var userSearch = this.state.work.filter((item: Object) => { return item.name === exerciseSelected }); if (userSearch) { this.setState({ userSearchActive: true, infoToggle: true, searchToggle: true, userSearchFound: { name: userSearch[0].name, transcript: userSearch[0].transcript, female: { image: userSearch[0].female.image }, male: { image: userSearch[0].male.image } } }) } } render() { if (this.state.errorInfo) { // Error path return ( <div> <h2>Something went wrong.</h2> <details style={{ whiteSpace: 'pre-wrap' }}> {this.state.error && this.state.error.toString()} <br /> {this.state.errorInfo.componentStack} </details> </div> ); } const app = this.state.step === 'start' ? ( <div> <Controls closeAll={this.closeAll} searchToggle={this.state.searchToggle} toggleSearch={this.toggleSearch} toggleGender={this.toggleGender} gender={this.state.gender} counterDecrease={this.counterDecrease} counterIncrease={this.counterIncrease} toggleInfo={this.toggleInfo} infoToggle={this.state.infoToggle} /> <Exercise transcript={this.state.userSearchActive ? this.state.userSearchFound.transcript : (this.state.work.length > 0 ? this.state.work[this.state.counter].transcript : '')} infoToggle={this.state.infoToggle} title={this.state.userSearchActive ? this.state.userSearchFound.name : (this.state.work.length > 0 ? this.state.work[this.state.counter].name : '')} /> <Search searchToggle={this.state.searchToggle} excercises={this.state.work} updateCard={this.updateCard} searchTerm={this.state.searchTerm} getSearchValue={this.getSearchValue} /> <Heading searchToggle={this.state.searchToggle} infoToggle={this.state.infoToggle} title={this.state.userSearchActive ? this.state.userSearchFound.name : (this.state.work.length > 0 ? this.state.work[this.state.counter].name : '')} /> </div> ) : ( <p className="loading">..Sorry, there has been an error..</p> ); return ( <Container excercises={this.state.work} searchToggle={this.state.searchToggle} infoToggle={this.state.infoToggle} img={this.state.userSearchActive ? this.state.userSearchFound[this.state.gender ? 'male' : 'female'].image : (this.state.work.length > 0 ? this.state.work[this.state.counter][this.state.gender ? 'male' : 'female'].image : '')}> {app} </Container> ); } } export default MainApp;
$(function() { /* Push the body and the nav over by 285px over */ $('.icon-menu').click(function() { $('.menu').animate({ left: "0px" }, 200); $('body').animate({ left: "90px" }, 200); }); /* Then push them back */ $('.icon-close').click(function() { $('.menu').animate({ left: "-90px" }, 200); $('body').animate({ left: "0px" }, 200); }); $('a [href*="#"]:not([href="#"])').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); if (target.length) { $('html, body').animate({ scrollTop: target.offset().top }, 1000); return false; } } }); }); $(function(){ var old = console.log; var logger = document.getElementById('result'); console.log = function (message) { if (typeof message == 'object') { logger.innerHTML += (JSON && JSON.stringify ? JSON.stringify(message) : message) + '<br />'; } else { logger.innerHTML += message + '<br />'; } } }); $(function() { $('.scroll-pane').jScrollPane(); }); function StockPriceTicker() { 'use strict'; var ticker = document.getElementById("tickBox").value, YQL_url = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22" + ticker + "%22)&format=json&env=store://datatables.org/alltableswithkeys", StockTickerHTML = "", CompName, Price, ChnageInPrice, PercentChnageInPrice, Time, Open, PrevClose, stockhtmlTable, stockhtmlChart, Symbol, Ask, Bid, Volume, Exchange, StockTickerXML = $.get(YQL_url, function (_return) { var stock = _return.query.results.quote; CompName = stock.Name; Symbol = stock.symbol; Price = stock.LastTradePriceOnly; Time = stock.LastTradeTime; ChnageInPrice = stock.Change; PercentChnageInPrice = stock.Change_PercentChange; Open = stock.Open; PrevClose = stock.PreviousClose; Ask = stock.Ask; Bid = stock.Bid; Volume = stock.Volume; Exchange = stock.StockExchange; stockhtmlTable = "<h2> Company Name: " + CompName + " (" + Symbol + ") </h2>"; stockhtmlTable = stockhtmlTable + "<table style='width:35%' align='center'> <tr>"; stockhtmlTable = stockhtmlTable + "<th>Last Trade Price ($):</th>"; stockhtmlTable = stockhtmlTable + "<th>" + Price + "</th>"; stockhtmlTable = stockhtmlTable + "<th>Last Trade Time:</th>"; stockhtmlTable = stockhtmlTable + "<th>" + Time + "</th></tr>"; stockhtmlTable = stockhtmlTable + "<tr><th>Change ($):</th>"; stockhtmlTable = stockhtmlTable + "<th>" + ChnageInPrice + "</th>"; stockhtmlTable = stockhtmlTable + "<th>Percent Change ($):</th>"; stockhtmlTable = stockhtmlTable + "<th>" + PercentChnageInPrice + "</th></tr>"; stockhtmlTable = stockhtmlTable + "<tr><th>Open ($):</th>"; stockhtmlTable = stockhtmlTable + "<th>" + Open + "</th>"; stockhtmlTable = stockhtmlTable + "<th>Previous Close ($):</th>"; stockhtmlTable = stockhtmlTable + "<th>" + PrevClose + "</th></tr>"; stockhtmlTable = stockhtmlTable + "<tr><th>Ask ($):</th>"; stockhtmlTable = stockhtmlTable + "<th>" + Ask + "</th>"; stockhtmlTable = stockhtmlTable + "<th>Bid ($):</th>"; stockhtmlTable = stockhtmlTable + "<th>" + Bid + "</th></tr>"; stockhtmlTable = stockhtmlTable + "<th>Volume (shares) :</th>"; stockhtmlTable = stockhtmlTable + "<th>" + Volume + "</th>"; stockhtmlTable = stockhtmlTable + "<th> Stock Exchange :</th>"; stockhtmlTable = stockhtmlTable + "<th>" + Exchange + "</th></tr>"; stockhtmlTable = stockhtmlTable + "</table><br>"; stockhtmlTable = stockhtmlTable + "<button style=\"background-color: green;border: none;color: white;text-align: center;padding: 5px 20px;font-size: 16px;\" onclick=\"insert1D('" + Symbol + "')\" id='1DButton' class='tickButton'>1D</button>"; stockhtmlTable = stockhtmlTable + "<button style=\"background-color: green;border: none;color: white;text-align: center;padding: 5px 20px;font-size: 16px;\" onclick=\"insert5D('" + Symbol + "')\" id='5DButton' class='tickButton'>5D</button>"; stockhtmlTable = stockhtmlTable + "<button style=\"background-color: green;border: none;color: white;text-align: center;padding: 5px 20px;font-size: 16px;\" onclick=\"insert1M('" + Symbol + "')\" id='1MButton' class='tickButton'>1M</button>"; stockhtmlTable = stockhtmlTable + "<button style=\"background-color: green;border: none;color: white;text-align: center;padding: 5px 20px;font-size: 16px;\" onclick=\"insert6M('" + Symbol + "')\" id='6MButton' class='tickButton'>6M</button>"; stockhtmlTable = stockhtmlTable + "<button style=\"background-color: green;border: none;color: white;text-align: center;padding: 5px 20px;font-size: 16px;\" onclick=\"insert1Y('" + Symbol + "')\" id='1YButton' class='tickButton'>1Y</button>"; stockhtmlTable = stockhtmlTable + "<button style=\"background-color: green;border: none;color: white;text-align: center;padding: 5px 20px;font-size: 16px;\" onclick=\"insert2Y('" + Symbol + "')\" id='2YButton' class='tickButton'>2Y</button>"; stockhtmlTable = stockhtmlTable + "<button style=\"background-color: green;border: none;color: white;text-align: center;padding: 5px 20px;font-size: 16px;\" onclick=\"insert5Y('" + Symbol + "')\" id='5YButton' class='tickButton'>5Y</button>"; stockhtmlTable = stockhtmlTable + "<button style=\"background-color: green;border: none;color: white;text-align: center;padding: 5px 20px;font-size: 16px;\" onclick=\"insert9Y('" + Symbol + "')\" id='9YButton' class='tickButton'>9Y</button>"; document.getElementById("showStockTick").innerHTML = stockhtmlTable; insert6M(Symbol); }); } function insert1D(Symbol) { insertChart(Symbol,"1d"); } function insert5D(Symbol) { insertChart(Symbol,"5d"); } function insert1M(Symbol) { insertChart(Symbol,"1m"); } function insert6M(Symbol) { insertChart(Symbol,"6m"); } function insert1Y(Symbol) { insertChart(Symbol,"1y"); } function insert2Y(Symbol) { insertChart(Symbol,"2y"); } function insert5Y(Symbol) { insertChart(Symbol,"5y"); } function insert9Y(Symbol) { insertChart(Symbol,"9y"); } function insertChart(Symbol,length) { insertImage = "<img src='https://chart.finance.yahoo.com/z?s=" + Symbol + "&t=" + length + "&q=l&l=on&z=s&p=m50,m200'/>"; document.getElementById("stockChart").innerHTML = insertImage; }
'use strict'; var SVGGLSL = this.SVGGLSL = function SVGGLSL(canvas) { if (!canvas) { canvas = document.createElement('canvas'); } this.canvas = canvas; this.gl2d = WebGL2D.enable(canvas); // adds new context "webgl-2d" to canvas }; SVGGLSL.prototype.convert = function (svg, callback) { canvg(this.canvas, svg, { ignoreMouse: true, ignoreAnimation: true, ignoreDimensions: true, ignoreClear: true, renderCallback: callback }); }; SVGGLSL.prototype.getVertexShaderSource = function () { return this.gl2d.getVertexShaderSource(); }; SVGGLSL.prototype.getFragmentShaderSource = function () { return this.gl2d.getFragmentShaderSource(); };
module.exports = { title: '<%= projectName %>', description: '<%= description %>', themeConfig: { nav: [ { text: 'Home', link: '/' }, { text: 'Company', link: '<%= companyWebsite %>' }, { text: 'License', link: '/LICENSE.md' }, ], sidebar: [ ['/', 'Home'], ], repo: '<%= repoUrl %>', docsDir: 'docs', docsBranch: 'master' }, markdown: { lineNumbers: true, }, serviceWorker: true, plugins: [ ['vuepress-plugin-zooming', { // selector for images that you want to be zoomable // default: '.content img' selector: 'img', // make images zoomable with delay after entering a page // default: 500 // delay: 1000, // options of zooming // default: {} options: { bgColor: 'black', zIndex: 10000, }, }], ], }
/** * Created by chent on 2017/1/18. */ angular.module("myApp").controller("ProductCtrl",["$scope","$rootScope","ProductService",function ($scope,$rootScope,ProductService) { var page,time,status; $scope.changeStatus = function(newStatus){ page = 0; time = 0; status = newStatus; $scope.products = loadProducts(status,page,time); }; //$rootScope 在购买的时候应该会有用吧 //$scope.products = ProductService.getProductList(); $scope.refreshPage = function () { $scope.products = loadProducts(status,page,time); }; $scope.loadMore = function () { page = page+1; var products = loadProducts(status,page,time); if(products.length>0) for(var i=0,len=products.length; i<len; i++){ $scope.products.push(products[i]); } }; function loadProducts(status,page,time) { return ProductService.getProductList(status,page,time); } function initPage(){ page =0;time=0; var productStatusArray = ProductService.getProductStatusArray(); $scope.productStatusArray = productStatusArray; status = productStatusArray[0]; $scope.products = loadProducts(status,page,time); } //初始化 initPage(); }]); myApp.controller("ProductDetailCtrl",["$scope","$rootScope",'$stateParams','ProductService',function ($scope,$rootScope,$stateParams,ProductService) { //取得传过来的参数 console.log($rootScope.backState) var productId = $stateParams.productId; // console.log(); $scope.product = ProductService.getProductDetail(productId); }]);
import React, { useState, useEffect } from 'react'; import PropTypes from 'prop-types'; import { View, ScrollView, StyleSheet, Image, Dimensions, TouchableOpacity } from 'react-native'; import StyledButton from '../../UI/StyledButton'; import { colors, baseStyles } from '../../../styles/common'; import { strings } from '../../../../locales/i18n'; import FadeOutOverlay from '../../UI/FadeOutOverlay'; import ScrollableTabView from 'react-native-scrollable-tab-view'; import { getTransparentOnboardingNavbarOptions } from '../../UI/Navbar'; import OnboardingScreenWithBg from '../../UI/OnboardingScreenWithBg'; import Text from '../../Base/Text'; import { getBasicGasEstimates, getRenderableFiatGasFee } from '../../../util/custom-gas'; import { connect } from 'react-redux'; import Device from '../../../util/Device'; const IMAGE_3_RATIO = 281 / 354; const IMAGE_2_RATIO = 353 / 416; const IMAGE_1_RATIO = 295 / 354; const DEVICE_WIDTH = Dimensions.get('window').width; const IMG_PADDING = Device.isIphone5() ? 220 : 200; const styles = StyleSheet.create({ scroll: { flexGrow: 1 }, wrapper: { paddingVertical: Device.isIphone5() ? 15 : 30, flex: 1 }, title: { fontSize: 24, marginBottom: Device.isIphone5() ? 8 : 14, justifyContent: 'center', textAlign: 'center' }, subtitle: { fontSize: 14, marginBottom: Device.isIphone5() ? 8 : 14, justifyContent: 'center', textAlign: 'center', lineHeight: 20 }, subheader: { fontSize: 16, marginBottom: Device.isIphone5() ? 8 : 14, lineHeight: 22.5, justifyContent: 'center', textAlign: 'center' }, link: { marginTop: Device.isIphone5() ? 12 : 24, fontSize: 14, justifyContent: 'center', textAlign: 'center', lineHeight: 20 }, ctas: { flex: 1, justifyContent: 'flex-end', paddingHorizontal: 40 }, ctaWrapper: { justifyContent: 'flex-end' }, carouselImage: {}, // eslint-disable-next-line react-native/no-unused-styles carouselImage1: { width: DEVICE_WIDTH - IMG_PADDING, height: (DEVICE_WIDTH - IMG_PADDING) * IMAGE_1_RATIO }, // eslint-disable-next-line react-native/no-unused-styles carouselImage2: { width: DEVICE_WIDTH - IMG_PADDING, height: (DEVICE_WIDTH - IMG_PADDING) * IMAGE_2_RATIO }, // eslint-disable-next-line react-native/no-unused-styles carouselImage3: { width: DEVICE_WIDTH - IMG_PADDING, height: (DEVICE_WIDTH - IMG_PADDING) * IMAGE_3_RATIO }, carouselImageWrapper: { flexDirection: 'row', justifyContent: 'center' }, circle: { width: 8, height: 8, borderRadius: 8 / 2, backgroundColor: colors.grey500, opacity: 0.4, marginHorizontal: 8 }, solidCircle: { opacity: 1 }, progessContainer: { flexDirection: 'row', alignSelf: 'center', marginVertical: Device.isIphone5() ? 18 : 36 }, tab: { margin: 32 } }); const gas_education_carousel_1 = require('../../../images/gas-education-carousel-1.png'); // eslint-disable-line const gas_education_carousel_2 = require('../../../images/gas-education-carousel-2.png'); // eslint-disable-line const gas_education_carousel_3 = require('../../../images/gas-education-carousel-3.png'); // eslint-disable-line const carousel_images = [gas_education_carousel_1, gas_education_carousel_2, gas_education_carousel_3]; /** * View that is displayed to first time (new) users */ const GasEducationCarousel = ({ navigation, route, conversionRate, currentCurrency }) => { const [currentTab, setCurrentTab] = useState(1); const [gasFiat, setGasFiat] = useState(null); useEffect(() => { const setGasEstimates = async () => { const gasEstimate = await getBasicGasEstimates(); const gasFiat = getRenderableFiatGasFee(gasEstimate.averageGwei, conversionRate, currentCurrency); setGasFiat(gasFiat); }; setGasEstimates(); }, [conversionRate, currentCurrency]); const onPresGetStarted = () => { navigation.pop(); route?.params?.navigateTo?.(); }; const renderTabBar = () => <View />; const onChangeTab = obj => { setCurrentTab(obj.i + 1); }; const openLink = () => navigation.navigate('Webview', { screen: 'SimpleWebview', params: { url: 'https://community.metamask.io/t/what-is-gas-why-do-transactions-take-so-long/3172' } }); const renderText = key => { if (key === 1) { return ( <View style={styles.tab}> <Text noMargin bold black style={styles.title} testID={`carousel-screen-${key}`}> {strings('fiat_on_ramp.gas_education_carousel.step_1.title')} </Text> <Text grey noMargin bold style={styles.subheader}> {strings('fiat_on_ramp.gas_education_carousel.step_1.average_gas_fee')} {gasFiat} </Text> <Text grey noMargin style={styles.subtitle}> {strings('fiat_on_ramp.gas_education_carousel.step_1.subtitle_1')} </Text> <Text grey noMargin style={styles.subtitle}> {strings('fiat_on_ramp.gas_education_carousel.step_1.subtitle_2')}{' '} <Text bold>{strings('fiat_on_ramp.gas_education_carousel.step_1.subtitle_3')}</Text> </Text> </View> ); } if (key === 2) { return ( <View style={styles.tab}> <Text noMargin bold black style={styles.title} testID={`carousel-screen-${key}`}> {strings('fiat_on_ramp.gas_education_carousel.step_2.title')} </Text> <Text grey noMargin style={styles.subtitle}> {strings('fiat_on_ramp.gas_education_carousel.step_2.subtitle_1')} </Text> <Text grey noMargin bold style={styles.subtitle}> {strings('fiat_on_ramp.gas_education_carousel.step_2.subtitle_2')} </Text> <TouchableOpacity onPress={openLink}> <Text link noMargin bold style={styles.link}> {strings('fiat_on_ramp.gas_education_carousel.step_2.learn_more')} </Text> </TouchableOpacity> </View> ); } if (key === 3) { return ( <View style={styles.tab}> <Text noMargin bold black style={styles.title} testID={`carousel-screen-${key}`}> {strings('fiat_on_ramp.gas_education_carousel.step_3.title')} </Text> <Text noMargin bold style={styles.subheader}> {strings('fiat_on_ramp.gas_education_carousel.step_3.subtitle_1')} </Text> <Text noMargin style={styles.subtitle}> {strings('fiat_on_ramp.gas_education_carousel.step_3.subtitle_2')}{' '} </Text> <Text noMargin style={styles.subtitle}> {strings('fiat_on_ramp.gas_education_carousel.step_3.subtitle_3')}{' '} <Text bold>{strings('fiat_on_ramp.gas_education_carousel.step_3.subtitle_4')}</Text>{' '} {strings('fiat_on_ramp.gas_education_carousel.step_3.subtitle_5')} </Text> </View> ); } }; return ( <View style={baseStyles.flexGrow} testID={'gas-education-carousel-screen'}> <OnboardingScreenWithBg screen={'carousel'}> <ScrollView style={baseStyles.flexGrow} contentContainerStyle={styles.scroll}> <View style={styles.wrapper}> <ScrollableTabView style={styles.scrollTabs} renderTabBar={renderTabBar} onChangeTab={onChangeTab} > {['one', 'two', 'three'].map((value, index) => { const key = index + 1; const imgStyleKey = `carouselImage${key}`; return ( <View key={key} style={baseStyles.flexGrow}> <View style={styles.carouselImageWrapper}> <Image source={carousel_images[index]} style={[styles.carouselImage, styles[imgStyleKey]]} resizeMethod={'auto'} testID={`carousel-${value}-image`} /> </View> <View style={baseStyles.flexGrow}> {renderText(key)} {key === 3 && ( <View style={styles.ctas}> <View style={styles.ctaWrapper}> <StyledButton type={'confirm'} onPress={onPresGetStarted} testID={'gas-education-fiat-on-ramp-start'} > {strings('fiat_on_ramp.gas_education_carousel.step_3.cta')} </StyledButton> </View> </View> )} </View> </View> ); })} </ScrollableTabView> <View style={styles.progessContainer}> {[1, 2, 3].map(i => ( <View key={i} style={[styles.circle, currentTab === i && styles.solidCircle]} /> ))} </View> </View> </ScrollView> </OnboardingScreenWithBg> <FadeOutOverlay /> </View> ); }; GasEducationCarousel.navigationOptions = ({ navigation }) => getTransparentOnboardingNavbarOptions(navigation); GasEducationCarousel.propTypes = { /** * The navigator object */ navigation: PropTypes.object, /** /* conversion rate of ETH - FIAT */ conversionRate: PropTypes.any, /** /* Selected currency */ currentCurrency: PropTypes.string, /** * Object that represents the current route info like params passed to it */ route: PropTypes.object }; const mapStateToProps = state => ({ conversionRate: state.engine.backgroundState.CurrencyRateController.conversionRate, currentCurrency: state.engine.backgroundState.CurrencyRateController.currentCurrency }); export default connect(mapStateToProps)(GasEducationCarousel);
//development.js //"dburl": "mongodb://test:123456@192.168.218.145:27017/test" module.exports = { "dburl": "mongodb://ecast:123456@192.168.216.85:27017/ecast" };
import React, { useState, useEffect } from "react"; import { StyleSheet, Text, View, SafeAreaView, StatusBar, TouchableOpacity, ActivityIndicator, Image, FlatList, } from "react-native"; import axios from "axios"; import { ScrollView } from "react-native-gesture-handler"; export default function HomeScreen({ navigation }) { const [data, setData] = useState(); const [isLoading, setIsLoading] = useState(true); const fetchData = async () => { const response = await axios.get( "https://lereacteur-vinted-api.herokuapp.com/offers" ); setData(response.data); setIsLoading(false); }; useEffect(() => { fetchData(); }, []); return isLoading ? ( <ActivityIndicator size="large" color="#4AB1BA" margin={400} /> ) : ( <SafeAreaView style={styles.safeAreaView}> <FlatList data={data.offers} numColumns={2} renderItem={({ item }) => { return ( <TouchableOpacity style={styles.annonce} onPress={() => { navigation.navigate("Offre", { id: item._id, }); }} > <View style={styles.profil}> <Image source={ item.owner.account.avatar ? { uri: item.owner.account.avatar.secure_url, } : require("../assets/avatarVinted.png") } style={styles.avatar} /> <Text style={styles.details}> {item.owner.account.username} </Text> </View> <View style={styles.img}> <Image source={ item.product_pictures[0] ? { uri: item.product_pictures[0].secure_url, } : { uri: item.product_image.secure_url } } style={styles.picture} /> </View> <View style={styles.infos}> <Text style={styles.price}>{item.product_price} €</Text> <Text style={styles.details}> {item.product_details[0].MARQUE} </Text> <Text style={styles.details}> {item.product_details[1].TAILLE} </Text> </View> </TouchableOpacity> ); }} keyExtractor={(item) => item._id} /> </SafeAreaView> ); } const styles = StyleSheet.create({ safeAreaView: { flex: 1, backgroundColor: "white", paddingLeft: 10, paddingHorizontal: 10, }, annonce: { height: 360, width: 190, marginBottom: 10, marginRight: 10, }, profil: { height: 40, width: "100%", flexDirection: "row", alignItems: "center", }, avatar: { height: 25, width: 25, borderRadius: 15, marginHorizontal: 7, }, img: { height: 250, width: "100%", }, picture: { flex: 1, }, infos: { height: 70, width: "100%", justifyContent: "center", paddingLeft: 10, }, price: { fontSize: 14, fontWeight: "500", }, details: { fontSize: 12, color: "#838383", }, });