text
stringlengths
7
3.69M
class Checkout { //Checkout part 1 get firstName () { return $('input#first-name') }; get lastName () { return $('input#last-name') }; get postalCode () { return $('input#postal-code') }; get cancelBtn () { return $('form > div.checkout_buttons > button#cancel') }; get continueBtn () { return $('form > div.checkout_buttons > input') }; get textError () { return $('div.error-message-container > h3').getText() }; get buttonError () { return $('form > div > div.error-message-container.error > h3 > button.error-button') }; //Checkout part 2 get totalAmount () { return $('#checkout_summary_container > div > div.summary_info > div.summary_subtotal_label').getText() }; get secondCancelBtn () { return $('#checkout_summary_container > div > div.summary_info > div.cart_footer > button#cancel') }; get finishBtn () { return $('#checkout_summary_container > div > div.summary_info > div.cart_footer > button#finish') }; get backhomeBtn () { return $('#contents_wrapper > div.checkout_complete_container > button#back-to-products') }; get arrayOfPrices () { return $$('div.cart_list > div.cart_item > div.cart_item_label > div.item_pricebar > div.inventory_item_price') }; get headerForCheckout () { return $('h2.complete-header').getText() }; get textCheckout () { return $('div.complete-text').getText() }; get titleCheckout (){ return $('div.header_secondary_container').getText() } // Functions setName(name){ this.firstName.click(); this.firstName.setValue(name); }; setLastName(lastname){ this.lastName.click(); this.lastName.setValue(lastname); }; setPostalCode(number){ this.postalCode.click(); this.postalCode.setValue(number); }; setInputs(){ this.firstName.click(); this.firstName.setValue("Vicenzo"); this.lastName.click(); this.lastName.setValue("Mantilla"); this.postalCode.click(); this.postalCode.setValue("2000"); this.continueBtn.click(); }; } module.exports = new Checkout();
const d3 = require('d3'); /* Add any other packages */ require('dotenv').config(); /* Pull in secrets from the .env file, if needed */ const apiKey = process.env.API_KEY; const anotherSecret = process.env.ANOTHER_SECRET;
var connection = require('../connection'); function cleaning() { this.addcleaning = function (addcleaning, res) { connection.acquire(function (err, con) { con.query('insert into cleaning set ?', addcleaning, function (err, result) { con.release(); if (err) { res.send({ status: 1 , message: 'cleaning creation failed' }); } else { res.send({ status: 0 , message: 'cleaning created successfully' }); } }); }); }; this.editcleaning = function (editcleaning, res) { connection.acquire(function (err, con) { con.query('update cleaning set ? where cleaning.clid = ?', [editcleaning[0], editcleaning[0].clid], function (err, result) { con.release(); if (err) { res.send({ status: 1 , message: 'cleaning update failed' }); } else { res.send({ status: 0 , message: 'cleaning updatesuccessfully' }); } }); }); }; this.deletecleaning = function (clid, res) { connection.acquire(function (err, con) { con.query('delete from cleaning where cleaning.clid = ?', [clid], function (err, result) { con.release(); if (err) { res.send({ status: 1 , message: 'Failed to delete cleaning' }); } else { res.send({ status: 0 , message: 'cleaning Deleted successfully' }); } }); }); }; this.getcleaning = function (clid, res) { connection.acquire(function (err, con) { con.query('select * from cleaning where clid =?', [clid], function (err, result) { con.release(); res.send(result); }); }); }; this.listcleaning = function (res) { connection.acquire(function (err, con) { con.query('select * from cleaning order by clid desc', function (err, result) { con.release(); res.send(result); }); }); }; }; module.exports = new cleaning();
// [work] const work_form = { name: "이름", data: "날짜", from: "시작시간", to: "종료시간", area: "활동장소", }; const work_example = { name: "한명훈", data: "2021/07/26", from: "13:00", to: "18:00", area: "SW라운지", }; // [activity] const activity_form = { who: "활동자 이름", what: { title: "활동명", detail: "활동 상세 내용" }, when: { data: "활동 날짜", time: "활동 시간" }, image: "이미지 링크", }; const activity_example = { who: "한명훈", what: { title: "3D 프린터 제작 과정 설명", detail: "3D 프린터 이미지 파일을 가져왔으나 기계를 사용할 줄 모르는 학생에게 관련 프로그램 및 장치 작동법을 설명했다.", }, when: { data: "2021/07/26", time: "14:20" }, image: "https://wp-blog.toss.im/wp-content/uploads/2020/07/3V5A3982-%E1%84%89%E1%85%A1%E1%84%87%E1%85%A9%E1%86%AB.jpg", }; const report_data = { works: [work_example, work_example], activities: [activity_example, activity_example, activity_example], QAes: [], }; function get_work_time(report_data) { var result = ""; report_data["works"].forEach((work) => { result += `<br>* ${work["from"]} ~ ${work["to"]}`; }); return result.slice(4); } function get_work_area(report_data) { var result = ""; report_data["works"].forEach((work) => { result += `<br>* ${work["area"]}`; }); return result.slice(4); } function get_activity(report_data) { var result = ""; report_data["activities"].forEach((activity) => { result += `<br>* ${activity["what"]["title"]}`; }); return result.slice(4); } function get_image(report_data) { const images = []; report_data["activities"].forEach((activity) => { images.push(activity["image"]); }); return images; } function write_form(report_data) { const name = report_data["works"][0]["name"]; const date = get_work_time(report_data); const area = get_work_area(report_data); const activity = get_activity(report_data); const images = get_image(report_data); const form = document.querySelector("#report"); form.innerHTML = ` <div class="container"> <div class="item center"> <h2>SW 라운지 튜터 활동보고서</h2> </div> <div class="item center border b-c">활동시간</div> <div class="item v-m border">${date}</div> <div class="item center border b-c">활동장소</div> <div class="item v-m border">${area}</div> <div class="item center border b-c">활동</div> <div class="item v-m border">${activity}</div> <div class="item center border b-c">Q&A</div> <div class="item v-m border">Q&A 내용</div> <div class="item center border b-c">활동 사진</div> <div class="item center border"><img src="${images[0]}"></div> <div class="item center border"><img src="${images[1]}"></div> <div class="item center border"><h5>2021년 7월 26일<br />성명: ${name} (인)</h5></div> <div class="item center"> <h3>제주대학교 SW융합교육원장 귀하</h3> </div> </div>`; } write_form(report_data);
import React, {Component} from 'react'; import PostItem from '../../../components/PostItem/index'; import styles from './index.css'; import loadingComponentWrapper from '../../../utils/loadingComponent'; class List extends Component { constructor(props) { super(props); } render() { const { list = [] } = this.props; return <div className={styles.container}>{list.map(item => <PostItem key={item.title} post={item}></PostItem>)}</div>; } } export default loadingComponentWrapper(List, props => !props.list || props.list.length == 0);
/* Angular app that defines two new directives: dashboard & chart Example: <div ng-app="components"> <dashboard server="http://0.0.0.0:6543"> <chart title="Downloads and Daily Users" id="chart1" fields="downloads_count,users_count" type="series"/> <chart title="Daily Users" id="chart2" fields="users_count" type="series"/> <chart title="Download counts per month" id="chart4" type="aggregate" field="downloads_count" interval="month"/> </dashboard> </div> */ var app = angular.module('components', []); app.directive('dashboard', function() { return { restrict: 'E', scope: {}, transclude: true, controller: function($scope, $element, $attrs) { this.server = $scope.server = $attrs.server; var charts = $scope.charts = []; this.addChart = function(chart) { charts.push(chart); } }, template: '<div class="tabbable">' + '<h3>Monolith Dashboard</h3>' + '<div class="tab-content" ng-transclude></div>' + '</div>', replace: true }; }); app.directive('chart', function() { return { require: '^dashboard', restrict: 'E', scope: {title: '@', id: '@', fields: '@', field: '@', type: '@', interval: '@'}, transclude: false, controller: function($scope, $element, $attrs) { var today = new Date(); var _30daysago = new Date(); _30daysago.setDate(today.getDate() - 30); $scope.today = $.datepicker.formatDate('mm/dd/yy', today); $scope._30daysago = $.datepicker.formatDate('mm/dd/yy', _30daysago); $scope.draw = function () { $scope.chart.draw(); $("#modal-" + $scope.id).modal('hide'); }; }, // XXX can this be externalized as a template ? // not an ugly string template: '<div><div class="chart" >' + // title '<h2 class="chart">{{ title }}</h2>' + // y axis legend '<div class="y_axis" id="y_axis-{{id}}"/>' + // actual chart '<div id="chart-{{id}}" style="height:300px; margin: 0 auto"/>' + // legend and change button '<div class="legend">' + '<a href="#modal-{{id}}" role="button" class="chart_btn btn" data-toggle="modal">Change</a>' + '<div id="legend-{{id}}"></div>' + '<div style="clear:both"></div>' + '</div>' + // modal box '<div id="modal-{{id}}" class="modal hide fade">' + '<div class="modal-header">' + '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' + '<h3>Change "{{ title }}"</h3>' + '</div>' + '<div class="modal-body">' + '<form id="query-{{id}}"><fieldset>' + '<label for="startdate-{{id}}">Start Date</label>' + '<input type="text" id="startdate-{{id}}" value="{{_30daysago}}"/>' + '<label for="enddate-{{id}}"> End date </label>' + '<input type="text" id="enddate-{{id}}" value="{{today}}"/>' + '<label for="appid-{{id}}"> App id (1 to 100)</label>' + '<input type="text" id="appid-{{id}}" value="1"/>' + '<br/>' + // err well '<button type="submit" class="chart_btn btn" ng-click="draw()">Update</button>' + '</fieldset></form></div></div>' + '</div>{{end}}</div>', replace: true, link: function(scope, element, attrs, dashboard) { dashboard.addChart(scope); attrs.$observe('end', function(value) { setTimeout(function() { if (scope.type == 'series') { scope.chart = new MonolithSeries(scope.id, dashboard.server, "#startdate-" + scope.id, "#enddate-" + scope.id, "#appid-" + scope.id, "chart-" + scope.id, scope.title, scope.fields); } if (scope.type == 'aggregate') { scope.chart = new MonolithAggregate(scope.id, dashboard.server, "#startdate-" + scope.id, "#enddate-" + scope.id, "#appid-" + scope.id, "chart-" + scope.id, scope.title, scope.field, scope.interval); } scope.chart.draw(); }); }, 1000); }, }; })
"use strict"; function Prefab(game) { var prefabs = game.prefabs = game.prefabs || new Object(); //CREATION MANUELLE var player = BABYLON.Mesh.CreateSphere("player", 10, 2, game.scene); player.position = new BABYLON.Vector3(0, 3, 0); player.scaling = new BABYLON.Vector3(1, 0.2, 1); player.material = game.material.white; player.isVisible = false; var head = BABYLON.Mesh.CreateSphere("head", 10, 0.6, game.scene); head.position = new BABYLON.Vector3(0, 0.8, 0); head.scaling = new BABYLON.Vector3(1.5, 3, 1.5); head.parent = player; head.material = game.material.greenAlien; head.isVisible = false; prefabs.player = player; var laserBullet = BABYLON.Mesh.CreateSphere("bullet", 10, 0.5, game.scene); laserBullet.scaling = new BABYLON.Vector3(1.5, 0.25, 0.25); laserBullet.material = game.material.blueLaser; laserBullet.isVisible = false; prefabs.laserBullet = laserBullet; var bonus = BABYLON.Mesh.CreateSphere("bonus", 10, 0.5, game.scene); bonus.scaling = new BABYLON.Vector3(2, 2, 2); bonus.material = game.material.redAlien; bonus.isVisible = false; prefabs.bonus = bonus; //CREATION LOADED var ares = game.prefabs.ares; console.log(ares); ares.scaling = new BABYLON.Vector3(0.03, 0.03, 0.03); //ares.bakeCurrentTransformIntoVertices(); var orion = game.prefabs.orion; orion.scaling = new BABYLON.Vector3(1.5, 1.5, 1.5); var missile = game.prefabs.missile; missile.scaling = new BABYLON.Vector3(0.4, 0.4, 0.5); for (var index in prefabs) { prefabs[index].position = new BABYLON.Vector3(0, 3, 0); }; };
window.onload = function(){ // Exercise 1: // Define a filter function on the String object. The function accepts an array of strings that // specifies a list of banned words. The function returns the string after removing all the // banned words. // Example: // console.log("This house is not nice!".filter('not')); // Output: "This house is nice!" String.prototype.filter = function(arg) { return this.split(' ').filter(el => el !== 'not' || el === '').join(' '); }; console.log('Excersise 1') console.log('This is not not a fruit.'.filter('not')); // Exercise 2: // Write a BubbleSort algorithm on the Array object. Bubble sort is a simple sorting algorithm // that works by repeatedly stepping through the list to be sorted, // Example:[6, 4, 0, 3, -2, 1].bubbleSort(); // Output : [-2, 0, 1, 3, 4, 6] Array.prototype.bubbleSort = function() { const length = this.length; const arr = this; for(let i = 0; i < length - 1; i++) { for(let j = 0; j < length - 1; j++) { temp = arr[j]; if(temp > arr[j + 1]) { // swap value between arr[i] and arr[j] arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } return arr; }; console.log('Excersise 2') console.log([6, 4, 0, 3, -2, 1].bubbleSort()); // Exercise 3: // Create an object called Teacher derived from a Person function constructor, and implement // a method called teach that receives a string called subject, and prints out: [teacher's name] // is now teaching [subject]. Create a Teacher object and call its teach method. // Also do the same thing using Object.create. When using Object.create you will need a // factory function instead of a function constructor in order to pass parameters such as // ‘name’ to be set in the prototype. // 1. function Person(name){ this.name = name; } Person.prototype.teach = function(subject){ console.log(this.name + " is now teaching " + subject); }; const Teacher = new Person('Tina 1'); Teacher.teach('WAP'); // 2. const Person2 = { name: 'Default', setName: function(name){ this.name = name; } } const Teacher2 = Object.create(Person2); Teacher2.teach = function(subject){ console.log(this.name + ' is now teaching ' + subject); } const tina = Object.create(Teacher2); tina.setName('Tina 2'); tina.teach('WAA'); // Exercise 4: // Write code that will create person, student, and professor objects. // • Person objects have // o name and age fields // o a greeting method that prints out: “Greetings, my name is [name] and I am // [age] years old.” // o a salute method that prints out: “Good morning!, and in case I dont see you, // good afternoon, good evening and good night!” // • Student objects inherit name, age, and salute from person. They also have a field // ‘major’ and have their own greeting method. Their greeting is “Hey, my name is // [name] and I am studying [major]. The greeting should be output to the console. // • Professor objects inherit name, age, and salute from person. They also have a field // ‘department’ and have their own greeting method. Their salutation is “Good day, // my name is [name] and I am in the [department] department.” Output it to the // console. // • Create a professor object and a student object. Call both the greeting and salutation // methods on each. // • Do this exercise once using the object prototype approach for inheritance and then // using the function constructor approach. Person3 = { name: 'Default Person', age: 28, greeting: function(){ console.log("Greetings, my name is " + this.name + " and I am " + this.age + " years old.") }, salute: function(){ console.log("Good morning!, and in case I dont see you, good afternoon, good evening and good night!"); } } Student = Object.create(Person3); Student.major = 'WAP'; Student.greeting = function(){ console.log("Hey, my name is " + this.name + " and I am studying " + this.major + ".") } Professor = Object.create(Person3); Professor.department = 'Dreier'; Professor.salute = function(){ console.log("Good day, my name is " + this.name + " and I am in the " + this.department + " department.") } nhan = Object.create(Student); nhan.name = 'Nhan'; nhan.age = '32'; nhan.greeting(); nhan.salute(); dinh = Object.create(Professor); dinh.name = 'Dinh'; dinh.age = '32'; dinh.greeting(); dinh.salute(); };
// 全局静态界面加载动画 export default { mounted() { this.$loading.show() setTimeout(() => { this.$loading.hide() }, 300) } }
import React, { Component } from 'react'; import { connect } from 'react-redux'; class FilterBarTemp extends Component { constructor(props) { super(props); this.categories = this.props.cards.reduce((arr, item) => { if (arr.indexOf(item['category']) === -1) { arr.push(item['category']); } return arr }, []); } render() { return ( <div className="filter-bar col-4"> Search string: <input type="text" name="" onChange={ e => this.props.onChangeSearchStr(e.target.value) }/> {this.categories.map(( item, index ) => <div className="filter-item" key={index}> <label> <input type="checkbox" value={item} onChange={ e => e.target.checked ? this.props.onAddSearchCategory(e.target.value) : this.props.onRemoveSearchCategory(e.target.value)} /> {item.toUpperCase()} </label> </div>)} </div> ) } } const mapStateToProps = state => ({ cards: state.cards }); export const FilterBar = connect( mapStateToProps, dispatch => ({ onChangeSearchStr: (str) => { dispatch({ type: 'CHANGE_SEARCH_STR', payload: str}) }, onAddSearchCategory: (item) => { dispatch({ type: 'ADD_SEARCH_CATEGORY', payload: item}) }, onRemoveSearchCategory: (item) => { dispatch({ type: 'REMOVE_SEARCH_CATEGORY', payload: item}) } }))(FilterBarTemp);
import React, { Component } from 'react' import { BrowserRouter as Router, Route } from 'react-router-dom' import App from './components/App' import Media from './components/Media' import Contact from './components/Contact' class Routes extends Component { render() { return ( <Router> <div> <Route exact path="/" component={App} /> <Route path="/contact" component={Contact} /> <Route path="/media" component={Media} /> </div> </Router> ) } } export default Routes
'use strict'; var layout = require('./components/layout/layout.html'); appRoute.$inject = ['$stateProvider', '$urlRouterProvider']; function appRoute($stateProvider, $urlRouterProvider) { $stateProvider .state('layout', { abstract: true, views: { layout: { template: layout } } }); $urlRouterProvider.otherwise('/'); } module.exports = appRoute;
// source: in_sdk_header.proto /** * @fileoverview * @enhanceable * @suppress {messageConventions} JS Compiler reports an error if a variable or * field starts with 'MSG_' and isn't a translatable message. * @public */ // GENERATED CODE -- DO NOT EDIT! goog.provide('proto.insider.sdk.DataProto'); /** * @enum {number} */ proto.insider.sdk.DataProto = { DATA_UPGRADE: 0, DATA_PARA_OPERATION: 1, DATA_ALARM: 2, DATA_HEART_BEAT: 3, DATA_AI: 4, DATA_PICTURE: 5 };
var mainApplicationModuleName = "mean"; var mainApplicationModule = angular.module(mainApplicationModuleName,["ngResource", "ngRoute","articles","usuarios","example","bootstrap","lp"]); mainApplicationModule.config(['$locationProvider',function($locationProvider){ $locationProvider.hashPrefix('!'); } ]); if(window.location.hash === '#_=_'){ window.location.hash = '#!'; } angular.element(document).ready(function(){ angular.bootstrap(document,[mainApplicationModuleName]); try { $(document.body).attr("ng-app", mainApplicationModuleName); } catch(e){ } }); mainApplicationModule.run(['$rootScope', function($rootScope) { $rootScope.page = { setTitle: function(title) { this.title = title + ' | Site Name'; } } }]);
// 10-asynchronous/01-get-posts/script.js - 10.1: chargement d'articles (() => { document.getElementById('run').addEventListener('click', () => { window.lib.getPosts((error, callback) => { callback.forEach(post); console.log(post); }); }); })();
const images = {}; images.hacktiv8 = require('./hacktiv8.png'); images.hactiv8Logo = require('./hactiv8-logo.jpg'); images.textJanjian = require('./text-janjian-v2.png'); images.iconJanjian = require('./icon-janjian-v2.png'); module.exports = images;
import axios from '@/libs/api.request' export function fetch(url,data,method){ method = method || 'POST' return new Promise((resolve,rejects)=>{ var datas = axios.request({ url , data, method }) resolve(datas) }) }
class Faq_item extends React.Component { state = { hidden: true } myFunction = () => { this.setState({ hidden: !this.state.hidden}); } render() { return ( <section> <article> <h1>{this.props.question}</h1><span onClick={this.myFunction}>{this.state.hidden ? "+" : "-"}</span> <p className={this.state.hidden ? "isHidden" : "isShown"}>{this.props.answer}</p> </article> <style jsx>{` .isHidden { display: none } .isShown { display: block } `} </style> </section> ); } } export default Faq_item;
import React from "react"; import "./Header.css"; import images from "../../images/images"; import { Link } from "react-router-dom"; const Header = ({ handleSignup, handleLogin }) => { return ( <div className="Header"> <nav className="nav navBar"> <Link to="/"> <img src={images.logo} className="logo" alt="Repify" /> </Link> <ul className="navItems"> <li className="navLink"> <Link className="links" onClick={handleLogin} to="/login"> Login </Link> <Link className="links" onClick={handleSignup} to="/register"> Signup </Link> </li> </ul> </nav> </div> ); }; export default Header;
const mongoose = require('mongoose'); module.exports = (req, res, next) => { try { mongoose.connect('mongodb://localhost:27017/ralali', { useNewUrlParser: true }); db = mongoose.connection; next() } catch (err) { res.status(500).json({ error: err }) } }
import Series from './Series'; import SeriesContainer from './SeriesContainer'; export default SeriesContainer(Series);
import DialogView from 'igui_root/src/scripts/widgets/DialogView'; import Router from 'igui_root/src/scripts/Router'; import template from 'igui_root/src/templates/widgets/modelDialogTemplate.html'; var ModelDialogView = DialogView.extend({ template: template, _resultProps: { titleIconClass: true, title: true, modalClass: true, navigateOnSubmit: true }, // The below attributes (may) need to be overrided titleIconClass: null, // e.g: 'icon-XXXX', title: null, // e.g: "Create/Modify XXXX", modalClass: 'modal-lg', navigateOnSubmit: false, _postRender: function () { this.listenTo(this.model, 'submitted', this.onSubmitted.bind(this)); }, onSubmitted: function() { this.close(); // model.is might not be set in bulk mode if(this.navigateOnSubmit && this.model.id) { if($('.modal').length) { $('.modal').on('hidden.bs.modal', () => this.navigateToModel()); } else { this.navigateToModel(); } } }, // Helper function for inheriting views navigateToModel: function() { // replace=true is needed so that when the user presses 'Back', he goes back straight // to the list view Router.navigate(this.model.modelType().toLowerCase() + 's/' + this.model.id, {replace: true}); } }, { _optionsToAttach: ['navigateOnSubmit'] }); export default ModelDialogView;
function formcheck(form){ var file = form.userfile.value; if (file.length == 0) { document.getElementById("check").style.color = "green"; document.getElementById("check").innerHTML = "Please enter a file"; return false; } file = file.toUpperCase(); var jpeg = file.indexOf(".JPG"); var png = file.indexOf(".PNG"); if (jpeg == -1 && png == -1) { document.getElementById("check").style.color = "red"; document.getElementById("check").innerHTML = "Please enter only valid image files" ; return false; } return true; }
// Всплывающая форма Обратный звонок var open = document.querySelector (".cat_menu--item--call"); var close = document.querySelector (".call_close"); var wind = document.querySelector(".window_call"); open.addEventListener("click", function(evt) { evt.preventDefault(); wind.classList.add("form_opened"); document.getElementById('grey_back').style.display = 'block' }); close.addEventListener("click", function(evt) { evt.preventDefault(); wind.classList.remove("form_opened"); document.getElementById('grey_back').style.display = 'none' }); // Мобильное меню var mobBut = document.querySelector (".but_menu"); var catMenu = document.querySelector (".cat_menu"); var catCall = document.querySelector (".cat_menu--item--call"); var mobClose = document.querySelector (".mob_close"); mobBut.addEventListener("click", function(evt) { evt.preventDefault(); catMenu.classList.add("mob_menu--open"); mobClose.classList.add("block_menu"); document.querySelector (".we").classList.add("block_menu"); document.querySelector (".services").classList.add("block_menu"); document.querySelector (".certificates").classList.add("block_menu"); document.querySelector (".rent").classList.add("block_menu"); document.querySelector (".photo").classList.add("block_menu"); document.querySelector (".contacts").classList.add("block_menu"); }); mobClose.addEventListener("click", function(evt) { catMenu.classList.remove("mob_menu--open"); mobBut.style.order = "-2"; mobClose.classList.remove("block_menu"); document.querySelector (".we").classList.remove("block_menu"); document.querySelector (".services").classList.remove("block_menu"); document.querySelector (".certificates").classList.remove("block_menu"); document.querySelector (".rent").classList.remove("block_menu"); document.querySelector (".photo").classList.remove("block_menu"); document.querySelector (".contacts").classList.remove("block_menu"); }); // Закрытие вспл. окон по Esc document.body.addEventListener('keyup', function (e) { var key = e.keyCode; if (key == 27) { document.querySelector('.window_call').classList.remove('form_opened'); document.getElementById('grey_back').style.display = 'none' }; }, false);
/* const initialState = { selectedControl: null, layoutRows: 10, layoutColumns: 3, } const reducer = (state = initialState, action) => { const newState = {...state}; switch(action.type) { case 'APPLY_PROPS': debugger console.log(`[reducer] APPLY_PROPS`); break; } return newState; }; export default reducer; */ import { combineReducers } from 'redux' import designer from './designerReducer' // Note: this naming affects the property of the state inside the container's mapToXXX import controlProps from './controlPropsReducer'; //import appSplitPane from './appReducer'; //import noobControl from './noobControlReducer'; const noobApp = combineReducers({ designer, controlProps, //appSplitPane //noobControl }) export default noobApp
/** * Copyright 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ goog.provide('audioCat.ui.menu.item.SaveToGoogleDriveItem'); goog.require('audioCat.action.ActionType'); goog.require('audioCat.service.EventType'); goog.require('audioCat.ui.menu.item.MenuItem'); goog.require('goog.events'); goog.require('goog.ui.Component.EventType'); /** * The menu item for encoding the project for storing locally. * @param {!audioCat.utility.DomHelper} domHelper Facilitates DOM interactions. * @param {!audioCat.action.ActionManager} actionManager Manages actions. * @param {!audioCat.service.Service} service The current service. * @constructor * @extends {audioCat.ui.menu.item.MenuItem} */ audioCat.ui.menu.item.SaveToGoogleDriveItem = function(domHelper, actionManager, service) { goog.base(this, 'Save project to ' + service.getServiceName() + '.'); /** * A list of listener keys to unlisten later. * @private {!Array.<goog.events.Key>} */ this.listenerKeys_ = []; // Enable / disable this item based on whether we should save the document. this.listenerKeys_.push(goog.events.listen(service, audioCat.service.EventType.SHOULD_SAVE_STATE_CHANGED, function() { this.setEnabled(service.getSaveNeeded()); }, false, this)); // Respond to clicks. var action = actionManager.retrieveAction( audioCat.action.ActionType.SAVE_TO_SERVICE); this.listenerKeys_.push(goog.events.listen( this, goog.ui.Component.EventType.ACTION, action.doAction, false, action)); }; goog.inherits(audioCat.ui.menu.item.SaveToGoogleDriveItem, audioCat.ui.menu.item.MenuItem); /** @override */ audioCat.ui.menu.item.SaveToGoogleDriveItem.prototype.disposeInternal = function() { goog.base(this, 'disposeInternal'); for (var i = 0; i < this.listenerKeys_.length; ++i) { goog.events.unlistenByKey(this.listenerKeys_[i]); } };
const loginForm = document.querySelector("#login-form"); // const loginForm = document.getElementById("login-form"); const loginInput = document.querySelector("#login-form input"); // const loginButton = document.querySelector("#login-form button"); function onLoinSubmit(tomato){ tomato.preventDefault(); // console.log("hello" ,loginInput.value); // console.log("click!!!"); const username = loginInput.value; console.log(username); // if(username === ""){ // alert("Please write your name"); // } else if(username.length >15){ // alert("Your name is too long."); // } // => html에서 required maxlength="15" 이렇게 쓸 수 있음 } loginForm.addEventListener("submit", onLoinSubmit); // tomato.preventDefault(); 이걸로 submit되지 않음 // onLoinSubmit({information}) //https://codesandbox.io/s/frosty-austin-7vrk2d //codesandbox.io
"use strict"; exports.EventsStrategy = void 0; var _callbacks = _interopRequireDefault(require("./utils/callbacks")); var _iterator = require("./utils/iterator"); var _type = require("./utils/type"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var EventsStrategy = /*#__PURE__*/function () { function EventsStrategy(owner) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; this._events = {}; this._owner = owner; this._options = options; } EventsStrategy.create = function create(owner, strategy) { if (strategy) { return (0, _type.isFunction)(strategy) ? strategy(owner) : strategy; } else { return new EventsStrategy(owner); } }; var _proto = EventsStrategy.prototype; _proto.hasEvent = function hasEvent(eventName) { var callbacks = this._events[eventName]; return callbacks ? callbacks.has() : false; }; _proto.fireEvent = function fireEvent(eventName, eventArgs) { var callbacks = this._events[eventName]; if (callbacks) { callbacks.fireWith(this._owner, eventArgs); } return this._owner; }; _proto.on = function on(eventName, eventHandler) { var _this = this; if ((0, _type.isPlainObject)(eventName)) { (0, _iterator.each)(eventName, function (e, h) { _this.on(e, h); }); } else { var callbacks = this._events[eventName]; if (!callbacks) { callbacks = (0, _callbacks.default)({ syncStrategy: this._options.syncStrategy }); this._events[eventName] = callbacks; } var addFn = callbacks.originalAdd || callbacks.add; addFn.call(callbacks, eventHandler); } }; _proto.off = function off(eventName, eventHandler) { var callbacks = this._events[eventName]; if (callbacks) { if ((0, _type.isFunction)(eventHandler)) { callbacks.remove(eventHandler); } else { callbacks.empty(); } } }; _proto.dispose = function dispose() { (0, _iterator.each)(this._events, function (eventName, event) { event.empty(); }); }; return EventsStrategy; }(); exports.EventsStrategy = EventsStrategy;
import React from 'react'; const headerStyle = { color: '#fff', backgroundColor: '#ff6600', } const TableHeader = () => ( <thead style={headerStyle}> <tr> <th style={{textAlign:'center'}}>Comments</th> <th style={{textAlign:'center'}}>Vote Count</th> <th style={{textAlign:'center'}}>Upvote</th> <th>News Details</th> </tr> </thead> ) export default TableHeader;
var bcrypt = require('bcrypt'); module.exports = { create: function(req, res) { var userOpts = {}; userOpts.name = req.body.name; userOpts.email = req.body.email; bcrypt.genSalt(10, function(err, salt) { bcrypt.hash(req.body.password, salt, function(err, hash) { userOpts.password = hash; var user = new Models.User(userOpts); user.save(function(err, user) { if (err) { res.status(500).json(err); return } res.status(200).json(user); }); }); }); }, read: function(req, res) { }, update: function(req, res) { }, delete: function(req, res) { } }
"use strict"; var app = angular.module("petshopDapp"); app.controller('MenuController', function ($scope, $ionicModal, $ionicScrollDelegate) { });
import React, { Component } from 'react'; import Input from './Input'; import Textarea from './Textarea'; import Button from './Button'; import AskFormNotification from './AskFormNotification'; import AskFormValidator from './AskFormValidator'; class AskForm extends Component { state = { inputValue: '', textareaValue: '', notificationShow: false, formValidated: false } emailWrong = false textWrong = false validationFailed = false showNotification = () => { if (this.state.notificationShow) { setTimeout(() => { this.setState({ notificationShow: false }) }, 4000); return <AskFormNotification /> } else { return null } } validateForm = () => { const { inputValue, textareaValue } = this.state if (inputValue.includes('@') && inputValue.includes('.') && !inputValue.includes('@.') && !inputValue.includes('.@') && (inputValue.indexOf('@') !== 0) && (inputValue.indexOf('.') !== 0) && (inputValue.indexOf('@') < inputValue.lastIndexOf('.')) && (inputValue.length - inputValue.lastIndexOf('.') >= 3)) { this.emailWrong = false } else { this.emailWrong = true } if (textareaValue) { this.textWrong = false } else { this.textWrong = true } this.setState({ formValidated: true }) } handleChange = e => { if (e.target.name === 'askFormInput') { this.setState({ inputValue: e.target.value, formValidated: false, }) } else if (e.target.name === 'askFormArea') { this.setState({ textareaValue: e.target.value, formValidated: false, }) } } handleSubmit = e => { e.preventDefault() this.validateForm() if (this.emailWrong || this.textWrong) { this.validationFailed = true return } this.emailWrong = false this.textWrong = false this.validationFailed = false this.setState({ inputValue: '', textareaValue: '', formValidated: false, notificationShow: !this.state.notificationShow }) } componentDidUpdate() { if (!this.state.formValidated) { this.validateForm() } } render() { return ( <> {this.showNotification()} <form onSubmit={this.handleSubmit}> <Input type='text' name='askFormInput' value={this.state.inputValue} placeholder='Adres email' onChange={this.handleChange} /> {(this.validationFailed && this.emailWrong) && <AskFormValidator text='Podaj poprawny adres email' />} <Textarea value={this.state.textareaValue} placeholder='Wiadomość' onChange={this.handleChange} /> {(this.validationFailed && this.textWrong) && <AskFormValidator text='Wpisz wiadomość' />} <Button text='Wyślij' /> </form> </> ); } } export default AskForm;
import React, {Component} from 'react'; import { View, Text, TextInput } from 'react-native'; import {NumInput} from '../components/Common'; import styles from '../styles/EditByWater'; import common from '../styles/Common'; export default class WaterItem extends Component { constructor(props) { super(props); let {waterL, waterT} = this.props; this.state = { waterL, waterT }; } changeWaterL(waterL) { this.setState({waterL}); this.changeValue('waterL', waterL); } changeWaterT(waterT) { this.setState({waterT}); this.changeValue('waterT', waterT); } changeValue(type, val) { let {title, passChange} = this.props; passChange(title, type, val); } render() { let {rented} = this.props; return ( <View style={common.flexByRow}> <View style={common.flexChild}> <Text style={common.rowText}>{this.props.title}</Text> </View> <View style={[styles.water, styles.waterL]}> <NumInput passNum={this.changeWaterL.bind(this)} initVal={this.state.waterL} style={common.rowText} editable={rented}/> </View> <View style={styles.water}> <NumInput passNum={this.changeWaterT.bind(this)} initVal={this.state.waterT} style={common.rowText} editable={rented}/> </View> </View> ); } }
'use strict'; angular.module('AdBase') .factory('ouTypeService', ['ouTypeResource','$q', function (ouTypeResource,$q) { var service = {}; service.findActifsFromNow = function(){ var deferred = $q.defer(); ouTypeResource.findActifsFromNow().success(function(data,status,headers,config){ deferred.resolve(data); }).error(function(data,status,headers,config){ deferred.reject("An error occured when searching actives items."); }); return deferred.promise; }; return service; }] );
import faker from 'faker'; // I'm seeding data so I can be fancy! const users = [...Array(5)].map(() => ({ id: faker.random.uuid(), name: faker.name.firstName(), email: faker.internet.exampleEmail(), age: faker.random.number({ min: 20, max: 50 }), })); const validPost = user => ({ id: faker.random.uuid(), title: faker.lorem.sentence(), body: faker.lorem.sentences(), published: faker.random.boolean(), author: user.id, }); const posts = users.map(user => validPost(user)); const randomPost = posts => faker.random.arrayElement(posts); const comments = users.map(user => ({ id: faker.random.uuid(), text: faker.lorem.paragraph(), author: user.id, post: randomPost(posts).id, })); const db = { users, posts, comments, }; export { db as default };
import React, { Component } from 'react'; import faker from 'faker'; import lodash from 'lodash'; import createCSV from './createCSV'; import { CopiedDiv } from './Dialogues.js'; const randomDate = (start, end, cap) => { const determineMonth = name => { const monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]; const monthNumber = ( monthNames.indexOf(monthNames.find(month => month === name)) + 1 ).toString(); return monthNumber.length === 1 ? '0' + monthNumber.toString() : monthNumber; }; let date; date = faker.date .past(lodash(start, end), cap) .toString() .split(' ') .slice(1, 4); date[0] = determineMonth(date[0]); date = [date[0], date[1], date[2]].join('-'); return date; }; const GenerateUser = options => { const user = { id: lodash.random(1, 9999999), fname: faker.name.firstName(), mInitial: faker.name.firstName()[0], lname: faker.name.lastName(), address1: faker.address.streetAddress(), city: faker.address.city(), state: faker.address.stateAbbr(), zip: faker.address.zipCode(), county: faker.address.county(), cityYN: lodash.random(1, 100) > 97 ? 'No' : 'Yes', email: `${faker.hacker.noun()}.${faker.hacker.noun()}@fakeemail.com`, hPhone: faker.phone.phoneNumberFormat(), wPhone: '', cPhone: '', birthDate: randomDate(22, 55, '2000-01-01'), otherDate: '', regState: faker.address.stateAbbr(), regNum: faker.finance.account(), yrGraduation: '', option1: 'No', businessName1: '', businessAddress1: '', option2: 'No', businessName2: '', businessAddress2: '', option3: 'No', option4: 'No', option5: 'No', school1: '', option6: 'No', school2: '', expectedGrad: randomDate(22, 55, 2018), wherePract: '', internetPharm: 'No', bulkDrug: 'No', anotherCo: 'No', claims: 'No', complaints: 'No', membership: 'No', signed: '', dateSigned: randomDate(0, 0, new Date()), pmtType: '', dateSubmitted: randomDate(0, 0, new Date()), polEffDate: '', cert: '', certDate: randomDate(0, 0, new Date()), nap: '', otherTraining: '', otherPract: '', employer: '', referred: 'No', fieldRep: 4004040, appType: '', archive: 'Yes', title: '', anotherCarrier: 'No', addState: '', explain: '', paramAgency: 'No', fraudSigned: '', fraudSignedDate: randomDate(0, 0, new Date()), compound: 'No', compoundExplain: '', anotherCarrierExplain: 'No', bulkDrugExplain: '', anotherCoExplain: '', claimsExplain: '', complaintsExplain: '', premium: '$139.00', businessLiability: 'No', emailSent: 1, OptionalCoverage: '', OptCovChoice: '', OptCovPrice: '', TotalPremium: '$139.00', address2: '', ExistsPIJ: 0, CustNum: '', PremiumMessage: '', DiscountVerb: '', DiscountAmount: '', TaxVerb: '', TaxAmount: '', ErrorDescription: '', PrevPolicy: '', PrevName: '', PaymentLink: '', WorkPHL: '', Notes: 'Generated by PHL Faker.', OptCovDisclaimer: '', PIJEffDate: '', SelfEmployHours: '', CltSeqNum: '', schoolAuth: 0, moGraduation: '', advPractice: 'No', occurLimit: '000000000001000000', aggrLimit: '000000000003000000', schoolState: '', schoolAddress: '', schoolCity: '', schoolCounty: '', country: 'USA', email2: '', practState: faker.address.stateAbbr(), practAddress: faker.address.streetAddress(), practCity: faker.address.city(), practCounty: faker.address.county(), groupBillFlag: 1, liabLimit: '$1,000,000/$3,000,000', sexPhyLimit: '$50,000.00', exlAdvPract: 'Yes' }; user.signed = `${user.fname} ${user.mInitial}. ${user.lname}`; const insuredType = options.univOnly ? 'option6' : `option${lodash.random(1, 6)}`; user[insuredType] = 'Yes'; user.cert = user.signed; user.fraudSigned = user.signed; user.moGraduation = user.expectedGrad.split('-')[1]; user.yrGraduation = user.expectedGrad.split('-')[0]; switch (insuredType) { case 'option1': user.practState = faker.address.stateAbbr(); user.practAddress = faker.address.streetAddress(); user.practCity = faker.address.city(); user.practCounty = faker.address.county(); user.businessName1 = faker.company.companyName(0); user.businessAddress1 = `${faker.address.streetAddress()} ${faker.address.city()} ${faker.address.state()}`; break; case 'option2': user.practState = faker.address.stateAbbr(); user.practAddress = faker.address.streetAddress(); user.practCity = faker.address.city(); user.practCounty = faker.address.county(); user.businessName1 = faker.company.companyName(0); user.businessAddress1 = `${faker.address.streetAddress()} ${faker.address.city()} ${faker.address.state()}`; break; case 'option3': case 'option4': user.practState = faker.address.stateAbbr(); user.practAddress = faker.address.streetAddress(); user.practCity = faker.address.city(); user.practCounty = faker.address.county(); user.SelfEmployHours = 10; break; case 'option5': user.school1 = 'University of Iowa'; user.practState = faker.address.stateAbbr(); user.practAddress = faker.address.streetAddress(); user.practCity = faker.address.city(); user.practCounty = faker.address.county(); break; case 'option6': user.expectedGrad = '05-01-2023'; user.moGraduation = user.expectedGrad.split('-')[1]; user.yrGraduation = user.expectedGrad.split('-')[0]; user.school2 = 'University of Iowa'; user.schoolState = 'IA'; user.schoolAddress = '115 S Grand Ave'; user.schoolCity = 'Iowa City'; user.schoolState = 'IA'; user.schoolCounty = 'Johnson'; user.schoolAuth = 1; break; default: console.log(`Something went wrong with user ${user.id}.`); } return user; }; class Users extends Component { constructor(props) { super(props); this.state = { users: '', options: { numberOfRecords: 1, univOnly: false }, isCopied: false }; this.processCSVRequest = this.processCSVRequest.bind(this); this.buildUsers = this.buildUsers.bind(this); this.getOptions = this.getOptions.bind(this); this.grabCopy = this.grabCopy.bind(this); this.removeCopied = this.removeCopied.bind(this); } grabCopy() { if (this.state.users.length) { document.getElementById('userCSV').select(); document.execCommand('copy'); this.setState({ isCopied: true }); } } removeCopied() { this.setState({ isCopied: false }); } getOptions() { this.setState( { options: { numberOfRecords: document.getElementById('numberOfRecords').value, univOnly: document.getElementById('univOnly').checked } }, () => this.removeCopied() ); } buildUsers() { const users = []; for (let i = 0; i < this.state.options.numberOfRecords; i++) { const user = GenerateUser(this.state.options); users.push(user); } return users; } async processCSVRequest() { const options = await this.getOptions(); const users = await this.buildUsers(); const csv = await createCSV(users); this.setState( { users: csv }, () => (document.getElementById('userCSV').value = this.state.users) ); } render() { return ( <div> {this.state.isCopied && <CopiedDiv />} <div className="content"> <h2>User Settings</h2> <div className="controls-grid"> <div> <label htmlFor="numberOfRecords"> How many fake users do you need? </label> <input id="numberOfRecords" type="number" min="1" defaultValue={this.state.options.numberOfRecords} className="number-selector" /> </div> <div className="checkbox"> <input type="checkbox" id="univOnly" defaultChecked="false" /> <label htmlFor="univOnly">University Only?</label> </div> <button className="controls-button" onClick={this.processCSVRequest}> Let's Go! </button> </div> </div> <div className="content"> <h2>The Data</h2> <div className="output-grid"> <textarea className="output-display" id="userCSV" defaultValue={this.state.users} onClick={this.grabCopy} onBlur={this.removeCopied} readOnly="true" /> </div> <div className="instructions"> <p> Click anywhere in the box to automatically copy the data to your clipboard. </p> </div> </div> </div> ); } } export default Users;
import React from "react"; const Balance = ({ balance, currency }) => ( <div className="card col-12 col-md-4 col-lg-4 p-3"> <h2>Egyenleg</h2> <div className={`mt-3 ${balance < 0 ? "neg" : "pos"}`}> <h1>{`${Math.abs(balance).toLocaleString().replace(/,/g, " ")} HUF`}</h1> </div> <div className="currency"> <div> <h4> {`${(balance * currency.rates.EUR) .toFixed(2) .toString() .replace(/\./, ",")} EUR`} </h4> </div> <div> <h4> {`${(balance * currency.rates.USD) .toFixed(2) .toString() .replace(/\./, ",")} USD`} </h4> </div> <div> <h4> {`${(balance * currency.rates.GBP) .toFixed(2) .toString() .replace(/\./, ",")} GBP`} </h4> </div> </div> </div> ); export default Balance;
$(function () { //jsonp var inp = $('#inp'); var searchbtn = $('#searchbtn'); // // 显示按钮 // $('.city').on('click', function () { // $('.search').show(); // inp.focus();// 获取焦点 // }) // // 取消按钮 // $('#cancel').on('click', function () { // $('.search').hide(); // }) //更换城市天气 // 确认按钮 searchbtn.on('click', function () { if (inp.val().trim() != '') { fun(inp.val().trim()); // $('.search').hide(); } }) $(document).keydown(function (event) { if (event.keyCode == 13) { searchbtn.click(); } }); // 背景图片 Event(); //获取缓存数据--用于测试 var musicIds = localStorage.getItem('musicIds'); //如果不存在缓存数据,发起ajax请求 fun(''); // if(!musicIds){ // //初始化获取 // fun(''); // }else{ // //如果存在缓存数据 // musicIds = JSON.parse(musicIds); // console.log('musicIds ==> ', musicIds); // initialize(musicIds); // } function fun(cityText) { $.ajax({ //请求类型 // type: 'GET', //请求地址 url: 'https://www.tianqiapi.com/api', //请求参数 data: { appid: 99896829, appsecret: 'dU2ZGAxw', version: 'v9', city: cityText, }, dataType: 'jsonp', //请求成功后执行的回调函数 success: function (data) { console.log('data ==> ', data); if (inp.val().trim() != '' && data.city != inp.val().trim()) { alert('输入搜索错误!请检查后输入内容重试!'); return; } //将数据缓存在浏览器的本地存储 localStorage //JSON.stringify(data);把对象转为字符串 localStorage.setItem('musicIds', JSON.stringify(data)); // 当前城市名称 $('.city').text(data.city); initialize(data); }, //true: 异步, false: 同步, 默认异步, 对于jsonp无效 async: true }) } function initialize(obj) { var data = obj.data; // 当前温度情况 real_time(obj.data[0]); // 当天24小时天气情况 All_day(data[0].hours); // 7天预告信息 Notice(data); } function real_time(obj) { var data = obj; console.log(data); // 当前温度 $('.tt_text').html(data.tem == '' ? data.hours[0].tem + '&#176' : data.tem + '&#176'); // 当前天气状态图标 var wendu = $('#temperature'); if (wendu.find('use').length != 0) { wendu.find('use').remove(); } var html = '<use xlink:href="#icon-' + data.wea_night_img + '"></use>'; wendu.html(html); // 提示 $('.air_tips').text(data.air_tips).prop('title', data.air_tips); } function All_day(obj) { var Today = $('.Today>ul'); var d = new Date(); var h = d.getHours();//获取当前小时数(0-23) // 遍历当前24小时 Today.html(''); for (var i in obj) { var str = ` <div class="hour">${obj[i].hours}</div> <svg class="icon"> <use xlink:href="#icon-${obj[i].wea_img}"></use> </svg> <div class="real">${obj[i].tem}&#8451</div>`; var lis = $('<li>' + str + '</li>'); if (parseInt(obj[i].hours) == h) { lis.addClass('active'); } Today.append(lis); lis.on('click', function () { // 当前温度 $('.tt_text').html(parseInt($(this).find('.real').text()) + '&#176'); // 当前天气状态图标 var wendu = $('#temperature'); if (wendu.find('use').length != 0) { wendu.find('use').remove(); } wendu.html($(this).find('.icon').html()); }) } } //7天天气预告 function Notice(obj) { var prediction = $('.prediction'); prediction.html(''); for (var i in obj) { var str = `<div class="week" data-state="${i}"> <div class="w_left">${obj[i].day}</div> <div class="w_rigth"> <div class="f_temperature"> ${obj[i].tem2}&#8451 ~ ${obj[i].tem1}&#8451 </div> <svg class="icon"> <use xlink:href="#icon-${obj[i].wea_day_img}"></use> </svg> </div> </div>`; var divs = $(str); if (i == 0) { divs.addClass('active'); } divs.on('click', function () { var arr = obj[$(this).data('state')]; real_time(arr); console.log(arr.hours); All_day(arr.hours); }) prediction.append(divs); } } function Event() { // 获取背景对象 var background = $('.background'); var myDate = new Date(); var h = myDate.getHours();//获取当前小时数(0-23) if (h >= 7 && h <= 19) { background.css('background-image', 'url(./images/Noon.png)'); } else { background.css('background-image', 'url(./images/Night.png)'); } } })
$(document).ready(function(){ var tabla_usuario = ""; function recorrer(data,option){ if(option){ tabla_usuario.destroy(); $('.tr_usuarios').remove(); } $.each(data,function(i,item){ $('.tbody_usuarios').append('<tr class="tr_usuarios"><td>'+item.usuFoto+'</td><td>'+item.usuNombre+'</td><td>'+item.usuApellido+'</td><td>'+item.usuTelefono+'</td><td>'+item.usuCorreo+'</td><td>'+item.usuPuesto+'</td><td><button class="btn btn-radius-mini editarUsuario" data-toggle="modal" data-target="#editarUsuario" value='+item.idUsuario+'><i class="fa fa-pencil"></i></button>&#160;<button class="btn btn-radius-mini eliminarUsuario" value='+item.idUsuario+'><i class="fa fa-eraser"></i></button></tr>'); }); } var tabla = ""; // Listar usuarios $.ajax({ url:'listarUsuarios', type:'GET', dataType:'JSON', success:function(data){ if(data != null && data != false){ recorrer(data,false); }else{ alertify.error("Hubo un error al listar los usuarios"); } },error:function(error){ alertify.error("Error al conectar con el servidor"); } }); // var id = $('#sortable').find('li:last-child').val(); // $("#sortable").sortable({ // change:function(){ // },update:function(){ // for(var x = 0;x <= id;x++){ // $('#sortable > li:nth-child('+x+')').val(x); // } // } // }); // $("#sortable").disableSelection(); $('body').on('click','.editarUsuario',function(){ var id = $(this).val(); $.ajax({ url:'editarUsuario', type:'POST', dataType:'JSON', data:{ id:id },success:function(data){ if(data != null && data != false){ $('#e_nombre').val(item.usuNombre); $('#e_apellido').val(item.usuApellido); $('#e_telefono').val(item.usuTelefono); $('#e_correo').val(item.usuCorreo); }else{ alertify.error("Hubo un error al obtener la información"); } },error:function(error){ alertify.error("Error al conectar con el servidor"); } }); }); $('#formAgregarUsuario').submit(function(){ var formData = new FormData($('#formAgregarUsuario')[0]); $.ajax({ url:'agregarUsuario', type:'POST', dataType:'JSON', data: formData, cache:false, processData:false, contentType:false, success:function(data){ if(data != null && data != false){ recorrer(data,true); alertify.success("Usuario agregado correctamente"); }else{ alertify.error("Hubo un error al agregar el usuario"); } },error:function(error){ alertify.error("Error al conectar con el servidor"); } }); return false; }); $('#formActualizarUsuario').submit(function(){ var formData = new FormData($('#formActualizarUsuario')[0]); $.ajax({ url:'actualizarUsuario', type:'POST', dataType:'JSON', data:formData, processData:false, cache:false, contentType:false, success:function(data){ if(data != null && data != false){ recorrer(data,true); alertify.success("Usuario actualizado correctamente"); }else{ alertify.error("Hubo un error al actualizar el usuario"); } },error:function(error){ alertify.error("Error al conectar con el servidor"); } }); return false; }); $('body').on('click','.eliminarUsuario',function(){ var id = $(this).val(); $.ajax({ url:'eliminarUsuario', type:'POST', dataType:'JSON', data:{ id:id }, success:function(data){ if(data != null && data != false){ recorrer(data,true); tabla = $('#tabla_usuarios').DataTable(); }else{ alertify.error("Hubo un error al eliminar el usuario"); } },error:function(error){ alertify.error("Error al conectar con el servidor"); } }); }); });
/** * @file Game.jsx * @description React extension javascript that exports a Game react component. * @author Manyi Cheng */ import React, { Component } from 'react'; import Player from './Player.jsx'; import Deck from './Deck.jsx'; import GameplayField from './GameplayField.jsx'; import peachIcon from '../res/peach.png'; import luigiIcon from '../res/luigi.png'; import booIcon from '../res/boo.png'; import Timer from './Timer.js'; import * as Rules from '../Rules.js'; import * as PlayerBot from '../PlayerBot.js'; import startButton from '../res/startbutton.png'; /** * @class A class that extends react Component, represents a big two Game. * @description This class represents Game component in a big two game. * @param {*} props Props from parent component. */ class Game extends Component { constructor(props) { super(props); this.state = { rules: true, playerScore: 0, playerCards: [], leftCards: [], topCards: [], rightCards: [], playerField: [], leftField: [], topField: [], rightField: [], startingTurn: true, turn: null, minutes: 10, seconds: 0, cardsPlayed: [], freeMove: false, lastMove: [], lastMovePlayer: null, gameOver: false, }; this.startGame = this.startGame.bind(this); this.resetGame = this.resetGame.bind(this); this.handlePlayerDeal = this.handlePlayerDeal.bind(this); this.handlePlayerPass = this.handlePlayerPass.bind(this); this.BotPlayCards = this.BotPlayCards.bind(this); this.updateNextTurn = this.updateNextTurn.bind(this); this.updateField = this.updateField.bind(this); this.updateNextTurnCards = this.updateNextTurnCards.bind(this); this.getCardsforTurn = this.getCardsforTurn.bind(this); this.typeSort = this.typeSort.bind(this); this.handleTimer = this.handleTimer.bind(this); this.suitSort = this.suitSort.bind(this); this.isGameOver = this.isGameOver.bind(this); this.displayPass = this.displayPass.bind(this); } /** * @description Execute the code synchronously when the component gets loaded or mounted in the DOM. This method is called during the mounting phase of the React Life-cycle * @deprecated Will be decrecated be React in the future. */ UNSAFE_componentWillMount() { this.resetGame(); } /** * @description Starts the game upon user closing the rules. */ startGame() { this.setState({ rules: false, }); if (this.state.turn !== 'player') { this.BotPlayCards(); } } /** * @description Resets game states upon user clicking play again button. */ async resetGame() { let deck = Rules.newDeck(); let playerCards = await Rules.setUserCards(deck); let leftCards = await Rules.setUserCards(deck); let topCards = await Rules.setUserCards(deck); let rightCards = await Rules.setUserCards(deck); let turn = Rules.setFirstTurn(playerCards, leftCards, topCards, rightCards); this.setState({ rules: true, playerScore: 0, playerField: [], leftField: [], topField: [], rightField: [], playerCards: playerCards, leftCards: leftCards, topCards: topCards, rightCards: rightCards, initialMinutes: 10, initialSeconds: 0, turn: turn, startingTurn: true, cardsPlayed: [], lastMove: [], lastMovePlayer: null, gameOver: false, playerFieldText: '', }); } /** * Handles game over condition when the timer reaches 0. */ handleTimer() { this.setState({ gameOver: true, }); } /** * @description player action on clicking deal button with selected cards. * @param {*} cards Selected cards to be dealt. * @returns true if valid play, false if invalid play. */ handlePlayerDeal(cards) { this.setState({ playerFieldText: '' }); if (this.state.startingTurn) { let validPlay = Rules.isValidStartingPlay(cards); if (validPlay) { this.updateNextTurnCards(cards); this.setState({ startingTurn: false }); return true; } else { this.setState({ playerFieldText: 'Your play must be valid and contain 3 of diamonds for starting turn', }); } } else { let valid = Rules.isValidPlay(cards); let isFreeMove = this.state.lastMovePlayer === 'player'; let stronger = Rules.isStrongerPlay(this.state.lastMove, cards); if (valid && (isFreeMove || stronger)) { this.updateNextTurnCards(cards); return true; } else { if (!valid) { this.setState({ playerFieldText: 'Your play must be valid', }); } else if (!stronger && cards.length === this.state.lastMove.length) { this.setState({ playerFieldText: 'Your play must be stronger than the previous play' }); } else if (cards.length !== this.state.lastMove) { this.setState({ playerFieldText: 'Your play must contain same number of cards as the previous play', }); } } } } /** * @description Controls the logic when its bot's turn to play cards. */ BotPlayCards() { let currentCards = this.getCardsforTurn(); let bestMove; if (this.state.startingTurn) { bestMove = PlayerBot.BotStartingTurn(currentCards); this.setState({ startingTurn: false }); } else { if (this.state.lastMovePlayer === this.state.turn) { bestMove = PlayerBot.BotFreeTurn(currentCards); } else { bestMove = PlayerBot.BotPlayCards(currentCards, this.state.lastMove); } } this.updateNextTurnCards(bestMove); } /** * @description gets the current players' cards of the turn. * @returns current player cards */ getCardsforTurn() { if (this.state.turn === 'left') return this.state.leftCards; if (this.state.turn === 'top') return this.state.topCards; if (this.state.turn === 'right') return this.state.rightCards; if (this.state.turn === 'player') return this.state.playerCards; } /** * @description Updates state cards for next turn based on the cards dealt by the current player. * @param {*} cards Cards dealt by the current player. */ updateNextTurnCards(cards) { if (cards) { let cardsPlayed = this.state.cardsPlayed; let currentPlayerCards = this.getCardsforTurn(); cards.forEach((card) => { currentPlayerCards.splice(currentPlayerCards.indexOf(card), 1); }); if (this.state.lastMove) { this.state.lastMove.forEach((card) => { cardsPlayed.push(card); }); } if (this.state.turn === 'left') this.setState({ leftCards: currentPlayerCards }); if (this.state.turn === 'top') this.setState({ topCards: currentPlayerCards }); if (this.state.turn === 'right') this.setState({ rightCards: currentPlayerCards }); if (this.state.turn === 'player') this.setState({ playerCards: currentPlayerCards }); this.updateField(cards); this.setState( { cardsPlayed: cardsPlayed, lastMove: cards, freeMove: false, lastMovePlayer: this.state.turn, }, () => { this.updateNextTurn(); } ); } else { if (this.state.turn === 'left') this.setState({ leftField: [] }, () => { this.displayPass(); }); if (this.state.turn === 'top') this.setState({ topField: [] }, () => { this.displayPass(); }); if (this.state.turn === 'right') this.setState({ rightField: [] }, () => { this.displayPass(); }); if (this.state.turn === 'player') this.setState({ playerField: [] }, () => { this.displayPass(); }); this.updateNextTurn(); } } /** * @description Updates the GamplayField when players deal cards. * @param {*} cards Field cards */ updateField(cards) { if (this.state.turn === 'left') this.setState({ leftField: [] }, () => { this.setState({ leftField: cards }); }); if (this.state.turn === 'top') this.setState({ topField: [] }, () => { this.setState({ topField: cards }); }); if (this.state.turn === 'right') this.setState({ rightField: [] }, () => { this.setState({ rightField: cards }); }); if (this.state.turn === 'player') this.setState({ playerField: [] }, () => { this.setState({ playerField: cards }); }); } /** * @description Set states turn, and field text for next turn, then on call back triggers next turn's play. * @returns Nothing */ updateNextTurn() { if (this.isGameOver()) return; setTimeout(() => { if (this.state.turn === 'player') { this.setState({ turn: 'right', playerFieldText: '' }, () => { this.BotPlayCards(); }); } else if (this.state.turn === 'right') { this.setState({ turn: 'top' }, () => { this.BotPlayCards(); }); } else if (this.state.turn === 'top') { this.setState({ turn: 'left' }, () => { this.BotPlayCards(); }); } else this.setState({ turn: 'player' }); }, 1200); } /** * @description Handles player passing for starting turn, last move, free move and normal situations. */ handlePlayerPass() { if (this.state.startingTurn) { this.setState({ freeMove: true, playerFieldText: 'You cannot pass the first turn', }); } else if (this.state.lastMovePlayer === 'player') { this.setState({ freeMove: true, playerFieldText: 'You cannot pass the free move', }); } else { this.setState({ playerField: [], playerFieldText: '' }); this.displayPass(); this.updateNextTurn(); } } /** * @description Sorts player's cards in type order upon player clicking type button. */ typeSort() { let cards = this.state.playerCards; Rules.sortCardsValue(cards); this.setState({ playerCards: cards }); } /** * @description Sorts player's cards in suit order upon player clicking suit button. */ suitSort() { let cards = this.state.playerCards; Rules.sortCardsSuit(cards); this.setState({ playerCards: cards }); } /** * @description Checks whether the game is over and sets the game states gameOver and playerScore 1s after validation. */ isGameOver() { let currentPlayerCards = this.getCardsforTurn(); if (currentPlayerCards.length === 0) { let score = this.computePlayerScore(); setTimeout(() => { this.setState({ gameOver: true, playerScore: score, }); return true; }, 1000); } } /** * @description Computes player score of the game. * @returns {int} Computed score. */ computePlayerScore() { let len = this.state.playerCards.length; return Math.ceil((13 - len) * (100 / 13)); } /** * @description Displays text when players choose to pass the current turn. */ displayPass() { let field = this.state.turn; let node = document.createElement('div'); node.append(document.createTextNode('Pass')); node.setAttribute('class', 'gameplayfield-text'); document.getElementById(field).append(node); setTimeout(() => { document.getElementById(field).removeChild(node); }, 1000); } render() { if (this.state.rules) { return ( <div> <div className="game-container"> <div className="window-container"> <div className="window"> <div className="rules-cover"> <h4 className="rules-heading"> <span className="rules-heading-span">Rules</span> </h4> </div> <div className="rules-details"> <ul className="rules-details"> <li>Type: 2 > A > K > Q > J > 10 > 9 > 8 > 7 > 6 > 5 > 4 > 3 </li> <li>suits: Spades > hearts > clubs > diamonds</li> <li>Playable combinations: single, pairs, triples, five-cards</li> <li> A combination can only be beaten by a better combination with the same number of cards. </li> <li> </li> <li>A Straight consists of five cards of consecutive rank with mixed suits.</li> <li>A Flush consists of any five cards of the same suit.</li> <li> A Full House consists of three cards of one rank and two of another rank </li> <li>A quads is made up of all four cards of one rank, plus any fifth card</li> <li>A Straight Flush consists of five consecutive cards of the same suit.</li> </ul> </div> <div className="rules-button"> <img className="start-button" src={startButton} onClick={this.startGame} alt="start-button" /> </div> <div>3XA3 G06</div> </div> </div> </div> </div> ); } else { return ( <div> <div className="game-container"> {this.state.gameOver && <div className="window-container"> <div className="window"> <div className="gameover-container"> <div>Game Over!</div> <div>Score {this.state.playerScore}</div> <button id="reset-button" disabled={false} className="playagain-button" onClick={this.resetGame} > Play Again </button> </div> </div> </div>} <div className="game-opponent"> <img src={booIcon} alt="character" className="top-icon" /> <img src={luigiIcon} alt="character" className="opponent-icon" /> <div className="game-left"> <Deck class="opponent-container-left" cardClass="computer-side" cards={this.state.leftCards} ></Deck> </div> <div className="game-middle"> <Deck class="opponent-container-top" cardClass="computer-top" cards={this.state.topCards} ></Deck> <GameplayField player={this.state.playerField} right={this.state.rightField} left={this.state.leftField} top={this.state.topField} playerFieldText={this.state.playerFieldText} ></GameplayField> </div> <div className="game-right"> <Timer initialMinutes={this.state.minutes} initialSeconds={this.state.seconds} onTimer={this.handleTimer} /> <Deck class="opponent-container-right" cardClass="computer-side" cards={this.state.rightCards} ></Deck> </div> <img src={peachIcon} alt="character" className="opponent-icon" /> </div> <Player cards={this.state.playerCards} playerTurn={this.state.turn === 'player'} freeMove={this.state.freeMove} playCards={this.handlePlayerDeal} passTurn={this.handlePlayerPass} turn={this.state.turn} typeSort={this.typeSort} suitSort={this.suitSort} gameOver={this.state.gameOver} playerScore={this.state.playerScore} ></Player> </div> </div> ); } } } export default Game;
alert("123"); alert("456");
(function () { class CalcModel extends Subject { constructor () { super() this.data = { leftNum: 0, rightNum: 0 } } setLeftNum (num) { this.data.leftNum = num this.nortify(); } setRightNum (num) { this.data.rightNum = num this.nortify(); } multiplication () { return this.data.leftNum * this.data.rightNum } division () { return this.data.leftNum / this.data.rightNum } } var calcModel = new CalcModel(); class calcView extends Observer { constructor ($output, calcType) { super(); this.calcType = calcType this.$output = $output this.model = calcModel this.model.observerList.add(this) } update () { this.$output.innerHTML = this.model[this.calcType]() } } new calcView(document.getElementById('outputMultiplication'), 'multiplication') new calcView(document.getElementById('outputDivision'), 'division') $leftNum = document.getElementById('leftNum') $leftNum.addEventListener('change', function(e){ calcModel.setLeftNum(e.currentTarget.value) }); $rightNum = document.getElementById('rightNum') $rightNum.addEventListener('change', function(e){ calcModel.setRightNum(e.currentTarget.value) }); })()
'use strict'; const path = require('path'); const _ = require('underscore'); module.exports = (files) => { const obj = {}; files.forEach((file) => { obj[path.extname(file)] = true; }); const extList = _.keys(obj); if (extList.length > 1) { throw new Error(`exts are intermingled. (${extList.join(', ')})`); } return extList.shift(); };
import React from "react"; import ReactDOM from "react-dom"; import App from "view/app"; import {Provider} from "react-redux" import store from "store" import "common/css/bootstrap.min.css"; import "common/css/reset.css"; import "common/css/common.css"; import "common/css/style.css"; import "common/fonts/iconfont.css" ReactDOM.render( <Provider store={store}> <App/> </Provider>, document.getElementById('root') );
var modal_login = document.getElementById('loginModal'); var btnlogin = document.getElementById('btnlogin'); var btn_login = document.getElementById('btn_login'); var span_login = document.getElementById('close1'); var modal_signup = document.getElementById('signupModal'); var btnsignup = document.getElementById('btnsignup'); var btn_signup = document.getElementById('btn_signup'); var span_signup = document.getElementById('close2'); var modal_share = document.getElementById('shareModal'); var btnshare = document.getElementById('btnshare'); var btn_share = document.getElementById('btn_share'); var span_share = document.getElementById('close3'); btnlogin.onclick = function(){ modal_login.style.display = "block"; modal_signup.style.display = "none"; modal_share.style.display = "none"; }; btn_login.onclick = function(){ modal_login.style.display = "block"; modal_signup.style.display = "none"; modal_share.style.display = "none"; }; btnsignup.onclick = function(){ modal_login.style.display = "none"; modal_signup.style.display = "block"; modal_share.style.display = "none"; }; btn_signup.onclick = function(){ modal_login.style.display = "none"; modal_signup.style.display = "block"; modal_share.style.display = "none"; }; btnshare.onclick = function () { modal_login.style.display = "none"; modal_signup.style.display = "none"; modal_share.style.display = "block"; }; btn_share.onclick = function () { modal_login.style.display = "none"; modal_signup.style.display = "none"; modal_share.style.display = "block"; }; span_login.onclick = function() { modal_login.style.display = "none"; //modal_signup.style.display = "none"; }; span_signup.onclick = function(){ //modal_login.style.display = "none"; modal_signup.style.display = "none"; }; span_share.onclick = function(){ modal_share.style.display = "none"; }; window.onclick = function(event){ if (event.target === modal_login){ modal_login.style.display = 'none'; } else if (event.target === modal_signup){ modal_signup.style.display = 'none'; }else if (event.target === modal_share){ modal_share.style.display = 'none'; } };
import React from "react"; export default function PageA() { return <div className="pages">This is PageA</div>; }
import Letter from '../../../models/letter'; export default (userObj, args, { user }) => { if (userObj.id === user.id) { return Letter.find({ toEmail: user.email }); } };
countries = [ { 'name': 'United States', 'short': 'US', 'scale': 1.0 }, { 'name': 'United Kingdom', 'short': 'UK', 'scale': 0.3 }, { 'name': 'Spain', 'short': 'ES', 'scale': 0.45 }, { 'name': 'China', 'short': 'CN', 'scale': 0.15 }, { 'name': 'Brazil', 'short': 'BR', 'scale': 0.35 } ]
//给输入框绑定事件 $('.login_input').on('keyup',function(){ showClearBtn(this); }); // 给清空按钮绑定事件 $('.login_content').on('click','.aui-icon-close',function(){ //如果当前按钮显示状态,则给对应本行的input框内容清空,并去隐藏按钮 if($api.hasCls(this,'active')){ var needClearInput = $api.first($api.closest(this, '.info_row')); needClearInput.value = ''; $api.removeCls(this, 'active'); } }); //input框有内容时显示本行清空按钮 function showClearBtn(that){ //获取对应本行的清除btn var $clearBtn = $(that).parents('.info_row').find('.aui-icon-close'); // 根据内容选择是否显示btn if(that.value != ''){ $clearBtn.addClass('active'); }else{ $clearBtn.removeClass('active'); } } // 打开页面 function openRegestWin(){ api.openWin({ name: 'regest', url: './regest.html' }); } function openResetPsw(){ var mobile = $api.dom('.mobile').value; api.openWin({ name: 'resetPWD', url: './reset-password.html', pageParam: { mobile: mobile } }); } // 关闭页面 function closeLoginWin(){ api.closeWin({ name: 'login' }); } function closeRegestWin(){ api.closeWin({ name: 'regest' }); } function closeResetWin(){ api.closeWin({ name: 'resetPWD' }); }
// handlebars compile fn for Challenge Question function renderQues(id, question, answerA, answerB, answerC, answerD, lessonId) { var tmpl = $('#question-template').html() var quesTmpl = Handlebars.compile(tmpl) var data = { id: id, question: question, answerA: answerA, answerB: answerB, answerC: answerC, answerD: answerD, lessonId: lessonId } return quesTmpl(data) } // collect users correct and incorrect answer attempts function postQuestionAnswer(userId, questionId, correct, lessonId) { // post to userAnswers $.post('http://localhost:3000/userAnswers', { userId: userId, questionId: questionId, correct: correct, lessonId: lessonId }) } // load video and question $('.module-lessons-nav').on('click', '.lesson', function(e) { e.preventDefault(); // stylize nav bar $('.lesson').removeClass('active') $(this).closest('.lesson').addClass('active') // load video var lessonId = $(this).data('id') $.get('http://localhost:3000/lessons/' + lessonId + '/videos').done(function (videos) { $('.study-content').html(videos[0].videoSrc) }) // load question $.get('http://localhost:3000/lessons/' + lessonId + '/questions').done(function (questions) { var ques = questions[0] $('.challenge').html(renderQues(ques.id, ques.question, ques.answerA, ques.answerB, ques.answerC, ques.answerD, lessonId)) }).done (function () { $('.feedback').html('') }) }) // Check answer to challenge question $('.challenge').on('click', 'button', function(e) { e.preventDefault() var ans = $('input[name=dq1]:checked').val() var questionId = $('.question-container').data('id') var lessonId = $('.question-container #lessonId').val() $.get('http://localhost:3000/questions/' + questionId).done(function (question) { if (ans == question.correctAnswer) { $('.feedback').html('Right on!') postQuestionAnswer(1, questionId, true, lessonId) // add checkmark for correct answer var idSelector = $('[data-id=' + lessonId + ']') idSelector.find('i.fa').removeClass('fa-play-circle-o').addClass('fa-check') $('.lesson.active').removeClass('active') } else { $('.feedback').html('Sorry, try again') postQuestionAnswer(1, questionId, false, lessonId) // remove feedback text setTimeout(function() { $('.feedback').html(''); }, 3000); } }).done(function (){ // set points value $.get('http://localhost:3000/userAnswers?correct=true').done(function (correctAnswers) { $('.points').html(correctAnswers.length) }) }) }); var Router = Backbone.Router.extend({ // Route definition routes: { ':topicId': 'showTopic', '#1': 'metaphys', '#2': 'epistem', '#3': 'anthro', '#4': 'relig', '#5': 'ethics' }, // Route handlers metaphys: function () { router.navigate('/#1', { trigger: true }) }, epistem: function () { router.navigate('/#2', { trigger: true }) }, anthro: function () { router.navigate('/#3', { trigger: true }) }, relig: function () { router.navigate('/#4', { trigger: true }) }, ethics: function () { router.navigate('/#5', { trigger: true }) }, showTopic: function(topicId) { // set topic name on page load $.get('http://localhost:3000/topics/' + topicId).done(function(topic) { $('.module-lessons-nav .title').html(topic.name); }).done(function (){ // set points value $.get('http://localhost:3000/userAnswers?correct=true').done(function (correctAnswers) { $('.points').html(correctAnswers.length) }) }) // Get lessons list for the topic on page load $.get('http://localhost:3000/topics/' + topicId + '/lessons').done(function (lessons) { var tmpl = $('#lessons-template').html() var template = Handlebars.compile(tmpl); $('.module-lessons-nav .lesson-list').html(template(lessons)) // set active lesson class $( ".module-lessons-nav .lesson:first-child" ).trigger( "click" ); }).done(function (lessons) { // check if lesson question has been answered correctly and add styling lessons.forEach(function(lesson) { $.get('http://localhost:3000/lessons/' + lesson.id + '/userAnswers?correct=true').done(function (correctAnswers) { var idSelector = $('[data-id=' + lesson.id + ']') if (correctAnswers.length) { idSelector.addClass('completed') // add checkmark if correct idSelector.find('i.fa').removeClass('fa-play-circle-o').addClass('fa-check') } }) }) }) } }) var router = new Router Backbone.history.start()
import React, { Component } from "react"; import _ from "lodash"; import withAuth from "../libs/withAuth"; import "../libs/mycools"; import Layout from "../components/Layout"; import UserPanel from "../components/shared/userpanel"; import CreateDebitNoteStepOne from "../components/debit-note/create/create-debit-note-one"; import CreateDebitNoteStepTwo from "../components/debit-note/create/create-debit-note-two"; import CreateDebitNoteStepThree from "../components/debit-note/create/create-debit-note-three"; import CreateDebitNoteStepFour from "../components/debit-note/create/create-debit-note-four"; const CONTENT_STEP = [ "Select Invoice", "Debit Note Items", "Insert Debit Note Details", "Summary" ]; const lang = "debit-create"; class createDebitNote extends Component { constructor(props) { super(props); this.layout = React.createRef(); this.state = { currentStep: 1, stepOneProp: undefined, stepTwoProp: undefined, stepThreeProp: undefined, stepFourProp: undefined, isInvoiceChange: true, subVatItemChange: true }; } nextStep = () => { this.setState({ currentStep: this.state.currentStep + 1 }); }; previousStep = () => { this.setState({ currentStep: this.state.currentStep - 1 }); }; updateStepOneState = state => { this.setState({ stepOneProp: state, isInvoiceChange: state.isInvoiceChange }); }; updateStepTwoState = state => { this.setState({ stepTwoProp: state, isInvoiceChange: state.isInvoiceChange, subVatItemChange: state.subVatItemChange }); }; updateStepThreeState = state => { this.setState({ stepThreeProp: state, isInvoiceChange: state.isInvoiceChange }); }; updateStepFourState = state => { this.setState({ stepFourProp: state, subVatItemChange: state.subVatItemChange }); }; render() { return ( <Layout hideNavBar={true} ref={this.layout} {...this.props}> <UserPanel {...this.props} /> {this.state.currentStep === 1 ? ( <CreateDebitNoteStepOne mainState={this.state} updateState={this.updateStepOneState} nextStep={() => this.nextStep()} previousStep={() => this.previousStep()} contentStep={CONTENT_STEP} lang={lang} /> ) : ( "" )} {this.state.currentStep === 2 ? ( <CreateDebitNoteStepTwo mainState={this.state} updateState={this.updateStepTwoState} nextStep={() => this.nextStep()} previousStep={() => this.previousStep()} contentStep={CONTENT_STEP} lang={lang} /> ) : ( "" )} {this.state.currentStep === 3 ? ( <CreateDebitNoteStepThree mainState={this.state} updateState={this.updateStepThreeState} nextStep={() => this.nextStep()} previousStep={() => this.previousStep()} contentStep={CONTENT_STEP} lang={lang} /> ) : ( "" )} {this.state.currentStep === 4 ? ( <CreateDebitNoteStepFour mainState={this.state} updateState={this.updateStepFourState} previousStep={() => this.previousStep()} contentStep={CONTENT_STEP} lang={lang} /> ) : ( "" )} </Layout> ); } } export default withAuth(createDebitNote);
import React, { Fragment } from 'react'; import { Grid, Typography, Box, Button, IconButton } from '@material-ui/core' import api from '../../../api.js' import { withStyles, makeStyles } from '@material-ui/core/styles'; import CustomisedSuggestedSkillsChip from '../../../Components/CustomisedSuggestedSkillsChip' import { connect } from "react-redux"; import { addSkill, updateSuggestedSkills } from '../../../redux/actions/skill' import { withSnackbar } from 'notistack'; import ClearIcon from '@material-ui/icons/Clear' import CircularLoading from '../../../Components/LoadingBars/CircularLoading' const styles = theme => ({ '@global': { body: { backgroundColor: theme.palette.common.white, }, }, paper: { marginTop: theme.spacing(5), marginBottom: theme.spacing(5), display: 'flex', flexDirection: 'column', alignItems: 'center', }, }) class SuggestedSkillsView extends React.Component { constructor(props) { super(props); this.state = { skill: {}, description: [], isLoaded: false }; console.log("constructor" + this.props.suggestedSkills) this.handleAdd = this.handleAdd.bind(this) this.showDescription = this.showDescription.bind(this) } componentDidMount() { console.log("mount") api.skills.suggested().then(res => { if (res.data.response_code === 200) { console.log('200') console.log(res.data.suggested_skills) res.data.suggested_skills.forEach(skill => { skill.skill.id = parseInt(skill.id) }) this.props.updateSuggestedSkills(res.data.suggested_skills) //return array this.state.isLoaded = true } }).catch(err => { console.log(err) this.state.isLoaded = true }) } handleAdd(suggested, event) { const skillName = suggested.skill[0].skill const skillId = suggested.skill[0].id event.preventDefault() const action = key => ( <Fragment> <IconButton onClick={() => { this.props.closeSnackbar(key) }} size="small" style={{ color: 'white' }}> <ClearIcon /> </IconButton> </Fragment> ); if (this.props.currentSkills.some(skill => skill.id === skillId)) { console.log(skillName + " is already in current skills"); this.props.enqueueSnackbar(skillName + " is already in your current skills.", { variant: "warning", action }) } else { console.log(skillName + " is now added to skills"); api.skills.add({ "skill_add": [skillName] }).then(response => { if (response.data.response_code === 200) { this.props.addSkill({ id: skillId, skill: skillName }); //store this.props.enqueueSnackbar(skillName + ' added to your skills.', { variant: "success", action }) api.skills.suggested().then(res => { if (res.data.response_code === 200) { console.log('200') res.data.suggested_skills.forEach(skill => { skill.skill.id = parseInt(skill.id) }) this.props.updateSuggestedSkills(res.data.suggested_skills) //return array } }).catch() } else { this.props.enqueueSnackbar('Error adding skills.', { variant: "error", action }) } }).catch(error => { this.props.enqueueSnackbar('Error adding skills.', { variant: "error", action }) }) } } showDescription(jobSearchHistory) { this.setState({ description: jobSearchHistory }) console.log(jobSearchHistory) } render() { const { classes } = this.props; return ( <div className={classes.paper}> <Grid container direction="row" style={{ width: '100%' }}> <Grid item xs={12} md={12}> <Typography component="div"> <Box fontSize="h6.fontSize" m={2} letterSpacing={2} textAlign='left' color="primary.main" fontWeight="fontWeightBold" > SUGGESTED SKILLS <Typography variant='body2' color='textSecondary' align='left' style={{ fontSize: 'medium' }}> Based on your career interests, these are some skills that will get you further in your job hunt! </Typography> </Box> </Typography> </Grid> </Grid> {this.props.suggestedSkills !== null ? <Grid container style={{ padding: '1.5%', display: 'flex', justifyContent: 'center', flexWrap: 'wrap', }}> { this.props.suggestedSkills.length === 0 ? <Typography > <Box> Oops! You have not searched for jobs in the past one month... </Box> </Typography> : <div> {this.props.suggestedSkills.map((skill, index) => { return <CustomisedSuggestedSkillsChip suggested={skill} handleAdd={this.handleAdd} showDescription={this.showDescription} /> })} {this.state.description.length !== 0 ? <Box m={2} lineHeight='1'> <Typography variant='body2' color='textSecondary' display="inline"> {"Because you searched for "} </Typography> {this.state.description.map((desc, index) => { return index !== this.state.description.length - 1 ? index === this.state.description.length - 2 ?//no comma <span> <Typography style={{ fontWeight: 'bold' }} variant='body2' color='textSecondary' display="inline"> {desc} </Typography> <Typography variant='body2' color='textSecondary' display="inline"> {" and "} </Typography> </span> : <span> <Typography style={{ fontWeight: 'bold' }} variant='body2' color='textSecondary' display="inline"> {desc} </Typography> <Typography variant='body2' color='textSecondary' display="inline"> {", "} </Typography> </span> : <Typography style={{ fontWeight: 'bold' }} variant='body2' color='textSecondary' display="inline"> {desc} </Typography> }) } </Box> : <Box > <br /> </Box>} </div> } </Grid> : <Grid container justify='center'> <CircularLoading /> </Grid>} </div> ); } } const mapStateToProps = state => { return { suggestedSkills: state.skill.suggestedSkills, currentSkills: state.skill.skills } }; export default connect( mapStateToProps, { addSkill, updateSuggestedSkills } )(withSnackbar (withStyles(styles, { withTheme: true })(SuggestedSkillsView)));
var K = {};
const archivoTareas = require ("./tareas"); let accion = process.argv [2]; let tareas = [] switch(accion) { case 'listar': console.log("--------------------------------"); console.log('------Listado de tareas---------'); console.log('---------------------------------'); tareas = archivoTareas.leerJSON(); tareas.forEach((tarea1, index) => { console.log((index + 1) + '. ' + tarea1.titulo + ' -- ' + tarea1.estado); }); break; case "entrar": console.log("----------------------------"); console.log('-----Nueva tarea creada-----'); console.log('----------------------------'); let titulo = process.argv[3]; let tarea1 = { titulo: titulo, estado: 'pendiente' } archivoTareas.guardarTarea(tarea1); console.log(tarea1.titulo + ' -> ' + tarea1.estado); console.log("------------------------"); console.log('----Tarea Ingesada-------'); console.log('-------------------------'); break; case 'filtrar': let estados = process.argv[3]; console.log('----------Tareas ' + estados +"-----------"); console.log('--------------------------------------------'); tareas = archivoTareas.leerJSON(); let tareasFiltradas = tareas.filter(tarea1 => tarea1.estado == estados); console.log (tareasFiltradas); break; case undefined: console.log ('----Tenés que pasarme una acción-------------------------'); console.log ('Nueva tarea--- Entar y la tarea ---Para verlas---- listar'); console.log ('Para su Estado = filtrar y a)pendiente b) en progreso c) terminada'); break; default: console.log('No entiendo qué me estás pidiendo'); console.log('Las acciones disponibles son: listar, entrar , filtrar, '); break; }
import React, { Component } from 'react'; import Recipe from './Recipe' import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { getRecipes } from '../../actions/recipeActions'; class Recipes extends Component { componentDidMount() { this.props.getRecipes(); } render() { const { recipes } = this.props; return( <React.Fragment> <h1 className="display-4 mb-2"><span className="text-info">Recipe Book</span></h1> {recipes.map(recipe => <Recipe key={recipe.id} recipe={recipe}/> )} </React.Fragment> ) } } Recipes.propTypes = { recipes: PropTypes.array.isRequired, getRecipes: PropTypes.func.isRequired } const mapStateToProps = (state) => ({ recipes: state.recipe.recipes }) export default connect(mapStateToProps, {getRecipes})(Recipes);
/*! * optback.js | MIT (c) Shinnosuke Watanabe * https://github.com/shinnn/optback.js */ window.optback = function optback(args) { var maybeCallback = getCallback(args); var maybeOptions = args[args.length - 2]; if (!maybeOptions || typeof maybeOptions !== 'object') { maybeOptions = {}; } return { options: maybeOptions, callback: maybeCallback }; };
/** * Created by romankaczorowski on 07.12.2017. */ function checkFare(){ if($('#name').val()!='' && $('#surname').val() != ''){ $('#survived').attr("disabled", false); }else{ $('#survived').attr("disabled", true); } } (function($){ $(function(){ $(document).ready(function(){ checkFare(); }); $('#name').on('change', function(){ checkFare(); }); $('#surname').on('change', function(){ checkFare(); }); }); // end of document ready })(jQuery); // end of jQuery name space
let slider = $('.slider'); let arrowPrev = $('#slider_prev') let arrowNext = $('#slider_next') slider.slick({ autoplay: true, autoplaySpeed: 3000, speed: 300, infinite: true, slidesToShow: 3, slidesToScroll: 1, prevArrow: arrowPrev, nextArrow: arrowNext, responsive: [ { breakpoint: 998, settings: { slidesToShow: 2, slidesToScroll: 1, dots: true, } }, { breakpoint: 650, settings: { slidesToShow: 1, slidesToScroll: 1, dots: true, } } ] }); // slider.slick({ // autoplay: true, // autoplaySpeed: 3000, // speed: 300, // infinite: true, // slidesToShow: 3, // slidesToScroll: 1, // prevArrow: arrowPrev, // nextArrow: arrowNext, // }); // Изменение типа слайдера // let windowScrennCheck = window.matchMedia('(max-width: 992px'); // function screenTest(e) { // if (e.matches) { // } // } // screenTest(windowScrennCheck); // windowScrennCheck.addListener(screenTest);
(function () { if (!document.addEventListener) return let options = INSTALL_OPTIONS let element function updateElement () { element = INSTALL.createElement(options.container, element) element.setAttribute('app', 'readAbility') const size = `${options.size}em` element.style.fontSize = `${size}` } window.INSTALL_SCOPE = { ...INSTALL_SCOPE, setOptions (nextOptions) { options = nextOptions updateElement() }, setSize (nextOptions) { options = nextOptions element.style.fontSize = `${options.size}em` } } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', updateElement) } else { updateElement() } }())
const { Router } = require("express"); const passport = require("passport"); const SpotifyStrategy = require("passport-spotify").Strategy; const { pickAll } = require("ramda"); const { getAbsolutePath } = require("../utils"); const fileService = require("../services/fileService"); const pickProfileDetails = pickAll([ "id", "username", "displayName", "profileUrl", ]); const verifyProfile = ( accessToken, refreshToken, expires_in, profile, done ) => { const user = { ...pickProfileDetails(profile), auth: { accessToken, refreshToken, expires_in, }, }; fileService.write("user.json", user); done(null, user); }; const createRoutes = () => { const router = Router(); router.get( "/spotify", passport.authenticate("spotify", { scope: [ "user-library-read", "playlist-read-private", "playlist-modify-private", ], }) ); router.get( "/spotify/callback", passport.authenticate("spotify", { failureRedirect: "/login" }), (_, res) => res.redirect("/") ); return router; }; module.exports = (app, { spotify }) => { passport.use( new SpotifyStrategy( { ...spotify, callbackURL: getAbsolutePath("/auth/spotify/callback") }, verifyProfile ) ); passport.serializeUser((user, done) => done(null, user)); passport.deserializeUser((obj, done) => done(null, obj)); app.use(passport.initialize()); app.use(passport.session()); app.use("/auth", createRoutes()); return passport; };
"use strict"; const express = require("express"); const routes = express.Router(); const movies = [ { id: 1, title: "2001: A Space Odyssey", year: 1968, animated: false }, { id: 2, title: "The Godfather", year: 1972, animated: false }, { id: 3, title: "The Lion King", year: 1994, animated: true }, { id: 4, title: "Black Panther", year: 2018, animated: false }, ]; let nextId = 5; // GET /movies - respond with a JSON array of movies // specify routes.[method] // specify path ("/movies") // put arrow function with two paramaters - req(request) & res(response) routes.get("/movies", (req, res) => { res.json(movies); }); // GET single movie routes.get("/movies/:id", (req, res) => { const id = parseInt(req.params.id); const movie = movies.find((movie) => movie.id === id); if (movie) { res.json(movie); } else { res.status(404); res.send(`No movie with id ${id} exists.`); } }); // POST (add) movie routes.post("/movies", (req, res) => { const movie = req.body; movie.id = nextId++; movies.push(movie); res.status(201); res.json(movie); }); // DELETE movie routes.delete("/movies/:id", (req, res) => { const id = parseInt(req.params.id); const index = movies.findIndex((movie) => movie.id === id); if (index != -1) { movies.splice(index, 1); } res.status(204); // always have to have res.send() or res.json() res.send(); }); // export routes for use in server.js module.exports = routes;
module.exports = class Table { constructor(options = {}) { const { columns = [], delimiter = '\t', lineDelimiter = '\n', beforeLine = '', afterLine = '', beforeHeaderPlaceholder, afterHeaderPlaceholder } = options Object.assign(this, { columns, delimiter, lineDelimiter, beforeLine, afterLine, beforeHeaderPlaceholder, afterHeaderPlaceholder }) } header() { let header = this.columns.map(column => this.heading(column)).join(this.delimiter) header = this.wrapLine(header) if (this.beforeHeaderPlaceholder) { const before = this.columns.map(() => this.beforeHeaderPlaceholder).join(this.delimiter) header = this.wrapLine(before) + this.lineDelimiter + header } if (this.afterHeaderPlaceholder) { const after = this.columns.map(() => this.afterHeaderPlaceholder).join(this.delimiter) header += this.lineDelimiter + this.wrapLine(after) } return header } heading(column) { return typeof column === 'string' ? column : column.title } row(row) { const cells = this.columns.map(column => this.cell(column, row)) const content = cells.map(cell => this.escape(cell)).join(this.delimiter) return this.wrapLine(content) } wrapLine(content) { return `${this.beforeLine || ''}${content}${this.afterLine || ''}` } cell(column, row) { if (typeof column === 'string') { return row[column] } else if (typeof column.key === 'string') { return row[column.key] } else if (typeof column.format === 'function') { return column.format(row, column) } } escape(str) { return str.replace(new RegExp(`${this.delimiter}`, 'g'), ' ') } format(rows) { return [this.header(), ...rows.map(row => this.row(row))].join(this.lineDelimiter) } }
import React from 'react'; import Header from '../../../main/Header'; import useLocation from '../resources/useLocation'; import PositionDetails from './PositionDetails'; import PositionAccept from './PositionAccept'; const Position = (props) => { const [coords, errorMessage] = useLocation(); console.log(); return ( <div className='app-main'> <Header path={props.location.pathname} /> <main className='main'> <PositionDetails geo={coords} /> <PositionAccept wait={!errorMessage && !coords} error={errorMessage} /> </main> </div> ); }; export default Position;
import React, { useState } from 'react' import { useSelector, useDispatch } from 'react-redux'; import { Paper, Button, Card, CardContent, Typography, CardActionArea, CardMedia, Slide, TextField, Grid } from '@material-ui/core'; import { GroupAdd, AddToQueue } from '@material-ui/icons'; import axios from '../Api/api'; import { addChannel, addServer } from '../../actions'; export default function CreateJoinModal(props) { // Get State from Redux Store const { userId } = useSelector(state => state.user); const { activeServer, activeChannel } = useSelector(state => state.chat); const dispatch = useDispatch(); // Get data from props const { handleSnackMessage, modalType } = props; // Local state to control Modal Windows + Data fields const [mainVisible, setMainVisible] = useState(true); const [mainDirection, setMainDirection] = useState('left'); const [createVisible, setCreateVisible] = useState(false); const [createDirection, setCreateDirection] = useState('left'); const [joinVisible, setJoinVisible] = useState(false); const [joinDirection, setJoinDirection] = useState('left'); const [serverName, setServerName] = useState(''); const [serverId, setServerId] = useState(''); const [channelName, setChannelName] = useState(''); // Handles showing the Join Server window const showJoinServer = () => { setMainDirection('right'); setCreateDirection('left'); setJoinVisible(true); setMainVisible(false); } // Handles showing the Create Server window const showCreateServer = () => { setMainDirection('right'); setJoinDirection('left'); setCreateVisible(true); setMainVisible(false); } // Method to handle creation of servers const createServer = async (serverName, userId) => { try { const response = await axios.post(`/server/create?serverName=${serverName}&userId=${userId}`); dispatch(addServer(response.data)); const message = `Server ${response.data.server.split('-')[0]} with ID ${response.data.server.split('-')[1]} created`; handleSnackMessage(message, false); } catch (err) { handleSnackMessage(err.response.data, false); } } // Method to handle joining of servers const joinServer = async (serverId, userId) => { try { const response = await axios.post(`/server/join?serverId=${serverId}&userId=${userId}`); handleSnackMessage(response.data, true); } catch (err) { handleSnackMessage(err.response.data, false); } } // Method to handle creation of channels const createChannel = async (channelName, server) => { try { const response = await axios.post(`/channel/create?channelName=${channelName}&server=${server}&userId=${userId}`); dispatch(addChannel(response.data)); const message = `Server ${response.data.channel.split('-')[0]} with ID ${response.data.channel.split('-'[1])} created`; handleSnackMessage(message, false); } catch (err) { handleSnackMessage(err.response.data, false); } } // Method to handle renaming of servers const renameServer = async (serverName, serverId) => { try { const response = await axios.post(`/server/rename?serverName=${serverName}&serverId=${serverId}&userId=${userId}`); handleSnackMessage(response.data, true); } catch (err) { handleSnackMessage(err.response.data, false); } } // Method to handle renaming of channels const renameChannel = async (channelName, channelId) => { try { const response = await axios.post(`/channel/rename?channelName=${channelName}&channelId=${channelId}&serverId=${activeServer.split('-')[1]}&userId=${userId}`); handleSnackMessage(response.data, true); } catch (err) { handleSnackMessage(err.response.data, false); } } // Method to handle deleting of channels const deleteChannel = async (channelName, channelId) => { try { const response = await axios.delete(`/channel/delete?channelId=${channelId}&serverId=${activeServer.split('-')[1]}&userId=${userId}`); handleSnackMessage(response.data, true); } catch (err) { handleSnackMessage(err.response.data, false); } } // Handles keypress and calls the callback method const handleKeyPress = (e, callbackMethod) => { if (e.key === "Enter") { callbackMethod(); } } // Renders the Main Modal Window with options to Create / Join server const renderMainServer = () => { return ( <Slide direction={mainDirection} in={mainVisible} timeout={500} mountOnEnter unmountOnExit> <Grid container spacing={3} justify="center" alignItems="center"> <Grid item xs={12}> <Typography variant="h5" color="primary" align="center">Another server? Wow you're popular!</Typography> </Grid> <Grid item sm={6} xs={12}> <Card className="grid-card"> <CardActionArea onClick={() => showCreateServer()}> <CardContent> <Typography variant="h5" color="primary" gutterBottom>Create</Typography> <Typography variant="body1" paragraph>Create a server and invite all your buddies.</Typography> <CardMedia> <AddToQueue className="modal-card-icon" /> </CardMedia> <Button variant="contained" color="primary" className="modal-button">Join a server</Button> </CardContent> </CardActionArea> </Card> </Grid> <Grid item sm={6} xs={12}> <Card className="grid-card"> <CardActionArea onClick={() => showJoinServer()}> <CardContent> <Typography variant="h5" color="secondary" gutterBottom>Join</Typography> <Typography variant="body1" paragraph>Join a friends server and pwn some noobs!</Typography> <CardMedia> <GroupAdd className="modal-card-icon" /> </CardMedia> <Button variant="contained" color="secondary" className="modal-button">Join a server</Button> </CardContent> </CardActionArea> </Card> </Grid> </Grid> </Slide > ) } // Renders the Server Create Modal Window const renderServerCreate = () => { return ( <Slide direction={createDirection} in={createVisible} mountOnEnter unmountOnExit timeout={500}> <Grid container spacing={3} justify="center" alignItems="center"> <Grid item xs={12}> <Typography variant="h5" color="primary" align="center">Create a Server!</Typography> </Grid> <Grid item xs={12} className="grid-textfield"> <Typography variant="body1" paragraph> Enter a Server Name to create a server and get access to unlimited chat channels! </Typography> <TextField id="create-server-field" label="Server Name" value={serverName} onChange={(e) => setServerName(e.target.value)} onKeyPress={(e) => handleKeyPress(e, () => createServer(serverName, userId))} margin="dense" variant="outlined" autoComplete="off" /> </Grid> <Grid item xs={12} className="grid-button"> <Button className="modal-button" variant="contained" color="primary" onClick={() => createServer(serverName, userId)}>Create Server</Button> </Grid> </Grid> </Slide > ) } // Renders the Server Join Modal Window const renderServerJoin = () => { return ( <Slide direction={joinDirection} in={joinVisible} mountOnEnter unmountOnExit timeout={500}> <Grid container spacing={3} justify="center" alignItems="center"> <Grid item xs={12}> <Typography variant="h5" color="primary" align="center">Join a Server!</Typography> </Grid> <Grid item xs={12} className="grid-textfield"> <Typography variant="body1" paragraph> Enter a the Server Id provided by your friend and start chatting right now! </Typography> <TextField id="join-server-field" label="Server Id" value={serverId} onChange={(e) => setServerId(e.target.value)} onKeyPress={(e) => handleKeyPress(e, () => joinServer(serverId, userId))} margin="dense" variant="outlined" autoComplete="off" /> </Grid> <Grid item xs={12} className="grid-button"> <Button className="modal-button" variant="contained" color="primary" onClick={() => joinServer(serverId, userId)}>Join Server</Button> </Grid> </Grid> </Slide > ) } // Renders the Channel Create Modal Window const renderChannelCreate = () => { return ( <Slide direction='left' in={true} mountOnEnter unmountOnExit timeout={500}> <Grid container spacing={3} justify="center" alignItems="center"> <Grid item xs={12}> <Typography variant="h5" color="primary" align="center">Create a Channel!</Typography> </Grid> <Grid item xs={12} className="grid-textfield"> <Typography variant="body1" paragraph> Enter a Channel Name for your new channel and start chatting right now! </Typography> <TextField id="create-channel-field" label="Channel Name" value={channelName} onChange={(e) => setChannelName(e.target.value)} onKeyPress={(e) => handleKeyPress(e, () => createChannel(channelName, activeServer))} margin="dense" variant="outlined" autoComplete="off" /> </Grid> <Grid item xs={12} className="grid-button"> <Button className="modal-button" variant="contained" color="primary" onClick={() => createChannel(channelName, activeServer)}>Create Channel</Button> </Grid> </Grid> </Slide > ) } // Renders a modal with an input const renderServerRename = () => { return ( <Slide direction='left' in={true} mountOnEnter unmountOnExit timeout={500}> <Grid container spacing={3} justify="center" alignItems="center"> <Grid item xs={12}> <Typography variant="h5" color="primary" align="center">Rename Server</Typography> </Grid> <Grid item xs={12} className="grid-textfield"> <Typography variant="body1" paragraph> Enter a new Server Name for Server - {activeServer.split('-')[0]} </Typography> <TextField id="create-channel-field" label="Channel Name" value={serverName} onChange={(e) => setServerName(e.target.value)} onKeyPress={(e) => handleKeyPress(e, () => renameServer(serverName, activeServer.split('-')[1]))} margin="dense" variant="outlined" autoComplete="off" /> </Grid> <Grid item xs={12} className="grid-button"> <Button className="modal-button" variant="contained" color="primary" onClick={() => renameServer(serverName, activeServer.split('-')[1])}>Rename Server</Button> </Grid> </Grid> </Slide > ) } // Renders a modal to rename a channel const renderChannelRename = () => { return ( <Slide direction='left' in={true} mountOnEnter unmountOnExit timeout={500}> <Grid container spacing={3} justify="center" alignItems="center"> <Grid item xs={12}> <Typography variant="h5" color="primary" align="center">Rename Chanel</Typography> </Grid> <Grid item xs={12} className="grid-textfield"> <Typography variant="body1" paragraph> Enter a new Channel Name for Channel - {activeChannel.split('-')[0]} </Typography> <TextField id="create-channel-field" label="Channel Name" value={channelName} onChange={(e) => setChannelName(e.target.value)} onKeyPress={(e) => handleKeyPress(e, () => renameChannel(channelName, activeChannel.split('-')[1]))} margin="dense" variant="outlined" autoComplete="off" /> </Grid> <Grid item xs={12} className="grid-button"> <Button className="modal-button" variant="contained" color="primary" onClick={() => renameChannel(channelName, activeChannel.split('-')[1])}>Rename Channel</Button> </Grid> </Grid> </Slide > ) } // Renders a modal to delete a channel const renderChannelDelete = () => { return ( <Slide direction='left' in={true} mountOnEnter unmountOnExit timeout={500}> <Grid container spacing={3} justify="center" alignItems="center"> <Grid item xs={12}> <Typography variant="h5" color="primary" align="center">Rename Server</Typography> </Grid> <Grid item xs={12} className="grid-textfield"> <Typography variant="body1" paragraph> Are you sure you want to delete - {activeChannel.split('-')[0]} </Typography> </Grid> <Grid item xs={12} className="grid-button"> <Button className="modal-button" variant="contained" color="primary" style={{ backgroundColor: 'green', marginRight: "8px" }} onClick={() => deleteChannel(channelName, activeChannel.split('-')[1])}>Yes</Button> <Button className="modal-button" variant="contained" color="primary" style={{ backgroundColor: 'red', marginLeft: "8px" }} onClick={() => handleSnackMessage('Not deleting channel', false)}>No</Button> </Grid> </Grid> </Slide > ) } if (modalType === 'server-create-join') return ( <Paper className="container-prompt"> {renderMainServer()} {renderServerCreate()} {renderServerJoin()} </Paper > ) else if (modalType === 'channel-create') { return ( <Paper className="container-prompt"> {renderChannelCreate()} </Paper > ) } else if (modalType === 'server-rename') { return ( <Paper className="container-prompt"> {renderServerRename()} </Paper> ) } else if (modalType === "channel-rename") { return ( <Paper className="container-prompt"> {renderChannelRename()} </Paper> ) } else if (modalType === "channel-delete") { return ( <Paper className="container-prompt"> {renderChannelDelete()} </Paper> ) } }
function companyRegistration() { //YYYY/NNNNNNNN/NN SOUTH AFRICAN COMPANY REGISTRATION NUMBER }
import React, { useState } from 'react' import SimpleBar from 'simplebar-react' import 'simplebar/dist/simplebar.min.css' import flyfpv_gif from '../../assets/flyfpv_gif.gif' import smashjam_gif from '../../assets/smashjam_gif.gif' import bgwishlist_gif from '../../assets/bgwishlist_gif.gif' import diceroller_gif from '../../assets/diceroller_gif.gif' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faShoppingCart, faGamepad, faPuzzlePiece, faDiceD20 } from '@fortawesome/free-solid-svg-icons' import './Portfolio.scss' export default function Portfolio() { const [gifcard, setGifcard] = useState() const [gifVis, setGifVis] = useState('hidden') return ( <> <SimpleBar style={{width: '100%', height: '100%'}}> <div className='card-page' > <div className='card-wrapper'> <div className='card' onClick={() => { setGifVis('visible') setGifcard(flyfpv_gif) }}> <div className='card-title'> <FontAwesomeIcon icon={faShoppingCart} style={{color: 'lightskyblue'}}/> <h4>eCommerce Platform</h4> </div> <p>A site for FPV/Drone hobbyists to browse and buy parts or share their builds with the FPV community.</p> </div> <div className='card-links'> <a href='https://github.com/AndersLofgran/flyfpv' target='_blank noopener noreferrer'>Source Code</a> <a href='http://167.172.119.254:4499/#/' target='_blank noopener noreferrer'>Site</a> </div> </div> <div className='card-wrapper'> <div className='card' onClick={() => { setGifVis('visible') setGifcard(smashjam_gif) }}> <div className='card-title'> <FontAwesomeIcon icon={faGamepad} style={{color: 'lightskyblue'}}/> <h4>Game Companion</h4> </div> <p>Learn more about the game's fighters, news updates, and create or join in tournaments with friends! <br/><br/>(Under development)</p> </div> <div className='card-links'> <a href='https://github.com/Game-Companion-App/smash-jam' target='_blank noopener noreferrer'>Source Code</a> </div> </div> <div className='card-wrapper'> <div className='card' onClick={() => { setGifVis('visible') setGifcard(bgwishlist_gif) }}> <div className='card-title'> <FontAwesomeIcon icon={faPuzzlePiece} style={{color: 'lightskyblue'}}/> <h4>Board Game Wishlist</h4> </div> <p>Search through hundreds of games and find some new favorites.</p> </div> <div className='card-links'> <a href='https://github.com/AndersLofgran/NoDB-project' target='_blank noopener noreferrer'>Source Code</a> </div> </div> <div className='card-wrapper'> <div className='card' onClick={() => { setGifVis('visible') setGifcard(diceroller_gif) }}> <div className='card-title'> <FontAwesomeIcon icon={faDiceD20} style={{color: 'lightskyblue'}}/> <h4>Dice Roller</h4> </div> <p>Simple dice roller with custom dice saving, for all your role-playing needs. <br/><br/> (My first, self-taught project)</p> </div> <div className='card-links'> <a href='https://github.com/AndersLofgran/dice-roller' target='_blank noopener noreferrer'>Source Code</a> </div> </div> </div> <div className={`gif-${gifVis}`} onClick={() => { setGifVis('hidden') setGifcard() }}> <img src={gifcard} alt=''/> </div> </SimpleBar> </> ) }
/** A trie that is space efficient, and stores its children in a sorted array. */ function RadixTree(symbolPartial, symbolNotFound) { this.root = new RadixTree.Node(0, symbolPartial, "", null); this.partial = symbolPartial; this.notFound = symbolNotFound; this.searchstr = ""; this.searchInvalid = false; this.searchIndex = 0; this.searchNode = this.root; this.treeUpdated = false; }; /** Resets the consume feature */ RadixTree.prototype.resetConsume = function () { this.searchNode = this.root; }; /** You essentially pump in one symbol at a time to this function and it will keep track of if what you've pumped is a valid word, a part of a valid word, or could not possibly be a word @return Whatever you passed in for the partial or not found symbol along with the possibility of whatever you pumped in for the leaf nodes. */ RadixTree.prototype.consume = function (searchindex, character) { return this.searchNode.consume(searchindex, character, this); }; /** Checks whether something is in the tree or not. This was the predecessor of the consume method. Deprecated. @private @return Whatever you passed in for the partial or not found symbol along with the possibility of whatever you pumped in for the leaf nodes. */ RadixTree.prototype.check = function (searchterm) { var old = this.searchstr, olen = old.length; this.searchstr = searchterm; if (!this.treeUpdated && searchterm.length >= olen) { for (var i = 0; i < olen; i++) { if (searchterm.charCodeAt(i) != old.charCodeAt(i)) { this.searchIndex = 0; this.searchInvalid = false; this.searchNode = this.root; break; } } if (this.searchInvalid) return this.notFound; } else { this.searchIndex = 0; this.searchNode = this.root; this.treeUpdated = false; } return this.searchNode.check(this.searchIndex, searchterm, this); }; /** Set something in the tree as a leaf node. @return what you replaced. */ RadixTree.prototype.set = function (toAdd, newValue) { this.treeUpdated = true; return this.root.set(0, toAdd, newValue, this); }; /** Get something from the tree. @return Whatever you passed in for the partial or not found symbol along with the possibility of whatever you pumped in for the leaf nodes. */ RadixTree.prototype.get = function (toGet) { return this.root.get(0, toGet, this); }; /** Remove something from the tree. @return Whatever you passed in for the partial or not found symbol along with the possibility of whatever you pumped in for the leaf nodes. */ RadixTree.prototype.remove = function (toRemove) { return this.root.remove(0, toRemove, this) }; /** A node in the tree. */ RadixTree.Node = function (fromChar, isToken, searchToken, parent) { this.fromChar = fromChar; this.isToken = isToken; this.token = searchToken; this.children = []; this.chars = []; this.parent = parent; }; /** The internals for setting a leaf node in the tree @return the old value you replaced. */ RadixTree.Node.prototype.set = function (fromChar, toAdd, newValue, tree) { if (fromChar == toAdd.length) { var token = this.isToken; this.isToken = newValue; return token; } var searchChar = toAdd.charCodeAt(fromChar); var index = this.search(searchChar); var needNew = (index == this.chars.length) || (this.chars[index] != searchChar); if (needNew) { if (this.chars[index] < searchChar) index++; this.chars.splice(index, 0, searchChar); this.children.splice(index, 0, new RadixTree.Node(fromChar, newValue, toAdd.substring(fromChar), this)); } else { var replacingNode = this.children[index]; var sim = replacingNode.compare(fromChar, toAdd); if (sim < replacingNode.token.length) { var newNode = this.children[index] = new RadixTree.Node(fromChar, tree.partial, replacingNode.token.substring(0, sim), this); replacingNode.token = replacingNode.token.substring(sim); replacingNode.parent = newNode; newNode.children.push(replacingNode); newNode.chars.push(replacingNode.token.charCodeAt(0)); replacingNode.fromChar = fromChar + sim; newNode.set(fromChar + sim, toAdd, newValue, tree); } else { replacingNode.set(fromChar + sim, toAdd, newValue, tree); } } }; /** The internals for getting a leaf node in the tree @return see RadixTree.prototype.get */ RadixTree.Node.prototype.get = function (fromChar, toGet, tree) { if (fromChar == toGet.length) { return this.isToken; } var searchChar = toGet.charCodeAt(fromChar); var index = this.search(searchChar); var needNew = (index == this.chars.length) || (this.chars[index] != searchChar); if (needNew) { return tree.notFound; } else { var replacingNode = this.children[index]; var sim = replacingNode.compare(fromChar, toGet); if (sim < replacingNode.token.length) { if (sim + fromChar < toGet.length) return tree.notFound; return tree.partial; } else { return replacingNode.get(fromChar + sim, toGet, tree); } } }; /** Trim a node, handle stuffs if it's not a leaf. Or if it is one. Not a nice function. */ RadixTree.Node.prototype.trim = function (tree) { var l = this.children.length; if (l > 1) { this.isToken = tree.partial; } else { var parent = this.parent; var index = parent.search(this.token.charCodeAt(0)); if (l == 0) { parent.children.splice(index, 1); parent.chars.splice(index, 1); if (parent) { var token = parent.isToken; if (token == tree.partial) { parent.trim(tree); } } } else { var child = this.children[0]; parent.children[index] = child; child.token = this.token + child.token; child.fromChar = this.fromChar; } } }; /** The internals for getting rid of a leaf node in the tree @return see RadixTree.prototype.remove */ RadixTree.Node.prototype.remove = function (fromChar, toRemove, tree) { if (fromChar == toRemove.length) { var token = this.isToken; if (token != tree.notFound && token != tree.partial) { this.trim(tree); } return token; } var searchChar = toRemove.charCodeAt(fromChar); var index = this.search(searchChar); var needNew = (index == this.chars.length) || (this.chars[index] != searchChar); if (needNew) { return tree.notFound; } else { var replacingNode = this.children[index]; var sim = replacingNode.compare(fromChar, toRemove); if (sim < replacingNode.token.length) { if (sim + fromChar < toRemove.length) return tree.notFound; return tree.partial; } else { return replacingNode.remove(fromChar + sim, toRemove, tree); } } }; /** Honestly, don't use this, maintained for in case it comes in handy. @private @return see RadixTree.prototype.get */ RadixTree.Node.prototype.check = function (fromChar, searchterm, tree) { var t = this.token, tlen = t.length; var max = this.fromChar + tlen; if (fromChar < max) { var i = fromChar - this.fromChar; while (i < tlen && fromChar < searchterm.length) { if (searchterm.charCodeAt(fromChar) != t.charCodeAt(i)) { tree.searchInvalid = true; tree.searchIndex = fromChar; return tree.notFound; } fromChar++; i++; } tree.searchIndex = fromChar; if (fromChar < max && fromChar == searchterm.length) { return tree.partial; } } if (fromChar == max && fromChar >= searchterm.length) { if (this.isToken == tree.notFound) { tree.searchInvalid = true; } return this.isToken; } var searchChar = searchterm.charCodeAt(fromChar); var index = this.search(searchChar); var needNew = (index == this.chars.length) || (this.chars[index] != searchChar); if (needNew) { tree.searchInvalid = true; return tree.notFound; } else { var replacingNode = this.children[index]; tree.searchNode = replacingNode; return replacingNode.check(fromChar, searchterm, tree); } }; /** Internal for checking whether something is in the tree or not by consumption. @return see RadixTree.prototype.consume */ RadixTree.Node.prototype.consume = function (fromChar, nextChar, tree) { var t = this.token, tlen = t.length; var max = this.fromChar + tlen; if (fromChar < max) { var i = fromChar - this.fromChar; if (i < tlen) { if (nextChar != t.charCodeAt(i)) { return tree.notFound; } fromChar++; } if (fromChar < max) { return tree.partial; } else { return this.isToken; } } var index = this.search(nextChar); var needNew = (index == this.chars.length) || (this.chars[index] != nextChar); if (needNew) { return tree.notFound; } else { var replacingNode = this.children[index]; tree.searchNode = replacingNode; return replacingNode.consume(fromChar, nextChar, tree); } }; /** Compare the similarity in two strings from a point to whenever it's done. */ RadixTree.Node.prototype.compare = function (fromChar, toCompare) { var t = this.token, len = t.length, i = 0; while (i < len && toCompare.charCodeAt(fromChar++) == t.charCodeAt(i)) { i++; } return i; }; /** Search for the index of a char. @return same as Array.prototype.binaryIndexOf */ RadixTree.Node.prototype.search = function (character) { return this.chars.binaryIndexOf(character); }; /** Search for the index of an element that's comparable in an ordered list. @return {number} -1 or index. */ Array.prototype.binaryIndexOf = function (searchElement) { 'use strict'; var minIndex = 0; var maxIndex = this.length - 1; var currentIndex = 0; var currentElement; while (minIndex <= maxIndex) { currentIndex = (minIndex + maxIndex) / 2 | 0; currentElement = this[currentIndex]; if (currentElement < searchElement) { minIndex = currentIndex + 1; } else if (currentElement > searchElement) { maxIndex = currentIndex - 1; } else { return currentIndex; } } return currentIndex; }; /** Checks if the stream has any symbols in the tree that can be consumed. Will always consume the longest index. @return {Object} an indication of what was found. */ function canConsume(raw_stream, tree) { var data = raw_stream.data, len = data.length; var i = raw_stream.i, x = 0; tree.resetConsume(); var ret = -1; var retSym = tree.notFound; while (i < len) { var sym = tree.consume(x, data.charCodeAt(i)); if (sym === tree.notFound) return { len: ret, sym: retSym }; x++; i++; if (sym !== tree.partial) { ret = x; retSym = sym; } } return { len: ret, sym: retSym }; };
//github地址:https://github.com/SmileZXLee/uni-dingTalkHelper import config from '../config/index.js' function openDingTalk(errback) { return new Promise(function(resolve, reject) { if (!isApp()) { reject('请在App中运行!'); } else { if (plus.os.name === 'Android') { plus.runtime.launchApplication({ pname: config.dingTalkPname }, (err) => { reject(err.message); }); resolve(); } else if (plus.os.name === 'iOS') { plus.runtime.launchApplication({ action: config.dingTalkScheme }, (err) => { reject(err.message); }); resolve(); } } }) } function isApp() { let isApp = false; //#ifdef APP-PLUS isApp = true; //#endif return isApp; } function isDingtalkInstalled() { if (plus.runtime.isApplicationExist({ pname: config.dingTalkPname, action: config.dingTalkScheme })) { return true; } else { return false; } } function getNextClockFullTime(startMin, endMin, selectedWeeksArr) { const currentDate = getCurrentDate(); const randomTime = getRandomMinAndSecond(startMin, endMin); const currentDateFullRandomMin = getCurrentDateForYYMMDD() + ' ' + randomTime; const diffTime = getDiffTimeToCurrentTime(currentDateFullRandomMin); if (diffTime > 0 && selectedWeeksArr.includes(currentDate.getDay())) { //如果今天的时间符合要求 return currentDateFullRandomMin; } let nextDate = null; //寻找下一个符合要求的日期 for (let i = 0; i < 7; i++) { //获取1周内的所有日期,寻找临近的符合要求的日期 currentDate.setDate(currentDate.getDate() + 1); if (selectedWeeksArr.includes(currentDate.getDay())) { nextDate = currentDate; break; } } if (nextDate) { const nextDateFullRandomMin = getDateForYYMMDD(nextDate) + ' ' + randomTime; return nextDateFullRandomMin; } return '获取失败'; } function getCurrentDate() { return new Date(); } function getCurrentDateForYYMMDD() { const date = getCurrentDate(); return getDateForYYMMDD(date); } function getDateForYYMMDD(date) { return `${date.getFullYear()}-${fillZero2Two(date.getMonth() + 1)}-${fillZero2Two(date.getDate())}(${getWeekWithIndex(date.getDay())})`; } function getDateForYYMMDDHHMMSS() { const date = getCurrentDate(); return `${date.getFullYear()}-${fillZero2Two(date.getMonth() + 1)}-${fillZero2Two(date.getDate())}(${getWeekWithIndex(date.getDay())}) ${fillZero2Two(date.getHours())}:${fillZero2Two(date.getMinutes())}:${fillZero2Two(date.getSeconds())}`; } function getDiffTimeToCurrentTime(dateStr) { dateStr = getTimeWithoutWeek(dateStr); dateStr = dateStr.replace(/-/, "/").replace(/-/, "/"); var date1 = getCurrentDate(); var date2 = new Date(dateStr); var disTime = date2.getTime() - date1.getTime(); return disTime; } function getMinAndSecondDiff(startMin, endMin) { const startMinArr = startMin.split(':'); const startTotalMin = startMinArr.length === 2 ? (parseInt(startMinArr[0]) * 60 + parseInt(startMinArr[1])) : 0; const endMinArr = endMin.split(':'); const endTotalMin = endMinArr.length === 2 ? (parseInt(endMinArr[0]) * 60 + parseInt(endMinArr[1])) : 0; return endTotalMin - startTotalMin; } function getRandomMinAndSecond(startMin, endMin) { const startMinArr = startMin.split(':'); const startTotalMin = startMinArr.length === 2 ? (parseInt(startMinArr[0]) * 60 + parseInt(startMinArr[1])) : 0; const endMinArr = endMin.split(':'); const endTotalMin = endMinArr.length === 2 ? (parseInt(endMinArr[0]) * 60 + parseInt(endMinArr[1])) : 0; if (endTotalMin <= startTotalMin) { return `${fillZero2Two(startMin)}:${fillZero2Two(getRandom(0,60))}`; } const randomMin = getRandom(startTotalMin, endTotalMin); return `${fillZero2Two(randomMin / 60)}:${fillZero2Two(randomMin % 60)}:${fillZero2Two(getRandom(0,60))}`; } function getCurrentDateFullRandomMin(startMin, endMin) { return getCurrentDateForYYMMDD() + ' ' + getRandomMinAndSecond(startMin, endMin); } function getRandom(start, end) { let random = Math.random() return parseInt((start + (end - start) * random)) } function getWeekWithIndex(index) { const weekArr = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']; return weekArr[index]; } function getTimeWithoutWeek(time) { var regExp = /\(.*?\)/g; return time.replace(regExp, ''); } function fillZero2Two(value) { value = parseInt(value); return value >= 10 ? value : '0' + value; } module.exports = { isApp, openDingTalk, isDingtalkInstalled, getRandomMinAndSecond, getNextClockFullTime, getDateForYYMMDDHHMMSS, getMinAndSecondDiff }
import React, { PureComponent } from "react"; import { ScrollView, View } from "react-native"; import { Container, Text } from "@app/components"; import Color from "@app/assets/colors"; import Styles from "@app/assets/styles"; import { EmptyContent } from "@app/containers"; export default class BarangScreen extends PureComponent { renderHeader = () => { return ( <View style={Styles.containerRow}> <Text style={{ color: Color.grey }}>Nama Barang</Text> <View style={Styles.containerRowFlexEnd}> <View style={Styles.textTitleBarang}> <Text style={{ color: Color.grey }}>Tersedia</Text> </View> <View style={Styles.textTitleBarang}> <Text style={{ color: Color.grey }}>Dibutuhkan</Text> </View> </View> </View> ); } renderItem = ({ data }) => ( data.map((item, index) => ( <View style={{ marginTop: 24 }} key={index}> <View style={Styles.containerRow}> <Text style={Styles.textFieldBarang}>{item.name}</Text> <View style={Styles.containerRowFlexEnd}> <View style={Styles.textTitleBarang}> <Text style={Styles.textFieldBarang}>{item.real_qty}</Text> </View> <View style={Styles.textTitleBarang}> <Text style={Styles.textFieldBarang}>{item.max_qty}</Text> </View> </View> </View> <View style={Styles.dividerTableBarang} /> </View> )) ) render() { if (this.props.data == null || this.props.data.length == 0) { return ( <ScrollView style={Styles.containerDefault}> <Container> <EmptyContent content={"Barang Kosong"} /> </Container> </ScrollView> ); } else { return ( <ScrollView style={Styles.containerDefault}> <Container> {this.renderHeader()} {this.renderItem({ data: this.props.data })} </Container> </ScrollView> ); } } }
import React from "react"; import "./Footer.css"; import logoAstra from "../../../assets/images/logos/logo-astra-rojo.png"; import logoDLR from "../../../assets/images/logos/DLR-LogoBlanco.png"; import { Container, Row, Col } from 'react-bootstrap'; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; const Footer = () => { return ( <footer> <Container> <Row> <Col md={4} xs={12} className="right-line"> <div className="mw-90"> <div className="location"> <h3>Matriz</h3> <p>Carretera a San Luis Rio Colorado, Km 8.5, Col. Ex-Ejido Coahuila</p> <div className="list-tile"> <FontAwesomeIcon className="icon" icon="phone" /> <span>Tel. +52 (686) 561-63-53</span> </div> <div className="list-tile"> <FontAwesomeIcon className="icon" icon="envelope" /> <span>ventas@dlr.com.mx</span> </div> </div> <div> <h3>Tijuana</h3> <p>Carretera Aeropuerto #11-1</p> <div className="list-tile"> <FontAwesomeIcon className="icon" icon="phone" /> <span>Tel. +52 (664) 647-87-95</span> </div> <div className="list-tile"> <FontAwesomeIcon className="icon" icon="envelope" /> <span>ventas@dlr.com.mx</span> </div> </div> </div> </Col> <Col md={4} xs={12} className="right-line"> <div className="mw-90"> <h3>Ensenada</h3> <p>Carretera Ensenada - Tecate Km 104, El Sauzal de Rodríguez</p> <div className="list-tile"> <FontAwesomeIcon className="icon" icon="phone" /> <span>Tel. +52 (646) 178-10-20</span> </div> <div className="list-tile"> <FontAwesomeIcon className="icon" icon="envelope" /> <span>ventas@dlr.com.mx</span> </div> </div> </Col> <Col md={4} xs={12}> <div className="mw-90 center-all"> <img className="logo" src={logoDLR} alt="logo-astradev"></img> <p>@2019 DLR. Derechos Reservados</p> <div> <span>Desarrollado por:</span> <a className="astra-logo" href="http://astradev.co/" target="_blank" rel="noopener noreferrer" > <img height={22} src={logoAstra} alt="logo AstraDev" /> </a> </div> </div> </Col> </Row> </Container> </footer> ); }; export default Footer;
const BaseMvnxError = require('./BaseMvnxError') class ArtifactNotFoundError extends BaseMvnxError { constructor (context) { super('EARTIFACTNOTFOUND', context) } get details () { let text = `Could not retrieve the aritfact "${this.context.artifactName}". Tried the following sources:` if (this.context.localArtifactPath) { text += `\n * Local Path: ${this.context.localArtifactPath}` } if (this.context.remoteArtifactUrl) { text += `\n * Remote URL: ${this.context.remoteArtifactUrl}` } return text } get solution () { return 'Please try the following options:\n' + ' * Check if you\'ve spelled the artifact correctly.\n' + ' * Check if the artifact is available in the local/remote repository.\n' + ' * Omit --ignore-local/--only-local.' } } module.exports = ArtifactNotFoundError
import React from 'react'; import PropTypes from 'prop-types'; export default class NewItemForm extends React.Component { constructor(props) { super(props); this.state = { old_item: '', name: '', price: '', description: '', category: '', limited: false, quantity: '', discountable: true }; this.changeHandler = this.changeHandler.bind(this); this.changeHandlerPrice = this.changeHandlerPrice.bind(this); this.checkHandler = this.checkHandler.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } getInitialState() { return { name: '', price: '', description: '', category: '', limited: false, quantity: '', discountable: true }; } changeHandler(event) { let input = event.target.value; let arr = ['name', 'price', 'description', 'category', 'quantity']; let index = arr.indexOf(event.target.name); this.setState({ [arr[index]]: input }); } changeHandlerPrice(event) { let input = parseFloat(event.target.value) .toFixed(3) .toString() .slice(0, -1); this.setState({ price: input }); } checkHandler(event) { let arr = ['limited', 'discountable']; let index = arr.indexOf(event.target.name); arr[index] === 'limited' ? this.setState({ [arr[index]]: !this.state[arr[index]], quantity: '' }) : this.setState({ [arr[index]]: !this.state[arr[index]] }); } handleSubmit(event) { event.preventDefault(); $.ajax({ url: '/POS/items/new', dataType: 'json', type: 'POST', data: { item: { name: this.state.name, price: this.state.price, description: this.state.description, category: this.state.category, limited: this.state.limited, quantity: this.state.quantity, discountable: this.state.discountable, user_id: this.props.user } }, success: function(data) { this.setState(prevState => { return { old_item: prevState.name }; }); this.setState(this.getInitialState()); }.bind(this) }); } render() { return ( <div> {this.state.old_item && ( <div className="alert alert-success"> <strong>Item '{this.state.old_item}' saved</strong> </div> )} <form onSubmit={this.handleSubmit}> <label htmlFor="name">Name:</label> <input name="name" type="string" required="required" placeholder="Item name" value={this.state.name} onChange={this.changeHandler} className="form-control w-50" /> <br /> <label htmlFor="price">Price:</label> <input name="price" type="number" required="required" placeholder="$" step="0.01" value={this.state.price} onChange={this.changeHandler} onBlur={this.changeHandlerPrice} className="form-control w-25" /> <br /> <label htmlFor="description">Description:</label> <input name="description" type="string" placeholder="Description" value={this.state.description} onChange={this.changeHandler} className="form-control w-50" /> <br /> <label htmlFor="category">Category:</label> <input name="category" type="string" placeholder="Category" value={this.state.category} onChange={this.changeHandler} className="form-control w-50" /> <br /> <label htmlFor="limited">Limited: </label> <input name="limited" type="checkbox" checked={this.state.limited} onChange={this.checkHandler} /> <br /> {this.state.limited && ( <React.Fragment> <label htmlFor="quantity">Quantity:</label> <input name="quantity" type="number" required="required" placeholder="Quantity" value={this.state.quantity} onChange={this.changeHandler} className="form-control w-50" /> <br /> </React.Fragment> )} <label htmlFor="discountable">Discountable: </label> <input name="discountable" type="checkbox" checked={this.state.discountable} onChange={this.checkHandler} /> <br /> <input type="submit" value="Submit" className="btn btn-primary" /> <a className="btn btn-secondary mx-2" href="/POS/items" role="button"> Back to items </a> </form> </div> ); } }
import styled from "styled-components"; const TitlePrimitive = function ({component, variant, className, children, center, ...props}) { const Component = `${component || "h2"}`; return <Component className={className}>{children}</Component>; }; export const StyledTitle = styled(TitlePrimitive)` font-family: "Futura PT"; line-height: 1.25em; margin-top: 0; margin-bottom: 0.5em; ${(props) => (props.variant == "h1" ? "font-size: 2.75rem; " : "")} ${(props) => (props.variant == "h2" ? "font-size: 1.75rem; font-weight: 300;" : "")} ${(props) => (props.variant == "h3" ? "font-size: 1.75rem; font-weight: 300; margin-bottom:16px;" : "")} ${(props) => (props.variant == "h4" ? "font-family: 'Lato',sans-serif; font-size: 1.25rem; color: #0A5A87;" : "")} ${(props) => (props.variant == "h5" ? "font-family: 'Lato',sans-serif; font-size: 1.1rem; color: #0A5A87;" : "")} ${(props) => props.center && "text-align: center;"} @media screen and (min-width: 960px) { ${(props) => (props.variant == "h1" ? "font-size: 3rem; " : "")} ${(props) => (props.variant == "h2" ? "font-size: 2rem; " : "")} ${(props) => (props.variant == "h3" ? "font-size: 1.85rem; " : "")} } @media screen and (min-width: 1280px) { ${(props) => (props.variant == "h1" ? "font-size: 3.5rem; " : "")} ${(props) => (props.variant == "h2" ? "font-size: 2.5rem; " : "")} ${(props) => (props.variant == "h3" ? "font-size: 2.25rem; " : "")} } @media screen and (min-width: 1690px) { ${(props) => (props.variant == "h1" ? "font-size: 3.75rem; " : "")} ${(props) => (props.variant == "h2" ? "font-size: 2.75rem; " : "")} ${(props) => (props.variant == "h3" ? "font-size: 2.5rem; " : "")} ${(props) => (props.variant == "h4" ? "font-size: 1.25rem; " : "")} } `;
function loadMeshData(string){ var lines = string.split("\n"); var positions = []; var normals = []; var vertices = []; for( var i = 0; i < lines.length; i++){ var parts = lines[i].trimRight().split(' '); } }
import styled from 'styled-components' const Oops = () => { return ( <Error> <h3>Could not fetch data for the resource</h3> </Error> ); } const Error = styled.h3` font-size:30px; margin-top:50px; text-align:center; color:red; ` export default Oops;
import React from 'react'; import { Form, Input, Button, Typography, message } from 'antd'; import { useMutation } from 'react-query'; import { useHistory } from 'react-router-dom'; import axios from 'axios'; import Cookies from 'js-cookie'; import { Container } from './SignIn.styles'; import { Link } from '../SingUp/SignUp.styles'; import auth from '../../Utils/auth'; import { API_URL } from '../../Utils/config'; const layout = { labelCol: { span: 8 }, wrapperCol: { span: 16 }, }; const tailLayout = { wrapperCol: { offset: 8, span: 16 }, }; const validateMessages = { required: '${label} is required!', types: { email: '${label} is not validate email!', }, }; const postLogin = async ({ email, password }) => { const { data } = await axios.post(`${API_URL}/auth/login`, { email, password, }); return data; }; const SignIn = ({ setForm }) => { const history = useHistory(); const [mutateLogin, { isLoading, error }] = useMutation(postLogin, { onSuccess: (response) => { const { tokens, user } = response; auth.storeToken(tokens.access.token, tokens.refresh.token); Cookies.set('role', user.role); history.push('/issues'); }, }); React.useEffect(() => { if (error) { renderError(); } }, [error]); const onFinish = async ({ email, password }) => { await mutateLogin({ email, password }); }; const renderError = () => { const { response: { data }, } = error; return message.error(data.message); }; return ( <Container> <Typography.Title level={3}>Login</Typography.Title> <Form {...layout} name="signin" initialValues={{ remember: true }} onFinish={onFinish} validateMessages={validateMessages} > <Form.Item name="email" label="Email" rules={[{ required: true, type: 'email' }]}> <Input /> </Form.Item> <Form.Item name="password" label="Password" rules={[{ required: true }]}> <Input type="password" /> </Form.Item> <Form.Item {...tailLayout}> <Button type="primary" htmlType="submit" style={{ marginRight: 8 }} loading={isLoading}> Log in </Button> Or <Link onClick={() => setForm('signup')}>register now!</Link> </Form.Item> </Form> </Container> ); }; export default SignIn;
import {GET_REPOS, PROFILE_ERROR, GET_PROFILE, GET_PROFILES, CLEAR_PROFILE, UPDATE_PROFILE} from '../Actions/types' const initialState = { profile: null, profiles: [], repos:[], error: {}, loading: true, } const profile = (state=initialState, action)=>{ const {type, payload} = action switch (type) { case GET_PROFILE: return { ...state, profile: payload, loading: false } case GET_PROFILES: return{ ...state, profiles:payload, loading: false } case UPDATE_PROFILE: return{ ...state, profile: payload, loading: false } case PROFILE_ERROR: return { ...state, error: payload, loading: false } case CLEAR_PROFILE: return{ ...state, profile: null, repos: [], loading: false } case GET_REPOS: return{ ...state, repos:payload, loading: false } default: return state } } export default profile
import React, { Component } from 'react' import './Estilo.scss' const Linguagem = props => { console.log(props); return ( <div className="ling"> {props.nome} <br/> {props.nota} </div> ) } class Contador extends Component { state = { contador: 0 } render() { setTimeout(() => this.setState({contador: this.state.contador + 1}), 2000) console.log(this.state); return ( <div> Contador atualmente em: {this.state.contador} </div> ); } } export class App extends Component { render() { return ( <div> <Linguagem nome='JS' nota={5} /> <Linguagem nome='C' nota={8} /> <Contador /> </div> ); } } export default App;
import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); export default new Vuex.Store({ state: { authenticated: false, isAdmin: false, isParamUserID: false, //verify if uid === this.$route.params.id avatar: '' }, mutations: { setAuth(state, flag) { state.authenticated = flag; }, setAdmin(state, flag) { state.isAdmin = flag; }, setParamUserID(state, flag) { state.isParamUserID = flag; }, setAvatar(state, payload) { state.avatar = payload; } }, actions: { setAuth(state, flag) { state.commit('setAuth', flag); }, setAdmin(state, flag) { state.commit('setAdmin', flag); }, setParamUserID(state, payload) { let { uid, paramID } = payload; try { uid = parseInt(uid); paramID = parseInt(paramID); } catch (error) { console.log(`Vuex can't parse state var: `, error); } state.commit('setParamUserID', uid === paramID); }, setAvatar(state, payload) { state.commit('setAvatar', payload); } }, getters: { isAuthenticated: state => state.authenticated, isAdmin: state => state.isAdmin, isParamUserID: state => state.isParamUserID, getAvatar: state => state.avatar } });
const embeds = require('../util/embeds.js'); exports.help = { syntax: 'purge <AMOUNT>', required: 'MANAGE_MESSAGES', description: 'Delete up to 100 messages at once that are less than 2 weeks old.' }; exports.run = async (client, message, args) => { if (isNaN(args[0]) || args[0] < 1 || args[0] != Math.floor(args[0])) { return embeds.errorSyntax(message.channel, client[message.guild.id].prefix + this.help.syntax); } if (args[0] > 100) { return embeds.error(message.channel, 'You can delete a maximum of 100 messages at once.', 'ERROR'); } const deleted = await message.channel.bulkDelete(args[0], true); embeds.feedback(message.channel, `Deleted \`${deleted.size}\`/\`${args[0]}\` messages.`, '', 5000); // var deleted = 0; // while (deleted < args[0]) { // const messages = await message.channel.bulkDelete(args[0] - deleted > 100 ? 100 : args[0] - deleted, true); // deleted += messages.size; // } };
/** @babel */ import request from 'request-promise'; import {format as urlFormat, parse as urlParse} from 'url'; const pkg = require('../package.json'); let currentToken = null; function callGithub(apiMethod, {httpMethod = 'GET', query = {}} = {}) { const parsed = urlParse(`https://api.github.com${apiMethod}`, true); delete parsed.search; const passedQuery = Object.assign({}, query); if (currentToken) { passedQuery.access_token = currentToken; } const uri = urlFormat(Object.assign(parsed, { query: passedQuery, })); return request({ uri, method: httpMethod, json: true, headers: { 'Content-Type': 'application/json;charset=utf-8', 'User-Agent': `${pkg.name} (Atom plugin)`, }, }); } function issueComparator(a, b) { if (a.state !== b.state) { return a.state === 'open' ? -1 : 1; } return Number(a.number) - Number(b.number); } export default { async authenticate() { currentToken = atom.config.get(`${pkg.name}.userToken`); }, async listWatchedRepos() { await this.authenticate(); return await callGithub('/user/subscriptions'); }, async issuesForRepo(user, repo, query = {}) { await this.authenticate(); const issues = await(callGithub(`/repos/${user}/${repo}/issues`, {query})); issues.sort(issueComparator); return issues; }, };
import React from 'react'; import { Dimensions, LayoutAnimation, StyleSheet, Text, TextInput, TouchableOpacity, TouchableWithoutFeedback, View, } from 'react-native'; import Ionicons from 'react-native-vector-icons/Ionicons'; import { useNavigation } from '@react-navigation/native'; const Layout = { window: { width: Dimensions.get('window').width, }, }; const SearchContainerHorizontalMargin = 10; const SearchContainerWidth = Layout.window.width - SearchContainerHorizontalMargin * 2; const SearchIcon = () => ( <View style={styles.searchIconContainer}> <Ionicons name="ios-search" size={18} color="#ccc" /> </View> ); class PlaceholderButtonSearchBar extends React.PureComponent { static defaultProps = { placeholder: 'Search', placeholderTextColor: '#ccc', } render() { return ( <View style={styles.container}> <TouchableWithoutFeedback hitSlop={{ top: 10, left: 10, bottom: 5, right: 10 }} onPress={this._handlePress}> <View style={styles.searchContainer} pointerEvents='box-only'> <TextInput editable={false} placeholder={this.props.placeholder} placeholderTextColor={this.props.placeholderTextColor} selectionColor={this.props.selectionColor} style={styles.searchInput} /> <SearchIcon /> </View> </TouchableWithoutFeedback> </View> ); } _handlePress = () => { this.props.navigator.push('search'); }; } class SearchBar extends React.PureComponent { state = { text: '', showCancelButton: false, inputWidth: SearchContainerWidth, }; _textInput: TextInput; componentDidMount() { requestAnimationFrame(() => { this._textInput.focus(); }); } _handleLayoutCancelButton = (e: Object) => { if (this.state.showCancelButton) { return; } const cancelButtonWidth = e.nativeEvent.layout.width; requestAnimationFrame(() => { LayoutAnimation.configureNext({ duration: 200, create: { type: LayoutAnimation.Types.linear, property: LayoutAnimation.Properties.opacity, }, update: { type: LayoutAnimation.Types.spring, springDamping: 0.9, initialVelocity: 10, }, }); this.setState({ showCancelButton: true, inputWidth: SearchContainerWidth - cancelButtonWidth, }); }); }; render() { let { inputWidth, showCancelButton } = this.state; let searchInputStyle = {}; if (this.props.textColor) { searchInputStyle.color = this.props.textColor; } if (this.props.textFontFamily) { searchInputStyle.fontFamily = this.props.textFontFamily; } return ( <View style={styles.container}> <View style={[styles.searchContainer, { width: inputWidth }]}> <TextInput ref={view => { this._textInput = view; }} clearButtonMode="while-editing" onChangeText={this._handleChangeText} value={this.state.text} autoCapitalize="none" autoCorrect={false} returnKeyType="search" placeholder="Search" placeholderTextColor={this.props.placeholderTextColor || '#ccc'} onSubmitEditing={this._handleSubmit} style={[styles.searchInput, searchInputStyle]} /> <SearchIcon /> </View> <View key={ showCancelButton ? 'visible-cancel-button' : 'layout-only-cancel-button' } style={[ styles.buttonContainer, { opacity: showCancelButton ? 1 : 0 }, ]}> <TouchableOpacity style={styles.button} hitSlop={{ top: 15, bottom: 15, left: 15, right: 20 }} onLayout={this._handleLayoutCancelButton} onPress={this._handlePressCancelButton}> <Text style={{ fontSize: 17, color: this.props.tintColor || '#007AFF', ...(this.props.textFontFamily && { fontFamily: this.props.textFontFamily }), }}> {this.props.cancelButtonText || 'Cancel'} </Text> </TouchableOpacity> </View> </View> ); } _handleChangeText = text => { this.setState({ text }); this.props.onChangeQuery && this.props.onChangeQuery(text); }; _handleSubmit = () => { let { text } = this.state; this.props.onSubmit && this.props.onSubmit(text); this._textInput.blur(); }; _handlePressCancelButton = () => { if (this.props.onCancelPress) { this.props.onCancelPress(this.props.navigation.goBack); } else { this.props.navigation.goBack(); } }; } export default function (props) { const navigation = useNavigation(); return ( <SearchBar {...props} navigation={navigation} /> ); } const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'row', }, buttonContainer: { position: 'absolute', right: 0, top: 0, paddingTop: 15, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', }, button: { paddingRight: 17, paddingLeft: 2, }, searchContainer: { height: 30, width: SearchContainerWidth, backgroundColor: '#f2f2f2', borderRadius: 5, marginHorizontal: SearchContainerHorizontalMargin, marginTop: 10, paddingLeft: 27, }, searchIconContainer: { position: 'absolute', left: 7, top: 6, bottom: 0, }, searchInput: { flex: 1, fontSize: 14, paddingTop: 1, }, });
import Router from 'next/router' import NProgress from 'nprogress' // ** // import styles // ** import "./page-loader.scss" export default PageLoader = () => { NProgress.configure({ showSpinner: false }) Router.onRouteChangeStart = () => { NProgress.start() } Router.onRouteChangeComplete = () => NProgress.done() Router.onRouteChangeError = () => NProgress.done() }
/** * Chat.js * @author wawbz * @namespace BZCHAT */ if (typeof jQuery === "undefined") { throw new Error("BZCHAT requires jQuery"); } if (typeof io === "undefined") { throw new Error("BZCHAT requires socket.io"); } if (typeof moment === "undefined") { throw new Error("BZCHAT requires moment.js"); } var BZCHAT = { varsion: "1.0.0" }; (function () { $.fn.scrollDown = function () { // jQuery function var el = $(this); el.scrollTop(el[0].scrollHeight); }; String.prototype.capitalize = function () { return this.charAt(0).toUpperCase() + this.slice(1); } BZCHAT.config = {}; BZCHAT.element = { chatMessage: ".direct-chat-messages", chatContact: ".direct-chat-contacts", sendMessage: '#send-message', messageToSend: '#message-to-send' }; BZCHAT.config.Router = { SocketServer: 'http://192.168.5.60:8888', SessionUser: '/users/login/session', OnlineUser: '/users/online', Notification: '/chat/notify' }; BZCHAT.config.Avatar = { have: function (avatar) { return 'https://main.baezeni.com/people-manager/pic/' + avatar; }, no: function (avatar) { return 'https://dummyimage.com/50x50/496173/ffffff&text=' + avatar; } }; })(); (function () { BZCHAT.fn = {}; BZCHAT.fn.findObjectByKey = function (array, key, value) { for (var i = 0; i < array.length; i++) { if (array[i][key] === value) { return array[i]; } } return null; } })(); (function () { BZCHAT.templateUser = function (user) { var name = user.email.split("@")[0].capitalize(); var avatar = user.avatar ? BZCHAT.config.Avatar.have(user.avatar) : BZCHAT.config.Avatar.no(name.substr(0, 1)) var html = '<li>' + ' <a href="javascript:void(0);" data-userid="' + user.id + '">' + ' <img class="contacts-list-img" src="' + avatar + '">' + ' <div class="contacts-list-info">' + ' <span class="contacts-list-name">' + ' ' + name + ' <i id="online-status-' + user.id + '" class="fa ' + (user.status === 'Y' ? 'fa-circle user-online' : 'fa-circle-o user-offline') + '"></i> ' + ' <span id="unread-number-' + user.id + '" data-toggle="tooltip" title="3 New Messages" class="badge notify-number"></span>' + ' <small class="contacts-list-date pull-right">' + moment(user.datetime).calendar() + '</small>' + ' </span>' + ' <span class="contacts-list-msg"></span>' + ' </div>' + ' </a>' + '</li>'; return html; }; BZCHAT.templateMessage = { left: function (msg, action) { var user = BZCHAT.fn.findObjectByKey(BZCHAT.User.Online, "id", msg.user_from_id); var name = user.email.split("@")[0].capitalize(); var avatar = user.avatar ? BZCHAT.config.Avatar.have(user.avatar) : BZCHAT.config.Avatar.no(name.substr(0, 1)) var html = '<div class="direct-chat-msg">' + ' <div class="direct-chat-info clearfix">' + ' <span class="direct-chat-name pull-left">' + name + '</span>' + ' <span class="direct-chat-timestamp pull-right">' + moment(msg.datetime).calendar() + '</span>' + ' </div>' + ' <img class="direct-chat-img" src="' + avatar + '" alt="' + name + '">' + ' <div class="direct-chat-text">' + ' ' + msg.message.toString() + ' </div>' + '</div>'; $(BZCHAT.element.chatMessage).append(html); this.buttom(action); this.readMessage(msg); }, right: function (msg, action) { var user = BZCHAT.fn.findObjectByKey(BZCHAT.User.Online, "id", msg.user_from_id); var name = user.email.split("@")[0].capitalize(); var avatar = user.avatar ? BZCHAT.config.Avatar.have(user.avatar) : BZCHAT.config.Avatar.no(name.substr(0, 1)) var html = '<div class="direct-chat-msg right">' + ' <div class="direct-chat-info clearfix">' + ' <span class="direct-chat-name pull-right">' + name + '</span>' + ' <span class="direct-chat-timestamp pull-left">' + moment(msg.datetime).calendar() + '</span>' + ' </div>' + ' <img class="direct-chat-img" src="' + avatar + '" alt="' + name + '">' + ' <div class="direct-chat-text">' + ' ' + msg.message.toString() + ' </div>' + ' </div>'; $(BZCHAT.element.chatMessage).append(html); this.buttom(action); }, buttom: function (action) { if (action) { $(BZCHAT.element.chatMessage).animate({ scrollTop: $(BZCHAT.element.chatMessage).prop("scrollHeight") }, 500); } else { $(BZCHAT.element.chatMessage).scrollDown(); } }, readMessage: function (data) { if (data.status && data.status === "UR") { BZCHAT.socket.emit("chat.update", data); } } } })(); (function () { BZCHAT.GET = function (URL, type, dataType) { var dataAPI = ""; var isSuccess = false; var response = $.ajax({ type: type, url: URL, data: dataType, async: false, cache: false, success: function () { isSuccess = true; } }).responseText; if (!isSuccess) { dataAPI = ""; } dataAPI = JSON.parse(response); return dataAPI; }; BZCHAT.SessionUser = BZCHAT.GET(BZCHAT.config.Router.SessionUser, 'GET', 'JSON'); BZCHAT.GetUnreadMessage = function () { return BZCHAT.GET(BZCHAT.config.Router.Notification, 'GET', 'JSON'); }; })(); /** * @function is connect socket server */ (function (io) { BZCHAT.socket = io(BZCHAT.config.Router.SocketServer, { transports: ['websocket'], upgrade: false }); BZCHAT.socket.emit("join", BZCHAT.SessionUser); })(io); /** * @User is manager user online */ (function () { BZCHAT.User = {}; BZCHAT.User.Active = ''; BZCHAT.User.UserList = function () { var user = BZCHAT.GET(BZCHAT.config.Router.OnlineUser, 'GET', 'JSON'); var template = ''; for (var i in user) { if (user[i].id !== BZCHAT.SessionUser.id) { template += BZCHAT.templateUser(user[i]); } } $(BZCHAT.element.chatContact).find('ul').html(template); return user; }; BZCHAT.socket.on('user joined', function (user) { $('#online-status-' + user.id).removeClass('fa-circle-o user-offline').addClass('fa-circle user-online'); }); BZCHAT.socket.on('leavechat', function (user) { $('#online-status-' + user.id).removeClass('fa-circle user-online').addClass('fa-circle-o user-offline'); }); BZCHAT.User.Online = BZCHAT.User.UserList(); })(); /** * @Message is manager chat message */ (function () { BZCHAT.Message = {}; BZCHAT.socket.on("history.message", function (messages) { BZCHAT.Message.History(messages); }); BZCHAT.Message.History = function (messages) { for (var i in messages) { var msg = messages[i]; if (msg.user_from_id === BZCHAT.SessionUser.id) { BZCHAT.templateMessage.right(msg, false); } else { BZCHAT.templateMessage.left(msg, false); } } }; BZCHAT.Message.GET = function (message) { BZCHAT.templateMessage.left(message, true); }; BZCHAT.Message.SEND = function () { var message = $(BZCHAT.element.messageToSend).val(); if (!BZCHAT.User.Active) { alert("No user to send"); return false; } if (!message) return false; var data = { user_from_id: BZCHAT.SessionUser.id, user_to_id: BZCHAT.User.Active, message: message, datetime: new Date() }; BZCHAT.socket.emit('chat.message', data); BZCHAT.templateMessage.right(data, true); $(BZCHAT.element.messageToSend).val(''); $(BZCHAT.element.messageToSend).focus() }; BZCHAT.Message.Room = function (user_from_id, user_to_id) { if (user_from_id === user_to_id) { return false; } var room = [user_from_id, user_to_id].sort().join(''); //Array sort and join need to do both server and client BZCHAT.socket.emit('chat.room', { room: room, user: BZCHAT.SessionUser }); $(BZCHAT.element.chatMessage).empty(); BZCHAT.User.Active = user_to_id; }; BZCHAT.Message.notify = function (data) { var NotifyAll = 0; for (var user in data) { var number = data[user].length; NotifyAll += number; $('#unread-number-' + user).text(number > 0 ? number : ''); } if (!NotifyAll) { $('.badge.notify-number').text(''); } $('#all-notify').text(NotifyAll || ''); }; BZCHAT.Message.notifyMe = function (data) { var user = BZCHAT.fn.findObjectByKey(BZCHAT.User.Online, "id", data.user_from_id); var name = user.email.split("@")[0].capitalize(); if (!("Notification" in window)) { alert("This browser does not support desktop notification"); } else if (Notification.permission === "granted") { var notification = new Notification(name + " Said :", { icon: '/assets/img/ico-128.png', body: data.message, }); setTimeout(function () { notification.close() }, 3000) } else if (Notification.permission !== "denied") { Notification.requestPermission(function (permission) { if (permission === "granted") { var notification = new Notification(name + " Said :", { icon: '/assets/img/ico-128.png', body: data.message, }); setTimeout(function () { notification.close() }, 3000) // notification.onclick = function () { // window.open("http://stackoverflow.com/a/13328397/1269037"); // }; } }); } }; BZCHAT.socket.on('send.message', function (message) { if (BZCHAT.User.Active && BZCHAT.User.Active === message.user_from_id) { //if chat message box is open BZCHAT.Message.GET(message); } else { // if no send notification BZCHAT.socket.emit("chat.notify", message); } }); BZCHAT.socket.on('get.notify', function (info) { setTimeout(function () { BZCHAT.Message.notify(info.data); BZCHAT.Message.notifyMe(info.message); }, 1000); }); BZCHAT.Message.UpdateNotify = function () { setTimeout(function(){ var notify = BZCHAT.GetUnreadMessage(); BZCHAT.Message.notify(notify); },1500); }; })(); (function ($) { BZCHAT.Message.UpdateNotify(); $(document).on('click', BZCHAT.element.chatContact + ' li a', function () { var userID = $(this).data('userid'); BZCHAT.Message.Room(BZCHAT.SessionUser.id, userID); BZCHAT.Message.UpdateNotify(); }); $(BZCHAT.element.messageToSend).keydown(function (e) { if (e.keyCode === 13) { BZCHAT.Message.SEND(); if (e.preventDefault) e.preventDefault(); return false; } }); $(document).on('click', BZCHAT.element.sendMessage, function () { BZCHAT.Message.SEND(); }); $(document).on('click', '[data-widget="chat-pane-toggle"]', function () { var box = $(this).parents('.direct-chat').first(); box.toggleClass('direct-chat-contacts-open'); }); $('ul.contacts-list li').click(function () { $('.direct-chat').removeClass('direct-chat-contacts-open'); }); })($);
var _ = require("lodash");//underscore with more stuff var C4Fct = { //urlConnect4MP : "http://localhost:8080", //"http://www.felixdebon.fr", //dev //urlConnect4MP : "http://www.felixdebon.fr", //prod arrayToString: function(array){ var n = array.length; var s = ""; for (var i=0;i<n;i++){ s += array[i].toString(); } return s; }, // Returns a random integer between min (included) and max (included) getRandomIntInclusive : function(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }, // Chose randomly an element in an array and return it getRandomElementInArray : function (array){ //var n = array.length; var index = this.getRandomIntInclusive(0,array.length-1); return array[index]; }, isPseudoUsed: function (pseudo, players){ for ( var prop in players) { if( players[prop].pseudo === pseudo){ return true; } } return false; }, displayPlayers: function (players){ console.log("--- Players --- :"); for ( var prop in players) { console.log(players[prop].pseudo); } }, emptyGrid : function(){ //can contain 3 differents value: // 0 : for empty emplacement // 1 : for red disc // 2 : for blue disk return [//game map [0, 0, 0, 0, 0, 0],//first column (grid's top first) [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], ]; }, game: function(level){ this.pseudo = null; this.opponentPseudo = null; this.turn = 1 + Math.floor(2*Math.random());// 1 or 2 randomely (tells us who is going to play by his code, 1 always start) this.lastMove = {}; this.opponentType = "robot"; //can be "robot" ou "human" this.level = level || "normal"; this.nbMove = 0; this.winner = 0; this.players = {}; this.classNames = ["noDisc","redDisc","blueDisc"]; this.urlSolver = "http://connect4.gamesolver.org/solve?"; //this.urlConnect4MP = "http://connect4.gamesolver.org/solve?"; this.me = {}; this.opponent = {}; this.position = [];//list of column's numbers successively played, first column is 1 this.grid = C4Fct.emptyGrid();//game matrix map this.aligned = C4Fct.emptyGrid();//tells where to display the check symbol when 4 discs or more are aligned this.messages = [];//chat messages this.inputValue = ''; }, /** * For each value of the scores array we determine where it appears (positions) and how often * and then a decreasing sort is made on the score value **/ getArrayStat: function(array){ //var array = [2,2,3,15,6,100,100]; //console.log('array:',array); var n = array.length; var stat = {}; for(var i=0;i<n;i++){ if ( array[i] != 100 ){//score of 100 on a column means that the column is full. if ( !stat[array[i]] ){ stat[array[i]] = {occurrence: 1, positions:[i], value:array[i]}; }else{ stat[array[i]].occurrence++; stat[array[i]].positions.push(i); } } } //console.log('stat:',stat); var statSorted =_.sortBy(stat, 'value').reverse(); //console.log('statSorted:',statSorted); return statSorted; }, /** * Dans le tableau retourné par C4Fct.getArrayStat() cet objet donne l'indice à choisir pour jouer * en fonction du niveau de jeu et du nombre de choix possibles **/ // getRankToPLayFromLevelAndNbrChoices : { // "easy": [0,0,1,2,3,4,5], // "normal": [0,0,0,1,2,3,4], // "hard": [0,0,0,0,1,2,3], // "very hard":[0,0,0,0,0,0,0], // }, infoFromLevel : { "easy": { img:"R2D2.png", speech:"01001000 01101001 00100001...", rankToPLayFromLevelAndNbrChoices:[0,0,1,2,3,4,5] }, "normal":{ img:"6PO.png", speech:"Your chances of survival are 3720 to 1...", rankToPLayFromLevelAndNbrChoices:[0,0,0,1,2,3,4] } , "hard":{ img:"Terminator.png", speech:"Sarah Connor ?", rankToPLayFromLevelAndNbrChoices:[0,0,0,0,1,2,3] }, "very hard":{ img:"HAL9000.png", speech:"Dave, this conversation can serve no purpose anymore. Goodbye.",//My mind is going... I can feel it rankToPLayFromLevelAndNbrChoices:[0,0,0,0,0,0,0] }, }, /** * get the solution from Pascal Pons's server with "alpha beta pruning" algorithm (cf. game.url) * and make the computer play **/ computerMove: function(that){ var game = that.state.game; var pos = C4Fct.arrayToString(game.position); //var pos ="32";//console.log('pos=',pos); var options = { method: 'GET' }; //ReferenceError: Can't find variable: fetch iphone !! fetch(game.urlSolver+"pos="+pos, options).then(function(res) { return res.json(); }).then(function(data){ //console.log('data=',data); // data.score = score for each playable column: winning moves have a positive score and losing moves // have a negative score. The absolute value of the score gives you the number of moves // before the end of the game. Hence best moves have highest scores. // score of 100 on a column means that the column is full. var array = data.score; var stat = C4Fct.getArrayStat(array); var n = stat.length; //console.log('n:'+ n+ ' stat:',stat); var columnPlayed; //donne l'incide du tableau stat à choisir pour jouer à ce nivaau là var rank = C4Fct.infoFromLevel[game.level].rankToPLayFromLevelAndNbrChoices[n-1]; //columnPlayed = C4Fct.getRandomElementInArray(stat[n-1].positions); columnPlayed = C4Fct.getRandomElementInArray(stat[rank].positions); that.state.game.turn = 1; var lastMove = C4Fct.addDisc(game, columnPlayed); that.state.game.lastMove = lastMove; that.state.game.lastMove.blink = true; game.nbMove++; //we update the game state that.forceUpdate(); //that.setState({ game : game }); var win = C4Fct.testWin(game, lastMove); if ( win ){//computer win game.winner = 1; game.turn = null; alert("You loose!"); }else{//pass turn to user if ( that.state.game.nbMove === 42 ){ alert("draw 0-0 !"); } game.turn = 2; //that.state.game.turn = 2; } //that.setState({ game : game }); that.forceUpdate(); }.bind(that) ) .catch(function(error) { console.log('There has been a problem with your fetch operation 4: ' + error.message); }); }, /** * Try to add a disc at a given column on the game's grid, * if it's possible we update the game object **/ addDisc: function(game, col){ var canAddDisc = false; //we go from bottom to top of connect4's board searching for a free cell (with column=col) for(var line=5;line>=0;line--){ if ( game.grid[col][line] === 0 && line >= 0){ canAddDisc = true; game.grid[col][line] = game.turn; game.position.push(col+1);//+1 because first column start by 1 in string notation, not 0. return {col:col,line:line, turn:game.turn, blink:false}; } } if ( !canAddDisc ){ return false; } }, /** * Try to remove a disc at a given column from the game's grid, **/ removeDisc: function(game, col){ var canRemoveDisc = false; //we go from top to bottom of connect4's board searching for a disc (with column=col) for(var line=0;line<6;line++){ if ( game.grid[col][line] > 0 ){ canRemoveDisc = true; game.grid[col][line] = 0; game.position.pop();//Remove the last element of the array return {col:col,line:line, turn:3-game.turn, blink:false}; } } if ( !canRemoveDisc ){ return false; } }, // test_generic : function(use1, a , b, use2, c, d, e, f, game, lastMove, optionCheck){ // for(var k=1;k<=3;k++){ // if ( (use1 || (lastMove.col + a*k >= b)) && (use2 || (lastMove.line + c*k >= d)) ){ // if ( game.grid[lastMove.col + e*k][lastMove.line + f*k] === lastMove.turn){ // nbAlignedDisc++; // if ( optionCheck ){ // game.aligned[lastMove.col + e*k][lastMove.line + f*k] = true; // } // }else{ // break; // } // } // } // }, //Check if the last move win (i.e. at least four pieces connected) testWin: function(game, lastMove){//we will record the aligned discs in game.aligned matrix var count = function(nbAlignedDisc, game){ //count both direction if ( nbAlignedDisc >= 4 ){//yes it can be > 4 ! return true; }else{ game.aligned = C4Fct.emptyGrid(); return false; } } //use to verify if we have 4 chips horizontally aligned //if so the 'aligned' grid will be update var test_alignment_EW = function(game, lastMove){ var nbAlignedDisc = 1; game.aligned[lastMove.col][lastMove.line] = true; //Horizontal right direction //C4Fct.test_generic(0,1,7,1,0,0,1,0,game, lastMove, optionCheck); for(var k=1;k<=3;k++){ if ( lastMove.col+k < 7 ){ if ( game.grid[lastMove.col+k][lastMove.line+0] === lastMove.turn){ nbAlignedDisc++; game.aligned[lastMove.col+k][lastMove.line+0] = true; }else{ break; } } } //console.log('nbAlignedDisc:'+nbAlignedDisc); //C4Fct.test_generic(0,-1,0,1,0,0,-1,0,game, lastMove, optionCheck); //Horizontal left direction for(var k=1;k<=3;k++){ if ( lastMove.col-k >= 0 ){ if ( game.grid[lastMove.col-k][lastMove.line+0] === lastMove.turn){ nbAlignedDisc++; game.aligned[lastMove.col-k][lastMove.line+0] = true; }else{ break; } } } //console.log('nbAlignedDisc:'+nbAlignedDisc); //count in both direction return count(nbAlignedDisc, game); } var test_alignment_NS = function(game, lastMove){ var nbAlignedDisc = 1; game.aligned[lastMove.col][lastMove.line] = true; //vertical down for(var k=1;k<=3;k++){ if ( lastMove.line + k < 6 ){ if ( game.grid[lastMove.col+0][lastMove.line + k] === lastMove.turn){ nbAlignedDisc++; game.aligned[lastMove.col+0][lastMove.line + k] = true; }else{ break; } } } //vertical up doesn't need to be checked (it will always be empty due to gravity effect...) //count return count(nbAlignedDisc, game); } var test_alignment_NW = function(game, lastMove){ var nbAlignedDisc = 1; game.aligned[lastMove.col][lastMove.line] = true; //toward North/west for(var k=1;k<=3;k++){ if ( (lastMove.col - k >= 0) && (lastMove.line - k >= 0) ){ if ( game.grid[lastMove.col-k][lastMove.line - k] === lastMove.turn){ nbAlignedDisc++; game.aligned[lastMove.col - k][lastMove.line- k] = true; }else{ break; } } } //toward South/Est for(var k=1;k<=3;k++){ if ( (lastMove.col + k < 7 ) && (lastMove.line + k < 6 ) ){ if ( game.grid[lastMove.col + k][lastMove.line + k] === lastMove.turn){ nbAlignedDisc++; game.aligned[lastMove.col + k][lastMove.line + k] = true; }else{ break; } } } //count return count(nbAlignedDisc, game); } var test_alignment_NE = function(game, lastMove){ var nbAlignedDisc = 1; game.aligned[lastMove.col][lastMove.line] = true; //toward North/Est for(var k=1;k<=3;k++){ if ( (lastMove.col + k < 7 ) && (lastMove.line - k >= 0 ) ){ if ( game.grid[lastMove.col + k][lastMove.line - k] === lastMove.turn){ nbAlignedDisc++; game.aligned[lastMove.col + k][lastMove.line - k] = true; }else{ break; } } } //toward South/West for(var k=1;k<=3;k++){ if ( (lastMove.col - k >= 0 ) && (lastMove.line + k < 6 ) ){ if ( game.grid[lastMove.col - k][lastMove.line + k] === lastMove.turn){ nbAlignedDisc++; game.aligned[lastMove.col - k][lastMove.line + k] = true; }else{ break; } } } //count return count(nbAlignedDisc, game); } //we use the functions if ( test_alignment_EW(game, lastMove) ){ return true; } else if ( test_alignment_NS(game, lastMove) ){ return true; } else if ( test_alignment_NW(game, lastMove) ){ return true; } else if ( test_alignment_NE(game, lastMove) ){ return true; } else { return false; } }, // getPlayers: function(that, callback){ // $.ajax({ // url: "http://www.felixdebon.fr/connect4/getplayers", // //url: "/connect4/getplayers", // dataType: 'json', // cache: false, // success: function(data) { // callback(data); // console.log("data with jquery:",data); // }.bind(that), // error: function(xhr, status, err) { // console.log('There has been a problem with your $.ajax operation 2: ' + err.message); // }.bind(that) // }); // }, getPlayers: function(that, callback){//doesn't work in production !(I replaced it by a websocket) var options = { method: 'GET' }; fetch("www.felixdebon.fr/connect4/getplayers", options).then(function(res) { return res.json(); }) .then(function(data){ //console.log("players recue=",data); callback(data); }.bind(that) ) .catch(function(error) { console.log('There has been a problem with your fetch operation 2: ' + error.message); }); }, //for asynchronous test with mocha test: function(callback){ setTimeout(function(){ callback(); },500); }, }; module.exports = C4Fct;
const ts = require("typescript"); const { pathsToModuleNameMapper } = require("ts-jest"); /** @type { (dirname: string) => import('@jest/types').Config.InitialOptions } */ module.exports.makePackageConfig = (dirname) => { const packageJson = require(dirname + "/package.json"); const packageBaseName = packageJson.name.replace("@jspsych/", ""); // based on https://github.com/formium/tsdx/blob/462af2d002987f985695b98400e0344b8f2754b7/src/createRollupConfig.ts#L51-L57 const tsCompilerOptions = ts.parseJsonConfigFileContent( ts.readConfigFile(dirname + "/tsconfig.json", ts.sys.readFile).config, ts.sys, dirname ).options; return { preset: "ts-jest", moduleNameMapper: pathsToModuleNameMapper(tsCompilerOptions.paths, { prefix: "<rootDir>/" }), testEnvironment: "jsdom", testEnvironmentOptions: { fetchExternalResources: true, pretendToBeVisual: true, url: "http://localhost/", }, displayName: { name: packageBaseName, color: packageBaseName === "jspsych" ? "white" : "cyanBright", }, }; };
import React from 'react'; import FacebookLogin from 'react-facebook-login'; export const Facebook = () => { const state = { isLoggedIn: false, userId: '', name: '', email: '', picture: '' } const responseFacebook = (response) => { state.isLoggedIn = true; state.userId = response.userId; state.name = response.name; state.email = response.email; state.picture = response.picture.data.url; } const componentClicked = () => console.log("clicked"); let fbContent; if (state.isLoggedIn) { fbContent = null } else { fbContent = ( < FacebookLogin appId = '456455218825532' autoLoad = { true } fields = "name,email,picture" onclick = { componentClicked } callback = { responseFacebook } />); } return ( < div > { fbContent } < /div> ) }
// example/demo08-android-call-javascript/src/case2/other.jsx import React from 'react'; import bridge from '../bridge'; import cs from './index.module.scss'; export default class Other extends React.PureComponent { state = { content: '' } render() { const { content } = this.state; return <div className={cs.other}> <h3>我是Other组件</h3> Other组件的内容: {content} </div> } componentDidMount() { bridge.on('VOLUME_DOWN', param => { this.setState({ content: '音量调小了' }); }); bridge.on('VOLUME_UP', param => { this.setState({ content: param.msg }); }); } }
import arg from 'arg'; export default function parseArgs(rawArgs) { const args = arg( { '--simple': Boolean, '--git': Boolean, '--install': Boolean, '--version': Boolean, '--help': Boolean, '-s': '--simple', '-g': '--git', '-i': '--install', '-v': '--version', '-h': '--help' }, { argv: rawArgs.slice(1) } ); return { command: args['_'], options: { skipPrompts: args['--simple'] || false, git: args['--git'] || false, runInstall: args['--install'] || false, version: args['--version'] || false, help: args['--help'] || false } } }
// =========== // BALL STUFF // =========== function Ball(descr) { for (var property in descr) { this[property] = descr[property]; } } var g_ball = new Ball({ cx: 450, cy: 515, radius: 10, xVel: -3, yVel: -8, color1: 'red', color2: 'yellow' }); var grd, rN; Ball.prototype.update = function () { // Remember my previous position var prevX = this.cx; var prevY = this.cy; // Compute my provisional new position (barring collisions) var nextX = prevX + this.xVel; var nextY = prevY + this.yVel; // Bounce off the paddles if (g_paddle1.collidesWith(prevX, prevY, nextX, nextY, this.radius) ) { var gpx = g_paddle1.cx if(nextX < gpx - 12) { if(this.xVel < 0) { if(this.xVel > -10) this.xVel -= 1.3; if(this.xVel <= -4) this.yVel * 0.5; } else this.xVel *= -0.5; } else if(nextX > gpx + 12) { if(this.xVel > 0) { if(this.xVel < 10) this.xVel += 1.3; if(this.xVel >= 4) this.yVel * 0.5; } else this.xVel *= -0.5; } if(this.yVel<20) this.yVel *= -1.015; } // Bounce off the bricks if (collideWhichBrick(allBricks[0],prevX, prevY, nextX, nextY, this.radius) || collideWhichBrick(allBricks[1],prevX, prevY, nextX, nextY, this.radius) || collideWhichBrick(allBricks[2],prevX, prevY, nextX, nextY, this.radius) || collideWhichBrick(allBricks[3],prevX, prevY, nextX, nextY, this.radius) ) { this.yVel *= -1; hitBrick.color= g_canvas.style.backgroundColor; hitBrick.active = false; updateScore(); } // Bounce off top and bottom edges if (nextY < 0) this.yVel *= -1; if (nextY > g_canvas.height) { this.reset(); updateLives(); } // Bounce off left and right edges if (nextX < 0 || nextX > g_canvas.width) this.xVel *= -1; // Reset if we fall off the left or right edges // ...by more than some arbitrary `margin` var margin = 4 * this.radius; if (nextX < -margin || nextX > g_canvas.width + margin) { this.reset(); } this.cx += this.xVel; this.cy += this.yVel; }; Ball.prototype.reset = function () { this.cx = 600; this.cy = 220; this.xVel = -3; this.yVel = 8; }; Ball.prototype.render = function (ctx) { grd = ctx.createRadialGradient(this.cx, this.cy, this.radius/(this.cy/2), this.cx, this.cy, this.radius/1.1); grd.addColorStop(0, this.color1); grd.addColorStop(1, this.color2); ctx.fillStyle = grd; fillCircle(ctx, this.cx, this.cy, this.radius); }; function fillCircle(ctx, x, y, r) { ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.fill(); }
'use strict' var isObject = require('is-object') var values = exports.values = { timestamp: function () { return new Date().getTime() } } exports.ServerValue = { TIMESTAMP: { '.sv': 'timestamp' } } var isSv = exports.is = function isServerValue (object) { return isObject(object) && values.hasOwnProperty(getSv(object)) } exports.parse = function parseServerValue (object) { var value = isSv(object) && getSv(object) if (!value) throw new Error('Invalid ServerValue: ' + JSON.stringify(object)) return values[value]() } function getSv (object) { return object['.sv'] }
/* heading */ if(typeof jQuery == "undefined"){ //alert("jQuery not installed ! try again") }else{ // alert("jQuery installed sucessfully") } /* detecting a click */ $("#circle1").click(function(){ alert("rec circle is clicked") }) $("#square1").click(function(){ alert("orange square is clicked") }) $("#square2").click(function(){ alert("green square is clicked") }) /* changing website content */ $("#circle2").hover(function(){ //hover or click $("#det-click").html("refresh the page to go back") //or //alert($("#det-click").html()) $("iframe").attr("src","https://timesofindia.indiatimes.com/") }) /* changing styles */ $("#circle3").click(function(){ //$("#cng-click").html("this topic is changing styles") //alert($("#cng-click").html()) //$("#circle3").css("background-color", "green") $("#circle3").fadeOut("slow") //we can use insted of fadeout() to hide() //alert("red circle is clicked to dis appear") }) $("#square3").click(function(){ $("#square3").hide() }) $("#square4").click(function(){ $("#square4").hide() }) //or /*$("#cng-style").click(function(){ $("#cng-style").css("display", "none") })*/ // all will disappear //or /*$("#cng-style").click(function(){ $(this).css("display", "none") })*/ /* fading content*/ $("#fadebtn-out").click(function(){ $("#fadetxt").fadeOut() }) $("#fadebtn-in").click(function(){ $("#fadetxt2").fadeIn() }) /* $("#togglebtn").click(function(){ $("#toggletext").fadeOut() }) $("#togglebtn").click(function(){ $("#toggletext").fadeIn() }) meathod 1 */ /* $("#togglebtn").click(function(){ if($("#toggletext").css("display") == "none"){ $("#toggletext").fadeIn() }else{ $("#toggletext").fadeOut() } }) meathod 2 */ var textDisplay = true $("#togglebtn").click(function(){ if(textDisplay){ $("#toggletext").fadeOut(function(){ textDisplay = false }) }else{ $("#toggletext").fadeIn(function(){ textDisplay = true }) } }) // meathod 3, meathod 2 is better /* animating content */ $("#circle4").click(function(){ //alert("clicked circle4") $("#circle4").animate({ width : "400px", height: "400px", marginLeft : "100px", marginTop : "100px", backgroundColor: "green", }, 2500, function(){ $("#circle4").css("background-color" , "green") }) }) /*AJAX*/ /* regular expressions*/ //var regex = /e/g // try with i or g //var string = "you are not subscribed,you are not subscribed" //var result = string.match(regex) //alert(result) /* form validation system*/ function isEmail(email) { var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/; return regex.test(email); } $("#submit").click(function(){ var errorMessage = "" var fieldsMissing ="" if ($("#Email").val() == ""){ fieldsMissing += "<br>Email" } if ($("#Telephone").val() == ""){ fieldsMissing += "<br>phonenumber" } if ($("#Password").val() == ""){ fieldsMissing += "<br>password" } if ($("#c-Password").val() == ""){ fieldsMissing += "<br>confirm pasword" } if(fieldsMissing != ""){ errorMessage += "<p>the following fields are missimg:" + fieldsMissing } if(isEmail($("#Email").val()) == false) { errorMessage += "<p>your email is not found ! try again</p>" } if($.isNumeric($("#Telephone").val()) == false){ errorMessage += "<p>your phonenumber is incorrect or not found ! try again</p>" } if($("#Password").val() != $("#c-Password").val()){ errorMessage += "<p>your password is incorrect or not matching! please try again</p>" } //alert(errorMessage) if(errorMessage != ""){ $("#errorMessage").html(errorMessage) }else{ $("#sucessfull").show() } })
import React from "react"; import {Route, Switch} from "react-router-dom"; import PrivateRoutes from "../utils/PrivateRoute"; import Login from "../components/Pages/auth/Login"; import Register from "../components/Pages/auth/Register"; import Landing from "../components/layouts/Landing"; import Genre from "../components/Pages/genre/Genre"; import GenreCreate from "../components/Pages/genre/Genre-create"; import GenreUpdate from "../components/Pages/genre/Genre-edit"; import Movie from "../components/Pages/movie/Movie"; import MovieCreate from "../components/Pages/movie/Movie-create"; import MovieUpdate from "../components/Pages/movie/Movie-edit"; // import MovieUpdate from "../components/Pages/movie/Movie-edit"; // import ProfileCreate from "../components/Pages/profile/Profile-create"; const TopLevelRoutes = () => ( <Switch> <Route path="/" exact component={Login} /> <Route path="/register" exact component={Register} /> <PrivateRoutes path="/dashboard" exact component={Landing} /> <PrivateRoutes path="/genre" exact component={Genre} /> <PrivateRoutes path="/genre-create" exact component={GenreCreate} /> <PrivateRoutes path="/genre/:id" exact component={GenreUpdate} /> <PrivateRoutes path="/movie" exact component={Movie} /> <PrivateRoutes path="/movie-create" exact component={MovieCreate} /> <PrivateRoutes path="/movie/:id" exact component={MovieUpdate} /> {/* <PrivateRoutes path="/movie/:id" exact component={MovieUpdate} /> */} </Switch> ) export default TopLevelRoutes;
const { HtmlUrlChecker } = require("broken-link-checker"); const { WebClient, LogLevel } = require('@slack/web-api'); const httpServer = require("http-server"); const Sitemapper = require("sitemapper"); const sitemap = new Sitemapper(); const path = require("path"); const fs = require("fs"); /** * This script uses the programmatic API of https://github.com/stevenvachon/broken-link-checker to check the links (including images, iframes, and client-side redirects) for either an individual page or for a whole site. Usage: # Log successes as well as failures. $ DEBUG=1 node scripts/check-links.js "https://www.pulumi.com" */ let [ baseURL, maxRetries ] = process.argv.slice(2); let retryCount = 0; if (!baseURL) { throw new Error("A baseURL (e.g., 'https://pulumi.com') is required."); } if (!maxRetries || Number.isNaN(maxRetries)) { maxRetries = 0; } // Globally patch bhttp, broken-link-checker's HTTP library. We do with sadness because // BLC doesn't expose an API for setting custom HTTP headers, and many services reject // HTTP requests that lack certain headers (like Accept) or other characteristics. const bhttp = require("bhttp"); const oldRequest = bhttp.request; bhttp.request = function() { const [ url, options, callback ] = arguments; // Modify request options. // https://git.cryto.net/joepie91/node-bhttp/src/branch/master/lib/bhttp.js#L886 options.headers.accept = "*/*"; // Some CDNs reject requests that don't provide an acceptable accept-encoding header. // The checker's underlying HTTP library seems to support deflate compression best, so // we use that for all requests. options.headers["accept-encoding"] = "deflate"; return oldRequest.apply(this, arguments); }; // Run. checkLinks(); // Runs the checker. async function checkLinks() { const checker = getChecker([]); // Load all URLs. const urls = await getURLsToCheck(baseURL); // Start the checker. checker.enqueue(baseURL); urls.forEach(url => checker.enqueue(url)); } // Returns an instance of either HtmlUrlChecker. // https://github.com/stevenvachon/broken-link-checker#htmlurlchecker function getChecker(brokenLinks) { // Specify an alternative user agent, as BLC's default doesn't pass some services' validations. const userAgent = "pulumi+blc/0.1"; // For details about each of the options used below, see the BLC docs at // https://github.com/stevenvachon/broken-link-checker#options. const opts = { requestMethod: "GET", filterLevel: 1, userAgent, excludeInternalLinks: false, excludeExternalLinks: false, excludeLinksToSamePage: true, excludedKeywords: [ ...getDefaultExcludedKeywords(), ] }; return new HtmlUrlChecker(opts, getDefaultHandlers(brokenLinks)); } // Returns the set of event handlers for HTMLUrlCheckers. // https://github.com/stevenvachon/broken-link-checker#htmlurlchecker function getDefaultHandlers(brokenLinks) { return { link: (result) => { try { onLink(result, brokenLinks); } catch (error) { fail(error); } }, error: (error) => { fail(error); }, page: (error, pageURL) => { try { onPage(error, pageURL, brokenLinks); } catch(error) { fail(error); } }, end: async () => { try { await onComplete(brokenLinks); } catch (error) { fail(error); } }, }; } // Handles BLC 'link' events, adding broken links to the running list. function onLink(result, brokenLinks) { const source = result.base.resolved; const destination = result.url.resolved; if (result.broken) { const reason = result.brokenReason; addLink(source, destination, reason, brokenLinks); // Always log broken links to the console. logLink(source, destination, reason); } else if (process.env.DEBUG) { // Log successes when DEBUG is truthy. logLink(source, destination, result.http.response.statusCode); } } // Handles BLC 'page' events. function onPage(error, pageURL, brokenLinks) { if (error) { addLink(pageURL, pageURL, error.message, brokenLinks); logLink(pageURL, pageURL, error.message); } else if (process.env.DEBUG) { logLink(pageURL, pageURL, "PAGE_OK"); } } // Handles the BLC 'complete' event, which is raised at the end of a run. async function onComplete(brokenLinks) { const filtered = excludeAcceptable(brokenLinks); if (filtered.length > 0) { // If we failed and a retry count was provided, retry. Note that retry count !== // run count, so a retry count of 1 means run once, then retry once, which means a // total run count of two. if (maxRetries > 0 && retryCount < maxRetries) { retryCount += 1; console.log(`Retrying (${retryCount} of ${maxRetries})...`); checkLinks(); return; } const list = filtered .map(link => `:link: <${link.source}|${new URL(link.source).pathname}> → ${link.destination} (${link.reason})`) .join("\n"); // Post the results to Slack. await postToSlack("docs-ops", list); } } /** We exclude some links: - Our generated API docs have lots of broken links. - Our available versions page includes links to private repos. - GitHub Edit Links may be broken, because the page might not yet exist! - Our LinkedIn page, for some reason, returns an HTTP error (despite being valid). - Our Visual Studio Marketplace link for the Azure Pipelines task extension, although valid and publicly available, is reported as a broken link. - A number of synthetic illustrative links come from our examples/tutorials. - GitLab 503s for requests for protected pages that don't contain certain cookies. */ function getDefaultExcludedKeywords() { return [ "example.com", "/docs/reference/pkg", "/registry/packages/*/api-docs", "/logos/pkg", "/docs/get-started/install/versions", "https://api.pulumi.com/", "https://github.com/pulls?", "https://github.com/pulumi/docs/edit/master", "https://github.com/pulumi/docs/issues/new", "https://github.com/pulumi/registry/edit/master", "https://github.com/pulumi/registry/issues/new", "https://github.com/pulumi/pulumi-hugo/edit/master", "https://github.com/pulumi/pulumi-hugo/issues/new", "https://www.linkedin.com/", "https://linkedin.com/", "https://marketplace.visualstudio.com/items?itemName=pulumi.build-and-release-task", "https://blog.mapbox.com/", "https://www.youtube.com/", "https://apps.twitter.com/", "https://www.googleapis.com/", "https://us-central1-/", "https://www.mysql.com/", "https://ksonnet.io/", "https://www.latlong.net/", "https://www.packet.com/", "https://www.random.org", "https://mbrdna.com", "https://www.linode.com/", "https://www.hetzner.com/cloud", "https://media.amazonwebservices.com/architecturecenter/AWS_ac_ra_web_01.pdf", "https://kubernetes-charts-incubator.storage.googleapis.com", "https://kubernetes-charts.storage.googleapis.com", "http://web-lb-23139b7-1806442625.us-east-1.elb.amazonaws.com", "https://ruby-app-7a54c5f5e006d5cf33c2-zgms4nzdba-uc.a.run.app", "https://hello-a28eea2-q1wszdxb2b-ew.a.run.app", "https://ruby-420a973-q1wszdxb2b-ew.a.run.app", "https://280f2167f1.execute-api.us-east-1.amazonaws.com", "http://my-bucket-1234567.s3-website.us-west-2.amazonaws.com", "https://gitlab.com/users/sign_in", "https://gitlab.com/profile/applications", "https://blog.coinbase.com/", "https://www.netfilter.org/", "https://codepen.io", "https://twitter.com", "https://t.co", "https://www.akamai.com", "http://localhost:16686/search", // Local Jaeger endpoint presented in troubleshooting guide. "https://ceph.io", "https://www.pagerduty.com", "https://support.pulumi.com", "https://support.pulumi.com/", "https://www.pulumi.com/support/", "https://pbs.twimg.com/profile_images/", "https://linen.dev/", "https://cloud.yandex.com/", "http://localhost:3000", "https://data-flair.training", "https://opensource.org/licenses", "https://console.eventstore.cloud/authentication-tokens", "https://telecomreseller.com/2019/03/20/crossing-cloud-chasms-avoiding-catastrophic-cloud-calamities", "https://www.enterprisetech.com/2018/10/23/startup-pulumi-rolls-cloud-native-tools", "http://optout.networkadvertising.org/?c=1", "https://thenewstack.io/", "https://rootly.com/", "https://www.vultr.com/", "https://shell.azure.com/", "https://portal.azure.com/", "https://www.noaa.gov/information-technology/open-data-dissemination", ]; } // Filters out transient errors that needn't fail a link-check run. function excludeAcceptable(links) { return (links // Ignore GitHub and npm 429s (rate-limited). We should really be handling these more // intelligently, but we can come back to that in a follow up. .filter(b => !(b.reason === "HTTP_429" && b.destination.match(/github.com|npmjs.com/))) // Ignore remote disconnects. .filter(b => b.reason !== "ERRNO_ECONNRESET") // Ignore BLC_UNKNOWN's .filter(b => b.reason !== "BLC_UNKNOWN") // Ignore BLC_INVALID's .filter(b => b.reason !== "BLC_INVALID") // Ignore HTTP 308s. .filter(b => b.reason !== "HTTP_308") // Ignore HTTP 503s. .filter(b => b.reason !== "HTTP_503") // Ignore complaints about MIME types. BLC currently hard-codes an expectation of // type text/html, which causes it to fail on direct links to images, PDFs, and // other media. // https://github.com/stevenvachon/broken-link-checker/issues/65 // https://github.com/stevenvachon/broken-link-checker/blob/43770535ad7b84cadec9dc54c5140694389e33dc/lib/internal/streamHTML.js#L36-L39 .filter(b => !b.reason.startsWith(`Expected type "text/html"`)) ); } // Posts a message to the designated Slack channel. async function postToSlack(channel, text) { const token = process.env.SLACK_ACCESS_TOKEN; if (!token) { console.warn("No SLACK_ACCESS_TOKEN on the environment. Skipping."); return; } const client = new WebClient(token, { logLevel: LogLevel.ERROR }); return await client.chat.postMessage({ text, channel: `#${channel}`, as_user: true, mrkdwn: true, unfurl_links: false, }); } // Adds a broken link to the running list. function addLink(source, destination, reason, links) { links.push({ source, destination, reason, }); } // Logs a link result to the console. function logLink(source, destination, reason) { console.log(source); console.log(` -> ${destination}`); console.log(` -> ${reason}`); console.log(); } // Logs and exits immediately. function fail(error) { console.error(error.message); process.exit(1); } // Start by fetching the sitemap from `baseURL`. async function getURLsToCheck(base) { return await sitemap .fetch(`${base}/sitemap.xml`) .then(map => { const urls = map.sites // Exclude resource docs, SDK docs, and CLI download pages. .filter(page => !page.match(/\/registry\/packages\/.+\/api-docs\//)) .filter(page => !page.match(/\/docs\/reference\/pkg\/nodejs|python\//)) .filter(page => !page.match(/\/docs\/install\/versions\//)) // Always check using the supplied baseURL. .map(url => { const newURL = new URL(url); const baseURLObj = new URL(base); newURL.hostname = baseURLObj.hostname; newURL.protocol = baseURLObj.protocol; return newURL.toString(); }) // Tack on any additional pages we'd like to check. .concat([ "https://github.com/pulumi/pulumi", ]) // Sort everything alphabetically. .sort(); // Return the list of URLs to be crawled. return urls; }); }
import React from 'react'; const Footer = () => ( <footer> <div><p>Created by Pedro Gomes for <a href="https://www.i3d.net" target="_blank" rel="noopener noreferrer">i3D.net</a> - Frontend assignment</p></div> </footer> ); export default Footer;
import React from 'react' function Email({ handleBlur, handleChange, values, touched, errors, index, item }) { return <> <label htmlFor="email">Email Address</label> <input id="email" name={`emailArr[${index}].email`} type="text" onChange={handleChange} onBlur={handleBlur} value={values && values.emailArr[index] && values.emailArr[index].email} /> {console.log({ touched, errors })} {touched.emailArr && errors.emailArr && touched.emailArr[index] && touched.emailArr[index].email && errors.emailArr[index] && errors.emailArr[index].email ? ( <div>{errors.emailArr && errors.emailArr[index] && errors.emailArr[index].email}</div> ) : null} </> } export default Email
var active = true; try { chrome.storage.sync.get({ activate: true }, function (items) { active = items.activate; if (active) { main(); } track(items.activate ? "true" : "false"); }); } catch (e) { if (active) { main(); } track("undefined"); } function track(active) { //UA-9413471-3 ga('create', 'UA-9413471-3', 'auto'); ga('set', 'dimension1', active); ga('send', 'pageview'); // //Analytics // var _gaq = window._gaq || []; // _gaq.push(['_setAccount', 'UA-9413471-3']); // _gaq.push(['_gat._forceSSL']); // _gaq.push(["_setCustomVar", 1, "Active", active, 3]); // _gaq.push(['_trackPageview']); } //Content script, image replacer function main() { //rNet (function ($) { // https://cdn.rawgit.com/AaronLayton/rNet/master/images/ var self = { rNetImgs: [ 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/1.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/10.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/12-years.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/181642_1863007259994_3526037_n.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/185616_10150396267885237_6828450_n.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/2.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/3.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/4.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/5.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/51558185.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/6.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/7.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/8.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/Aaron.png', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/adrian at the beach.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/adrian wars.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/adrian.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/Adrian0898549.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/adrian2.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/AdrianHead2.png', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/adriankrjkvgj.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/adrianv111.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/AndyBrentDance.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/andy_brent.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/bane.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/barry.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/ben-hippy.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/berty.png', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/Cache all the things.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/coffee-gods.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/damn-it-man.png', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/dan.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/dan2.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/dan3.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/dan4.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/dan5.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/danagain.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/danfalls.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/dannnn.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/danped.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/dating.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/designers-assemble.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/eventure-independant-traders.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/eventure-matt-404.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/EventureMatt.png', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/fkjekjfe.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/gaywatch.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/getwellsoon.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/glee.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/group.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/gurnhillspongepants.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/ha.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/hodor.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/homer-steve.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/i-aint-getting-on-no-plane.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/Image1.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/IMG_5116.JPG', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/layjuff.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/lol.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/maintenance.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/mark-and-andy.png', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/Marky Golf.png', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/markyB.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/mattupsidedown.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/mattV2.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/matt_drake.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/mermaid.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/miltonator.png', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/output.txt', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/parcelshop.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/perfect.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/porkins.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/rambling.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/Remarkable Cinema Rush.png', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/remarkasamable.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/sam+car.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/sam-1.png', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/sam.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/sammy.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/samramid.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/sams-weekend.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/samV22.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/Samwise.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/SCP.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/STAHP.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/steve1.png', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/superman_pic2.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/TeamTwat.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/the gurnhills.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/TheRock.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/Tim Tim Tim.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/Twinnuies.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/Uncle Albert-Matt.png', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/Untitled2.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/Untitled55555.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/Untitledgfrg5g5.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/warwick.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/yearbook.jpg', 'https://cdn.rawgit.com/AaronLayton/rNet/master/images/yourstimes.jpg' ], //Handles all images on page with an interval of time handleImages: function (lstImgs, time) { $.each($('img'), function (i, item) { //Skip if image is already replaced if ($.inArray($(item).attr('src'), lstImgs) == -1) { var h = $(item).height(); var w = $(item).width(); //If image loaded if (h > 0 && w > 0) { self.handleImg(item, lstImgs); } else { //Replace when loaded $(item).load(function () { //Prevent 'infinite' loop if ($.inArray($(item).attr('src'), lstImgs) == -1) { self.handleImg(item, lstImgs); } }); } } }); //Keep replacing if (time > 0) { setTimeout(function () { self.handleImages(lstImgs, time); }, time); } }, //Replace one image handleImg: function (item, lstImgs) { $(item).error(function () { //Handle broken imgs self.handleBrokenImg(item, lstImgs); }); self.setRandomImg(item, lstImgs); }, //Set a random image from lstImgs to item setRandomImg: function (item, lstImgs) { var h = $(item).height(); var w = $(item).width(); $(item).css('width', w + 'px').css('height', h + 'px'); $(item).attr('src', lstImgs[Math.floor(Math.random() * lstImgs.length)]); }, //Removed broken image from lstImgs, run handleImg on item handleBrokenImg: function (item, lstImgs) { var brokenImg = $(item).attr('src'); var index = lstImgs.indexOf(brokenImg); if (index > -1) { lstImgs.splice(index, 1); } self.setRandomImg(item, lstImgs); }, }; //Run on jQuery ready $(function () { self.handleImages(self.rNetImgs, 3000); }); //Set global variable $.rNet = self; })(jQuery); //end rNet }
import React from 'react' import styled from 'styled-components/native'; import { View } from 'react-native'; const Top1 = styled.View` margin-top: ${(props) => props.theme.space[1]}; ` const Top2 = styled.View` margin-top: ${(props) => props.theme.space[2]}; ` const Top3 = styled.View` margin-top: ${(props) => props.theme.space[3]}; ` const Top4 = styled.View` margin-top: ${(props) => props.theme.space[4]}; ` const Top5 = styled.View` margin-top: ${(props) => props.theme.space[5]}; ` //////////////////////////// const Bottom1 = styled.View` margin-bottom: ${(props) => props.theme.space[1]}; ` const Bottom2 = styled.View` margin-bottom: ${(props) => props.theme.space[2]}; ` const Bottom3 = styled.View` margin-bottom: ${(props) => props.theme.space[3]}; ` const Bottom4 = styled.View` margin-bottom: ${(props) => props.theme.space[4]}; ` const Bottom5 = styled.View` margin-bottom: ${(props) => props.theme.space[5]}; ` //////////////////////////// const Left1 = styled.View` margin-left: ${(props) => props.theme.space[1]}; ` const Left2 = styled.View` margin-left: ${(props) => props.theme.space[2]}; ` const Left3 = styled.View` margin-left: ${(props) => props.theme.space[3]}; ` const Left4 = styled.View` margin-left: ${(props) => props.theme.space[4]}; ` const Left5 = styled.View` margin-left: ${(props) => props.theme.space[5]}; ` //////////////////////////// const Right1 = styled.View` margin-right: ${(props) => props.theme.space[1]}; ` const Right2 = styled.View` margin-right: ${(props) => props.theme.space[2]}; ` const Right3 = styled.View` margin-right: ${(props) => props.theme.space[3]}; ` const Right4 = styled.View` margin-right: ${(props) => props.theme.space[4]}; ` const Right5 = styled.View` margin-right: ${(props) => props.theme.space[5]}; ` export const Spacer = ({ variant }) => { if(variant === 'top1') return <Top1/> if(variant === 'top2') return <Top2/> if(variant === 'top3') return <Top3/> if(variant === 'top4') return <Top4/> if(variant === 'top5') return <Top5/> if(variant === 'bottom1') return <Bottom1/> if(variant === 'bottom2') return <Bottom2/> if(variant === 'bottom3') return <Bottom3/> if(variant === 'bottom4') return <Bottom4/> if(variant === 'bottom5') return <Bottom5/> if(variant === 'left1') return <Left1/> if(variant === 'left2') return <Left2/> if(variant === 'left3') return <Left3/> if(variant === 'left4') return <Left4/> if(variant === 'left5') return <Left5/> if(variant === 'right1') return <Right1/> if(variant === 'right2') return <Right2/> if(variant === 'right3') return <Right3/> if(variant === 'right4') return <Right4/> if(variant === 'right5') return <Right5/> else {return <Top1/>} }
const { Schema } = require('mongoose'); const { isFQDN, isURL } = require('validator'); const env = require('../env'); const connection = require('../connections/mongoose/instance'); const { applyElasticPlugin, setEntityFields } = require('../elastic/mongoose'); const { deleteablePlugin, imagePlugin, paginablePlugin, repositoryPlugin, searchablePlugin, userAttributionPlugin, } = require('../plugins'); const schema = new Schema({ name: { type: String, required: true, trim: true, }, domainName: { type: String, trim: true, validate: { validator(v) { if (!v) return true; return isFQDN(String(v)); }, message: 'Invalid domain name: {VALUE}', }, }, website: { type: String, required: true, trim: true, validate: { validator(v) { return isURL(v, { protocols: ['http', 'https'], require_protocol: true, }); }, message: 'Invalid publisher website URL for {VALUE}', }, }, }, { timestamps: true }); setEntityFields(schema, 'name'); applyElasticPlugin(schema, 'publishers'); schema.virtual('customUri').get(function getCustomUri() { const { domainName } = this; if (!domainName) return null; const { NODE_ENV } = env; const protocol = NODE_ENV === 'production' ? 'https' : 'http'; return `${protocol}://${domainName}`; }); schema.plugin(deleteablePlugin, { es_indexed: true, es_type: 'boolean', }); schema.plugin(userAttributionPlugin); schema.plugin(imagePlugin, { fieldName: 'logoImageId' }); schema.plugin(repositoryPlugin); schema.plugin(paginablePlugin); schema.plugin(searchablePlugin, { fieldNames: ['name'] }); schema.pre('save', async function checkDelete() { if (!this.isModified('deleted') || !this.deleted) return; const placements = await connection.model('placement').countActive({ publisherId: this.id }); if (placements) throw new Error('You cannot delete a publisher that has related placements.'); const topics = await connection.model('topic').countActive({ publisherId: this.id }); if (topics) throw new Error('You cannot delete a publisher that has related topics.'); const stories = await connection.model('story').countActive({ publisherId: this.id }); if (stories) throw new Error('You cannot delete a publisher that has related stories.'); }); schema.pre('save', async function updatePlacements() { if (this.isModified('name')) { // This isn't as efficient as calling `updateMany`, but the ElasticSearch // plugin will not fire properly otherwise. // As such, do not await the update. const Placement = connection.model('placement'); const docs = await Placement.find({ publisherId: this.id }); docs.forEach((doc) => { doc.set('publisherName', this.name); doc.save(); }); } }); schema.pre('save', async function updateTopics() { if (this.isModified('name')) { // This isn't as efficient as calling `updateMany`, but the ElasticSearch // plugin will not fire properly otherwise. // As such, do not await the update. const Topic = connection.model('topic'); const docs = await Topic.find({ publisherId: this.id }); docs.forEach((doc) => { doc.set('publisherName', this.name); doc.save(); }); } }); schema.index({ name: 1, _id: 1 }, { unique: true }); schema.index({ name: -1, _id: -1 }, { unique: true }); schema.index({ updatedAt: 1, _id: 1 }, { unique: true }); schema.index({ updatedAt: -1, _id: -1 }, { unique: true }); module.exports = schema;
export default { label: 'Fraction', id: 'fraction-2', list: [ { type: 'numberInput', id: 'improper-mixed', label: 'Improper to Mixed', commonData: { title: 'Convert the below improper fraction to mixed fraction.', type: 'improperToMixed' }, data: [ `3/2, 5/4, 9/2, 7/3, 4/3, 7/2, 11/5, 7/5, 8/3, 10/3`, `17/10, 9/5, 21/5, 15/7, 6/5, 22/7, 33/5, 43/5, 17/3, 22/3`, `143/100, 101/100, 173/100, 167/100, 137/100, 347/100, 457/100, 661/100, 907/100, 941/100` ] }, { type: 'numberInput', id: 'mixed-improper', label: 'Mixed to Improper', commonData: { title: 'Convert the below mixed fraction into improper fraction.', type: 'mixedToImproper' }, data: [ `3 1/2, 2 1/5, 1 2/5, 2 2/3, 3 1/3, 1 1/2, 1 1/4, 4 1/2, 2 1/3, 1 1/3`, `4 4/5, 6 1/5, 3 3/7, 2 2/7, 6 6/7, 5 3/10, 4 8/10, 6 9/10, 8 3/5, 3 4/5`, `6 1/100, 5 34/100, 1 43/100, 1 73/100, 1 67/100, 3 47/100, 4 57/100, 6 61/100, 9 7/100, 9 41/100` ] }, { type: 'numberInput', id: 'simple-fraction', label: 'Simple Fraction', commonData: { title: 'Write the fraction in the lowest term.', type: 'simpleFraction' }, data: [ `2/6, 3/9, 2/4, 20/30, 4/8, 5/15, 11/44, 5/10, 15/20, 6/12`, `2/8, 5/25, 8/88, 7/35, 14/35, 28/35, 63/70, 42/70, 16/40, 32/40`, `10/20, 90/100, 100/300, 40/50, 30/1000, 70/100, 10/1000, 400/500, 110/1000, 10/700` ] }, { type: 'numberInput', id: 'equal-fraction', label: 'Equal Fractions', commonData: { title: 'Fill in the empty boxes to form equal fractions.' }, data: [ { type: 'equalFraction', text: `1/2 3, 1/2 4, 1/2 2, 2/3 2, 3/4 2, 1/3 3, 1/3 2, 1/5 10, 2/5 5, 3/4 2` }, { type: 'equalFraction2', text: `1/2 2, 1/2 3, 1/2 4, 2/3 2, 1/5 10, 2/5 5, 3/4 2, 3/4 2, 1/3 3, 1/3 2` }, { type: 'equalFraction3', text: `1/2, 2/3, 5/6, 1/3, 1/8, 1/4, 3/5, 3/4, 1/3, 1/3` } ] }, { type: 'numberInput', id: 'frac-decimal', label: 'Fraction to Decimal', commonData: { title: 'Write the decimal equivalet of the faction.', type: 'fracToDeci' }, data: [ `1/2, 1/4, 1/5, 3/5, 7/10, 2/5, 3/4, 1/10, 3/10, 9/10`, `7/100, 3/1000, 99/100, 43/100, 432/1000, 43/1000, 2/100, 91/1000,43/100, 500/1000`, `20/25, 10/25, 40/50, 10/40, 100/1000, 25/100, 75/100, 30/100, 5/20, 36/60`, `3/2, 5/4, 16/10, 5/2, 7/5, 10/4, 9/3, 7/4, 10/4, 9/2` ] }, { type: 'numberInput', id: 'decimal-frac', label: 'Decimal to Fraction', commonData: { title: 'Write the fraction equivalent of the decimal number.', type: 'deciToFrac' }, data: [ `0.5, 0.25, 0.2, 0.7, 0.75, 0.8, 0.4, 0.9, 0.1, 0.3`, `1.5, 1.25, 2.5, 1.2, 3.5, 1.7, 1.3, 4.5, 1.75, 2.25`, `0.01, 0.34, 0.001, 0.11, 0.034, 0.105, 0.789, 0.99, 0.43, 0.555` ] } ] };