text
stringlengths
7
3.69M
import { logger, util } from '@citation-js/core' import wdk from 'wikidata-sdk' const QUERY_BUILDERS = { issn: { value: '?value wdt:P236 ?key', key: items => items.map(item => item.ISSN) }, orcid: { value: '?value wdt:P496 ?key', key: items => items.flatMap(item => (item.author || []).map(getOrcid)) }, language: { value: '?value wdt:P218 ?key', key: items => items.map(item => item.language) } } function unique (array) { return array.filter((value, index, array) => array.indexOf(value) === index) } function buildQuery (type, items) { const { key, value } = QUERY_BUILDERS[type] const keys = '"' + unique(key(items)).join('" "') + '"' return `{ VALUES ?key { ${keys} } . ${value} . BIND("${type}" AS ?cache) }` } export function getOrcid (author) { const orcid = author._orcid || author.ORCID || author._ORCID || author.orcid return orcid && orcid.replace(/^https?:\/\/orcid\.org\//, '') } export function fillCaches (csl) { // initialize caches const caches = {} for (const cache in QUERY_BUILDERS) { caches[cache] = {} } // fill caches const queries = Object.keys(QUERY_BUILDERS).map(type => buildQuery(type, csl)).join(' UNION ') const query = `SELECT ?key ?value ?cache WHERE { ${queries} }` try { const url = wdk.sparqlQuery(query) const response = JSON.parse(util.fetchFile(url)) const results = wdk.simplify.sparqlResults(response) for (const { key, value, cache } of results) { caches[cache][key] = value } } catch (e) { logger.error(e) } return caches }
const mongoose = require('mongoose'); var Form = mongoose.model('Form', { name:{ type: String, }, components: { type: String } }); module.exports = { Form };
import "./style.css"; import layout from "./layout.html"; import { getRaf } from "@app"; import clamp from "@utils/clamp"; import map from "@utils/map"; import { easeOutQuint } from "@utils/easing"; export default class Download { static selector = ".download"; constructor(block) { this.block = block; this.block.innerHTML = layout; } }
import "../../styles/login.css" import {Link} from "react-router-dom"; import { useState,useEffect} from "react"; import { useHistory } from "react-router-dom"; import axios from "axios"; import Loading from "../loading"; export default function Login(props){ let history = useHistory(); let [loading,setLoading]=useState(false); let [email,setEmail]=useState(""); let [pwd,setPwd]=useState(""); let [show,setShow]=useState(true); let [res,setRes]=useState(""); let [ins,setIns]=useState(""); useEffect(()=>{ let loginStatus = async()=>{ if(localStorage.getItem('userData')){ let userDetails = JSON.parse(localStorage.getItem('userData')); await axios.post("https://urlshortnerbe.herokuapp.com/users/authenticate",{ token:userDetails.token }) .then(async(response)=>{ console.log(response.data.auth); if(response.data.auth){ history.push("/dashboard") } }) .catch(error=>console.log(error)) } } loginStatus(); },[history]) let handleEvent = async()=>{ setRes(""); setLoading(true); //console.log(email,pwd); if(email && pwd){ await axios.post("https://urlshortnerbe.herokuapp.com/users/login",{ email:email, password:pwd }) .then(async(response)=>{ await setRes(response.data.message); await setIns(response.data.instruction); setTimeout(() => { localStorage.setItem('userData',JSON.stringify({email:email,token:response.data.token,firstname:response.data.firstname})); let url ="/dashboard"; if(response.data.token){ props.history.push({ pathname: url, state: { email:email, firstname:response.data.firstname, token:response.data.token } }); } }, 1000); setLoading(false); }).catch((error)=>{ console.log(error); }) } else{ setRes("Fields can not be empty") } } return <> <div className="login-wrapper"> <h1>Log in and start sharing</h1> <h4>Don't have an account? <Link to="/user/register" className="link">Sign up</Link></h4> <div className="form-wrapper"> <label>Email address or username</label><br/> <input type="email" onChange={(e)=>setEmail(e.target.value)} required={true}></input><br/> <div className="pass-wrapper"> <label className="pass">Password </label> <button className="showhide" onClick={()=>setShow(!show)}><i className="fas fa-eye"></i> Show</button> </div><br/> <input type={show?"password":"text"} onChange={(e)=>setPwd(e.target.value)} required={true}></input><br/> <Link to="/user/forgot-password" className="link">Forgot your password?</Link><br/> <button className="login" onClick={handleEvent}>Login</button> <div> {loading?<Loading/>:<></>} </div> <div style={{color:"green"}}>{res} {ins}</div> </div> </div> </> }
// server.js // BASE SETUP // ============================================================================= console.log("======================="); // call the packages we need var express = require('express'); var cors = require('cors'); var request = require('request'); var jsforce = require('jsforce'); var cloudinary = require('cloudinary'); var bodyParser = require("body-parser"); var spawn = require("child_process").spawn, child; var mongoose = require('mongoose'); var app = express(); var Bear = require('./models/bear'); // configure app to use bodyParser() // this will let us get the data from a POST app.use(bodyParser.urlencoded({ extended: false, limit: '5mb' })); // parse application/json app.use(bodyParser.json({ limit: '5mb' })); app.use(bodyParser.raw({ limit: '5mb' })); var port = process.env.PORT || 8083; // set our port // mongoose.connect('mongodb://node:node@novus.modulusmongo.net:27017/Iganiq8o'); console.log("Creating database..."); // const MongoClient = require('mongodb').MongoClient; mongoose.connect('mongodb://127.0.0.1:27017'); // connect to our database console.log("Database created."); var bear = new Bear(); bear.name = "TestBear"; // save the bear and check for errors bear.save(function(err) { if (err) console.log(err); // res.send(err); // res.json({ message: 'Bear created!' }); console.log("Bear created!"); }); // ROUTES FOR OUR API // ============================================================================= var router = express.Router(); // get an instance of the express Router // test route to make sure everything is working (accessed at GET http://localhost:8080/api) router.get('/', function(req, res) { res.json({ message: 'hooray! welcome to our api!' }); }); // more routes for our API will happen here // REGISTER OUR ROUTES ------------------------------- // all of our routes will be prefixed with /api app.use('/api', router); // START THE SERVER // ============================================================================= app.listen(port); console.log('Magic happens on port ' + port);
import React, {Component} from 'react'; import withStyles from "@material-ui/core/styles/withStyles"; import Typography from '@material-ui/core/Typography'; import TextField from '@material-ui/core/TextField'; import DialogContent from '@material-ui/core/DialogContent'; import DialogContentText from '@material-ui/core/DialogContentText'; import {styles} from './simpleQuestionStyles-material-ui'; class SimpleQuestion extends Component { render() { const {classes, title} = this.props; return ( <div className={classes.root}> <Typography style={{fontSize: '20px', margin: '15px 25px 0 0'}}> {title} </Typography> <form onSubmit={(event) => event.preventDefault()} onChange={(event) => this.props.changed(event, this.props.id, this.props.type, title)} className={classes.container}> <DialogContent> <DialogContentText> Введите ответ на вопрос </DialogContentText> <TextField required margin="dense" type="text" fullWidth value={this.props.value} /> </DialogContent> </form> </div> ) } } export default withStyles(styles)(SimpleQuestion);
import {useForm} from "react-hook-form"; import s from "../FilterCharacters/filter.module.css" const FilterLocations = ({ filter }) => { const { register, handleSubmit } = useForm(); return ( <div> <form id='form' onChange={ handleSubmit(filter) }> <div className="form-group w-auto"> <input type="text" className="form-control" name='name' ref={ register } aria-describedby="emailHelp" placeholder="Enter episode name ..."/> </div> <div> <label className={ s.label } htmlFor="type"> Type </label> <select className={ s.select } name="type" id="type" ref={register} onChange={ handleSubmit(filter) } > <option value="all">All</option> <option value="Planet">Planet</option> <option value="Fantasy town">Fantasy town</option> <option value="Dream">Dream</option> <option value="Cluster">Cluster</option> <option value="Space station">Space station</option> <option value="unknown">Unknown</option> </select> <label className={s.label} htmlFor="dimension"> Dimension </label> <select className={s.select} name="dimension" id="dimension" ref={ register } onChange={ handleSubmit(filter) } > <option value="all">All</option> <option value="Dimension C-137">Dimension C-137</option> <option value="Post-Apocalyptic Dimension">Post-Apocalyptic Dimension</option> <option value="Cronenberg Dimension">Cronenberg Dimension</option> <option value="Fantasy Dimension">Fantasy Dimension</option> <option value="Replacement Dimension">Replacement Dimension</option> <option value="Replacement Dimension">Replacement Dimension</option> <option value="Dimension K-83">Dimension K-83</option> <option value="unknown">Unknown</option> </select> </div> </form> </div> ) } export default FilterLocations;
var tokki = angular.module('services').service('calculationService', function(){ return{ customSum: function(data, key){ if (typeof (data) === 'undefined' && typeof (key) === 'undefined') { return 0; } var sum = 0; for (var i = 0; i < data.length; i++) { sum = sum + data[i][key]; } return sum; }, deudas: function(deudas, pagos){ var copy = angular.copy(deudas); deudasLength = deudas.length; pagosLength = pagos.length; for (var x=0; x<deudasLength; x++){ for(var z=0; z<pagosLength; z++){ if(copy[x].dte == pagos[z].dte && copy[x].id == pagos[z].folio_id && pagos[z].tipo == "pago"){ copy[x].total += pagos[z].monto; } } } return copy; } } });
const mongoose = require('mongoose') mongoose.connect(process.env.MONGO_URI, { 'useNewUrlParser': true, 'useFindAndModify': false, 'useUnifiedTopology': true, 'useCreateIndex': true }, (err) => { if (err) return console.log(err) console.log('[mongoose service ... OK]') }) // const MongoClient = require('mongodb').MongoClient; // const uri = process.env.MONGO_URI; // const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); // client.connect(err => { // const collection = client.db("Account").collection("devices"); // // perform actions on the collection object // client.close(); // });
import React from 'react'; import renderer from 'react-test-renderer'; import Adapter from 'enzyme-adapter-react-16'; import {configure, mount, shallow} from 'enzyme'; import {MemoryRouter} from 'react-router-dom'; import toJson from 'enzyme-to-json'; import {Provider} from 'react-redux'; import configureStore from 'redux-mock-store'; configure({adapter: new Adapter()}); import {images} from 'constants/Images'; import CreateEdit from './'; const media = { uid: '5F59D81F-C089-2397-8CD7-247C1E23B191', url: 'https://podcast.ustudio.com/show/5F59D81F-C089-2397-8CD7-247C1E23B191', title: 'Lorem ipsum dolor', description: 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut tincidunt vehicula', show_uid: '0CCBBCD9-1BE5-471B-2738-B5DB1DC2B642', image_url: '/assets/media/show_thumb_2.png', show_url: '/show/0CCBBCD9-1BE5-471B-2738-B5DB1DC2B642', published_at: '1510014877', duration: 42537063, source: { filename: 'IMG_2116.MOV', src: 'https://podcast.ustudio.com/media/IMG_2116.MOV', size: 130023424, published_at: 1525269660 } }; describe('Create Edit Component', () => { const initialState = { notifications: [] }; const mockStore = configureStore(); it('should render the component correctly', () => { const handleSubmitMockFn = jest.fn(); const deleteMockFn = jest.fn(); const cancelMockFn = jest.fn(); const wrapper = shallow( <CreateEdit attachment={media.source} name={media.name} namePlaceholder="Media Name" desciption={media.description} descriptionPlaceholder="Add a brief description about this media..." keywords={media.keywords} keywordsPlaceholder='Add keywords separated by commas...' notes={media.internal_notes} notesPlaceholder='Add a note...' thumbnail={media.image_url} handleSubmit={handleSubmitMockFn} onDelete={deleteMockFn} onCancel={cancelMockFn} handleInputChange={jest.fn()} /> ); expect(toJson(wrapper)).toMatchSnapshot(); }); it('should call handle submit prop on form submit', () => { const store = mockStore(initialState); const handleSubmitMockFn = jest.fn(); const wrapper = mount(<Provider store={store}> <CreateEdit handleInputChange={jest.fn()} handleSubmit={handleSubmitMockFn} /> </Provider>); wrapper.find('form').simulate('submit'); expect(handleSubmitMockFn).not.toHaveBeenCalled(); const wrapperNew = mount(<Provider store={store}> <CreateEdit handleInputChange={jest.fn()} handleSubmit={handleSubmitMockFn} name={"name"} thumbnail={"thumbnail"} /> </Provider>); wrapperNew.find('form').simulate('submit'); expect(handleSubmitMockFn).toHaveBeenCalled(); }); it('should call onDelete prop on clicking Delete button', () => { const store = mockStore(initialState); const onDeleteMockFn = jest.fn(); const wrapper = mount(<Provider store={store}> <CreateEdit handleInputChange={jest.fn()} handleSubmit={jest.fn()} onDelete={onDeleteMockFn} /> </Provider>); wrapper.find('a.default-link').simulate('click'); expect(onDeleteMockFn).toHaveBeenCalled(); }); it('should call onCancel prop on clicking Cancel button', () => { const store = mockStore(initialState); const onClickMockFn = jest.fn(); const wrapper = mount(<Provider store={store}> <CreateEdit handleInputChange={jest.fn()} handleSubmit={jest.fn()} onCancel={onClickMockFn} /> </Provider>); wrapper.find('button.cancelBtn').simulate('click'); expect(onClickMockFn).toHaveBeenCalled(); }); });
describe('P.views.ReportsMonthlyLayout', function() { var View = P.views.ReportsMonthlyLayout; var Model = P.models.workouts.Report; var noop = function() {}; describe('date change', function() { beforeEach(function() { spyOn(Model.prototype, 'pFetch').and.returnValue(new Promise(noop)); this.model = new Model(); this.view = new View({ model: this.model, userID: 'foo' }); }); it('should disable the links to change dates', function() { this.view.date = moment('2015-05-01', 'YYYY-MM-DD'); this.view.render(); expect(this.view.$('.js-period-after').is('.disabled')) .toBe(true); expect(this.view.$('.js-period-before').is('.disabled')) .toBe(true); }); }); });
import React from 'react'; import Button from 'react-bootstrap/Button'; import Container from 'react-bootstrap/Container'; import Row from 'react-bootstrap/Row'; import Col from 'react-bootstrap/Col'; import Navbar from 'react-bootstrap/Navbar'; // Header import { Header } from '..' // Images import BannerBg from '../../public/images/bg-banner.png'; import ImgLogo from '../../public/images/img-logo.svg'; import IconPngJpg from '../../public/images/icon-png-jpg.svg'; import IconSvg from '../../public/images/icon-svg.svg'; import IconCss from '../../public/images/icon-css.svg'; // icon import { FiMenu, FiLinkedin, FiTwitter, FiShare, FiShare2, FiPenTool, FiSearch, FiMail, FiGithub, FiYoutube } from "react-icons/fi"; // link import Link from "next/link"; // Styled Component import styled from "styled-components"; // LandingBanner const LandingBanner = styled.section` position: relative; display: flex; justify-content: center; align-items: center; min-height: 100vh; background-color: var(--color-brand); background: rgb(93,33,210); background: linear-gradient(180deg, rgba(93,33,210,1) 0%, rgba(175,33,210,1) 100%); // background-image: url(${BannerBg}); background-position: center center; background-repeat: no-repeat; background-size: cover; &:before { position: absolute; content: ""; top: 0; left: 0; right: 0; bottom: 0; background-image: url(${BannerBg}); background-position: center center; background-repeat: no-repeat; background-size: cover; } `; const BannerHeader = styled(Navbar)` padding: 1rem 1.8rem !important; background-color: rgba(var(--color-brand-rgb), 0.86); .navbar-toggler:hover, .navbar-toggler:focus { background-color: rgba(var(--color-neutral-10-rgb), 0.2); } .navbar-toggler.active, .navbar-toggler:active { background-color: rgba(var(--color-neutral-100-rgb), 0.2); } .navbar-action--primary { padding: 0.48rem 1.4rem; border: solid 1px var(--color-primary-accent); background-color: var(--color-primary-accent); font-size: var(--fs-rg); font-weight: var(--fw-bold); color: var(--color-neutral-90); svg { margin: -2px 0.6rem 0 0; } &:hover, &:focus { border: solid 1px var(--color-neutral-10); background-color: var(--color-neutral-10); color: var(--color-brand); } &:active { background-color: rgba(var(--color-neutral-10-rgb), 90%) !important; color: var(--color-brand) !important; } } `; const BannerBody = styled.div` margin-top: -74px; .banner-title { font-size: var(--fs-xl); font-weight: var(--fw-bold); color: var(--color-neutral-10); @media (max-width: 767px) { font-size: var(--fs-lg); } } .banner-desc { margin: 1.2rem 2rem 2.6rem 0; font-size: var(--fs-md); font-weight: var(--fw-light); color: var(--color-neutral-10); @media (max-width: 767px) { font-size: var(--fs-rg); } } `; const BannerBodyActions = styled.div` display: flex; justify-content: center; grid-gap: 1rem; .banner-action--primary { padding: 0.8rem 1.4rem; border: solid 1px var(--color-primary-accent); background-color: var(--color-primary-accent); font-weight: var(--fw-bold); color: var(--color-neutral-90); svg { margin: -2px 0.6rem 0 0; } &:hover, &:focus { border: solid 1px var(--color-neutral-10); background-color: var(--color-neutral-10); color: var(--color-brand); } &:active { background-color: rgba(var(--color-neutral-10-rgb), 90%) !important; color: var(--color-brand) !important; } } .banner-action--secondary { padding: 0.8rem 1.4rem; border: solid 1px var(--color-primary-accent); background-color: transparent; color: var(--color-primary-accent); font-weight: var(--fw-bold); svg { margin: -2px 0.6rem 0 0; } &:hover, &:focus { border: solid 1px var(--color-neutral-10); background-color: transparent; color: var(--color-neutral-10); } &:active { border: solid 1px var(--color-neutral-10) !important; background-color: rgba(var(--color-neutral-10-rgb), 20%) !important; color: var(--color-neutral-10) !important; } } `; const Logo = styled.h1` width: 152px; height: 32px; background: url(${ImgLogo}) left center no-repeat; margin: 0; line-height: 1; `; const Navigation = styled.div` display: flex; flex-direction: row; align-items: center; grid-gap: 2.4rem; margin-right: 2.4rem; a { font-size: var(--fs-rg); font-weight: var(--fw-semibold); color: var(--color-neutral-10) !important; &:hover { text-decoration: none; color: var(--color-primary-accent) !important; } } @media (max-width: 767px) { border-top: solid 1px rgba(var(--color-neutral-10-rgb), 0.2); margin: 0.4rem 0 0.8rem 0; padding-top: 1rem; flex-direction: column; grid-gap: 0.6rem; } `; const ActionBar = styled.div` @media (max-width: 768px) { display: flex; button { flex: 1; } } `; const SectionAbout = styled.section` padding: 6rem 0; `; const SectionTitle = styled.div` display: flex; justify-content: center; `; const SectionFileTypes = styled.section` padding: 6rem 0; // background-color: var(--color-neutral-20); background-color: rgba(var(--color-brand-rgb), 0.024); `; const SectionContact = styled.section` padding: 6rem 0; background-color: var(--color-neutral-10); `; const SectionContactCredits = styled.p` margin: 1rem 0; color: var(--color-neutral-80); a { color: var(--color-brand); text-decoration: underline; &:hover, &:focus { color: var(--color-brand-secondary); } } `; const SocialLinks = styled.div` display: flex; justify-content: center; grid-gap: 1.6rem; a { display: flex; justify-content: center; align-items: center; width: 3rem; height: 3rem; border-radius: 50%; background-color: rgba(var(--color-brand-rgb), 0.06); svg { stroke: var(--color-brand); } &:hover, &:focus { background-color: var(--color-brand); svg { stroke: var(--color-neutral-10); } } } `; // Feature Cards const FeatureCards = styled.div` display: grid; grid-template-columns: repeat(3, minmax(240px, 1fr)); grid-gap: 2.6rem; margin: 4rem 0 0 0; @media (max-width: 991px) { grid-template-columns: repeat(2, minmax(240px, 1fr)); } @media (max-width: 767px) { grid-template-columns: repeat(1, minmax(240px, 1fr)); } `; const FeatureCardItem = styled.div` display: flex; flex-direction: column; align-items: center; background: rgba(var(--color-brand-rgb), 0.05); border-radius: 1rem; padding: 3.2rem 2.8rem; .icon { display: flex; align-items: center; justify-content: center; width: 8rem; height: 8rem; border-radius: 50%; background-color: rgba(var(--color-neutral-10-rgb), 1); box-shadow: 3px 16px 32px 0 rgba(var(--color-brand-rgb), 16%); } .card-title { margin: 2rem 0 1rem 0; font-size: var(--fs-md); font-weight: var(--fw-bold); } .card-desc { margin: 0; font-size: var(--fs-rg); text-align: center; } &:nth-child(2n) { background: rgba(var(--color-brand-secondary-rgb), 0.05); .icon { box-shadow: 3px 16px 32px 0 rgba(var(--color-brand-secondary-rgb), 16%); } } &:nth-child(3n) { background: rgba(var(--color-brand-teritiary-rgb), 0.05); .icon { box-shadow: 3px 16px 32px 0 rgba(var(--color-brand-teritiary-rgb), 16%); } } `; // Feature Icon Cards const FileSupportCards = styled.div` display: grid; grid-template-columns: repeat(3, minmax(240px, 1fr)); grid-gap: 2.6rem; margin: 4rem 0 0 0; @media (max-width: 991px) { grid-template-columns: repeat(2, minmax(240px, 1fr)); } @media (max-width: 767px) { grid-template-columns: repeat(1, minmax(240px, 1fr)); } `; const FileSupportCardItem = styled.div` display: flex; flex-direction: column; align-items: center; background: var(--color-neutral-10); border-radius: 1rem; padding: 3.2rem 2.8rem; box-shadow: 3px 33px 81px 0 rgb(111 118 138 / 16%); .card-icon { display: flex; justify-content: center; align-items: center; border-radius: 50%; background-color: rgba(var(--color-brand-rgb), 1); width: 8rem; height: 8rem; img { width: 4.2rem; height: 4.2rem; } } .card-title { margin: 2rem 0 1rem 0; font-size: var(--fs-md); font-weight: var(--fw-bold); } .card-desc { margin: 0; font-size: var(--fs-rg); text-align: center; } // Color Variants &:nth-child(2n) .card-icon { background: rgba(var(--color-brand-secondary-rgb), 1); } &:nth-child(3n) .card-icon { background: rgba(var(--color-brand-teritiary-rgb), 1); } `; const Landing = ({ setOpen, user, setUser }) => { return( <div> <BannerHeader fixed="top" expand="md"> <Navbar.Brand><Logo><div className="sr-only">TryShape</div></Logo></Navbar.Brand> <Navbar.Toggle> <FiMenu color="var(--color-neutral-10" size="24px"/> </Navbar.Toggle> <Navbar.Collapse className="justify-content-end"> <Navigation> <a data-scroll href="#keyfeatures">Key Features</a> <a data-scroll href="#filesupport">File Support</a> <a data-scroll href="#contact">Contact</a> </Navigation> <ActionBar> <Link href="/app"> <Button className="navbar-action--primary"> <FiSearch />Browse Now </Button> </Link> </ActionBar> </Navbar.Collapse> </BannerHeader> <LandingBanner> <BannerBody> <Container> <Row className="justify-content-md-center"> <Col lg="8" className="d-flex flex-column justify-content-center"> <h2 className="banner-title text-center">Create, Export, Share, and Use any Shapes of your choice.</h2> <p className="banner-desc text-center"> TryShape is an opensource platform to create shapes of your choice using a simple, easy-to-use interface. You can create banners, circles, polygonal shapes, export them as SVG, PNG, and even as CSS. </p> <BannerBodyActions> <Link href="/app" ><Button variant="primary"><FiPenTool/>Try Now</Button></Link> <a href="https://github.com/TryShape" target="_blank" className="btn btn-outline-secondary" rel="noopener noreferrer"><FiGithub />GitHub</a> </BannerBodyActions> </Col> </Row> </Container> </BannerBody> </LandingBanner> <SectionAbout id="keyfeatures"> <Container> <SectionTitle> <h2 className="section-title text-center">Key Features</h2> </SectionTitle> <p className="p-lead text-center">TryShape is here to take care of your customized shape needs</p> <p className="p-desc text-center w-75 m-auto"> The modern website and web application designs need shapes of random dimensions, colors, and creativity. It is too much for our brains to remember CSS clip-path rules to define shapes. Let's create, share, export shapes in a minute using TryShape. </p> <FeatureCards> <FeatureCardItem> <div className="icon"> <FiPenTool size='64px' color="var(--color-brand)"/> </div> <h3 className="card-title">Create</h3> <p className="card-desc"> Make your creative thoughts a reality with a few clicks. You can create any circular, elliptical, and polygonal shape within a minute time. </p> </FeatureCardItem> <FeatureCardItem> <div className="icon"> <FiShare size='64px' color="var(--color-brand-secondary)"/> </div> <h3 className="card-title">Export</h3> <p className="card-desc"> Export the shapes as images and CSS snippets. You can export the shapes as SVG, PNG, JPEG, and CSS. </p> </FeatureCardItem> <FeatureCardItem> <div className="icon"> <FiShare2 size='64px' color="var(--color-brand-teritiary)"/> </div> <h3 className="card-title">Share</h3> <p className="card-desc"> When you create something fabously great, do share it with the awesome developer community. TryShape allows you to do that when you make your ceativity public. </p> </FeatureCardItem> </FeatureCards> </Container> </SectionAbout> <SectionFileTypes id="filesupport"> <Container> <SectionTitle> <h2 className="section-title text-center">Great Export type Support</h2> </SectionTitle> <p className="p-lead text-center">Hassle free usage for your web design and development!</p> <p className="p-desc text-center w-75 m-auto"> TryShape supports exporting shapes as images, CSS snippets, and SVG. You can export them specifying any dimension, color, name of your choice. </p> <FileSupportCards> <FileSupportCardItem> <div className="card-icon"> <img src={IconSvg} /> </div> <h3 className="card-title">SVG</h3> <p className="card-desc"> Export and save your shape as the Scalable Vector Graphics(SVG) file. It gives you the power to use the SVG image straight into your application. </p> </FileSupportCardItem> <FileSupportCardItem> <div className="card-icon"> <img src={IconPngJpg} /> </div> <h3 className="card-title">PNG and JPEG</h3> <p className="card-desc"> PNG and JPEG types are the most used image types in web applications. Export your shapes as .png and .jpeg image files. </p> </FileSupportCardItem> <FileSupportCardItem> <div className="card-icon"> <img src={IconCss} /> </div> <h3 className="card-title">CSS Snippet</h3> <p className="card-desc"> Don't want to image the shapes as files? No problem. You can create CSS snippets with your shapes and export that instead. </p> </FileSupportCardItem> </FileSupportCards> </Container> </SectionFileTypes> <SectionContact id="contact"> <Container> <SocialLinks> <a href="https://github.com/TryShape" target="_blank" rel="noopener noreferrer"><FiGithub /></a> <a href="https://twitter.com/tapasadhikary" target="_blank" rel="noopener noreferrer"><FiTwitter /></a> <a href="https://www.linkedin.com/in/tapasadhikary/" target="_blank" rel="noopener noreferrer"><FiLinkedin /></a> <a href="https://www.youtube.com/c/TapasAdhikary/featured" rel="noopener noreferrer"><FiYoutube /></a> <a href="mailto:tapas.adhikary@gmail.com" rel="noopener noreferrer"><FiMail /></a> </SocialLinks> <SectionContactCredits className="text-center"><small>TryShape is an opensource project developed by <a href="https://tapasadhikary.com/" target="_blank">Tapas Adhikary</a> and friends.</small></SectionContactCredits> </Container> </SectionContact> </div> ) }; export default Landing;
var game = new Phaser.Game(500, 400, Phaser.AUTO, ''); var PhaserGame = function() { this.bmd = null; this.bad = null; this.points = { 'x': [ -50, 128, 256, 384, 450, 550 ], 'y': [ 240, 240, 240, 240, 240, 240 ] }; this.pi = 0; this.path = []; }; PhaserGame.prototype = { init() { this.stage.backgroundColor = '#000'; }, preload() { this.load.image('bad', 'assets/bad.png'); this.load.image('tower', 'assets/tower.png'); this.load.image('ground', 'assets/ground.jpg'); }, create() { this.add.sprite(0, 0, 'ground'); this.bmd = this.add.bitmapData(this.game.width, this.game.height); this.bmd.addToWorld(); var py = this.points.y; for (var i = 0; i < py.length; i++) { py[i] = this.rnd.between(32, 432); } this.plot(); this.bad = this.add.sprite(0, 0, 'bad'); this.bad.anchor.set(0.5); this.turrets = this.add.group(); this.input.onDown.add(this.addTurret, this); }, addTurret(event) { console.log(event) this.turrets.create(event.x - 50, event.y - 50, 'tower'); }, update() { this.bad.x = this.path[this.pi].x; this.bad.y = this.path[this.pi].y; this.bad.rotation = this.path[this.pi].angle; this.pi++; if (this.pi >= this.path.length) { this.pi = 0; } }, plot() { this.bmd.clear(); var x = 1 / game.width; var ix = 0; for (var i = 0; i <= 1; i += x) { var px = this.math.bezierInterpolation(this.points.x, i); var py = this.math.bezierInterpolation(this.points.y, i); this.bmd.rect(px, py, 1, 1, 'rgba(255, 255, 255, 1)'); var node = { x: px, y: py, angle: 0 }; if (ix > 0) { node.angle = this.math.angleBetweenPoints(this.path[ix - 1], node); } this.path.push(node); ix += 1 } } }; game.state.add('Game', PhaserGame, true);
import React from "react"; import { BrowserRouter as Router, Switch, Route } from "react-router-dom"; import StartLoader from "./components/startLoader"; import Quiz from "./components/quiz" import Score from "./components/score" import { makeStyles } from "@material-ui/core"; const useStyles = makeStyles({ header: { width: "100%", height: "20%", fontSize: "30px", fontWeight: 700, display: "flex", alignItems:"center", justifyContent:"center", color: "#3f51b5", fontFamily:"Roboto" }, body: { width: "100%", height: "75%", overflowY:"auto" } }); function App() { const classes = useStyles(); return [ <div className={classes.header}>Quiz Portal</div>, <div className={classes.body}> <Router> <Switch> <Route path="/quiz"> <Quiz /> </Route> <Route path="/score"> <Score /> </Route> <Route path="/"> <StartLoader /> </Route> </Switch> </Router> </div> ] } export default App;
DrunkCupid.Views.Profile = Backbone.CompositeView.extend({ template: JST['profile'], className: 'main-container', events: { "submit form": "sendPhoto", "click .p-close": "exitForm" }, exitForm: function (e) { e.preventDefault(); $('.p-modal-screen').removeClass('is-open'); $('.p-modal-form').removeClass('is-open') }, addPhoto: function (e) { e.preventDefault(); $('.p-modal-screen').addClass('is-open'); $('.p-modal-form').addClass('is-open') }, sendPhoto: function (e) { e.preventDefault(); var file = this.$("#input-image")[0].files[0]; var formData = new FormData(); formData.append('photo[profilepic]', file); var that = this; this.photoModel.saveFormData(formData, { success: function (mod) { this.allPhotos.add(this.photoModel) this.model.set({image_url: mod.attributes.image_url}) // Backbone.history.navigate("/#/profile", {trigger: true}); }.bind(this) }); $('.p-modal-screen').removeClass('is-open'); $('.p-modal-form').removeClass('is-open'); }, initialize: function (options) { this.allPhotos = options.allPhotos; this.allQuestions = options.allQuestions; this.allResponses = options.allResponses; this.photoModel = options.photoModel; this.addSubs(); }, render: function () { var content = this.template(); this.$el.html(content); this.attachSubviews(); return this; }, addSubs: function () { this.subviews('.profile-container').each(function(sub) { sub.remove(); }); var profTopView = new DrunkCupid.Views.ProfileTop({model: this.model}); this.addSubview('.profile-container', profTopView); var profMonolith = new DrunkCupid.Views.ProfileMonolith({model: this.model}); this.addSubview('.profile-container', profMonolith); var photosView = new DrunkCupid.Views.AllPhotos({collection: this.allPhotos}); this.addSubview('.profile-container', photosView); if (this.model.id === DrunkCupid.CurrentUser.id) { var questionsView = new DrunkCupid.Views.AllQuestions({ collection: this.allQuestions, allResponses: this.allResponses }); this.addSubview('.profile-container', questionsView); } else { var twoOfUs = new DrunkCupid.Collections.TwoOfUs([], {withId: this.model.id}); twoOfUs.fetch({reset: true}); var twoOfUsView = new DrunkCupid.Views.TwoOfUs({ collection: twoOfUs, model: this.model }); this.addSubview('.profile-container', twoOfUsView); }; } })
// 公共地址 export const baseNetUrl = 'http://106.75.49.216:1337'; export const baseLocaleUrl = 'http://localhost:1337';
// import functions import { formattedDate, tripDays } from "./utils"; // callback for click listener function performAction() { // access values from user const destinationCity = document.getElementById("destinationCity").value; const destinationCountry = document.getElementById("destinationCountry").value; const startDate = document.getElementById("tripDateFrom").value; const finishDate = document.getElementById("tripDateTo").value; if (!destinationCity || !destinationCountry || !startDate || !finishDate) { alert("Please fill all the fields"); return; } // chaining promises postData("/api/journal", { city: destinationCity, country: destinationCountry, startDate, finishDate, tripDays: tripDays(startDate, finishDate), }).then(updateErase); } // dynamic UI update const updateUI = (entry) => { createContainer(entry); document.getElementById(`startDate-${entry.id}`).innerHTML = "<b>From: </b>" + entry.startDate; document.getElementById(`finishDate-${entry.id}`).innerHTML = "<b>To: </b>" + entry.finishDate; document.getElementById(`city-${entry.id}`).innerHTML = `<h5>${entry.city.toUpperCase()}</h5>`; document.getElementById(`tripDays-${entry.id}`).innerHTML = "<b>Duration: </b>" + entry.tripDays + " day(s)"; document.getElementById(`maxTemp-${entry.id}`).innerHTML = "<b>Max Temp: </b>" + entry.maxTemp + "ºC"; document.getElementById(`minTemp-${entry.id}`).innerHTML = "<b>Min Temp: </b>" + entry.minTemp + "ºC"; document.getElementById(`img-${entry.id}`).setAttribute("src", entry.img); }; // creates new html dynamically function createContainer(entry) { const container = document.createElement("li"); container.setAttribute("class", "card horizontal"); const cardImg = document.createElement("div"); cardImg.setAttribute("class", "card-image avatar-holder"); const cardContent = document.createElement("div"); cardContent.setAttribute("class", "card-content"); for (let key in entry) { if (key != "id" && key != "img") { let el = document.createElement("div"); el.setAttribute("id", `${key}-${entry.id}`); cardContent.appendChild(el); } if (key === "img") { let el = document.createElement("img"); el.setAttribute("id", `${key}-${entry.id}`) el.setAttribute("class", "city-avatar"); cardImg.appendChild(el); } } container.appendChild(cardImg); container.appendChild(cardContent); document.getElementById("entryHolder").appendChild(container); } function updateErase(entry) { updateUI(entry); document.getElementById("destinationCity").value = ""; document.getElementById("destinationCountry").value = ""; document.getElementById("tripDateFrom").value = ""; document.getElementById("tripDateTo").value = ""; } // post data const postData = async (url = "", data = {}) => { const response = await fetch(url, { method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json", }, body: JSON.stringify(data), }); try { const newData = await response.json(); return newData; } catch (error) { console.log(error); alert(error); } }; export default performAction; export { formattedDate };
import React, { Component } from "react"; import { Breadcrumb, Card } from "antd"; import contactList from "./data/contactList"; import Accountlist from "components/Accounts/Accountlist"; class FullList extends Component { constructor() { super(); this.state = { noContentFoundMessage: 'No Contact found in selected folder', contactList: contactList } } render() { const {contactList, noContentFoundMessage } = this.state; return ( <div className="gx-main-content"> <div className="gx-app-module"> <div className="gx-module-account-list"> <div className="gx-module-box-content"> <Card className="gx-card" title="Account Full List" style={{marginBottom: 0, borderRadius: 0 }}> <Breadcrumb> <Breadcrumb.Item>Home</Breadcrumb.Item> <Breadcrumb.Item><span className="gx-link">Accounts</span></Breadcrumb.Item> <Breadcrumb.Item>Accounts Full List</Breadcrumb.Item> </Breadcrumb> </Card> {contactList.length === 0 ? <div className="gx-h-100 gx-d-flex gx-align-items-center gx-justify-content-center"> {noContentFoundMessage} </div> : <Accountlist contactList={contactList} /> } </div> </div> </div> </div> ) } } export default FullList;
import * as f from '@kuba/f' import h, { render } from '@kuba/h' export default (strings, ...expressions) => { const textContent = f.zip(strings, expressions).flat(Infinity).join('').replace(/[\n ]+/g, ' ').trim() render( document.head, <style>{textContent}</style> ) }
import { eventBus } from '../../../service/eventBus'; export class ViewSettings { constructor() { this.settingsContainer = document.querySelector('.settings-container-js'); this.settingsBtn = document.querySelector('.settings-btn-js'); this.propsTitle = document.querySelector('.props-title-js'); this.propsList = document.querySelector('.list-js'); this.categoriesContainer = document.querySelector('.categories-js'); this.tagsInput = null; this.errorMes = ''; } initEvents() { document.addEventListener('click', e => { if ( !e.target.classList.contains('settings-btn-js') && !e.target.closest('.settings-container-js') ) { this.closeContainer(); } }); } renderProps(elems, tags) { this.propsTitle.textContent = elems.title; let isInput = false; let isGit = false; let addText = ''; let template = ''; elems.props.forEach(elem => { template += `<li class="list-item ${elem.checked ? 'checked' : ''}" id="${ elem.id }">${elem.text}<span class="toggle-slider ${ elem.checked ? 'toggle-slider-active' : '' }"></span></li>`; if (elem.checked && elem.id === 'img-git') { isGit = true; } if (elem.tags) { isInput = true; addText = elem.addText; this.errorMes = elem.errorMes; } }); if (isInput) { template += `<p class="settings-addtext settings-addtext-js ${ isGit ? 'hidden' : '' }">${addText}</p> <p class="message message-js hidden">${this.errorMes}</p> <input class="tags tags-js" maxlength="15" type="text" ${ isGit ? 'disabled' : '' } value="${tags.join(' ')}">`; } this.propsList.innerHTML = template; this.setUpInput(); } setUpInput() { this.tagsInput = document.querySelector('.tags-js'); if (!this.tagsInput) { return; } this.tagsInput.addEventListener('change', () => { if (this.isValidTags(this.tagsInput.value)) { const currTags = this.tagsInput.value.split(' '); eventBus.post('add-tags', currTags); } else { this.showInvalidMessage(); } }); this.tagsInput.addEventListener('input', () => { this.removeInvalidMessage(); }); } isValidTags(tags) { const regex = /^[a-zA-Z\s,]*$/; return regex.test(tags); } showInvalidMessage() { this.tagsInput.classList.add('invalid'); const messageContainer = document.querySelector('.message-js'); messageContainer.textContent = this.errorMes; messageContainer.classList.remove('hidden'); } removeInvalidMessage() { this.tagsInput.classList.remove('invalid'); document.querySelector('.message-js').classList.add('hidden'); } renderCategories(elems) { const categories = document.querySelectorAll('.categories-item-js'); elems.forEach((elem, index) => { categories[index].textContent = elem; }); } toggleContainer() { this.settingsContainer.classList.toggle('open'); this.settingsContainer.classList.toggle('closed'); } toggleBtn() { this.settingsBtn.classList.toggle('active-btn'); } closeContainer() { this.settingsContainer.classList.remove('open'); this.settingsContainer.classList.add('closed'); } toggleCategories(itemClicked) { const items = document.querySelectorAll('.categories-item-js'); items.forEach(item => item.classList.remove('active')); itemClicked.classList.add('active'); } toggleProps(id) { const input = document.querySelector('.tags-js'); if (input && id !== 'img-git') { document.querySelector('.settings-addtext-js').classList.remove('hidden'); input.removeAttribute('disabled'); } else if (input) { document.querySelector('.settings-addtext-js').classList.add('hidden'); input.setAttribute('disabled', ''); } const currentElem = document.getElementById(id).firstElementChild; const items = document.querySelectorAll('.toggle-slider'); items.forEach(item => item.classList.remove('toggle-slider-active')); currentElem.classList.add('toggle-slider-active'); } toggleBlock(id) { const item = document.getElementById(id); item.classList.toggle('checked'); item.firstElementChild.classList.toggle('toggle-slider-active'); } renderNoResultsError(data) { const messageContainer = document.querySelector('.message-js'); messageContainer.textContent = data.noResultsError; messageContainer.classList.remove('hidden'); } }
import React, { useState, useEffect } from 'react' import { useParams } from 'react-router-dom' import Axios from 'axios' export default function ShowUser() { const [user, setUser] = useState([]) const { identifier } = useParams() const getUser = async () => { try { const response = await Axios.get(`https://jsonplaceholder.typicode.com/users/${identifier}`) setUser(response.data) } catch (e) { console.log(e.message) } } useEffect(() => { getUser() }, [identifier]) return ( <div className="container"> <div className="card"> <div className="card-header">{user.name}</div> <div className="card-body">{user.username}</div> <div className="card-body">{user.phone}</div> <div className="card-body">{user.website}</div> <div className="card-body">{user.email}</div> </div> </div> ) }
const { environment } = require('@rails/webpacker') // resolving $ function is not found from view const webpack = require('webpack') environment.plugins.append('Provide', new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery', Popper: ['popper.js', 'default'] }) ) // END resolving module.exports = environment
const db = wx.cloud.database(); const admin = db.collection('shiwuzhaoling'); Page({ /** * 页面的初始数据 */ data: { a:'-->', ppp:[], ne:[], activeId: 0, list: [{ id: 0, title: "思源楼" }, { id: 1, title: "知行楼" }, { id: 2, title: "通方楼" }, { id: 3, title: "天佑" }, { id: 4, title: "图书馆" }, { id: 5, title: "一期生活服务区" }, { id: 6, title: "一期食堂" }, { id: 7, title: "二期食堂" }, { id: 8, title: "操场" }, { id: 9, title: "宿舍楼附近" }, { id: 10, title: "旧实验楼" }, { id: 11, title: "新实验楼" }, { id: 12, title: "教工食堂" }, { id: 13, title: "大学生活动中心" }, { id: 14, title: "行政楼" }, { id: 15, title: "其它" }], TabCur:0, MainCur:0, VerticalNavTop:0, load: true, img: "https://gd4.alicdn.com/imgextra/i2/2522860159/TB2KwijesaK.eBjSspjXXXL.XXa_!!2522860159.jpg", ne:[] }, VerticalMain(e) { let that = this; let list = this.data.list; let tabHeight = 0; if (this.data.load) { for (let i = 0; i < list.length; i++) { let view = wx.createSelectorQuery().select("#main-" + list[i].id); view.fields({ size: true }, data => { list[i].top = tabHeight; tabHeight = tabHeight + data.height; list[i].bottom = tabHeight; }).exec(); } that.setData({ load: false, list: list }) } let scrollTop = e.detail.scrollTop + 20; for (let i = 0; i < list.length; i++) { if (scrollTop > list[i].top && scrollTop < list[i].bottom) { that.setData({ VerticalNavTop: (list[i].id - 1) * 50, TabCur: list[i].id }) return false } } }, tabSelect(e) { console.log(e.currentTarget.dataset.id); this.setData({ TabCur: e.currentTarget.dataset.id, MainCur: e.currentTarget.dataset.id, VerticalNavTop: (e.currentTarget.dataset.id - 1) * 50 }) }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { var that = this; var ne = []; var list = that.data.list; var listItem = []; wx.showLoading({ title: '加载中', }) wx.cloud.callFunction({ name:'findLost', success(res){ console.log(res.result.data) for(var i = 0; i < res.result.data.length; i++){ if(res.result.data[i].shenhe == '通过'){ ne.push(res.result.data[i]) } } for(let x = 0; x < list.length; x++){ listItem = []; for(let y = 0; y < ne.length; y++){ if(ne[y].array1 == list[x].title){ listItem.push(ne[y]) } if(y == ne.length - 1){ list[x].product = listItem; } } } console.log(list); that.setData({ ne:ne, ppp:ne, list:list }) wx.hideLoading({ }) } }) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { this.onLoad(); wx.stopPullDownRefresh({ success: (res) => {}, }) }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { wx.showToast({ icon: 'none', title: '别滑了兄弟!到底了', }) }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { }, selectType(e) { var that=this var ne=[] that.setData({ activeId: e.currentTarget.dataset.id }) for (var i = 0; i < that.data.ne.length; i++) { if (that.data.activeId == that.data.ne[i].index1) { ne.push(that.data.ne[i]) } } that.setData({ ppp: ne }) }, showLost(event){ var that=this var array=[] var qqq=event.currentTarget.dataset.id; wx.cloud.callFunction({ name:'findWhere', data:{ jihe:'shiwuzhaoling', id:qqq }, success(res){ var see = res.result.data[0].see; see = see + 9; console.log(see); wx.cloud.callFunction({ name:'changSee', data:{ jihe:'shiwuzhaoling', id:qqq, see:see }, success(res){ console.log(see); } }) } }) // db.collection("shiwuzhaoling").where({ // _id: qqq // }).get({ // success(res) { // var see = res.data[0].see // see++; // console.log(see) // db.collection("shiwuzhaoling").doc(qqq).update({ // data: { // see: see // }, // success(res) { // console.log("浏览量+1", see) // } // }) // } // }) wx.navigateTo({ url: '../showLost/showLost?data='+qqq, }) } })
import { sort } from '@ember/object/computed'; import DS from 'ember-data'; const { Model, attr, hasMany, belongsTo } = DS; export default class ProductModel extends Model { @attr() label; @attr() altLabel; @attr() description; @attr('number') sortIndex; @attr('uri-set') productLabels; @hasMany('product-group') productGroups; @hasMany('offering') offerings; @belongsTo('unit-price-specification') unitPrice; @belongsTo('quantitative-value') targetUnit; @belongsTo('file') thumbnail; @sort('offerings', 'offeringSortKeys') sortedOfferings; offeringSortKeys = ['typeAndQuantity.value'] get labelArray() { const enabled = (this.productLabels || []); return [{ uri: "http://veeakker.be/product-labels/d9fa5ad6-0d0e-4990-b8a7-ca3a60eb3a85", label: "Frozen", image: "/images/product-labels/diepvries.png", selected: enabled.includes( "http://veeakker.be/product-labels/d9fa5ad6-0d0e-4990-b8a7-ca3a60eb3a85") }, { uri: "http://veeakker.be/product-labels/fa0d5d40-762e-4f89-ac82-46c1a4ee00bf", label: "Natuurpunt", image: "/images/product-labels/natuurpunt.png", selected: enabled.includes( "http://veeakker.be/product-labels/fa0d5d40-762e-4f89-ac82-46c1a4ee00bf") }, { uri: "http://veeakker.be/product-labels/c9e43e38-3f7f-4116-9817-80bdede3f123", label: "PintaFish", image: "/images/product-labels/pintafish.png", selected: enabled.includes( "http://veeakker.be/product-labels/c9e43e38-3f7f-4116-9817-80bdede3f123") }]; } get enabledLabelArray() { return this.labelArray.filter(({selected}) => selected); } }
import Vue from "vue"; import Vuex from "vuex"; import createPersistedState from "vuex-persistedstate"; import Public from "./modules/Public"; import Compliant from "./modules/Compliant"; import Admin from "./modules/Admin"; import User from "./modules/User"; import Auth from "./modules/User/auth"; Vue.use(Vuex); export default new Vuex.Store({ modules: { Public, Compliant, User, Auth, Admin, }, plugins: [ createPersistedState({ paths: ["Auth"], }), ], });
export const changeLangAction = (lang) => ({ type: 'CHANGE_LANG', lang: lang })
var project = new Project('gamecenter_kha'); if (platform === Platform.iOS) { project.addLib('GameKit'); project.addLib('AddressBook'); project.addLib('AssetsLibrary'); project.addLib('CoreData'); project.addLib('CoreLocation'); project.addLib('CoreMotion'); project.addLib('CoreTelephony'); project.addLib('CoreText'); project.addLib('Foundation'); project.addLib('MediaPlayer'); project.addLib('QuartzCore'); project.addLib('Security'); project.addLib('SystemConfiguration'); //project.addLib('libc++.dylib'); //project.addLib('libz.dylib'); project.addLib('SafariServices'); // optional project.addLib('ios/GoogleOpenSource.framework'); project.addLib('ios/GoogleSignIn.framework'); project.addLib('ios/gpg.framework'); project.addFile('ios/gamecenterkore/**'); project.addIncludeDir('ios/gamecenterkore'); } else if (platform === Platform.Android) { project.addFile('android/gamecenterkore/**'); project.addIncludeDir('android/gamecenterkore'); project.addJavaDir('android/java'); } return project;
var Q = require("q"); var fs = require("fs"); var start = Date.now(); function getValue() { var deferred = Q.defer(); var value = Math.random() * 5000; console.log("getValue will return", value); setTimeout(function() { deferred.resolve(value); }, value); return deferred.promise; } function runParallel(file1, file2) { var promise = Q.all([ Q.nbind(fs.readFile)(file1) .then(function(text) { return JSON.parse(text); }), Q.nbind(fs.readFile)(file2) .then(function(text) { return JSON.parse(text); }), getValue(), getValue(), getValue(), getValue() ]); /*promise.then(function(results) { console.log(JSON.stringify(results, null, " ")); }) .catch(function(error) { console.log(error); }) .finally(function() { console.log("promise state:", promise.inspect().state); console.log("Done in", Date.now() - start, "ms"); });*/ promise.spread(function(obj1, obj2, value1, value2, value3, value4) { console.log("obj1:", obj1); console.log("obj2:", obj2); console.log("value1:", value1); console.log("value2:", value2); console.log("value3:", value3); console.log("value4:", value4); }) .catch(function(error) { console.log(error); }) .finally(function() { console.log("promise state:", promise.inspect().state); console.log("Done in", Date.now() - start, "ms"); }); } runParallel("./1.json", "./2.json"); //runParallel("./good.json", "./bad.json");
import React from "react"; import { createPortal } from "react-dom"; export function ModalWrapper({ children, onToggleModal }) { return createPortal( <div className="modal" onClick={onToggleModal}> {children} </div>, document.getElementById("modal-root") ); }
import React from 'react' import {selectSignedIn,setSignedIn,setUserData} from '../../features/userSlice' import {useSelector,useDispatch} from 'react-redux' import { GoogleLogout } from 'react-google-login'; function NavBar() { const isSignedIn = useSelector(selectSignedIn); const dispatch = useDispatch(); const logout = () =>{ dispatch(setSignedIn(false)); dispatch(setUserData(null)); } return ( <div> { isSignedIn && <GoogleLogout clientId='725759536945-ku4fv6k2ksus98drecuh43eg7d5jr2lm.apps.googleusercontent.com' render={(renderProps) => ( <button onClick={renderProps.onClick} disabled={renderProps.disabled} className="logout_button" > Logout </button> )} onLogoutSuccess={logout} //onFailure={login} // isSignedIn={true} cookiePolicy={'single_host_origin'} ></GoogleLogout> } </div> ) } export default NavBar
let Vec3 = {}; Vec3.create = function(x, y, z) { return new Float32Array([x,y,z]); } Vec3.lerp = function(out, a, b, w) { out[0] = M.mix(a[0], b[0], w); out[1] = M.mix(a[1], b[1], w); out[2] = M.mix(a[2], b[2], w); return out; }
describe('ActivityService', function () { var ActivityService, mockStateManager, $log, $httpBackend, $interval; beforeEach(angular.mock.module('Mobilot')); beforeEach(function () { mockStateManager = { getParams: function(){ return { mobidulCode: 'mobidulCode' }; } }; module(function ( $provide ) { $provide.value('StateManager', mockStateManager); }); }); beforeEach(inject(function($injector){ ActivityService = $injector.get('ActivityService'); $log = $injector.get('$log'); $httpBackend = $injector.get('$httpBackend'); $interval = $injector.get('$interval'); })); it('should exist', function () { expect(ActivityService).toBeDefined(); }); describe('.commitActivity()', function () { it('should exist', function () { expect(ActivityService.commitActivity).toBeDefined(); }); it('should push an activity to the storage and return true', function () { var activity = { type: ActivityService.TYPES.APP_EVENT, name: ActivityService.APP_EVENTS.USER_POSITION, payload: { foo: 'bar' } }; var respond = ActivityService.commitActivity(activity); expect(ActivityService._activityStore.pop().payload.foo == 'bar' && respond).toBeTruthy(); }); it('should return false and log an error if activity is incorrect', function () { var activity = { type: ActivityService.TYPES.APP_EVENT, name: 'wrong name', payload: { foo: 'bar' } }; $log.reset(); var respond = ActivityService.commitActivity(activity); expect( ! respond && $log.error.logs[0]).toBeTruthy(); }); }); describe('.pushActivity()', function () { beforeEach(function () { $httpBackend.expectPOST('/mobidulCode/PushActivity', '[{"type":"APP_EVENT","name":"USER_POSITION","payload":{"foo":"bar"}}]') .respond(200, { success: true }); var activity = { type: ActivityService.TYPES.APP_EVENT, name: ActivityService.APP_EVENTS.USER_POSITION, payload: { foo: 'bar' } }; ActivityService.commitActivity(activity); }); it('should exist', function () { expect(ActivityService.pushActivity).toBeDefined(); }); it('should return a success promise', function () { ActivityService.pushActivity() .then(function ( response ) { expect(response.success).toBe(true); }); $httpBackend.flush(); }); it('should clear the activity storage', function () { ActivityService.pushActivity() .then(function(){ expect(ActivityService._activityStore[0]).not.toBeDefined(); }); $httpBackend.flush(); }); }); describe('.startPushInterval()', function () { beforeEach(function () { $httpBackend.whenPOST('/mobidulCode/PushActivity') .respond(200, { success: true }); var activity = { type: ActivityService.TYPES.APP_EVENT, name: ActivityService.APP_EVENTS.USER_POSITION, payload: { foo: 'bar' } }; ActivityService.commitActivity(activity); }); it('should exist', function () { expect(ActivityService.startPushInterval).toBeDefined(); }); it('should start an interval that calls pushActivity()', function () { spyOn(ActivityService, 'pushActivity').and.callThrough(); ActivityService.startPushInterval(); $interval.flush(ActivityService.PUSH_INTERVAL); expect(ActivityService.pushActivity).toHaveBeenCalled(); $httpBackend.flush(); }); }); describe('.stopPushInterval()', function () { beforeEach(function () { $httpBackend.whenPOST('/mobidulCode/PushActivity') .respond(200, { success: true }); var activity = { type: ActivityService.TYPES.APP_EVENT, name: ActivityService.APP_EVENTS.USER_POSITION, payload: { foo: 'bar' } }; ActivityService.commitActivity(activity); ActivityService.startPushInterval(); spyOn(ActivityService, 'pushActivity').and.callThrough(); }); it('should exist', function () { expect(ActivityService.stopPushInterval).toBeDefined(); }); it('should call pushActivity() one last time', function () { ActivityService.stopPushInterval(); expect(ActivityService.pushActivity).toHaveBeenCalled(); $httpBackend.flush(); }); it('should cancel the interval', function () { ActivityService.stopPushInterval(); $interval.flush(ActivityService.PUSH_INTERVAL); //called times 2 because the function calls it once as well expect(ActivityService.pushActivity).not.toHaveBeenCalledTimes(2); }) }); });
import React from 'react' import { Button, Checkbox, Footer, Group, Header, Panel, PanelHeader, PanelHeaderBack, Progress, } from "@vkontakte/vkui"; import Icon16Add from '@vkontakte/icons/dist/16/add'; import PropTypes from 'prop-types' import Div from "@vkontakte/vkui/dist/components/Div/Div"; import InfoRow from "@vkontakte/vkui/dist/components/InfoRow/InfoRow"; class Tasks extends React.Component { constructor(props) { super(props); } state = { tasks: [ { title: 'Сходить в кино', }, { title: 'Убить Путина', } ] }; componentDidUpdate(prevProps, prevState, snapshot) { console.log(this.state.tasks) } updateTask = value => ( this.setState({ tasks: [ ...this.state.tasks, { title: value } ] }) ); render() { return ( <Panel id={this.props.id}> <PanelHeader left={<PanelHeaderBack onClick={this.props.go} data-to={'home'} />}> Задачи </PanelHeader> <Header> Сегодня </Header> <Group> {this.state.tasks.length ? this.state.tasks.map(item => <Checkbox>{item.title}</Checkbox>) : <Div>На сегодня задач нет</Div>} </Group> <Footer> <Button before={ <Icon16Add/> } size={"l"} onClick={this.props.go} data-to={"create-task"}> Создать задачу </Button> </Footer> </Panel> ); } } Tasks.propTypes = { id: PropTypes.string, task: PropTypes.shape({ title: PropTypes.string, text: PropTypes.string }) }; export default Tasks
var aDocument = { user:"alovelace", first:"Ada", last:"Lovelace", born: 1815 alive: true } //complex, nested objects are maps! var aMap = { name: {first:"Ada",last:"Lovelace"} born: 1815 } //documents live in collections //for example users collection contains users var collection = { aDocument, aMap } //names of documents in a collection must be unique //to refer to a document in a collection create a reference variable var aDocumentRef = db.collection('users').doc('aDoc') // reference vars point to the location //does not perform any network operations // and is free! /* ************* REF STRINGS For convenience, you can also create references by specifying the path to a document or collection as a string, with path components separated by a forward slash (/). For example, to create a reference to the alovelace document: */ var docRef = db.doc('users/alovelace') //nest subcollections var messageRef = db.collection('rooms').doc('roomA').collection('messages').doc('message1')
import React from 'react'; import "./SignIn.css"; import { Link } from 'react-router-dom'; import { AuthLabel } from '../AuthInputLabel'; function SignInComponent(props) { const { userName, password, userNameError, passwordError, apiError, userNameOnChangeHandler, passwordOnChangeHandler, signInHandler, } = props; return ( <form id = "sign-in" onSubmit = { signInHandler }> <h1>Sign In</h1> <input type = "text" placeholder = "Username" value = { userName } onChange = { userNameOnChangeHandler } className = { userNameError ? "invalid-input" : "" }/> <AuthLabel error = { userNameError }/> <input type = "password" placeholder = "Password" value = { password } onChange = { passwordOnChangeHandler } className = { passwordError ? "invalid-input" : "" }/> <AuthLabel error = { passwordError }/> <AuthLabel error = { apiError } /> <button onClick = { signInHandler }>Sign In</button> <p className = "link">Don't have an account yet? <Link to="/sign-up">Sign up</Link></p> </form> ); } export { SignInComponent };
import { combineReducers } from "redux"; import postsTypes from "./postsTypes"; const postsReduсer = (state = null, action) => { const { type, payload } = action; switch (type) { case postsTypes.SET_ITEMS: return payload; case postsTypes.APPEND_ITEM: return { ...state, items: state.items.map(item => { if (item.id === action.data.item.id) { return { ...action.data.item }; } return item; }) }; case postsTypes.REMOVE_ITEM: return state.filter(item => item.id !== payload); default: return state; } }; export default combineReducers({ items: postsReduсer });
///TODO: REVIEW /** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ function TreeNode(val) { this.val = val; this.left = this.right = null; } /** * Encodes a tree to a single string. * * @param {TreeNode} root * @return {string} */ var serialize = function(root) { var res = ""; LDR(root); if(res[0] === '#') res = res.substring(1); return res; function LDR(node) { if(node !== null && node.val !== undefined) { res += "#" + node.val; if(node.left !== null) { LDR(node.left); } else { res += "#N"; } if(node.right !== null) { LDR(node.right); } else { res +="#N"; } } } }; /** * Decodes your encoded data to tree. * * @param {string} data * @return {TreeNode} */ var deserialize = function(data) { /// 1#2#N#N#3#4#N#N#5#N#N var nodes = data.split('#'); return LDR(0).node; function LDR(i) { if(nodes[i] !== undefined && nodes[i] !== "" && nodes[i] !== 'N') { var root = new TreeNode(parseInt(nodes[i])); i++; var res = LDR(i); i = res.i; root.left = res.node; res = LDR(i); i = res.i; root.right = res.node; return {node: root, i:i}; } else { return {node: null, i: ++i}; } } }; let str = '1#2#N#N#3#4#N#N#5#N#N'; console.log(deserialize(str));
alert('index.js')
'use strict'; const scriptInfo = { name: 'FML', desc: 'Get FML Quote', createdBy: 'IronY' }; const _ = require('lodash'); const gen = require('../generators/_fmlLine'); const logger = require('../../lib/logger'); const ircTypography = require('../lib/_ircTypography'); module.exports = app => { app.Commands.set('fml', { desc: 'Get a random FML quote', access: app.Config.accessLevels.identified, call: (to, from, text, message) => gen() .then(result => { if (!result) { app.say(to, 'I could not seem to find any FML lines'); return; } let output = new ircTypography.StringBuilder({ logo: 'fml' }); output.append(result[0]); app.say(to, output.text); }) .catch(err => { app.say(to, 'Something went wrong with the FML API'); logger.error('FML Command Error:', { err }); }) }); return scriptInfo; };
'use strict'; app.controller('productCtrl',function ($scope, $http) { $scope.allProduct = []; $scope.maxCost = 0; $scope.clickCtry = function (e) { $scope.name = e.target.innerText; var category = angular.element(document.querySelector(".category")); var catName = angular.element(document.querySelector(".cat")); var banner = angular.element(document.querySelector(".banner")); var products = angular.element(document.querySelector(".products")); var bigCategory = angular.element(document.querySelector(".big-category")); var products = angular.element(document.querySelector(".products")); var h1 = angular.element(document.querySelector("h1")); bigCategory.css("display","block"); products.css("display","block"); h1.css("display","block"); catName.css("display", "none"); $http.get("https://jsworkshop.000webhostapp.com/?model=product") .then(function(response) { $scope.allProduct = response.data; $scope.statuscode = response.status; $scope.statustext = response.statusText; category.css("background","#222"); console.log(response.statusText); $http.get("https://jsworkshop.000webhostapp.com/?model=shop") .then(function (response) { $scope.shops = response.data; console.log(response.statusText); let j = 0 let n = $scope.allProduct.length; let tmp = []; for(let i = 0; i < n; i++){ $scope.allProduct[i].shop = []; for (let k = 0; k < $scope.shops.length; k++) { $scope.allProduct[i].shop.push($scope.shops[k].stock[i]); } } for(let i = 0; i < n; i++){ if(($scope.allProduct[i].category[0].name == $scope.name) || ($scope.allProduct[i].category[1].name == $scope.name)){ tmp[j] = $scope.allProduct[i]; j++; if ($scope.maxCost <= $scope.allProduct[i].shop[0].cost) { $scope.maxCost = $scope.allProduct[i].shop[0].cost; } } } $scope.products = tmp; }); }); category.css("background","#222"); banner.css("display","none"); products.css("display","block"); } $scope.overflow = function () { var body = angular.element(document.querySelector("body")); body.css("overflow-y","scroll"); } $scope.show = function () { var wind = angular.element(document.querySelector('.m-window')); var wrap = angular.element(document.querySelector('#wrap')); var index = angular.element(document.querySelector('input[name="index"]:checked')); $scope.showArr = $scope.products[+index[0].value]; wrap.css("display","block"); wind.css("display","block"); } $scope.bue = function () { var wind = angular.element(document.querySelector('.m-window')); var wrap = angular.element(document.querySelector('#wrap')); var select = angular.element(document.querySelector('select')); var date = angular.element(document.querySelector('input[type="date"]')); wrap.css("display","none"); wind.css("display","none"); if (localStorage.basket) { var obj = JSON.parse(localStorage.getItem("basket")); var a = []; a.push($scope.showArr.name); a.push(select[0].value); a.push(date[0].value); obj.push(a); var sObj = JSON.stringify(obj) localStorage.setItem('basket', sObj); }else{ var obj = []; var a = []; a.push($scope.showArr.name); a.push(select[0].value); a.push(date[0].value); obj.push(a); var sObj = JSON.stringify(obj) localStorage.setItem('basket', sObj); } } $scope.close = function () { var wind = angular.element(document.querySelector('.m-window')); var wrap = angular.element(document.querySelector('#wrap')); var basket = angular.element(document.querySelector('.basket-window')); basket.css("display","none"); wrap.css("display","none"); wind.css("display","none"); } $scope.basket = function () { if (!localStorage.basket) { alert("Корзина пуста"); }else{ $scope.obj = JSON.parse(localStorage.getItem("basket")); var wind = angular.element(document.querySelector('.basket-window')); var wrap = angular.element(document.querySelector('#wrap')); wrap.css("display","block"); wind.css("display","block"); } } $scope.filter = function () { var cost = angular.element(document.querySelector('.rz-pointer-max')); var j = 0; var tmp = []; for(let i = 0; i < $scope.allProduct.length; i++){ if(($scope.allProduct[i].category[0].name == $scope.name) || ($scope.allProduct[i].category[1].name == $scope.name)){ tmp[j] = $scope.allProduct[i]; j++; } } $scope.products = tmp; var fName = angular.element(document.querySelector('input[name="fName"]')); tmp = []; j = 0; for(let i = 0; i < $scope.products.length; i++){ if(($scope.products[i].name.indexOf(fName[0].value) == 0) && ($scope.maxCost > $scope.products[i].shop[0].cost) && ($scope.slider.min < $scope.products[i].shop[0].cost)){ tmp[j] = $scope.products[i]; j++; } } $scope.products = tmp; }; $scope.slider = { min: 0, options: { floor: 0, ceil: 6000, step: 1, minRange: 1, maxRange: 6000 } }; });
// Requiring bcrypt for password hashing. Using the bcrypt-nodejs version as the regular bcrypt module // sometimes causes errors on Windows machines // var bcrypt = require("bcrypt-nodejs"); // Creating our User model module.exports = function(sequelize, DataTypes) { var Address = sequelize.define("Address", { // The email cannot be null, and must be a proper email before creation addressfirst: { type: DataTypes.STRING, allowNull: true, unique: false, }, addresslast: { type: DataTypes.STRING, allowNull: false, unique: false, }, // The password cannot be null address: { type: DataTypes.STRING, allowNull: false }, city: { type: DataTypes.STRING, allowNull: false }, zip: { type: DataTypes.INTEGER, allowNull: true }, addressemail: { type: DataTypes.STRING, allowNull: false, validate: { isEmail: true } } , addressphone: { type: DataTypes.INTEGER, allowNull: false } // // Creating a custom method for our User model. This will check if an unhashed password entered by the user can be compared to the hashed password stored in our database // Address.prototype.validPassword = function(password) { // return bcrypt.compareSync(password, this.password); // }; // // Hooks are automatic methods that run during various phases of the User Model lifecycle // // In this case, before a User is created, we will automatically hash their password // Address.hook("beforeCreate", function(food) { // food.password = bcrypt.hashSync(food.password, bcrypt.genSaltSync(10), null); }); return Address; };
'use strict'; angular.module('<%=angularAppName%>') .controller('AuditDetailModalCtrl', function ($scope, $uibModalInstance, ObjectDiff, diff, audit) { $scope.diffValue = ObjectDiff.toJsonView(diff); $scope.diffValueChanges = ObjectDiff.toJsonDiffView(diff); $scope.audit = audit; $scope.cancel = function () { $uibModalInstance.dismiss('cancel'); }; });
'use strict'; const camera = require('./LSOnline/util/camera'); const globals = require('./LSOnline/util/globals'); const browser = require('./LSOnline/util/browser'); const Overlay = require('./LSOnline/util/overlay'); function preparePanel (url) { browser.prepareScreen(1000); camera.createCamera(3223, 5349, 14, 0, 0, 218, 20); browser.open(url); } function changePanel (url) { browser.close(); setTimeout(function () { browser.prepareScreen(); browser.open(url); }, 1000); } function showCharacter (characters) { setTimeout(function () { browser.inject(`showCharacters('${characters}',3000)`); }, 4000); } function destroyPanel () { camera.destroyCamera(); browser.close(); } mp.events.add({ loginPanelAppeared: url => { // preparePanel(url); // Only for test (debug) purposes. New login panel coming soon. mp.events.callRemote('authorizePlayer', 'Mati', 'XP#lSw0gbB1N'); }, loginButtonClicked: (login, password) => { mp.events.callRemote('authorizePlayer', login, password); }, remindAccount: () => { Overlay.notify( 'Nie posiadasz konta?', 'Wejdź na lsonline.pl i załóż je już teraz', 'info', 5000 ); }, userAuthorized: async characters => { destroyPanel(); // Only for test (debug) purposes. New login panel coming soon. mp.events.callRemote('loginPlayer', 1); // changePanel("package://LSOnline/browser/dist/characterSelect/index.html"); // showCharacter(characters); }, characterSelected: characterId => { destroyPanel(); mp.events.callRemote('loginPlayer', characterId); } });
/** * NetUitl 网络请求的实现 * @author lidong * @date 2016-03-17 * https://github.com/facebook/react-native */ import React, { Component } from 'react'; import { Platform, TouchableOpacity, StyleSheet, Navigator, View, Image, Text } from 'react-native'; import HHButton from './../Components/HHButton' export default class HHUtils extends Component { static NaviGoBack(navigator) { if (navigator && navigator.getCurrentRoutes().length > 1) { navigator.pop(); return true; } return false; } /** *route :路由栈 *params:导航条对象 */ static renderScene(route, navigator) { let Component = route.component; return ( <Component {...route.params} navigator={navigator} /> ); } static renderNavBar() { const styles = { title: { flex: 1, alignItems: 'center', justifyContent: 'center' }, button: { flex: 1, width: 50, alignItems: 'center', justifyContent: 'center' }, buttonText: { fontSize: 18, color: '#FFFFFF', fontWeight: '400' } } var routeMapper = { LeftButton(route, navigator, index, navState) { if(index > 0) { return ( <TouchableOpacity onPress={() => navigator.pop()} style={styles.button}> <Text style={styles.buttonText}>Back</Text> </TouchableOpacity> ); } else { return ( <TouchableOpacity onPress={() => navigator.pop()} style={styles.button}> <Text style={styles.buttonText}>Logo</Text> </TouchableOpacity> ); } }, RightButton(route, navigator, index, navState) { if(index > 0 && route.rightButton) { return ( <TouchableOpacity onPress={() => navigator.pop()} style={styles.button}> <Text style={styles.buttonText}></Text> </TouchableOpacity> ); } else { return null } }, Title(route, navigator, index, navState) { return ( <View style={styles.title}> <Text style={styles.buttonText}>{route.title ? route.title : 'Splash'}</Text> </View> ); } }; return ( <Navigator.NavigationBar style={{ alignItems: 'center', backgroundColor: '#00a6ac', shadowOffset:{ width: 1, height: 0.5, }, shadowColor: '#55ACEE', shadowOpacity: 0.8, }} routeMapper={routeMapper} /> ); } } const styles = StyleSheet.create({ container: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', backgroundColor: 'green', height:64 }, rightButtonStyle:{ marginRight:10, marginTop:27, }, leftButtonStyle:{ marginLeft:10, marginTop:27, }, centerTextStyle:{ marginTop:27, }, iconImg: { width: 30, height: 30, }, showText: { fontSize: 16, color:'white' } });
module.exports.bothelp = `Halo, kami adalah bot File Saver. Kami akan terus memperbarui bot kami.`; module.exports.botsrc = `Kalian bisa instal sendiri, pastikan langkah diikuti dengan benar.`; module.exports.botcommand = `<b>Berikut adalah beberapa perintah dan penggunaan admin.</b> ~ Bagaimana pengguna melarang, unban dan kick dari bot dan grup. <b>/ban</b> userID caption jika ada. <b>/banchat</b> userID (pribadi). <b>/unban</b> userID. <b>/unbanchat</b> userID (pribadi). <b>/kick</b> userID. <b>Dapatkan UserID dari saluran log.</b> ~ Bagaimana cara menggunakan pin dan unpin di grup. <b>/pin</b> reply ke pesan yang mau di pin. <b>/unpin</b> reply ke pesan yang mau di unpin. ~ Bagaimana cara kirim pesan ke pengguna dari grup. <b>/send</b> pesan. kirim pesan di grup. ~ Bagaimana cara kirim pesan ke pengguna dari bot. <b>/sendchat</b> userID pesan. kirim ke pengguna melalui bot. <b>Cara menghapus file dari bot.</b> Anda dapat menghapus file 4 cara. ⚫ Hapus file individual dengan file_id. ⚫ Hapus file grup dengan mediaId. ⚫ Hapus semua file Kirim oleh pengguna. ⚫ Hapus semua file Kirim ke bot. ~ Hapus file individual dengan file_id. <b>/rem</b> file_id. Ini akan menghapus file satu per satu saat Anda memberikan file_id, dapatkan file_id dari saluran log. ~ Hapus file grup dengan mediaId. <b>/remgrp</b> mediaId. Ini akan menghapus media dalam grup, dapatkan mediaId dari saluran log. ~ Hapus semua file Kirim oleh pengguna. <b>/remall</b> userID. Anda dapat menghapus semua file dikirim oleh pengguna tertentu jika pengguna mengirim konten atau spam yang kasar, dapatkan userid dari saluran log. ~ Hapus semua file Kirim ke bot. <b>/clear</b>. Ini akan menghapus semua file yang dikirim ke bot secara permanen. <b>Kirim pesan ke pengguna</b> <b>/broadcast</b>. Anda dapat menyiarkan pesan teks ke pengguna Anda, pesan akan dikirim dari pengguna terakhir bergabung untuk pertama-tama bergabung dengan pengguna untuk mengurangi spam. Cobalah untuk tidak mengirim terlalu banyak pesan sekaligus jika Anda memiliki sejumlah besar pengguna. <b>Cara mengetahui total pengguna bot.</b> <b>/stats</b>. Anda akan mendapatkan total pengguna memulai bot Anda, data waktu nyata akan diperbarui setelah siaran yang berhasil. `;
import React from 'react' import { ThemeProvider, Box } from '../src' export default () => ( <ThemeProvider> <Box p={3} bg="blue"> ThemeProvider </Box> </ThemeProvider> )
import React from 'react'; import {withStyles} from "material-ui/styles/index"; import PropTypes from "prop-types"; import classNames from 'classnames'; import Banner from './banner'; import Toolbar from "./toolbar"; import WAVEInterface from "react-audio-recorder/dist/waveInterface"; import VolumUpIcon from 'material-ui-icons/VolumeUp'; import Button from 'material-ui/Button'; const intBus = (app) => { if (window.bus) { window.bus.on('wksMsg', (type, value) => { if (type === 'showBanner') { app.setState({ isCorrect: value, show_banner: true, }); } }); } else { setTimeout(()=> { intBus(app); }, 1); } }; const styles = theme => ({ root: { width: '100%', height: '100%', display: 'flex', flexDirection: 'column', }, toolbar: { marginTop: '64px', height: '68px', }, playground: { width: '100%', flex: 1, height: `calc(100% - 64px)` }, playgroundMoveDown: { height: 'calc(100% - 64px - 68px)' }, fab: { position: 'absolute', right: theme.spacing.unit * 2, top: '70px', zIndex: 2, } }); class Workspace extends React.Component { state = { show_banner: false, isCorrect: false, question: null, }; componentDidMount = () => { intBus(this); }; componentWillReceiveProps = (props) => { if (props.question !== this.props.question) { this.setState({question: props.question}); if (window.bus && props.question) { if (props.question.sentence) { window.bus.fire('setSentence', props.question.sentence); } else { window.bus.fire('clearWorkspace'); } if (props.question.audio) { this.playAudio(props.question.audio); } } } }; playAudio = (audio) => { setTimeout(() => { const reader = new FileReader(); reader.readAsArrayBuffer(audio); reader.onloadend = () => { WAVEInterface.audioContext.decodeAudioData(reader.result, (buffer) => { const source = WAVEInterface.audioContext.createBufferSource(); source.buffer = buffer; source.connect(WAVEInterface.audioContext.destination); source.loop = false; source.start(0); }); }; }, 10); }; handleBannerClose = () => { this.setState({ show_banner: false }); if (this.state.isCorrect) { this.props.next(); } }; render() { const { classes, showtoolbar } = this.props; return ( <div className={classes.root}> {showtoolbar && <Toolbar question={this.state.question} onClose={this.props.closeToolbar} onSave={this.props.saveQuestion} getQuestion={() => {return this.state.question}} /> } {!showtoolbar && this.state.question && this.state.question.audio && <Button variant="fab" className={classes.fab} onClick={() => {this.playAudio(this.state.question.audio)}} > <VolumUpIcon/> </Button> } <div id="playground" className={classNames(classes.playground, {[classes.playgroundMoveDown]: showtoolbar})}/> <Banner correct={this.state.isCorrect} open={this.state.show_banner} onClose={this.handleBannerClose} /> </div> ); } } Workspace.propTypes = { classes: PropTypes.object.isRequired, showtoolbar: PropTypes.bool.isRequired, question: PropTypes.object, closeToolbar: PropTypes.func.isRequired, saveQuestion: PropTypes.func.isRequired, next: PropTypes.func, }; export default withStyles(styles)(Workspace);
//------------ Rest Operator ------------- function test(name,age, ...numbers){ console.log(name, age, numbers.reduce((a,b)=>a+b)) } test('Zakir Hossain',25, 1,2,3,4,5,6,7,8,9,10) //------------- Spread Operator ------------ let array=[1,2,3,4,5] console.log(...array) let obj={ a:10, b:20, c:30 } let obj2={ ...obj } console.log(obj2)
#!/usr/bin/env node require("../dist/cli/install_webapi");
const { Command, Timestamp } = require("klasa"); const { MessageEmbed } = require("discord.js"); class Tag extends Command { constructor(...args) { super(...args, { name: "tag", aliases: ["tagcmd", "bottag"], runIn: ["text"], description: language => language.get("COMMAND_TAG_DESCRIPTION"), usage: "<add|create|all|edit|delete|get|name:string> [params:string] [...]", usageDelim: " ", extendedHelp: message => message.language.get("COMMAND_TAG_EXTENDED_HELP") }); this.ts = new Timestamp("MM/DD/YYYY"); } run(message, [type, ...params]) { if (type === "add") return this.add(message, params); if (type === "create") return this.add(message, params); if (type === "all") return this.all(message); if (type === "edit") return this.edit(message, params); if (type === "delete") return this.delete(message, params[0]); if (type === "get") return this.get(message, params[0]); if (!["add", "create", "all", "edit", "delete", "get"].includes(type)) return this.get2(message, type); } async add(message, [name, ...content]) { if (name === undefined) return message.send("Please provide a tag name."); if (["add", "create", "all", "edit", "delete", "get"].includes(name)) return message.send("The tag name is reserved. Man, that would screw me up."); if (message.guild.settings.tags.find(t => t.name === name)) return message.send("The tag already exists. So unoriginal..."); if (!content.length) return message.send("Please provide some content for the tag. Here's an idea: dat banana boi is not a weeb."); const newTag = { name, content: content.join(" "), creator: message.author.id, creatorString: message.author.tag, created: this.ts.display(new Date()) }; await message.guild.settings.update("tags", newTag, { action: "add" }); return message.send(`Created the tag **\`${name}\`** for the server.`); } async create(message, [name, ...content]) { if (name === undefined) return message.send("Please provide a tag name."); if (["add", "create", "all", "edit", "delete", "get"].includes(name)) return message.send("The tag name is reserved."); if (message.guild.settings.tags.find(t => t.name === name)) return message.send("The tag already exists. So unoriginal..."); if (!content.length) return message.send("Please provide some content for the tag. Here's an idea: dat banana boi is not a weeb."); const newTag = { name, content: content.join(" "), creator: message.author.id, creatorString: message.author.tag, created: this.ts.display(new Date()) }; await message.guild.settings.update("tags", newTag, { action: "add" }); return message.send(`Created the tag **\`${name}\`** for the server.`); } async all(message) { const { tags } = message.guild.settings; const allTags = new MessageEmbed(); allTags.setColor(0xFFFFFF); allTags.setTitle("Current guild tags"); let index = 0; if (tags.length < 1) allTags.setDescription("This server has no tags. Be the one to break the silence."); else allTags.setDescription(tags.map(tag => `\`${++index}\` -> ${tag.name} -> **${tag.creatorString}**`).join("\n")); return message.sendEmbed(allTags); } async edit(message, [name, ...newContent]) { if (name === undefined) return message.send("Please provide a tag name."); if (["add", "create", "all", "edit", "delete", "get"].includes(name)) return message.send("The tag name is reserved. Man, that would screw me up."); const { tags } = message.guild.settings; if (!tags.find(t => t.name === name)) return message.send("The tag was not found."); if (tags.find(t => t.name === name).creator !== message.author.id && !message.member.permissions.has("ADMINISTRATOR")) return message.send("Hey! That ain't your tag, and you don't have **Administrator** permissions, so back off.") if (!newContent.length) return message.send("Please provide some content for the tag."); const newTag = { name, content: newContent.join(" "), creator: message.author.id, creatorString: message.author.tag, created: this.ts.display(new Date()) }; await message.guild.settings.update("tags", newTag, { action: "overwrite" }); return message.send(`Edited the tag with name: \`${name}\`.`); } async delete(message, name) { if (name === undefined) return message.send("Please provide a tag name."); if (["add", "create", "all", "edit", "delete", "get"].includes(name)) return message.send("The tag name is reserved. Man, that would screw me up."); if (!message.guild.settings.tags.find(t => t.name === name)) return message.send("The tag was not found. Create one or move on."); if (message.guild.settings.tags.find(t => t.name === name).creator !== message.author.id && !message.member.permissions.has("ADMINISTRATOR")) return message.send("Hey! That ain't your tag, or you don't have **Administrator** permission, so back off.") const { tags } = message.guild.settings; const tag = tags.indexOf(message.guild.settings.tags.find(t => t.name === name)); await message.guild.settings.update("tags", tag, { action: "remove" }); return message.send(`Deleted the tag with name: \`${name}\`. Let's hope it's in a better place.`); } async get(message, name) { if (name === undefined) return message.send("Please provide a tag name."); if (["add", "create", "all", "edit", "delete", "get"].includes(name)) return message.send("The tag name is reserved."); if (!message.guild.settings.tags.find(t => t.name === name)) return message.send("Invalid tag name passed"); const tag = message.guild.settings.tags.find(t => t.name === name); const tagEmbed = new MessageEmbed(); tagEmbed.setTitle(name); tagEmbed.setColor(0xFFFFFF); tagEmbed.setDescription(` **Tag creator** -> \`${tag.creatorString}\` **Tag creation** -> \`${tag.created}\` **Tag content** ${tag.content} `); return message.sendEmbed(tagEmbed); } async get2(message, name) { if (name === undefined) return message.send("Please provide a tag name."); if (["add", "create", "all", "edit", "delete", "get"].includes(name)) return message.send("The tag name is reserved."); if (!message.guild.settings.tags.find(t => t.name === name)) return message.send("Invalid tag name passed"); const tag = message.guild.settings.tags.find(t => t.name === name); return message.send(tag.content.replace(/@/g, "@\u200b")); } } module.exports = Tag;
editFunction = function (row, store) { Ext.define('GIGADE.EmsGoalComGoal', { extend: 'Ext.data.Model', fields: [ { name: 'department_code', type: 'string' }, { name: 'department_name', type: 'string' } ] }); var EmsGoalComStoreGoal = Ext.create("Ext.data.Store", { autoDestroy: true, model: 'GIGADE.EmsGoalComGoal', proxy: { type: 'ajax', url: '/Ems/GetDepartmentStore', reader: { type: 'json', root: 'data' } } }); var editFrm = Ext.create('Ext.form.Panel', { id: 'editFrm', frame: true, plain: true, layout: 'anchor', autoScroll: true, labelWidth: 45, url: '/Ems/SaveEmsGoal', defaults: { anchor: "95%", msgTarget: "side", labelWidth: 80 }, items: [ { xtype: 'combobox', //網頁 allowBlank: false, editable: false, fieldLabel: "部門", id: 'department_code', name: 'department_code', store: EmsGoalComStoreGoal, displayField: 'department_name', valueField: 'department_code', emptyText: "請選擇..." }, { xtype: 'numberfield', fieldLabel: '年份', id: 'year', name: 'year', allowBlank:false, allowDecimals: false, editable: false, minValue: 2000, maxValue: 9999, value: parseInt ((new Date).getFullYear()) }, { xtype: 'numberfield', fieldLabel: '月份', id: 'month', name: 'month', allowBlank: false, allowDecimals: false, editable: false, minValue: 1, maxValue: 12, value: parseInt(((new Date).getMonth() + 1)) }, { xtype: 'numberfield', fieldLabel: '目標', allowBlank: false, id: 'goal_amount', name: 'goal_amount', minValue:0 }, ], buttons: [{ text: "保存", formBind: true, disabled: true, handler: function () { var form = this.up('form').getForm(); if (form.isValid()) { form.submit({ params: { department_code: Ext.htmlEncode(Ext.getCmp("department_code").getValue()), year: Ext.htmlEncode(Ext.getCmp("year").getValue()), month: Ext.htmlEncode(Ext.getCmp("month").getValue()), goal_amount: Ext.htmlEncode(Ext.getCmp("goal_amount").getValue()) }, success: function (form, action) { var result = Ext.decode(action.response.responseText); if (result.success) { if (result.msg == 0) { Ext.Msg.alert("提示信息", "" + Ext.getCmp("month").getValue() + "月份數據已存在不可重複添加!"); } else if (result.msg == 1) { Ext.Msg.alert("提示信息", "保存成功!"); store.load(); editWin.close(); } else if (result.msg ==3) { Ext.Msg.alert("提示信息", "所選日期大於當前日期,請重新選擇"); } } else { alert(result.msg); Ext.Msg.alert("提示信息", "保存失敗!"); store.load(); editWin.close(); } } }); } } } ] }); var editWin = Ext.create('Ext.window.Window', { title: "新增業績目標", id: 'editWin', iconCls:"icon-user-add", width: 350, height: 220, 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: "關閉窗口", handler: function (event, toolEl, panel) { Ext.MessageBox.confirm("提示信息","是否關閉窗口", function (btn) { if (btn == "yes") { Ext.getCmp('editWin').destroy(); } else { return false; } }); } }] }); editWin.show(); }
const merge = require('deepmerge') const args = require('./args').current const pathResolver = require('./pathResolver') module.exports = function() { let configFileTree = [] let primary = getConfigFile(args.target) configFileTree.push(primary) resolveConfigTree(configFileTree, primary) configFileTree.reverse() const configDataList = configFileTree.map(config => config.data) const result = merge.all(configDataList) return result } function resolveConfigTree(sourceList, configObj) { const from = configObj.meta.from if (from) { let nextConfig = getConfigFile(from) sourceList.push(nextConfig) resolveConfigTree(sourceList, nextConfig) } } function getConfigFile(target) { const path = pathResolver.forTarget(target) return require(path) }
const scroll = document.querySelectorAll(".scroll__icon"); //Path const header = document.querySelector(".header"); const first = document.querySelector(".first"); const onebag = document.querySelector(".onebag"); const grains = document.querySelector(".grains"); const manual = document.querySelector(".manual"); const offer = document.querySelector(".offer"); scroll[0].addEventListener("click", (e) => { window.scrollTo({ top: getCoords(onebag).top, left: 0, behavior: "smooth", }); }); scroll[1].addEventListener("click", (e) => { window.scrollTo({ top: getCoords(grains).top, left: 0, behavior: "smooth", }); }); scroll[2].addEventListener("click", (e) => { window.scrollTo({ top: getCoords(manual).top, left: 0, behavior: "smooth", }); }); scroll[3].addEventListener("click", (e) => { window.scrollTo({ top: getCoords(offer).top, left: 0, behavior: "smooth", }); }); function getCoords(elem) { // кроме IE8- var box = elem.getBoundingClientRect(); return { top: box.top + pageYOffset, left: box.left + pageXOffset, }; }
var cacheBuster = "?t=" + Date.parse(new Date()); var stageW = "100%"; var stageH = 530;//"100%"; var attributes = {}; attributes.id = 'show_pro_img'; attributes.name = attributes.id; var params = {}; params.bgcolor = "#000000"; params.wmode ="transparent"; var flashvars = {}; flashvars.componentWidth = stageW; flashvars.componentHeight = stageH; flashvars.pathToFiles = ""; flashvars.xmlPath = "Runtime/Data/banner.xml"; swfobject.embedSWF("Tpl/default/Public/Flash/banner.swf"+cacheBuster, attributes.id, stageW, stageH, "9.0.124", "Tpl/default/Public/Flash/expressInstall.swf", flashvars, params);
$(document).ready(function () { function parse(val) { var result = "Not found", tmp = []; location.search //.replace("?", "") // this is better, there might be a question mark inside .substr(1) .split("&") .forEach(function (item) { tmp = item.split("="); if (tmp[0] === val) result = decodeURIComponent(tmp[1]); }); return result; } var myusername = parse('user'); $('#user_name').html(myusername); var client = new Client('http://188.68.59.198:8080', myusername); });
//Clone un obj sans faire de lien //Sert uniquement dans ce fichier function clone(obj) { // Handle the 3 simple types, and null or undefined if (null == obj || "object" != typeof obj) return obj; // Handle Date if (obj instanceof Date) { var copy = new Date(); copy.setTime(obj.getTime()); return copy; } // Handle Array if (obj instanceof Array) { var copy = []; for (var i = 0, len = obj.length; i < len; i++) { copy[i] = clone(obj[i]); } return copy; } // Handle Object if (obj instanceof Object) { var copy = {}; for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]); } return copy; } throw new Error("Unable to copy obj! Its type isn't supported."); } // transforme un fichier csv en un tableau de tableau // N'ACCEPTE QUE DES VALEURS NUMÉRIQUES COMME ATTRIBUT // N'ACCEPTE PAS ENCORE DES ATTRIBUTS STRING function traitDataCsv(data) { //console.log(data); var tab1 = [], ind = 0, ind2, arr, unAtt = 0; var regex1 = /,[a-zA-Z0-9]*\n/ var regex2 = /[a-zA-Z0-9]*\n/ var regex3 = /\n/ //console.log(data.search(regex1)) // si =-1 il y a un attribut dans le fichier //console.log(data.search(regex2)) //console.log(data.search(regex3)) // on met dans tab1 chaque ligne du fichier while (arr != -1) { ind2 = ind; ind = data.indexOf("\n",ind); //console.log(ind); tab1.push(data.substring(ind2,ind)); //Quand on arrive à la dernière ligne ind = -1 if (ind == (-1)) { arr = -1; // on prépare la fin du while tab1.pop(); // on éjecte le dernier élément fictif vu qu'il n'y pas de "\n" tab1.push(data.substring(ind2,data.length)) // on met la denière ligne dans tab1 }; ind++; } //console.log("tab1=",tab1); arr=ind=0; var tab2 = []; for (var i = 0; i < tab1.length; i++) { tab2.push(new Array()); while (arr != -1) { ind2 = ind; ind = tab1[i].indexOf(",",ind); //console.log(ind); tab2[i].push(tab1[i].substring(ind2,ind)); if (ind == (-1)) { arr = -1; tab2[i].pop(); tab2[i].push(tab1[i].substring(ind2,tab1[i].length)) }; ind++; } arr=ind=0; }; //console.log("tab2=",tab2); var tabAtt = tab2.splice(0,1)[0]; //On prend la prems ligne correspondant aux nom des att //console.log("tabAtt=",tabAtt); //console.log(tab2); var toChangestr = tabAtt[tabAtt.length-1]; // on selectionne le dernier attribut //toChangestr = toChangestr.slice(0,toChangestr.length-1) // on enlève l'espace invisible après le dernier attribut, sinon on se retrouve avec '"att"' au lieu de 'att' while (toChangestr.search(/ /) != -1) { toChangestr = toChangestr.slice(0,toChangestr.length-1) // on enlève l'espace après le dernier attribut } //console.log("tabAtt=",tabAtt); tabAtt.pop(); //console.log(tabAtt); tabAtt.push(toChangestr); //console.log(tabAtt); //tabAtt.push(0); var tab3 = [] // tab des objets //var varName, // varName2 = ""; for (var i = 0; i < tab2.length; i++) { var obj = {} for (var j = 0; j < tabAtt.length; j++) { //console.log(tabAtt[j]); //console.log(typeof(tabAtt[j])); varName = tabAtt[j]; obj[varName] = scientToDecimal(tab2[i][j]); //coerce values } tab3.push(obj); } //console.log("tab3=",tab3); var tabF = tab3; //console.log(tabF); return tabF; } // Est sensé gérer les fichiers dans un format JSON DONNÉ ! Il existe plusieur variantes :s function traitDataJson1(data) { //console.log(data); var myregex = /"[a-zA-Z0-9]*"\s*:\s*[a-zA-Z0-9]*\.?[a-zA-Z0-9]*/; var t1, t2, t3, t4, t5; var t3 = data.indexOf("},"); var tab1 = []; var test = 0; var aaa = data.indexOf("{"); var aaa2 = data.indexOf("}"); var nbAtt = 0; while (aaa<aaa2) { var inde1 = data.indexOf(",",aaa); if (inde1 != -1) {nbAtt++;} aaa=inde1+1; } //console.log(nbAtt); var index1 = 0; while (data.length > 1) { var obj = {}; for (var i = 0; i < nbAtt-1; i++) { var lala = data.match(myregex); //on cherche la première ligne //console.log(lala); // UNe fois trouvé, on y extrait les données var rezReg = lala[0]; // on met sous string le rez var rezRegCp = rezReg; //console.log(rezReg); var ind1 = rezReg.indexOf('"'); var ind2 = rezReg.indexOf('"',ind1+1); var att1 = rezRegCp.slice(ind1+1,ind2); // nom de l'attribut en string rezRegCp = rezReg; // on réinitie la str pour de nouvelle recherche //console.log(att1); var ind3 = rezReg.indexOf(":"); var val1 = rezRegCp.slice(ind3+1); val1 = +val1; //console.log(val1); obj[att1] = val1; //console.log(obj); // on passe à la seconde "ligne" index1 = data.indexOf(","); data = data.slice(index1+1,data.length); }; //console.log(data); var lala = data.match(myregex); //on cherche la première ligne //console.log(lala); // UNe fois trouvé, on y extrait les données var rezReg = lala[0]; // on met sous string le rez var rezRegCp = rezReg; //console.log(rezReg); var ind1 = rezReg.indexOf('"'); var ind2 = rezReg.indexOf('"',ind1+1); var att1 = rezRegCp.slice(ind1+1,ind2); rezRegCp = rezReg; // on réinitie la str pour de nouvelle recherche //console.log(att1); var ind3 = rezReg.indexOf(":"); var val1 = rezReg.slice(ind3+1); val1 = +val1; //console.log(val1); obj[att1] = val1; //console.log(obj); tab1.push(obj); index1 = data.indexOf("}"); data = data.slice(index1+2,data.length); //console.log(data); } //console.log(data.length); console.log(tab1); } //Traite les fichiers txt avec des " " au lieux des "," des fichiers csv function parseDataMathlab(data1) { var data = data1, dataRez = [], indicAttLign; //console.log(data); //console.log(data.match(regex1)[0]); //On extrait le nom des attributs indicAttLign = data.indexOf("\n"); var strAtt1 = data; strAtt1 = strAtt1.slice(0,indicAttLign); //console.log("stratt1 = ",strAtt1); data = data.slice(indicAttLign+1,data.length); //console.log(data); var nbLign = nbLignes(data); var nbAtt = nbAttributs(data); var attNames = strAtt1.split(" ",nbAtt); //console.log(attNames); //console.log(nbLign,nbAtt); //console.log(data); // On s'occupe de la dernière car on sais pas ce qui se passe avec la méthode ci-dessous var indexLastLigne = data.lastIndexOf("\n"), cpdata = data; cpdata = cpdata.slice(indexLastLigne+1,cpdata.length) //console.log("cpdata = ",cpdata); // On s'occupe des n-1 premières ligne for (var i = 0; i < nbLign-1; i++) { dataRez.push(new Array()); var indexLigneVide = data.indexOf("\n"), datacp2 = data; datacp2 = datacp2.slice(0,indexLigneVide) if (datacp2.indexOf(" ") == -1) { var indexLigne3 = data.indexOf("\n"); indexLigne3++; data = data.slice(indexLigne3,data.length); } else{ dataRez[i] = data.split(" ",nbAtt); // on s'occupe des NbAtt-1 premiers attributs car il ne finise pas par "\n" for (var j = 0; j < nbAtt-1; j++) { dataRez[i][j] = scientToDecimal(dataRez[i][j]); }; //on s'occupe du dernier attribut en excluant le "\n" de fin de ligne var indexLigne = dataRez[i][nbAtt-1].indexOf("\n"); dataRez[i][nbAtt-1] = dataRez[i][nbAtt-1].slice(0,indexLigne); dataRez[i][nbAtt-1] = scientToDecimal(dataRez[i][nbAtt-1]); var indexLigne2 = data.indexOf("\n"); indexLigne2++; data = data.slice(indexLigne2,data.length); } }; //console.log(data); pk la derniere ligne disparait partiellement // Surement car je coupé à data.length-1 au lieu de data.lengh, toute façon c'est mieux comme ça car dernière ligne pas de "\n" // on prend la dernière ligne récupèrer plus haut avec cpdata pour la traiter comme ci-dessus dataRez.push(new Array()); dataRez[i] = cpdata.split(" ",nbAtt); for (var j = 0; j < nbAtt; j++) { dataRez[i][j] = +dataRez[i][j] }; //console.log(dataRez); var dataRez2 = [attNames,dataRez] console.log(dataRez2); var dataRezF = []; for (var i = 0; i < dataRez2[1].length; i++) { var obj1 = {}; for (var j = 0; j < dataRez2[0].length; j++) { obj1[dataRez2[0][j]] = dataRez2[1][i][j]; }; dataRezF.push(obj1); }; console.log(dataRezF); return dataRezF; } // Compte le nombre de ligne d'un fichier résultat mathlab. IL EST NECESSAIRE DE NE PAS AVOIR DE LIGNE SUPLÉMENTAIRE EN DEBUT/FIN DE FICHIER // data1 = string function nbLignes(data1) { var cpt = 0, r1 = -1; do { r1 = data1.indexOf("\n",r1+1) //console.log(r1) cpt++ ; } while (r1 != -1) cpt; //console.log(cpt); return cpt; }; // Compte le nombre d'attribut dans un fichier mathlab en supposant que le dernier attribut ne soit pas suivi d'un espace et que les attributs de la premières ligne soit séparé d'un seul espace ! // objet sans espace function nbAttributs(data1) { var indexL1 = data1.indexOf("\n"), strL1 = data1.slice(0,indexL1), // on extrait la première ligne pour y compter les attributs cpt = 0, posEsp = 0, oldPosEsp; //console.log(strL1) while (posEsp != -1) { oldPosEsp = posEsp; posEsp = strL1.indexOf(" ",posEsp+1) if (posEsp-oldPosEsp >= 1 ) {cpt++}; } cpt++ //console.log(cpt); return cpt++ }; // transforme une chaine de caractère représentant un nombre au format scientifique en format décimal interpretable par la machine /* Accepte les formates suivants Le e/E symbolise 10^ xxx xxxE+xxx xxxE-xxx xxxExxx XXXe+XXX XXXe-XXX XXXeXXX */ function scientToDecimal(str1) { var strCopy = str1; var tabRez = []; if (/e/i.test(strCopy) == true) { var rez1 = strCopy.match(/e/i); tabRez.push(strCopy.slice(0,rez1.index)); // on prend la partie avant le E strCopy = str1; // on réinitie la chaine pour new traitements if (strCopy[rez1.index+1] == "+") { tabRez.push(strCopy.slice(rez1.index+2,strCopy.lenght)); return tabRez[0]*Math.pow(10,tabRez[1]); } else if (strCopy[rez1.index+1] == "-") { tabRez.push(strCopy.slice(rez1.index+2,strCopy.lenght)); return tabRez[0]*(1/Math.pow(10,tabRez[1])); } else { tabRez.push(strCopy.slice(rez1.index+1,strCopy.lenght)); return tabRez[0]*Math.pow(10,tabRez[1]); } } else { return +str1; } }
/** * Creates a diagram that illustrates what a 2-3 tree looks likes. * * Container ID: twoThreeTreeCON */ (function () { "use strict"; var jsav = new JSAV("twoThreedgmCON"); // Create all the arrays that represent the nodes in the 2-3 tree. var arrays = window.twothreetree.getArrayNodes(jsav); // Position the array nodes. var width = 840; window.twothreetree.positionRow(arrays.slice(0, 1), 0, width, 70); window.twothreetree.positionRow(arrays.slice(1, 4), 80, width, 450); window.twothreetree.positionRow(arrays.slice(4), 160, width, 560); // Create lines that connect all the nodes. var properties = {"stroke-width": 1.5}; var length = 2; window.twothreetree.getArrayNodesEdges(jsav, arrays, length, properties); }());
/* eslint-disable jsx-a11y/anchor-is-valid */ import { GlobalStyle } from '../Theme'; import styled from 'styled-components'; import { useEffect } from 'react'; import Header from '../components/Header'; import DesignBanner from '../components/DesignBanner'; import DesignCard from '../components/DesignCard'; import DesignView from '../components/DesignView'; import Footer from '../components/Footer'; import bgPattern from '../assets/images/shared/desktop/bg-pattern-leaf.svg'; const StyledGraphicDesignPageContainer = styled.div` main { width: 100%; display: flex; flex-direction: column; align-items: center; } .desing-view-container { height: 52.4rem; display: flex; flex-direction: column; justify-content: space-between; align-items: center; margin-bottom: 31.1rem; } .design-cards { height: 151.4rem; display: flex; flex-direction: column; justify-content: space-between; align-items: center; margin-bottom: 9.6rem; } @media screen and (min-width: 768px) { .desing-view-container { width: 68.9rem; height: 42.4rem; margin-bottom: 38.4rem; } .design-cards { height: 100.4rem; } } @media screen and (min-width: 1444px) { main { background-image: url(${bgPattern}); background-repeat: no-repeat; background-position: 0 47.5rem; } display: flex; flex-direction: column; align-items: center; .design-cards { width: 111.1rem; height: 47.8rem; flex-wrap: wrap; flex-direction: row; } .desing-view-container { width: 111.1rem; height: 30.8rem; flex-direction: row; margin-bottom: 31.1rem; } } `; function GraphicDesign() { useEffect(() => { window.scrollTo(0, 0); }); const designViewData = [ { title: 'web design', width: '32.7rem', height: '25rem', svgName: 'web', }, { title: 'app design', width: '32.7rem', height: '25rem', svgName: 'app', }, ]; const designCardData = [ { design: 'graphic-design', title: 'tim brown', desc: 'A book cover designed for Tim Brown’s new release, ‘Change’', fileName: 'change', }, { design: 'graphic-design', title: 'boxed water', desc: 'A simple packaging concept made for Boxed Water', fileName: 'boxed-water', }, { design: 'graphic-design', title: 'science', desc: 'A poster made in collaboration with the Federal Art Project', fileName: 'science', }, ]; const renderList = designViewData.map((item, idx) => { return ( <DesignView key={idx} title={item.title} svgName={item.svgName} width={item.width} height={item.height} home="false" /> ); }); const renderDesignCards = designCardData.map((item, idx) => { return ( <DesignCard design={item.design} title={item.title} desc={item.desc} fileName={item.fileName} key={idx} /> ); }); return ( <StyledGraphicDesignPageContainer> <GlobalStyle /> <main> <Header /> <DesignBanner title="Graphic Design" content="We deliver eye-catching branding materials that are tailored to meet your business objectives." bgName="graphic-design" /> <div className="design-cards">{renderDesignCards}</div> <div className="desing-view-container">{renderList}</div> <Footer /> </main> </StyledGraphicDesignPageContainer> ); } export default GraphicDesign;
import React from 'react'; import '../css/Post.css' export default function PostF(props) { return ( <div className="blog-post"> <img src = {props.image} alt=""></img> <div className="post-info"> <h1>{props.title}</h1> <p>{props.content}</p> </div> </div> ) }
import React, { useState, useEffect} from 'react'; import Highcharts from "highcharts"; import HighchartsReact from "highcharts-react-official"; import axios from 'axios'; function FedStateAvgCompareBarGraphComponent(props) { const stateName = props.stateName; const [data, setData] = useState({}) function handleResponse(response) { console.log(response); setData(response.data); } useEffect(() => { axios.get('/fedStateIncomeTaxRateComparison', { params: { stateTax: stateName } }) .then(handleResponse); }, [stateName]); const options = { chart: { type: 'column' }, title: { text: 'Federal/State Tax Bracket Comparison' }, subtitle: { text: 'Biden v. Trump' }, xAxis: { categories: [ '0 - $9,875', '$9,876 - $40,125', '$40,125 - $85,525', '$85,526 - $163,300', '$163,301 - $207,350', '$207,351 - $518,400', '$518,401 +' ], crosshair: true }, yAxis: { min: 0, title: { text: 'Tax Liability (US$)' } }, legend: { enabled: false }, colors: [ 'blue', 'red' ], series: [{ name: 'Biden', data: [data.Biden_1, data.Biden_2, data.Biden_3, data.Biden_4, data.Biden_5, data.Biden_6, data.Biden_7] }, { name: 'Trump', data: [data.Trump_1, data.Trump_2, data.Trump_3, data.Trump_4, data.Trump_5, data.Trump_6, data.Trump_7] }] }; return ( <React.Fragment> <HighchartsReact highcharts={Highcharts} options={options} /> </React.Fragment> ) } export default FedStateAvgCompareBarGraphComponent;
/** * Created by yang on 2020/2/28. */ // CommonJS 模块化规范的导入: // let {flag, test, demo} = require('./01-CommonJS规范-导出(nodejs 模块化规范).js') // 也可以这样做 // let moduleA = require('./01-CommonJS规范-导出(nodejs 模块化规范).js') // let test = moduleA.test; // let demo = moduleA.demo; // let flag = moduleA.flag;
'use strict'; var mockModule = require('./mocked-backend'); describe('mock resource calls', function() { it('lists all patients', function() { browser.addMockModule('httpBackendMock', mockModule.httpBackendMock); browser.get('/'); var patients = element.all(by.repeater('patient in patients')); expect(patients.count()).toBe(1); }); });
/** * View to handle date selection for scheduling a training program. */ P.views.programs.schedule.DateEdit = P.views.Layout.extend({ templateId: 'programs.schedule.date_edit', className: 'v-DateEdit', events: { 'submit': 'submit', 'select .v-miniCal': 'select', 'change .js-date': 'changeDate' }, regions: { rCal: '.r-cal' }, changeDate: function() { var date = this.$('.js-date').val(), err = P.helpers.Time.validateDate(date); if (err) { this.showError(err); return; } P.common.forms.Input.valid(this.$('.js-date')); this.rCal.currentView.setDate(date); }, onRender: function() { this.rCal.show(new P.views.calendar.Mini({ selectedDate: this.startDate(), moment: this.model.get('start') })); }, select: function(event, date) { P.stopEvent(event); P.common.forms.Input.valid(this.$('.js-date')); this.$('.js-date').val(date); }, serializeData: function() { return { start: this.startDate() }; }, showError: function(errMessage) { P.common.forms.Input.invalid(this.$('.js-date'), errMessage); }, startDate: function() { var start = this.model.get('start'); if (!start) { console.warn('"start" date not set.'); return; } return start.format('YYYY-MM-DD'); }, submit: function(event) { P.stopEvent(event); var rawDate = this.$('.js-date').val().trim(), date = moment(rawDate, 'YYYY-MM-DD'), err = P.helpers.Time.validateDate(rawDate); if (err) { this.showError(err); return; } this.model.set('start', date); this.$el.trigger('close'); } });
import React from 'react'; import './cargarMutantes.css'; function CargarMutantesView () { return ( <p > Test de Cargar mutantes </p> ) } export default CargarMutantesView;
window.Aubay = window.Aubay || {}; (function (window, undefined) { 'use strict'; var form = document.getElementById('login-form'), arrayInput = form.querySelectorAll('[data-validate]'), Form = { CleanFields: function() { Array.from(arrayInput).forEach(function(elem) { elem.addEventListener('keypress', (event) => { var formItem = elem.closest('label'), msgField = elem.nextSibling.nextSibling; formItem.className = ''; msgField.innerHTML = ''; }); }); }, Validate: function() { Form.CleanFields(); form.addEventListener('submit', function(e){ var i = 0, isValid = true, msgReturn = document.getElementById('return-general'), name = e.target.elements['txtUsername'].value, password = e.target.elements['txtPassword'].value; while (i < arrayInput.length) { var rule = arrayInput[i].getAttribute('data-validate'), formItem = arrayInput[i].closest('label'), msgField = arrayInput[i].nextSibling.nextSibling, currentVal = arrayInput[i].value; e.preventDefault(); if (rule == 'type-required') { if (!Form.ValidateRequired(currentVal)){ formItem.className = 'error'; msgField.innerHTML = 'Please, fill the field'; isValid = false; } } i++; } if (isValid) { if (name === 'admin' && password === 'admin') { window.location.href = 'https://gauchazh.clicrbs.com.br/'; } else { msgReturn.innerHTML = 'Invalid credentials'; } } }); }, ValidateRequired: function(value){ return value !== ''; } }; Aubay.app = function () { return { Init: function () { Form.Validate() } }; }; }(window, undefined)); Aubay = new Aubay.app(); Aubay.Init();
// const { Model } = require('sequelize'); // const sequelize = require('../utils/db/sequelize'); // const Post = require('./Post'); // const Comment = require('./Comment'); module.exports = (sequelize, { STRING }) => { const User = sequelize.define( 'User', { firstName: { type: STRING, allowNull: false, validate: { customValidator(value) { if (value === null && this.age !== 10) { throw new Error("name can't be null unless age is 10"); } }, }, }, lastName: { type: STRING, }, }, { sequelize, underscored: true, tableName: 'users', }, ); User.associate = ({ Post, Comment }) => { User.hasMany(Comment); User.belongsTo(Post); }; return User; };
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const mongoose = require("mongoose"); const DataAccess_1 = require("../DataAccess"); class MessageSchema { static get schema() { let schemaDefinition = { userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true, }, content: { type: String, required: true, }, groupReceive: new mongoose.Schema({ role: { type: Number, required: true }, product: { type: Number, required: false } }, { _id: false }), fileId: { type: mongoose.Schema.Types.ObjectId, ref: 'File', }, }; return DataAccess_1.DataAccess.initSchema(schemaDefinition); } } exports.default = DataAccess_1.DataAccess.connection.model('Message', MessageSchema.schema);
"use strict"; exports.__esModule = true; var bankAccount = /** @class */ (function () { function bankAccount(owner, balance) { this.transactions = []; this.owner = owner; this.balance = balance; } bankAccount.prototype.getBalance = function () { return this.balance; }; bankAccount.prototype.withdrawal = function (withdrawalAmt) { this.balance -= withdrawalAmt; this.transactions.push(withdrawalAmt); return withdrawalAmt; }; bankAccount.prototype.deposit = function (depositAmt) { this.balance += depositAmt; this.transactions.push(depositAmt); return depositAmt; }; return bankAccount; }()); exports.bankAccount = bankAccount;
/** * Error handler for uncaught exceptions */ export default function handleUncaughtException(err) { console.error(err) process.exit(1) }
import React from 'react'; import { Container, Col, Row, Alert, ListGroup, ListGroupItem, } from 'reactstrap'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faGithub } from '@fortawesome/free-brands-svg-icons'; import Link from 'next/link'; import 'bootstrap/dist/css/bootstrap.min.css'; import '../css/about.css'; const About = () => ( <Container className="about__container"> <Row> <Col> <h3 className="about__whoami__title mr-3">What is Classic Bot?</h3> <a href="https://github.com/JFGHT/Classic-Bot" target="_blank" rel="noopener noreferrer" > <FontAwesomeIcon icon={faGithub} size="lg" /> </a> </Col> </Row> <Row className="mb-3"> <Col> Classic bot is a Chat client made to log in into the classic Battle.net, so you can speak with your friends without the need of Warcraft/Starcraft/Diablo game. </Col> </Row> <Row> <Col> <h3>How does it work?</h3> </Col> </Row> <Row className="mb-3"> <Col> It is using the Classic Chat API – Alpha v3 made my Blizzard ( <a href="https://us.forums.blizzard.com/en/warcraft3/u/newclassic-11551/summary" target="_blank" rel="noopener noreferrer" > Mark Chandler </a> ). You need an &nbsp; <b> API Key </b> &nbsp;in order to connect to the server. </Col> </Row> <Row> <Col> <h3>How do I get an API Key?</h3> </Col> </Row> <Row className="mb-2"> <Col> Copied directly from the&nbsp; <a href="https://s3-us-west-1.amazonaws.com/static-assets.classic.blizzard.com/public/Chat+Bot+API+Alpha+v3.pdf" target="_blank" rel="noopener noreferrer" > official document </a> : </Col> </Row> <Row className="mb-3"> <Col> <Alert color="info"> Connect to Battle.net using StarCraft Remastered, Diablo 2 or Warcraft 3 and once in your preferred channel (Op or Clan) use the command /register-bot to start the registration process. An email is required to be registered to the account and after executing the command an email with activation link will be sent to the email on file. The user is required to click on the link to get a valid API Key. Executing the command a second time will issue a new API Key and invalidate the old key. </Alert> </Col> </Row> <Row> <Col> <h3>Current API (alpha 3) limitations</h3> </Col> </Row> <Row className="mb-3"> <Col> <ListGroup flush> <ListGroupItem>Only chieftains can get API Keys</ListGroupItem> <ListGroupItem>Nothing outside the channel can be done (not even whispers)</ListGroupItem> <ListGroupItem>Friend list is not available</ListGroupItem> <ListGroupItem>Clan list is not available</ListGroupItem> <ListGroupItem>Battle.net chat commands are not available</ListGroupItem> </ListGroup> </Col> </Row> <Row> <Col> <h3>To do</h3> </Col> </Row> <Row className="mb-3"> <Col> <ListGroup flush> <ListGroupItem>Kick users</ListGroupItem> <ListGroupItem>Ban users</ListGroupItem> <ListGroupItem>Start a whispering conversation</ListGroupItem> <ListGroupItem>Play a sound when whispered or mentioned</ListGroupItem> </ListGroup> </Col> </Row> <Row> <Col> <h3>Technologies used</h3> </Col> </Row> <Row className="mb-3"> <Col> ReactJS, NextJS, Redux, Reactstrap (Bootstrap). </Col> </Row> <Row> <Col> <h3 className="about__whoami__title mr-3">/Whoami</h3> <a href="https://github.com/JFGHT" target="_blank" rel="noopener noreferrer" > <FontAwesomeIcon icon={faGithub} size="lg" /> </a> </Col> </Row> <Row className="mb-3"> <Col> I'm a Warcraft III player with passion for technologies. You can usually find me at Clan RoC in Europe server! </Col> </Row> <Row className="mb-3"> <Col> <Link prefetch href="/"> <a>Go back</a> </Link> </Col> </Row> </Container> ); export default About;
// use setState() const React = require('react'); class DigitalClicker extends React.Component{ constructor(props) { super(props); this.state = { timesClicked: 0, }; this.clicker = this.clicker.bind(this) } clicker(){ this.setState({ timesClicked: this.state.timesClicked + 1 }) } render(){ return( <button onClick={this.clicker}>{this.state.timesClicked}</button> ) } } module.exports = DigitalClicker;
import React, { Component } from 'react'; import logo from './wop.jpg'; const VERSION_16 = '1.6'; const VERSION_12 = '1.2'; const Colored = ({ value }) => { const colors = [ 'white', 'red', 'green', 'yellow', 'blue', 'cyan', 'magenta', 'white' ]; const colored = []; let i = 0; while (i < value.length) { let next = value.indexOf('^', i + 1); if (next === -1) next = value.length; if (value[i] !== '^') { colored.push(value.slice(0, next)); i = next; continue; } const colorCode = parseInt(value[i + 1], 10); const text = value .slice(i + 2, next) .replace('\xa0', ' ') .replace(String.fromCharCode(127), ''); if (text) colored.push( <span key={colored.length} className={colors[colorCode]}> {text} </span> ); i = next; } return colored; }; class App extends Component { constructor(props) { super(props); this.state = { serverInfo16: [], serverInfo12: [], version: VERSION_16 }; this.gametypes = [ 'Free For All', 'Tournament', 'Single Player', 'Spray your Color', 'Last Pad Standing', 'Team Deathmatch', 'Capture the Lolly', 'Team Spray your Color', 'Big Balloon' ]; this.toggleVersion = this.toggleVersion.bind(this); } withoutColor(hostname) { return hostname.replace(/\^\d/g, ''); } sortInfo(info) { return info.sort((a, b) => { const hostname1 = this.withoutColor(a.hostname); const hostname2 = this.withoutColor(b.hostname); return hostname1.localeCompare(hostname2); }); } componentDidMount() { const socket = window.io(process.env.REACT_APP_SERVER); socket.on('updated', data => { const sortedInfo = this.sortInfo(data).map(info => ({ ...info, players: this.getPlayers(info) })); this.setState(_ => ({ serverInfo16: sortedInfo.filter(info => info.version === VERSION_16), serverInfo12: sortedInfo.filter(info => info.version === VERSION_12) })); }); } getPlayers(server) { let playersString = server['.Web2'] || server.g_beryllium || server.g_Modifier_WeaponScore if(!playersString && server.Players_Bot) { playersString = server.Players_Bot.concat( server.Players_Team && server.Players_Team.split('\n').slice(1).join('\n') ); } if (!playersString) return []; const infoStr = playersString.split('\n').slice(1, -1); return infoStr .map(playerString => { const player = /([-\d]+) ([-\d]+) "(.+?)"/.exec(playerString); return { name: player[3].trim(), frags: player[1], ping: player[2] }; }) .sort((a, b) => b.frags - a.frags); } versionClass(version) { return this.state.version === version ? 'active' : ''; } toggleVersion() { this.setState(state => ({ version: state.version === VERSION_16 ? VERSION_12 : VERSION_16 })); } render() { const serverInfo = this.state.version === VERSION_16 ? this.state.serverInfo16 : this.state.serverInfo12; return ( <div className="app"> <header className="header"> <img src={logo} className="logo" alt="logo" /> <div className="header-center"> <div className="switch" onClick={this.toggleVersion}> <div className={this.versionClass('1.6')}> <span>1.6</span> </div> <div className={this.versionClass('1.2')}> <span>1.2</span> </div> </div> </div> <h1 className="app-title"> World of Padman - Server Status </h1> </header> <div className="container"> {serverInfo.map(server => ( <div className="row" key={server.hostname}> <div className="server-title"> <h1> <Colored value={server.hostname} /> </h1> </div> <div className="server-info"> <div className="info"> <div className="key">Current Map:</div> <div className="value"> {server.mapname} </div> </div> <div className="info"> <div className="key">Game type:</div> <div className="value"> {this.gametypes[server.gametype]} </div> </div> <div className="info"> <div className="key">Point limit:</div> <div className="value"> {server.pointlimit} </div> </div> <div className="info"> <div className="key">Time limit:</div> <div className="value"> {server.timelimit} </div> </div> </div> <div className="players-info"> <div className="info title"> <div className="name">Player</div> <div className="frags">Score</div> <div className="ping">Ping</div> </div> {!server.players.length ? <div className="info no-players">No players online</div> : server.players.map((player, idx) => ( <div className="info" key={idx}> <div className="name"> <Colored value={player.name} /> </div> <div className="frags"> {player.frags} </div> <div className="ping"> {player.ping} </div> </div> ))} </div> </div> ))} </div> </div> ); } } export default App;
var mongoose = require("mongoose"); var Schema = mongoose.Schema; var UserSchema = new Schema({ name: { type: String, trim: true }, email: { type: String, match: [/.+\@.+\..+/, "Please enter a valid e-mail address"], trim: true }, password:{ types: String, match: String, }, specialty: { type: String, trim: true }, image: { type: String, trim: true, } }); //add username and password and add validation to input username var User = mongoose.model("User", UserSchema); module.exports = User;
class Chat extends React.Component { constructor(props) { super(props); this.state = { messages: [], input: '', word: '', } } addMessage(message, sender) { var msg = { sender: sender, message: message }; this.setState((state)=>{ var msglist = state.messages; msglist.push(msg); return { messages: msglist, input: '', } }); } componentDidMount(){ socket.on('receiveMessage', (data)=>{ this.addMessage(data.message, 'other'); }); } handleInput = (e)=>{ var change = e.target.value; this.setState({ input: change }); }; sendMessage = (e)=>{ e.preventDefault(); var message = this.state.input; socket.emit('sendMessage', {message: message}, (response)=>{ if (response != 'empty') { this.addMessage(message, 'self'); } }); }; render() { var msglist = this.state.messages; var msgArray = []; for (let i = 0, l = msglist.length; i < l; i++) { var msgClass = 'chatMsg chatMessageAppear '; var sender; if (msglist[i].sender == 'self') { msgClass += 'chatMsgSelf'; sender = <p><b>You</b></p>; } else { msgClass += 'chatMsgOther'; sender = <p><b>Other</b></p>; } var msg = <p>{ msglist[i].message }</p>; var html = <div className={msgClass} key={i}>{sender}{msg}</div>; msgArray.push(html); } return( <div className="chat"> <div className='chatHeader chatHeaderSlideIn'> <a href="/"><div>x</div></a> <span>{this.props.word}</span> </div> <div className='chatArray'> {msgArray} </div> <div className='chatSend chatSendAppear'> <form action="" onSubmit={this.sendMessage}> <textarea value={this.state.input} onChange={this.handleInput}></textarea> <button type='submit'>Send</button> </form> </div> </div> ); } }
/*global ODSA */ // Written by Cliff Shaffer // Show the costs for some simple problems, for a given n or for growing n $(document).ready(function() { "use strict"; var av_name = "SimpleCostsCON"; var av = new JSAV(av_name); var topAlign = 50; var left = 100; var yLength = 150; // Graph y axis size var xLength = 150; // Graph x axis size // First, draw the top row of graphs: for an arbitrary (but specific) value of n av.label("Costs for all inputs of an arbitrary (but fixed) size $n$ for three representative algorithms", {top: topAlign - 50, left: 130}).addClass("largeLabel"); var axis = av.g.polyline([[left, topAlign], [left, topAlign + yLength], [left + xLength, topAlign + yLength]]); var xLabel = av.label("$I_n$", {top: topAlign + yLength - 5, left: left + xLength - 75}).addClass("smallLabel"); av.label("cheap", {top: topAlign + yLength - 5, left: left}).addClass("smallLabel"); av.label("expensive", {top: topAlign + yLength - 5, left: left + 120}).addClass("smallLabel"); av.label("$2^n-1$", {top: topAlign + 3, left: left - 30}).addClass("smallLabel"); av.label("_", {top: topAlign - 20, left: left - 4}).addClass("largeLabel"); av.label("$*$", {top: topAlign - 10, left: left + 70}); av.label("Towers of Hanoi", {top: topAlign + 150, left: left + 20}); left += 250; var axis = av.g.polyline([[left, topAlign], [left, topAlign + yLength], [left + xLength, topAlign + yLength]]); xLabel = av.label("$I_n$", {top: topAlign + yLength - 5, left: left + xLength - 75}).addClass("smallLabel"); av.label("cheap", {top: topAlign + yLength - 5, left: left}).addClass("smallLabel"); av.label("expensive", {top: topAlign + yLength - 5, left: left + 120}).addClass("smallLabel"); av.label("$n$", {top: topAlign - 10, left: left - 20}); av.label("_", {top: topAlign - 20, left: left - 4}).addClass("largeLabel"); av.g.line(left, topAlign + 16, left + xLength, topAlign + 16); av.label("FindMax", {top: topAlign + 150, left: left + 50}); left += 250; var axis = av.g.polyline([[left, topAlign], [left, topAlign + yLength], [left + xLength, topAlign + yLength]]); xLabel = av.label("$I_n$", {top: topAlign + yLength - 5, left: left + xLength - 75}).addClass("smallLabel"); av.label("cheap", {top: topAlign + yLength - 5, left: left}).addClass("smallLabel"); av.label("expensive", {top: topAlign + yLength - 5, left: left + 120}).addClass("smallLabel"); av.label("$n$", {top: topAlign - 10, left: left - 20}); av.label("_", {top: topAlign - 20, left: left - 4}).addClass("largeLabel"); av.label("$1$", {top: topAlign + xLength - 40, left: left - 20}); av.label("_", {top: topAlign + xLength - 50, left: left - 4}).addClass("largeLabel"); av.g.line(left, topAlign + xLength - 14, left + xLength, topAlign + 16); av.label("Find", {top: topAlign + 150, left: left + 70}); // Now, draw the second row of graphs: Behavior as n grows toward infinity topAlign += 260; left = 100; av.label("Costs, as $n$ grows, for some representative algorithms", {top: topAlign - 50, left: 200}).addClass("largeLabel"); av.g.polyline([[left, topAlign], [left, topAlign + yLength], [left + xLength, topAlign + yLength]]); av.label("$n$", {top: topAlign + yLength - 5, left: left + xLength - 75}).addClass("smallLabel"); av.label("cheap", {top: topAlign + yLength - 5, left: left}).addClass("smallLabel"); av.label("expensive", {top: topAlign + yLength - 5, left: left + 120}).addClass("smallLabel"); av.label("$2^n-1$", {top: topAlign + 3, left: left - 30}).addClass("smallLabel"); av.label("_", {top: topAlign - 20, left: left - 4}).addClass("largeLabel"); av.label("$T(n) = 2^n-1$", {top: topAlign + 50, left: left + 30}); av.label("Towers of Hanoi", {top: topAlign + 150, left: left + 20}); var xGraph = left; var yGraph = topAlign + yLength; // It appears that path can only handle 6 points, so the last one is // made a bit high av.g.path(["M", xGraph + 1, yGraph - 1, "C", xGraph + 2, yGraph - 3, xGraph + 3, yGraph - 7, xGraph + 4, yGraph - 15, xGraph + 5, yGraph - 31, xGraph + 6, yGraph - 63, xGraph + 7, yGraph - 150, ].join(",")); left += 250; av.g.polyline([[left, topAlign], [left, topAlign + yLength], [left + xLength, topAlign + yLength]]); av.label("$n$", {top: topAlign + yLength - 5, left: left + xLength - 75}).addClass("smallLabel"); av.label("cheap", {top: topAlign + yLength - 5, left: left}).addClass("smallLabel"); av.label("expensive", {top: topAlign + yLength - 5, left: left + 120}).addClass("smallLabel"); av.label("$n$", {top: topAlign - 10, left: left - 20}); av.label("_", {top: topAlign - 20, left: left - 4}).addClass("largeLabel"); av.label("$1$", {top: topAlign + xLength - 40, left: left - 20}); av.label("_", {top: topAlign + xLength - 50, left: left - 4}).addClass("largeLabel"); av.g.line(left, topAlign + xLength - 14, left + xLength, topAlign + 16); av.label("FindMax", {top: topAlign + 150, left: left + 50}); left += 250; av.g.polyline([[left, topAlign], [left, topAlign + yLength], [left + xLength, topAlign + yLength]]); av.label("$n$", {top: topAlign + yLength - 5, left: left + xLength - 75}).addClass("smallLabel"); av.label("cheap", {top: topAlign + yLength - 5, left: left}).addClass("smallLabel"); av.label("expensive", {top: topAlign + yLength - 5, left: left + 120}).addClass("smallLabel"); av.label("$1$", {top: topAlign + xLength - 40, left: left - 20}); av.label("_", {top: topAlign + xLength - 50, left: left - 4}).addClass("largeLabel"); av.g.line(left, topAlign + xLength - 14, left + xLength, topAlign + xLength - 14); av.label("Find (Best)", {top: topAlign + 150, left: left + 40}); topAlign += 190; av.g.polyline([[left, topAlign], [left, topAlign + yLength], [left + xLength, topAlign + yLength]]); av.label("$n$", {top: topAlign + yLength - 5, left: left + xLength - 75}).addClass("smallLabel"); av.label("cheap", {top: topAlign + yLength - 5, left: left}).addClass("smallLabel"); av.label("expensive", {top: topAlign + yLength - 5, left: left + 120}).addClass("smallLabel"); av.label("$n$", {top: topAlign - 10, left: left - 20}); av.label("_", {top: topAlign - 20, left: left - 4}).addClass("largeLabel"); av.label("$1$", {top: topAlign + xLength - 40, left: left - 20}); av.label("_", {top: topAlign + xLength - 50, left: left - 4}).addClass("largeLabel"); av.g.line(left, topAlign + xLength - 14, left + xLength, topAlign + xLength/2); av.label("Find (Average)", {top: topAlign + 150, left: left + 40}); topAlign += 190; av.g.polyline([[left, topAlign], [left, topAlign + yLength], [left + xLength, topAlign + yLength]]); av.label("$n$", {top: topAlign + yLength - 5, left: left + xLength - 75}).addClass("smallLabel"); av.label("cheap", {top: topAlign + yLength - 5, left: left}).addClass("smallLabel"); av.label("expensive", {top: topAlign + yLength - 5, left: left + 120}).addClass("smallLabel"); av.label("$n$", {top: topAlign - 10, left: left - 20}); av.label("_", {top: topAlign - 20, left: left - 4}).addClass("largeLabel"); av.label("$1$", {top: topAlign + xLength - 40, left: left - 20}); av.label("_", {top: topAlign + xLength - 50, left: left - 4}).addClass("largeLabel"); av.g.line(left, topAlign + xLength - 14, left + xLength, topAlign + 16); av.label("Find (Worst)", {top: topAlign + 150, left: left + 40}); av.displayInit(); av.recorded(); });
function Router($stateProvider, $urlRouterProvider){ function secureState($q, $auth, $state, $rootScope){ return new $q(resolve => { if($auth.isAuthenticated()) return resolve(); //Assume users not logged in //Create a flash message! $rootScope.$broadcast('flashMessage', { type: 'warning', content: 'You must be logged in to access the page' }); $state.go('login'); }); } $stateProvider .state('about', { templateUrl: './views/about.html', url: '/about' }) .state('home', { templateUrl: './views/home.html', url: '/' }) .state('albumsIndex', { templateUrl: './views/albums/index.html', url: '/albums', //optional controller: 'AlbumsIndexCtrl', //optional resolve: {secureState} }) .state('albumsNew', { templateUrl: './views/albums/new.html', url: '/albums/new', controller: 'AlbumsNewCtrl' //optional }) .state('albumsEdit', { templateUrl: './views/albums/edit.html', url: '/albums/:id/edit', //optional - id is parameter of state controller: 'AlbumsEditCtrl' //optional }) .state('albumsShow', { templateUrl: './views/albums/show.html', url: '/albums/:id', controller: 'AlbumsShowCtrl' //optional }) .state('login', { templateUrl: './views/auth/login.html', url: '/login', //optional - id is parameter of state controller: 'AuthLoginCtrl' //optional }) .state('register', { templateUrl: './views/auth/register.html', url: '/register', //optional - id is parameter of state controller: 'AuthRegisterCtrl' //optional }) .state('tracksIndex', { templateUrl: './views/tracks/index.html', url: '/tracks', //optional controller: 'TracksIndexCtrl' //optional }) .state('tracksNew', { templateUrl: './views/tracks/new.html', url: '/albums/:albumId/tracks/new', //optional controller: 'TracksNewCtrl' //optional }) .state('concertsIndex', { templateUrl: './views/concerts/index.html', url: '/concerts', //optional controller: 'ConcertsIndexCtrl' //optional }); $urlRouterProvider.otherwise('/'); } export default Router;
import React from 'react'; import '../../App.css'; export default function Cardfour() { return <div className='cardfour'></div>; }
const Create = require("./Create"); const GetHistory = require("./GetHistory"); const DeleteByUUID = require("./DeleteByUUID"); module.exports = { Create, GetHistory, DeleteByUUID, };
export const isFormatedVersion = (version) => { // expected format: 0.0.0_0 const pattern = /^\d+[\.]\d+[\.]\d+[_]\d+$/; return pattern.test(version); };
import {createStore} from "redux"; const SET_NEW_TRACKER = 'SET_NEW_TRACKER'; const REMOVE_TRACKER = 'REMOVE_TRACKER'; const START_TRACKER = 'START_TRACKER'; const STOP_TRACKER = 'STOP_TRACKER'; let initialState = { trackers: [] }; if (localStorage.getItem('trackersState') !== null) { initialState = {...JSON.parse(localStorage.getItem('trackersState'))} } export const setNewTracker = (name, startPoint) => ({ type: SET_NEW_TRACKER, name, startPoint }); export const startTracker = (index, newStartPoint) => ({ type: START_TRACKER, index, newStartPoint }); export const stopTracker = (index, value) => ({ type: STOP_TRACKER, index, value }); export const removeTracker = (index = 0) => ({ type: REMOVE_TRACKER, index }); const trackersReducer = (state = initialState, action) => { switch (action.type) { case SET_NEW_TRACKER: { const stateCopy = { ...state, trackers: [...state.trackers, { name: action.name, startPoint: action.startPoint, value: 0, trackerOn: true }] } localStorage.setItem('trackersState', JSON.stringify(stateCopy)); return stateCopy; } case STOP_TRACKER: { let trackers = [...state.trackers]; trackers[action.index] = { ...trackers[action.index], value: action.value, trackerOn: false } const stateCopy = { ...state, trackers: trackers, } localStorage.setItem('trackersState', JSON.stringify(stateCopy)); return stateCopy; } case START_TRACKER: { let trackers = [...state.trackers]; trackers[action.index] = { ...trackers[action.index], startPoint: action.newStartPoint, trackerOn: true } const stateCopy = { ...state, trackers: trackers, } localStorage.setItem('trackersState', JSON.stringify(stateCopy)); return stateCopy; } case REMOVE_TRACKER: { let trackers = [...state.trackers]; trackers.splice(action.index, 1); const stateCopy = { ...state, trackers: trackers, } localStorage.setItem('trackersState', JSON.stringify(stateCopy)); return stateCopy; } default: return state; } }; const store = createStore(trackersReducer); export default store;
let mini = new Map(); let answer = 0; let rel; let maxN; function checkUniq(selected){ let tmap = new Map(); //console.log(selected) for(let i =0;i<rel.length;i++){ let s = ""; for(let j =0;j<selected.length;j++){ let t = parseInt(selected[j]); s += rel[i][t]; } //console.log(s); if(tmap.has(s)) return false; tmap.set(s, true); } return true; } function perm(start,depth,selected,n){ if(n === depth){ let state = checkUniq(selected); if(state){ console.log(selected) mini.set(selected,true); answer++; } return; } for(let i = start;i<maxN;i++){ let temp = "" + i; let s = selected + i; if(mini.has(s) || mini.has(temp)){ continue; } perm(i+1,depth+1,s,n); } } function solution(relations) { maxN = relations[0].length; rel = relations; //console.log(n) for(let i =1;i<=maxN;i++){ //console.log("") perm(0,0,"",i); } return answer; } (function solve(){ let relations = [["100","ryan","music","2"],["200","apeach","math","2"],["300","tube","computer","3"],["400","con","computer","4"],["500","muzi","music","3"],["600","apeach","music","2"]]; console.log(solution(relations)); })();
import * as React from 'react'; export default class About extends React.Component { render() { return ( <div> <h1>关于我们</h1> <h2>专业的FE</h2> </div> ); } }
import _defineProperty from "@babel/runtime/helpers/defineProperty"; import _slicedToArray from "@babel/runtime/helpers/slicedToArray"; function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } import React from 'react'; import Spinner from '@ctkit/spinner'; import Router from './Router'; import { Helmet } from "react-helmet"; export default (function (_ref) { var id = _ref.id, config = _ref.config, routes = _ref.routes, layout = _ref.layout; var _React$useState = React.useState(false), _React$useState2 = _slicedToArray(_React$useState, 2), loaded = _React$useState2[0], setLoaded = _React$useState2[1]; React.useEffect(function () { setTimeout(function () { return setLoaded(true); }, 1200); }, []); if (!loaded) return React.createElement("div", { className: "text-center", style: { padding: 100 } }, React.createElement(Spinner, null)); return React.createElement(React.Fragment, null, React.createElement(Helmet, null), React.createElement(Router, { routes: routes, layout: layout, config: _objectSpread({}, config, { appId: id }) })); });
alert("JS is cool"); //alert doesn't work in node //about:blank - when using the console let color = prompt("What's your favorite color?"); let result = confirm("You are dumb!"); // true or false return via cancel or okay console.log("This is less obtrusive. Color = ", color, " boolean=", result); /* this is the start of a multiline comment, and this is the ending. */ /* JavaScript has 6 primitive data types, but we'll only talk about 5 of them. string - var greeting = "hello"; number - var favoriteNum = 33; boolean - var isAwesome = true; undefined - var foo; or var setToUndefined = undefined; null - var empty = null; the other is a symbol */ typeof ""; //- "string" typeof 5; //- "number" typeof false; //- "boolean" typeof Symbol(); //- "symbol" typeof undefined; //- "undefined" typeof null; // hmmm, this is not what we expect, it returns "object"! parseInt("2"); // 2 parseFloat("2"); // 2 parseInt("3.14"); // 3 parseFloat("3.14"); // 3.14 parseInt("2.3alkweflakwe"); // 2 parseFloat("2.3alkweflakwe"); // 2.3 parseInt("w2.3alkweflakwe"); // NaN (not a number) parseFloat("w2.3alkweflakwe"); // NaN (not a number) //A nice shorthand for this conversion is the unary operator +: +"2"; // 2 +"3.14"; // 3.14 +"2.3alkweflakwe"; // NaN +"w2.3alkweflakwe"; // NaN //Converting to a boolean: !! var greeting = "hi"; var nothing = 0; !!greeting; // true !!nothing; // false //Difference between == and === //== allows for type coercion of the values, while === does not. //in fact, === is sometimes referred to as the "strict" equality operator, //while == is sometimes referred to as the "loose" equality operator // 1. 5 + "hi"; // "5hi" // 2. if ("foo") { console.log("this will show up!"); } // 3. if (null) { console.log("this won't show up!"); } // 4. +"304"; // 304 "" + 2; // "2" 5 == "5"; // true 5 === "5"; // false "true" === true; // false "true" == true; // false true == 1; // true true === 1; // false undefined === null; // false undefined == null; // true /* In JavaScript there are 6 falsey values: 0 "" null undefined false NaN (short for not a number) */ !!false //false !!-1 //true !!-0 //false !![] //true !!{} // true !!"" //false !!null //false //switch var feeling = prompt("How are you feeling today?").toLowerCase(); // what do you think the .toLowerCase does at the end? switch(feeling){ case "happy": console.log("Awesome, I'm feeling happy too!"); break; case "sad": console.log("That's too bad, I hope you feel better soon."); break; case "hungry": console.log("Me too, let's go eat some pizza!"); break; default: console.log("I see. Thanks for sharing!"); } 5 % 3 === 2 // true (the remainder when five is divided by 3 is 2) var num = prompt("Please enter a whole number"); if ( num % 2 === 0 ) { console.log("the num variable is even!") } else if ( num % 2 === 1) { console.log("the num variable is odd!") } else { console.log("Hey! I asked for a whole number!"); } var num = Math.random(); if (num > .5){ console.log("Over 0.5 ", num) } else { console.log("Under 0.5 ", num) } // falsey - 0, "", false, null, undefined and NaN.
/** * Scale one point * @param p * @param scale * @returns {{x: number, y: number}} */ export function scaleCoOridnate(p, scale) { return {x: p.x * scale.x, y: p.y * scale.y} } /** * Scale all points in curve * @param curve * @param scale * @returns {Array} */ export function scaleCurveCoOrdinates(curve, scale) { return curve.map((p) => scaleCoOridnate(p, scale)); } /** * Scale an array of curves * @param curves * @param scale */ export function scaleCurvesCoOrdinates(curves, scale) { return curves.map(curve => scaleCurveCoOrdinates(curve, scale)); } /** * returns an array by flattening the x, y co-ordinates of the points in the curve * * @param curve * @returns {Array} */ export function flattenCurve(curve) { const flat = []; curve && curve.map(p => { flat.push(p.x); flat.push(p.y); }); return flat; } /** * @returns initial state of the game */ export function initialGameState() { return { currentCurveIdx: 0, currentPointIdx: 0, nextCurveIdx: 0, nextPointIdx: 1 }; } /** * Given an array of curves, and the current state of the game, * calculates the next state of the game. * * @param curves * @param currentState * @returns nextState */ export function calculateNextState(curves, currentState) { if (curves[currentState.currentCurveIdx] && curves[currentState.currentCurveIdx].length > currentState.nextPointIdx + 1) { console.log("moving to the next point"); return { currentCurveIdx: currentState.currentCurveIdx, currentPointIdx: currentState.nextPointIdx, nextCurveIdx: currentState.currentCurveIdx, nextPointIdx: currentState.nextPointIdx + 1 } } else if (curves.length > currentState.currentCurveIdx + 1) { console.log("jumping to the next curve"); return { currentCurveIdx: currentState.currentCurveIdx + 1, currentPointIdx: 0, nextCurveIdx: currentState.currentCurveIdx + 1, nextPointIdx: 1 } } else { console.log("end of the drawing"); return { currentCurveIdx: curves.length - 1, currentPointIdx: curves[curves.length - 1].length - 1, nextCurveIdx: curves.length - 1, nextPointIdx: curves[curves.length - 1].length - 1 }; } } export function isCloseProximity(point1, point2, delta) { return Math.abs(point1.x - point2.x) < delta && Math.abs(point1.y - point2.y) < delta; }
$(document).ready(function(){ $("#setUser .cta.part1").click(function(e){ e.preventDefault(); e.stopPropagation(); var x = $("#userEmail").val(); if(!x || !validateEmail(x)) { $("#userEmail").addClass("error").focus(); return false; } else { var usr = fetchUser(x); $("#part1, #part2").slideToggle(200); } }); $('input[type="radio"]').change(function(){ $(this).parents(".questionBlock").removeClass("error"); }) $("#part2 .cta.back").click(function(e){ e.preventDefault(); e.stopPropagation(); $("#part2, #part1").slideToggle(200); }); $("#part3 .cta.back").click(function(e){ e.preventDefault(); e.stopPropagation(); $("#part3, #part2").slideToggle(200); }); $("#part4 .cta.back").click(function(e){ e.preventDefault(); e.stopPropagation(); $("#part4, #part3").slideToggle(200); }); $("#part2 .cta.proceed").click(function(e){ e.preventDefault(); e.stopPropagation(); $("#part2, #part3").slideToggle(200); }); $("#part3 .cta.proceed").click(function(e){ e.preventDefault(); e.stopPropagation(); if(validatePart3()){ storeDetails("#part2"); $("#part4, #part3").slideToggle(200); } }); $("#part4 .cta.finish").click(function(e){ e.preventDefault(); e.stopPropagation(); if(validatePart4()){ if(storeDetails("#part3")) { saveResult(); } } }); }); function validatePart3(){ if($('#part3 input[type="radio"]:checked').length == 12) { return true; } else { $('#part3 input[type="radio"]').each(function(){ if(!$(this).is(":checked") && !$(this).siblings('input[type="radio"]').is(":checked")){ $(this).parents(".questionBlock").addClass("error"); showPop("All questions have to be answered"); } else { $(this).parents(".questionBlock").removeClass("error"); } }); return false; } } function validatePart4(){ if($('#part4 input[type="radio"]:checked').length == 12) { return true; } else { $('#part4 input[type="radio"]').each(function(){ if(!$(this).is(":checked") && !$(this).siblings('input[type="radio"]').is(":checked")){ $(this).parents(".questionBlock").addClass("error"); showPop("All questions have to be answered"); } else { $(this).parents(".questionBlock").removeClass("error"); } }); return false; } } function saveResult(){ // } function storeDetails(sel){ // } function fetchUser(email){ // } function getData(url) { var result = null; attachLoader(); $.ajax({ url: url, type: 'get', dataType: 'json', async: false, success: function(data) { result = data; }, error: function(xhr, status, thrown) { showPop(thrown); } }); return result; } function showModalMessage(arg) { $('.messageModal').detach(); var modalCard = '<div class="messageModal"><div class="messageModalInner inner"><a class="close">&#10060;</a><div class="modalContent"></div><button class="modalCta">Close</button></div></div>'; var message = either(arg["message"],arg["content"]); var duration = either(arg["duration"],3000) ; $('body').append(modalCard); if(arg && arg["class"]) { $(".messageModal").addClass(arg["class"]); var innerClass = arg["class"]; innerClass += "Inner"; $(".messageModal .messageModalInner").addClass(innerClass); } if(arg && arg["closable"] && arg["closable"] != "1") { $(".messageModal .messageModalInner .close, .messageModal .messageModalInner .modalCta").detach(); } if(arg && arg["nobutton"]) { $(".messageModal .messageModalInner .modalCta").detach(); } if(arg["width"]) // small, wide, xl, xxl { $('.messageModal').addClass(arg["width"]); } $('.messageModal .modalContent').html(message); $('.messageModal').fadeIn(150).css("display","flex"); if (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) { var innerhght = $(".messageModalInner").height() + 40 + "px"; $(".messageModalInner").css({ "position":"absolute", "margin":"auto", "left":"0", "right":"0", "top":"0", "bottom":"0", "height":innerhght }) } if(!arg || arg["timed"] == undefined || arg["timed"] == null || isNaN(arg["timed"]) || arg["timed"] == "1") { setTimeout(function(){ $('.messageModal').fadeOut(150); },duration); } } $(document).on("click", ".messageModal .modalCta, .messageModal .close", function(e){ e.preventDefault(); e.stopPropagation(); $('.messageModal').fadeOut(150); }); //either value, preferably first arguement function either(arg1,arg2) { if(arg1 === undefined || arg1 === null) { return arg2; } else { return arg1; } } function showPop(msg){ showModalMessage({"message":msg,"nobutton":true}); } function testName(name) { var rx = /^[a-zA-Z ]+$/; return rx.test(name); } function validateEmail(mail) { var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i; return re.test(mail); } function isDate(value) { if(!value) { return false; } var arr = value.split("-"); var va = parseInt(arr[0]); var vb = parseInt(arr[1]); var vc = parseInt(arr[2]); if (!value.length === 10 || !arr.length === 3) { return false; } else if(!arr[0].length === 2 || arr[0] === '' || isNaN(arr[0]) || !isValidDateForMonth(va,vb,vc)) { return false; } else if(!arr[1].length === 2 || arr[1] === '' || isNaN(arr[1])) { return false; } else if(!arr[2].length === 4 || arr[2] === '' || isNaN(arr[2])) { return false; } else { return true; } } function isValidDateForMonth(vdate,vmonth,vyear) { switch (vmonth) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: if(parseInt(vdate) < 1 || parseInt(vdate) > 31) { return false; } else { return true; } break; case 4: case 6: case 9: case 11: if(parseInt(vdate) < 1 || parseInt(vdate) > 30) { return false; } else { return true; } break; case 2: if(isLeapYear(vyear)) { if(parseInt(vdate) < 1 || parseInt(vdate) > 28) { return false; } else { return true; } } else { if(parseInt(vdate) < 1 || parseInt(vdate) > 27) { return false; } else { return true; } } break; } }
import { Meteor } from 'meteor/meteor'; import { Recipes } from '../imports/model/recipes.js'; import '../imports/ui/common/header.js'; import '../imports/ui/common/footer.js'; import '../imports/ui/home/home.js'; import '../imports/ui/about/about.js'; import '../imports/ui/search/search.js'; import '../imports/ui/recipe/recipe.js'; import '../imports/ui/create/create.js'; import '../imports/ui/myrecipes/myrecipes.js'; import '../imports/ui/edit/edit.js'; checkSignedIn = function() { var currentUser = Meteor.userId(); if (currentUser) { this.next(); } else { this.render("not-signedIn"); } } // routing by Iron Router // http://meteortips.com/second-meteor-tutorial/iron-router-part-1/ Router.route('/', { name: 'home', template: 'home', data: function() { rlist = Recipes.find({}).fetch(); return { trending: rlist, }; }, waitOn: function() { return Meteor.subscribe('recipesLastest', 4); }, onBeforeAction: function() { var currentUser = Meteor.userId(); if (currentUser) { this.next(); } else { // for the moment, home content is not dependent on user. Same stuff // will have to render different template/modify template for non-users // this.render("about"); this.next(); } }, }); // ex: /about Router.route('/about', { name: 'about', template: 'about', }); // ex: /search?q=bread Router.route('/search', { name: 'search', template: 'search', }); // ex: /my-recipes Router.route('/my-recipes', { name: 'my-recipes', template: 'myrecipes', data: function() { rlist = Recipes.find({}).fetch(); return rlist; }, waitOn: function() { return Meteor.subscribe('recipesByMe'); }, onBeforeAction: checkSignedIn, }); // ex: /create Router.route('/create', { name: 'create', template: 'create', onBeforeAction: checkSignedIn, }); // ex: /recipe/1mc0ifnrWu4 Router.route('/recipe/:_id', { name: 'recipe', template: 'recipe', data: function() { var recipeId = this.params._id; r = Recipes.findOne({ _id: recipeId }); return r; }, waitOn: function() { return Meteor.subscribe('recipeById', this.params._id); }, }); // ex: /edit/1mc0ifnrWu4 Router.route('/edit/:_id', function () { // redirect Router.go('edit', { _id: this.params._id }); }); // ex: /recipe/edit/1mc0ifnrWu4 Router.route('/recipe/edit/:_id', { name: 'edit', template: 'edit', data: function() { var recipeId = this.params._id; r = Recipes.findOne({ _id: recipeId }); return r; }, waitOn: function() { return Meteor.subscribe('recipeById', this.params._id); }, onBeforeAction: function() { var currentUser = Meteor.userId(); // check user is signed in if (!currentUser) { this.render("not-signedIn"); } // chech user owns recipe // as a possible security question, is data read on client?? // btw this evals to true for recipes with no owner and user not signed in // hence must check if user signed in first else if (Router.current().data().owner != currentUser) { this.render("access-denied"); } // all gucci else { this.next(); } }, }); Router.configure({ layoutTemplate: 'main', loadingTemplate: 'loading', notFoundTemplate: 'not-found', });
// ///////////////////////////////////////////////////////////////////////////// // Actions // ///////////////////////////////////////////////////////////////////////////// export const ADD_SESSION = 'ADD_SESSION'; export const UPDATE_SESSION = 'UPDATE_SESSION'; export const DELETE_SESSION = 'DELETE_SESSION'; export function addSession (data) { return { type: ADD_SESSION, data }; } export function updateSession (sessionId, data) { return { type: UPDATE_SESSION, sessionId, data }; } export function deleteSession (sessionId) { return { type: DELETE_SESSION, sessionId }; } // ///////////////////////////////////////////////////////////////////////////// // Reducer // ///////////////////////////////////////////////////////////////////////////// const initialSessionsState = [ ]; export default function sessionsReducer (state = initialSessionsState, action) { switch (action.type) { case ADD_SESSION: { const { data } = action; return [...state, data]; } case DELETE_SESSION: { const { sessionId } = action; return state.filter(s => s.id !== sessionId); } // Session specific reducers: case UPDATE_SESSION: case REGISTER_HIT: { const { sessionId } = action; const sessionIdx = state.findIndex(s => s.id === sessionId); if (sessionIdx < 0) throw new Error(`Session not found: ${sessionId}`); const session = state[sessionIdx]; return Object.assign([], state, { [sessionIdx]: singleSessionReducer(session, action) }); } default: return state; } } // ///////////////////////////////////////////////////////////////////////////// // Actions // ///////////////////////////////////////////////////////////////////////////// export const REGISTER_HIT = 'REGISTER_HIT'; export function registerHit (sessionId, round, arrow, data) { return { type: REGISTER_HIT, sessionId, round, arrow, data }; } // ///////////////////////////////////////////////////////////////////////////// // Reducer // ///////////////////////////////////////////////////////////////////////////// export function singleSessionReducer (state = {}, action) { switch (action.type) { case REGISTER_HIT: { const { round, arrow, data } = action; const hits = Object.assign([], state.hits, { [round]: Object.assign([], state.hits[round] || [], { [arrow]: data }) }); return { ...state, hits }; } case UPDATE_SESSION: return { ...state, ...action.data }; default: return state; } }
import { GET_BLOGS, SELECTED_BLOG } from "../ActionTypes/ActionTypes"; const initialValues = { blogs: [], }; export const BlogReducer = (state = initialValues, action) => { switch (action.type) { case GET_BLOGS: { return { ...state, blogs: action.payload, }; } default: return state; } }; export const SingleBlogReducer = (state = {}, { type, payload }) => { switch (type) { case SELECTED_BLOG: { return { ...state, ...payload }; } default: return state; } };
const InlineStyles = [ { value: 'Bold', style: 'BOLD' }, { value: 'Italic', style: 'ITALIC' }, { value: 'Underline', style: 'UNDERLINE' }, { value: 'Strikethrough', style: 'STRIKETHROUGH' }, { value: 'Code', style: 'CODE' } ]; const StyleMap = { 'HIGHLIGHT': { 'backgroundColor': 'red', 'color': 'white', }, 'CODESECTION': { 'backgroundColor': 'orange', 'color': 'white', 'border': '0.3em solid orange', 'borderRadius': '5px', 'margin': '20px', 'fontWeight': 'bold', } }; export {InlineStyles, StyleMap}
// if number of teaspoons divides into 4, then convert to tablespoons // but if there's leftover, divide const convert = require('convert-units'); // groups of what measurements can be added const canBeAddedLookup = [ ['#'], ['ml', 'tsp', 'tbsp', 'fl oz', 'cup', 'pt', 'l', 'qt', 'gal'], ['g', 'oz', 'lb'], ]; const canBeAdded = (m1, m2) => { if (m1 === m2) return true; return canBeAddedLookup.find(g => g.find(t => t === m1)).includes(m2); }; // return { quantity: x, measurement: y } // m1 is grocery list item, m2 is new ingredient (adding new ingredient to grocery list) const standardize = { // use the library's nomenclature 'fl oz': 'fl-oz', 'tbsp': 'Tbs', 'pt': 'pnt', }; function roundToTwo(num) { return +(Math.round(num + "e+2") + "e-2"); } const addIngredient = (q1, m1, q2, m2) => { let q = q1 + q2, m = m1; if (m1 === m2) return { quantity: `${q}`, measurement: m }; const arr = canBeAddedLookup.find(g => g.find(t => t === m1)); const index1 = arr.findIndex(t => t === m1); const index2 = arr.findIndex(t => t === m2); if (index1 > index2) { // convert m2 to m1 q2 = convert(q2).from(standardize[m2] || m2).to(standardize[m1] || m1); m = m1; } else { // convert m1 to m2 q1 = convert(q1).from(standardize[m1] || m1).to(standardize[m2] || m2); m = m2; } q = roundToTwo(q1 + q2); return { quantity: `${q}`, measurement: m }; }; module.exports = { addIngredient, canBeAdded, };
import { useState, useEffect } from 'react'; const useDevice = (props) => { const mediaMatch = window.matchMedia(`(max-width: ${props}px)`); const [matches, setMatches] = useState(mediaMatch.matches); useEffect(() => { const handler = e => setMatches(e.matches); mediaMatch.addListener(handler); return () => mediaMatch.removeListener(handler); }); return matches; } export default useDevice;
var Job = require("./Job.js") class JobCollection { constructor() { this.jobs = [] } addJob(job) { this.jobs.push(job) } createJob(employerUrlSlug, description, jobType, salary) { var newJob = new Job(employerUrlSlug, description, jobType, salary) this.jobs.push(newJob) } sendToJson (file) { var fs = require('fs') var jobsStringified = JSON.stringify(this.jobs) fs.writeFile(file, jobsStringified, 'utf-8') } readJobsJson (file) { var fs = require('fs') var fileContents = fs.readFileSync(file, 'utf-8') var data = JSON.parse(fileContents); if (data.length > 0) { for (var job of data) { this.createJob(job.employer, job.description, job.jobType, job.salary) } } } } module.exports = JobCollection
var mysql = require("mysql"); var inquirer = require("inquirer"); var connection = mysql.createConnection({ host: "localhost", port: 3306, //make sure this is the port on computer where running this code user: "root", password: "Password1", //comment this out when push database: "employee_tracker" }); function Add(what) { switch (what) { case "Add an employee": function CreateEmployee() { //gets information that we need to add employee info to the data tables inquirer.prompt([ { type: "input", name: "first_name", message: "What is the employee's first name?" //add some type of validation in here? }, { type: "input", name: "last_name", message: "What is the employee's last name?" }, { type: "input", name: "title", message: "What is the employee's title?" }, { type: "input", name: "salary", message: "What is the employee's salary?" }, { type: "input", name: "department", message: "What department does the employee work in?" }, { type: "list", message: "Does the employee have a manager", name: "manager", choices: ["Yes", "No"] } ]).then(function(data) { connection.query( //check if department exists "INSERT INTO department SET ?", { name: data.department }, function(err) { if (err) throw err; } ); // // new Add().addEmp(data); // }); } return "Option 1"; // break; case "Add a role": async function CreateRole() { await inquirer.prompt([ { type: "input", name: "title", message: "What is the position title?" }, // { // type: "input", // name: "dept_id", // message: "What department is the position in?" // }, { type: "input", name: "salary", message: "What is the salary of the position?" } ]); } return "Ok here"; // break; case "Add a department": function CreateDepartment() { inquirer.prompt([ { type: "input", name: "dept_name", message: "What is the department name?" } ]); } return "Different"; // break; } } module.exports = Add;
let $show = document.querySelector('.show') // A function that goes to the start of the show let setFirstSlide = () => { //finds first element let $first = document.querySelector('.slide:first-child') //adds a class to it $first.classList.add('current') } // A function that goes to the end of the show let setLastSlide = () => { } // Remove ".current" from all ".slide" let unsetSlides = () => { } // Previous slide let prevSlide = () => { } // Next slide let nextSlide = () => { //1. locate the current slide let $curr = document.querySelector('.current') //2. Remove the current class $curr.classList.remove('current') //3. find the next slide let $next = $curr.nextElementSibling if ($next != null){ //there is no next slide //4. If it exists, add the current class $next.classList.add('current') } else { //5. if it doesn't exist, go back to the beginning setFirstSlide() } } // When the interface has fully loaded... let windowLoaded = () => { //check if there's a hash set, if so start at that slide //window.location.hash //else, use the first slide //setup the first slide setFirstSlide() //add all the event listeners document.querySelector('#next').addEventListener('click', nextSlide) } window.addEventListener('load', windowLoaded)
import React, { useContext, useEffect } from 'react' import Link from 'next/link' import { SisuContext } from '../contexts/SisuContenxt' const screenData = { headerText: 'Bem-vindo ao SimulaSisu' } export default function Home () { const { headerText, changeText } = useContext(SisuContext) if (headerText !== screenData.headerText) { useEffect(() => { changeText(screenData.headerText) }, []) } return ( <> <h1>Home</h1> <Link href="/about">About</Link> </> ) }
function hnt(n,a,b,c){ if(n===1){ console.log("Move "+n+" from "+a+" to "+c); } else{ hnt(n-1,a,c,b); console.log("Move "+n+" from "+a+" to "+c); hnt(n-1,b,a,c); } } module.exports = hnt;
import React, {Component} from 'react'; import NavBar from './Navbar.jsx'; import {browserHistory} from "react-router"; import {Image} from "semantic-ui-react" import welcome1 from "../img/welcome3.png"; import welcome2 from "../img/welcome4.png"; import header from "../img/header.png"; import star from "../img/star.png"; import pusher from "../img/button.png"; import audio from "../sounds/door.mp3" import audio2 from "../sounds/flash.mp3" class Home extends Component { constructor() { super() this.state = { visible: true, audio: new Audio(audio), audio2: new Audio(audio2), moved:false } this.toggle = this.toggle.bind(this) } componentWillMount() { if (this.props.location.state && this.props.location.state.visible === false) { this.setState({visible: false}) } } go() { this.setState({moved:true}) this.state.audio2.play(); let nav =()=> browserHistory.push("/list"); setTimeout(nav , 2000) } toggle() { this.setState({visible: false}) this.state.audio.play(); } render() { const {visible} = this.state console.log(this); return ( <div> {/* <embed src="ton_fichier.mp3" autostart="true" loop="false" hidden="true"></embed> */} <Image className={visible ? "welcome1" : "welcome1bis"} onClick={() => this.toggle()} src={welcome1} style={{ height: "98vh" }}/> <Image className={visible ? "welcome2" : "welcome2bis"} onClick={() => this.toggle()} src={welcome2} style={{ height: "98vh" }}/> <div className={this.state.moved ? "move2":"move"}> <div className="wallpaper"> <NavBar/> <Image className="title" src={header}/> <Image className="star" src={star}/> <Image className="pusher" src={pusher} onClick={()=>this.go()}/> </div> </div> {/* <p className="paraph">Cliquez pour tous les attraper !</p> */} </div> ) } } export default Home;
import { useEffect, useState } from "react"; import "./css/App.css"; import 'bootstrap/dist/css/bootstrap.css'; import axios from "axios"; import Header from "./components/Header"; import Navigation from "./components/Navigation"; import Card from "./components/Card"; import ErrorPage from "./components/Card/ErrorPage"; function App() { const [nasa, setNasa] = useState({ response: {}, loading: true, date: new Date(), error: false }); const formattedDate = date => { const mydate = date.toLocaleDateString().split("/"); return `${mydate[2]}-${mydate[0]}-${mydate[1]}`; }; const apiKey = "DwJlsmcEi4JZIyBUKFEJlPMhx28CgmIjTb7Fvh3w"; const apiUrl = `https://api.nasa.gov/planetary/apod?api_key=${apiKey}&date=${formattedDate( nasa.date )}`; const getNasaData = () => { axios .get(apiUrl) .then(response => { setNasa({ ...nasa, response: response.data, loading: false, error: false, errorMessage: "" }); }) .catch(error => setNasa({ ...nasa, response: {}, loading: false, error: true, errorMessage: `Error ${error.response.data.code}: ${error.response.data.msg}` }) ); }; const handleDateChange = (date, to = "") => { to === "daybefore" ? setNasa({ ...nasa, date: new Date(new Date(date).setDate(new Date(date).getDate() - 1)), loading: true, error: false }) : to === "dayafter" ? setNasa({ ...nasa, date: new Date(new Date(date).setDate(new Date(date).getDate() + 1)), loading: true, error: false }) : setNasa({ ...nasa, date: new Date(date), loading: true, error: false }); }; useEffect(getNasaData, [nasa.date]); return ( <div className="App"> <Header /> <section className="content"> <Navigation nasa={nasa} setNasa={setNasa} handleDateChange={handleDateChange} /> <hr /> {nasa.loading ? ( <div className="spinner"></div> ) : nasa.error ? ( <ErrorPage nasa={nasa} setNasa={setNasa} /> ) : ( <Card nasa={nasa.response} /> )} </section> </div> ) } export default App;
import {getObjectExclude} from '../../common/common'; class EventHandler { constructor(props) { this.props = props; } toValue = (event='') => { if (event === null) { return ''; } else { return event.nativeEvent ? event.target.value : event; } }; onChange = (event) => { this.props.onChange(this.toValue(event)); }; onBlur = (event) => { this.props.onBlur(this.toValue(event), event); }; onSearch = (event) => { this.props.onSearch(this.toValue(event)); }; } const replaceEvent = (props, handler) => { const events = ['onChange', 'onBlur', 'onSearch']; let callback = events.reduce((result, event) => { if (props[event]) { result[event] = handler[event]; } return result; }, {}); return Object.assign({}, getObjectExclude(props, events), callback); }; const eventWrapper = (props) => { const handler = new EventHandler(props); return replaceEvent(props, handler); }; export default eventWrapper