text
stringlengths
7
3.69M
import React from "react"; import ToDoItems from "../Components/ToDoItems"; function Header() { return ( <header> My To-Do list </header>); } class ToDoList extends React.Component { constructor(props) { super(props); this.inputRef = React.createRef(); //create reference for input box this.state = { //state is similar to props, but it is private and fully controlled by the component. itemsArray: [] }; this.addTask = this.addTask.bind(this); // This binding is necessary to make `this` work in the callback this.removeTask = this.removeTask.bind(this); // This binding is necessary to make `this` work in the callback } render() { return ( <div className="toDoListMain"> <div className="myHeader"> <Header/> </div> <div className="inputAndButtonDiv"> <form onSubmit={this.addTask}> <input id="taskInput" placeholder="Enter your task..." ref={this.inputRef} > </input> <button className="myButton"> + </button> </form> </div> <div className="listOfTasks"> <ToDoItems entries={this.state.itemsArray} removeTask={this.removeTask} /> </div> </div> ); } addTask(e) { e.preventDefault(); const input = this.inputRef; //alternative: document.getElementById("taskInput"); if (input.current.value !== "") { let newItem = { text: input.current.value, //don't use "current" in alt version key: Date.now() //we use Date.now to give unique key for components }; this.setState({ itemsArray: this.state.itemsArray.concat(newItem) }); input.current.value = ""; } } removeTask(key) { const filteredItems = this.state.itemsArray.filter(function (item) { return (item.key !== key); }); //we filter all entries except the one which is clicked this.setState({ itemsArray: filteredItems }) } } //TO DO /* add flip move add done task below (strikethrough) remove done task as you now remove normal task */ export default ToDoList;
import {Kind} from 'graphql/language'; import {GraphQLScalarType} from 'graphql'; import {returnOnError} from '../helpers'; function serialize(value) { return value instanceof Date ? value.toISOString() : null; } function parseValue(value) { return returnOnError(() => value == null ? null : new Date(value), null); } function parseLiteral(ast) { return ast.kind === Kind.STRING ? parseValue(ast.value) : null; } export default new GraphQLScalarType({ name: 'ISODate', description: 'JavaScript Date object as an ISO timestamp', serialize, parseValue, parseLiteral });
var assert = require('assert'); // import the core APIs var cbs = require('../callbackless.js'); var unit = cbs.unit; var fmap = cbs.fmap; var liftA = cbs.liftA; var flatMap = cbs.flatMap; var continue$ = cbs.continue$; // import the file APIs var cbs_fs = require('../callbackless-fs.js'); var readFile = cbs_fs.readFile; var readFile$ = cbs_fs.readFile$; // import the string APIs var cbs_str = require('../callbackless-str.js'); var toUpperCase$ = cbs_str.toUpperCase$; var concat$ = cbs_str.concat$; // import the testing APIs var cbs_testing = require('../callbackless-testing.js'); var print$ = cbs_testing.print$; var assertEquals$ = cbs_testing.assertEquals$; /** * This test case tests file promise API of callbackless. * * The point is to demonstrate using sync code to express async logic with promises. Under the * hood, the test case calls the fs.readFile(path, encoding, callback) async API of Node, therefore * there's no blocking calls. But with the file promise API of callbackless-fs, all the async code * is abstracted away, you can never find any callbacks in the code. * * Naming convention for variables (and functions): * * <data>$: the promise for the data, e.g. data1$ means the promise of the data in file1 * <fn>$: the lifted function for the original function fn, which accepts and returns promises, e.g. * the toUpperCase$ is the lifted function for toUpperCase which works on string promises. */ function testFilePromise_functor() { console.log('Running ' + arguments.callee.name); // readFile returns a promise of the data which will be available in the future, but we can do // operations on it immediately before it's actually available. var data1$ = readFile('data/data_1.txt'); // at this point we don't know the content of data_1.txt var data2$ = readFile('data/data_2.txt'); // at this point we don't know the content of data_2.txt var data3$ = readFile('data/data_3.txt'); // at this point we don't know the content of data_3.txt // apply toUpperCase$ to a promise of string and return another promise of string. The actual value // may not be available at this point, but we don't care. var upperCaseData1$ = toUpperCase$(data1$); // unit wrapps (lifts) a directly available data into a computational context (promise), so that // it can work with lifted functions. var expectedUpperCaseData1$ = unit("HELLO CALLBACKLESS.JS!"); // assertEquals$ asserts the data in the two promises are equal. // The underlying _assertEquals will be invoked when the 2 promises are finished. assertEquals$(expectedUpperCaseData1$, upperCaseData1$); // concatenates 2 promises of strings and returns another promise of string // keep in mind that it just establishes the relationship, we don't care the actual value now. var data1AndData2$ = concat$(data1$, data2$); // unit wrapps (lifts) a directly available data into a computational context (promise). var expectedData1AndData2$ = unit("hello callbackless.js!cool!"); // assertEquals$ asserts the data in the two promises are equal. // The underlying _assertEquals will be invoked when the 2 promises are finished. var passed$ = assertEquals$(expectedData1AndData2$, data1AndData2$); return passed$; } /** * The test data contains 3 files. The contents of the previous file is the path of the next file. * This test starts from the path of the first file, then follows the path one by one until the * third file. * * During the execution, there're 3 asynchronous file reading operations involved under the hood, * but all the callbacks are abstracted away by the promise. */ function testFilePromise_monad() { console.log('Running ' + arguments.callee.name); var path1 = 'data/file_1.txt'; var path2$ = readFile('data/file_1.txt'); var path3$ = readFile$(path2$); var data3$ = readFile$(path3$); var expectedData3$ = unit('Hey, I am here!') var passed$ = assertEquals$(expectedData3$, data3$); return passed$; } function _toUpperCase(str) { return str.toUpperCase(); } function runTests() { var result1$ = testFilePromise_functor(); var result2$ = continue$(result1$, testFilePromise_monad); continue$(result2$, function() { console.log("Done"); }); } runTests();
app.controller('EventController', ['$scope', '$modal', '$stateParams', '$http', '$window', '$document', 'Auth', function($scope, $modal, $stateParams, $http, $window, $document, Auth) { //helpr for infinate scrolling var counter = 0; //Grab the event ID var eventId = $stateParams.id; //init the socket var socket = io('http://moscrop.me:3000'); //List of unread messages var unreadCount = 0; var notifications = []; var _this = this; //event details $scope.event_details = {}; //list of posts $scope.posts = []; //HTML5 notifcations $scope.enable_notifications = false; //Defualt login status $scope.isLoggedIn = Auth.isAuthenticated(); $scope.user = Auth.getUser(); //Show if there is nothing else to show. $scope.moreContent = true; //Handle any changes caused by the user $scope.$on('loginStatusChanged', function (event, data) { $scope.isLoggedIn = data.logged; $scope.user = data.user; }); //Handle the page visability chnage for notifcations $scope.$on('$visibilitychange', function(event, data) { if(!data) { unreadCount = 0; Tinycon.setBubble(unreadCount) } }); $http.get("/api/v1/event/" + eventId) .success(function(data) { $scope.event_details = data; console.log(data); } ); $scope.addPost = function() { var modalInstance = $modal.open( { templateUrl: '/partials/postDialog.html', controller: 'newPostDialogController', resolve: { eventId: function () { return $stateParams.id; }, user: function () { return $scope.user; }, } }); } $scope.radioPlayer = function() { $window.open('http://player.bailriggfm.co.uk/fto-elections','playerWindow','top=165,left=190,height=660,width=380'); } $scope.request_nofications = function() { if (! $window.Notification) return false; $window.Notification.requestPermission(function(result) { if (result === 'granted') { $scope.enable_notifications = true; } else { $scope.enable_notifications = false; } }); }; $scope.loadMore = function() { $http.get("/api/v1/event/" + eventId + "/posts/" + counter) .success(function(data) { console.log(data.length); if (data.length > 0) { $scope.posts.push.apply($scope.posts, data); } else { $scope.moreContent = false; console.log("Done!"); } } ); counter += 10; }; $scope.loadMore(); socket.on('post.new.' + eventId, function (data) { var post = JSON.parse(data); console.log('socket: post.new'); $scope.posts.unshift(post); $scope.$apply(); //Update favicon bubble if($document.prop('hidden')) { unreadCount += 1 Tinycon.setBubble(unreadCount); if(post.base.payload_type === 'text' && $scope.enable_notifications && $window.Notification.permission === 'granted') { var notification = new $window.Notification(post.payload.header, { body: post.payload.body, }); notification.onclick = function(ev) { window.focus() ev.preventDefault() }; setTimeout(function() { notification.close() }, 5000) } } }); }]); app.controller('newPostDialogController', ['$scope', '$modalInstance', '$http', '$upload', 'eventId', 'EventService', 'user', function($scope, $modalInstance, $http, $upload, eventId, EventService, user) { $scope.event_id = eventId; $scope.user_id = user.id; $scope.tweets = {}; $scope.progress = 0; $scope.changeTab = function(tab) { console.log('changeTab'); $scope.view_tab = tab; } $scope.addPost = function(post) { EventService.addPost(post).then( function(data) { $modalInstance.dismiss(); }, function(error) { $scope.error = error; } ); } $scope.searchHastag = function(hashtag) { $http.post("/api/v1/tweets", hashtag) .success(function(data) { console.log(data); $scope.tweets = {}; $scope.tweets = data.statuses; } ); } $scope.addTweet = function(tweet) { var postData = { payload_type : 'tweet', user_id : $scope.user_id, event_id : eventId, tid : tweet.id, tuid : tweet.user.id, name : tweet.user.name, screen_name : tweet.user.screen_name, avatar : tweet.user.profile_image_url, text : tweet.text, }; EventService.addPost(postData).then( function(data) { $modalInstance.dismiss(); }, function(error) { $scope.error = error; } ); } $scope.addPhoto = function (photo, $file) { console.log(photo); $upload.upload({ url: '/api/v1/post/new', data: photo, file: $file[0], headers: {'X-CSRF-Token': $('meta[name=csrf-token]').attr('content')}, }).progress(function (evt) { $scope.progress = parseInt(100.0 * evt.loaded / evt.total); }).success(function (data, status, headers, config) { $modalInstance.dismiss(); }).error(function (err) { console.log('Error occured during upload'); }); } }]);
const colors = { 2: "rgb(238, 228, 218)", 4: "rgb(237, 224, 200)", 8: "rgb(242, 177, 121)", 16: "rgb(245, 149, 99)", 32: "rgb(246, 124, 95)", 64: "rgb(246, 94, 59)", 128: "rgb(237, 207, 114)", 256: "rgb(237, 204, 97)", 512: "rgb(237, 200, 80)", 1024: "rgb(237, 197, 63)", 2048: "rgb(237, 194, 46)" }; function getColor(value) { if (value <= 2048) return colors[value]; if (value / 2048 <= 2048) return colors[value / 2048]; return colors[2048]; } export function setTileColor(tile) { const newTile = { ...tile }; if (newTile.value === null) { newTile.color = "white"; } else { newTile.color = getColor(newTile.value); } newTile.alreadyCombined = false; return newTile; }
const pokemonData = require('../../../pokemon'); const trainerData = require('../../../trainers'); const createTrainer = (knex, trainer) => { return knex('trainers') .insert( { name: trainer.name, pokemon: trainer.pokemon }, 'id' ) .then(id => { const joinerPromises = []; trainer.pokemon.forEach(p => { joinerPromises.push(createJoin(knex, id[0], p)); }); return Promise.all(joinerPromises); }); }; const createJoin = (knex, trainerID, pokemon) => { return knex('trainers_pokemon').insert({ trainer_id: trainerID, pokemon_id: pokemon }); }; exports.seed = function(knex) { return knex('trainers_pokemon') .del() .then(() => knex('pokemon').del()) .then(() => knex('trainers') .del() .then(async () => { await knex.raw('TRUNCATE TABLE pokemon RESTART IDENTITY CASCADE'); await knex.raw('TRUNCATE TABLE trainers RESTART IDENTITY CASCADE'); }) ) .then(() => { return Promise.all([knex('pokemon').insert(pokemonData)]); }) .then(() => { const trainerPromises = []; trainerData.forEach(trainer => { trainerPromises.push(createTrainer(knex, trainer)); }); return Promise.all(trainerPromises); }) .then(() => console.log('Seeding Complete')) .catch(error => console.log(`Error seeding file: ${error}`)); };
import Task from './Task'; function Tasks(props) { const tasks = props.tasksList; console.log(props.tasksList); return ( <> {tasks.map( (t)=> <Task key={t.id} task={t} onDelete={props.onDelete} onToggleRemainder={props.onRemainder} /> )} </> ); } export default Tasks;
var AwesomeAngularMVCApp = angular.module('AwesomeAngularMVCApp', ['ngRoute']); // AwesomeAngularMVCApp.controller('LandingPageController', LandingPageController); AwesomeAngularMVCApp.controller('LoginController', LoginController); var configFunction = function ($routeProvider, $httpProvider) { $routeProvider. when('/routeOne', { templateUrl: 'routesDemo/one' }) .when('/routeTwo', { templateUrl: 'routesDemo/two' }) .when('/routeTwo/:donuts', { templateUrl: function (params) { return '/routesDemo/two?donuts=' + params.donuts; } }) .when('/routeThree', { templateUrl: 'routesDemo/three' }) .when('/login?returnUrl', { templateUrl: 'Account/Login', controller: LoginController }) ; //$httpProvider.interceptors.push('AuthHttpResponseInterceptor'); } configFunction.$inject = ['$routeProvider', '$httpProvider']; AwesomeAngularMVCApp.config(configFunction);
angular.module('myFirstApp', ['ngRoute']) .config(['$routeProvider', function($routeProvider){ $routeProvider.when('/about'.{ templateUrl:'views/about.html' }) .when('/contact', { templateUrl:'views/contact.html' }) .otherwise({templateUrl:'views/404.html'}) }]) .factory('personService', function(){ var person = {}; person.printName = function(firstName,lastName) { return firstName + ' ' +lastName; } return person; }) .controller('myController', function($scope, personService) { $scope.firstName = 'Trainee'; $scope.lastName = 'Russo'; $scope.printName = function () { return personService.printName($scope.firstName,$scope.lastName) }; } );
import React from "react"; import Home from "./pages/home"; import Chat from "./pages/chat"; import store from "./store/index.js"; import { Provider as StoreProvider } from "react-redux"; import "./App.css"; import { BrowserRouter as Router, Switch, Route, Redirect, useHistory, } from "react-router-dom"; function App() { const history = useHistory(); return ( <div className="App"> <StoreProvider store={store}> <Router> <Switch history={history}> <Route exact path="/" render={() => <Redirect to="/home" />} /> <Route exact path="/home" component={Home} /> <Route exact path="/chat" component={Chat} /> </Switch> </Router> </StoreProvider> </div> ); } export default App;
document.observe("dom:loaded", function() { $$('input[id*="_countdown_width"]').first().addClassName('validate-number'); $$('input[id*="_countdown_height"]').first().addClassName('validate-number'); $$('input[id*="_border_size"]').first().addClassName('validate-number'); $$('input[id*="_numbers_item"]').first().addClassName('validate-number'); $$('input[id*="_countdown_color"]').first().addClassName('color'); $$('input[id*="_border_color"]').first().addClassName('color'); });
import user from './User/Reducer'; export {user}
import { before, GET, POST, PUT, route } from 'awilix-express' import { authenticate, permission } from "../ApiController"; import TermConditionMapper from "../feature/termcondition/TermConditionMapper"; @route('/term-condition') export default class TermConditionController { constructor( { addTermConditionUseCase, getTermConditionUseCase, updateTermConditionUseCase } ) { this.addTermConditionUseCase = addTermConditionUseCase; this.getTermConditionUseCase = getTermConditionUseCase; this.updateTermConditionUseCase = updateTermConditionUseCase } @GET() @before([authenticate]) async getTermCondition(req, res, next) { try { const result = await this.getTermConditionUseCase.execute(); res.status(200).send(result) } catch (err) { next(err) } } @POST() @before([authenticate, permission]) async addTermCondition(req, res, next) { try { const body = req.body; let mapper = new TermConditionMapper() let param = mapper.addTermCondition(body) const result = await this.addTermConditionUseCase.execute(param); res.status(200).send(result) } catch (err) { next(err) } } @route('/:id') @PUT() @before([authenticate, permission]) async updateTermCondition(req, res, next) { try { const body = req.body; let mapper = new TermConditionMapper() let param = mapper.updateTermCondition(req.params.id, body) const result = await this.updateTermConditionUseCase.execute(param); res.status(200).send(result) } catch (err) { next(err) } } }
angular .module('layout') .component('planTrip', { templateUrl: 'app/layout/plantrip.html', controller: PlanTripController }); /** @ngInject */ function PlanTripController() { // var vm = this; }
const HEROES = [ { id: 11, name: 'Mr. Nice' }, { id: 12, name: 'Narco' }, { id: 13, name: 'Bombasto' }, { id: 14, name: 'Celeritas' }, { id: 15, name: 'Magneta' }, { id: 16, name: 'RubberMan' }, { id: 17, name: 'Dynama' }, { id: 18, name: 'Dr IQ' }, { id: 19, name: 'Magma' }, { id: 20, name: 'Tornado' } ]; class AppComponent { render() { const wire = hyperHTML.wire; const selectedHero = this.selectedHero; hyperHTML.bind(document.querySelector('my-app'))` <style>${AppComponent.styles}</style> <h1>${this.title}</h1> <h2>My Heroes</h2> <ul class=heroes> ${this.heroes.map( hero => wire(hero)` <li class=${hero === selectedHero ? 'selected' : ''} data-id=${hero.id} onclick=${this} > <span class=badge>${hero.id}</span> ${hero.name} </li>` )} </ul> ${selectedHero ? wire(this, ':editor')` <div> <h2>${selectedHero.name} details!</h2> <div><label>id: </label>${selectedHero.id}</div> <div> <label>name: </label> <input value=${selectedHero.name} oninput=${this} placeholder=name> </div> </div>` : '' }`; } static get styles() { return ` .selected { background-color: #CFD8DC !important; color: white; } .heroes { margin: 0 0 2em 0; list-style-type: none; padding: 0; width: 15em; } .heroes li { cursor: pointer; position: relative; left: 0; background-color: #EEE; margin: .5em; padding: .3em 0; height: 1.6em; border-radius: 4px; } .heroes li.selected:hover { background-color: #BBD8DC !important; color: white; } .heroes li:hover { color: #607D8B; background-color: #DDD; left: .1em; } .heroes .text { position: relative; top: -3px; } .heroes .badge { display: inline-block; font-size: small; color: white; padding: 0.8em 0.7em 0 0.7em; background-color: #607D8B; line-height: 1em; position: relative; left: -1px; top: -4px; height: 1.8em; margin-right: .8em; border-radius: 4px 0 0 4px; }`; } constructor() { this.title = 'Tour of Heroes'; this.heroes = HEROES; this.selectedHero = null; this.render(); } handleEvent(e) { switch (e.type) { case 'click': // <li> has been clicked const id = e.currentTarget.dataset.id; this.selectedHero = HEROES.find(hero => hero.id == id); break; case 'input': // <input> Hero editor changed this.selectedHero.name = e.currentTarget.value; break; } this.render(); } }
/** * @author 王集鹄(wangjihu,http://weibo.com/zswang) * bae环境 */ var http = require('http'); var event = require('./service/event'); require('./service/channel.manager.js'); require('./service/player.manager.js'); require('./service/chat.plugin.js'); require('./service/nlog.plugin.js'); require('./service/player.plugin.js'); //require('./file-storage'); require('./service/mysql-storage'); http.createServer(function(request, response){ event.emit('request', request, response); }).listen(process.env.APP_PORT);
;[...Array(5)].forEach((_, i) => require(`./assets/${i}.jpg`)) ;[...Array(5)].forEach((_, i) => require(`./assets/${i}.png`)) ;[...Array(3)].forEach((_, i) => require(`./assets/${i}.svg`))
angular .module('app') .config(routesConfig); /** @ngInject */ function routesConfig($stateProvider, $urlRouterProvider, $locationProvider) { $locationProvider.html5Mode(true).hashPrefix('!'); $urlRouterProvider.otherwise('/home/new'); $stateProvider .state('home', { url: '/home/{locId}', params: { // default params locId: 'new' }, component: 'home', resolve: { } }) .state('home-trip', { url: '/home/{locId}/{trip}', params: { // default params locId: 'new' }, component: 'homeTrip', resolve: { } }) .state('search', { // for mobile url: '/search', component: 'search', resolve: { } }) .state('result', { url: '/result/{locId}/{keyword}', component: 'result', resolve: { } }) .state('myplan', { url: '/myplan', component: 'myplan', resolve: { } }) .state('myplan-trip', { url: '/myplan/{trip}', component: 'planTrip', resolve: { } }) .state('myplan-trip-edit', { url: '/myplan/{trip}/edit', component: 'tripEdit', resolve: { } }) .state('myfavor', { url: '/myfavor', component: 'myfavor', resolve: { } }) .state('myfavor-trip', { url: '/myfavor/{trip}', component: 'favorTrip', resolve: { } }) .state('more', { url: '/more/{user}', component: 'more', resolve: { } }) ; }
/*Счетчик состоит из спана и кнопок, которые должны увеличивать и уменьшать значение счетчика на 1. Создай переменную counterValue в которой будет хранится текущее значение счетчика. Создай функции increment и decrement для увеличения и уменьшения значения счетчика Добавь слушатели кликов на кнопки, вызовы функций и обновление интерфейса <div id="counter"> <button type="button" data-action="decrement">-1</button> <span id="value">0</span> <button type="button" data-action="increment">+1</button> </div>*/ const value = document.getElementById("value"); const incrementBtn = document.querySelector('[data-action="increment"]'); const decrementBtn = document.querySelector('[data-action="decrement"]'); let counterValue = value.textContent; function increment() { counterValue++; value.textContent = counterValue; } function decrement() { counterValue--; value.textContent = counterValue; } incrementBtn.addEventListener('click', increment); decrementBtn.addEventListener('click', decrement);
/** * A module that routes to a controller according to the url * @module users/userRoutes * @param app - the userRouter (express.Router()) invoked by the server */ var userController = require('./userController.js'); module.exports = function (app) { app.post('/signup', userController.signup); app.post('/login', userController.login); };
define(function(require) { 'use strict'; require('application/applicationTemplate'); require('businessValue/businessValueTemplate'); require('contact/contactTemplate'); require('cost/costTemplate'); require('deployment/deploymentTemplate'); require('general/generalTemplate'); require('health/healthTemplate'); require('security/securityTemplate'); require('usage/usageTemplate'); var angular = require('angular'); var applicationController = require('application/applicationController'); var applicationService = require('application/applicationService'); var applicationDirective = require('application/applicationDirective'); var businessValueController = require('businessValue/businessValueController'); var businessValueService = require('businessValue/businessValueService'); var businessValueDirective = require('businessValue/businessValueDirective'); var contactController = require('contact/contactController'); var contactService = require('contact/contactService'); var contactDirective = require('contact/contactDirective'); var costController = require('cost/costController'); var costService = require('cost/costController'); var costDirective = require('cost/costDirective'); var deploymentController = require('deployment/deploymentController'); var deploymentService = require('deployment/deploymentService'); var deploymentDirective = require('deployment/deploymentDirective'); var generalController = require('general/generalController'); var generalService = require('general/generalService'); var generalDirective = require('general/generalDirective'); var healthController = require('health/healthController'); var healthService = require('health/healthService'); var healthDirective = require('health/healthDirective'); var securityController = require('security/securityController'); var securityService = require('security/securityService'); var securityDirective = require('security/securityDirective'); var usageController = require('usage/usageController'); var usageService = require('usage/usageService'); var usageDirective = require('usage/usageDirective'); var applicationModule = angular.module('my.applicationModule', [ 'application.template', 'businessValue.template', 'contact.template', 'cost.template', 'deployment.template', 'general.template', 'health.template', 'security.template', 'usage.template' ]); applicationModule .controller('applicationController', applicationController) .service('applicationService', applicationService) .directive('applicationDirective', applicationDirective) .controller('businessValueController',businessValueController) .service('businessValueService',businessValueService) .directive('businessValueDirective',businessValueDirective) .controller('contactController', contactController) .service('contactService', contactService) .directive('contactDirective', contactDirective) .controller('costController',costController) .service('costService',costService) .directive('costDirective',costDirective) .controller('deploymentController',deploymentController) .service('deploymentService',deploymentService) .directive('deploymentDirective',deploymentDirective) .controller('generalController',generalController) .service('generalService',generalService) .directive('generalDirective',generalDirective) .controller('healthController', healthController) .service('healthService',healthService) .directive('healthDirective',healthDirective) .controller('securityController',securityController) .service('securityService',securityService) .directive('securityDirective',securityDirective) .controller('usageController',usageController) .service('usageService',usageService) .directive('usageDirective',usageDirective); return applicationModule; });
import React, { useContext } from 'react'; import { GlobalContext } from '../context/GlobalState'; export default function Transaction(props) { const { deleteTransaction } = useContext(GlobalContext); const sign = props.transaction.amount < 0 ? '-' : '+'; return ( <li className={sign === '+' ? 'plus' : 'minus'}> <span> {props.transaction.text} {sign}${Math.abs(props.transaction.amount)} </span> <button onClick={() => deleteTransaction(props.transaction.id)} className="waves-effect waves-light btn grey darken-4" > x </button> </li> ); }
import React, {useRef} from 'react'; import { Dropdown } from 'semantic-ui-react'; import DocumentsReadyTable from './DocumentsReadyTable/DocumentsReadyTable'; import UploadMaketModal from "../../modals/UploadMaket/UploadMaketModal"; import RoleBasedRender from '../../RoleBasedRender/RoleBasedRender'; import DateTimePicker from '../../DateTimePicker/DateTimePicker'; const mockInfo = [ { date: new Date().toISOString(), object: 'Объект 1', document: 'Макет Availability', status: 'Не отправлен' }, { date: new Date().toISOString(), object: 'Объект 1', document: 'Макет Availability', status: 'Отправлен' }, { date: new Date().toISOString(), object: 'Объект 1', document: 'Макет Availability', status: 'Не отправлен' }, { date: new Date().toISOString(), object: 'Объект 1', document: 'Макет Availability', status: 'Отправлен' }, { date: new Date().toISOString(), object: 'Объект 1', document: 'Макет Availability', status: 'Не отправлен' }, { date: new Date().toISOString(), object: 'Объект 1', document: 'Макет Availability', status: 'Отправлен' }, { date: new Date().toISOString(), object: 'Объект 1', document: 'Макет Availability', status: 'Не отправлен' }, { date: new Date().toISOString(), object: 'Объект 1', document: 'Макет Availability', status: 'Не отправлен' }, ]; const mockInfo2 = [ { date: new Date().toISOString(), document: 'Макет Availability', status: 'Не отправлен' }, { date: new Date().toISOString(), document: 'Макет Availability', status: 'Отправлен' }, { date: new Date().toISOString(), document: 'Макет Availability', status: 'Не отправлен' }, { date: new Date().toISOString(), document: 'Макет Availability', status: 'Отправлен' }, { date: new Date().toISOString(), document: 'Макет Availability', status: 'Не отправлен' }, { date: new Date().toISOString(), document: 'Макет Availability', status: 'Отправлен' }, { date: new Date().toISOString(), document: 'Макет Availability', status: 'Не отправлен' }, { date: new Date().toISOString(), document: 'Макет Availability', status: 'Не отправлен' }, ]; const dateFilterOptions = [ { key: '1 января 2019 - 1 сентября 2019', text: '1 января 2019 - 1 сентября 2019', value: '1 января 2019 - 1 сентября 2019', }, { key: '1 сентября 2019 - 1 октября 2019', text: '1 сентября 2019 - 1 октября 2019', value: '1 сентября 2019 - 1 октября 2019', }, ]; const statusOptions = [ { key: 'С любым статусом', text: 'С любым статусом', value: 'С любым статусом', }, { key: 'Отправлен', text: 'Отправлен', value: 'Отправлен', }, { key: 'Не отправлен', text: 'Не отправлен', value: 'Не отправлен', }, ]; function DocumentsReady() { const childRef = useRef(); const handleDelete = event => console.log('Clicked delete'); const handleRowClick = event => console.log('Clicked'); return ( <div> <div className='flex-row space'> <div className='flex-row'> <DateTimePicker /> <Dropdown defaultValue='С любым статусом' fluid className="app-dropdown-button date-range-selector small-input-dropdown dropdown-margin" selection icon='angle down' options={ statusOptions } /> </div> <RoleBasedRender requiredRoles={ ['Администратор'] } > <button className='primary-button flex-row' onClick={() => childRef.current.showModal()}>Загрузить макет Availability</button> </RoleBasedRender> </div> <RoleBasedRender requiredRoles={ ['Администратор'] } > <DocumentsReadyTable objects={ mockInfo } onDelete={ handleDelete } onRowClick={ handleRowClick } /> </RoleBasedRender> <RoleBasedRender requiredRoles={ ['Потребитель'] } > <DocumentsReadyTable objects={ mockInfo2 } onDelete={ handleDelete } onRowClick={ handleRowClick } /> </RoleBasedRender> <UploadMaketModal ref={childRef}/> </div> ); } export default DocumentsReady;
import {combineReducers} from 'redux'; import cates from './categoryReducer'; import products from './productReducer'; import comments from './commentReducer'; import errorObject from './errorReducer'; import account from './accountReducer'; import carts from './cartReducer'; const rootReducer = combineReducers({ // short hand property names cates,products,comments,errorObject,account,carts }) export default rootReducer;
/** * The MIT License (MIT) * Copyright (c) 2016, Jeff Jenkins @jeffj. */ const React = require('react'); const _ = require('lodash'); const Markdown = require('react-remarkable'); import { OverlayTrigger, Popover } from 'react-bootstrap'; import { Link } from 'react-router'; const Para = React.createClass({ getInitialState: function() { return { text: this.props.text } }, propTypes:{ text: React.PropTypes.string.isRequired, sref: React.PropTypes.array.isRequired, tags: React.PropTypes.array.isRequired, onUp: React.PropTypes.func.isRequired, _key: React.PropTypes.number.isRequired, linkId: React.PropTypes.string, scrollID: React.PropTypes.bool }, render: function() { const tags = this.props.tags.concat(this.props.sref); const text = this.buildParagraphs(tags, this.props.text); const scroll = this.props.scrollID?'scroll':null; return <p id={scroll} className="page-para" onMouseDown={this._down} onMouseLeave={this._leave} onMouseUp={this._up} > {text} </p> }, /** * Builds a Paragraphs text. */ buildParagraphs: function(tags, text){ const that = this; tags = _.sortBy(tags, function(tag){return tag.index[1]}); var nodes=[]; var beforeIndex = 0; //Iterate over the tags and add links to them. _.each(tags, function(tag, i){ // Get the text and node surrounding the tags const beforeText = text.slice(beforeIndex, tag.index[0]); const nodeText = text.slice(tag.index[0], tag.index[1]); //const className = const key = nodes.length-1; var linkClass = tag.sref?'link-sref':'link-href'; if (tag._id === that.props.linkId)linkClass += ' highlight'; const node = tag.sref? <Link to={'/'+tag.sref+'/link/'+tag._id} key={key} className={linkClass} >{nodeText}</Link>: <a target="_blank" href={tag.href} key={key} className={linkClass}> {nodeText} <span className="glyphicon glyphicon-new-window" style={{fontSize: "1.3rem", marginLeft:'.4rem'}} /> </a> // const popover = <Popover // id="popover-link"> // <strong>Holy guacamole!</strong> Check this info. // </Popover> // const overLay = <OverlayTrigger // key={key} // placement="top" overlay={popover}> // {node} // </OverlayTrigger> // Hold and index of the last node. beforeIndex = tag.index[1] // Push the nodes into the nodes array nodes.push(beforeText); nodes.push(node); nodes.push(afterText); }); const lastIndex = tags.length>0?tags[tags.length-1].index[1]:0; const afterText = text.slice(lastIndex, text.length);// Get the trailing text for the paragraph. nodes.push(afterText); return nodes; }, /** * Gets the page's selected text. */ _down: function(e){ this.down = true; }, /** * Gets the page's selected text. */ _up: function(e){ const text = this._getSelectionText(); const startIndex = this.props.text.indexOf(text) const endIndex = startIndex + text.length; if ( this.down && startIndex!==-1 && text.length>0) { this.props.onUp(this.props._key, startIndex, endIndex); } }, /** * Gets the page's selected text. */ _leave: function(e){ this.down = false; }, /** * Gets the page's selected text. */ _getSelectionText: function() { var text = ""; if (window.getSelection) { text = window.getSelection().toString(); } else if (document.selection && document.selection.type != "Control") { text = document.selection.createRange().text; } return text; } }) module.exports = Para;
import { createStyles, makeStyles } from "@material-ui/core/styles"; export default makeStyles((theme) => createStyles({ tittleH3: { fontStyle: 'normal', fontWeight: 'bold', fontSize: '10px', margin: '0px' }, formControl: { width: '30%', }, inputCustom: { height: '40px', width:'110px' }, h4: { marginLeft:'10px', fontStyle: 'normal', fontWeight: 'normal', fontSize: '16px', lineHeight: '22px', letterSpacing: '-0.02em', color: ' #595959' } }) );
angular.module('dataCoffee').controller('listCategorias', listCategorias); listCategorias.$inject = ['$scope', '$http', '$rootScope', '$route']; function listCategorias($scope, $http, $rootScope, $route) { $http({ method: 'GET', url: $rootScope.url.list.categoria, headers: { 'Content-Type': 'application/json' } }).then(function success(response) { $scope.categorias = response.data; }, function error(response) { console.log(response.statusText); }); $scope.deletar = function(id) { //$scope.alert_reset(); alertify.set({ labels: { ok: "Sim", cancel: "Não" } }); alertify.confirm("Deseja remover este item?", function (e) { if (e){ $http({ method: 'GET', url: $rootScope.url.categoria + '?id=' + id, headers: {'Content-Type': 'application/json; charset=utf-8'} }).then(function success(response) { $scope.categoria = response.data; $http({ method: 'POST', url: $rootScope.url.del.categoria, data: $scope.categoria, headers: {'Content-Type': 'application/json; charset=utf-8'} }); $route.reload(); alertify.success("Removido com sucesso!"); }, function error(response) { console.log(response.statusText); }); } }); } }
import Link from 'next/link' import Avatar from '../components/avatar' import DateFormater from '../components/date-formater' import UseVisibility from '../components/useVisibility' import CoverImage from './cover-image' export default function PostPreview({ title, coverImage, date, excerpt, author, slug, tag }) { return ( <UseVisibility> <div className="p-6"> <div className="mb-5"> <CoverImage slug={slug} title={title} src={coverImage} /> </div> <h4 className="text-red-400 mb-2 text-xl lg:text-2xl leading-tight"> <Link as={`/tags/${tag.slug}`} href="/tags/[slug]"> <a className="hover:underline">{tag.name}</a> </Link> </h4> <h3 className="text-red-700 text-3xl mb-3 leading-snug"> <Link as={`/posts/${slug}`} href="/posts/[slug]"> <a className="hover:underline">{title}</a> </Link> </h3> <div className="text-gray-700 text-lg mb-4"> <DateFormater dateString={date} /> </div> <p className="text-lg text-gray-700 leading-relaxed mb-4">{excerpt}</p> <Avatar name={author.name} picture={author.profile_image} /> </div> </UseVisibility> ) }
const frutas = ['Maçã', 'Banana', 'Melancia'] // forEach() -> Método que percorre cada elemento function listaCompras(nome, indice) { console.log(`${indice + 1} - ${nome}`) } frutas.forEach(listaCompras) //A impressão é: //1 - Maçã //2 - Banana //3 – Melancia const frutas = ['Maçã', 'Banana', 'Melancia']; // for(let i =0; i< frutas.length; i++) { // console.log(frutas[i]); // } frutas.forEach((elemento, indice) => {console.log(`${indice + 1} - ${elemento}`)}); // for(const element of frutas)
#!/usr/bin/env node require('dotenv').config() const pReduce = require('./lib/p-reduce'); const delay = require('./lib/delay'); const Octokit = require('@octokit/rest') const octokit = new Octokit({ auth: process.env.GH_AUTH_TOKEN, previews: ['dorian-preview'] }) const [, , ...args] = process.argv const owner = args const options = octokit.repos.listForOrg.endpoint.merge({org: owner, type: 'all'}) octokit .paginate(options) .then(repositories => pReduce(repositories, (repository) => { if (repository.archived) { return Promise.resolve(); } const repo = repository.name return octokit.repos .enableVulnerabilityAlerts({ owner, repo }) .then(response => { if (response && response.status === 204) { console.log(`Success for ${owner}/${repo}`) } else { console.log(`Failed for ${owner}/${repo}`) } return delay(500); }) .catch(error => { console.error(`Failed for ${owner}/${repo} ${error.message} ${error.documentation_url} `) }) }) ) .catch(error => { console.error(`Getting repositories for organization ${owner} failed. ${error.message} (${error.status}) ${error.documentation_url} `) })
module.exports = { "extends": "eslint:recommended", "parser": "babel-eslint", "plugins": [ "react" ], "ecmaFeatures": { "arrowFunctions": true, "bindaryLiterals": true, "blockBindings": true, "classes": true, "defaultParams": true, "destructuring": true, "forOf": true, "generators": true, "modules": true, "objectLiteralComputedProperties": true, "objectLiteralShorthandMethods": true, "objectLiteralShorthandProperties": true, "octalLiterals": true, "restParams": true, "spread": true, "superInFunctions": true, "templateStrings": true, "jsx": true }, "env": { "browser": true, "node": true }, "rules": { "complexity": [1, 8], "curly": 2, "dot-notation": 1, "eqeqeq": 2, "no-else-return": 1, "no-extra-bind": 1, "no-multi-spaces": 2, "no-new": 2, "no-return-assign": 2, "no-self-compare": 2, "no-unused-expressions": 2, "no-useless-call": 1, "no-useless-concat": 1, "no-shadow-restricted-names": 2, "no-shadow": 2, "no-unused-vars": 1, "no-use-before-define": 2, "array-bracket-spacing": 1, "block-spacing": 1, "brace-style": 2, "camelcase": 2, "comma-spacing": 2, "comma-style": 2, "computed-property-spacing": 2, "jsx-quotes": 1, "key-spacing": 1, "new-parens": 2, "no-lonely-if": 1, "no-mixed-spaces-and-tabs": 2, "no-spaced-func": 2, "no-trailing-spaces": 2, "no-unneeded-ternary": 2, "object-curly-spacing": [1, "always"], "padded-blocks": [2, "never"], "quotes": [2, "single"], "semi": [2, "always"], "space-after-keywords": 2, "space-before-blocks": 2, "space-before-function-paren": [2, "never"], "space-in-parens": 2, "space-infix-ops": 2, "space-return-throw-case": 2, "spaced-comment": 2, "arrow-parens": 2, "arrow-spacing": 2, "constructor-super": 2, "generator-star-spacing": [2, { "before": true, "after": false }], "no-const-assign": 2, "no-this-before-super": 2, "no-var": 2, "react/jsx-no-undef": 2, "react/jsx-sort-prop-types": 1, "react/no-did-mount-set-state": 1, "react/no-did-update-set-state": 1, "react/no-multi-comp": 1, "react/no-unknown-property": 1, "react/prop-types": [1, { "ignore": ["className", "children", "style"] }], "react/self-closing-comp": 2, "react/sort-comp": 2, "react/wrap-multilines": 2 } };
// Usando um módulo criado! const reprograma = require('reprograma-course-tools'); console.log(reprograma.digaOla('Jessica'));
import _ from 'lodash'; export class Team { constructor(name, teams) { this._name = name; this._members = new Set(); this._teams = teams; } /** * * @returns {Teams} */ get teams() { return this._teams; } get name() { return this._name; } enemies() { return this.teams.enemies(this); } /** * @returns {Set} */ get members() { return this._members; } /** * @returns {Array} */ toArray() { return Array.from(this.members); } add(member) { this.members.add(member); return this; } get memberNames() { var out = []; for (let member of this.members) { out.push(member.name); } return out; } toString() { return this.name; } get defeated() { let out = true; for (let member of this.members) { switch (member.health) { case 'awake': out = false; break; case 'dazed': out = false; break; default: // leave as is } if (!out) { break; } } return out; } } export class Teams { constructor() { this._teams = new Map(); } get teams() { return this._teams; } add(name) { this.teams.set(name, new Team(name, this)); return this; } getTeam(name) { return this._teams.get(name); } get names() { const names = []; for (let team of this.teams.values()) { names.push(team.name); } return names; } toString() { return this.names.join(','); } enemies(fromTeam) { let enemies = []; for (let team of this.teams.values()) { if (!(fromTeam.name === team.name)) { enemies = enemies.concat(Array.from(team.members)); } } return enemies; } get done() { let stillStanding = 0; for (let team of this.teams.values()) { if (!team.defeated) { ++stillStanding; } } return stillStanding < 2; } }
var app = angular.module('pibescWeb', [ //internal 'navbar', 'home', 'versiculoDia', 'agendaEventos', 'videoSemana', //external 'carouselHeader', 'ui.bootstrap', 'ngAnimate', 'ngSanitize', 'ngRoute' ]) .config([ '$routeProvider', '$locationProvider', function($routeProvider, $locationProvider){ $routeProvider.when("/",{ template: "<home></home>" }) }] ); //can also be done like this: // .config(function($routeProvider){ // });
var loremIpsum = require('lorem-ipsum'); var objectAssign = require('object-assign'); var _ = require('lodash'); var loremIpsumArgs = { units: 'sentences', sentenceLowerBound: 2, sentenceUpperBound: 12, paragraphLowerBound: 1, paragraphUpperBound: 1, format: 'plain' }; class MessageGenerator { constructor(names) { var _this = this; this._names = names || ['Paf', '__ME__']; this._i=0; return _this; } /** * return on random message or a an array of them if the n argument is passed * @param n * @returns {*} */ next(n) { var _this = this; if (n === undefined) { var name = _this._names[Math.floor(Math.random() * _this._names.length)]; return { text: loremIpsum(loremIpsumArgs), author: name, date: new Date() } } return _.times(n, function (i) { return _.extend({id: i}, _this.next()); }); } /** * produce n random messages, with a random delay iwth average value delay (milliseconds) and fires the callback with each new one. * @param n * @param delay * @param callback */ async(n, delay, callback) { var _this = this; var asyncHandler = function (nLeft) { if (nLeft == 0) { return; } setTimeout(function () { var i = _this._i; _this._i++; callback(_.extend({id: i}, _this.next())); asyncHandler(nLeft - 1); }, 2 * delay * Math.random()); }; asyncHandler(n); } }; export default MessageGenerator;
import * as actions from '../actions/types'; const initialState = { expenses: [], loading: false } const expenseReducer = (state = initialState, action) => { switch(action.type) { case actions.GET_EXPENSES: return { ...state, expenses: action.payload, loading: false } case actions.DELETE_EXPENSE: return { ...state, expenses: state.expenses.filter(expense => expense._id !== action.payload) } case actions.ADD_EXPENSE: return { ...state, expenses: [action.payload, ...state.expenses] } case actions.EXPENSE_LOADING: return { ...state, loading: true } case actions.ADD_EXPENSE_FAIL: return { ...state, loading: false } default: return state } } export default expenseReducer;
export { default } from './NavbarProfile';
import './modal-action-number.less' import ModalDeleteUser from './modal-delete-user/modal-delete-user.jsx' import {lastAppointment} from 'services' class ModalActionNumber extends React.Component { constructor (props) { super(props) this.state = { confirmDelete: false } this.handleClick = this.handleClick.bind(this) this.handleDelete = this.handleDelete.bind(this) } handleClick (e) { if (e.target.classList.contains('modal-action-number')) { this.props.onShowComponent() } } handleDelete () { this.setState({confirmDelete: true}) } dispatchCustomers (id) { let wlp = window.location.pathname wlp = '/send-sms' window.location.search = `?client_id=[${id}]&referrer=${wlp}` } prevent = e => e.stopPropagation() render () { return (<div className={'modal-action-number' + (this.props.isOffModal ? ' hidden_bgr' : '')} onClick={this.props.offActionsModal}> <div className={this.state.confirmDelete ? 'modal-action-wrap hide' : 'modal-action-wrap' + (this.props.isOffModal ? ' closing-popup' : '')} onClick={this.prevent}> <div className='modal-action-number__profile' style={{backgroundImage: `linear-gradient(rgba(79, 45, 167, 0.95), rgba(79, 45, 167, 0.95)), url(${config.urls.base_client_data + this.props.onHandleCustomer.id}/${encodeURIComponent(this.props.onHandleCustomer.profile_image)})`}} ref={customerProfile => { this.customerProfile = customerProfile }}> <div className='modal-action-number__profile-image'> <img className='modal-action-number__profile-image-img' onError={e => { // set background img if image not found this.customerProfile.style.cssText = `background-image: linear-gradient(rgba(79, 45, 167, 0.95), rgba(79, 45, 167, 0.95)), url(${config.urls.clients_public + config.urls.defaultPicture})` e.target.setAttribute('src', config.urls.clients_public + config.urls.defaultPicture) }} src={`${config.urls.base_client_data}${this.props.onHandleCustomer.id}/${encodeURIComponent(this.props.onHandleCustomer.profile_image)}`} /> </div> <p className='modal-action-number__profile-name'>{this.props.onHandleCustomer.name}</p> <div className='last_appointment'>{lastAppointment(this.props.onHandleCustomer && this.props.onHandleCustomer.last_appointment)}</div> </div> <div className='modal-action-number__communications'> <a href={`tel:${this.props.onHandleCustomer.phone}`} className='modal-action-number__communications-tel'> <img src={config.urls.base_clients_list_data + 'ic-call-24-px.svg'} /> <p className='modal-action-number__communications-text'> {`${config.translations.modal_actions_call} ${this.props.onHandleCustomer.name}`} </p> </a> <a href={`sms:${this.props.onHandleCustomer.phone}`} className='modal-action-number__communications-sms'> <img src={config.urls.base_clients_list_data + 'ic-textsms-24-px.svg'} /> <span className='modal-action-number__communications-text'>{config.translations.modal_actions_sms}</span> </a> {this.props.onHandleCustomer.phone_canonical && <a href={config.urls.wa_api.replace('{phone}', this.props.onHandleCustomer.phone_canonical.slice(1))} className='modal-action-number__communications-chat'> <img src={config.urls.base_clients_list_data + 'whatsapp.svg'} /> <span className='modal-action-number__communications-text'>{config.translations.modal_actions_chat}</span> </a>} <div className='modal-action-number__communications-delete' onClick={this.handleDelete}> {this.state.confirmDelete && <ModalDeleteUser onDeleteCustomer={this.props.onDeleteCustomer} isOffModal={this.props.isOffModal} offActionsModal={this.props.offActionsModal} onShowComponent={this.props.onShowComponent} selectedUser={this.props.onHandleCustomer} />} <img src={config.urls.base_clients_list_data + 'ic-delete-forever-24-px.svg'}/> <span className='modal-action-number__communications-text'>{config.translations.modal_actions_delete}</span> </div> <div className='modal-action-number__communications-cancel' onClick={this.props.offActionsModal}> <span className='modal-action-number__communications-cancel-text'>{config.translations.customer_actions}</span> </div> </div> </div> </div>) } } export default ModalActionNumber
import Link from 'next/link'; const NavLink = (props) => { const {location, name} return ( <a> <Link href={location}>{name}</Link> </a> ) } export default NavLink
import React from 'react'; import ReactDom from 'react-dom'; import Header from './Header'; import $ from 'jquery'; export default React.createClass({ getInitialState: function() { return { data: [], csPwd:false, idCard:false }; }, componentDidMount: function() { let reqParam = this.props.location.state; console.log('页面传递参数:' + reqParam); console.log(reqParam); //绑定事件 $('.mask_box').on('touchend','.closeX',function() { this.props.history.pushState(reqParam, "/mobile") }.bind(this)); }, render: function() { const m1 = ( <section className="mask_box" id="mask_1"> <section className="mask_content"> <a className="mui-icon mui-icon-closeempty closeX" ></a> <div className="content_prop"> <p>请用手机15304473967</p> <h3>发送CXXD至1001获取验证码</h3> <input type="text" placeholder="请输入验证码" id="mask_1_text"/> <button type="submit" className="selectBtn_bCol" id="mask_1_submit">确定</button> </div> </section> </section> ); const m2 = ( <section className="mask_box" id="mask_2"> <section className="mask_content"> <a className="mui-icon mui-icon-closeempty closeX" ></a> <div className="content_prop"> <p>短信验证码已发送至</p> <h3 className="font_46">18899887756</h3> <input type="text" placeholder="请输入验证码" id="mask_2_text"/> <button type="submit" className="selectBtn_bCol" id="mask_2_submit">确定</button> </div> </section> </section> ); let type = 2; if(null!= this.props.location.state) { type = this.props.location.state.type; } let m = ('1'== type) ? m1 : m2; return( <section className="mui-content contentBox"> <Header headerLabel="运营商查询"/> {m} </section> ); } });
class Weather { constructor(city) { this.city = city; } //fetch weather from API async getWeather() { const response = await fetch(`https://cors-anywhere.herokuapp.com/https://www.metaweather.com/api/location/search/?query=${this.city}`); const responsData = await response.json(); return responsData; } //change location changeLocation(city) { this.city = city; } }
/** * 1.声明一个函数 say,拥有一个形参 what,函数的功能是输出 "say: what" (what 替换为 形参的具体值) * 2.声明一个函数 isNullable,拥有一个形参 unknown,函数的功能是判断 unknown 是否是 ''、null、undefined、NaN * 并返回 true 或 false * 3.定义变量 a,输出 isNullable('')、isNullable(+'a')、isNullable(a)、isNullable(a + '')、isNullable(null)、isNullable(undefined)、isNullable(typeof undefined) * 4.声明一个函数 parseNumber,有一个形参 unknown,函数的功能是将 unknown 转化为 Number 类型,且需要将 NaN 转化为 0 * 返回转化后的值 * 5.理解 p66 3.7.2 */ function say(what) { console.log("say:", what); } function isNullable(unknown) { return unknown === '' || unknown === null || unknown === undefined || String(unknown) === 'NaN'; } function parseNumber(unknown) { const n = Number(unknown); /** NaN 不等于 NaN,因此要转化为字符串形式判断 */ if (String(n) === 'NaN') { return 0; } return n; /** 简写 * return n === NaN ? 0 : n; */ } say("happen"); let a; console.log(isNullable); console.log(isNullable('')); /** true */ console.log(isNullable(+'a')); /** false */ console.log(isNullable(a)); /** true */ console.log(isNullable(a + '')); /** false */ console.log(isNullable(null)); /** true */ console.log(isNullable(undefined)); /** true */ console.log(isNullable(typeof undefined)); /** false */ console.log(parseNumber(NaN)); console.log(parseNumber('NaN')); console.log(parseNumber('1a')); console.log(parseNumber('2333')); /** * 1.声明一个函数 log,将形参 some 转换为字符串,并在前面加上 "[debug] ",最后输出到控制台 * 例:log('glj 23333'); * 打印:[debug] glj 23333 * 2.声明一个函数 triangle,形参为一个正整数 n,先将 n 用 parseNumber 转换为数字,如果传入的 n 不符合条件,输出控制台提示 n 必须为正整数 * 当 n 符合条件时,用符号 '*' 在控制台打印一个直角三角形 * 例:triangle('a'); * 打印: n 必须为正整数,但传入的 n 为 `a` * * 例:triangle(1.5); * 打印: n 必须为正整数,但传入的 n 为 `1.5` * * 例:triangle(3); * 打印:* * * * * * * * */ function log(some) { return "[debug] " + String(some); } console.log(log(undefined)); function triangle(n) { if (typeof n === 'number' && n % 1 === 0 && n > 0) { for (let i = 1; i <= n; i++) { let num = ''; for (let j = 1; j <= i; j++) { num += '*'; } console.log(num) } return; } return console.log('n 必须为正整数,但传入的 n 为', n); } triangle(5); /** * 1.实现一个函数 render,入参 unknown,调用函数 isNullable 判断, * 当 isNullable(unknown) 为假时,打印 unknown 是无效值,并返回 null;为真时打印 unknown 是有效值,并返回 glj: unknown * * 2.打印一个杨辉三角 */ function render(unknown) { if (isNullable(unknown)) { console.log(unknown + '是无效值'); return null; } console.log(unknown + '是有效值'); return "glj:" + unknown; } render(56); /** * 递归法:未优化 * 原因:每一层都要全量递归到 (0, 0),导致性能极差 * * 该函数使用了递归的方法,多次调用自己以达到效果 * 在准备写函数时应当先找到函数的数学规律,通过规律来决定函数体的形式 */ function triangle2(n) { /** m 为行号,n 为列号 */ function calculation(m, n) { /** 第一个数为 1 */ if (n === 0) { return 1; } /** 最后一个数为 1 */ if (m === n) { return 1; } /** 多次调用函数使得中间的数为前一行的两个数相加 */ return calculation(m - 1, n - 1) + calculation(m - 1, n); } /** 该函数使用了两个 for 循环换以达到打印多行不同内容的目的 * 第一个 for 循环决定该结果有几行 * 第二个 for 循环决定改行有几个结果 */ for (let i = 0; i < n; i++) { let arr = []; /** 用来放第 i 行的数 */ for (let j = 0; j <= i; j++) { arr.push(calculation(i, j)); } console.log(arr.join(' ')); /** 字符串形式输出 */ } } triangle2(10); /** 迭代法:杨辉三角 */ function yangHuiTriangle(n) { /** 缓存上一层计算结果 */ let parentResult = []; for (let x = 0; x < n; x++) { const temp = []; /** 行号和列号是相等的 */ for (let y = 0; y <= x; y++) { /** 求该坐标上一层左侧数值和右侧数值 */ const parentLeftValue = parentResult[y - 1] || 0; const parentRightValue = parentResult[y] || 0; temp[y] = Math.max(1, parentLeftValue + parentRightValue); } /** 将本层计算结果缓存到 parentResult */ parentResult = temp; /** join 将数组项用空格拼接为字符串 */ console.log(temp.join(' ')); } } triangle2(10);
// This files handles evertything related to countdown on smartwatch // setInterval id var id = null; //global timer variables let hrs = 0; let minutes = 0; let seconds = 0; let timestampCount = 0; function countdownTimer() { // when user clicks on timer button it will either show the timer diplay on screen if // it was off or it will show the // home screen if timer was already on in display by checking the color of the timer icon // rgb(57, 62, 70) -> timer app was off turn it on // rgb(255, 255, 255)-> timer is on turn close the app let $icon = document.querySelector(".fa-clock-o"); if (window.getComputedStyle($icon).color === "rgb(57, 62, 70)") { document.querySelector(".date-time").style.display = "none"; document.querySelector(".messages").style.display = "none"; document.querySelector(".full-message").style.display = "none"; document.querySelector(".music-player").style.display = "none"; document.querySelector(".fa-music").style.color = "#393e46"; document.querySelector(".fa-comments").style.color = "#393e46"; $icon.style.color = "white"; } else if (window.getComputedStyle($icon).color === "rgb(255, 255, 255)") { document.querySelector(".date-time").style.display = "block"; document.querySelector(".messages").style.display = "flex"; document.querySelector(".full-message").style.display = "none"; document.querySelector(".music-player").style.display = "block"; document.querySelector(".fa-music").style.color = "#393e46"; document.querySelector(".fa-comments").style.color = "#393e46"; $icon.style.color = "#393e46"; } } function startPauseTimer() { /* This function takes care of start and pause timer */ let $playPause = document.querySelector(".play-timer"); let $timer = document.querySelector(".timer"); // if the timer icon was previouly play then how pause else vice versa $playPause.classList = $playPause.classList[1] === "fa-play" ? "fa fa-pause play-timer" : "fa fa-play play-timer"; // if play option is clicked if block is executed or if pause button is clicked else block is executed if ($playPause.classList[1] === "fa-pause") { id = setInterval(() => { seconds += 1; if (seconds == 61) { seconds = 0; minutes += 1; } if (minutes == 61) { seconds = 0; minutes = 0; hrs += 1; } $timer.innerHTML = `${hrs < 10 ? `0${hrs}` : hrs}:${ minutes < 10 ? `0${minutes}` : minutes }:${seconds < 10 ? `0${seconds}` : seconds}`; }, 1000); } else if ($playPause.classList[1] === "fa-play") { clearInterval(id); } } function getTimeStamp() { /** * When user clicks on flag icon the timestamp is noted and diplay below the main timer */ let $timestampContainer = document.querySelector(".timestamp-container"); // <div class="container"> // <p>1</p> // <p class="timestamp">00:00:00</p> // </div> // below code will create tags as per above comment let $container = document.createElement("div"); $container.classList = "container"; let $number = document.createElement("p"); $number.appendChild(document.createTextNode(++timestampCount)); $container.appendChild($number); let $timestamp = document.createElement("p"); $timestamp.classList = "timestamp"; $timestamp.appendChild( document.createTextNode(document.querySelector(".timer").innerHTML) ); $container.appendChild($timestamp); $timestampContainer.appendChild($container); } function stop() { /** * if user clicks on sqaaure icon the timestamp list is cleared and timer is set to zero */ clearInterval(id); document.querySelector(".timer").innerHTML = "00:00:00"; document.querySelector(".play-timer").classList = "fa fa-play play-timer"; document.querySelector(".timestamp-container").innerHTML = ""; } export { countdownTimer, startPauseTimer, getTimeStamp, stop };
//====== Importuje triedu DomLevels s metódami pre prácu s HTML DOM levels import {DomLevels} from "../srcRoot/domLevels.js"; import {MenuControl} from "../srcRoot/menuControl.js"; //====== Nahráme príslušný CSS súbor s popisom nižšie document.getElementsByTagName("head")[0].insertAdjacentHTML( 'beforeend', '<link id="original" rel="stylesheet" href="../srcLibrary/goAtHome.css" />'); // CSS current template // workbanch // workbanch-button export class GoAtHome { constructor(data={}, container={}, otherParams={}) { this.doConstruct(data, container, otherParams); } doConstruct(data={}, container={}, otherParams={}) { this.data = data; if( Object.keys(container).length > 0) { for(let key of Object.keys(container)) eval('this.' + key + ' = container.' + key + ';'); } if( Object.keys(otherParams).length > 0) { for(let key of Object.keys(otherParams)) eval('this.' + key + ' = otherParams.' + key + ';'); } } execRender(data={}, container={}, otherParams={}) { this.doConstruct(data, container, otherParams) let domLevels = new DomLevels(); let cnt = domLevels.createDivElement( this.parentID, this.ID, this.tester); $('#' + this.ID).addClass('workbanch d-flex justify-content-center'); let button = domLevels.createDivElement( this.ID, this.ID+'-as-button', this.tester); $('#' + this.ID+'-as-button').addClass('workbanch-button '); $('#' + this.ID+'-as-button').html(this.buttonText); $('#' + this.ID+'-as-button').unbind(); $('#' + this.ID+'-as-button').click(function() { let menuControl = new MenuControl(); menuControl.call('home'); }); } }
import React from "react"; // Data Layer export const StateContext = React.createContext(); // Provider export const StateProvider = ({ reducer, initialState, children }) => ( <StateContext.Provider value={React.useReducer(reducer, initialState)}> {children} </StateContext.Provider> ); // This is how it's used inside of a component export const useStateValue = () => React.useContext(StateContext);
import types from './actionTypes'; function readyToInstall(installable = true) { return {type: types.readyToInstall, payload: {installable}}; } function installCompleted(result) { return {type: types.installCompleted, payload: {result}}; } function installDetected() { return {type: types.installDetected}; } export default { readyToInstall, installCompleted, installDetected, }
import classNames from 'classnames'; import { FeelIcon as FeelIconSvg } from '../../icons'; const noop = () => {}; /** * @param {Object} props * @param {Object} props.label * @param {String} props.feel */ export default function FeelIcon(props) { const { feel = false, active, disabled = false, onClick = noop } = props; const feelRequiredLabel = 'FEEL expression is mandatory'; const feelOptionalLabel = `Click to ${active ? 'remove' : 'set a'} dynamic value with FEEL expression`; const handleClick = e => { onClick(e); // when pointer event was created from keyboard, keep focus on button if (!e.pointerType) { e.stopPropagation(); } }; return ( <button class={ classNames('bio-properties-panel-feel-icon', active ? 'active' : null, feel === 'required' ? 'required' : 'optional') } onClick={ handleClick } disabled={ feel === 'required' || disabled } title={ feel === 'required' ? feelRequiredLabel : feelOptionalLabel } > <FeelIconSvg /> </button> ); }
<!DOCTYPE html> <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/addons/p5.dom.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/addons/p5.sound.min.js"></script> <script src="p5.play.js"></script> <!-- The core Firebase JS SDK is always required and must be listed first --> <script src="https://www.gstatic.com/firebasejs/7.15.1/firebase-app.js"></script> <script src="https://www.gstatic.com/firebasejs/7.15.1/firebase-database.js"></script> <!-- TODO: Add SDKs for Firebase products that you want to use https://firebase.google.com/docs/web/setup#available-libraries --> <script> // Your web app's Firebase configuration var firebaseConfig = { apiKey: "AIzaSyBNete7_S-J1gy_e--bJo8dg2b6UUoVnaM", authDomain: "hotairballoon-3bf15.firebaseapp.com", databaseURL: "https://hotairballoon-3bf15-default-rtdb.firebaseio.com", projectId: "hotairballoon-3bf15", storageBucket: "hotairballoon-3bf15.appspot.com", messagingSenderId: "626683535337", appId: "1:626683535337:web:a8da905294cda5d22cf578" }; // Initialize Firebase firebase.initializeApp(firebaseConfig); </script> <link rel="stylesheet" type="text/css" href="style.css"/> <meta charset="utf-8"> </head> <body> <script src="sketch.js"></script> </body> </html>
const initState = {}; //this is where we maniplate the state const dreamReducer = (state = initState, action) => { switch (action.type) { case "ADD_DREAMCATCHER": console.log("added dreamcatcher", action.dreamcatcher); return state; case "ADD_DREAMCATCHER_ERROR": console.log("add dreamcatcher failed", action.err); return state; default: return state; } }; export default dreamReducer;
const express= require ("express"); const router= express.Router(); const productController= require ("../controllers/productController.js") router.get ("/", productController.entrarProduct); module.exports = router;
var token = artifacts.require('CoLabToken'); module.exports = deployer => { deployer.deploy(token); };
import './index.less'; import React, { Component } from 'react'; import { Router, Route, Link } from 'react-router'; class MovieItem extends Component { constructor (props) { super(props) } maybeRenderAlias () { let movie = this.props.movie; if (movie.alias) { return ( <div className="movie-card__info-item"> <span className="movie-card__info-head"> 别名: </span> <span className="movie-card__info-content"> {movie.alias} </span> </div> ); } } getDirectorList (list) { let result = list.map((i) => { return i.name; }); return result.join(','); } render () { const { movie } = this.props; return ( <div className="movie-item--list"> {/*<div className="movie-card__poster">*/} {/*<img className="movie-card__poster-img" src={movie.images.large}/>*/} {/*</div>*/} <div className="movie-card__info"> <div className="movie-card__title"> <Link to={{pathname: '/detail/' + movie.title+ movie.year}} className="movie-card__title-link" > {movie.title} </Link> </div> {/* <div className="movie-card__info-item"> <span className="movie-card__info-head"> 导演: </span> <span className="movie-card__info-content"> {this.getDirectorList(movie.directors || [])} </span> </div> <div className="movie-card__info-item"> <span className="movie-card__info-head"> 类型: </span> <span className="movie-card__info-content"> {movie.genres.join(', ')} </span> </div> {this.maybeRenderAlias()} <div className="movie-card__info-item"> <span className="movie-card__info-head"> 简介: </span> <span className="movie-card__info-content"> /!*{movie.synopsis.slice(0, 56) + '...'}*!/ </span> </div>*/} </div> </div> ) } } export default MovieItem;
'use strict'; import React, { Component, PropTypes } from 'react'; import { ActivityIndicator, Image, NavigationExperimental, StyleSheet, Text, TouchableHighlight } from 'react-native'; import { connect } from 'react-redux'; import Intro from './Intro'; import LoginEmail from './LoginEmail'; import LoginPassword from './LoginPassword'; import SignupName from './SignupName'; import SignupEmail from './SignupEmail'; import SignupPassword from './SignupPassword'; import Trips from './Trips'; import { apiLogin, apiSignup, navigatePush, navigatePop } from '../actions'; import { nextRoutes } from '../constants'; const { CardStack: NavigationCardStack, Header: NavigationHeader } = NavigationExperimental; class AppContainer extends Component { render() { let { backAction, navigationState } = this.props; let newProps = {}; if (this.shouldRenderBack()) { newProps.onNavigateBack = backAction; } return ( <NavigationCardStack {...newProps} navigationState={navigationState} renderOverlay={props => ( <NavigationHeader {...props} style={styles.header} renderLeftComponent={this.renderBackButtonComponent.bind(this)} renderRightComponent={this.renderNextButtonComponent.bind(this)} /> )} renderScene={this.renderScene} style={styles.container} /> ); } shouldRenderBack() { const { navigationState } = this.props; const index = navigationState.index; const key = navigationState.routes[index].key; return !(index === 0 || key === 'Trips'); } renderScene({ scene }) { const { route } = scene; switch(route.key) { case 'Intro': return <Intro />; case 'LoginEmail': return <LoginEmail />; case 'LoginPassword': return <LoginPassword />; case 'SignupName': return <SignupName />; case 'SignupEmail': return <SignupEmail />; case 'SignupPassword': return <SignupPassword />; case 'Trips': return <Trips />; } } renderBackButtonComponent(props) { if (!this.shouldRenderBack()) { return null; } return ( <TouchableHighlight activeOpacity={0.5} underlayColor={'#ffe945'} onPress={this.props.backAction} > <Image source={require('../assets/back-button.png')} style={styles.backButton} /> </TouchableHighlight> ); } renderNextButtonComponent(props) { const dismissKeyboard = require('dismissKeyboard'); const currentScene = props.scene.route.key; let next = nextRoutes[currentScene]; let { authState } = this.props; if (!next) { return null; } if (authState.isFetching) { return ( <ActivityIndicator animating={true} style={styles.activityIndicator} size={'small'} /> ); } let onPressAction = () => { switch (next) { case 'Trips': dismissKeyboard(); if (currentScene === 'LoginPassword') { return this.props.loginAction(); } else if (currentScene === 'SignupPassword') { return this.props.signupAction(); } else { return null; } default: return this.props.pushAction(next); } }; return ( <TouchableHighlight activeOpacity={1.0} underlayColor={'#ffe945'} onPress={onPressAction} > <Text style={styles.nextButton}> Next </Text> </TouchableHighlight> ); } } AppContainer.propTypes = { navigationState: PropTypes.object, authState: PropTypes.object, backAction: PropTypes.func.isRequired, loginAction: PropTypes.func.isRequired, signupAction: PropTypes.func.isRequired, pushAction: PropTypes.func.isRequired }; const styles = StyleSheet.create({ container: { flex: 1 }, header: { backgroundColor: 'rgba(0, 0, 0, 0.0)', borderBottomWidth: 0 }, backButton: { margin: 10 }, nextButton: { fontSize: 16, margin: 10 }, activityIndicator: { height: 20, marginRight: 10, marginTop: 8 } }); export default connect( state => ({ navigationState: state.navigationState, authState: state.authState }), dispatch => ({ backAction: () => { dispatch(navigatePop()); }, loginAction: () => { dispatch(apiLogin()); }, signupAction: () => { dispatch(apiSignup()); }, pushAction: (key) => { dispatch(navigatePush(key)); } }) )(AppContainer);
/** * Created by liu 2018/6/5 **/ import React, {Component} from 'react'; import {storeAware} from 'react-hymn'; import {Spin, Radio, Form, message, Button, Modal, Input} from 'antd'; import TableView from '../../components/TableView' import Breadcrumb from '../../components/Breadcrumb.js' import AdvertisingSearch from '../../components/SearchView/AdvertisingSearch.js' import {articleTypeList, articleTypeSave, articleRemote} from '../../requests/http-req.js' const FormItem = Form.Item; const RadioGroup = Radio.Group; export default class ArticleType extends Component { constructor(props) { super(props); this.state = { showLoading: false, pageNo: 0, pageSize: 10, total: 0, listData: [], showModal: false, keyWords: null, searchKewWord: null, language: 'zh', typeName: null, id: null, description: null } } selectedRowKeys = null componentDidMount() { this.getData() } getData() { this.setState({showLoading: true}) articleTypeList({ pageNo: this.state.pageNo, pageSize: this.state.pageSize, keyWords: this.state.searchKewWord }).then((req) => { //console.log(req) if (!req.data.data) { message.warning('暂无数据') this.setState({showLoading: false}) return } //console.log(req) req.data.data && req.data.data.forEach((item, index) => { item.index = this.state.pageNo == 0 ? (index + 1) : (this.state.pageNo - 1) * 10 + index + 1 }) if (req.status == 200) { if (req.data.length == 0) { message.warning('没有符合的数据') } this.setState({ listData: req.data.data, pageNo: req.data.data.pages, total: req.data.total, }, () => { //console.log(this.state.listData) }) } this.setState({showLoading: false}) }) } onChangePagintion = (e) => { this.setState({ pageNo: e }, () => { this.getData() }) } onAdd = () => { if (this.state.keyWords && this.state.keyWords == '' || this.state.language && this.state.language == '' || this.state.typeName && this.state.typeName == '') { message.warning('检查') return; } articleTypeSave({ keyWords: this.state.keyWords, language: this.state.language, typeName: this.state.typeName, id: this.state.id, description: this.state.editDescribe }).then(req => { //console.log(req) if (req.status == 200) { message.success('成功') this.setState({ showModal: false, keyWords: null, language: 'zh', typeName: null, id: null, editDescribe: '' }) this.getData() } }) } onDel = () => { if (this.selectedRowKeys.length != 1) { message.warning('选择一个') } let id = this.state.listData[this.selectedRowKeys[0]].id articleRemote(id).then(req => { message.success('删除') //console.log(req) this.getData() }) } onSelectedRowKeys = (e) => { this.selectedRowKeys = e } renderUserList = () => { return ( <Spin spinning={this.state.showLoading}> <div className='row-user'> <Button onClick={() => this.setState({showModal: true})} style={{marginRight: '5px', marginLeft: '5px'}}>增加</Button> <Button onClick={this.onDel} style={{marginRight: '5px', marginLeft: '5px'}}>删除</Button> </div> <div style={{display: 'flex', flexDirection: 'column', marginTop: '20px', marginBottom: '20px'}}> <TableView columns={this.columns} data={this.state.listData} total={this.state.total} pageNo={this.state.pageNo} pageSize={this.state.pageSize} onSelectedRowKeys={this.onSelectedRowKeys} onChangePagintion={this.onChangePagintion}/> </div> </Spin> ) } renderSearch = () => { return ( <Form style={{ flexDirection: 'row', paddingLeft: '20px', display: 'flex', height: '60px', width: '100%', alignItems: 'center' }} className="ant-advanced-search-form" > <FormItem style={{margin: 'auto', flex: 1, paddingRight: '15px'}} label="名称" // hasFeedback // validateStatus="warning" > <Input onChange={(e) => { this.setState({searchKewWord: e.target.value}) }} value={this.state.searchKewWord} style={{width: '100%'}}/> </FormItem> <div style={{flex: 3}}/> <Button onClick={() => this.getData()} type="primary" icon="search" style={{ marginRight: '15px', }}>搜索 </Button> </Form> ) } render() { return ( <div className='center-user-list'> <Breadcrumb data={window.location.pathname}/> {this.renderSearch()} {this.renderUserList()} <Modal destroyOnClose={true} onCancel={() => this.setState({showModal: false})} title={"新增类型"} visible={this.state.showModal} onChange={() => { this.setState({showModal: false}) }} footer={null} > <div style={{display: 'flex', flexDirection: 'row', margin: '10px'}}> <div style={{width: '120px'}}>类型名称:</div> <Input value={this.state.typeName} onChange={(e) => { this.setState({typeName: e.target.value}) }}/> </div> <div style={{display: 'flex', flexDirection: 'row', margin: '10px'}}> <div style={{width: '120px'}}>类型ID:</div> <Input value={this.state.id} onChange={(e) => { this.setState({id: e.target.value}) }}/> </div> <div style={{display: 'flex', flexDirection: 'row', margin: '10px'}}> <div style={{width: '120px'}}>语言:</div> <RadioGroup onChange={(e) => this.setState({language: e})} value={this.state.language}> <Radio value={'zh'}>中文</Radio> <Radio value={'en'}>英文</Radio> </RadioGroup> </div> <div style={{display: 'flex', flexDirection: 'row', margin: '10px'}}> <div style={{width: '120px'}}>关键词:</div> <Input value={this.state.keyWords} onChange={(e) => { this.setState({keyWords: e.target.value}) }}/> </div> <div style={{display: 'flex', flexDirection: 'row', margin: '10px'}}> <div style={{width: '120px'}}>描述:</div> <Input value={this.state.editDescribe} onChange={(e) => { this.setState({editDescribe: e.target.value}) }}/> </div> <div style={{display: 'flex', flexDirection: 'row', alignItems: 'center', justifyContent: 'center'}}> <Button style={{width: '100px', marginLeft: '30px'}} onClick={() => this.onAdd()}>保存 </Button> <Button style={{width: '100px', marginLeft: '30px'}} onClick={() => this.setState({showModal: false})}>取消 </Button> </div> </Modal> </div> ) } columns = [ { width: 70, title: '序号', dataIndex: 'index', } , { title: '类型名称', dataIndex: 'typeName', key: 'typeName', } , { title: '类型ID', dataIndex: 'id', key: 'id', } , { title: '关键词', dataIndex: 'keyWords', key: 'keyWords' } , { title: '描述', dataIndex: 'description', key: 'description', } , { title: '语言', dataIndex: 'language', key: 'language', render: (t, r) => <div>{t == 'zh' ? '中文' : '英文'}</div> } , { title: '创建时间', dataIndex: 'createTime', key: 'createTime', }, { title: '修改时间', dataIndex: 'updateTime', key: 'updateTime', } ]; }
// // Created by Petro Borshchahivskyi on 2019-09-09. // /** * @typedef {Object} config * @property {Boolean} showDP = true - show digital points * @property {Boolean} showDots = true - show colon (clock's middle dots) * @property {Boolean} showText = false * @property {Number} digitsCount = 4 * @property {Number} size.margin - distance between digits * @property {Number} size.segmentWidth - vertical segment width * @property {Number} size.segmentHeight - vertical segment height * @property {Number} size.radius - dot radius * @property {String} colors.normal - color of segment * @property {String} colors.active - color of active segment * @property {String} colors.dot - color of dots * calculated: * @property {Number} size.width - SVG width * @property {Number} size.height - SVG height * @property {Number} size.gap * @property {Number} size.gapH * @property {Number} size.digitWidth * @property {Number} size.digitHeight * @property {Number} size.dotsPlace */ const xmlns = 'http://www.w3.org/2000/svg'; const defaultOptions = { digitsCount: 4, showDots: true, showDP: true, showText: false }; const defaultSizes = { segmentWidth: 16, segmentHeight: 64, margin: 10 }; const defaultColors = { normal: 'lightgray', active: 'red', dot: 'lightgray' }; /** * class Display * @extends config */ export default class Display { /** * @param {Element|String} element - parent element or selector to add SVG container * @param {config} options */ constructor(element, options = {}) { // store options Object.assign(this, { ...defaultOptions, ...options, size: { ...defaultSizes, ...options.size }, colors: { ...defaultColors, ...options.colors } }); this.svg = this.getSVG(element); let sizes = this.getSizesBySegment(); this.svg.setAttributeNS(null, 'viewBox', `0 0 ${sizes.width} ${sizes.height}`); if (!this.givenSVG) { this.svg.setAttributeNS(null, 'width', this.size.width || sizes.width); this.svg.setAttributeNS(null, 'height', this.size.height || sizes.height); } Object.assign(this.size, sizes); this.polygonShifts = { true: Display.getHorizontalPolygonShifts(this.size.segmentWidth, this.size.segmentHeight), false: Display.getVerticalPolygonShifts(this.size.segmentWidth, this.size.segmentHeight) }; this.draw(); } draw() { this.digits = []; this.colons = []; let x = 0; for (let i = 0; i < this.digitsCount; i++) { this.digits.push(this.makeDigit(x)); x += this.size.digitWidth + this.size.margin; const reverseI = this.digitsCount - i; if (this.showDots && reverseI % 2 && reverseI > 2) { this.colons.push(this.makeColon(x + this.size.radius)); x += this.size.dotsPlace; } } } getSVG(element = document.body) { if (element === String(element)) { element = document.querySelector(element); if (!element) throw new Error(`Cannot find element "${arguments[0]}"`); } if (element instanceof SVGElement) { this.givenSVG = true; return element; } const svg = document.createElementNS(xmlns, 'svg'); element.appendChild(svg); return svg; } getSizesBySegment() { const sW = this.size.segmentWidth; const sH = this.size.segmentHeight; const radius = this.size.radius || sW / 2; const gap = sW / 2 * Math.sqrt(2) / 4; const gapH = gap / Math.sqrt(2); const digitWidth = sW + 2 * gapH + sH + this.showDP * sW; const digitHeight = sW + 4 * gapH + 2 * sH; const dotsPlace = this.size.margin + sW + this.showDP * sW; const marginsCount = this.digitsCount - 1; const dotsCount = Math.ceil(this.digitsCount / 2) - 1; const width = this.digitsCount * digitWidth + this.size.margin * marginsCount + dotsPlace * dotsCount * this.showDots; return {radius, gap, gapH, digitWidth, digitHeight, dotsPlace, width, height: digitHeight}; } /** * change segment state * @param {Number} digit - digit index [0..digitsCount) * @param {Number} segment - segment number [1..7] * @param {Boolean} show - state */ setSegment(digit, segment, show) { this.fillSegment(this.digits[digit][segment - 1], show); } fillSegment(segment, status = false) { segment.setAttribute('fill', status ? this.colors.active : this.colors.normal); } clearDigit(digitIndex) { this.digits[digitIndex].forEach(segment => segment && this.fillSegment(segment, false)); } clear() { this.digits.forEach((digit, i) => this.clearDigit(i)); this.colons.forEach((colon, i) => this.setColon(i, false)); } setChar(digitIndex, char, dot = false) { const charByte = Display.getCharByte(char) | dot; this.digits[digitIndex].forEach((segment, i) => { if (segment) this.fillSegment(segment, charByte >> (7 - i) & 1); }); } setWord(word) { let char = 0; this.digits.forEach((_, i) => { const n = i + this.digitsCount % 2; if (this.showDots && i && !(n % 2) && word[char] === ':') { char++; this.setColon(Math.floor(n / 2) - 1, true); } this.setChar(i, word[char++] || ' ', Boolean(word[char] === '.' && char++)); }); } setColon(index, dotUp, dotDown = dotUp) { if (typeof index === 'boolean' && dotUp === undefined) { dotUp = dotDown = index; index = 0; } if (!this.showDots || index >= this.colons.length) return; this.fillSegment(this.colons[index].dotUp, dotUp); this.fillSegment(this.colons[index].dotDown, dotDown); } makeDigit(x = 0) { const index = this.digits.length; const group = document.createElementNS(xmlns, 'g'); group.setAttributeNS(null, 'name', `digit${index}`); this.svg.appendChild(group); const {gapH, radius, segmentWidth: sW, segmentHeight: sH, digitWidth: dW, digitHeight: dH} = this.size; const shift = sW / 2 + gapH; const a = this.addSegment(group,'a', x + shift , 0 ); const b = this.addSegment(group,'b', x + sH + gapH * 2, shift ); const c = this.addSegment(group,'c', x + sH + gapH * 2, shift + sH + 2 * gapH ); const d = this.addSegment(group,'d', x + shift , dH - sW ); const e = this.addSegment(group,'e', x + 0 , shift + sH + 2 * gapH ); const f = this.addSegment(group,'f', x + 0 , shift ); const g = this.addSegment(group,'g', x + shift , sH + 2 * gapH ); const dp = this.showDP ? this.addDot(group, x + dW - radius, dH - radius, 'dp') : null; if (this.showText) this.addText(group, x + shift + sH / 2, shift + sH / 2, index); return Object.assign([a, b, c, d, e, f, g, dp], {a, b, c, d, e, f, g, dp}) } makeColon(x) { const group = document.createElementNS(xmlns, 'g'); group.setAttributeNS(null, 'name', 'colon'); const shift = this.size.segmentHeight - this.size.radius; const dotUp = document.createElementNS(xmlns, 'circle'); dotUp.setAttribute('cx', x); dotUp.setAttribute('cy', shift); dotUp.setAttribute('r', this.size.radius); dotUp.setAttribute('fill', this.colors.dot); group.appendChild(dotUp); const dotDown = dotUp.cloneNode(); dotDown.setAttribute('cy', this.size.digitHeight - shift); group.appendChild(dotDown); this.svg.appendChild(group); return Object.assign([dotUp, dotDown], {dotUp, dotDown}); } addSegment(parent = this.svg, name, x, y) { const isHorizontal = ['a', 'd', 'g'].includes(name); const points = this.getSegmentPolygon(x, y, isHorizontal); const polygon = document.createElementNS(xmlns, 'polygon'); polygon.setAttribute('class', name); polygon.setAttribute('points', points.join(' ')); polygon.setAttribute('fill', this.colors.normal); parent.appendChild(polygon); if (this.showText) { const shiftW = this.size.segmentWidth / 2; const shiftH = this.size.segmentHeight / 2; this.addText(parent, x + (isHorizontal ? shiftH : shiftW), y + (isHorizontal ? shiftW : shiftH), name, true); } return polygon; }; addDot(parent = this.svg, x, y, name = 'dp') { const dot = document.createElementNS(xmlns, 'circle'); dot.setAttribute('class', name); dot.setAttribute('cx', x); dot.setAttribute('cy', y); dot.setAttribute('r', this.size.radius); dot.setAttribute('fill', this.colors.dot); parent.appendChild(dot); return dot; } addText(parent = this.svg, x, y, text, small = false) { const textElement = document.createElementNS(xmlns, 'text'); textElement.setAttribute('x', x); textElement.setAttribute('y', y); textElement.innerHTML = text; if (small) textElement.setAttribute('class', 'small'); parent.appendChild(textElement); return textElement; } getSegmentPolygon(x, y, isHorizontal) { return this.polygonShifts[isHorizontal].map(p => (p[0] + x) + ',' + (p[1] + y)); } static getVerticalPolygonShifts(sWidth, sHeight) { const p = sWidth / 2; return [ [p, 0], [sWidth, p], [sWidth, sHeight - p], [p, sHeight], [0, sHeight - p], [0, p] ]; } static getHorizontalPolygonShifts(sWidth, sHeight) { const p = sWidth / 2; return [ [0, p], [p, 0], [sHeight - p, 0], [sHeight, p], [sHeight - p, sWidth], [p, sWidth] ]; } static getCharByte(char) { switch (char) { // ABCDEFGp A case '0': return 0b11111100; // --- case '1': return 0b01100000; // | | case '2': return 0b11011010; // F | | B case '3': return 0b11110010; // | G | case '4': return 0b01100110; // --- case '5': return 0b10110110; // | | case '6': return 0b10111110; // E | | C case '7': return 0b11100000; // | | case '8': return 0b11111110; // --- (*) p case '9': return 0b11110110; // D case 'A': case 'a': return 0b11101110; case 'B': case 'b': return 0b00111110; case 'C': return 0b10011100; case 'c': return 0b00011010; case 'D': case 'd': return 0b01111010; case 'E': case 'e': return 0b10011110; case 'F': case 'f': return 0b10001110; case 'G': case 'g': return 0b10111100; case 'H': return 0b01101110; case 'h': return 0b00101110; case 'I': case 'i': return 0b00001100; case 'J': case 'j': return 0b01111000; case 'L': case 'l': return 0b00011100; case 'N': case 'n': return 0b00101010; case 'O': return 0b11111100; case 'o': return 0b00111010; case 'P': case 'p': return 0b11001110; case 'Q': case 'q': return 0b11100110; case 'R': case 'r': return 0b00001010; case 'S': case 's': return 0b10110110; case 'T': case 't': return 0b00011110; case 'U': return 0b01111100; case 'u': return 0b00111000; case 'Y': case 'y': return 0b01110110; case '_': return 0b00010000; case '-': return 0b00000010; case '°': return 0b11000110; case '?': return 0b11001010; case 'K': case 'k': case 'M': case 'm': case 'V': case 'v': case 'W': case 'w': case 'X': case 'x': case 'Z': case 'z': case ' ': case '': default: return 0b00000000; } } }
export { default } from 'twyr-dsl/components/twyr-card/header/subhead';
import React, { Component } from 'react'; import pic from './pic.png'; import './App.css'; class App extends Component { constructor(props) { super(props); this.state = {value: ''}; this.state1 = {value: ''}; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(event) { this.setState({value: event.target.value}); } handleSubmit(event) { var text = this.state.value; text = text.replace(/\*/g,"\\*") console.log(text); text = text.replace(/\`/g, "\\`") console.log(text); text = text.replace(/\_/g, "\\_") console.log(text); ///fix first line var line = text.split('\n'); line[0] = "_ _" + line[0]; var text = line[0] + "\n"; for(var i=1; i<line.length; i++) { text += line[i] + "\n"; } this.setState({value: text }); event.preventDefault(); } render() { return ( <div className="App"> <header className="App-header"> <img src={pic} className="App-logo" alt="logo" /> <h1 className="App-title">Escape ASCII for Discord here</h1> </header> <div className="blankspace"></div> <form className="form-stuff" onSubmit={this.handleSubmit}> <label> <textarea className="texts" rows="22" value={this.state.value} onChange={this.handleChange} /> </label> <input className="submitbox" type="submit" value="escape" /> </form> </div> ); } } export default App;
var http = require("http"); var express = require("express"); var app = express(); var server = http.createServer(app); var io = require("socket.io")(server); var mongoUtil = require("./mongoUtil"); var chatterName; var messageStack = []; mongoUtil.connect(); app.get("/", (req, res)=>{ res.sendFile(__dirname+"/public/socket-client.html"); }); io.on("connection", (client)=>{ console.log("New Client connected!"); client.emit("MsgToClient", {status : "Connection accepted!"}) client.on("MsgToServer", (username, msg)=>{ messageStack.push(msg); chatterName = username; console.log(username + " says : " + msg); client.emit("toClient", 'Me', msg); client.broadcast.emit("toClient",username, msg); }) client.on("disconnect", ()=>{ var data = { username : chatterName, messages : messageStack } mongoUtil.insertData(data); }) }) server.listen(3030, function(){ console.log("Socket Server running on Port 3030...") })
import React from 'react'; import styled from 'styled-components'; const Container = styled.div` display: flex; align-items: center; width: calc(100%-10px); cursor: pointer; position: relative; transition: all 0.2s ease-out; padding: 5px; border-radius: 4px; opacity: ${props => props.disabled ? '0.5' : '1'} &:hover { background-color: ${props => props.readonly ? 'transparent' : '#939393'}; } ` const Avatar = styled.img` width: 36px; height: 36px; display: flex; margin-right: 10px; font-size: 10px; text-align: center; line-height: 0px; ` const UserName = styled.h4` font-weight: bold; display: flex; margin-bottom: 3px; ` const GamerInfo = styled.div` display: flex; flex-direction: column; ` const GamesCount = styled.p` display: flex; justify-self: end; font-size: 12px; right: 12px; top: 9px; ` const RemoveButton = styled.button` width: 25px; height: 25px; position: absolute; right: 5px; background: transparent; border: none; cursor: pointer; font-size: 16px; ` class Gamer extends React.Component { onRemoveGamer = (e) => { e.preventDefault(); e.stopPropagation(); this.props.onRemove(); } render () { const { gamer, margin, readonly, disabled } = this.props; let multiplayerGames = gamer.games && gamer.games.length > 0 ? gamer.games.filter(game => { return game.is_multiplayer }): []; return ( <Container readonly={readonly || false} disabled={disabled || false} style={{marginBottom: margin ? '10px' : '0'}}> <Avatar src={gamer.avatarfull} alt="Avatar"/> <GamerInfo> <UserName>{gamer.realname.trim() || gamer.personaname}</UserName> <GamesCount>{multiplayerGames.length || 0} multiplayer games</GamesCount> </GamerInfo> {!readonly && <RemoveButton onClick={this.onRemoveGamer}>&#10005;</RemoveButton>} </Container> ) } } export default Gamer;
const { Router } = require('express'); const heroController = require('../controller/superhero.controller'); const paginate = require('../middlewares/paginate.mw'); const uploadImage = require('../middlewares/upload.image'); const heroRouter = Router(); heroRouter.post('/', uploadImage, heroController.createSuperhero); heroRouter.get('/', paginate, heroController.getSuperHeroes); heroRouter.get('/:id', heroController.getSuperhero); heroRouter.patch('/:id', heroController.updateSuperHero); heroRouter.delete('/:id', heroController.deleteSuperHero); module.exports = heroRouter;
import { expect } from 'chai' import { cloneDeep } from 'lodash' import { accountToApi, accountFromApi } from '../account-service' describe('account-service', function () { describe('accountFromApi', function () { it('should convert roles array into role object', function () { const client = { id: 1, roles: ['ABC', 'DEF'] } const res = accountFromApi(client) expect(res.roles).to.be.an.object expect(res.roles.ABC).to.be.true expect(res.roles.DEF).to.be.true }) it('sets an empty object as roles when no roles received', function () { const client = { id: 1 } const res = accountFromApi(client) expect(res.roles).to.be.an.object }) }) describe('accountToApi', function () { it('should create an array with roles value set to true', function () { const client = { id: 1, roles: { set: true, notSet: false } } const res = accountToApi(client) expect(res.roles).to.be.an.array expect(res.roles.length).to.equal(1) expect(res.roles[0]).to.equal('set') }) it('creates does not change passed data', function () { const client = { id: 1, roles: { test: 1 } } const copy = cloneDeep(client) const res = accountFromApi(client) expect(res).to.be.not.equal(client) expect(client).to.deep.equal(copy) }) }) })
let settings= { subtitles: 'none', source: 'piratebay', type: 'movies', player: 'vlc' } module.exports = { settings }
//计算模块,钱,注数 class Calculate { //计算注数 //active 是当前选中的号码个数 //play_name是当前的玩法标识 computeCount(active, play_name) { let count = 0; //当前注数默认为0; const exist = this.play_list.has(play_name); //判断玩法是否存在。 const arr = new Array(active).fill('0'); //创建数组的同时,赋值一个常量(表示数组的长度,但是是空的),所以用fill将数组中的每个元素都变为‘0’ //let e=new Array(3);console.log(e);//(3) [empty × 3] if(exist && play_name.at(0) === "r") { count = Calculate.combine(arr, play_name.split('')[1]).length; //combine是静态方法,通过类去调用 // 用指定字符分割字符串,返回一个数组. } //不满足时count为0. return count; } //@@@@@@@@@@组合运算,@@@@@@@@@ // 指的是从x个元素中,选出y个进行组合,有多少种方案 // arr是参与组合运算的数组,size是组合运算的基数@@@@@@@@@@@ static combine(arr, size) { //???最后算出来是什么 let allResult = []; //最后的结果。 //为了及时运行函数,采用自调,三个参数对应f函数中的参数, // 在es6中不能匿名自调 //假设选中的是任二,则size是二,arr是选中号码的集合, (function f(arr, size, result) { let arrLen = arr.length; //如果集合小于基数,返回 if(size > arrLen) { return; } //如果两者相等,则 if(size === arrLen) { allResult.push([].concat(result, arr)); console.log(allResult); console.log(result); } else { for(let i = 0; i < arrLen; i++) { let newResult = [].concat(result); newResult.push(arr[i]); if(size === 1) { allResult.push(newResult) } else { let newArr = [].concat(arr); newArr.splice(0, i + 1); f(newArr, size - 1, newResult) } } } })(arr, size, []) return allResult; } //计算金额,奖金范围预测 //active 是当前选中的号码个数 computeBonus(active, play_name) { const play = play_name.split(''); //['r','2'] const self = this; let arr = new Array(play[1] * 1).fill(0); let min, max; if(play[0] === 'r') { let min_active = 5 - (11 - active); //最小命中数, // 11中5,选了active个,剩下的号码11 - active全中,则选中的号码中,能中的号码数5 - (11 - active),即为最小命中数。 //一共有5个号码会中,如选中<6个,则最小命中数是<0,选中=6个,则最小命中数是=0 // 如选中>6个,则最小命中数>0,如选中7个,则最小命中数是1,因为剩下4个号码,则选择的号码中一定会有一个中 //最小命中数>0,选中>6个,最大是5. if(min_active > 0) { //选择任五,任四及以下。 if(min_active - play[1] >= 0) { arr = new Array(min_active).fill(0); min = Calculate.combine(arr, play[1]).length; } else { //选择任六及以上。 //选号满足要求。要求至少选择play[1]个。 if(play[1] - 5 > 0 && active - play[1] >= 0) { arr = new Array(active - 5).fill(0); min = Calculate.combine(arr, play[1] - 5).length; //arr = new Array(active).fill(0); // min = Calculate.combine(arr,5).length; } else { //选号不满足要求。选择少于play[1]个。 min = active - play[1] > -1 ? 1 : 0 } } } else { //不能全中的情况。 min = active - play[1] > -1 ? 1 : 0; } //最大命中数,最大是5,在active中选择最小的数。 let max_active = Math.min(active, 5); //选任六及以上。 if(play[1] - 5 > 0) { if(active - play[1] >= 0) { arr = new Array(active - 5).fill(0); max = Calculate.combine(arr, play[1] - 5).length; } else { max = 0; } //选任五以下 } else if(play[1] - 5 < 0) { arr = new Array(Math.min(active, 5)).fill(0); max = Calculate.combine(arr, play[1]).length; //选任五 } else { max = 1; } } return [min, max].map(item => item * self.play_list.get(play_name).bonus); //play_name //map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。 } } export default Calculate
var searchData= [ ['filehandling_2ecpp_19',['fileHandling.cpp',['../file_handling_8cpp.html',1,'']]], ['filehandling_2eh_20',['fileHandling.h',['../file_handling_8h.html',1,'']]], ['flip_21',['flip',['../flip_8cpp.html#a4edd79e29805f2796fdab0549d09f06d',1,'flip(bmpFile *inBmp, const char direction):&#160;flip.cpp'],['../flip_8h.html#a4edd79e29805f2796fdab0549d09f06d',1,'flip(bmpFile *inBmp, const char direction):&#160;flip.cpp']]], ['flip_2ecpp_22',['flip.cpp',['../flip_8cpp.html',1,'']]], ['flip_2eh_23',['flip.h',['../flip_8h.html',1,'']]], ['flip_5fh_24',['FLIP_H',['../flip_8cpp.html#a437dbd600594b5661231f9ee25af95f0',1,'FLIP_H():&#160;flip.cpp'],['../rotate_8cpp.html#a437dbd600594b5661231f9ee25af95f0',1,'FLIP_H():&#160;rotate.cpp']]] ];
import registerComponent from "../../../core/component_registrator"; import BaseComponent from "../../component_wrapper/component"; import { Bullet as BulletComponent } from "./bullet"; export default class Bullet extends BaseComponent { _getActionConfigs() { return { onTooltipHidden: {}, onTooltipShown: {}, onContentReady: { excludeValidators: ["disabled"] } }; } get _propsInfo() { return { twoWay: [["canvas", { width: 0, height: 0, top: 0, left: 0, bottom: 0, right: 0 }, "canvasChange"]], allowNull: [], elements: [], templates: [], props: ["value", "color", "target", "targetColor", "targetWidth", "showTarget", "showZeroLevel", "startScaleValue", "endScaleValue", "tooltip", "onTooltipHidden", "onTooltipShown", "size", "margin", "disabled", "rtlEnabled", "classes", "className", "defaultCanvas", "onContentReady", "pointerEvents", "canvasChange", "canvas"] }; } get _viewComponent() { return BulletComponent; } } registerComponent("dxBullet", Bullet);
// 활성화/비활성화 애니메이션 시간. var ANIMATION_DURATION =600; //활성화 영역 높이값. var ACTIVE_HEIGHT = 93; //비활성화 영 높이값. var DE_ACTIVE_HEIGHT = 20; // 현재 활성화되어 있는 메뉴 아이템. var $currentActiveMenuItem; $(document).ready(function(){ $(".menu_item").bind("mouseenter", function(){ //1. 활성화된 메뉴 아이템이 있는 경우 비활성화 시켜준다. if($currentActiveMenuItem){ deactiveMenuItem($currentActiveMenuItem) } activeMenuItem($(this)); }); }); // 메뉴 아이템 비활성화 처리. function deactiveMenuItem($menuItem){ //1-1. 메뉴 아이템의 높이 값을 축소. $menuItem.stop(); $menuItem.animate({height:DE_ACTIVE_HEIGHT}, ANIMATION_DURATION, "easeOutQuint" ); //1-2. 메뉴 아이템의 컨텐츠 위치 값을 0으로 만든다. // (메뉴 아이템 비활성화 영역이 보이도록) $menuItem.find("div").stop(); $menuItem.find("div").animate({top:0}, ANIMATION_DURATION, "easeOutQuint" ); } // 메뉴 아이템 활성화 처리. function activeMenuItem($menuItem){ //2. 메뉴 아이템을 활성화 시켜준다. //2-1. 메뉴 아이템의 높이 값을 메뉴 아이템 이미지만큼 확대시켜줌. $menuItem.stop(); $menuItem.animate({height:ACTIVE_HEIGHT}, ANIMATION_DURATION, "easeOutQuint" ); //2-2. 메뉴 아이템 컨텐츠 위치값을 -20만큼 이동시킨다 // (메뉴 아이템 활성화 영역이 보이도록) $menuItem.find("div").stop(); $menuItem.find("div").animate({top:-DE_ACTIVE_HEIGHT}, ANIMATION_DURATION, "easeOutQuint" ); // 활성화된 메뉴 아이템 업데이트. $currentActiveMenuItem = $menuItem; }
'use strict'; import React, {Component} from 'react'; import {CardItemContainerEditor} from "./items/CardItemContainerEditor"; export class CardEditor extends Component{ constructor(props) { super(props); this.state = { card: props.card }; this.handleCardChange = this.handleCardChange.bind(this); this.updateCardContent = this.updateCardContent.bind(this); this.onUpdate = props.onUpdate; } render() { const card = this.state.card; const cardItems = card.content || []; return ( <form className="card-editor"> <input name="name" type="text" value={card.name} onChange={this.handleCardChange}/> <CardItemContainerEditor container={cardItems} onUpdate={this.updateCardContent} onRemove={this.removeItem}/> </form> ); } handleCardChange(event) { const target = event.target; const value = target.value; const name = target.name; let card = this.state.card; card[name] = value; this.props.onUpdate(card); } updateCardContent(content) { const card = this.state.card; card.content = content; this.props.onUpdate(card); } }
const jwt = require("jsonwebtoken"); const APIError = require("./APIError"); const { JWT_SECRET_KEY } = require("../config"); function ensureAuth(request, response, next) { try { const token = request.headers.authorization.split(" ")[1]; jwt.verify(token, JWT_SECRET_KEY); return next(); } catch (err) { return next( new APIError(401, "Unauthorized", "Missing or invalid auth token.") ); } } module.exports = ensureAuth;
import React from "react"; import PropTypes from "prop-types"; import TableCell from "@material-ui/core/TableCell"; import TableHead from "@material-ui/core/TableHead"; import TableRow from "@material-ui/core/TableRow"; import TableSortLabel from "@material-ui/core/TableSortLabel"; import Checkbox from "@material-ui/core/Checkbox"; import Tooltip from "@material-ui/core/Tooltip"; import CheckBoxOutlineBlank from "@material-ui/icons/CheckBoxOutlineBlank"; import CheckBoxIcon from "@material-ui/icons/CheckBox"; import IndeterminateCheckBoxIcon from "@material-ui/icons/IndeterminateCheckBox"; import { withStyles, Typography } from "../../../node_modules/@material-ui/core"; const styles = { tableCellPadding: { padding: "0 5px", }, checkBoxSize: { fontSize: "15px", }, checkBoxWidth: { width: "15px", }, }; class EnhancedTableHead extends React.Component { createSortHandler = property => (event) => { const { onRequestSort } = this.props; onRequestSort(event, property); }; render() { const { onSelectAllClick, order, orderBy, numSelected, rowCount, edit, columnData, disableAction, disableCheckBox, viewItem, actionItem, classes, } = this.props; return ( <TableHead> <TableRow> { disableAction || disableCheckBox ? null : ( <TableCell padding="checkbox"> <Checkbox className={classes.checkBoxWidth} indeterminate={numSelected > 0 && numSelected < rowCount} checked={numSelected === rowCount} icon={<CheckBoxOutlineBlank className={classes.checkBoxSize} />} checkedIcon={<CheckBoxIcon className={classes.checkBoxSize} />} indeterminateIcon={ <IndeterminateCheckBoxIcon className={classes.checkBoxSize} /> } onChange={onSelectAllClick} /> </TableCell> ) } {columnData.map(column => ( <TableCell className={classes.tableCellPadding} key={column.id} numeric={column.numeric} padding={column.disablePadding ? "none" : "default"} sortDirection={orderBy === column.id ? order : false} > <Tooltip title="Sort" placement={column.numeric ? "bottom-end" : "bottom-start"} enterDelay={300} > <TableSortLabel active={orderBy === column.id} direction={order} onClick={this.createSortHandler(column.id)} > <Typography variant="body2"> {column.label} </Typography> </TableSortLabel> </Tooltip> </TableCell> ))} { edit ? ( <TableCell padding="checkbox"> <Typography variant="body2"> Edit </Typography> </TableCell> ) : null } { viewItem ? ( <TableCell padding="checkbox"> <Typography variant="body2"> View </Typography> </TableCell> ) : null } { actionItem ? ( <TableCell padding="checkbox"> <Typography variant="body2"> Action </Typography> </TableCell> ) : null } </TableRow> </TableHead> ); } } EnhancedTableHead.propTypes = { numSelected: PropTypes.number.isRequired, onRequestSort: PropTypes.func.isRequired, onSelectAllClick: PropTypes.func.isRequired, order: PropTypes.string.isRequired, orderBy: PropTypes.string.isRequired, rowCount: PropTypes.number.isRequired, }; export default withStyles(styles)(EnhancedTableHead);
/** * 使用fs模块实现文件的拷贝 */ var fs = require('fs'); var src = 'htdocs/1.html'; //源 var dest = 'htdocs/11.html'; //目标 //读取文件内容 var buf = fs.readFileSync(src); //写出文件内容 fs.writeFileSync(dest, buf); console.log('文件复制完成');
export { default } from './ViewWeek'
import React from 'react'; import { Admin, Resource } from 'react-admin'; import createHistory from 'history/createBrowserHistory'; import loopbackClient from './loopbackClient'; import authClient from './authClient'; import * as Employees from './employee'; import * as Reviews from './reviews'; import './App.css'; const history = createHistory(); const App = () => ( <Admin history={history} dataProvider={loopbackClient(process.env.REACT_APP_API_URL)} authProvider={authClient} > { permissions => ([ <Resource name="users" edit={permissions === 'admin' ? Employees.Edit : null} list={Employees.List} create={permissions === 'admin' ? Employees.Create : null} show={Employees.Show} icon={Employees.Icon} options={{ label: 'Employees' }} />, <Resource name="reviews" edit={Reviews.Edit} list={Reviews.List} create={permissions === 'admin' ? Reviews.Create : null} show={permissions === 'admin' ? Reviews.Show : null} icon={Reviews.Icon} options={{ label: 'Performance Review' }} /> ]) } </Admin> ); export default App;
define([ 'jquery', 'underscore', 'backbone' ], function($, _, Backbone){ var logisticGrowth = function(pop, r, K){ pop = pop*r*(1-pop/K) return pop }; return logisticGrowth; });
const settings = { "analysis": { "filter": { "gramFilter": { "type": "nGram", "min_gram": 1, "max_gram": 20, "token_chars": [ "letter", "digit" ] } }, "analyzer": { "gramAnalyzer": { "type": "custom", "tokenizer": "whitespace", "filter": [ "lowercase", "gramFilter" ] }, "whitespaceAnalyzer": { "type": "custom", "tokenizer": "whitespace", "filter": [ "lowercase" ] } } } }; const mappings = { "event": { "properties": { "event": { "type": "text", "analyzer": "gramAnalyzer", "search_analyzer": "whitespaceAnalyzer" }, "timestamp": { "index": false, "type": "date", }, // "custom_data": { // "type": "nested", // "properties": { // "key": { "type": "text" }, // "value": { "type": "text" }, // } // } } } }; module.exports = { settings, mappings }
const button = document.querySelector("input"); const table = document.querySelector("table"); const getRate = () => { var xhr = new XMLHttpRequest(); xhr.open("GET", "https://bank.gov.ua/NBUStatService/v1/statdirectory/exchange?json"); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { if (xhr.status == 200) { var data = JSON.parse(xhr.responseText); data.splice(56); document.querySelector("#date").innerHTML = "на " + data[0].exchangedate; let filter = data.filter((el) => { return el.rate > 25 }) console.log(filter) filter.forEach((element) => { if (element.cc !== "XDR") { let tr = document.createElement("tr"); table.append(tr); for (i = 0; i < 3; i++) { let td = document.createElement("td"); tr.append(td); } let first = tr.firstChild; first.innerHTML = element.txt; first.nextSibling.innerHTML = element.cc; tr.lastChild.innerHTML = element.rate.toFixed(2); } }); } else { let div = document.querySelector("main").lastChild.previousSibling; div.classList.add("error"); if (xhr.status == 400) { document.querySelector(".error").innerHTML = "Status code: 400, клієнська помилка" } if (xhr.status == 500) { document.querySelector(".error").innerHTML = "Status code: 500, серверна помилка" } } } } xhr.send(); button.removeEventListener('click', getRate) } button.addEventListener('click', getRate)
import React from "react"; import { BrowserRouter as Router, Route } from "react-router-dom"; import home from "./components/homePage/home"; import landlord from "./components/landlordPage/landlord"; import welcome from "./components/welcomePage/welcome"; import registration from "./components/registrationPage/registration"; import login from "./components/loginPage/login"; import application from "./components/apartmentApplicationPage/apartmentApplication"; function App() { return ( <Router> <div> <Route exact path="/" component={welcome} /> <Route exact path="/home" component={home} /> <Route exact path="/landLord" component={landlord} /> <Route exact path="/registration" component={registration} /> <Route exact path="/login" component={login} /> <Route exact path="/application" component={application} /> </div> </Router> ); } export default App;
import { combineReducers } from "redux"; import { cats_reducer } from "./cats_reducer" export const rootReducer = combineReducers({ cats: cats_reducer })
'use strict'; module.exports = (sequelize, DataTypes) => { const Tag = sequelize.define('Tag', { name: DataTypes.STRING }, { timestamps: false }); Tag.associate = function(models) { Tag.belongsToMany(models.Article, { through: 'Articles_Tags', as: 'tags', foreignKey: 'article_id' }); }; return Tag; };
import React, { useEffect, useState } from 'react'; import { connect } from 'dva'; import styles from './addQuestions.scss' import { Select, Button, Form, Input, notification } from 'antd'; import Editor from 'for-editor' import { injectIntl } from 'react-intl'; const { Option } = Select; function AddQuestions(props) { const { addQuestions, getClass, classify, allQuestions, allSubject, getText, allText, num, updatanull, err } = props const [mask, updataMask] = useState(false) const [addedMask, updataAddedMask] = useState(false) useEffect(() => { getClass() allQuestions() getText() }, []) useEffect(() => { if (num === 1) { updataMask(false) updataAddedMask(true) updatanull() } }, [num]) useEffect(() => { if (err) { // console.log(err) openNotification() updataMask(false) updatanull() } }, [err]) function openNotification() { notification.open({ message: 'Notification Title', description: "err", onClick: () => { console.log('Notification Clicked!'); }, }); }; //声明题干 let [value, setValue] = useState('') //声明答案 let [answerValue, setAnswerValue] = useState('') let handleChange = (value) => { setValue(value) } let handleChangeAnswer = (answerValue) => { setAnswerValue(answerValue) } let handleSubmit = e => { //validateFields 校验并获取一组输入域的值与 Error,若 fieldNames 参数为空,则校验全部组件 props.form.validateFieldsAndScroll((err, values) => { if (!err) { addQuestions({ title: values.stem, exam_id: values.exam_id, subject_id: values.subject_id, questions_type_id: values.questions_type_id, questions_stem: value, questions_answer: answerValue, user_id: 'w6l6n-cbvl6s' }); } }); }; const { getFieldDecorator } = props.form; return ( <div className={styles.wrapper}> <h2>{props.intl.formatMessage({ id: 'router.questions.add' })}</h2> <div className={styles.content}> <Form onSubmit={handleSubmit}> <div className={styles.con}> <h3>{props.intl.formatMessage({ id: 'router.questions.add.topic.information' })}</h3> <div className={styles.stem}> <label>{props.intl.formatMessage({ id: 'router.questions.add.stem' })}</label> <Form.Item> {getFieldDecorator('stem', { //validateTrigger 校验子节点值的时机 validateTrigger: 'onBlur', //rules 校验规则 rules: [ { required: true }, { min: 1, max: 20, message: '输入字数大于20!' } ], })(<Input placeholder={props.intl.formatMessage({ id: 'router.questions.add.a' })} />)} </Form.Item> </div> <div className={styles.topic_theme}> <label>{props.intl.formatMessage({ id: 'router.questions.add.topic.theme' })}</label> <Editor placeholder={props.intl.formatMessage({ id: 'router.questions.add.Please.enter.the.content' })} value={value} onChange={(value) => handleChange(value)} /> </div> <div className={styles.class}> <div className={styles.examination_type}> <label>{props.intl.formatMessage({ id: 'router.questions.add.please.choose.the.exam.type' })}</label> <Form.Item> {getFieldDecorator('exam_id', { initialValue: "8sc5d7-7p5f9e-cb2zii-ahe5i" })(<Select style={{ width: 200 }} > { classify.map(item => ( <Option key={item.exam_id} value={item.exam_id}>{item.exam_name}</Option> )) } </Select>)} </Form.Item> </div> <div className={styles.course_types}> <label>{props.intl.formatMessage({ id: 'router.questions.add.please.choose.the.course.type' })}</label> <Form.Item> {getFieldDecorator('subject_id', { initialValue: "fqtktr-1lq5u" })(<Select style={{ width: 200 }} > { allSubject.map(item => ( <Option key={item.subject_id} value={item.subject_id}>{item.subject_text}</Option> )) } </Select>)} </Form.Item> </div> <div className={styles.topic_type}> <label>{props.intl.formatMessage({ id: 'router.questions.add.please.choose.the.topic.type' })}</label> <Form.Item> {getFieldDecorator('questions_type_id', { initialValue: "774318-730z8m" })( <Select style={{ width: 200 }} > { allText.map(item => ( <Option key={item.questions_type_id} value={item.questions_type_id}>{item.questions_type_text}</Option> )) } </Select>)} </Form.Item> </div> </div> <div className={styles.answer_information}> <h3>{props.intl.formatMessage({ id: 'router.questions.add.answer.information' })}</h3> <Editor placeholder={props.intl.formatMessage({ id: 'router.questions.add.Please.enter.the.content' })} answerValue={answerValue} onChange={(answerValue) => handleChangeAnswer(answerValue)} /> </div> <div className={styles.footer}> <Button onClick={() => updataMask(true)}> {props.intl.formatMessage({ id: 'router.questions.add.submission' })} </Button> </div> { mask && <div className={styles.mask}> <div className={styles.mask_content}> <div className={styles.content_top}> <span>?</span> <h3>你确定要添加这道试题吗?</h3> <p>真的要添加吗</p> </div> <Form.Item className={styles.footer_button}> <Button onClick={() => updataMask(false)}> 取消 </Button> <Button type="primary" htmlType="submit" style={{ width: 110 }}> 确定 </Button> </Form.Item> </div> </div> } { addedMask && <div className={styles.added_mask}> <div className={styles.added_mask_content}> <i>√</i> <h3>试题添加成功</h3> <Button type="primary" style={{ width: 110 }} onClick={() => updataAddedMask(false)}> 知道了 </Button> </div> </div> } </div> </Form> </div> </div> ); } AddQuestions.propTypes = { }; const mapStateToProps = state => { return { ...state.add, } } const mapDispatchToProps = dispatch => { return { //添加试题 addQuestions: payload => { dispatch({ type: "add/addQuestions", payload }) }, // 获取考试类型 getClass: () => { dispatch({ type: "add/getClass" }) }, // 获取课程类型 allQuestions: () => { dispatch({ type: "add/getAllSubject" }) }, // 获取题目类型 getText: () => { dispatch({ type: "add/getAllQuestions" }) }, updatanull: () => { dispatch({ type: "add/changeNull" }) } } } export default injectIntl(connect(mapStateToProps, mapDispatchToProps)(Form.create()(AddQuestions)));
import Head from "./Head.js" import Bottom from "./Bottom.js" export default class Main { constructor() { this.init(); // Main.instance.checkLogin(); } static get instance() { if (!Main._instance) { Object.defineProperty(Main, "_instance", { value: new Main() }) } return Main._instance; } init() { let bottom = new Bottom(); bottom.appendTo("#bottom-fill"); } checkLogin() { if (!sessionStorage.name) { let head = new Head(); head.appendTo("#head-fill"); return } delete Head._left["请登录"] delete Head._left["免费注册"] Head._left[sessionStorage.name + "已登录"] = {}; let head = new Head(); head.appendTo("#head-fill"); } }
import React from 'react'; export default class ComponentStateAndInteractions extends React.Component { constructor(props) { super(props); // components internal state is declared in the constructor and exists during the lifecycle of the component this.state = { studentsCount: 0 }; } addStudentToCount(e) { // this.setState received an object that u wan't to merge with current state - output is a new object this.setState({studentsCount: this.state.studentsCount + 1}); } render() { return ( <div className="app-block"> <h2>This is an example of components internal state and interactions with it</h2> <p>Total number of students in class {this.state.studentsCount}</p> {/*event handler for click on the button*/} <button onClick={(e) => this.addStudentToCount(e)}>Add a student to count</button> </div> ); } }
import React from 'react'; import {Text, View, TouchableOpacity, Image, ScrollView} from 'react-native'; import styles from '../styles/styles.js'; import {HEIGHT, WIDTH} from '../styles/styles.js'; import AnimalText from './animalText'; import InPageImage from './inPageImage'; import AnimalTemplate from './animalTemplate'; import {localDB} from '../index.ios.js'; var arrayOfTexts = []; var arrayOfImagesFull = []; var arrayOfImagesElement = []; var arrayOfImagesThumbnails = []; var arrayOfFacts = []; var finalArray = []; var img1 = require('../images/arrow.png'); var img2 = require('../images/arrowUp.png') var actualImg = require('../images/arrow.png');; var nameOfAnimal = ""; var tmpb = "alpaka"; //temporary name for animal var showFact = false; var factsStyle = { height: 0, marginTop:20, display: 'none', }; export default class DatabaseContent extends React.Component { constructor(props) { super(props); } handlerButtonOnClick = () => { showFact = !showFact; if (showFact) { factsStyle = { height: HEIGHT/2, marginTop:20, maxWidth:"80%", }; actualImg = img2; } else { factsStyle = { height: 0, display: 'none', }; actualImg = img1; } } loadText = () => { // function to load informations about animal. localDB.get(nameOfAnimal, {attachments : true}) .then (doc => { this.forceUpdate(); arrayOfFacts = []; arrayOfTexts = []; arrayOfImagesFull = []; arrayOfImagesElement = []; arrayOfImagesThumbnails = []; tmp = []; finalArray = []; let counterImg = 0; let counterTxt = 0; if (this.props.adult) { // Adult version of animal doc.text_adult.forEach((i, idx) => { arrayOfTexts.push( <AnimalText style={{marginVertical:"10%", fontSize: HEIGHT/25, maxWidth:"80%"}} key={idx}> {i} </AnimalText> )}); } else { // Child version of animal doc.text_child.forEach((i, idx) => { arrayOfTexts.push( <AnimalText style={{marginVertical:"10%", fontSize: HEIGHT/25, maxWidth:"80%"}} key={idx}> {i} </AnimalText> )}); } doc.images.forEach((i,idx) => { //get images from localDB arrayOfImagesFull.push( // image in full resolution i.full ); arrayOfImagesThumbnails.push( // thumbnail i.thumbnail ); arrayOfImagesElement.push( // add elements of image to the array <InPageImage key={(arrayOfTexts.length + idx)} indexes={[idx]} thumbnails={arrayOfImagesThumbnails} images={arrayOfImagesFull} navigator={this.props.navigator} /> ); }); doc.facts.forEach((i, idx) => { // get facts of animal tmp.push( <Text style={{fontSize: HEIGHT/30}} key={idx+200}>{'\u2022'} {i}</Text> ); }); arrayOfFacts.push(<ScrollView style = {factsStyle}>{tmp}</ScrollView>); //add Box of facts arrayOfFacts.push(<TouchableOpacity onPress={this.handlerButtonOnClick}><Image style={{top:10, alignSelf:'center', marginBottom: 25}} source={actualImg}/></TouchableOpacity>); finalArray = finalArray.concat(arrayOfFacts); while (true) { // zip texts with images. In order : Image, text, image, text .... if (counterImg < arrayOfImagesElement.length) { finalArray.push(arrayOfImagesElement[counterImg]); counterImg++; } if (counterTxt < arrayOfTexts.length) { finalArray.push(arrayOfTexts[counterTxt]); counterTxt++; } if ((counterImg === arrayOfImagesElement.length) && (counterTxt === arrayOfTexts.length)) { break; } } }); if (!arrayOfTexts.length) { // return info text if it's loading data from localDB. return ( <Text style={{alignSelf:'center', marginTop: "25%", fontWeight: '800',flex:1, fontSize: 20}}> Načítavam </Text> ) } return finalArray; } render() { if (this.props.animalName == tmpb){ nameOfAnimal = this.props.animalName; } tmpb = this.props.animalName; return ( <AnimalTemplate> <Text style={{marginTop:20, fontWeight:'900', fontSize:HEIGHT/20, alignSelf:'center'}}>Základní informace</Text> {this.loadText()} </AnimalTemplate> ); } }
var express = require('express'); var router = express.Router(); var RestHandler = require('./restHandler'); module.exports = function (ModelName) { var restHandler = new RestHandler(ModelName); router.get('/', restHandler.getItems); router.get('/:id', restHandler.getItem); router.post('/', restHandler.createItem); router.put('/:id', restHandler.changeItem); router.patch('/:id', restHandler.updateItem); router.delete('/:id', restHandler.deleteItem); return router; };
describe('Question page', () => { it('When a poll is clicked on the home page, correct info is shown', () => { cy.visit('/') cy.login('johndoe') cy.get('a[href*="8xf0y6ziyjabvozdd253nd"]').click() cy.contains("Would You Rather") // * the text "Would You Rather" cy.get('img[data-cy=creator-image]') // * the picture of the user who posted the polling question; and cy.contains("have horrible short term memory") cy.contains("have horrible long term memory") // * the two options }) it('For answered polls, each of the two options contain certain info', () => { cy.visit('/questions/6ni6ok3ym7mf1p33lnez') cy.login('johndoe') cy.get('[data-cy=question-option]').as('question-options') cy.get('@question-options').first().contains("become a superhero")// * the text of the option; cy.get('@question-options').first().contains("0 people voted") // * the number of people who voted for that option; cy.get('@question-options').first().contains("0%") // * the percentage of people who voted for that option. cy.get('@question-options').last().contains("become a supervillain")// * the text of the option; cy.get('@question-options').last().contains("2 people voted") // * the number of people who voted for that option; cy.get('@question-options').last().contains("100%") // * the percentage of people who voted for that option. }) it('The option selected by the logged in user should be clearly marked.', () => { cy.visit('/questions/6ni6ok3ym7mf1p33lnez') cy.login('johndoe') cy.get('[data-cy=question-option]').as('question-options').should('have.class', 'voted') cy.get('@question-options').first().should('not.have.class', 'voted-option') cy.get('@question-options').last().should('have.class', 'voted-option') }) it('When the user is logged in, the details of the poll are shown. If the user is logged out') it('shows buttons to select not voted question', () => { cy.visit('/questions/8xf0y6ziyjabvozdd253nd') cy.login('johndoe') cy.get('.select-option-button').should('have.length', 2) cy.get('.select-option-button').first().click() cy.get('.selected-option-button').should('not.exist') }) it('when option is selected', () => { cy.visit('/questions/8xf0y6ziyjabvozdd253nd') cy.login('johndoe') cy.get('[data-cy=question-option]').as('question-options') cy.get('@question-options').first().find('button').click() cy.get('@question-options').find('button').should('not.exist'); }) })
import { widthBreakpointMd, widthBreakpointSm, widthBreakpointXL, widthBreakpointXS, widthBreakpointXXS, } from '@codeparticle/whitelabelwallet.styleguide/styles/layout.scss'; export const BREAKPOINTS = { PORTRAIT: widthBreakpointXXS, LANDSCAPE: widthBreakpointXS, TABLET: widthBreakpointSm, DESKTOP: widthBreakpointMd, WIDESCREEN: widthBreakpointXL, };
import React, {Component, Fragment} from 'react'; import {Table, Divider, Button, Modal, message, Input, Select} from 'antd'; import {Link} from 'react-router-dom'; import {connect} from 'react-redux'; import MainLoader from "../../common/Main Loader"; import InfoBatch from "./InfoBatch"; import FormGasto from "../animals/FormGasto"; import * as animalGastoActions from "../../../redux/actions/ganado/gastoAnimalActions"; import * as lotesActions from '../../../redux/actions/ganado/lotesActions'; import {bindActionCreators} from "redux"; const Option = Select.Option; const columns = [ { title: 'Arete Rancho', dataIndex: 'arete_rancho', key:'arete_rancho', render: (text, record) => ( <span> <Link to={`/admin/animals/${record.id}`}>{record.arete_rancho}</Link> </span> ), width:200, },{ title: 'Arete Siniga', dataIndex: 'arete_siniga', key:'arete_siniga', width:150 },{ title: 'Propietario', dataIndex: 'owner', key:'owner', width:150 },{ title:'Última Pesada', dataIndex:'pesadas', key:'pesadas', render:val=><p>{val.length===0?0:val[val.length-1].peso}Kg</p>, width:150 }]; class BatchDetailPage extends Component { state={ visible:false, selectedRowKeys:[], loading:false, canEdit:false, search:'', }; onSelectChange = (selectedRowKeys) => { this.setState({ selectedRowKeys }); }; showModal = () => { this.setState({ visible: true, }); }; handleCancel = () => { this.setState({ visible: false, }); }; saveGastos=(gasto)=>{ this.setState({loading:true}); let keys = this.state.selectedRowKeys; let parcialAmount = gasto.costo/keys.length; parcialAmount=parcialAmount.toFixed(2); let parcialQuantity = gasto.cantidad/keys.length; parcialQuantity=parcialQuantity.toFixed(2); for(let i in keys){ let animalId = keys[i]; gasto['animal']=animalId; gasto['costo']=parcialAmount; if(gasto.cantidad)gasto['cantidad']=parcialQuantity; let toSend = Object.assign({}, gasto); console.log(toSend) this.props.animalGastoActions.saveAnimalGasto(toSend) .then(r=>{ }).catch(e=>{ for (let i in e.response.data){ message.error(e.response.data[i]) } }) } this.setState({loading:false}); this.handleCancel(); message.success('Gasto agregado con éxito') }; handleStatus=(status)=>{ let lote = {}; lote['id'] = this.props.match.params.id; lote['status']=status; lote['corral']=null //this.props.lotesActions.editLote() }; handleEdit=()=>{ this.setState({canEdit:!this.state.canEdit}) }; edit=(lote)=>{ console.log(lote); if(lote.corral===undefined)delete lote['corral']; this.props.lotesActions.editLote(lote) .then(r=>{ message.success('editado con éxito') }).catch(e=>{ console.log(e.response.data) }) }; handleSearch=(e)=>{ this.setState({search:e.target.value}) }; render() { let {fetched, lote, corrales} = this.props; let {visible, selectedRowKeys, loading, canEdit, search} = this.state; if(!fetched)return(<MainLoader/>); const rowSelection = { selectedRowKeys, onChange: this.onSelectChange, }; let option_corrales = corrales.map((a, key)=><Option value={a.id} key={key}>{a.no_corral}</Option>); const disablebutton = selectedRowKeys.length > 0; let regEx = new RegExp(search, "i"); let animals = lote.animals?lote.animals.filter(a=>regEx.test(a.arete_rancho)||regEx.test(a.arete_siniga)||regEx.test(a.owner)):[]; return ( <Fragment> <div style={{marginBottom:10, color:'rgba(0, 0, 0, 0.65)' }}> Ganado <Divider type="vertical" /> <Link to={'/admin/lotes'}> Lotes </Link> <Divider type="vertical" /> {lote.name} </div> <InfoBatch {...lote} canEdit={canEdit} handleEdit={this.handleEdit} option_corrales={option_corrales} edit={this.edit}/> {loading?<MainLoader/>:''} <Divider/> <h3>Aretes de este Lote:</h3> <Input.Search onChange={this.handleSearch} value={search} style={{ width: 400 , margin:'1% 0'}} placeholder={'Busca por propietario, arete rancho o arete siniga'}/> <Modal title="Agregar nuevo animal" visible={visible} onCancel={this.handleCancel} width={'30%'} maskClosable={true} footer={[ null, null, ]} > <FormGasto saveGasto={this.saveGastos} handleCancel={this.handleCancel}/> </Modal> <Table pagination={false} scroll={{x:650, y:500}} rowSelection={rowSelection} columns={columns} dataSource={animals.filter(a=>a.status===true)} rowKey={record => record.id}/> {/*<Button disabled={!disablebutton} onClick={this.showModal} style={{margin:'1% 0'}}>Agregar Gasto</Button>*/} </Fragment> ); } } function mapStateToProps (state, ownProps) { let corrales = state.corrales.list.filter(c=>{ return c.lotes===null }); let loteId = ownProps.match.params.id; let lote = state.lotes.list.filter(l => { return loteId == l.id; }); lote = lote[0]; return { lote, corrales, fetched: lote !== undefined && corrales !==undefined, } } function mapDispatchToProps(dispatch){ return{ animalGastoActions:bindActionCreators(animalGastoActions, dispatch), lotesActions:bindActionCreators(lotesActions, dispatch), } } BatchDetailPage = connect(mapStateToProps, mapDispatchToProps)(BatchDetailPage); export default BatchDetailPage;
import React from 'react' import './error-indicator.css' const ErrorIndicator = () => { return ( <p className="error">Ooops...Something went wrong</p> ) } export default ErrorIndicator;
$(document).ready(function(){ obtenerTareas(); let modificar =false; function obtenerTareas(){ //alert("pruebas"); $.ajax({//invocamos a ajax url:'listar.php', type: "GET", success: function(tareas){ let task=JSON.parse(tareas); let template = ''; task.forEach(task =>{ template += `. <tr taskId="${task.id}"> <td>${task.id}</td> <td><a href='#' class="task-item">${task.name}</a></td> <td>${task.description}</td> <td> <button class="btn btn-danger">ELIMINAR</button></td> </tr> ` }); $('#tasks').html(template);//obtenemos el task } }); } $('#task-form').submit(e=>{ const datos = { name: $('#name').val(), description: $('#description').val(), id: $('#id').val(), } const url = modificar === false ? 'insertar.php': 'modificar.php'; $.post(url, datos, (response) =>{ obtenerTareas(); }); }); //invocamos obten el control de todo el formulario $(document).on('click','.task-item',(e)=>{ const elemento=$(this)[0].activeElement.parentElement;//tr const id=$(elemento).attr('taskId'); console.log(id); }); });
import Vue from 'vue'; import VueRouter from 'vue-router'; const routerPush = VueRouter.prototype.push VueRouter.prototype.push = function push(location) { return routerPush.call(this, location).catch(error => error) } const Index = () => import('@/views/index.vue') const Data = () => import('@/views/data.vue') Vue.use(VueRouter); const routes = [ { path: '/', name: 'Index', title: '首页', component: Index }, { path: '/data', name: 'data', title: '首页', component: Data }, { path: '*', name: '404', component: () => import(/* 404 */ '../views/404'), }, ] const linkVersion = window.location.pathname.match(/^\/(v\d{4}(-\d)?)/) const testVersion = window.location.pathname.match(/^\/(f-\w+)/) const rootPath = linkVersion ? linkVersion[1] : (testVersion ? testVersion[1] : '/') console.log(rootPath); const router = new VueRouter({ el: '#app', mode: 'history', base: rootPath, routes }) router.beforeEach((to,form,next)=>{ console.log(to,form) next() }) export default router
var Store = require('flux/utils').Store; var _albums = []; var CHANGE_EVENT = "change"; var AlbumConstants = require('../constants/album_constants'); var AppDispatcher = require('../dispatcher/dispatcher'); var AlbumStore = new Store(AppDispatcher); var resetAlbums = function(albums) { _albums = albums.slice(0); }; AlbumStore.all = function () { return _albums.slice(0); }; AlbumStore.__onDispatch = function(payload) { switch(payload.actionType) { case AlbumConstants.ALBUMS_RECEIVED: var result = resetAlbums(payload.albums); AlbumStore.__emitChange(); break; } }; module.exports = AlbumStore;
import { StaticQuery, graphql } from "gatsby"; import React from "react"; const CertificationsContent = () => ( <StaticQuery query={graphql` query { wordpressAcfPages(wordpress_id: { eq: 23 }) { acf { certifications { certifications_content certifications_image { alt_text slug source_url } } } } } `} render={data => ( <div className="col-12"> {data.wordpressAcfPages.acf.certifications.map(item => ( <div className="row se-bg-white " key={item.certifications_image.slug} > <div className="col-12 col-sm-8 col-lg-2"> <div className="img_part"> <img src={item.certifications_image.source_url} alt={item.certifications_image.alt_text} /> </div> </div> <div className="col-12 col-sm-8 col-lg-10"> <div className="se_logo_excerpt"> <p>{item.certifications_content}</p> </div> </div> </div> ))} </div> )} /> ); export default CertificationsContent;
'use strict'; app.factory('factBlacklist', function($http, $q) { var factBlacklist = {}; factBlacklist.getAll = function( ) { var deferred = $q.defer(); $http({method: 'GET', url: '/blacklist'}). success(function(data, status, headers, config) { console.log('factory "factBlacklist" - GET /blacklist: return success data: ' + JSON.stringify(data)); deferred.resolve(data); }). error(function(data, status, headers, config) { deferred.reject('factory "factBlacklist" - GET /blacklist: error loading data from server'); }); return deferred.promise; }; factBlacklist.addWordlist = function(wordlist) { var deferred = $q.defer(); console.log('factory "factBlacklist" - addWordlist wordlist: ' + JSON.stringify(wordlist)); var json = { wordlist : wordlist } $http({method: 'POST', url: '/blacklist', data: json}). success(function(data, status, headers, config) { console.log('factory "factBlacklist" - POST /blacklist: return success data: ' + JSON.stringify(data)); deferred.resolve(data); }). error(function(data, status, headers, config) { deferred.reject('factory "factBlacklist" - POST /blacklist: error loading data from server'); }); return deferred.promise; }; factBlacklist.deleteWord = function(uid) { var deferred = $q.defer(); console.log('factory "factBlacklist" - deleteDomain uid: ' + JSON.stringify(uid)); var url = '/blacklist/' + uid $http({method: 'DELETE', url: url}). success(function(data, status, headers, config) { console.log('factory "factBlacklist" - DELETE /blacklist: return success data: ' + JSON.stringify(data)); deferred.resolve(data); }). error(function(data, status, headers, config) { deferred.reject('factory "factBlacklist" - DELETE /blacklist: error loading data from server'); }); return deferred.promise; }; return factBlacklist; });
import React from 'react'; import ReactDOM from 'react-dom'; import { shallow } from 'enzyme'; import Menu from './Menu'; it('renders without crashing', () => { const div = document.createElement('div'); ReactDOM.render(<Menu />, div); ReactDOM.unmountComponentAtNode(div); }); describe('Testing component', () => { const onClick = jest.fn(); const createTestProps = (props) => { return { onClick, timeline: { ...props, }, }; }; const createWrapper = props => shallow(<Menu {...props} />); let wrapper; describe('callbacks', () => { beforeEach(() => { const props = createTestProps({ profile: 'test' }); wrapper = createWrapper(props); }); it('onClick should be call', () => { wrapper.find('button').simulate('click'); expect(onClick).toHaveBeenCalledTimes(1); expect(onClick).toHaveBeenCalledWith('test'); }); }); });
// Add vendor prefixed styles module.exports = { options: { flatten: true, layoutdir: '<%= paths.app %>/layouts', layout: 'default-layout.hbs', // the files are in 'layoutdir', assets: '<%= paths.app %>/resources', partials: ['<%= paths.app %>/partials/*.hbs'], data: '<%= paths.app %>/resources/data/*.json' }, dev: { files: { '<%= paths.app %>/': ['<%= paths.app %>/pages/*.hbs'] } } };
import React from "react"; import axios from "./axios"; import Logo from "./Logo"; import { Link, BrowserRouter, Route } from "react-router-dom"; import ProfilePicUpload from "./ProfilePicUpload"; import Profile from "./Profile"; import OtherProfiles from "./OtherProfiles"; import JobBoard from "./JobBoard"; import Friends from "./Friends"; import Online from "./Online"; import Chat from "./Chat"; export default class App extends React.Component { constructor() { super(); this.state = { firstname: "", lastname: "", email: "", profilePic: "/media/SVG/defaultimg.svg", bio: "", showUploader: false }; this.toggleUploader = this.toggleUploader.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.setNewImage = this.setNewImage.bind(this); this.setBio = this.setBio.bind(this); } componentDidMount() { axios.get("/user").then(resp => { this.setState({ firstname: resp.data.firstname, lastname: resp.data.lastname, email: resp.data.email, profilePic: resp.data.profilePic || this.state.profilePic, bio: resp.data.bio }); }); } toggleUploader() { this.setState({ showUploader: !this.state.showUploader }); } handleSubmit(e) { e.preventDefault(); } setNewImage(profilePic) { this.setState({ profilePic }); } setBio(bio) { this.setState({ bio }); } render() { return ( <BrowserRouter> <div> <div id="profilePic"> <Link to="/"> <img className="logoSmallheader" src="/media/SVG/logo-black.svg" /> </Link> <img onClick={this.toggleUploader} src={this.state.profilePic} alt="" /> </div> {this.state.showUploader && ( <ProfilePicUpload setNewImage={this.setNewImage} handleSubmit={this.handleSubmit} /> )} <div> <Route exact path="/" render={() => ( <Profile firstname={this.state.firstname} lastname={this.state.lastname} email={this.state.email} profilePic={this.state.profilePic} bio={this.state.bio} setBio={this.setBio} /> )} /> <Route path="/user/:id" component={OtherProfiles} /> <Route path="/friends" component={Friends} /> <Route path="/jobs" component={JobBoard} /> <Route path="/online" component={Online} /> <Route path="/chat" render={() => ( <Chat firstname={this.state.firstname} lastname={this.state.lastname} email={this.state.email} profilePic={this.state.profilePic} /> )} /> </div> </div> </BrowserRouter> ); } }
import useSWR, { SWRConfig } from 'swr'; import { useState } from 'react'; import '../pages/api/station'; const fetcher = (...args) => fetch(...args).then((res) => res.json()); export default function Times({ abbr, index, clickedIndex }) { if (index !== clickedIndex) return ''; const departureTimeUrl = `https://api.bart.gov/api/etd.aspx?cmd=etd&key=MW9S-E7SL-26DU-VV8V&json=y&orig=${abbr}`; //sconst { data, error } = useSWR(stationsUrl, fetcher); const { data, error } = useSWR(() => departureTimeUrl, fetcher); if (error) return <div>Error...</div>; if (!data) return <div>Loading...</div>; //console.log(data.root.station[0]); //console.log(abbr); //let info = data.root.station[0].map((obj, idx) => { // return <div key={obj.abbr}>{console.log(obj)}</div>; //}); let info = 'No Train Data Available'; // { // data.root.station[0].etd ? (info = `${data.root.station[0].etd[0].estimate[0].minutes} minutes`) : ''; // } let nest = ''; { data.root.station[0].etd ? (info = [ ...data.root.station[0].etd.map((obj, idx) => { nest = obj.estimate.map((objct, idx) => { return Object.values(objct); }); console.log(nest); return ( <div className="flex space-x-4 "> <div> {obj.destination}: </div> <div className=""> <div>Minutes: {nest[0][0]}</div> <div>Direction: {nest[0][2]}</div> <div>Line: {nest[0][4]}</div> </div> <br /> </div> ); }) ]) : ''; } return info; }
alert(1); //模块 var ylzrApp = angular.module('ylzrApp', []); //配置值 ylzrApp.value('defaultInput', 5); ylzrApp.constant('testConstant', 10); //配置方法 ylzrApp.factory('MathFun', function () { var factory = {}; factory.js = function (a, b) { return a * b; } return factory; }); //配置服务 // ylzrApp.service('JsService', function (MathService) { // this.dyjs = function (a, b) { // return MathService.js(a, b); // }; // }); alert(2); //控制器 ylzrApp.controller('ylzrCtrl', function ($scope, MathFun, defaultInput, testConstant) { alert(3); $scope.number = testConstant; $scope.result = MathFun.js($scope.number, $scope.number); $scope.ksjs = function () { $scope.result = MathFun.js($scope.number, $scope.number); } }); alert(4);
import React from "react"; import PropTypes from "prop-types"; import { accent, strBlack } from "../../../styles/color"; const NavBarTab = props => { const { iconName, title, onClicked } = props; return ( <div onClick={onClicked}> <i className={iconName} /> <p>{title}</p> <style jsx>{` div { display: flex; flex: 1; color: ${strBlack}; justify-content: center; align-items: center; padding: 10px 0; } div:hover { color: ${accent}; } p { margin: 0px; margin-left: 10px; font-weight: bold; } i { font-size: 22px; } `}</style> </div> ); }; NavBarTab.propTypes = { title: PropTypes.string.isRequired, iconName: PropTypes.string.isRequired, onClicked: PropTypes.func.isRequired }; export default NavBarTab;
import { Debug } from '../../core/debug.js'; import { uniformTypeToName, UNIFORMTYPE_INT, UNIFORMTYPE_FLOAT, UNIFORMTYPE_VEC2, UNIFORMTYPE_VEC3, UNIFORMTYPE_VEC4, UNIFORMTYPE_IVEC2, UNIFORMTYPE_IVEC3, UNIFORMTYPE_IVEC4, UNIFORMTYPE_FLOATARRAY, UNIFORMTYPE_VEC2ARRAY, UNIFORMTYPE_VEC3ARRAY, UNIFORMTYPE_MAT2, UNIFORMTYPE_MAT3 } from './constants.js'; import { DynamicBufferAllocation } from './dynamic-buffers.js'; // Uniform buffer set functions - only implemented for types for which the default // array to buffer copy does not work, or could be slower. const _updateFunctions = []; _updateFunctions[UNIFORMTYPE_FLOAT] = function (uniformBuffer, value, offset) { const dst = uniformBuffer.storageFloat32; dst[offset] = value; }; _updateFunctions[UNIFORMTYPE_VEC2] = (uniformBuffer, value, offset) => { const dst = uniformBuffer.storageFloat32; dst[offset] = value[0]; dst[offset + 1] = value[1]; }; _updateFunctions[UNIFORMTYPE_VEC3] = (uniformBuffer, value, offset) => { const dst = uniformBuffer.storageFloat32; dst[offset] = value[0]; dst[offset + 1] = value[1]; dst[offset + 2] = value[2]; }; _updateFunctions[UNIFORMTYPE_VEC4] = (uniformBuffer, value, offset) => { const dst = uniformBuffer.storageFloat32; dst[offset] = value[0]; dst[offset + 1] = value[1]; dst[offset + 2] = value[2]; dst[offset + 3] = value[3]; }; _updateFunctions[UNIFORMTYPE_INT] = function (uniformBuffer, value, offset) { const dst = uniformBuffer.storageInt32; dst[offset] = value; }; _updateFunctions[UNIFORMTYPE_IVEC2] = function (uniformBuffer, value, offset) { const dst = uniformBuffer.storageInt32; dst[offset] = value[0]; dst[offset + 1] = value[1]; }; _updateFunctions[UNIFORMTYPE_IVEC3] = function (uniformBuffer, value, offset) { const dst = uniformBuffer.storageInt32; dst[offset] = value[0]; dst[offset + 1] = value[1]; dst[offset + 2] = value[2]; }; _updateFunctions[UNIFORMTYPE_IVEC4] = function (uniformBuffer, value, offset) { const dst = uniformBuffer.storageInt32; dst[offset] = value[0]; dst[offset + 1] = value[1]; dst[offset + 2] = value[2]; dst[offset + 3] = value[3]; }; // convert from continuous array to vec2[3] with padding to vec4[2] _updateFunctions[UNIFORMTYPE_MAT2] = (uniformBuffer, value, offset) => { const dst = uniformBuffer.storageFloat32; dst[offset] = value[0]; dst[offset + 1] = value[1]; dst[offset + 4] = value[2]; dst[offset + 5] = value[3]; dst[offset + 8] = value[4]; dst[offset + 9] = value[5]; }; // convert from continuous array to vec3[3] with padding to vec4[3] _updateFunctions[UNIFORMTYPE_MAT3] = (uniformBuffer, value, offset) => { const dst = uniformBuffer.storageFloat32; dst[offset] = value[0]; dst[offset + 1] = value[1]; dst[offset + 2] = value[2]; dst[offset + 4] = value[3]; dst[offset + 5] = value[4]; dst[offset + 6] = value[5]; dst[offset + 8] = value[6]; dst[offset + 9] = value[7]; dst[offset + 10] = value[8]; }; _updateFunctions[UNIFORMTYPE_FLOATARRAY] = function (uniformBuffer, value, offset, count) { const dst = uniformBuffer.storageFloat32; for (let i = 0; i < count; i++) { dst[offset + i * 4] = value[i]; } }; _updateFunctions[UNIFORMTYPE_VEC2ARRAY] = (uniformBuffer, value, offset, count) => { const dst = uniformBuffer.storageFloat32; for (let i = 0; i < count; i++) { dst[offset + i * 4] = value[i * 2]; dst[offset + i * 4 + 1] = value[i * 2 + 1]; } }; _updateFunctions[UNIFORMTYPE_VEC3ARRAY] = (uniformBuffer, value, offset, count) => { const dst = uniformBuffer.storageFloat32; for (let i = 0; i < count; i++) { dst[offset + i * 4] = value[i * 3]; dst[offset + i * 4 + 1] = value[i * 3 + 1]; dst[offset + i * 4 + 2] = value[i * 3 + 2]; } }; /** * A uniform buffer represents a GPU memory buffer storing the uniforms. * * @ignore */ class UniformBuffer { device; /** @type {boolean} */ persistent; /** @type {DynamicBufferAllocation} */ allocation; /** @type {Float32Array} */ storageFloat32; /** @type {Int32Array} */ storageInt32; /** * A render version used to track the last time the properties requiring bind group to be * updated were changed. * * @type {number} */ renderVersionDirty = 0; /** * Create a new UniformBuffer instance. * * @param {import('./graphics-device.js').GraphicsDevice} graphicsDevice - The graphics device * used to manage this uniform buffer. * @param {import('./uniform-buffer-format.js').UniformBufferFormat} format - Format of the * uniform buffer. * @param {boolean} [persistent] - Whether the buffer is persistent. Defaults to true. */ constructor(graphicsDevice, format, persistent = true) { this.device = graphicsDevice; this.format = format; this.persistent = persistent; Debug.assert(format); if (persistent) { this.impl = graphicsDevice.createUniformBufferImpl(this); const storage = new ArrayBuffer(format.byteSize); this.assignStorage(new Int32Array(storage)); graphicsDevice._vram.ub += this.format.byteSize; // TODO: register with the device and handle lost context // this.device.buffers.push(this); } else { this.allocation = new DynamicBufferAllocation(); } } /** * Frees resources associated with this uniform buffer. */ destroy() { if (this.persistent) { // stop tracking the vertex buffer // TODO: remove the buffer from the list on the device (lost context handling) const device = this.device; this.impl.destroy(device); device._vram.ub -= this.format.byteSize; } } get offset() { return this.persistent ? 0 : this.allocation.offset; } /** * Assign a storage to this uniform buffer. * * @param {Int32Array} storage - The storage to assign to this uniform buffer. */ assignStorage(storage) { this.storageInt32 = storage; this.storageFloat32 = new Float32Array(storage.buffer, storage.byteOffset, storage.byteLength / 4); } /** * Called when the rendering context was lost. It releases all context related resources. * * @ignore */ loseContext() { this.impl?.loseContext(); } /** * Assign a value to the uniform specified by its format. This is the fast version of assigning * a value to a uniform, avoiding any lookups. * * @param {import('./uniform-buffer-format.js').UniformFormat} uniformFormat - The format of * the uniform. */ setUniform(uniformFormat) { Debug.assert(uniformFormat); const offset = uniformFormat.offset; const value = uniformFormat.scopeId.value; if (value !== null && value !== undefined) { const updateFunction = _updateFunctions[uniformFormat.updateType]; if (updateFunction) { updateFunction(this, value, offset, uniformFormat.count); } else { this.storageFloat32.set(value, offset); } } else { Debug.warnOnce(`Value was not set when assigning to uniform [${uniformFormat.name}]` + `, expected type ${uniformTypeToName[uniformFormat.type]}`); } } /** * Assign a value to the uniform specified by name. * * @param {string} name - The name of the uniform. */ set(name) { const uniformFormat = this.format.map.get(name); Debug.assert(uniformFormat, `Uniform name [${name}] is not part of the Uniform buffer.`); if (uniformFormat) { this.setUniform(uniformFormat); } } update() { const persistent = this.persistent; if (!persistent) { // allocate memory from dynamic buffer for this frame const allocation = this.allocation; const oldGpuBuffer = allocation.gpuBuffer; this.device.dynamicBuffers.alloc(allocation, this.format.byteSize); this.assignStorage(allocation.storage); // buffer has changed, update the render version to force bind group to be updated if (oldGpuBuffer !== allocation.gpuBuffer) { this.renderVersionDirty = this.device.renderVersion; } } // set new values const uniforms = this.format.uniforms; for (let i = 0; i < uniforms.length; i++) { this.setUniform(uniforms[i]); } if (persistent) { // Upload the new data this.impl.unlock(this); } else { this.storageFloat32 = null; this.storageInt32 = null; } } } export { UniformBuffer };
import types from './types'; import axios from 'axios'; export function authCheck(){ const response = axios.get('/api/auth/check'); return{ type: types.AUTH_CHECK, payload: response, }; }; export function getProfileData(){ const response = axios.get('/api/profile/data'); return{ type: types.GET_PROFILE, payload: response } } export function signOut(){ const response = axios.get('/api/auth/logout'); return{ type: types.SIGN_OUT, payload: response } } export function register_customer_choice(){ const response = { accountChoice: "customer", step: 2 } return{ type: types.REGISTER_CUSTOMER_CHOICE, payload: response } } export function register_worker_choice(){ const response = { accountChoice: "worker", step: 2 } return{ type: types.REGISTER_WORKER_CHOICE, payload: response } } export function toggleOn_view_applicants(){ const response = { view: true } return{ type: types.VIEW_APPLICANTS, payload: response, } } export function toggleOff_view_applicants(){ const response = { view: false } return{ type: types.VIEW_APPLICANTS, payload: response, } }