max_stars_repo_path
stringlengths
3
961
max_stars_repo_name
stringlengths
5
122
max_stars_count
int64
0
224k
id
stringlengths
1
8
content
stringlengths
2
1.07M
score
float64
-0.95
3.88
int_score
int64
0
4
doczrc.js
ricsam/react-mixitup
2
15995548
export default { files: 'documentation/*.{md,markdown,mdx}', ignore: ['readme.md', 'changelog.md', 'code-of-conduct.md', 'contributing.md', 'license.md'], dest: 'docs/docs', base: '/docs' };
0.265625
0
src/shared/game-rules.js
igotlegs/skipbo
0
15995556
const GameRules = { MIN_PLAYERS: 2, MAX_PLAYERS: 4, MIN_PLAYER_NAME_LENGTH: 3, PLAYER_DECK_SIZE: 25, PLAYER_HAND_SIZE: 5, } export default GameRules
0.652344
1
main/src/wiki-templates/#if.js
ghbjklhv/Kiwipedia
11
15995564
export default { name: "#if", async render(params, renderer) { return await renderer( "if", { 1: "", 2: params[1], 3: params[2], 4: params[3] } ); } };
0.605469
1
public/js.js
HurriAchmad/ultimatum
0
15995572
var ikon = document.getElementById("ikon"); ikon.onclick = function(){ document.body.classList.toggle("light-theme"); if (document.body.classList.contains("light-theme")){ document.getElementById("gambar").style.backgroundImage="url(backlight.jpg)"; ikon.src = "images/moon.png"; console.log('Jadi terang') }else{ document.getElementById("gambar").style.backgroundImage="url(background.jpg)"; ikon.src = "images/sun.png"; console.log('Jadi gelap') } } // Click on a close button to hide the current list item var close = document.getElementsByClassName("close"); var i; for (i = 0; i < close.length; i++) { close[i].onclick = function() { var div = this.parentElement; div.style.display = "none"; } } // Create a new list item when clicking on the "Add" button function newElement() { var li = document.createElement("li"); var inputValue = document.getElementById("myInput").value; var t = document.createTextNode(inputValue); li.appendChild(t); if (inputValue === '') { alert("You must write something!"); } else { document.getElementById("myUL").appendChild(li); } document.getElementById("myInput").value = ""; var span = document.createElement("SPAN"); var txt = document.createTextNode("\u00D7"); span.className = "close"; span.appendChild(txt); li.appendChild(span); for (i = 0; i < close.length; i++) { close[i].onclick = function() { var div = this.parentElement; div.style.display = "none"; } } }
1.914063
2
src/components/Logo/Logo.js
Konovalenko19/react-chat
0
15995580
import React from "react"; import "./Logo.scss"; const Logo = props => { const { withIcon = false, } = props; return ( <div className="Logo"> {withIcon && <div className="Logo__Icon"> <svg viewBox="0 0 30 42"> <path d="M15 3 Q16.5 6.8 25 18 A12.8 12.8 0 1 1 5 18 Q13.5 6.8 15 3z" /> </svg> </div> } <div className="Logo__Text">waterChat</div> </div> ); }; export default Logo;
1.054688
1
index.js
omar2535/vuepress-sidebar-children-autogenerator
2
15995588
var path = require('path') const fs = require('fs'); function generateSidebarContents(dirPath, children, collapsable, filesToExclude, directoriesToExclude) { fs.readdirSync(dirPath, { withFileTypes: true }).forEach(file => { let fullPath = `${dirPath}${file.name}/`; if (file.isDirectory()) { if (!directoriesToExclude.includes(file.name)) { let dirChildren = generateSidebarContents(fullPath, [], collapsable, filesToExclude, directoriesToExclude); children.push({ title: file.name, path: fullPath.substr(1), collapsable: collapsable, children: dirChildren }); } } else { if (path.extname(file.name) === ".md" && !filesToExclude.includes(file.name.toLowerCase()) && !filesToExclude.includes(file.name)) { children.push(fullPath.slice(1, -1)); } } }); return children; } /** * Find all markdown files with path and creates a children object for the sidebar * @param {string} basePath the base path to the directory with children from the project's root. Example: ./notes/ * @param {boolean} [collapsable=true] whether or not this sidebars children will be collapsable. Defaults to true * @param {string[]} [filesToExclude=["readme.md"]] exact file names to exclude as an array, defaults to ['readme.md'] * @param {string[]} [directoriesToExclude] the directories that should not be added to children, * defaults to ['.vuepress', 'node_modules', '.git'] * @returns {object[]} children as an array */ function generateChildren(basePath, collapsable, filesToExclude, directoriesToExclude) { if (!basePath.startsWith(".")) basePath = `.${basePath}`; if (!basePath.endsWith('/')) basePath = `${basePath}/` return generateSidebarContents(basePath, [], collapsable || true, filesToExclude || ['readme.md'], directoriesToExclude || ['.vuepress', 'node_modules', '.git']); } module.exports = generateChildren;
1.664063
2
src/pages/index.js
jevdjauon/gatsby-tut
0
15995596
import React from "react" import { graphql } from "gatsby" import Header from "../components/Header" import Main from "../layouts/Main" const IndexPage = ({ data }) => { const meta = data.site.siteMetadata return ( <Main> <h1>{meta.title}</h1> <p>{meta.description}</p> <p>{meta.author}</p> <div style={{ height: "600px" }}> <p> Lorem ipsum dolor sit amet consectetur adipisicing elit. Veritatis, ullam inventore placeat debitis illum quaerat culpa suscipit vero, aspernatur ea reprehenderit minus tempora. Delectus aperiam earum quaerat, provident beatae aliquid! </p> </div> </Main> ) } export const query = graphql` { site { siteMetadata { title description author } } } ` export default IndexPage
1.15625
1
lib/routePaths.js
khietvo-agilityio/sapphire-express
0
15995604
var path = require('path'); var fs = require('fs'); function unDos(filepath) { filepath = path.resolve(filepath); if (filepath.indexOf(':') == 1) { filepath = filepath.slice(2); } filepath = filepath.replace(/\\/g, '/'); return filepath; } var thisDir = CONFIG.basePath; var mainAssets = CONFIG.sapphireRoot + '/../public'; exports.urlPathToFilePath = function(which) { var relative = which.indexOf(root) != 0; var paths = which.split('/'); paths.shift(); // console.log('urlPathToFilePath', which, paths) if (paths[0] == 'assets') { return mainAssets + '/' + paths.join('/'); } else { return CONFIG.basePath + '/apps/' + paths.join('/'); return result; } }
1.132813
1
src/routes/index.js
Zoharos/openshift-api
0
15995612
const asyncHandler = require('express-async-handler'); const util = require('util'); const exec = util.promisify(require('child_process').exec); const express = require('express'); const router = express.Router(); router.use(express.json()); router.post('/new', asyncHandler(async (req, res, next) => { const { stdout, stderr } = await exec('oc new-project zohar'); stderr ? res.status(400).send('stderr: ' + stderr) : res.status(200).send('stdout: ' + stdout); })); router.post('/delete', asyncHandler(async (req, res, next) => { const { stdout, stderr } = await exec('oc delete project zohar'); stderr ? res.status(400).send('stderr: ' + stderr) : res.status(200).send('stdout: ' + stdout); })); router.post('/login', asyncHandler(async (req, res, next) => { const { stdout, stderr } = await exec('oc login ' + process.env.OPENSHIFT_URL + ' --token=' + req.body.token); stderr ? res.status(400).send('stderr: ' + stderr) : res.status(200).send('stdout: ' + stdout); })); module.exports = router; // 0523074799 // oc login https://api.starter-us-east-1.openshift.com --token=<KEY>
1.140625
1
front/__tests__/factories/Event.js
shinosakarb/Tebukuro
50
15995620
export default { event1 : { id: 1, communityId: 1, name: 'event1', eventStartsAt: '2017-03-04T13:00:00.000Z', eventEndsAt: '2017-03-04T17:00:00.000Z', description: 'This is the first event.', address: 'address1' }, event2 : { id: 2, communityId: 1, name: 'event2', eventStartsAt: '2017-12-11T09:00:00.000Z', eventEndsAt: '2017-12-15T20:00:00.000Z', description: 'This is the second event.', address: 'address2' } }
0.5625
1
packages/puppeteer-extra-plugin-repl/lib/super-readline.js
victornpb/puppeteer-extra
3,789
15995628
const chalk = require('chalk') const { Interface, clearLine, clearScreenDown, cursorTo, emitKeypressEvents, moveCursor } = require('readline') /** * Extends the native readline interface with color support. * * A drop-in replacement for `readline`. * * Additionally accepts an options.color object with chalk colors * for `prompt` and `completer`. * * @todo this could be enhanced with auto complete hints in grey. * @todo similar to this: https://github.com/aantthony/node-color-readline * * @ignore * * @example * const readline = require('./super-readline') * * const rl = readline.createInterface({ * input: process.stdin, * output: process.stdout, * prompt: '> ', * completer: readline.defaultCompleter([ 'bob', 'yolk' ]), * colors: { * prompt: readline.chalk.cyan, * completer: readline.chalk.yellow * } * }) * * rl.prompt() */ class SuperInterface extends Interface { constructor(options) { super(options) this._colors = options.colors || {} this._writingTabComplete = false } _tabComplete(lastKeypressWasTab) { this._writingTabComplete = true super._tabComplete(lastKeypressWasTab) this._writingTabComplete = false } showTabCompletions() { this._tabComplete(true) } _writeToOutput(stringToWrite) { // colorize prompt itself const startsWithPrompt = stringToWrite.startsWith(this._prompt) if (this._colors.prompt && startsWithPrompt) { stringToWrite = `${this._colors.prompt( this._prompt )}${stringToWrite.replace(this._prompt, '')}` return super._writeToOutput(stringToWrite) } // colorize completer output if (this._colors.completer && this._writingTabComplete) { return super._writeToOutput(this._colors.completer(stringToWrite)) } // anything else super._writeToOutput(stringToWrite) } } const createSuperInterface = function(options) { return new SuperInterface(options) } /** * A typical default completer that can be used, for convenience. * * @ignore */ const defaultCompleter = completions => line => { const hits = completions.filter(c => c.startsWith(line)) // show all completions if none found const arr = hits.length ? hits : completions return [arr, line] } module.exports = { // customized exports: chalk, Interface: SuperInterface, createInterface: createSuperInterface, defaultCompleter, // default readline exports: clearLine, clearScreenDown, cursorTo, emitKeypressEvents, moveCursor }
1.523438
2
www/js/app.js
redheli/ionic_map
0
15995636
// Ionic Starter App // angular.module is a global place for creating, registering and retrieving Angular modules // 'starter' is the name of this angular module example (also set in a <body> attribute in index.html) // the 2nd parameter is an array of 'requires' angular.module('starter', ['ionic']) angular.module('starter', ['ionic', 'ngCordova']) .run(function($ionicPlatform) { $ionicPlatform.ready(function() { if(window.cordova && window.cordova.plugins.Keyboard) { // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard // for form inputs) cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); // Don't remove this line unless you know what you are doing. It stops the viewport // from snapping when text inputs are focused. Ionic handles this internally for // a much nicer keyboard experience. cordova.plugins.Keyboard.disableScroll(true); } if(window.StatusBar) { StatusBar.styleDefault(); } }); }) .config(function($stateProvider, $urlRouterProvider) { $stateProvider .state('map', { url: '/', templateUrl: 'templates/map.html', controller: 'MapCtrl' }); $urlRouterProvider.otherwise("/"); }) .controller('MapCtrl', function($scope, $state, $cordovaGeolocation) { $scope.$on("$stateChangeSuccess", function() { var mainMarker = { lat: 20.6219444444, lng: -105.228333333, focus: true, message: "<NAME>, MX", draggable: false}; $scope.map = { defaults: { tileLayer: 'http://{s}.tile.osm.org/{z}/{x}/{y}.png', maxZoom: 18, zoomControlPosition: 'bottomleft'}, center: { lat : 20.6219444444, lng : -105.228333333, zoom : 15}, markers: { mainMarker: angular.copy(mainMarker)} }; }); var options = {timeout: 10000, enableHighAccuracy: true}; $cordovaGeolocation.getCurrentPosition(options).then(function(position){ var init_lat = 1.3552799//42.299228067198634; var init_lng = 103.6945413;//-83.69717033229782; var mymap = L.map('map').setView([init_lat,init_lng], 15); $scope.map = mymap; mymap.options.maxZoom = 22; var osm = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'); var ggl = new L.Google(); var ggl2 = new L.Google('TERRAIN'); mymap.addLayer(ggl); var id_=0; // add pbf layer //Highly experimental Mapnik Vector Tiles PBFLayer var pbfSource = new L.TileLayer.PBFSource({ url: 'http://localhost:3001/services/postgis/cleantech/geom/vector-tiles/{z}/{x}/{y}.pbf?fields=name', debug: false, maxZoom: 22, minZoom: 6, clickableLayers: [], getIDForLayerFeature: function(feature) { //console.log('r '+feature.properties.r); //console.log('name '+feature.properties.name); return feature.properties.name;//feature.coordinates[0][0].x; }, /** * The filter function gets called when iterating though each vector tile feature (vtf). You have access * to every property associated with a given feature (the feature, and the layer). You can also filter * based of the context (each tile that the feature is drawn onto). * * Returning false skips over the feature and it is not drawn. * * @param feature * @returns {boolean} */ filter: function(feature, context) { return true; } }); //Globals that we can change later. var fillColor = 'rgba(200,200,200,0.4)'; var strokeColor = 'rgb(20,20,20)'; pbfSource.styleFor = pbfStyle; pbfSource.maxZoom = 22; function pbfStyle(feature) { var style = {}; var type = feature.type; //console.log(feature.properties); switch (type) { case 1: //'Point' r = feature.properties.name; //console.log(r); style.color = 'rgba(' + r +',' + r + ','+r+',1)'; // if(r<150){ // style.color = 'rgba(0,255,0,0.5)'; // } // if(r>150){ // style.color = 'rgba(255,255,0,0.5)'; // } // if(mymap.getZoom()>18){ // style.radius = 20; // } // else // { // style.radius = 0.5; // } } return style; } var style = { "version": 8, "sources": { "countries": { "type": "vector", "tiles": ["http://localhost:3001/services/postgis/cleantech2/geom/vector-tiles/{z}/{x}/{y}.pbf"], "maxzoom": 22 } }, "layers": [{ "id": "mcity_ped_crossing1", "type": "fill", "source": "countries", "source-layer": "Ken_CountyWithWater", "paint": { "fill-color": "#00ff00", "fill-opacity":0.5 } },{ "id": "mcity_ped_crossing2", "type": "fill", "source": "countries", "filter":["in","COUNTY",'Baringo','ASM','ATF','BD'], "source-layer": "Ken_CountyWithWater", "paint": { "fill-color": "#ffff00", "fill-opacity":0.5 } }] }; //Add layer // mymap.addLayer(pbfSource); mymap.on('zoomend', function() { console.log('zoom'+mymap.getZoom()) }); ////// var mvtSource = new L.TileLayer.MVTSource({ url: "http://192.168.1.111:3001/services/postgis/cleantech/geom/vector-tiles/{z}/{x}/{y}.pbf?fields=name", debug: false, clickableLayers: [], maxZoom: 22, minZoom: 6, getIDForLayerFeature: function(feature) { return "";//feature.properties.name;//feature.properties.id; }, /** * The filter function gets called when iterating though each vector tile feature (vtf). You have access * to every property associated with a given feature (the feature, and the layer). You can also filter * based of the context (each tile that the feature is drawn onto). * * Returning false skips over the feature and it is not drawn. * * @param feature * @returns {boolean} */ filter: function(feature, context) { // if (feature.layer.name === 'GAUL0') { return true; // } // return false; }, style: function (feature) { var style = {}; var type = feature.type; switch (type) { case 1: //'Point' style.color = 'rgba(49,79,79,1)'; style.radius = 0.5; style.selected = { color: 'rgba(255,255,0,0.5)', radius: 6 }; break; case 2: //'LineString' style.color = 'rgba(161,217,155,0.8)'; style.size = 3; style.selected = { color: 'rgba(255,25,0,0.5)', size: 4 }; break; case 3: //'Polygon' style.color = fillColor; style.outline = { color: strokeColor, size: 1 }; style.selected = { color: 'rgba(255,140,0,0.3)', outline: { color: 'rgba(255,140,0,1)', size: 2 } }; break; } return style; } }); //Add layer mymap.addLayer(mvtSource); ////// var ACCESS_TOKEN = '<KEY>'; /*var gl = L.mapboxGL({ accessToken: ACCESS_TOKEN, style: style }).addTo(mymap); */ osm.maxZoom = 22; ggl.maxZoom = 22; ggl2.maxZoom = 22; mymap.addControl(new L.Control.Layers( {'OSM':osm, 'Google':ggl, 'Google Terrain':ggl2,'cleantech':pbfSource}, {})); }, function(error){ console.log("Could not get location"); }); });
1.4375
1
src/components/linkedin/plain-wordmark/index.js
fpoumian/react-devicon
25
15995644
export { default } from './LinkedinPlainWordmark'
-0.332031
0
src/components/home-components/Home-tesimonials/Home-tesimonials.component.js
shohruzjon-tech/powerpatent
0
15995652
import React from 'react'; import { TestimonialsContainer , TestimonialHeadContainer, TestimonialHeaderBox, TestimonialHeaderTitle, TestimonialCarouselContainer, HeroTextContainer, CarouselSection, CarouselImage, CarouselImageBox } from './Home-tesimonials.styles'; import "slick-carousel/slick/slick.css"; import "slick-carousel/slick/slick-theme.css"; import Slider from "react-slick"; const HomeTestimonials=()=>{ const settings = { className: "center", autoplaySpeed: 1000, dots: true, centerMode: true, infinite: true, centerPadding: "60px", slidesToShow: 4, speed: 500, swipeToSlide: true, autoplay:true, touchMove:true, focusOnSelect:true, responsive: [ { breakpoint: 1000, settings: { slidesToShow: 2, slidesToScroll: 1, infinite: true, dots: true, }, }, { breakpoint: 600, settings: { slidesToShow: 1, slidesToScroll: 1, }, }, ], }; return( <TestimonialsContainer> <TestimonialHeadContainer> <TestimonialHeaderBox></TestimonialHeaderBox> <TestimonialHeaderTitle>TRUSTED BY:</TestimonialHeaderTitle> <TestimonialHeaderBox></TestimonialHeaderBox> </TestimonialHeadContainer> <TestimonialCarouselContainer> <Slider {...settings}> <CarouselSection> <CarouselImageBox> <CarouselImage src='https://firebasestorage.googleapis.com/v0/b/my-test-8f997.appspot.com/o/Picture10.png?alt=media&token=<PASSWORD>' /> </CarouselImageBox> </CarouselSection> <CarouselSection> <CarouselImageBox> <CarouselImage src='https://firebasestorage.googleapis.com/v0/b/my-test-8f997.appspot.com/o/Picture11.png?alt=media&token=<PASSWORD>' /> </CarouselImageBox> </CarouselSection> <CarouselSection> <CarouselImageBox> <CarouselImage src='https://firebasestorage.googleapis.com/v0/b/my-test-8f997.appspot.com/o/Picture2.png?alt=media&token=<PASSWORD>' /> </CarouselImageBox> </CarouselSection> <CarouselSection> <CarouselImageBox> <CarouselImage src='https://firebasestorage.googleapis.com/v0/b/my-test-8f997.appspot.com/o/Picture3.png?alt=media&token=<PASSWORD>' /> </CarouselImageBox> </CarouselSection> <CarouselSection> <CarouselImageBox> <CarouselImage src='https://firebasestorage.googleapis.com/v0/b/my-test-8f997.appspot.com/o/Picture4.png?alt=media&token=<PASSWORD>' /> </CarouselImageBox> </CarouselSection> <CarouselSection> <CarouselImageBox> <CarouselImage src='https://firebasestorage.googleapis.com/v0/b/my-test-8f997.appspot.com/o/Picture5.png?alt=media&token=<PASSWORD>' /> </CarouselImageBox> </CarouselSection> <CarouselSection> <CarouselImageBox> <CarouselImage src='https://firebasestorage.googleapis.com/v0/b/my-test-8f997.appspot.com/o/Picture6.png?alt=media&token=<PASSWORD>' /> </CarouselImageBox> </CarouselSection> <CarouselSection> <CarouselImageBox> <CarouselImage src='https://firebasestorage.googleapis.com/v0/b/my-test-8f997.appspot.com/o/Picture7.png?alt=media&token=<PASSWORD>' /> </CarouselImageBox> </CarouselSection> <CarouselSection> <CarouselImageBox> <CarouselImage src='https://firebasestorage.googleapis.com/v0/b/my-test-8f997.appspot.com/o/Picture8.png?alt=media&token=<PASSWORD>' /> </CarouselImageBox> </CarouselSection> <CarouselSection> <CarouselImageBox> <CarouselImage src='https://firebasestorage.googleapis.com/v0/b/my-test-8f997.appspot.com/o/Picture9.png?alt=media&token=<PASSWORD>' /> </CarouselImageBox> </CarouselSection> </Slider> </TestimonialCarouselContainer> </TestimonialsContainer> ) }; export default HomeTestimonials;
1.335938
1
src/errors/gone-error.js
uphold/http-errors
0
15995660
'use strict'; /** * Module dependencies. */ const HttpError = require('./http-error'); /** * Export "Gone" error. */ module.exports = class GoneError extends HttpError { /** * Constructor. */ constructor() { super(410, ...arguments); } };
0.785156
1
index.js
felipesantosds/crud-mynodejsql
0
15995668
// Importação da constante server. const { server } = require("./src/endpoints/routes/routes"); // Roda o servidor na porta 3000 do localhost. server.listen(3000, () => { // Informa que o servidor está rodando (e onde). console.log("Server started on http://localhost:3000"); // Testa a conexão com o banco. });
1.289063
1
src/v1.0.0/src/router/RESTfulStyle.js
fsjohnhuang/lpp
0
15995676
define(function(require, exports, module){ var _utils = {}; _utils.str = require('../Str'); _utils.array = require('../Array'); _utils.isRegExp = function(el){ return Object.prototype.toString.apply(el) === '[object RegExp]'; }; /** 浅对象复制 * @param {Object} obj * @returns {Object} */ var _clone = function(obj){ var copy = {}; for(p in obj){ copy[p] = obj[p]; } return copy; }; /** 将key解析为由id和paramNames组成的对象 * @param {String} key, 形如Index.aspx?id=1&Type=2 * @returns {Object}, 形如{id: 'index.aspx', paramNames: ['id', 'Type']} */ exports.parseMapKey2Entry = function (key){ var paramNames = [], id = '' , keyLastIdx = key.length - 1 , match = /^(\/?\w+?[^$/{}]*(?:\/\w+?[^$/{}]*)*)(\/\$\{.*)?$/.exec(key.lastIndexOf('/') === keyLastIdx ? key.substring(0, keyLastIdx) : key); if (match && match.length === 3) { id = match[1]; if (typeof (match[2]) != 'undefined'){ var paramVars = match[2].split('/'); var paraVal, paramMatch; for (var i = 0, len = paramVars.length; i < len; i++) { paramVal = paramVars[i]; paramMatch = /^\s*\$\{\s*(\S+)\s*\}\s*$/.exec(paramVal); if (paramMatch && paramMatch.length){ paramNames.push(paramMatch[1]); } } } } return { id: id, paramNames: paramNames }; }; /** 解析当前URL并获取匹配的路由回调函数集合 * @param {String} fragment * @param {Object} routes, 路由信息对象,内含strRoutes和regExpRoutes两个路由信息集合 * @param {Boolean} isSingleMatch, 是否单匹配模式 * @returns {Array} 路由回调函数集合 */ exports.parseCurURL2Funcs = function(fragment, routes, isSingleMatch){ fragment = _utils.str.trim(fragment); var strRoutes = _utils.array.grep(routes.strRoutes, function(el){ var idx = fragment.indexOf(el.id); return idx === 0 && (el.id.length === fragment.length || fragment.substr(el.id.length, 1) === '/'); }); var regExpRoutes = _utils.array.grep(routes.regExpRoutes, function(el){ var idx = fragment.indexOf(el.id); return idx === 0 && (el.id.length === fragment.length || fragment.substr(el.id.length, 1) === '/'); }); var tmpMatchRoutes = []; for (var i = 0, len = strRoutes.length; i < len; i++) { strRoutes[i].type = 1; tmpMatchRoutes.push(strRoutes[i]); }; for (var i = 0, len = regExpRoutes.length; i < len; i++) { regExpRoutes[i].type = 0; tmpMatchRoutes.push(regExpRoutes[i]); }; tmpMatchRoutes.sort(function(a, b){ return b.id.length - a.id.length; }); var curUrl = { protocol: location.protocol.toLocaleLowerCase(), host: location.host.toLocaleLowerCase(), port: location.port.toLocaleLowerCase(), pathname: location.pathname.toLocaleLowerCase() }; var matchRoutes = [], tmpMatchRoute, props = ['protocol', 'host', 'port', 'pathname'], pass = false; for (var i = 0, len = tmpMatchRoutes.length; i < len && (isSingleMatch && !matchRoutes.length || !isSingleMatch); i++) { tmpMatchRoute = tmpMatchRoutes[i]; if (tmpMatchRoute.type){ // 全字符串形式的路径信息 pass = _utils.array.all(props, function(el){ return tmpMatchRoute[el] === '' && true || curUrl[el] === tmpMatchRoute[el]; }); if (pass){ delete tmpMatchRoute.type; matchRoutes.push(tmpMatchRoute); } } else{ // 含正则表达式形式的路径信息 pass = _utils.array.all(props, function(el){ if (_utils.isRegExp(tmpMatchRoute[el])){ return tmpMatchRoute[el].test(curUrl[el]); } else{ return tmpMatchRoute[el] === '' && true || curUrl[el] === tmpMatchRoute[el]; } }); if (pass){ delete tmpMatchRoute.type; matchRoutes.push(tmpMatchRoute); } } } // 组装路径回调函数 var funcs = []; for (var i = 0, len = matchRoutes.length; i < len; i++) { var matchRoute = matchRoutes[i]; var params = {}; var index = fragment.indexOf(matchRoute.id); var queryString = fragment.substring(index + matchRoute.id.length); var vals = []; if (queryString.length > 1){ queryString = queryString.substring(1); vals = queryString.split('/'); if (vals.length === 2 && vals[1] === ''){ vals.length = 1; } } for (var j = 0, jLen = matchRoute.paramNames.length; j < jLen; j++) { var paramName = matchRoute.paramNames[j]; var val = vals[j]; params[paramName] = val && decodeURI(val) || val; }; funcs.push({ action: matchRoute.action, params: params }); } return funcs; }; /** 将id和params序列化为fragment * @param {String} id * @param {Object} params * @param {Object} 路由信息容器 * @returns {String} */ exports.stringify2Fragment = function(id, params, routes){ var route; for (var i = 0, len = routes.strRoutes.length; i < len && !route; i++) { if (routes.strRoutes[i].id === id){ route = routes.strRoutes[i]; } } for (var i = 0, len = routes.regExpRoutes.length; i < len && !route; i++) { if (routes.regExpRoutes[i].id === id){ route = routes.regExpRoutes[i]; } } if (!route){ return location.hash; } var vals = []; for (var i = 0, len = route.paramNames.length; i < len; i++) { var paramName = route.paramNames[i]; var val = null; for(var prop in params){ if (prop === paramName) { val = params[prop]; break; } } if (val === null) break; vals.push(val); }; var rs = id + (id.substring(id.length - 1) === '/' ? '' : '/') + _utils.array.map(vals, function(el){ return encodeURI(el);}).join('/'); return rs; }; });
1.335938
1
src/locales/en_GB.js
AmadeusITGroup/Interactive-Video-Player
0
15995684
(function(root, factory) { if (typeof define === "function" && define.amd) { // AMD. Register as an anonymous module. define(["riot-i18n"], function(i18n) { factory(i18n); }); } else if (typeof exports === "object") { // CommonJS factory(require("riot-i18n")); } else { // Browser globals factory(root.i18n); } })(this, function(i18n) { "use strict"; i18n._entities["en_GB"] = i18n._entities["en"] = { format: { month: { short: "MM YYYY", full: "MMMM YYYY" }, date: { short: "DD MM YYYY" }, currency: "{symbol}{value}" }, currency: { code: "GBP", symbol: "£" }, template: { label: { average: "Average cost of vacation in", from: "From", perperson: "Round trip / person", roundtrip_from: "Round trip / person from", average_cost_from: "Average daily cost from", pernight: "Price / night", to: "to", availability: "Check availability", dailycost: "Average daily cost / person incl Hotel in", viewmore: "View more on BudgetYourTrip", notspecified: "Not specified", bestoffer: "Best Offer", inclflight: "incl. flights and hotels", address: "Address", rating: "Rating", contactinfo: "Contact information", livedata: "Live data available at runtime", notips: "Tips will be visible here once filled ", notitle: "Title", pricenotfound: "Price not found" }, button: { booknow: "Book now", getthere: "Get there", checkavailability: "Check availability", contactus: "Contact us" }, error: { localisation: "Please enable localisation on your browser to view this section", pricenotfound: "Price not found" } }, header: { label: { current: "You are now visiting:" } }, player: { label: { towishlist: " has been added to your wish list", fromwishlist: " has been removed from your wish list" }, error: { support: "To view this video please enable JavaScript, and consider upgrading to a web browser that supports HTML5 video", cookies:"Please enable third party cookies in your browser to watch this video", "360Unavailable": "360 Video unavailable", unsupportedBrowser: "This video can't play in this browser", unsupportedVideo : "This video could not be loaded, either because the server or network failed or because of some plugins (e.g Ghostery)" } }, requirements: { label: { resolutiontoosmall: "Video's resolution is too small for an optimal experience.", leavepage: "Would you like to watch the video in a dedicated page?" }, button: { takemethere: "Yes, take me there", stayhere: "No, stay here" } } }; });
1.460938
1
framework/PVRUtils/docs/html/search/files_8.js
powervr-graphics/Native_SDK
559
15995692
var searchData= [ ['shaderutilsgles_2ecpp_803',['ShaderUtilsGles.cpp',['../_shader_utils_gles_8cpp.html',1,'']]], ['shaderutilsgles_2eh_804',['ShaderUtilsGles.h',['../_shader_utils_gles_8h.html',1,'']]], ['shaderutilsvk_2ecpp_805',['ShaderUtilsVk.cpp',['../_shader_utils_vk_8cpp.html',1,'']]], ['shaderutilsvk_2eh_806',['ShaderUtilsVk.h',['../_shader_utils_vk_8h.html',1,'']]], ['spritegles_2ecpp_807',['SpriteGles.cpp',['../_sprite_gles_8cpp.html',1,'']]], ['spritegles_2eh_808',['SpriteGles.h',['../_sprite_gles_8h.html',1,'']]], ['spritevk_2ecpp_809',['SpriteVk.cpp',['../_sprite_vk_8cpp.html',1,'']]], ['spritevk_2eh_810',['SpriteVk.h',['../_sprite_vk_8h.html',1,'']]], ['structuredmemory_2eh_811',['StructuredMemory.h',['../_structured_memory_8h.html',1,'']]] ];
0.449219
0
tests/xlsx-test.js
letsface/dpd-excel
0
15995700
var utils = require('../utils.js'); var XLSX = require('xlsx'); var assert = require('assert'); describe('XLSX to JSON', function() { it('convert test file test.xlsx', function() { var xlsx = XLSX.readFile(__dirname + '/test.xlsx'); var sheet_name_list = xlsx.SheetNames; var output = utils.sheet_to_row_object_array(xlsx.Sheets[sheet_name_list[0]]); assert.equal(output.length, 17); assert.equal(output[0]["Email Address"], "<EMAIL>"); assert.equal(output[0]["Given name"], "Andrea"); assert.equal(output[0]["Family name"], "Bergheim"); assert.equal(output[0]["Type"], "Pro-Am Day 1"); }); });
1.296875
1
src/Tokenizer.Context.test.js
apendua/any-language
1
15995708
/* eslint-env mocha */ /* eslint no-unused-expressions: "off" */ /* eslint prefer-arrow-callback: "off" */ import chai from 'chai'; import Context from './Tokenizer.Context.js'; chai.should(); describe('Test Tokenizer.Context', () => { describe('Given "abc" string', () => { beforeEach(function () { this.context = new Context('abc', 0, { lineNo: 1 }); }); describe('after first advance()', () => { beforeEach(function () { this.character = this.context.advance(); }); it('the returned value should be "a"', function () { this.character.should.equal('a'); }); it('get() should return current state', function () { this.context.get().should.deep.equal({ index: 0, value: '', ahead: 'b', state: {}, }); }); it('wrap() should return current position', function () { this.context.wrap({}).should.deep.equal({ from: 0, to: -1, line: 1, }); }); }); describe('after second advance()', () => { beforeEach(function () { this.context.advance(); this.character = this.context.advance(); }); it('the returned value should be "b"', function () { this.character.should.equal('b'); }); it('get() should return current state', function () { this.context.get().should.deep.equal({ index: 1, value: 'a', ahead: 'c', state: {}, }); }); it('wrap() should return current position', function () { this.context.wrap({}).should.deep.equal({ from: 0, to: 0, line: 1, }); }); }); describe('after third advance()', () => { beforeEach(function () { this.context.advance(); this.context.advance(); this.character = this.context.advance(); }); it('the returned value should be "c"', function () { this.character.should.equal('c'); }); it('get() should return current state', function () { this.context.get().should.deep.equal({ index: 2, value: 'ab', ahead: '', state: {}, }); }); it('wrap() should return current position', function () { this.context.wrap({}).should.deep.equal({ from: 0, to: 1, line: 1, }); }); }); }); });
1.703125
2
src/components/data/FetchItemDesc.js
inderpreet/learning-react-material-sense
0
15995716
export default function FetchItemDesc() { return [ { _id: 1, modelcode: "RVR303 Combo", modelcodetext: "RVR303 Restraint and Blue Genius Controls", desc: "<h2>Standard Features</h2><ul><li>1</li></ul>", brand: "Blue Giant", model: "RVR303 & Blue Genius III Gold Series", capacity: "35,000lb restraing strength", }, { _id: 2, modelcode: "HVR Combo", modelcodetext: "HVR Restraint and Blue Genius Controls", desc: "<h2>Standard Features</h2><ul><li>1</li></ul>", brand: "Blue Giant", model: "HVR & Blue Genius III Gold Series", capacity: "35,000lb restraing strength", }, { _id: 3, modelcode: "Dummy Combo", modelcodetext: "Noose Restraint and Blue Genius Controls", desc: "<h2>Standard Features</h2><ul><li>1</li></ul>", brand: "Blue Giant", model: "Noose & Blue Genius III Gold Series", capacity: "35,000lb restraing strength", }, ]; }
0.660156
1
resources/js/app.js
nhamtphat/bookworm
1
15995724
import React from 'react' import ReactDOM from 'react-dom' import Router from './router' import { Provider } from 'react-redux' import { PersistGate } from 'redux-persist/integration/react' import { store, persistor } from './_store' ReactDOM.render( <Provider store={store}> <PersistGate loading={null} persistor={persistor}> <Router /> </PersistGate> </Provider>, document.getElementById('root'), )
1.109375
1
public/js/node_modules_ant-design_icons_es_icons_HeatMapOutlined_js.js
makhatadze/admin_panel
0
15995732
(self["webpackChunk"] = self["webpackChunk"] || []).push([["node_modules_ant-design_icons_es_icons_HeatMapOutlined_js"],{ /***/ "./node_modules/@ant-design/icons-svg/es/asn/HeatMapOutlined.js": /*!**********************************************************************!*\ !*** ./node_modules/@ant-design/icons-svg/es/asn/HeatMapOutlined.js ***! \**********************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); // This icon file is generated automatically. var HeatMapOutlined = { "icon": { "tag": "svg", "attrs": { "viewBox": "64 64 896 896", "focusable": "false" }, "children": [{ "tag": "path", "attrs": { "d": "M955.7 856l-416-720c-6.2-10.7-16.9-16-27.7-16s-21.6 5.3-27.7 16l-416 720C56 877.4 71.4 904 96 904h832c24.6 0 40-26.6 27.7-48zm-790.4-23.9L512 231.9 858.7 832H165.3zm319-474.1l-228 394c-12.3 21.3 3.1 48 27.7 48h455.8c24.7 0 40.1-26.7 27.7-48L539.7 358c-6.2-10.7-17-16-27.7-16-10.8 0-21.6 5.3-27.7 16zm214 386H325.7L512 422l186.3 322zm-214-194.1l-57 98.4C415 669.5 430.4 696 455 696h114c24.6 0 39.9-26.5 27.7-47.7l-57-98.4c-6.1-10.6-16.9-15.9-27.7-15.9s-21.5 5.3-27.7 15.9zm57.1 98.4h-58.7l29.4-50.7 29.3 50.7z" } }] }, "name": "heat-map", "theme": "outlined" }; /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (HeatMapOutlined); /***/ }), /***/ "./node_modules/@ant-design/icons/es/icons/HeatMapOutlined.js": /*!********************************************************************!*\ !*** ./node_modules/@ant-design/icons/es/icons/HeatMapOutlined.js ***! \********************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js"); /* harmony import */ var _ant_design_icons_svg_es_asn_HeatMapOutlined__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @ant-design/icons-svg/es/asn/HeatMapOutlined */ "./node_modules/@ant-design/icons-svg/es/asn/HeatMapOutlined.js"); /* harmony import */ var _components_AntdIcon__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../components/AntdIcon */ "./node_modules/@ant-design/icons/es/components/AntdIcon.js"); // GENERATE BY ./scripts/generate.ts // DON NOT EDIT IT MANUALLY var HeatMapOutlined = function HeatMapOutlined(props, ref) { return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement(_components_AntdIcon__WEBPACK_IMPORTED_MODULE_1__.default, Object.assign({}, props, { ref: ref, icon: _ant_design_icons_svg_es_asn_HeatMapOutlined__WEBPACK_IMPORTED_MODULE_2__.default })); }; HeatMapOutlined.displayName = 'HeatMapOutlined'; /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (/*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.forwardRef(HeatMapOutlined)); /***/ }) }]);
1.054688
1
client/src/components/Users.js
rgoshen/yodlr
0
15995740
import React, { useEffect, useState } from 'react'; import axios from 'axios'; import { baseURL } from '../config'; import Table from 'react-bootstrap/Table'; import User from './User'; import Alert from 'react-bootstrap/Alert'; function Users() { const [users, setUsers] = useState([]); const [deleted, setDeleted] = useState(false); const [edited, setEdited] = useState(false); const getAllUsers = () => { axios .get(baseURL) .then((res) => { const allUsers = res.data; setUsers(allUsers); }) .catch((err) => console.error(err)); }; const handleDelete = (id) => { axios .delete(`${baseURL}/${id}`) .then((res) => { const user = res.data; console.log(user); setUsers(users.filter((user) => user.id !== id)); setDeleted(true); }) .catch((err) => console.error(err)); }; const handleEdit = (formData, id) => { const userData = { ...formData, id }; axios .put(`${baseURL}/${id}`, userData) .then((res) => { setUsers((users) => users.map((user) => (user.id === id ? res.data : user)) ); setEdited(true); }) .catch((err) => console.log(err)); }; useEffect(() => { getAllUsers(); console.log(users); }, []); useEffect(() => { if (deleted) { let resetDeletedTimer = setTimeout(() => { setDeleted(false); }, 2000); return () => { clearTimeout(resetDeletedTimer); }; } if (edited) { let resetEditedTimer = setTimeout(() => { setEdited(false); }, 2000); return () => { clearTimeout(resetEditedTimer); }; } }, [deleted, edited]); return ( <div className='constainer'> <h1 className='m-5'>Yodlr Admin Page</h1> <div className='container alert'> {deleted && <Alert variant='success'>User has been deleted!</Alert>} {edited && <Alert variant='success'>User has been updated!</Alert>} </div> <div className='container shadow-lg'> <Table striped bordered hover> <thead> <tr> <th>#</th> <th>First Name</th> <th>last Name</th> <th>Email</th> <th>State</th> <th>Save?</th> <th>Delete?</th> </tr> </thead> <tbody> {users.map((user, index) => { return ( <tr key={user.id}> <User id={index} user={user} handleEdit={handleEdit} handleDelete={handleDelete} /> </tr> ); })} </tbody> </Table> </div> </div> ); } export default Users;
1.6875
2
packages/navigation/atlassian-navigation/dist/esm/components/Settings/index.js
rholang/archive-old
1
15995748
import { __assign, __rest } from "tslib"; import React from 'react'; import SettingsIcon from '@atlaskit/icon/glyph/settings'; import { IconButton } from '../IconButton'; export var Settings = function (props) { var tooltip = props.tooltip, iconButtonProps = __rest(props, ["tooltip"]); return (React.createElement(IconButton, __assign({ icon: React.createElement(SettingsIcon, { label: tooltip }), tooltip: tooltip }, iconButtonProps))); }; //# sourceMappingURL=index.js.map
1.195313
1
content/themes/mneme-0.3.5/assets/js/index.js
wildfireone/ghost
0
15995756
/*global $ */ $(document).ready(function () { 'use strict'; var $grid = $('.grid'); if ($grid.length > 0) { $grid.imagesLoaded().progress(function (instance, image) { var $gridItem = $(image.img).parents('.grid-item'); $gridItem.removeClass('loading'); if (image.isLoaded) { $gridItem.addClass('loaded'); } else { $gridItem.addClass('unloaded'); } $gridItem.fadeIn('fast'); }).always(function () { $('.spinner').fadeOut('fast'); $('.grid').masonry({ itemSelector: '.grid-item' }); $('.pagination, .widgets, footer').show(); }); } else { $('.widgets, footer').show(); } });
1.15625
1
main.js
ioBroker/ioBroker.scheduler
7
15995764
/* jshint -W097 */ /* jshint strict: false */ /* jslint node: true */ 'use strict'; const utils = require('@iobroker/adapter-core'); // Get common adapter utils // @ts-ignore const adapterName = require('./package.json').name.split('.').pop(); /** * The adapter instance * @type {ioBroker.Adapter} */ let adapter; let timer; const devices = {}; function startAdapter(options) { options = options || {}; Object.assign(options, { name: adapterName, objectChange: (id, obj) => { if (devices[id]) { if (obj) { devices[id] = obj; delete devices[id].native; } else { delete devices[id]; } } }, unload: callback => { // stop running timer timer && clearTimeout(timer); timer = null; callback(); }, ready: () => main() }); adapter = new utils.Adapter(options); return adapter; } function checkObject(obj, type) { if (type === 'percent') { return obj.common.unit === '%' || ('min' in obj.common && 'max' in obj.common); } else if (type === 'temperature') { return obj.common.type === 'number'; } else if (type === 'onoff') { return obj.common.type === 'boolean'; } return false; } function convertValue(obj, type, value) { if (type === 'percent') { if ('min' in obj.common && 'max' in obj.common) { const delta = obj.common.max - obj.common.min; return obj.common.min + Math.round(delta * value / 100); } else { return value; } } else if (type === 'temperature') { return value; } else if (type === 'onoff') { return !!value; } return false; } const updateStates = async () => { const profiles = adapter.config.profiles; const now = new Date(); const active = {}; for (const k in profiles) { const profile = profiles[k]; let profileState = profile.type === 'profile' && profile.data.state && (await adapter.getForeignStateAsync(profile.data.state)); if (profileState && typeof profileState === 'object') { profileState = profileState.val; } if (profile.type === 'profile' && profile.data.dow.includes(now.getDay()) && profileState ) { const index = Math.floor((now.getHours() + now.getMinutes() / 60) / profile.data.intervalDuration); const value = profile.data.intervals[index]; profile.data.members.forEach(id => { if (!devices[id]) { adapter.log.warn(`Device ${id} used in schedule "${profile.title}", but object does not exist.`); // this object was deleted after adapter start return; } if (!active[id] || active[id].priority < profile.data.prio) { active[id] = { id: profile.id, title: profile.title, priority: profile.data.prio, type: profile.data.type, value, }; } else if (active[id] && active[id].priority === profile.data.prio) { adapter.log.error(`"${id}" is in two or more profiles: "${profile.title}" and "${active[id].title}"(<-used for control)`); } }); } } for (const id in active) { const profile = active[id]; if (!checkObject(devices[id], profile.type)) { adapter.log.error(`${device} in ${profile.title} is not type ${profile.type}`); continue; } const value = convertValue(devices[id], profile.type, profile.value); await adapter.setForeignStateChangedAsync(id, value); adapter.log.info(`${id} in ${profile.title} set to ${value}`); } } function startNextInterval() { const time = new Date(); if (time.getMinutes() < 30) { time.setMinutes(30); } else { time.setHours(time.getHours() + 1); time.setMinutes(0); } time.setSeconds(0); time.setMilliseconds(0); timer = setTimeout(() => { timer = null; updateStates(); startNextInterval(); }, time.getTime() - Date.now()); } const FORBIDDEN_CHARS = /[^._\-/ :!#$%&()+=@^{}|~\p{Ll}\p{Lu}\p{Nd}]+/gu; function getStateId(profile, profiles, _list) { _list = _list || []; _list.unshift(profile.title.replace(FORBIDDEN_CHARS, '_').replace(/\./g, '_')); if (profile.parent) { // find parent profile const parentProfile = profiles.find(item => item.id === profile.parent); if (parentProfile) { return getStateId(parentProfile, profiles, _list); } // eslint-disable-next-line console.error('Cannot find parent ' + profile.parent); return null; } return `${adapter.namespace}.${_list.join('.')}`; } async function main() { const profiles = adapter.config.profiles; // collect all devices for (let k = 0; k < profiles.length; k++) { const profile = profiles[k]; if (profile && profile.type === 'profile') { if (profile.data.state === true) { profile.data.state = getStateId(profile, profiles); } for (const m in profile.data.members) { if (!devices[profile.data.members[m]]) { const obj = await adapter.getForeignObjectAsync(profile.data.members[m]); if (obj && obj.common) { devices[obj._id] = obj; delete obj.native; } } } } } // subscribe on all used IDs adapter.subscribeForeignObjects(Object.keys(devices)); updateStates(); startNextInterval(); } // If started as allInOne mode => return function to create instance // @ts-ignore if (module.parent) { module.exports = startAdapter; } else { // or start the instance directly startAdapter(); }
1.664063
2
events/guildCreate.js
xCoreRoblox/xCore
0
15995772
module.exports = async (client, guild) => { client.logger.log(`Added to the guild '${client.guild.name} (${client.guild.id})`); client.user.setActivity(`${client.defaultSettings.prefix}help | ${client.guilds.size} servers`); };
0.941406
1
src/config/routes.js
kontactr/drive_lah_assignment
0
15995780
import React from 'react'; export const noRouteComponent = { exact: true, component: React.lazy(() => import('pages/NoRoute')), } const routes = { sessionManagement: { path: "/session-management", exact: true, publicRoute: true, databasePublic: true, component: React.lazy(() => import('pages/SessionManagement')), generateRoute: () => { return "/session-management" } }, login: { path: "/", exact: true, publicRoute: true, databasePublic: false, component: React.lazy(() => import('pages/Login')), generateRoute: () => { return "/" } }, dashboard: { path: "/dashboard", exact: true, publicRoute: false, databasePublic: false, component: React.lazy(() => import('pages/Dashboard')), generateRoute: () => { return "/dashboard" } }, } export default routes
1.015625
1
index.js
VladPav17/javascript-logging-lab-js-intro-000
0
15995788
console.error("HALP!") console.log("I would be a logger") console.warn("I want juice")
0.511719
1
frontend/src/components/UploadFile.js
spe-uob/Tracing-Data-Consolidation-Tool
0
15995796
import React from 'react'; import styles from './UploadFile.module.css'; import { backendBaseUrl } from '../config'; import loadingGif from '../images/loading-small-clockwise.gif'; import { Upload as UploadIcon } from 'react-feather'; class UploadFile extends React.Component { constructor(props) { super(props); this.state = { outbreakSource: '', file: '', statusMessage: '', error: false, loading: false, errorDetails: '', // error encountered during consolidation }; } downloadblob(blob, filename) { const url = URL.createObjectURL(blob); // Create a new anchor element const a = document.createElement('a'); // Set the href and download attributes for the anchor element // You can optionally set other attributes like `title`, etc // Especially, if the anchor element will be attached to the DOM a.href = url; a.download = filename || 'download'; // Click handler that releases the object URL after the element has been clicked // This is required for one-off downloads of the blob content const clickHandler = () => { setTimeout(() => { URL.revokeObjectURL(url); a.removeEventListener('click', clickHandler); }, 150); }; // Add the click event listener on the anchor element // Comment out this line if you don't want a one-off download of the blob content a.addEventListener('click', clickHandler, false); // Programmatically trigger a click on the anchor element // Useful if you want the download to happen automatically // Without attaching the anchor element to the DOM // Comment out this line if you don't want an automatic download of the blob content a.click(); // Return the anchor element // Useful if you want a reference to the element // in order to attach it to the DOM or use it in some other way return a; } onSuccessfulConsolidation (jobId) { fetch(`${backendBaseUrl}/processed?jobId=${jobId}`, { method: 'GET' }).then(response => response.blob()) .then(blob => { this.downloadblob(blob, "processed.xlsx"); }).catch(error => console.log(error)); } onFileChange = event => { this.setState({ file: event.target.files[0], }); } onValueChange = event => { this.setState({ outbreakSource: event.target.value }); } uploadFileData = event => { event.preventDefault(); this.setState({ statusMessage: 'Please wait while data is being processed', errorDetails: '', error: false, loading: true, }); let requestBody = new FormData(); requestBody.append('file', this.state.file); requestBody.append('outbreakSource', this.state.outbreakSource); fetch(`${backendBaseUrl}/upload`, { method: 'POST', body: requestBody }).then(response => response.json()).then(data => { console.log(data.error) // DEBUG this.props.markUploaded(data.jobId); if (data.error === "") { this.onSuccessfulConsolidation(data.jobId) this.setState({ statusMessage: 'File successfully consolidated', errorDetails: '', error: false, loading: false, }); } else { this.setState({ statusMessage: 'File sucessfully uploaded but encountered error during consolidation', errorDetails: data.error, error: true, loading: false, }); } }).catch(err => { console.log(err); // DEBUG this.setState({ statusMessage: 'File failed to upload', errorDetails: '', error: true, loading: false, }); }); } render() { const canUpload = this.state.file && /^[0-9]{2}\/[0-9]{3}\/[0-9]{4}$/.test(this.state.outbreakSource); return ( <div> <div className={styles.uploadContainer}> <table> <tbody> <tr> <td><div className={styles.header}>Outbreak Source (CPH):</div></td> <td className={styles.inputContainer}> <input onChange={this.onValueChange} type="value" placeholder="00/000/0000" /> </td> </tr> <tr> <td><div className={styles.header}>Excel File:</div></td> <td className={styles.inputContainer}> <input onChange={this.onFileChange} type="file" /> </td> </tr> </tbody> </table> <button className={`${styles.button} ${!canUpload ? styles.inactive : ''}`} title="Upload" disabled={!canUpload} onClick={this.uploadFileData}> <UploadIcon className={styles.uploadIcon} /> </button> </div> <div className={styles.progressContainer}> <div className={`${styles.statusMessage} ${this.state.error ? styles.error : ''}`}>{this.state.statusMessage}</div> <div className={styles.progressImageContainer}> {this.state.loading ? <img className={styles.loadingImage} src={loadingGif} alt="loading..." /> : null} </div> </div> <div className={`${styles.details} ${styles.error}`}>{this.state.errorDetails}</div> </div> ); } } export default UploadFile;
1.703125
2
front-end/src/fetchs/saleEndpoints/getSaleById.js
murilorsv14/Delivery-App
0
15995804
import api from '../api'; async function getSaleById(orderId) { const saleResult = await api .get(`/customer/orders/${orderId}`) .then((response) => (response.data)) .catch((err) => ({ error: err.response.data.message })); return saleResult; } export default getSaleById;
1.023438
1
src/Field.test.js
sladwig/gammon
2
15995812
import React from 'react'; import renderer from 'react-test-renderer'; import Field from './Field'; import boardPosition from './boardPosition'; import generateBoard from './generateBoard'; import { boardScenarios } from './generateBoard'; const blackPlayer = '0'; const whitePlayer = '1'; it('has Stones', () => { const component = renderer.create( <Field id={1} currentPlayer={{}} openDice={[]} board={boardPosition.start} selected={false} destinations={[]} selecting={() => {}} makeMove={() => {}} /> ); expect(component.getInstance().hasStones()).toBe(true); }); it('has no Stones', () => { const component = renderer.create( <Field id={1} currentPlayer={{}} openDice={[]} board={boardPosition.empty} selected={false} destinations={[]} selecting={() => {}} makeMove={() => {}} /> ); expect(component.getInstance().hasStones()).toBe(false); }); it('white has Stones', () => { const component = renderer.create( <Field id={1} currentPlayer={whitePlayer} openDice={[]} board={boardPosition.start} selected={false} destinations={[]} selecting={() => {}} makeMove={() => {}} /> ); expect(component.getInstance().hasStonesOfCurrentPlayer()).toBe(true); }); it('white has no black Stones', () => { const component = renderer.create( <Field id={1} currentPlayer={whitePlayer} openDice={[]} board={boardPosition.empty} selected={false} destinations={[]} selecting={() => {}} makeMove={() => {}} /> ); expect(component.getInstance().hasStonesOfCurrentPlayer()).toBe(false); }); it('white has no empty Stones', () => { const component = renderer.create( <Field id={1} currentPlayer={whitePlayer} openDice={[]} board={boardPosition.empty} selected={false} destinations={[]} selecting={() => {}} makeMove={() => {}} /> ); expect(component.getInstance().hasStonesOfCurrentPlayer()).toBe(false); }); it('black has Stones', () => { const component = renderer.create( <Field id={6} currentPlayer={blackPlayer} openDice={[]} board={boardPosition.start} selected={false} destinations={[]} selecting={() => {}} makeMove={() => {}} /> ); expect(component.getInstance().hasStonesOfCurrentPlayer()).toBe(true); }); it('black has no white Stones', () => { const component = renderer.create( <Field id={1} currentPlayer={blackPlayer} openDice={[]} board={boardPosition.empty} selected={false} destinations={[]} selecting={() => {}} makeMove={() => {}} /> ); expect(component.getInstance().hasStonesOfCurrentPlayer()).toBe(false); }); it('black has no empty Stones', () => { const component = renderer.create( <Field id={1} currentPlayer={blackPlayer} openDice={[]} board={boardPosition.empty} selected={false} destinations={[]} selecting={() => {}} makeMove={() => {}} /> ); expect(component.getInstance().hasStonesOfCurrentPlayer()).toBe(false); }); // start: [[], // [1,1],[],[],[],[],[0,0,0,0,0], // [],[0,0,0],[],[],[],[1,1,1,1,1], // [0,0,0,0,0],[],[],[],[1,1,1],[], // [1,1,1,1,1],[],[],[],[],[0,0], // [], // []], it('isPossibleDestination for black and respects possible moves', () => { // we are using the start position here so 6 cant move // with 5 to one because it is occupied const component = renderer.create( <Field id={1} currentPlayer={blackPlayer} openDice={[2, 5]} board={boardPosition.start} selected={6} selecting={() => {}} destinations={[4]} makeMove={() => {}} /> ); expect(component.getInstance().isPossibleDestination()).toEqual(false); }); // basically the logic is not in field anymore!? it('out isPossibleDestination for black, if player is home', () => { const component = renderer.create( <Field id={0} currentPlayer={blackPlayer} openDice={[2, 5]} board={generateBoard(boardScenarios.isAlmostDone)} selected={5} selecting={() => {}} destinations={[0]} makeMove={() => {}} /> ); expect(component.getInstance().isPossibleDestination()).toEqual(true); }); it('out isPossibleDestination for black, if player is home and almost done and dice bigger than stone ', () => { const component = renderer.create( <Field id={0} currentPlayer={blackPlayer} openDice={[2, 5]} board={generateBoard(boardScenarios.isAlmostDone, '0')} selected={3} selecting={() => {}} destinations={[0, 2]} makeMove={() => {}} /> ); expect(component.getInstance().isPossibleDestination()).toEqual(true); }); it('out NOT isPossibleDestination for black, if player is home and almost done and dice smaller than stone ', () => { const component = renderer.create( <Field id={0} currentPlayer={blackPlayer} openDice={[2, 1]} board={generateBoard(boardScenarios.isAlmostDone, '0')} selected={3} selecting={() => {}} destinations={[1, 2]} makeMove={() => {}} /> ); expect(component.getInstance().isPossibleDestination()).toEqual(false); }); it('isPossibleDestination for white and respects possible moves', () => { const component = renderer.create( <Field id={24} currentPlayer={whitePlayer} openDice={[2, 5]} board={boardPosition.start} selected={19} selecting={() => {}} destinations={[]} makeMove={() => {}} /> ); expect(component.getInstance().isPossibleDestination()).toEqual(false); }); // is possible destination it('isPossibleDestination for black', () => { const component = renderer.create( <Field id={2} currentPlayer={blackPlayer} openDice={[2, 4]} board={boardPosition.empty} selected={6} selecting={() => {}} destinations={[4, 2]} makeMove={() => {}} /> ); expect(component.getInstance().isPossibleDestination()).toEqual(true); }); it('not isPossibleDestination for black', () => { const component = renderer.create( <Field id={3} currentPlayer={blackPlayer} openDice={[2, 4]} board={boardPosition.empty} selected={6} selecting={() => {}} destinations={[]} makeMove={() => {}} /> ); expect(component.getInstance().isPossibleDestination()).toEqual(false); }); it('isPossibleDestination for white', () => { const component = renderer.create( <Field id={8} currentPlayer={whitePlayer} openDice={[2, 4]} board={boardPosition.empty} selected={6} selecting={() => {}} destinations={[8, 10]} makeMove={() => {}} /> ); expect(component.getInstance().isPossibleDestination()).toEqual(true); }); it('not isPossibleDestination for white', () => { const component = renderer.create( <Field id={11} currentPlayer={whitePlayer} openDice={[2, 4]} board={boardPosition.empty} selected={6} selecting={() => {}} destinations={[]} makeMove={() => {}} /> ); expect(component.getInstance().isPossibleDestination()).toEqual(false); });
1.523438
2
src/views/StockSearch/Common/StockSearchContainer.js
abhijeet17890/test-encoding
0
15995820
import React, { useState } from 'react'; import {Stock, GlobalCss} from '../Style'; import 'antd/dist/antd.css'; import StockResults from './StockResults'; import StockPageTitle from './StockPageTitle'; import SearchContainer from './SearchContainer'; function StockSearchContainer(props) { const [stockData, setstockData] = useState([]); const [stockSearch, setstockSearch] = useState(''); const stockResult = (data,search)=> { setstockData(data); setstockSearch(search); } return ( <> <GlobalCss /> <Stock> {/*header and switch part starts here */} <StockPageTitle val={props.match.params.val}/> <SearchContainer val={props.match.params.val} stockData={(data,search)=>stockResult(data,search)} prefixData={props.history.location.state} resultPage={true}/> {/*header and switch part ends here */} <StockResults val={props.match.params.val} stockInfo={stockData} stockSearch={stockSearch}/> </Stock> </> ) } export default StockSearchContainer;
1.4375
1
src/vocabulary/raise.js
sirvan3tr/apl
0
15995828
addVocabulary({ // ↗'CUSTOM ERROR' !!! CUSTOM ERROR '↗':function(om){aplError(om.toString())} })
0.40625
0
data/components/newsletter/index.js
BojanP85/gatsby-localization
0
15995836
import sr from './newsletter.sr'; import en from './newsletter.en'; export default { sr, en };
0.024048
0
apps/settings/js/modules/apn/apn_settings_manager.js
mozfreddyb/gaia
0
15995844
/** * ApnSettingsManager provides functions for managing apn items. When an item * is selected to be used, ApnSettingsManager also helps convert the selection * to the real settings expected by the platform. * ApnSettingsManager does its task by coordinating the following objects: * - ApnList * There is an ApnList object for each sim. ApnList stores ApnItem objects * representing apns come from the apn.json database, client provisioning * messages, and user's creation. Each ApnItem has an id assigned upon * the creation. The id is used to recored users' apn selection. * - ApnSelections * ApnSelections stores the id of the apn being used on each apn * type. * - ApnSettings * ApnSettings wraps the apn settings stored in the moz settings database * and provides simple interface for manipulation. * Implementation details please refer to {@link ApnSettingsManager}. * * @module modules/apn/apn_settings_manager */ define(function(require) { 'use strict'; var ApnConst = require('modules/apn/apn_const'); var ApnUtils = require('modules/apn/apn_utils'); var ApnItem = require('modules/apn/apn_item'); var ApnSettings = require('modules/apn/apn_settings'); var ApnList = require('modules/apn/apn_list'); var ApnSelections = require('modules/apn/apn_selections'); var APN_TYPES = ApnConst.APN_TYPES; var APN_LIST_KEY = ApnConst.APN_LIST_KEY; /** * @class ApnSettingsManager * @requires module:modules/apn/apn_const * @requires module:modules/apn/apn_utils * @requires module:modules/apn/apn_item * @requires module:modules/apn/apn_settings * @requires module:modules/apn/apn_list * @requires module:modules/apn/apn_selections * @returns {ApnSettingsManager} */ function ApnSettingsManager() { this._apnLists = {}; this._apnSelections = ApnSelections(); this._apnSettings = ApnSettings(); } ApnSettingsManager.prototype = { /** * Returns the id of the first preset apn item. * * @param {String} serviceId * @param {String} apnType * @returns {Promise String} */ _deriveActiveApnIdFromItems: function asc_fromItems(serviceId, apnType) { return this._apnItems(serviceId, apnType).then(function(apnItems) { if (apnItems.length) { return apnItems.sort(ApnUtils.sortByCategory)[0].id; } else { return null; } }); }, /** * Returns the id of the apn item that matches the current apn setting of * the specified apn type. * * @param {String} serviceId * @param {String} apnType * @returns {Promise String} */ _deriveActiveApnIdFromSettings: function asc_deriveFromSettings(serviceId, apnType) { return Promise.all([ this._apnItems(serviceId, apnType), this._apnSettings.get(serviceId, apnType) ]).then(function(results) { var apnItems = results[0]; var apnInUse = results[1]; // apnInUse is the apn that RIL is currently using. if (apnInUse) { var matchedApnItem = apnItems.find(function(apnItem) { return ApnUtils.isMatchedApn(apnItem.apn, apnInUse); }); if (matchedApnItem) { // Has matched apn in the existing apns. return matchedApnItem.id; } else { return this.addApn(serviceId, apnInUse); } } else { return null; } }.bind(this)); }, /** * Return the apn type an apn that is actively being used for. * * @access private * @memberOf ApnSettingsManager.prototype * @param {String} serviceId * @param {String} apnId * id of the apn being checked. * @returns {Promise String} */ _getApnAppliedType: function asc_getApnAppliedType(serviceId, apnId) { return this._apnSelections.get(serviceId).then(function(apnSelection) { return APN_TYPES.find((apnType) => apnSelection[apnType] === apnId); }.bind(this)); }, /** * Store the current apn selection to apn settings to the settings database. * * @access private * @memberOf ApnSettingsManager.prototype * @param {String} serviceId * @param {String} apnType */ _storeApnSettingByType: function asc_storeApnByType(serviceId, apnType) { return this._apnSelections.get(serviceId).then(function(apnSelection) { var apnList = this._apnList(serviceId); var apnId = apnSelection[apnType]; if (apnId) { // Get the apn item of apnType. return apnList.item(apnId); } }.bind(this)).then(function(apnItem) { if (apnItem) { return this._apnSettings.update(serviceId, apnType, apnItem.apn); } else { return this._apnSettings.update(serviceId, apnType, null); } }.bind(this)); }, /** * Get the apn item list of a sim slot. * * @access private * @memberOf ApnSettingsManager.prototype * @param {String} serviceId * @returns {ApnList} The apn item list. */ _apnList: function asc_apnList(serviceId) { var apnList = this._apnLists[serviceId]; if (!apnList) { this._apnLists[serviceId] = apnList = ApnList(APN_LIST_KEY + serviceId); } return apnList; }, /** * Get the apn items of an apn type for a sim slot. If the apn list is * empty, it fills the list by restoring the apn settings. * * @access private * @memberOf ApnSettingsManager.prototype * @param {String} serviceId * @param {String} apnType * @returns {Promise Array<ApnItem>} The apn items. */ _apnItems: function asc_apnItems(serviceId, apnType) { var apnList = this._apnList(serviceId); return apnList.items().then(function(apnItems) { if (apnItems) { return apnItems; } else { // Get the default preset apns by restoring. return this.restore(serviceId).then(function() { return apnList.items(); }); } }.bind(this)).then(function(apnItems) { return apnItems && apnItems.filter(ApnUtils.apnTypeFilter.bind(null, apnType)) || []; }); }, /** * Restore the apn settings to the default. Only apn items of the category * ApnItem.APN_CATEGORY.PRESET are restored. User created apn items * (custom apns) will not be affected. The preset apn items are from * the apn.json database and client provisioning messages. * * @access public * @memberOf ApnSettingsManager.prototype * @param {String} serviceId * @returns {Promise} */ restore: function asc_restore(serviceId) { var mobileConnection = navigator.mozMobileConnections[serviceId]; var networkType = mobileConnection.data.type; var that = this; return Promise.all([ ApnUtils.getOperatorCode(serviceId, 'mcc'), ApnUtils.getOperatorCode(serviceId, 'mnc') ]).then(function(values) { // Get default apns and client provisioning apns matching the mcc/mnc // codes. var mcc = values[0]; var mnc = values[1]; return Promise.all([ ApnUtils.getDefaultApns(mcc, mnc, networkType), ApnUtils.getCpApns(mcc, mnc, networkType) ]); }).then(function(results) { var apnList = that._apnList(serviceId); var presetApns = ApnUtils.separateApnsByType( Array.prototype.concat.apply([], results)); return apnList.items().then(function(apnItems) { // Remove all existing preset apns. apnItems = apnItems || []; var promises = []; apnItems.filter(function(apnItem) { if (apnItem.category === ApnItem.APN_CATEGORY.PRESET) { return true; } }).forEach(function(apnItem) { promises.push(apnList.remove(apnItem.id)); }); return Promise.all(promises); }).then(function() { // Add default preset apns. var promises = []; presetApns.forEach(function(presetApn) { promises.push(apnList.add(presetApn, ApnItem.APN_CATEGORY.PRESET)); }); return Promise.all(promises); }).then(function(apnIds) { // Set all preset apns as the active ones for each type. var promises = []; presetApns.forEach(function(presetApn, index) { var type = presetApn.types[0]; promises.push(that.setActiveApnId(serviceId, type, apnIds[index])); }); return Promise.all(promises); }); }); }, /** * Query apn items matching the mcc/mnc codes in the apn.json * database and the one received through client provisioning messages. * * @access public * @memberOf ApnSettingsManager.prototype * @param {String} serviceId * @param {String} apnType * @returns {Promise Array<ApnItem>} The apn items */ queryApns: function asc_queryApns(serviceId, apnType) { var that = this; return this.getActiveApnId(serviceId, apnType) .then(function(activeApnId) { if (activeApnId) { return activeApnId; } else { // If there is no existing active apn id, try to derive the id from // the current apn settings. return that._deriveActiveApnIdFromSettings(serviceId, apnType) .then(function(apnId) { // Set the id as the active apn id. that.setActiveApnId(serviceId, apnType, apnId); return apnId; }); } }).then(function(activeApnId) { // If there is still no active apn id, means that the apn settings have // not been set and we need to derive a default id from the current apn // items (stored in the apn list). if (activeApnId) { return activeApnId; } else { return that._deriveActiveApnIdFromItems(serviceId, apnType) .then(function(apnId) { // Set the id as the active apn id. that.setActiveApnId(serviceId, apnType, apnId); return apnId; }); } }).then(function(activeApnId) { return that._apnItems(serviceId, apnType).then(function(items) { items.forEach(function(apnItem) { apnItem.active = (apnItem.id === activeApnId); }); return items; }); }); }, /** * Add an apn to a sim slot. * * @access public * @memberOf ApnSettingsManager.prototype * @param {String} serviceId * @param {Object} apn * @param {ApnItem.APN_CATEGORY} category * @returns {Promise} */ addApn: function asc_addApn(serviceId, apn, category) { return this._apnList(serviceId).add(apn, category || ApnItem.APN_CATEGORY.CUSTOM); }, /** * Remove an apn from a sim slot. * * @access public * @memberOf ApnSettingsManager.prototype * @param {String} serviceId * @param {String} id * id of the apn item to be added. * @returns {Promise} */ removeApn: function asc_removeApn(serviceId, id) { return this._apnList(serviceId).remove(id) // check if the removed apn is actively being used. .then(this._getApnAppliedType.bind(this, serviceId, id)) .then(function(matchedApnType) { if (matchedApnType) { return this._deriveActiveApnIdFromItems(serviceId, matchedApnType) .then(this.setActiveApnId.bind(this, serviceId, matchedApnType)); } }.bind(this)); }, /** * Update an apn item. * * @access public * @memberOf ApnSettingsManager.prototype * @param {String} serviceId * @param {String} id * id of the apn item to be updated. * @param {Object} apn * @returns {Promise} */ updateApn: function asc_updateApn(serviceId, id, apn) { return this._apnList(serviceId).update(id, apn) // check if the updated apn is actively being used. .then(this._getApnAppliedType.bind(this, serviceId, id)) .then(function(matchedApnType) { if (matchedApnType) { return this._storeApnSettingByType(serviceId, matchedApnType); } }.bind(this)); }, /** * Get the id of the apn that is actively being used for an apn type. * * @access public * @memberOf ApnSettingsManager.prototype * @param {String} serviceId * @param {String} apnType * @returns {Promise String} */ getActiveApnId: function asc_getActiveApnId(serviceId, apnType) { return this._apnSelections.get(serviceId).then(function(apnSelection) { return apnSelection && apnSelection[apnType]; }); }, /** * Set the id of an apn that is to be used for an apn type. * * @access public * @memberOf ApnSettingsManager.prototype * @param {String} serviceId * @param {String} apnType * @param {String} id * @returns {Promise} */ setActiveApnId: function asc_setActiveApnId(serviceId, apnType, id) { return this._apnSelections.get(serviceId).then(function(apnSelection) { if (apnSelection[apnType] !== id) { apnSelection[apnType] = id; return this._storeApnSettingByType(serviceId, apnType); } }.bind(this)); } }; return new ApnSettingsManager(); });
1.664063
2
Control-Flow Logic-Lab/08. Fruit or Vegetable.js
Shtereva/JavaScript-Fundamentals
0
15995852
function fruitOrVegetable(product) { let result = ''; switch (product) { case 'banana': case 'apple': case 'kiwi': case 'cherry': case 'lemon': case 'grapes': case 'peach': result = 'fruit'; break; case 'tomato': case 'cucumber': case 'pepper': case 'onion': case 'garlic': case 'parsley': result = 'vegetable'; break; default: result = 'unknown'; break; } console.log(result); } fruitOrVegetable('pizza');
1.578125
2
server/src/server.js
jdgabriel/PSO-Teste
0
15995860
const app = require("./app"); app.listen(3001, "0.0.0.0", () => { console.log("Server Online!"); });
0.722656
1
src/utilities/__tests__/collection.test.js
abdusabri/hsds-react
59
15995868
import { sample } from '../collection' describe('sample', () => { test('Returns undefined if empty', () => { expect(sample()).toBeFalsy() }) test('Returns a random item from an array', () => { const array = [1, 2, 3] expect(array).toContain(sample(array)) }) test('Returns a random value from an Object', () => { const o = { a: 1, b: 2, c: 3, } expect(Object.values(o)).toContain(sample(o)) }) })
1.164063
1
app/screens/DefineGroupImagesScreen.js
DrikoArgon/sos-animal-app
0
15995876
'use strict' import React, {Component} from 'react' import { View, Text, StyleSheet, Image, TouchableOpacity, Dimensions, ScrollView, ListView } from 'react-native' import StyleVars from '../styles/StyleVars' import Routes from '../navigation/Routes' import ImagePicker from 'react-native-image-picker' import FirebaseRequest from '../Firebase/FirebaseRequest' const windowWidth = Dimensions.get("window").width const windowHeight = Dimensions.get("window").height export default class DefineGroupImagesScreen extends Component{ constructor(props){ super(props) this.state = { logoImageSource: null, logoImage: null, backgroundImageSource: null, backgroundImage: null, loading: false } } signUpGroup() { if (this.state.logoImage === null || this.state.backgroundImage === null) { return (console.error("Image(s) missing")) } this.setState({ loading: true }) FirebaseRequest.groupSignup({ name: this.props.data.name, socialMission: this.props.data.socialMission, owner: this.props.data.owner, cpf: this.props.data.cpf, activityType: this.props.data.activityType, adress: this.props.data.adress, district: this.props.data.district, phone: this.props.data.phone, celphone: this.props.data.celphone, email: this.props.data.email, city: this.props.data.city, state: this.props.data.state, country: this.props.data.country, cep: this.props.data.cep, website: this.props.data.website, logoImage: this.state.logoImage, backgroundImage: this.state.backgroundImage, password: <PASSWORD> }) .then((data) => { FirebaseRequest.groupLogin({ email: data.email, password: data.password }) .then((authData) => { FirebaseRequest.loadUserGroup(authData.uid) .then(() => { this.setState({ loading: false }) this.props.toRoute(Routes.ongArea({ amountOfScenesToPop: 3 })) }) .catch((err) => { this.setState({ loading: false }) console.error("Error loading user service", err.message) }) }) .catch((err) => { console.error("Login failed with error ", err.message) }) }) .catch((err) => { console.error("Error Signing Service: ", err.message) }) } selectPhotoTapped(isLogo) { const options = { title: 'Selecione uma opção', takePhotoButtonTitle: 'Tirar Foto...', chooseFromLibraryButtonTitle: 'Escolher da Biblioteca...', quality: 0, } ImagePicker.showImagePicker(options, (response) => { if (response.didCancel) { } else if (response.error) { console.warn('Image Picker error', response.error) } else { let source = { uri: response.uri } if (isLogo) { this.setState({ logoImageSource: source, logoImage: response.data }) } else { this.setState({ backgroundImageSource: source, backgroundImage: response.data }) } } }) } render(){ return( <View style={styles.container}> <ScrollView ref="scrollView" keyboardShouldPersistTaps="never" automaticallyAdjustContentInsects={true} alwaysBounceVertical={true} style={styles.scrollView} > <View style={styles.headerContainer}> <Text style={styles.headerText}>Imagem da Logo</Text> </View> <View style={styles.innerContainer}> <View style={styles.imageContainer}> <Image source={this.state.logoImageSource ? this.state.logoImageSource : require("../Resources/meuPerfilIcon.png")} style={this.state.logoImageSource ? styles.logoImageStyle : styles.profileImage} resizeMode={this.state.logoImageSource ? null : 'contain'} /> </View> <View style={styles.defineImageButtonContainer}> <TouchableOpacity activeOpacity={0.5} style={styles.defineImageButton} onPress={() => this.selectPhotoTapped(true)} > <Text style={styles.defineImageButtonText}>Definir imagem</Text> </TouchableOpacity> </View> </View> <View style={styles.headerContainer}> <Text style={styles.headerText}>Imagem de Fundo</Text> </View> <View style={styles.innerContainer}> <View style={styles.imageContainer}> <Image source={this.state.backgroundImageSource ? this.state.backgroundImageSource :require("../Resources/meuPerfilIcon.png")} style={this.state.backgroundImageSource ? styles.backgroundImageStyle : styles.profileImage} resizeMode='contain' /> </View> <View style={styles.defineImageButtonContainer}> <TouchableOpacity activeOpacity={0.5} style={styles.defineImageButton} onPress={() => this.selectPhotoTapped(false)} > <Text style={styles.defineImageButtonText}>Definir imagem</Text> </TouchableOpacity> </View> </View> <View style={styles.choosePlanButtonContainer}> <TouchableOpacity activeOpacity={0.5} style={styles.choosePlanButton} onPress={() => this.signUpGroup()} > <Text style={styles.choosePlanButtonText}>{this.state.loading ? "Cadastrando..." : "Cadastrar"}</Text> </TouchableOpacity> </View> </ScrollView> </View> ) } } const styles = StyleSheet.create({ container:{ flex: 1, backgroundColor: StyleVars.Colors.primary }, innerContainer: { alignItems: 'center', paddingVertical: 6 }, profileImage:{ height: windowHeight * 0.3, width: windowWidth * 0.3 }, nameText:{ fontSize: 20, color: 'white' }, locationText:{ fontSize: 16, color: 'white' }, rowContainer:{ flexDirection: 'row', paddingHorizontal: 20 }, headerContainer:{ flex: 1, backgroundColor: 'rgb(103,46,1)', justifyContent: 'center', alignItems: 'center', paddingVertical: 5, }, headerText:{ color: 'orange', fontSize: 16 }, textContainer:{ flex: 1, justifyContent: 'center', marginLeft: 15 }, rowText:{ color: 'white', fontSize: 10 }, defineImageButtonContainer:{ alignItems: 'center', justifyContent: 'center' }, defineImageButton:{ backgroundColor: StyleVars.Colors.secondary, borderRadius: 5, paddingVertical: 5, width: windowWidth * 0.7, marginBottom: 5, alignItems: 'center' }, defineImageButtonText:{ color: 'white', fontSize: 18 }, choosePlanButtonContainer:{ alignItems: 'center', justifyContent: 'center', marginTop: 10 }, choosePlanButton:{ backgroundColor: '#003000', borderRadius: 5, paddingVertical: 5, width: windowWidth * 0.8, marginBottom: 5, alignItems: 'center' }, choosePlanButtonText:{ color: 'lime', fontSize: 20 }, imageContainer: { backgroundColor: StyleVars.Colors.secondary, borderRadius: 5, width: windowWidth * 0.8, height: windowHeight * 0.3, marginBottom: 10, alignItems: 'center', justifyContent: 'center' }, logoImageStyle: { width: windowWidth * 0.45, height: windowWidth * 0.45, borderRadius: (windowWidth * 0.45) / 2 }, backgroundImageStyle: { width: windowWidth * 0.7, height: windowWidth * 0.7 } })
1.476563
1
packages/simple-ui/src/config/echarts/index.js
mrwd2009/mono-server
0
15995884
import React, { forwardRef } from 'react'; import EchartsReactCore from 'echarts-for-react/lib/core'; import * as echarts from 'echarts/core'; import { BarChart, LineChart, PieChart, } from 'echarts/charts'; import { LegendComponent, TooltipComponent, TitleComponent, ToolboxComponent, DataZoomComponent, GridComponent, } from 'echarts/components'; import { SVGRenderer, } from 'echarts/renderers'; import { theme } from './theme'; echarts.use([ BarChart, LineChart, PieChart, LegendComponent, TooltipComponent, TitleComponent, ToolboxComponent, DataZoomComponent, SVGRenderer, GridComponent, ]); echarts.registerTheme('billing', theme); // export the Component the echarts Object. const ReactEacharts = (props, ref) => { return <EchartsReactCore ref={ref} echarts={echarts} {...props} />; }; export default forwardRef(ReactEacharts);
1.007813
1
services/amazon.js
zakisaadeh/echo-uber-web-app
0
15995892
var needle = require('needle'); var settingsHelper = require("../helpers/settings"); var AWS = require('aws-sdk'); AWS.config.region = settingsHelper.getSetting("awsRegion"); var getUserProfile = function(access_token, cb){ needle.get('https://api.amazon.com/auth/o2/tokeninfo?access_token=' + encodeURIComponent(access_token), function(error, response) { if (!error && response.statusCode == 200) if (!settingsHelper.getSetting('amazonClientId') === response.body.aud) { var errorMsg = "the access token does not belong to us"; console.error(errorMsg); return cb(errorMsg); } else{ var options = { headers: { 'Authorization': 'bearer ' + access_token } } needle.get('https://api.amazon.com/auth/o2/tokeninfo?access_token=' + encodeURIComponent(access_token), options, function(user_profile_error, user_profile_response){ console.log(user_profile_response.body); return cb(null, user_profile_response.body); }); } }); }; var storeUser = function (user, cb){ var db = new AWS.DynamoDB(); var params = { TableName : 'Users', Item: { "amazonUserId": { "S": user.amazonUserId } } }; if(user.uberUserId){ params.Item["uberUserId"] = { "S": user.uberUserId }; } if(user.uberAccessToken){ params.Item["uberAccessToken"] = { "S": user.uberAccessToken }; } if(user.uberRefreshToken){ params.Item["uberRefreshToken"] = { "S": user.uberRefreshToken }; } if(user.uberRequestId){ params.Item["uberRequestId"] = { "S": user.uberRequestId }; } if(user.lat){ params.Item["lat"] = { "S": user.lat }; } if(user.lon){ params.Item["lon"] = { "S": user.lon }; } db.putItem(params, function(err, data) { if (err) console.log(err, err.stack); else console.log(data); // successful response return cb(err, data); }); }; var getUser = function (amazonUserId, cb){ var db = new AWS.DynamoDB(); var params = { TableName : 'Users', Key: { "amazonUserId": { "S": amazonUserId } } }; db.getItem(params, function(err, data) { if (err){ console.log(err, err.stack); // an error occurred return cb(err); } else{ console.log(data); // successful response return cb(null, flattenItem(data)); } }); }; function flattenItem(result){ var item = result.Item; var flattenedItem = {}; for (var property in item) { if (item.hasOwnProperty(property)) { var itemProp = item[property]; for (var innerProperty in itemProp) { if (itemProp.hasOwnProperty(innerProperty)) { flattenedItem[property] = itemProp[innerProperty]; break; } } } } return flattenedItem; } module.exports = { getUserProfile : getUserProfile, storeUser : storeUser, getUser: getUser };
1.546875
2
js/dinamicke_tacke.js
ivominic/openlayers
0
15995900
import 'ol/ol.css'; import Map from 'ol/Map'; import View from 'ol/View'; import { MultiPoint, Point } from 'ol/geom'; import TileLayer from 'ol/layer/Tile'; import OSM from 'ol/source/OSM'; import { Circle as CircleStyle, Fill, Stroke, Style } from 'ol/style'; import { getVectorContext } from 'ol/render'; var tileLayer = new TileLayer({ source: new OSM() }); var map = new Map({ layers: [tileLayer], target: 'map', view: new View({ center: [0, 0], zoom: 2 }) }); var imageStyle = new Style({ image: new CircleStyle({ radius: 5, fill: new Fill({ color: 'yellow' }), stroke: new Stroke({ color: 'red', width: 1 }) }) }); var headInnerImageStyle = new Style({ image: new CircleStyle({ radius: 2, fill: new Fill({ color: 'blue' }) }) }); var headOuterImageStyle = new Style({ image: new CircleStyle({ radius: 5, fill: new Fill({ color: 'black' }) }) }); var n = 200; var omegaTheta = 30000; // Rotation period in ms var R = 7e6; var r = 2e6; var p = 2e6; tileLayer.on('postrender', function (event) { var vectorContext = getVectorContext(event); var frameState = event.frameState; var theta = 2 * Math.PI * frameState.time / omegaTheta; var coordinates = []; var i; for (i = 0; i < n; ++i) { var t = theta + 2 * Math.PI * i / n; var x = (R + r) * Math.cos(t) + p * Math.cos((R + r) * t / r); var y = (R + r) * Math.sin(t) + p * Math.sin((R + r) * t / r); coordinates.push([x, y]); } vectorContext.setStyle(imageStyle); vectorContext.drawGeometry(new MultiPoint(coordinates)); var headPoint = new Point(coordinates[coordinates.length - 1]); vectorContext.setStyle(headOuterImageStyle); vectorContext.drawGeometry(headPoint); vectorContext.setStyle(headInnerImageStyle); vectorContext.drawGeometry(headPoint); map.render(); }); map.render();
1.4375
1
test/357_count-numbers-with-unique-digits.test.js
wayxzz/leet-code-questions
0
15995908
/* * * 给定一个非负整数 n,计算各位数字都不同的数字 x 的个数,其中 0 &le; x &lt; 10n。 * * 示例: * 给定 n = 2,返回 91。(答案应该是除[11,22,33,44,55,66,77,88,99]外,0 &le; x &lt; 100 间的所有数字) * * 致谢: * 特别感谢 @memoryless 添加这个题目并创建所有测试用例。 * * */
1.078125
1
src/client/js/dateChecker.js
RamiB1234/Travel-Buddy
0
15995916
function checkDate(enteredDate) { let now = new Date(); if(Date.parse(enteredDate)<now){ return false; } else{ return true; } } export { checkDate }
0.855469
1
webpack.config.js
qiansimin88/webpack
0
15995924
var autoprefixer = require('autoprefixer') var webpack = require('webpack') var HtmlWebpackPlugin = require('html-webpack-plugin') //css和js分离 var ExtractTextPlugin = require('extract-text-webpack-plugin') module.exports = { //source-map devtool: 'eval-source-map', entry: __dirname + '/app/main.js', output: { path: __dirname + '/build', filename: '[name]-[hash].js' //要配合HtmlWebpackPlugin插件使用 }, //本地服务 基于Nodejs npm install --save-dev webpack-dev-server devServer: { contentBase: './build', //本地服务器加载页面所在目录 color: true, //终端输出结果为彩色 historyApiFallback: true, //所以链接指向index.html 不跳转 inline: true, //浏览器实时刷新 port: 5656 }, //各种loaders /** * test : 所要处理的文件的拓展名或者正则表达式(必须) * Loader: Loader的名称(必须) * include/exclude: 手动添加必须处理的文件(文件夹)或屏蔽不需要处理的文件(文件夹)(可选) * query: 为loaders提供额外的设置选项(可选) */ module: { loaders : [ // { // test: /\.json$/, //以json结尾的所有文件 // loader: "json" // } //es6 { test: /\.js$/, exclude: /node_modules/, loader: 'babel', query: { presets: ['es2015'] } }, //vue { test: /\.vue/, loader: 'vue' }, //css { test: /\.css$/, loader: 'style!css!postcss'//style: 内嵌到页面 css:实现css在js文件中的require/import功能 }, //image //限制大小小于10k的转成base64 读取的是css内的background的图片 { test: /\.(png|jpg)$/, loader: 'url-loader?limit=1000' } ] }, //npm install postcss-loader autoprefixer postcss: [ autoprefixer({ browsers: ['last 2 versions'] }) //调用autoprefixer插件 ], //webpack plugins字段 安装各种插件 和loaders不同 Loader本质是处理文件的流 plugins: [ //webpack自带的添加声明的插件(在bundle的头添加注释)) 要require webpack依赖 new webpack.BannerPlugin('Copyright QSM inc@2016'), /** * HtmlWebpackPlugin 这个插件的作用是依据一个简单的模板,帮你生成最终的Html5文件, 这个文件中自动引用了你打包后的JS文件。每次编译都在文件名中插入一个不同的哈希值。 npm install --save-dev html-webpack-plugin 这个插件自动完成了我们之前手动做的一些事情,在正式使用之前需要对一直以来的项目结构做一些改变: 1.移除public文件夹,利用此插件,HTML5文件会自动生成,此外CSS已经通过前面的操作打包到JS中了,public文件夹里。 2.在app目录下,创建一个Html文件模板,这个模板包含title等其它你需要的元素, 在编译过程中,本插件会依据此模板生成最终的html页面,会自动添加所依赖的 css, js,favicon等文件, 在本例中我们命名模板文件名称为index.tmpl.html,模板源代码如下 3.更新webpack的配置文件,方法同上,新建一个build文件夹用来存放最终的输出文件 */ new HtmlWebpackPlugin({ template: __dirname + '/app/index.tmpl.html' //传入模板的位置 }), //给组件分配id new webpack.optimize.OccurenceOrderPlugin(), //压缩js new webpack.optimize.UglifyJsPlugin() // css和js分离 // new ExtractTextPlugin("style.css") ] }
1.101563
1
src/mobile/components/filter2/view.js
jpoczik/force
377
15995932
/* * decaffeinate suggestions: * DS002: Fix invalid constructor * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS205: Consider reworking code to avoid use of IIFEs * DS206: Consider reworking classes to avoid initClass * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ let _FilterView const _ = require("underscore") const _s = require("underscore.string") const { mediator } = require("../../../lib/mediator") import { bootstrap } from "../../components/layout/bootstrap" const { PoliteInfiniteScrollView, } = require("../../components/polite_infinite_scroll/client/view") const { DropdownView } = require("./dropdown/view") const { HeadlineView } = require("./headline/view") const template = function () { return require("./template.jade")(...arguments) } const artworkColumnsTemplate = function () { return require("../../components/artwork_columns/template.jade")(...arguments) } export const FilterView = (_FilterView = (function () { _FilterView = class FilterView extends PoliteInfiniteScrollView { constructor(...args) { super(...args) } static initClass() { this.prototype.labelMap = { medium: "Medium", price_range: "Price range", } this.prototype.events = { "click .is-show-more-button": "startInfiniteScroll", } } preinitialize() { this.onSync = this.onSync.bind(this) } initialize({ params, stuckFacet, stuckParam, aggregations }) { this.params = params this.stuckFacet = stuckFacet this.stuckParam = stuckParam this.aggregations = aggregations this.listenTo(this.collection, "initial:fetch", this.render) this.listenTo(this.collection, "sync", this.onSync) mediator.on("select:changed", this.setParams) this.facets = _.keys(this.labelMap) return Array.from(this.facets).map(facet => this.listenTo(this.params, `change:${facet}`, this.reset) ) } render() { this.$el.html(template()) this.postRender() return this } postRender() { this.onInitialFetch() this.renderCounts() this.renderDropdowns() return this.setupHeadline() } setupHeadline() { return new HeadlineView({ collection: this.collection, params: this.params, stuckParam: this.stuckParam, stuckFacet: this.stuckFacet, facets: this.facets, el: this.$(".artwork-filter-sentence"), }) } reset() { this.params.set({ page: 1 }, { silent: true }) return this.collection.fetch({ data: this.params.toJSON(), reset: true, success: () => { this.renderCounts() return this.onSync() }, }) } setParams({ name, value }) { if (value === "all") { return this.params.unset(name) } else { this.params.set(name, value) if (name === "price_range" && location.pathname.includes("/collect")) { return window.analytics.track("Commercial Filter Price Triggered", { price_range: value, }) } } } renderDropdowns() { return (() => { const result = [] const object = _.pick(this.collection.counts, _.keys(this.labelMap)) for (let name in object) { const options = object[name] const dropdownView = new DropdownView({ name, label: this.labelMap[name], filterOptions: options, filterParam: name, sort: "All", }) result.push( this.$(".artwork-filter-dropdowns").append( dropdownView.render().$el ) ) } return result })() } onInfiniteScroll() { if (this.finishedScrolling) { return } this.params.set("page", this.params.get("page") + 1) return this.collection.fetch({ data: this.params.toJSON(), remove: false, success: (artworks, res) => { if (res.length === 0) { return this.onFinishedScrolling() } }, }) } totalCount() { return _s.numberFormat(this.collection.counts.total.value) } renderCounts() { const work = this.totalCount() === "1" ? "Work" : "Works" return this.$(".artwork-filter-counts").text( `${this.totalCount()} ${work}` ) } onSync() { if (this.collection.length > 0) { this.$(".artwork-filter-list").html( artworkColumnsTemplate({ artworkColumns: this.collection.groupByColumnsInOrder(), }) ) return this.$(".artwork-filter-empty-message").hide() } else { return this.$(".artwork-filter-empty-message").show() } } } _FilterView.initClass() return _FilterView })())
1.492188
1
data/js/payment.js
bitcoincheque/banking-app-chrome
2
15995940
/** * payment.js * Copyright (c) 2016 Bitcoin Cheque Foundation (http://bitcoincheque.org) * * This program is free software; you can redistribute it and/or modify * it under the terms of the MIT license. * * Reads an html doc, finds bitcoin payment links and make cheque payments. */ $(document).ready(function () { // Intercept all clicks, check if it is a payment link $('body').on('click', 'a', function (e) { var href = $(this).attr('href'); if (/^bitcoin:/.test(href)) { var requests = href.match(/\?request=[\w\:.&=\-?\/]+/); if (requests) { var payment_link = requests[0].substring(9); makePayment(payment_link); return false; } } // Return true if not a bitcoin link so click will work normally return true; }); function makePayment(payment_link) { // Read payment information from visiting site $.getJSON(payment_link, function(json_payment_info) { // Decode it var payment_request_file = json_payment_info.payment_request; var i = payment_request_file.lastIndexOf('_'); var json_padded_base64 = payment_request_file.substring(i+1); var json_padded = window.atob(json_padded_base64); var json = json_padded.trim(); var cheque_request = JSON.parse(json); var data_json = cheque_request['data']; var md5sum = CryptoJS.MD5(data_json); var md5sum_str = md5sum.toString(); if(md5sum_str == cheque_request.md5) { var payment_request = JSON.parse(data_json); // Read bank login and default account from settings settings.getLoginDetails().then(function(login_details) { var bankingapp_url = login_details['BankingAppUrl']; var username = login_details['Username']; var password = login_details['Password']; var account = login_details['Account']; var data = {}; data['action'] = 'request_cheque'; data['username'] = username; data['password'] = password; data['account'] = account; data['payment_request'] = payment_request_file; $.post(bankingapp_url, data, function(response){ if(response.result == 'OK') { var url = payment_request.paylink; data = {}; data['action'] = 'send_payment_cheque'; data['cheque'] = response.cheque; // Send the cheque to the receiver $.post(url, data, function(response){ if(response.result != 'OK') { alert('Payment error. Error message: ' + response.message); } }, 'json'); } else { alert('Error requesting cheque from bank. Error message: ' + response.message); } },'json') }); }; }); } });
2.015625
2
components/ChapterScreen.js
ScantradFrance/ScantradFranceApp
2
15995948
import React, { useState, useEffect } from 'react'; import { View, Text, Image, ScrollView, RefreshControl, TouchableOpacity, Pressable, FlatList, Modal, Button, Dimensions } from 'react-native'; import BackgroundImage from './BackgroundImage'; import LoadingScreen from './LoadingScreen'; import ChapterSettings from './ChapterSettings'; import ReactNativeZoomableView from '@dudigital/react-native-zoomable-view/src/ReactNativeZoomableView'; import styles from "../assets/styles/styles"; import colors from "../assets/styles/colors"; import { sf_api } from '../config/secrets'; import { get as fetch } from 'axios'; import AsyncStorage from '@react-native-async-storage/async-storage'; const dimensions = Dimensions.get('window'); const ChangeChapterModal = ({ visible, setVisible, next, changeChapter }) => { return ( <Modal visible={visible} transparent={true} animationType={'slide'} > <View style={[styles.fullContainer, styles.changeChapterContainer]}> <Text style={[styles.text, styles.changeChapterTitle]}>{next ? "Aller au prochain chapitre ?" : "Aller au chapitre précédent ?"}</Text> <View style={styles.changeChapterClose}> <View style={styles.changeChapterButton}> <Button title="Rester" onPress={() => setVisible(false)} color={colors.secondary} /> </View> <View style={styles.changeChapterButton}> <Button title="Aller" onPress={() => changeChapter(next ? "next" : "previous")} color={colors.orange} /> </View> </View> </View> </Modal> ); } const VerticalPage = ({ onDoublePress, page }) => { return ( <Pressable onPress={onDoublePress} key={page.number}> <Image style={{ ...styles.chapterPageImage, aspectRatio: page.width / page.height, }} source={{ uri: page.uri }} fadeDuration={0} /> </Pressable> ); } const ChapterScreen = ({ navigation, route }) => { const [isLoadingPages, setLoadingPages] = useState(true); const [errorChapters, setErrorChapters] = useState(false); const [nbPages, setNbPages] = useState(0); const [type, setType] = useState(null); const [pages, setPages] = useState([]); const [refreshing, setRefreshing] = useState(false); const [currentPage, setCurrentPage] = useState(0); const [readStyle, setReadStyle] = useState('horizontal'); const [headerVisible, setHeaderVisible] = useState(true); const [settingsVisible, setSettingsVisible] = useState(false); const [doublePage, setDoublePage] = useState(true); const [japRead, setJapRead] = useState(true); const [nextChapter, setNextChapter] = useState(null); const [previousChapter, setPreviousChapter] = useState(null); const [changeChapterVisible, setChangeChapterVisible] = useState(false); const changeHeaderVisible = (state) => { navigation.setOptions({ tabBarVisible: false, headerShown: state !== undefined ? state : !headerVisible }); setHeaderVisible(state !== undefined ? state : !headerVisible); }; let lastPress = 0; const onDoublePress = () => { const time = new Date().getTime(); const delta = time - lastPress; const DOUBLE_PRESS_DELAY = 300; if (delta < DOUBLE_PRESS_DELAY) changeHeaderVisible(); lastPress = time; }; const changePage = async op => { const page = pages[currentPage + 2]; if (page !== undefined && !page.downloaded) { const uri = page.uri; Image.queryCache([uri]).then(cache => { if (!cache[uri]) Image.prefetch(uri); }); } if (op === "next") { if (currentPage + 1 < pages.length) setCurrentPage(currentPage + 1); else if (nextChapter) setChangeChapterVisible(true); } if (op === "previous") { if (currentPage > 0) setCurrentPage(currentPage - 1); else if (previousChapter) setChangeChapterVisible(true); } } const settingsChanged = (type, value) => { switch (type) { case "doublepage": setDoublePage(value); break; case "readstyle": value ? setReadStyle("vertical") : setReadStyle("horizontal"); break; case "japread": setJapRead(value); break; } } const loadManga = (manga_id) => { return fetch(sf_api.url + "mangas/" + manga_id).then(m => m.data); }; const loadChapters = () => { const chapter = route.params.chapter; AsyncStorage.getItem('downloads').then(d => JSON.parse(d || "{}")).then(async downloads => { const dl_chap = downloads[chapter.manga.id + "-" + Number(chapter.number)]; if (!dl_chap) { loadManga(route.params.chapter.manga.id).then(manga => { const number = Number(route.params.chapter.number); manga.chapters.forEach(c => { if (Number(c.number) === number + 1) setNextChapter({ manga: { id: manga.id, name: manga.name }, number: c.number }); if (Number(c.number) === number - 1) setPreviousChapter({ manga: { id: manga.id, name: manga.name }, number: c.number }); }); }).catch(() => {}); } else { if (downloads[chapter.manga.id + "-" + (Number(chapter.number) + 1)]) setNextChapter({ manga: { id: chapter.manga.id, name: chapter.manga.name }, number: leftPad(Number(chapter.number) + 1, 3) }); if (downloads[chapter.manga.id + "-" + (Number(chapter.number) - 1)]) setPreviousChapter({ manga: { id: chapter.manga.id, name: chapter.manga.name }, number: leftPad(Number(chapter.number) - 1, 3) }); } }).catch(() => {}); }; const getChapterPages = (manga_id, number) => { return fetch(sf_api.url + "chapters/" + manga_id + "/" + number).then(res => res.data); }; const loadChapterPages = () => { const chapter = route.params.chapter; AsyncStorage.getItem('downloads').then(d => JSON.parse(d || "{}")).then(async downloads => { const dl_chap = downloads[chapter.manga.id + "-" + Number(chapter.number)]; if (!dl_chap) { getChapterPages(chapter.manga.id, chapter.number).then(async chapter => { setNbPages(chapter.length); setType(chapter.pages[0].uri.includes("?top=") ? "webtoon" : "manga"); const uris = chapter.pages.map(p => p.uri); Image.queryCache(uris).then(cache => { uris.forEach(uri => { if (!cache[uri]) Image.prefetch(uri); }); }); setPages(chapter.pages.map((p, i) => ({ uri: p.uri, width: p.width, height: p.height, number: i + 1 }))); setLoadingPages(false); changeHeaderVisible(false); navigation.setOptions({ headerStyle: { borderBottomWidth: 0 } }); }).catch(() => setErrorChapters(true)); } else { setNbPages(dl_chap.pages.length); const pages = await Promise.all(dl_chap.pages.map(async (p, i) => { let ret = null; await Image.getSize(p, (width, height) => ret = { uri: p, width: width, height: height, number: i + 1 }); return ret; })); if (pages.includes(null)) return setErrorChapters(true); setType(dl_chap.type || "manga"); setPages(pages); setLoadingPages(false); changeHeaderVisible(true); navigation.setOptions({ headerStyle: { borderBottomWidth: 0 } }); } }).catch(() => setErrorChapters(true)); }; const onRefresh = () => { setRefreshing(true); setLoadingPages(true); loadNextPreviousChapter(); loadChapterPages(); setRefreshing(false); }; const updateHeader = () => { navigation.setOptions({ headerRight: () => !isLoadingPages && type === "manga" ? ( <Text> { readStyle === 'horizontal' ? ( <View> <Text style={[styles.text, styles.pagesIndicator]}>{(pages[currentPage] && pages[currentPage].number) || 0}/{nbPages}</Text> </View> ) : null } <TouchableOpacity onPress={() => setSettingsVisible(true)} activeOpacity={0.6}> <Image source={require('../assets/img/settings.png')} style={styles.settingsLogo} /> </TouchableOpacity> </Text> ) : null }); } const changeChapter = (op) => { setChangeChapterVisible(false); route.params.chapter = op === "next" ? nextChapter : previousChapter; setLoadingPages(true); setNextChapter(null); setPreviousChapter(null); setNbPages(0); setPages([]); setCurrentPage(0); updateHeader(); loadChapterPages(); loadChapters(); } useEffect(() => { Image.resolveAssetSource({uri: '../assets/img/settings.png'}); updateHeader(); loadChapterPages(); loadChapters(); }, []); useEffect(() => { updateHeader(); }, [currentPage, pages, readStyle, isLoadingPages]); useEffect(() => { if (type === "webtoon" && readStyle === 'horizontal') setReadStyle('vertical'); if (pages.length && !isLoadingPages) setLoadingPages(false); }, [pages]); if (isLoadingPages) return (<LoadingScreen />); if (errorChapters) return ( <BackgroundImage> <ScrollView refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} />} contentContainerStyle={styles.scrollView}> <Text style={[styles.text, styles.pagesErrorText]}> Une erreur s'est produite lors du chargement des pages... </Text> </ScrollView> </BackgroundImage> ) return ( <BackgroundImage> <View style={[styles.chapterProgressBar, { width: "100%", backgroundColor: colors.primary, zIndex: 1 }]}></View> <View style={[styles.chapterProgressBar, { width: currentPage / (nbPages - 1) * dimensions.width, backgroundColor: colors.orange, zIndex: 2 }]}></View> <ChapterSettings visible={settingsVisible} setVisible={setSettingsVisible} settingsChanged={settingsChanged} /> <ChangeChapterModal visible={changeChapterVisible} setVisible={setChangeChapterVisible} changeChapter={changeChapter} next={japRead ? currentPage === 0 : currentPage > 0} /> { type === "manga" && readStyle === 'horizontal' ? // manga <View style={styles.fullContainer} key={(pages[currentPage] && pages[currentPage].number) || 0}> <Pressable style={[styles.controlPages, styles.controlPagesPrevious]} onPress={() => changePage(japRead ? "next" : "previous")}></Pressable> <Pressable style={[styles.controlPages, styles.controlPagesNext]} onPress={() => changePage(japRead ? "previous" : "next")}></Pressable> <ReactNativeZoomableView maxZoom={2.0} minZoom={1} zoomStep={0.2} initialZoom={1} bindToBorders={true} > <Pressable onPress={onDoublePress}> <Image style={[pages[currentPage].width > pages[currentPage].height && doublePage ? styles.chapterDoublePageImage : styles.chapterPageImage, { aspectRatio: pages[currentPage].width / pages[currentPage].height } ]} source={{ uri: pages[currentPage].uri }} fadeDuration={0} /> </Pressable> </ReactNativeZoomableView> </View> : // webtoon <ReactNativeZoomableView maxZoom={2.0} minZoom={1} zoomStep={0.2} initialZoom={1} bindToBorders={true} > <FlatList data={pages} renderItem={({ item }) => <VerticalPage onDoublePress={onDoublePress} page={item} />} keyExtractor={item => item.number + ""} /> </ReactNativeZoomableView> } </BackgroundImage> ); } // https://stackoverflow.com/a/8043254 function leftPad(number, targetLength) { var output = number + ''; while (output.length < targetLength) { output = '0' + output; } return output; } module.exports = ChapterScreen;
1.554688
2
src/renderer/index.js
Jygsaw/vv
0
15995956
import './nvim/nvim';
-0.240234
0
examples/index.js
StormExecute/node-rules-system-esm
0
15995964
const NRS = require("node-rules-system"); //DONT EXPORT NRS_PASSWORD! USE MATH.RANDOM() AS THE SALT ALWAYS! const NRS_PASSWORD = "<PASSWORD>" + Math.random(); // Initialize NRS first here, // since the request module uses caching // of global setImmediate or process.nexttick functions NRS.init(NRS_PASSWORD); NRS.enableFullSecure(NRS_PASSWORD); const nodePath = require("path"); const fetch = require("node-fetch"); const request = require("request"); //IF YOU STILL NEED TO EXPORT THE SESSION, USE THIS CONSTRUCTION: const SECURE_NRS_SESSION = NRS.secureSession(NRS_PASSWORD, "examples/index.js"); SECURE_NRS_SESSION.startRecordLogs(); //SECURE_NRS_SESSION.getLogsEmitter().on("*", log => console.log(log)); //node-fetch SECURE_NRS_SESSION.connections.addDependencyAndPathsToWhiteList(["node-fetch", "examples/index.js"]); //request SECURE_NRS_SESSION.connections.addDependencyAndPathsToWhiteList(["request", "examples/index.js"]); const URL = "http://www.example.com"; const cwd = (() => { const _ = process.cwd(); if(_.endsWith("/examples")) return _; return nodePath.join(_, "./examples"); })(); fetch(URL) .then(res => res.text()) .then(body => { console.log("\x1b[34m%s\x1b[0m", "FETCH: DONE!", SECURE_NRS_SESSION.getUniqLogs()); request(URL, () => { //on versions 11.0.0, 11.1.0, 11.2.0 and 11.3.0, the console returns an error in this situation //fix(11.4.0): https://github.com/nodejs/node/commit/50005e7ddf9bd52433b20e612c2ca970bf772d3b#diff-bcbab7b1bfa5d1db1110121f54840169601f12177c390dd9157a9422de102e2b console.log("\x1b[34m%s\x1b[0m", "REQUEST: DONE!", SECURE_NRS_SESSION.getUniqLogs()); }); setImmediate(() => { const thisLogs = SECURE_NRS_SESSION.getAllLogs(); const lastLog = thisLogs[thisLogs.length - 2]; if ( lastLog.type == "callFn" && lastLog.callerPaths[0] == nodePath.join( cwd, "../node_modules/request/request.js" ) && lastLog.callerPaths[ lastLog.callerPaths.length - 1 ] == nodePath.join( cwd, "./index.js" ) ) { if(lastLog.grantRights == false) { throw "must be allowed!"; } } else { throw "something went wrong!"; } }); }) .catch(e => console.error("ERR", e)); const thisLogs = SECURE_NRS_SESSION.getAllLogs(); // -2 because the real last log is callFromSecureSession const lastLog = thisLogs[thisLogs.length - 2]; const majorNodeV = process.version.split(".")[0].replace(/\D/g, ""); if ( lastLog.type == "callFn" && lastLog.callerPaths[0] == nodePath.join( cwd, "../node_modules/node-fetch/lib/index.js" ) && lastLog.callerPaths[ lastLog.callerPaths.length - 1 ] == nodePath.join( cwd, "./index.js" ) ) { if(lastLog.grantRights == false) { throw "must be allowed!"; } } else { throw "something went wrong!"; }
1.335938
1
src/routes.js
SwipSwup/sew-4ai
0
15995972
import Liste from "@/components/ue06/Liste"; import Info from "@/components/ue06/Info"; export default [ // { name: 'info', path: '/info', component: Info, props: true}, // { name: 'liste', path: '*', component: Liste, props: true}, { name: 'default', path: '*', component: { name: 'DefaultView', render: h => h('div', 'Default view') }, props: true } ]
0.804688
1
js/gravity.js
junkangxu/Gravity
3
15995980
const maxGravity = 5; const minGravity = -5; function generateGravity() { gravityX = getRandomArbitrary(minGravity, maxGravity); gravityY = getRandomArbitrary(minGravity, maxGravity); } function applyGravity() { x += gravityX; y += gravityY; }
1.773438
2
electron/frontend/script.js
Gikkman/sysrand
0
15995988
const {ipcRenderer} = require('electron'); const unhandled = require('electron-unhandled'); unhandled(); /************************************************************************ * Event listeners ************************************************************************/ ipcRenderer .on('openDir-res', (event, path) => { console.log("Event 'openDir-res' received. Received data: " + path); makeTree(path); }) .on('getAllMetadata-res', (event, obj) => { console.log("Event 'getAllMetadata-res' received. Received data: "); console.log(obj); }) .on('paths-res', (event, res) => { console.log("Event 'paths-res' received. Received data: "); console.log(res); }); /************************************************************************ * Explicit methods ************************************************************************/ function onLoad() { ipcRenderer.send('getAllMetadata'); console.log("Event 'getAllMetadata' sent."); ipcRenderer.send('paths'); console.log("Event 'paths' sent."); }; onLoad(); function directory() { ipcRenderer.send('openDir'); console.log("Event 'openDir' sent."); } function loadGame(path, game) { ipcRenderer.send("loadGame", path, game); console.log("Event 'loadGame' sent."); } /************************************************************************ * JSTree ************************************************************************/ function makeTree(path) { $('#container') .on("open_node.jstree", (e, data) => { $('#container').jstree(true).set_type(data.node.id, "dir-open"); }) .on("after_close.jstree", (e, data) => { $('#container').jstree(true).set_type(data.node.id, "dir"); }) .jstree({ 'core' : { 'data' : { 'async': true, 'url': (node) => { return node.id === '#' ? 'http://localhost:7911/scan/' + encodeURIComponent(path) : 'http://localhost:7911/scan/' + encodeURIComponent(node.original.path); }, 'data' : (node) => { return { 'id' : node.id }; } } }, "plugins": ["wholerow", "types", "contextmenu"], "types" : { "default" : { "icon" : "fas fa-folder" }, "dir" : { "icon" : "fas fa-folder" }, "dir-open" : { "icon" : "fas fa-folder-open" }, "file" : { "icon" : "fas fa-file" } }, "contextmenu": { "items": contextMenuItem }, }); } function contextMenuItem(selectedNode) { let items = {}; if(selectedNode.type === 'file') { items.A = { label:"Load game", action: function(context) { let path = selectedNode.original.path; let file = selectedNode.original.file; loadGame(path, file); }}; } items.B = { label:"Console log", action: function(context) { console.log(selectedNode.original); }}; return items; }
1.351563
1
src/containers/search/SearchResultBatchPanelContainer.js
cesarvh/cspace-ui.js
0
15995996
import { connect } from 'react-redux'; import SearchResultBatchPanel from '../../components/search/SearchResultBatchPanel'; import { invoke, } from '../../actions/batch'; import { getUserPerms, } from '../../reducers'; const mapStateToProps = state => ({ perms: getUserPerms(state), }); const mapDispatchToProps = { invoke, }; export default connect( mapStateToProps, mapDispatchToProps, )(SearchResultBatchPanel);
0.902344
1
Components/Schema/Contracts/Hook.js
devitools/quasar
7
15996004
/** * @typedef {Object} Hook */ export default { /** */ methods: { /** * @param {string} hook * @param {Object} context */ triggerHook (hook, context = {}) { const hooks = this.hooks() if (!hooks) { return } if (!hooks[hook]) { return } const action = hooks[hook] if (typeof action !== 'function') { return } return action.call(this, context) }, /** * @param {string} hook */ triggerOption (hook) { if (!this.$options) { return } if (!this.$options[hook]) { return } const action = this.$options[hook] if (typeof action !== 'function') { return } return action.call(this) } }, beforeCreate () { this.$performance.start(this.$parent.$options.name) }, /** */ created () { this.$performance.start(`${this.$parent.$options.name}:initialize`) this.triggerOption('createdHook') this.triggerHook('created:default') this.triggerHook('created') this.$performance.end(`${this.$parent.$options.name}:initialize`) }, /** */ mounted () { this.triggerOption('mountedHook') this.triggerHook('mounted:default') this.triggerHook('mounted') this.$performance.end(this.$parent.$options.name) }, /** */ beforeMount () { this.triggerOption('beforeMountHook') this.triggerHook('beforeMount:default') this.triggerHook('beforeMount') }, /** */ beforeDestroy () { this.triggerOption('beforeDestroyHook') this.triggerHook('beforeDestroy:default') this.triggerHook('beforeDestroy') }, /** */ destroyed () { this.triggerOption('destroyedHook') this.triggerHook('destroyed:default') this.triggerHook('destroyed') } }
1.351563
1
modules/network.js
eRgo35/MelvinJS
0
15996012
const { default: axios } = require('axios') const { generateError } = require('./tools') const { MessageEmbed } = require('discord.js') module.exports = { ip: async function (message, args) { const urlIp = `http://ip-api.com/json/${args[1]}` axios.get(urlIp).then(res => { const ipInfo = new MessageEmbed() .setColor('#' + Math.floor(Math.random() * 16777215).toString(16)) .setTitle('IP Address Info') .setTimestamp(Date.now) .addField('Address:', res.data.query, false) .addField('Location:', `${res.data.city}, ${res.data.regionName}, ${res.data.country} (${res.data.lat} ${res.data.lon})`, false) .addField('Timezone:', res.data.timezone, false) .addField('Organization:', res.data.org, false) .addField('ISP:', res.data.isp, false) .setFooter({ text: 'Melvin', iconURL: 'https://cdn.discordapp.com/avatars/909848404291645520/f1617585331735015c8c800d21e56362.webp' }) return message.channel.send({ embeds: [ipInfo] }) }).catch(err => { console.log(err) generateError(message, `${args[1]} is not a valid IP Address or Domain`) }) } }
1.429688
1
app/assets/javascripts/copy-to-clip.js
uk-gov-mirror/hmrc.third-party-developer-frontend
3
15996020
$(document).ready(function() { // Copy To Clipboard var copyButtons = $('.copy-to-clip'); function copyTextToClipboard(text) { var textArea = document.createElement("textarea"); textArea.style.position = 'fixed'; textArea.style.top = 0; textArea.style.left = 0; textArea.style.width = '2em'; textArea.style.height = '2em'; textArea.style.padding = 0; textArea.style.border = 'none'; textArea.style.outline = 'none'; textArea.style.boxShadow = 'none'; textArea.style.background = 'transparent'; textArea.value = text; document.body.appendChild(textArea); textArea.select(); try { var successful = document.execCommand('copy'); } catch (e) { // allow failure - still want to remove textArea // test if we should even display the button later } document.body.removeChild(textArea); } copyButtons.each(function(index) { var self = $(this); var ariaLabel = self.attr('aria-label'); self.on('click', function(e) { e.preventDefault(); e.stopPropagation(); copyTextToClipboard(self.data('clip-text') ); self.attr('aria-label', ariaLabel.replace('Copy', 'Copied')); self.focus(); setTimeout(function() { self.attr('aria-label', ariaLabel); }, 2000); }); }); });
1.875
2
src/pages/mine.js
xfelinho/myriad-website
0
15996028
import React, { useState } from "react" import tw, { css } from "twin.macro" import { useTranslation, Trans } from "react-i18next" import SEO from "../components/seo" import MineAlgorithm from "../components/pages/mine/algoritm" import MinePool from "../components/pages/mine/pool" import Wallet from "../components/shared/wallet" import Links from "../components/shared/links" import BgImage from "../components/bg-image" import Cover from "../components/shared/cover" import Link from "../components/shared/link" import { PageContainer, BigText } from "../common/elements" const gradientTextStyle = css` background: -webkit-linear-gradient(60deg, #ffd17f, #ff5aa9); -webkit-background-clip: text; -webkit-text-fill-color: transparent; ` const MinePage = () => { const { t } = useTranslation() const [algoritm, changeAlgoritm] = useState("SHA256d") return ( <> <SEO title={t("mine.title")} /> <PageContainer> <Cover showArrow>{t("mine.title")}</Cover> </PageContainer> <div tw="bg-light-grey dark:bg-dark-light-bg py-24 px-6 sm:py-30 "> <PageContainer> <MineAlgorithm title={t("mine.algoritm.title")} selected={algoritm} onChange={value => changeAlgoritm(value)} /> </PageContainer> </div> <div tw="bg-black relative"> <PageContainer> <Wallet title={t("mine.wallet.title")} /> </PageContainer> </div> <PageContainer tw="py-24 sm:py-30 px-6"> <MinePool selected={algoritm} /> </PageContainer> <PageContainer tw="pb-24 sm:pb-43 px-6"> <BigText tw="text-orange sm:px-32" css={[gradientTextStyle]}> {t("mine.ready")} </BigText> </PageContainer> <hr tw="border-black border-opacity-25 dark:border-opacity-75" /> <PageContainer tw="py-24 sm:py-30 px-6"> <BigText tw="mb-32">{t("mine.links.title")}</BigText> <Links skip={["mine"]} /> </PageContainer> <BgImage filename="grad-1.png"> <PageContainer tw="py-24 px-6 sm:py-30 text-right text-white overflow-hidden"> <BigText tw="mb-16 sm:mb-24"> <Trans i18nKey="mine.need.title"> Is there a need for <br /> cryptocurrencies </Trans> </BigText> <Link uri="/community" tw="text-xl sm:text-2xl font-bold leading-extra-tight hover:text-black" showArrow > {t("mine.need.link")} </Link> </PageContainer> </BgImage> </> ) } export default MinePage
1.65625
2
pages/api/Release.js
max20211/repo
9
15996036
import { name, description } from '../../loader!../../repo' export default (req, res) => { res.setHeader('Cache-Control', 's-maxage=31536000') res.end(`Origin: ${name} Label: ${name} Suite: stable Version: 1.0 Codename: ios Architectures: iphoneos-arm Components: main Description: ${description} `) }
0.589844
1
app/javascript/react/data/postNewWebsite.js
SaalikLok/smidgeon-analytics
1
15996044
const postNewWebsite = async formPayload => { try { const response = await fetch("/api/v1/websites", { credentials: "same-origin", method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json", }, body: JSON.stringify(formPayload), }) if (!response.ok) { const errorsBody = await response.json() const errorObject = errorsBody const errorMessage = `${response.status} (${response.statusText})` const error = new Error(errorMessage) return errorObject } const responseBody = await response.json() return responseBody } catch (error) { console.error(`Error in fetch: ${error.message}`) } } export default postNewWebsite
1.375
1
server/index.js
hrasyid/wikiloop-battlefield
0
15996052
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. require(`dotenv`).config(); const http = require('http'); const express = require('express'); const consola = require('consola'); const {Nuxt, Builder} = require('nuxt'); const universalAnalytics = require('universal-analytics'); const rp = require('request-promise'); const mongoose = require('mongoose'); const {logger, apiLogger, perfLogger, getUrlBaseByWiki, computeOresField, fetchRevisions, useOauth} = require('./common'); const routes = require('./routes'); const wikiToDomain = require("./urlMap").wikiToDomain; const asyncHandler = fn => (req, res, next) => Promise .resolve(fn(req, res, next)) .catch(next); const logReqPerf = function (req, res, next) { // Credit for inspiration: http://www.sheshbabu.com/posts/measuring-response-times-of-express-route-handlers/ perfLogger.info(` log request starts for ${req.method} ${req.originalUrl}:`, { method: req.method, original_url: req.originalUrl, ga_id: req.cookies._ga, }); const startNs = process.hrtime.bigint(); res.on(`finish`, () => { const endNs = process.hrtime.bigint(); perfLogger.info(` log response ends for ${req.method} ${req.originalUrl}:`, { method: req.method, original_url: req.originalUrl, ga_id: req.cookies._ga, time_lapse_ns: endNs - startNs, start_ns: startNs, end_ns: endNs, }); if (req.session) { perfLogger.info(` log request session info for ${req.method} ${req.originalUrl}:`, { session_id: req.session.id }); } }); next(); }; let docCounter = 0; let allDocCounter = 0; // Import and Set Nuxt.js options const config = require('../nuxt.config.js'); config.dev = !(process.env.NODE_ENV === 'production'); // -------------- FROM STIKI API ------------- function setupSTikiApiLisenter(app) { let stikiRouter = express(); const apicache = require('apicache'); let cache = apicache.middleware; const onlyGet = (req, res) => res.method === `GET`; stikiRouter.use(cache('1 week', onlyGet)); const mysql = require('mysql2'); // create the pool const pool = mysql.createPool(process.env.STIKI_MYSQL); // now get a Promise wrapped instance of that pool const promisePool = pool.promise(); stikiRouter.get('/stiki', asyncHandler(async (req, res) => { logger.debug(`req.query`, req.query); let revIds = JSON.parse(req.query.revIds); const [rows, _fields] = await promisePool.query(`SELECT R_ID, SCORE FROM scores_stiki WHERE R_ID in (${revIds.join(',')})`); res.send(rows); req.visitor .event({ec: "api", ea: "/scores"}) .send(); })); stikiRouter.get('/stiki/:wikiRevId', asyncHandler(async (req, res) => { let revIds = req.query.revIds; logger.debug(`req.query`, req.query); let wikiRevId = req.params.wikiRevId; let _wiki = wikiRevId.split(':')[0]; let revId = wikiRevId.split(':')[1]; const [rows, _fields] = await promisePool.query(`SELECT R_ID, SCORE FROM scores_stiki WHERE R_ID = ${revId}`); res.send(rows); req.visitor .event({ec: "api", ea: "/scores/:wikiRevId"}) .send(); })); stikiRouter.get('/cbng/:wikiRevId', asyncHandler(async (req, res) => { logger.debug(`req.query`, req.query); let wikiRevId = req.params.wikiRevId; let _wiki = wikiRevId.split(':')[0]; let revId = wikiRevId.split(':')[1]; const [rows, _fields] = await promisePool.query(`SELECT R_ID, SCORE FROM scores_cbng WHERE R_ID = ${revId}`); res.send(rows); req.visitor .event({ec: "api", ea: "/cbng/:wikiRevId"}) .send(); })); stikiRouter.get('/cbng', asyncHandler(async (req, res) => { logger.debug(`req.query`, req.query); let revIds = JSON.parse(req.query.revIds); const [rows, _fields] = await promisePool.query(`SELECT R_ID, SCORE FROM scores_cbng WHERE R_ID in (${revIds.join(',')})`); res.send(rows); req.visitor .event({ec: "api", ea: "/scores"}) .send(); })); app.use(`/extra`, stikiRouter); } // -------------- FROM API ---------------- function setupApiRequestListener(db, io, app) { let apiRouter = express(); const apicache = require('apicache'); let cache = apicache.middleware; const onlyGet = (req, res) => res.method === `GET`; apiRouter.use(cache('1 week', onlyGet)); apiRouter.get('/', routes.root); apiRouter.get('/diff/:wikiRevId', asyncHandler(routes.diffWikiRevId)); apiRouter.get('/diff', asyncHandler(routes.diff)); apiRouter.get('/recentchanges/list', asyncHandler(routes.listRecentChanges)); apiRouter.get('/ores', asyncHandler(routes.ores)); apiRouter.get('/ores/:wikiRevId', asyncHandler(routes.oresWikiRevId)); apiRouter.get('/revision/:wikiRevId', asyncHandler(routes.revisionWikiRevId)); apiRouter.get('/revisions', asyncHandler(routes.revision)); apiRouter.get('/interaction/:wikiRevId', asyncHandler(routes.getInteraction)); apiRouter.get('/interactions', asyncHandler(routes.listInteractions)); apiRouter.post('/interaction/:wikiRevId', asyncHandler(routes.updateInteraction)); apiRouter.get("/markedRevs.csv", asyncHandler(routes.markedRevsCsv)); apiRouter.get("/markedRevs", asyncHandler(routes.markedRevs)); /** * Return a list of all leader * Pseudo SQL * * * ```SQL * SELECT user, count(*) FROM Interaction GROUP BY user ORDER by user; * ```` */ apiRouter.get('/leaderboard', asyncHandler(routes.leaderboard)); apiRouter.get('/stats', asyncHandler(routes.stats)); // TODO build batch api for avatar until performance is an issue. We have cache anyway should be fine. apiRouter.get("/avatar/:seed", asyncHandler(routes.avatar)); apiRouter.get('/latestRevs', asyncHandler(routes.latestRevs)); apiRouter.get('/flags', routes.flags); apiRouter.get('/mediawiki', asyncHandler(routes.mediawiki)); apiRouter.get('/version', routes.version); app.use(`/api`, apiRouter); } // ---------------------------------------- function setupMediaWikiListener(db, io) { logger.debug(`Starting mediaWikiListener.`); return new Promise(async (resolve, reject) => { logger.debug(`MediaWikiListener started`); const EventSource = require('eventsource'); const url = 'https://stream.wikimedia.org/v2/stream/recentchange'; logger.debug(`Connecting to EventStreams at ${url}`); const eventSource = new EventSource(url); eventSource.onopen = function (event) { logger.debug('--- Opened connection.'); }; eventSource.onerror = function (event) { logger.error('--- Encountered error', event); }; eventSource.onmessage = async function (event) { allDocCounter++; let recentChange = JSON.parse(event.data); // logger.debug(`server received`, data.wiki, data.id, data.meta.uri); recentChange._id = (`${recentChange.wiki}-${recentChange.id}`); if (recentChange.type === "edit") { // Currently only support these wikis. if (Object.keys(wikiToDomain).indexOf(recentChange.wiki) >= 0) { // TODO(xinbenlv): remove it after we build review queue or allow ORES missing if (recentChange.wiki == "wikidatawiki" && Math.random() <= 0.9) return; // ignore 90% of wikidata try { let oresUrl = `https://ores.wikimedia.org/v3/scores/${recentChange.wiki}/?models=damaging|goodfaith&revids=${recentChange.revision.new}`; let oresJson; try { oresJson = await rp.get(oresUrl, {json: true}); } catch(e) { if (e.StatusCodeError === 429) { logger.warn(`ORES hits connection limit `, e.errmsg); } return; } recentChange.ores = computeOresField(oresJson, recentChange.wiki, recentChange.revision.new); let doc = { _id: recentChange._id, id: recentChange.id, revision: recentChange.revision, title: recentChange.title, user: recentChange.user, wiki: recentChange.wiki, timestamp: recentChange.timestamp, ores: recentChange.ores, namespace: recentChange.namespace, nonbot: !recentChange.bot, wikiRevId: `${recentChange.wiki}:${recentChange.revision.new}`, }; docCounter++; doc.comment = recentChange.comment; io.sockets.emit('recent-change', doc); delete doc.comment; // TODO add // await db.collection(`MediaWikiRecentChange`).insertOne(doc); } catch (e) { if (e.name === "MongoError" && e.code === 11000) { logger.warn(`Duplicated Key Found`, e.errmsg); } else { logger.error(e); } } } else { logger.debug(`Ignoring revision from wiki=${recentChange.wiki}`); } } }; }); } function setupIoSocketListener(io) { io.on('connection', function (socket) { logger.debug(`New client connected `, Object.keys(io.sockets.connected).length); io.sockets.emit('client-activity', {liveUserCount: Object.keys(io.sockets.connected).length}); socket.on('disconnect', function () { io.sockets.emit('client-activity', {liveUserCount: Object.keys(io.sockets.connected).length}); logger.warn(`One client disconnected `, Object.keys(io.sockets.connected).length); }); }); } function setupAuthApi(app) { const passport = require(`passport`); const oauthFetch = require('oauth-fetch-json'); const session = require('express-session'); var MongoDBStore = require('connect-mongodb-session')(session); var mongoDBStore = new MongoDBStore({ uri: process.env.MONGODB_URI, collection: 'Sessions' }); app.use(session({ cookie: { // 90 days maxAge: 90*24*60*60*1000 }, secret: 'keyboard cat like a random stuff', resave: false, saveUninitialized: true, store: mongoDBStore, })); app.use(passport.initialize()); app.use(passport.session()); const MediaWikiStrategy = require('passport-mediawiki-oauth').OAuthStrategy; passport.serializeUser(function(user, done) { done(null, user); }); passport.deserializeUser(function(user, done) { done(null, user); }); passport.use(new MediaWikiStrategy({ consumerKey: process.env.MEDIAWIKI_CONSUMER_KEY, consumerSecret: process.env.MEDIAWIKI_CONSUMER_SECRET, callbackURL: `${process.env.OAUTH_CALLBACK_ENDPOINT}/auth/mediawiki/callback` // TODO probably need to set HOST and PORT }, function(token, tokenSecret, profile, done) { profile.oauth = { consumer_key: process.env.MEDIAWIKI_CONSUMER_KEY, consumer_secret: process.env.MEDIAWIKI_CONSUMER_SECRET, token: <PASSWORD>, token_secret: tokenSecret }; done(null, profile); } )); app.use((req, res, next) => { if (req.isAuthenticated() && req.user) { res.locals.isAuthenticated = req.isAuthenticated(); res.locals.user = { id: req.user.id, username: req.user._json.username, grants: req.user._json.grants }; logger.debug(`Setting res.locals.user = ${JSON.stringify(res.locals.user, null ,2)}`); } next(); }); app.get('/auth/mediawiki/login', passport.authenticate('mediawiki')); app.get('/auth/mediawiki/logout', asyncHandler(async (req, res) => { req.logout(); res.redirect('/'); })); app.get('/auth/mediawiki/callback', passport.authenticate('mediawiki', { failureRedirect: '/auth/mediawiki/login' }), function(req, res) { // Successful authentication, redirect home. logger.debug(` Successful authentication, redirect home. req.isAuthenticated()=`, req.isAuthenticated()); res.redirect('/'); }); function ensureAuthenticated(req, res, next) { if (req.isAuthenticated()) { return next(); } else { res.status( 401 ); res.send( 'Login required for this endpoint' ); } } app.get(`/api/auth/revert/:wikiRevId`, ensureAuthenticated, asyncHandler(async (req, res) => { logger.info(`Receive auth revert request`, req.params); let wiki = req.params.wikiRevId.split(':')[0]; let revId = req.params.wikiRevId.split(':')[1]; let apiUrl = `https://${wikiToDomain[wiki]}/w/api.php`; let revInfo = (await fetchRevisions([req.params.wikiRevId]))[wiki]; // assuming request succeeded let token = (await oauthFetch( apiUrl, { "action": "query", "format": "json", "meta": "tokens" }, {}, req.user.oauth)).query.tokens.csrftoken; // assuming request succeeded; // Documentation: https://www.mediawiki.org/wiki/API:Edit#API_documentation try { let data = await oauthFetch(apiUrl, { "action": "edit", "format": "json", "title": revInfo[0].title, // TODO(zzn): assuming only 1 revision is being reverted "tags": "WikiLoop Battlefield", "summary": `Identified as test/vandalism and undid revision ${revId} by [[User:${revInfo[0].user}]] with [[m:WikiLoop Battlefield]](v${require( './../package.json').version}). See it or provide your opinion at ${process.env.OAUTH_CALLBACK_ENDPOINT}/marked?wikiRevId=${req.params.wikiRevId}`, "undo": revId, "token": token }, {method: 'POST'}, req.user.oauth ); // assuming request succeeded; res.setHeader('Content-Type', 'application/json'); res.status(200); res.send(JSON.stringify(data)); logger.debug(`conducted revert for wikiRevId=${req.params.wikiRevId}`); } catch (err) { apiLogger.error(err); res.status( 500 ); res.send(err); } })); } async function start() { const app = express(); const cookieParser = require('cookie-parser'); const bodyParser = require('body-parser'); app.use(cookieParser()); // Setup Google Analytics app.use(universalAnalytics.middleware(process.env.GA_ID, {cookieName: '_ga'})); app.use(bodyParser()); app.use(logReqPerf); const server = http.Server(app); const io = require('socket.io')(server); app.set('socketio', io); // Init Nuxt.js const nuxt = new Nuxt(config) const {host, port} = nuxt.options.server // Build only in dev mode if (config.dev) { const builder = new Builder(nuxt) await builder.build() } else { await nuxt.ready() } await mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true, dbName: process.env.MONGODB_DB} ); app.use(function (req, res, next) { apiLogger.debug('req.originalUrl:', req.originalUrl); apiLogger.debug('req.params:', req.params); apiLogger.debug('req.query:', req.query); next(); }); if (useOauth) setupAuthApi(app); setupIoSocketListener(io); setupMediaWikiListener(mongoose.connection.db, io); setupApiRequestListener(mongoose.connection.db, io, app); if (process.env.STIKI_MYSQL) { await setupSTikiApiLisenter(app); } // Give nuxt middleware to express app.use(nuxt.render); // Listen the server // app.listen(port, host) server.listen(port, host); consola.ready({ message: `Server listening on http://${host}:${port}`, badge: true }) } start()
1.5
2
client/src/components/sidebar.js
Macquarts/tinytreasurecare
0
15996060
import React, { ReactNode } from 'react'; import { IconButton, Avatar, Box, CloseButton, Flex, HStack, VStack, Icon, useColorModeValue, Link, Drawer, DrawerContent, Text, useDisclosure, BoxProps, FlexProps, Menu, MenuButton, MenuDivider, MenuItem, MenuList, } from '@chakra-ui/react'; import { FiHome, FiTrendingUp, FiCompass, FiStar, FiSettings, FiMenu, FiBell, FiChevronDown, } from 'react-icons/fi'; import { IconType } from 'react-icons'; import { ReactText } from 'react'; import { useRouteMatch } from 'react-router'; import { useHistory } from 'react-router-dom'; export default function SideBar({ children }) { const { isOpen, onOpen, onClose } = useDisclosure(); let { path, url } = useRouteMatch(); return ( <Box minH="100vh" bg={useColorModeValue('gray.100', 'gray.900')}> <SidebarContent onClose={() => onClose} display={{ base: 'none', md: 'block' }} url={url} /> <Drawer autoFocus={false} isOpen={isOpen} placement="left" onClose={onClose} returnFocusOnClose={false} onOverlayClick={onClose} size="full" > <DrawerContent> <SidebarContent onClose={onClose} /> </DrawerContent> </Drawer> {/* mobilenav */} <MobileNav onOpen={onOpen} /> <Box ml={{ base: 0, md: 60 }} p="4"> {children} </Box> </Box> ); } const SidebarContent = ({ onClose, url, ...rest }) => { const LinkItems = () => { const userType = localStorage.getItem('userType'); return userType == 'PARENT' ? [ { name: 'Home', icon: FiHome, path: '/carers' }, { name: 'My Requests', icon: FiStar, path: '/my-requests' }, ] : [{ name: 'My Jobs', icon: FiStar, path: '/my-jobs' }]; }; return ( <Box transition="3s ease" bg={useColorModeValue('white', 'gray.900')} borderRight="1px" borderRightColor={useColorModeValue('gray.200', 'gray.700')} w={{ base: 'full', md: 60 }} pos="fixed" h="full" {...rest} > <Flex h="20" alignItems="center" mx="8" justifyContent="space-between"> <Text fontSize="md" fontFamily="monospace" fontWeight="bold"> TINY TREASURE CARE </Text> <CloseButton display={{ base: 'flex', md: 'none' }} onClick={onClose} /> </Flex> {LinkItems().map(link => ( <NavItem key={link.name} icon={link.icon} url={url + link.path}> {link.name} </NavItem> ))} </Box> ); }; const NavItem = ({ icon, url, children, ...rest }) => { return ( <Link href={url} style={{ textDecoration: 'none' }}> <Flex align="center" p="4" mx="4" borderRadius="lg" role="group" cursor="pointer" _hover={{ bg: 'cyan.400', color: 'white', }} {...rest} > {icon && ( <Icon mr="4" fontSize="16" _groupHover={{ color: 'white', }} as={icon} /> )} {children} </Flex> </Link> ); }; const MobileNav = ({ onOpen, ...rest }) => { const history = useHistory(); return ( <Flex ml={{ base: 0, md: 60 }} px={{ base: 4, md: 4 }} height="20" alignItems="center" bg={useColorModeValue('white', 'gray.900')} borderBottomWidth="1px" borderBottomColor={useColorModeValue('gray.200', 'gray.700')} justifyContent={{ base: 'space-between', md: 'flex-end' }} {...rest} > <IconButton display={{ base: 'flex', md: 'none' }} onClick={onOpen} variant="outline" aria-label="open menu" icon={<FiMenu />} /> <Text display={{ base: 'flex', md: 'none' }} fontSize="2xl" fontFamily="monospace" fontWeight="bold" > Logo </Text> <HStack spacing={{ base: '0', md: '6' }}> <Flex alignItems={'center'}> <Menu> <MenuButton py={2} transition="all 0.3s" _focus={{ boxShadow: 'none' }} > <HStack> <Avatar size={'sm'} src={ 'https://images.unsplash.com/photo-1619946794135-5bc917a27793?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&fit=crop&h=200&w=200&s=b616b2c5b373a80ffc9636ba24f7a4a9' } /> <VStack display={{ base: 'none', md: 'flex' }} alignItems="flex-start" spacing="1px" ml="2" > <Text fontSize="sm">{localStorage.getItem('firstName')}</Text> <Text fontSize="xs" color="gray.600"> {localStorage.getItem('userType')} </Text> </VStack> <Box display={{ base: 'none', md: 'flex' }}> <FiChevronDown /> </Box> </HStack> </MenuButton> <MenuList bg={useColorModeValue('white', 'gray.900')} borderColor={useColorModeValue('gray.200', 'gray.700')} > <MenuItem onClick={() => { localStorage.clear(); history.replace('/'); }} > Sign out </MenuItem> </MenuList> </Menu> </Flex> </HStack> </Flex> ); };
1.4375
1
assets/scripts/gametree/gametree_events.js
modularjon/evolution-game-client
8
15996068
'use strict'; const api = require('./gametree_api'); const ui = require('./gametree_ui'); const app = require('../app.js'); const logic = require('./gametree_logic'); const onGetUserScore = function(event) { event.preventDefault(); api.indexGames() .done(ui.userScoreSuccess) .fail(ui.failure); }; const onResetUserScore = function(event) { event.preventDefault(); if (logic.gameSolved || !app.user || !app.game) { return; } api.resetGame() .done(ui.resetUserScoreSuccess) .fail(ui.failure); }; const onCreateGame = function(event) { event.preventDefault(); api.createGame() .done(ui.createGameSuccess) .fail(ui.failure); }; const onTraySelect = function(event) { event.preventDefault(); if (logic.gameSolved || !app.user || !app.game) { return; } logic.selection = $(event.target).text(); $('.game-message').text('Now select a position within the tree.'); }; const onTreeSelect = function(event) { event.preventDefault(); if (logic.gameSolved || !app.user || !app.game) { return; } logic.tree[$(event.target).data('id')] = logic.selection; $(event.target).text(logic.selection); $('.game-message').text("Now pick another from the tray. When you've got them all filled, click submit!"); }; const onGameSubmit = function(event) { event.preventDefault(); if (logic.gameSolved || !app.user || !app.game) { return; } if(!logic.isGameSolved(logic.solution, logic.tree)) { $('.game-message').text('Not quite. Rearrange and try again!'); } else { api.submitGame() .done(ui.submitGameSuccess) .fail(ui.failure); } }; const addHandlers = () => { $('.get-user-score').on('click', onGetUserScore); $('.reset-user-score').on('click', onResetUserScore); $('.new-game').on('click', onCreateGame); $('.tray').on('click', onTraySelect); $('.child').on('click', onTreeSelect); $('.submit-game').on('click', onGameSubmit); }; module.exports = { addHandlers, };
1.414063
1
app/routes/questions.js
nancyhalladay24/111_Deaf
0
15996076
var express = require('express') var fs = require('fs') var router = express.Router() module.exports = router // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // Creating question journeys from files - June 2018 +++++++++++++++++++++++++++ // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ router.get('/', function(req, res) { res.redirect('/questions/start'); }); router.get('/start', function(req, res) { raw = fs.readFileSync('./data/question-sets/' + req.query.slug + '.json'); questionSet = JSON.parse(raw); res.redirect('/questions/0'); }); router.get('/:num', function(req, res) { var count = parseInt(req.params.num); if (count == '0') { // zero out a namespaced session obj req.session.disposition = {}; req.session.disposition.questionset = questionSet.questionset; req.session.disposition.revisiting = false; } var next = eval(count)+1; var prev = eval(count)-1 if (count === questionSet.questions.length-1) { next = questionSet.disposition } res.render('questions/question.html', { question: questionSet.questions[count].question, help: questionSet.questions[count].help, answers: questionSet.questions[count].answers, count: count, next: next, prev: prev }); }); router.post('/question-handler', function(req, res) { if (req.session.disposition.revisiting == true) { res.redirect('/edge'); } else { var nextQuestion = req.body.next; req.session.disposition.number = req.body.num; req.session.disposition.question = req.body.question; req.session.disposition.help = req.body.help; req.session.disposition.answer = req.body.answer; res.redirect(nextQuestion); } });
1.4375
1
node_modules/curl/node_modules/router/node_modules/mimes/index.js
pubsubio/pubsub-hub
3
15996084
var fs = require('fs'); var files = [__dirname + '/mime.types']; exports.avi = 'video/divx'; for (var i=0; i<files.length; i++) { try { var ls = fs.readFileSync(files[i], 'utf8').split('\n'); ls.forEach(function(line) { var reg = /^(\S*)\s*(\S*)$/, res = line.split(/\s+/); if(!res[1]) return; var type = res.shift(), exts = res; exts.forEach(function(ext) { exports[ext] = exports[ext] || type; }); }); break; } catch(err) {} } exports.resolve = function(fname) { return exports[fname.split('.').pop().split('~')[0].toLowerCase()] || 'application/octet-stream'; };
1.109375
1
src/components/Search.js
ukozazenje/petplace.com
0
15996092
import React, { Component } from "react" import { Index } from "elasticlunr" import {Link} from 'gatsby' import HomeHeroImg from "../static/images/homeHeroImg" import MobileHeroImg from "../static/images/mobileHomeHeroImg" import TabletHeroImg from "../static/images/tabletHomeHeroImg" import Pagination from "./search/pagination" import {Formik, Form, Field} from "formik" import { categoryColor } from '../components/functions' import NoImg from "../static/images/noSearchPostImg" const limit = 16 // Search component export default class Search extends Component { constructor(props) { super(props) this.state = { query: ``, posts: [], currentPosts: [], currentPage: 1, order: '', orderby: '', selectValue: '' } } getUrlParams = (search) => { let hashes = search.slice(search.indexOf('?') + 1).split('&') return hashes.reduce((params, hash) => { let [key, val] = hash.split('=') return { ...params, [key]: decodeURIComponent(val) } }, {}) } search = (title, selectValue) => { // const query = title.target.value const query = title || 'pet' this.index = this.getOrCreateIndex() this.setState({ query, // Query the index with search string to get an [] of IDs posts: this.index .search(query, {expand: true}) // Map over each ID and return the full document .map(({ ref }, index) => this.index.documentStore.getDoc(ref)), }, () => { const posts = [...this.state.posts] this.setState({ currentPosts: posts.slice(0, limit), currentPage: 1, selectValue: selectValue || "" }, () => this.sortBy(this.state.selectValue)) document.getElementById('search-results').scrollIntoView({behavior: "smooth", block: "start", inline: "nearest"}) }) } handlePageChange = (page) => { window.scrollTo({ top: 100, left: 0, behavior: 'smooth' }); const { posts } = this.state; const offset = (page - 1) * limit; const currentPosts = posts.slice(offset, offset + limit); this.setState({ currentPage: page, currentPosts, }); }; compareValues = (key, order='asc') => { if( key === 'date') { return (a, b) => { const dateA = new Date(a.date).getTime(); const dateB = new Date(b.date).getTime(); if(order !== 'asc') { return dateB > dateA ? 1 : -1; } else { return dateA > dateB ? 1 : -1; } } } else { return function(a, b) { if(!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) { return 0; } const varA = (typeof a[key] === 'string') ? a[key].toUpperCase() : a[key]; const varB = (typeof b[key] === 'string') ? b[key].toUpperCase() : b[key]; let comparison = 0; if (varA > varB) { comparison = 1; } else if (varA < varB) { comparison = -1; } return ( (order === 'desc') ? (comparison * -1) : comparison ); }; } } sortBy = (value) => { const values = value.split('-') const orderby = values[0] || this.state.orderby const order = values[1] || this.state.order const posts = [...this.state.posts] let sorted = [...posts.sort(this.compareValues(orderby, order))] this.setState({ posts: [...sorted], currentPosts: posts.slice(0, limit), currentPage: 1, selectValue: value, orderby: orderby, order: order }, () => { sessionStorage.setItem('selectValue', this.state.selectValue) }) } validate = (values) => { const errors = {}; if(!values.title) { errors.title = "Required" } else if(values.title.length < 3) { errors.title = "Minimum 3 characters" } return errors } componentDidMount(){ // Checking to see if we have set session storage for sorting posts const selectValue = sessionStorage.getItem('selectValue') || this.state.selectValue this.setState({ selectValue }, () => { this.props.location.state && this.props.location.state.title ? this.search(this.props.location.state.title, selectValue) : this.search(this.getUrlParams(this.props.location.search).q, selectValue) }) } render() { const total = this.state.posts.length return ( <> <div className="flex-container"> <section className="container is-fullhd search-hero-section-flex"> <div className="container is-fullhd form-container"> <div className="form-wrapper"> <h1>Search Our<br /> Vet-Approved Articles</h1> <p>Our comprehensive library of informative articles covers medical diagnosis, wellness tips, breed bios, and everything in between.</p> <Formik validate={this.validate} initialValues={{title: ""}} onSubmit={(values, actions) => { this.search(values.title) }} > {(props) => ( <Form className="search-box-wrapper "> <Field type="text" name="title" placeholder="Search...." className="search-input" /> <button type="submit" className="search-button" >Submit</button> {props.errors.title && props.touched.title ? <div className="form-error ">{props.errors.title}</div> : null} </Form> )} </Formik> </div> </div> </section> <div className="desktop-img"> <HomeHeroImg /> </div> <div className="tablet-img"> <TabletHeroImg /> </div> <div className="mobile-img"> <MobileHeroImg /> </div> </div> <section className={`section order-section`} id="search-results"> <div className="container search-results is-fullhd"> <div className="columns"> <div className="column"> <h2>Search Results</h2> </div> <div className="column is-3"> <select value={this.state.selectValue} className="search-select" name="orderby" onChange={(e)=>this.sortBy(e.target.value) } > <option value="">Sort by</option> <option value="title-asc">title A-Z</option> <option value="title-desc">title Z-A</option> <option value="date-asc">date ASC</option> <option value="date-desc">date DSC</option> </select> </div> </div> </div> </section> <section className="section search-page-section"> <div className="container is-fullhd"> <div className="columns search-page-columns"> <div className="column"> <div className="columns"style={{flexWrap: 'wrap'}}> { this.state.currentPosts.map((post) => ( <div key={post.id} className="column is-half-tablet is-one-quarter-desktop"> <div className="category-post-card"> <div className="card-img"> <Link to={post.path}> { post && post.featured_image && post.featured_image ? <img src={post.featured_image.replace(process.env.GATSBY_PP_URL, 'petplace.com')} alt="" /> : <NoImg /> } </Link> <Link to={(post && post.category_path) || '/'} className={`card-category ${categoryColor((post && post.category_name) || 'no category')}`} dangerouslySetInnerHTML={{ __html: (post && post.category_name) || 'no category' }} /> </div> <div className="card-content"> <Link className="card-title" to={post.path}> <h3 dangerouslySetInnerHTML={{ __html: post.title }} /> </Link> <div className="meta"> <span>{post.date || 'no date'}</span>&nbsp;·&nbsp; <span dangerouslySetInnerHTML={{ __html: post.author_name || 'Pet<EMAIL>'}} /> </div> </div> </div> </div> )) } </div> <div className="pagination"> <Pagination limit={limit} total={total} currentPage={this.state.currentPage} onPageChange={this.handlePageChange} /> </div> </div> {/* <PostsList limit={limit} loader={loader} currentPosts={currentPosts} total={this.state.posts.length} currentPage={this.state.currentPage} onPageChange={this.handlePageChange} /> */} </div> </div> </section> </> ) } getOrCreateIndex = () => this.index ? this.index : // Create an elastic lunr index and hydrate with graphql query posts Index.load(this.props.searchIndex) }
1.78125
2
day14/p1.js
MykhailoMatiiasevych/aoc2020
1
15996100
const readToLines = require('../common/readToLines') const input = readToLines('./input.txt') .filter(Boolean) .map(s => s.trim()) const res = input.reduce( ({ sum, mask, arr }, s) => { const [comm, val] = s.split(' = ') if (comm === 'mask') return { sum, mask: val.split(''), arr } const index = Number(comm.split(/\[|\]/)[1]) if (arr[index]) sum -= arr[index] const valBin = Number(val).toString(2).split('') arr[index] = Number.parseInt( mask .reduce( (res, m, i) => m === 'X' ? res : [...res.slice(0, i), m, ...res.slice(i + 1)], new Array(mask.length - valBin.length).fill('0').concat(valBin) ) .join(''), 2 ) sum += arr[index] return { sum, mask, arr } }, { sum: 0, mask: [], arr: [] } ) console.log(res.sum)
1.953125
2
tests/unit/vuex/modules/tag/state.spec.js
BerniWittmann/cape-frontend
5
15996108
import tagState from '@/vuex/modules/tag/state' describe('Vuex', () => { describe('Modules', () => { describe('Tag', () => { describe('State', () => { it('has an empty base state', () => { expect(tagState).toMatchSnapshot() }) }) }) }) })
1.015625
1
src/views/admin/Analytics.js
Mehboob1214/bip
0
15996116
import React from "react"; // components import MapExample from "components/Maps/MapExample.js"; import MapUsers from "components/Maps/MapUsers.js"; import CardPageVisits from "components/Cards/CardPageVisits.js"; import CardSocialTraffic from "components/Cards/CardSocialTraffic.js"; // import LineChart2 from "components/Cards/LineChart2.js"; export default function Maps() { return ( <> {/* <div className="flex flex-wrap"> <div className="w-full lg:w-12/12 xl:w-12/12"> <LineChart2 /> </div> </div> */} <div className="flex flex-wrap"> <div className="w-full lg:w-12/12 xl:w-12/12"> <div className="relative flex flex-col min-w-0 break-words bg-white w-full mb-6 shadow-lg rounded" style={{padding:"0px" }} > <div className="rounded-t mb-0 px-4 py-3 border-0" > <h1 className="font-semibold text-base text-blueGray-700" >SALES</h1> </div> <MapExample /> </div> </div> {/* <div className="w-full px-4"> <div className="relative flex flex-col min-w-0 break-words bg-white w-full mb-6 shadow-lg rounded"> <MapExample /> </div> </div> */} </div> <div className="flex flex-wrap"> <div className="w-full lg:w-6/12 xl:w-6/12 px-4" style={{marginTop:"20px" }} > <CardPageVisits /> </div> <div className="w-full lg:w-6/12 xl:w-6/12 px-4" style={{marginTop:"20px" }} > <CardSocialTraffic /> </div> {/* <div className="w-full px-4"> <div className="relative flex flex-col min-w-0 break-words bg-white w-full mb-6 shadow-lg rounded"> <MapExample /> </div> </div> */} </div> <div className="flex flex-wrap"> <div className="w-full lg:w-12/12 xl:w-12/12"> <div className="relative flex flex-col min-w-0 break-words bg-white w-full mb-6 shadow-lg rounded" style={{padding:"0px" }} > <div className="rounded-t mb-0 px-4 py-3 border-0" > <h1 className="font-semibold text-base text-blueGray-700" >VISITORS</h1> </div> <MapUsers /> </div> </div> </div> </> ); }
1.328125
1
tests/zones/africa/ndjamena.js
bamlab/moment-timezone
3
15996124
"use strict"; var helpers = require("../../helpers/helpers"); exports["Africa/Ndjamena"] = { "1911" : helpers.makeTestYear("Africa/Ndjamena", [ ["1911-12-31T22:59:47+00:00", "23:59:59", "LMT", -3612 / 60], ["1911-12-31T22:59:48+00:00", "23:59:48", "WAT", -60] ]), "1979" : helpers.makeTestYear("Africa/Ndjamena", [ ["1979-10-13T22:59:59+00:00", "23:59:59", "WAT", -60], ["1979-10-13T23:00:00+00:00", "01:00:00", "WAST", -120] ]), "1980" : helpers.makeTestYear("Africa/Ndjamena", [ ["1980-03-07T21:59:59+00:00", "23:59:59", "WAST", -120], ["1980-03-07T22:00:00+00:00", "23:00:00", "WAT", -60] ]) };
0.648438
1
src/App.js
rehan509/ShoeStore
0
15996132
import React from "react"; import Style from './App.css'; import Logo from './logo1.png'; import { BrowserRouter as Router, Routes, Route, Link, Outlet, useParams } from "react-router-dom"; export default function App() { return ( <Router> <Navbar /> <Routes> <Route path="/" element={<Home />} /> <Route path="launch" element={<Launch />}> <Route index={true} element={<LaunchIndex />} /> <Route index={true} element={<LaunchShoe />} /> </Route> <Route path="*" element={<NotFound />} /> </Routes> </Router> ); } function NotFound() { return ( <div> <h1>Not found!</h1> <p>Sorry your page was not found!</p> </div> ); } function Home() { return ( <div> <h1>Welcome Home!</h1> </div> ); } function Launch() { return ( <div> <h1>Launch</h1> <Outlet /> </div> ); } function LaunchIndex() { return ( <ul> {Object.entries(shoes).map(([slug, { name, img }]) => ( <div className="dataof"> <li key={slug}> <Link to={`/launch/${slug}`}> <h2>{name}</h2> <img src={img} alt={name} /> </Link> </li> </div> ))} </ul> ); } function LaunchShoe() { const { slug } = useParams(); const shoe = shoes[slug]; if (!shoe) { return <h2>Not Found!</h2>; } const { name, img } = shoe; return ( <div> <h2>{name}</h2> <img src={img} alt={name} /> </div> ); } const shoes = { "air-jordan-3-valor-blue": { name: "<NAME>", img: "https://secure-images.nike.com/is/image/DotCom/CT8532_104_A_PREM?$SNKRS_COVER_WD$&align=0,1" }, "jordan-mars-270-london": { name: "<NAME>", img: "https://secure-images.nike.com/is/image/DotCom/CV3042_001_A_PREM?$SNKRS_COVER_WD$&align=0,1" }, "air-jordan-1-zoom-racer-blue": { name: "<NAME>", img: "https://secure-images.nike.com/is/image/DotCom/CK6637_104_A_PREM?$SNKRS_COVER_WD$&align=0,1" } }; function Navbar(){ return<> <nav> <div> <nav className="navbar navbar-expand-lg bg-light text-black"> <button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo03" aria-controls="navbarTogglerDemo03" aria-expanded="false" aria-label="Toggle navigation"> <span className="navbar-toggler-icon" /> </button> <a className="navbar-brand nav-link enabled text-black mr-auto" href="#"><svg className="pre-logo-svg" height="60px" width="60px" fill="#111" viewBox="0 0 69 32"><path d="M68.56 4L18.4 25.36Q12.16 28 7.92 28q-4.8 0-6.96-3.36-1.36-2.16-.8-5.48t2.96-7.08q2-3.04 6.56-8-1.6 2.56-2.24 5.28-1.2 5.12 2.16 7.52Q11.2 18 14 18q2.24 0 5.04-.72z" /></svg></a> <div className="collapse navbar-collapse" id="navbarTogglerDemo03"> <ul className="navbar-nav mr-auto mt-2 mt-lg-0"> <li className="nav-item"> <a className="nav-link text-black" href="#"><Link to="/" >Home</Link> <span className="sr-only">(current)</span></a> </li> <li className="nav-item"> <a className="nav-link"><Link to="/launch">Launch</Link></a> </li> <li className="nav-item"> <a className="nav-link disabled text-black" href="#">Sale</a> </li> </ul> <form className="form-inline my-2 my-lg-0"> <input className="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" /> <button className="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form><svg width="1em" height="1em" viewBox="0 0 16 16" className="bi bi-heart" fill="currentColor" xmlns="http://www.w3.org/2000/svg"> <path fillRule="evenodd" d="M8 2.748l-.717-.737C5.6.281 2.514.878 1.4 3.053c-.523 1.023-.641 2.5.314 4.385.92 1.815 2.834 3.989 6.286 6.357 3.452-2.368 5.365-4.542 6.286-6.357.955-1.886.838-3.362.314-4.385C13.486.878 10.4.28 8.717 2.01L8 2.748zM8 15C-7.333 4.868 3.279-3.04 7.824 1.143c.06.055.119.112.176.171a3.12 3.12 0 0 1 .176-.17C12.72-3.042 23.333 4.867 8 15z" /> </svg> <svg width="1em" height="1em" viewBox="0 0 16 16" className="bi bi-bag" fill="currentColor" xmlns="http://www.w3.org/2000/svg"> <path fillRule="evenodd" d="M8 1a2.5 2.5 0 0 0-2.5 2.5V4h5v-.5A2.5 2.5 0 0 0 8 1zm3.5 3v-.5a3.5 3.5 0 1 0-7 0V4H1v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V4h-3.5zM2 5v9a1 1 0 0 0 1 1h10a1 1 0 0 0 1-1V5H2z" /> </svg> </div> </nav> <div className="alert alert-secondary" role="alert"> Nike Statement on COIVD-19 <a href="#" className="alert-link">Join Now</a> </div> </div> </nav> </> }
1.601563
2
_esm2015/add/operator/publishBehavior.js
IgorMinar/rxjs-builds
0
15996140
import { Observable } from '../../internal/Observable'; import { publishBehavior } from '../../internal/patching/operator/publishBehavior'; Observable.prototype.publishBehavior = publishBehavior; //# sourceMappingURL=publishBehavior.js.map
0.472656
0
frontend/src/components/AdminMenuList.js
Software-Engineering-Courses-Moshirpour/intellirn-app
0
15996148
const AdminMenuList = [ { id: 1, head: 'View received messages', url: '/admin-menu/contactus', src: '/images/doctor_checking_pregnant_lady.svg', }, { id: 2, head: 'Create new survey', url: '/admin-menu/survey/create-survey', src: '/images/eye_test.svg', }, { id: 3, head: 'Edit existing surveys', url: '/admin-menu/survey/edit-survey', src: '/images/healthy_man_donating_his_blood.svg', }, { id: 4, head: 'Create new education category', url: '/admin-menu/education/create-education-category', src: '/images/research_lab.svg', }, { id: 5, head: 'Edit existing education category', url: '/admin-menu/education/edit-education-category', src: '/images/routine_health_checkup.svg', }, { id: 6, head: 'Create new educations', url: '/admin-menu/education/create-education', src: '/images/routine_health_checkup.svg', }, { id: 7, head: 'Edit existing educations', url: '/admin-menu/education/edit-education', src: '/images/routine_health_checkup.svg', }, ]; export default AdminMenuList;
0.503906
1
Client/src/actions/ConsentForm/PregnantOrNursing/Yes/ACTION_PREGNANT_OR_NURSING_YES_RESET.js
BibhushanKarki/GlowLabs
47
15996156
const PREGNANT_OR_NURSING_YES_RESET = "PREGNANT_OR_NURSING_YES_RESET"; const ACTION_PREGNANT_OR_NURSING_YES_RESET = () => { return { type: PREGNANT_OR_NURSING_YES_RESET, }; }; export default ACTION_PREGNANT_OR_NURSING_YES_RESET;
0.613281
1
modules/system/hotbar.js
Qowy/dsa5-foundryVTT
0
15996164
export default class DSA5Hotbar extends Hotbar { async _render(force = false, options = {}) { await super._render(force, options); //$(this._element).append($('<div class="tokenQuickHot"></div>')) this.addContextColor() } addContextColor() { const parry = new RegExp(` ${game.i18n.localize('CHAR.PARRY')}$`) const attack = new RegExp(` ${game.i18n.localize('CHAR.ATTACK')}$`) const macroList = $(this._element).find('#macro-list') for (const macro of this.macros) { if (!macro.macro) continue if (parry.test(macro.macro.data.name)) { macroList.find(`[data-macro-id="${macro.macro.data._id}"]`).addClass("parry") } else if (attack.test(macro.macro.data.name)) { macroList.find(`[data-macro-id="${macro.macro.data._id}"]`).addClass("attack") } } } }
1.210938
1
components/list-item/src/stories.js
taranchauhan/govuk-react
0
15996172
import React from 'react'; import { storiesOf } from '@storybook/react'; import ListItem from '.'; storiesOf('ListItem', module).add('ListItem', () => ( <ListItem>ListItem example</ListItem> ));
0.746094
1
docs/documentation/html/search/files_1.js
IzzDarki/Ino
0
15996180
var searchData= [ ['debug_2ecpp_656',['Debug.cpp',['../_debug_8cpp.html',1,'']]], ['debug_2eh_657',['Debug.h',['../_debug_8h.html',1,'']]], ['dynamicarray_2eh_658',['DynamicArray.h',['../_dynamic_array_8h.html',1,'']]] ];
0.023926
0
components/CartItem.js
marcelobaez/sweet-web
0
15996188
import React from "react"; const CartItem = ({ cover, name, price, description, color, stock }) => { return ( <div className='w-full flex'> <div className='w-full sm:w-1/12 md:w-1/12 lg:w-1/12 xl:w-1/12'> <img className='object-cover w-full' src='https://res.cloudinary.com/dbvfkfj4d/image/upload/c_scale,w_1080/v1569955274/Sweethope/IMG_6429_kgyffw.jpg' ></img> </div> <div className='sm:w-11/12 md:w-11/12 lg:w-11/12 xl:w-11/12'> <div className='w-full pl-3 flex flex-wrap'> <div className=' w-full md:w-10/12 lg:w-10/12 xl:w-10/12 flex-none text-gray-900 font-bold text-lg'> Saona </div> <div className='w-full md:w-2/12 lg:w-2/12 xl:w-2/12 sm:text-left md:text-right lg:text-right xl:text-right text-left flex-none text-pink-500 font-semibold text-lg'> $ 1650 </div> <div className='w-full flex-none text-gray-600 font-base text-sm pb-4'> Conjunto corpiño top alto y bombacha regulable </div> <div className='w-full flex-none text-xs pb-2 text-gray-900'> <span>Color: Negro</span> </div> <div className='w-full flex-none text-xs text-gray-900'> <span>Cantidad: </span> <input type='number' step={1} min={0} max={3} defaultValue={1} /> </div> </div> </div> </div> ); }; export default CartItem;
1.335938
1
test/components/crawlers-page/crawlers-page.js
vsawchuk/CPDBv2_frontend
20
15996196
import React from 'react'; import { shallow } from 'enzyme'; import { stub } from 'sinon'; import CrawlersPage from 'components/crawlers-page'; import CrawlersTable from 'components/crawlers-page/crawlers-table'; import ShareableHeaderContainer from 'containers/headers/shareable-header/shareable-header-container'; describe('CrawlersPage component', function () { it('should render crawler page correctly', function () { const requestCrawlersStub = stub(); const crawlers = [{ id: 109, crawlerName: 'SUMMARY_REPORTS_COPA', numDocuments: 5, numNewDocuments: 1, recentRunAt: '2019-02-20', }, { id: 110, crawlerName: 'SUMMARY_REPORTS_COPA', numDocuments: 7, numNewDocuments: 2, recentRunAt: '2019-02-20', }, { id: 111, crawlerName: 'PORTAL_COPA', numDocuments: 15, numNewDocuments: 6, recentRunAt: '2019-02-20', }]; const nextParams = { limit: '20', offset: '20' }; const wrapper = shallow( <CrawlersPage crawlers={ crawlers } requestCrawlers={ requestCrawlersStub } nextParams={ nextParams } /> ); const shareableHeaderContainer = wrapper.find(ShareableHeaderContainer); const headerButton = shareableHeaderContainer.prop('headerButtons'); headerButton.props.buttonText.should.equal('Documents'); headerButton.props.to.should.equal('/documents/'); const crawlersTable = wrapper.find(CrawlersTable); crawlersTable.prop('rows').should.eql(crawlers); crawlersTable.prop('nextParams').should.eql(nextParams); crawlersTable.prop('requestCrawlers').should.eql(requestCrawlersStub); }); });
1.453125
1
src/store/index.js
jakubjirous/vue-coach-finder
0
15996204
import { createLogger, createStore, } from 'vuex'; import rootActions from './actions'; import rootGetters from './getters'; import { authModule } from './modules/auth'; import { coachesModule } from './modules/coaches'; import { requestsModule } from './modules/requests'; import rootMutations from './mutations'; export const store = createStore({ modules: { coaches: coachesModule, requests: requestsModule, auth: authModule, }, getters: rootGetters, mutations: rootMutations, actions: rootActions, plugins: [createLogger()], });
0.742188
1
test/common.js
dex4er/js-stream.pipeline
1
15996212
'use strict'; // taken from https://github.com/nodejs/node/blob/master/test/common/index.js exports.crashOnUnhandledRejection = function() { process.on('unhandledRejection', function(err) { process.nextTick(function() { throw err; }); }); }; exports.mustCall = function(fn, exact) { return _mustCallInner(fn, exact, 'exact'); }; function noop() {} var mustCallChecks = []; function runCallChecks(exitCode) { if (exitCode !== 0) return; var failed = mustCallChecks.filter(function(context) { if ('minimum' in context) { context.messageSegment = 'at least ' + context.minimum; return context.actual < context.minimum; } else { context.messageSegment = 'exactly ' + context.exact; return context.actual !== context.exact; } }); failed.forEach(function(context) { console.log( 'Mismatched %s function calls. Expected %s, actual %d.', context.name, context.messageSegment, context.actual ); console.log( context.stack .split('\n') .slice(2) .join('\n') ); }); if (failed.length) process.exit(1); } function _mustCallInner(fn, criteria, field) { criteria = criteria !== undefined ? criteria : 1; if (process._exiting) { throw new Error('Cannot use common.mustCall*() in process exit handler'); } if (typeof fn === 'number') { criteria = fn; fn = noop; } else if (fn === undefined) { fn = noop; } if (typeof criteria !== 'number') { throw new TypeError('Invalid ' + field + ' value: ' + criteria); } var context = { actual: 0, stack: new Error().stack, name: fn.name || '<anonymous>' }; context[field] = criteria; // add the exit listener only once to avoid listener leak warnings if (mustCallChecks.length === 0) process.on('exit', runCallChecks); mustCallChecks.push(context); return function() { context.actual++; return fn.apply(this, arguments); }; } Object.defineProperty(exports, 'hasCrypto', { get: function() { return Boolean(process.versions.openssl); } }); exports.printSkipMessage = function(msg) { console.log('1..0 # Skipped: ' + msg); }; exports.skip = function(msg) { exports.printSkipMessage(msg); process.exit(0); };
1.34375
1
src/utils/error/throwTaskFailed.js
keg-hub/keg-cli
0
15996220
const { getKegSetting } = require('@keg-hub/cli-utils') /** * Throws task failed error * * @returns {void} */ const throwTaskFailed = () => { getKegSetting('errorStack') ? (() => { throw new Error(`Task failed!`) })() : process.exit(1) } module.exports = { throwTaskFailed }
0.910156
1
scripts/paths.js
smilelmz/web_template
0
15996228
const fs = require('fs') const path = require('path') const appDirectory = fs.realpathSync(process.cwd()) const resolveApp = relativePath => path.resolve(appDirectory, relativePath) module.exports = { resolveApp, appDirectory, appSrc: resolveApp('src'), appDist: resolveApp('dist'), appIndex: resolveApp('src/index'), appHtml: resolveApp('public/index.html'), appPublic: resolveApp('public'), appTsConfig: resolveApp('tsconfig.json'), appNodeModules: resolveApp('node_modules'), appLessVar: resolveApp('src/themes/vars.less'), appMock: resolveApp('.mocks'), aliasPath: { '@': resolveApp('src'), '@config': resolveApp('src/config'), '@utils': resolveApp('src/utils'), '@components': resolveApp('src/components'), '@services': resolveApp('src/services'), '@assets': resolveApp('src/assets'), '@pages': resolveApp('src/pages'), '@themes': resolveApp('src/themes'), '@types': resolveApp('src/types'), '@hooks': resolveApp('src/hooks'), }, }
0.886719
1
out/amazon_ec2/dist/model/RequestSpotInstancesRequest.js
getkloudi/integration-wrapper-generator
0
15996236
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _ApiClient = _interopRequireDefault(require("../ApiClient")); var _InstanceInterruptionBehavior = _interopRequireDefault(require("./InstanceInterruptionBehavior")); var _RequestSpotLaunchSpecification = _interopRequireDefault(require("./RequestSpotLaunchSpecification")); var _SpotInstanceType = _interopRequireDefault(require("./SpotInstanceType")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } /** * The RequestSpotInstancesRequest model module. * @module model/RequestSpotInstancesRequest * @version 1.1.0 */ var RequestSpotInstancesRequest = /*#__PURE__*/ function () { /** * Constructs a new <code>RequestSpotInstancesRequest</code>. * Contains the parameters for RequestSpotInstances. * @alias module:model/RequestSpotInstancesRequest */ function RequestSpotInstancesRequest() { _classCallCheck(this, RequestSpotInstancesRequest); RequestSpotInstancesRequest.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ _createClass(RequestSpotInstancesRequest, null, [{ key: "initialize", value: function initialize(obj) {} /** * Constructs a <code>RequestSpotInstancesRequest</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/RequestSpotInstancesRequest} obj Optional instance to populate. * @return {module:model/RequestSpotInstancesRequest} The populated <code>RequestSpotInstancesRequest</code> instance. */ }, { key: "constructFromObject", value: function constructFromObject(data, obj) { if (data) { obj = obj || new RequestSpotInstancesRequest(); if (data.hasOwnProperty('AvailabilityZoneGroup')) { obj['AvailabilityZoneGroup'] = _ApiClient["default"].convertToType(data['AvailabilityZoneGroup'], 'String'); } if (data.hasOwnProperty('BlockDurationMinutes')) { obj['BlockDurationMinutes'] = _ApiClient["default"].convertToType(data['BlockDurationMinutes'], 'Number'); } if (data.hasOwnProperty('ClientToken')) { obj['ClientToken'] = _ApiClient["default"].convertToType(data['ClientToken'], 'String'); } if (data.hasOwnProperty('DryRun')) { obj['DryRun'] = _ApiClient["default"].convertToType(data['DryRun'], 'Boolean'); } if (data.hasOwnProperty('InstanceCount')) { obj['InstanceCount'] = _ApiClient["default"].convertToType(data['InstanceCount'], 'Number'); } if (data.hasOwnProperty('InstanceInterruptionBehavior')) { obj['InstanceInterruptionBehavior'] = _InstanceInterruptionBehavior["default"].constructFromObject(data['InstanceInterruptionBehavior']); } if (data.hasOwnProperty('LaunchGroup')) { obj['LaunchGroup'] = _ApiClient["default"].convertToType(data['LaunchGroup'], 'String'); } if (data.hasOwnProperty('LaunchSpecification')) { obj['LaunchSpecification'] = _RequestSpotLaunchSpecification["default"].constructFromObject(data['LaunchSpecification']); } if (data.hasOwnProperty('SpotPrice')) { obj['SpotPrice'] = _ApiClient["default"].convertToType(data['SpotPrice'], 'String'); } if (data.hasOwnProperty('Type')) { obj['Type'] = _SpotInstanceType["default"].constructFromObject(data['Type']); } if (data.hasOwnProperty('ValidFrom')) { obj['ValidFrom'] = _ApiClient["default"].convertToType(data['ValidFrom'], 'Date'); } if (data.hasOwnProperty('ValidUntil')) { obj['ValidUntil'] = _ApiClient["default"].convertToType(data['ValidUntil'], 'Date'); } } return obj; } }]); return RequestSpotInstancesRequest; }(); /** * @member {String} AvailabilityZoneGroup */ RequestSpotInstancesRequest.prototype['AvailabilityZoneGroup'] = undefined; /** * @member {Number} BlockDurationMinutes */ RequestSpotInstancesRequest.prototype['BlockDurationMinutes'] = undefined; /** * @member {String} ClientToken */ RequestSpotInstancesRequest.prototype['ClientToken'] = undefined; /** * @member {Boolean} DryRun */ RequestSpotInstancesRequest.prototype['DryRun'] = undefined; /** * @member {Number} InstanceCount */ RequestSpotInstancesRequest.prototype['InstanceCount'] = undefined; /** * @member {module:model/InstanceInterruptionBehavior} InstanceInterruptionBehavior */ RequestSpotInstancesRequest.prototype['InstanceInterruptionBehavior'] = undefined; /** * @member {String} LaunchGroup */ RequestSpotInstancesRequest.prototype['LaunchGroup'] = undefined; /** * @member {module:model/RequestSpotLaunchSpecification} LaunchSpecification */ RequestSpotInstancesRequest.prototype['LaunchSpecification'] = undefined; /** * @member {String} SpotPrice */ RequestSpotInstancesRequest.prototype['SpotPrice'] = undefined; /** * @member {module:model/SpotInstanceType} Type */ RequestSpotInstancesRequest.prototype['Type'] = undefined; /** * @member {Date} ValidFrom */ RequestSpotInstancesRequest.prototype['ValidFrom'] = undefined; /** * @member {Date} ValidUntil */ RequestSpotInstancesRequest.prototype['ValidUntil'] = undefined; var _default = RequestSpotInstancesRequest; exports["default"] = _default;
1.296875
1
微信脚本/今日头条极速版.js
ouwen000/auto.js
8
15996244
function click_(x,y){ if(x>0 && x < device.width && y > 0 && y < device.height){ click(x,y) }else{ log('坐标错误') } } function click__(obj){ click_(obj.bounds().centerX(),obj.bounds().centerY()) } function jsclick(way,txt,clickKey,n){ if(!n){n=1};//当n没有传值时,设置n=1 var res = false; if(!clickKey){clickKey=false}; //如果没有设置点击项,设置为false if (way == "text"){ res = text(txt).findOne(200); }else if(way == "id"){ res = id(txt).findOne(200); }else if(way == "desc"){ res = desc(txt).findOne(200); } if(res){ if ( clickKey ){ log('准备点击->',txt,"x:",res.bounds().centerX(),"y:",res.bounds().centerY()); click_(res.bounds().centerX(),res.bounds().centerY()); sleep(1000*n); }else{ log("找到->",txt); } return true; }else{ // log("没有找到->",txt) } } function download () { var url_s = "img.wenfree.cn/apk/jrttjsb.apk"; app.openUrl(url_s); var data_frequency = 0; while(data_frequency <= 180 ){ if(jsclick("text","普通下载",true,2)){ }else if(jsclick("text","安装",true,2)){ }else if(jsclick("text","立即下载",true,2)){ }else if(jsclick("text","确定",true,2)){ }else if(jsclick("text","仅允许一次",true,2)){ }else if(jsclick("text","完成",true,2)){ return true; }else{ jsclick("text","允许",true,2); jsclick("text","授权",true,2); } data_frequency++; sleep(1000); } } function remove_Sms(){ var storage = storages.read(); storage.remove("sms"); } function get_PhoneNumber(){ var storage = storages.read(); return storage.get("phoneNumber"); } function get_Sms(){ try { var storage = storages.read(); var res= storage.get("sms"); if (res){ remove_Sms(); var content = res.content; return content; } } catch (error) { } } function reg() { launchApp("今日头条极速版"); sleep(1000*6) var get_sms_button = true; var get_password = <PASSWORD>; var data_time_line = 0; while(data_time_line < 180){ var UI = currentActivity() log("UI->",UI) switch(UI){ case "com.ss.android.article.lite.activity.MainActivity": if (jsclick("text","点击登录",true,2)){ }else if(jsclick("text","登录领取32元红包",true,2) ){ }else if(jsclick("text","未登录",true,2)){ }else if(jsclick("text","我的",true,2)){ if (jsclick("text","提现兑换",false,2)){ var all_Info = className("TextView").find() if (all_Info){ for (var i = 0;i<all_Info.length;i++){ log(i,all_Info[i].text()) if (all_Info[i].text() == "元"){ var money = Number(all_Info[i-1].text()) var gold = Number(all_Info[i+2].text()) var gift = all_Info[i-3].text() log(money,gold,gift) info["money"]=money; info["gold"]=gold; info["gift"]=gift; break; } } } log("注册成功"); newsappinfoback(); return true } }else { var d = className("ImageView").findOne(200) if(d){ d.click() } back(); } break; case "com.ss.android.account.v2.view.AccountLoginActivity": if (jsclick("text","手机号",false,2)){ // var truePhone = "17775127804"; var truePhone = get_PhoneNumber(); if (truePhone){ text("手机号").findOne(1000).setText(truePhone); } }else if(jsclick("text","获取验证码",true,2)){ }else if(jsclick("text","请输入验证码",false,5)){ // var sms = "【今日头条极速版】验证码7435,用于手机登录,5分钟内有效.验证码提供给他人可能导致帐号被盗,请勿泄露,谨防被骗" var sms_ = get_Sms(); if (sms_){ var sms_ = sms_get_unmber(sms_); if (sms_){ setText(1,sms_) sleep(1000*2) sleep(1000*30) } }else{ sleep(1000*5) } }else{ jsclick("text","进入头条",true,5) } break; case "com.ss.android.article.base.feature.detail2.view.NewDetailActivity": log("判断错误") back(); sleep(1000); home(); break; default: back(); sleep(1000); home(); sleep(1000); launch(appBid); sleep(1000*5); jsclick("text","一键登录",true,2); break; } jsclick("text","允许",true,2) jsclick("text","好",true,2) data_time_line++; sleep(1000); } } function read(){ var loginKey = true var call_back_key = false var check_look = false var look_timesKey = 0 var look_times = 0 var look_news = 0 var zan = true var data_time_line = 0; while(data_time_line < 40){ var UI = currentActivity() log("UI->",UI,"data_time_line->",data_time_line) switch(UI){ case "com.ss.android.article.lite.activity.MainActivity": if( call_back_key && jsclick("text","我的",true,2)){ if (jsclick("text","提现兑换",false,2)){ var all_Info = className("TextView").find() if (all_Info){ for (var i = 0;i<all_Info.length;i++){ log(i,all_Info[i].text()) if (all_Info[i].text() == "元"){ var money = all_Info[i-1].text() var gold = all_Info[i+2].text() var gift = all_Info[i-3].text() log(money,gold,gift) info["money"]=money; info["gold"]=gold; info["gift"]=gift; break; } } } log("阅读完成"); return true } }else if(jsclick("text","首页",false,1)&& jsclick("text","我的",false,2)&&jsclick("text","推荐",true,5)){ if (random(1,100)> 50 ){ swipe(device.width/2,device.height*4/5,device.width/2,device.height*2/7,random(1200,2500)); }else{ swipe(device.width/2,device.height*4/5,device.width/2,device.height*2/7,random(1200,2500)); swipe(device.width/2,device.height*4/5,device.width/2,device.height*2/7,random(1200,2500)); } sleep(1000*3); var title = className("TextView").find(); if (title){ var title_times = 0 for (var i=0;i<title.length;i++){ log(i,title[i].text()) if (title[i].text().length > 15){ title_times++; if (title_times>2){ click(title[i].bounds().centerX(),title[i].bounds().centerY()); check_look = true; look_times = 0; look_timesKey = random(15,25); sleep(1000*random(3,5)); look_news++ break; } } sleep(50) } } sleep(1000*3) }else if(jsclick("text","首页",true,5)){ }else { var d = className("ImageView").findOne(200) if(d){ d.click() } back(); } break; case "com.ss.android.article.base.feature.detail2.view.NewDetailActivity": log("阅读文章"); if( check_look ){ if (look_times < look_timesKey){ if ( textMatches("/写评论.*/").findOne(200) ){ log("阅读文章","继续", look_timesKey-look_times ); if (random(1,100)> 50){ log("滑动1次") swipe(device.width/2,device.height*4/5,device.width/2,device.height*2/7,random(1000,3000)); }else{ log("滑动2次") swipe(device.width/2,device.height*4/5,device.width/2,device.height*2/7,random(1000,3000)); swipe(device.width/2,device.height*4/5,device.width/2,device.height*2/7,random(1000,3000)); } sleep(random(200,2000)); if (jsclick("text","已显示全部评论",false,2)){ back(); } look_times++; }else{ log("不是文章,退出"); back(); } }else{ log("阅读超时,退出"); back(); } }else{ log("非主动进入阅读,退出") back() } break; case "com.ss.android.article.base.feature.detail2.view.NewVideoDetailActivity": log("播放视频"); back(); break; case "com.ss.android.wenda.answer.list.AnswerListActivity": log("问答"); back(); break; default: back(); sleep(1000); launch(appBid); sleep(1000*5); break; } jsclick("text","允许",true,2) jsclick("text","好",true,2) data_time_line++; sleep(1000); } log("阅读完成,") } function money() { var money_times = 0; while(money_times < 60){ var UI = currentActivity() log("UI->",UI) switch(UI){ case "com.bytedance.polaris.browser.PolarisBrowserActivity": log("提现页面"); if (jsclick("text","输入提现账号",false,2)){ sleep(1000*2) setText(0,"文虹"); sleep(1000); setText(1,"<EMAIL>"); sleep(1000); jsclick("text","确认提现",true,2) }else if(jsclick("desc","立即提现",true,2)){ }else if(jsclick("text","立即提现",true,2)){ }else if(jsclick("text","提现成功",false,2)){ info["cash"] = 0.1 return true; }else if( jsclick("text","明天可再次提现",false,2) || jsclick("desc","明天可再次提现",false,2) ){ back(); sleep(1000); return false; }else{ if (jsclick("text",'提现',false,2) || jsclick("desc","马上邀请好友赚钱",false,2) ){ log("提现0.1"); click((507+934)/2,(934+1200)/2); sleep(1000*3); }else{ back(); sleep(1000); home(); } } break; case "com.ss.android.article.lite.activity.MainActivity": if (jsclick("text","点击登录",true,2)){ }else if(jsclick("text","登录领取32元红包",true,2) ){ }else if(jsclick("text","未登录",true,2)){ }else if(jsclick("text","我的",true,2)){ if (jsclick("text","提现兑换",false,2)){ var all_Info = className("TextView").find() if (all_Info){ for (var i = 0;i<all_Info.length;i++){ log(i,all_Info[i].text()) if (all_Info[i].text() == "元"){ var money = Number(all_Info[i-1].text()) var gold = Number(all_Info[i+2].text()) var gift = all_Info[i-3].text() log(money,gold,gift) info["money"]=money; info["gold"]=gold; info["gift"]=gift; break; } } } log("注册成功"); // return true } if (!jsclick("text","提现兑换",true,5)){ back(); sleep(1000); home(); } }else { var d = className("ImageView").findOne(200) if(d){ d.click() } back(); } break; case "com.ss.android.article.base.feature.detail2.view.NewDetailActivity": log("判断错误"); back(); sleep(1000); home(); break; default: back(); sleep(1000); launch(appBid); sleep(1000*5); break; } jsclick("text","允许",true,2); jsclick("text","好",true,2); money_times++; sleep(1000); } } function sendBroadcast(appName,data){ app.launchPackage( "com.flow.factory"); sleep(2000) var mapObject = { appName:appName, data:data } app.sendBroadcast( { packageName: "com.flow.factory", className: "com.flow.factory.trafficfactory.broadcast.TaskBroadCast", extras:mapObject } ); } function sms_get_unmber(sms){ var check_sms = sms.match(/\【今日头条极速版\】/) log(check_sms) if(check_sms[0]== "【今日头条极速版】"){ sms = sms.match(/\d{4,6}/) log(sms[0]) return sms[0] } } var appName = "今日头条极速版"; var appBid = "com.ss.android.article.lite"; var info={}; function main(){ if (launchApp("今日头条极速版") ){ if (reg()){ log(info) log(JSON.stringify(info)) read() reg() money() sendBroadcast("今日头条极速版",JSON.stringify(info)) }else{ sendBroadcast("今日头条极速版",JSON.stringify(info)) } }else if ( download() ){ if (reg()){ sendBroadcast("今日头条极速版",JSON.stringify(info)) }else{ sendBroadcast("今日头条极速版",JSON.stringify(info)) } } } log(currentActivity()) // var title = textMatches(/.*/).find(); // if (title){ // for (var i=0;i<title.length;i++){ // log(i,title[i].text()) // } // } function newsappinfoback(){ try{ var url = "http://news.wenfree.cn/phalapi/public/"; r = http.post(url, { "s": "App.Newsimeiapp.Imei", "imei": device.getIMEI(), "imei_tag": 'pixel xl', "app_name": appName, "app_data": JSON.stringify(info), "whos": 'ouwen000', }); return r.body.string(); }catch(err){ toastLog(err); } } // money() main(); // reg(); var all_Info = textMatches(/.*/).find(); for (var i = 0;i<all_Info.length;i++){ // log(i,all_Info[i].text(),all_Info[i].depth()) } var d = text('搜索').findOne() if(d){ log(d.text(),d.bounds().centerY()) var y = d.bounds().centerY(); if (y > 0 && y < device.height){ log('文章拉到底了') }else if(y < 0){ log('进入推荐区或者评论区') } } sleep(1000*2)
1.695313
2
complex/esbuild/lib/664.js
jackypan1989/js-bundler-comparison
2
15996252
(() => { // src/664.js var __default = example = 0; })();
0.168945
0
test/ut/compiler.js
nakamura-to/deku
1
15996260
TestCase('compiler', { 'setUp': function () { this.parser = deku.internal.parser; this.compiler = deku.internal.compiler; this.templateContext = { escape: deku.internal.core.escape, compile: deku.internal.core.compile, handleBlock: deku.internal.core.handleBlock, handleInverse: deku.internal.core.handleInverse, handlePartial: deku.internal.core.handlePartial, values: {}, partials: {}, templates: {}, processors: {}, prePipeline : deku.prePipeline, postPipeline: deku.postPipeline, noSuchValue: deku.noSuchValue, noSuchPartial: deku.noSuchPartial, noSuchProcessor: deku.noSuchProcessor, partialResolver: deku.partialResolver }; }, 'test Compiler: name': function () { var ast = this.parser.parse('{{hoge}}'); var compiler = new this.compiler.Compiler(); var env = compiler.compile(ast); assertSame(13, env.opcodes.length); assertSame('op_lookupHead', env.opcodes[0]); assertSame('hoge', env.opcodes[1]); assertSame('value', env.opcodes[2]); assertSame('default', env.opcodes[3]); assertSame('0', env.opcodes[4]); assertSame('op_evaluateValue', env.opcodes[5]); assertSame('hoge', env.opcodes[6]); assertSame('op_applyPrePipeline', env.opcodes[7]); assertSame('hoge', env.opcodes[8]); assertSame('op_applyPostPipeline', env.opcodes[9]); assertSame('hoge', env.opcodes[10]); assertSame('op_escape', env.opcodes[11]); assertSame('op_append', env.opcodes[12]); }, 'test Compiler: name: processor': function () { var ast = this.parser.parse('{{hoge|aaa}}'); var compiler = new this.compiler.Compiler(); var env = compiler.compile(ast); assertSame(21, env.opcodes.length); assertSame('op_lookupHead', env.opcodes[0]); assertSame('hoge', env.opcodes[1]); assertSame('value', env.opcodes[2]); assertSame('default', env.opcodes[3]); assertSame('0', env.opcodes[4]); assertSame('op_evaluateValue', env.opcodes[5]); assertSame('hoge', env.opcodes[6]); assertSame('op_applyPrePipeline', env.opcodes[7]); assertSame('hoge', env.opcodes[8]); assertSame('op_lookupHead', env.opcodes[9]); assertSame('aaa', env.opcodes[10]); assertSame('processor', env.opcodes[11]); assertSame('default', env.opcodes[12]); assertSame('0', env.opcodes[13]); assertSame('op_applyProcessor', env.opcodes[14]); assertSame('aaa', env.opcodes[15]); assertSame('hoge', env.opcodes[16]); assertSame('op_applyPostPipeline', env.opcodes[17]); assertSame('hoge', env.opcodes[18]); assertSame('op_escape', env.opcodes[19]); assertSame('op_append', env.opcodes[20]); }, 'test Compiler: name: multi processors': function () { var ast = this.parser.parse('{{hoge|aaa|bbb}}'); var compiler = new this.compiler.Compiler(); var env = compiler.compile(ast); assertSame(29, env.opcodes.length); assertSame('op_lookupHead', env.opcodes[0]); assertSame('hoge', env.opcodes[1]); assertSame('value', env.opcodes[2]); assertSame('default', env.opcodes[3]); assertSame('0', env.opcodes[4]); assertSame('op_evaluateValue', env.opcodes[5]); assertSame('hoge', env.opcodes[6]); assertSame('op_applyPrePipeline', env.opcodes[7]); assertSame('hoge', env.opcodes[8]); assertSame('op_lookupHead', env.opcodes[9]); assertSame('aaa', env.opcodes[10]); assertSame('processor', env.opcodes[11]); assertSame('default', env.opcodes[12]); assertSame('0', env.opcodes[13]); assertSame('op_applyProcessor', env.opcodes[14]); assertSame('aaa', env.opcodes[15]); assertSame('hoge', env.opcodes[16]); assertSame('op_lookupHead', env.opcodes[17]); assertSame('bbb', env.opcodes[18]); assertSame('processor', env.opcodes[19]); assertSame('default', env.opcodes[20]); assertSame('0', env.opcodes[21]); assertSame('op_applyProcessor', env.opcodes[22]); assertSame('bbb', env.opcodes[23]); assertSame('hoge', env.opcodes[24]); assertSame('op_applyPostPipeline', env.opcodes[25]); assertSame('hoge', env.opcodes[26]); assertSame('op_escape', env.opcodes[27]); assertSame('op_append', env.opcodes[28]); }, 'test Compiler: name: pathSegments': function () { var ast = this.parser.parse('{{aaa.bbb.ccc}}'); var compiler = new this.compiler.Compiler(); var env = compiler.compile(ast); assertSame(19, env.opcodes.length); assertSame('op_lookupHead', env.opcodes[0]); assertSame('aaa', env.opcodes[1]); assertSame('value', env.opcodes[2]); assertSame('default', env.opcodes[3]); assertSame('0', env.opcodes[4]); assertSame('op_lookupTail', env.opcodes[5]); assertSame('bbb', env.opcodes[6]); assertSame('value', env.opcodes[7]); assertSame('op_lookupTail', env.opcodes[8]); assertSame('ccc', env.opcodes[9]); assertSame('value', env.opcodes[10]); assertSame('op_evaluateValue', env.opcodes[11]); assertSame('aaa.bbb.ccc', env.opcodes[12]); assertSame('op_applyPrePipeline', env.opcodes[13]); assertSame('aaa.bbb.ccc', env.opcodes[14]); assertSame('op_applyPostPipeline', env.opcodes[15]); assertSame('aaa.bbb.ccc', env.opcodes[16]); assertSame('op_escape', env.opcodes[17]); assertSame('op_append', env.opcodes[18]); }, 'test Compiler: block': function () { var ast = this.parser.parse('{{#hoge}}abc{{/hoge}}'); var compiler = new this.compiler.Compiler(); var env = compiler.compile(ast); var descendant; assertSame(2, env.context.all.length); assertSame(env, env.context.all[0]); assertSame(14, env.opcodes.length); assertSame('op_lookupHead', env.opcodes[0]); assertSame('hoge', env.opcodes[1]); assertSame('value', env.opcodes[2]); assertSame('default', env.opcodes[3]); assertSame('0', env.opcodes[4]); assertSame('op_evaluateValue', env.opcodes[5]); assertSame('hoge', env.opcodes[6]); assertSame('op_applyPrePipeline', env.opcodes[7]); assertSame('hoge', env.opcodes[8]); assertSame('op_applyPostPipeline', env.opcodes[9]); assertSame('hoge', env.opcodes[10]); assertSame('op_invokeProgram', env.opcodes[11]); assertSame('program1', env.opcodes[12]); assertSame('op_append', env.opcodes[13]); descendant = env.context.all[1]; assertSame(2, descendant.opcodes.length); assertSame('op_appendContent', descendant.opcodes[0]); assertSame('abc', descendant.opcodes[1]); }, 'test Compiler: block: sibling': function () { var ast = this.parser.parse('{{#hoge}}abc{{/hoge}}{{#foo}}def{{/foo}}'); var compiler = new this.compiler.Compiler(); var env = compiler.compile(ast); var descendant; assertSame(3, env.context.all.length); assertSame(env, env.context.all[0]); assertSame(28, env.opcodes.length); assertSame('op_lookupHead', env.opcodes[0]); assertSame('hoge', env.opcodes[1]); assertSame('value', env.opcodes[2]); assertSame('default', env.opcodes[3]); assertSame('0', env.opcodes[4]); assertSame('op_evaluateValue', env.opcodes[5]); assertSame('hoge', env.opcodes[6]); assertSame('op_applyPrePipeline', env.opcodes[7]); assertSame('hoge', env.opcodes[8]); assertSame('op_applyPostPipeline', env.opcodes[9]); assertSame('hoge', env.opcodes[10]); assertSame('op_invokeProgram', env.opcodes[11]); assertSame('program1', env.opcodes[12]); assertSame('op_append', env.opcodes[13]); assertSame('op_lookupHead', env.opcodes[14]); assertSame('foo', env.opcodes[15]); assertSame('value', env.opcodes[16]); assertSame('default', env.opcodes[17]); assertSame('0', env.opcodes[18]); assertSame('op_evaluateValue', env.opcodes[19]); assertSame('foo', env.opcodes[20]); assertSame('op_applyPrePipeline', env.opcodes[21]); assertSame('foo', env.opcodes[22]); assertSame('op_applyPostPipeline', env.opcodes[23]); assertSame('foo', env.opcodes[24]); assertSame('op_invokeProgram', env.opcodes[25]); assertSame('program2', env.opcodes[26]); assertSame('op_append', env.opcodes[27]); descendant = env.context.all[1]; assertSame(2, descendant.opcodes.length); assertSame('op_appendContent', descendant.opcodes[0]); assertSame('abc', descendant.opcodes[1]); descendant = env.context.all[2]; assertSame(2, descendant.opcodes.length); assertSame('op_appendContent', descendant.opcodes[0]); assertSame('def', descendant.opcodes[1]); }, 'test Compiler: block: nesting': function () { var ast = this.parser.parse('{{#hoge}}abc{{#foo}}def{{/foo}}ghi{{/hoge}}'); var compiler = new this.compiler.Compiler(); var env = compiler.compile(ast); var descendant; assertSame(3, env.context.all.length); assertSame(env, env.context.all[0]); assertSame(14, env.opcodes.length); assertSame('op_lookupHead', env.opcodes[0]); assertSame('hoge', env.opcodes[1]); assertSame('value', env.opcodes[2]); assertSame('default', env.opcodes[3]); assertSame('0', env.opcodes[4]); assertSame('op_evaluateValue', env.opcodes[5]); assertSame('hoge', env.opcodes[6]); assertSame('op_applyPrePipeline', env.opcodes[7]); assertSame('hoge', env.opcodes[8]); assertSame('op_applyPostPipeline', env.opcodes[9]); assertSame('hoge', env.opcodes[10]); assertSame('op_invokeProgram', env.opcodes[11]); assertSame('program1', env.opcodes[12]); assertSame('op_append', env.opcodes[13]); descendant = env.context.all[1]; assertSame(18, descendant.opcodes.length); assertSame('op_appendContent', descendant.opcodes[0]); assertSame('abc', descendant.opcodes[1]); assertSame('op_lookupHead', descendant.opcodes[2]); assertSame('foo', descendant.opcodes[3]); assertSame('value', descendant.opcodes[4]); assertSame('default', descendant.opcodes[5]); assertSame('0', descendant.opcodes[6]); assertSame('op_evaluateValue', descendant.opcodes[7]); assertSame('foo', descendant.opcodes[8]); assertSame('op_applyPrePipeline', descendant.opcodes[9]); assertSame('foo', descendant.opcodes[10]); assertSame('op_applyPostPipeline', descendant.opcodes[11]); assertSame('foo', descendant.opcodes[12]); assertSame('op_invokeProgram', descendant.opcodes[13]); assertSame('program2', descendant.opcodes[14]); assertSame('op_append', descendant.opcodes[15]); assertSame('op_appendContent', descendant.opcodes[16]); assertSame('ghi', descendant.opcodes[17]); descendant = env.context.all[2]; assertSame(2, descendant.opcodes.length); assertSame('op_appendContent', descendant.opcodes[0]); assertSame('def', descendant.opcodes[1]); }, 'test Compiler: inverse': function () { var ast = this.parser.parse('{{^hoge}}abc{{/hoge}}'); var compiler = new this.compiler.Compiler(); var env = compiler.compile(ast); assertSame(2, env.context.all.length); assertSame(env, env.context.all[0]); assertSame(14, env.opcodes.length); assertSame('op_lookupHead', env.opcodes[0]); assertSame('hoge', env.opcodes[1]); assertSame('value', env.opcodes[2]); assertSame('default', env.opcodes[3]); assertSame('0', env.opcodes[4]); assertSame('op_evaluateValue', env.opcodes[5]); assertSame('hoge', env.opcodes[6]); assertSame('op_applyPrePipeline', env.opcodes[7]); assertSame('hoge', env.opcodes[8]); assertSame('op_applyPostPipeline', env.opcodes[9]); assertSame('hoge', env.opcodes[10]); assertSame('op_invokeProgramInverse', env.opcodes[11]); assertSame('program1', env.opcodes[12]); assertSame('op_append', env.opcodes[13]); }, 'test Compiler: content': function () { var ast = this.parser.parse('hoge'); var compiler = new this.compiler.Compiler(); var env = compiler.compile(ast); assertSame(2, env.opcodes.length); assertSame('op_appendContent', env.opcodes[0]); assertSame('hoge', env.opcodes[1]); }, 'test Compiler: comment': function () { var ast = this.parser.parse('{{! comment }}'); var compiler = new this.compiler.Compiler(); var env = compiler.compile(ast); assertSame(0, env.opcodes.length); }, 'test JsCompiler: asString: spike': function () { var ast = this.parser.parse('{{#hoge}}{{test.aaa}}{{#foo}}bar{{/foo}}{{/hoge}}'); var compiler = new this.compiler.Compiler(); var environment = compiler.compile(ast); var jsCompiler = new this.compiler.JsCompiler(environment); var result = jsCompiler.compile(true); assertNotUndefined(result); console.log(result); }, 'test compile: tag': function () { var fn = this.compiler.compile('{{name}}'); var data = {name: 'hoge'}; var result = fn.call(this.templateContext, data, [data]); assertSame('hoge', result); }, 'test compile: tag: pathSegments': function () { var fn = this.compiler.compile('{{aaa.bbb.ccc}}'); var data = {aaa: {bbb: {ccc: 'hoge'}}}; var result = fn.call(this.templateContext, data, [data]); assertSame('hoge', result); }, 'test compile: tag: pathSegments: function': function () { var fn = this.compiler.compile('{{aaa.bbb.getName}}'); var data = { name: 'data', aaa: { name: 'aaa', bbb: { name: 'bbb', getName: function () { return this.name; } } } }; var result = fn.call(this.templateContext, data, [data]); assertSame('bbb', result); }, 'test compile: tag: escape': function () { var fn = this.compiler.compile('{{name}}'); var data = {name: '<div>"aaa"</div>'}; var result = fn.call(this.templateContext, data, [data]); assertSame('&lt;div&gt;&quot;aaa&quot;&lt;/div&gt;', result); }, 'test compile: tag: unescape': function () { var fn = this.compiler.compile('{{{name}}}'); var data = {name: '<div>"aaa"</div>'}; var result = fn.call(this.templateContext, data, [data]); assertSame('<div>"aaa"</div>', result); }, 'test compile: content': function () { var fn = this.compiler.compile('abc'); var data = {}; var result = fn.call(this.templateContext, data, [data]); assertSame('abc', result); }, 'test compile: content: quotation': function () { var fn = this.compiler.compile('\\"\n\r\\"\n\r'); var data = {}; var result = fn.call(this.templateContext, data, [data]); assertSame('\\"\n\r\\"\n\r', result); }, 'test compile: content: escape sequence': function () { var fn = this.compiler.compile('\n\t\b\r\f\v\b\\\'\"\x10\u1234'); var data = {}; var result = fn.call(this.templateContext, data, [data]); assertSame('\n\t\b\r\f\v\b\\\'\"\x10\u1234', result); }, 'test compile: block: @root': function () { var fn = this.compiler.compile( [ '{{#container1}}', '{{#container2}}', '{{#container3}}{{@root.container1.name}}-{{name}}{{/container3}}', '{{/container2}}', '{{/container1}}' ].join('') ); var data = { container1: { name: 'c1', container2: { container3: { name: 'c3' } } } }; var result = fn.call(this.templateContext, data, [data]); assertSame('c1-c3', result); }, 'test compile: block: @parent': function () { var fn = this.compiler.compile( [ '{{#container1}}', '{{#container2}}', '{{#container3}}{{@parent.name}}-{{name}}{{/container3}}', '{{/container2}}', '{{/container1}}' ].join('') ); var data = { container1: { name: 'c1', container2: { name: 'c2', container3: { name: 'c3' } } } }; var result = fn.call(this.templateContext, data, [data]); assertSame('c2-c3', result); }, 'test compile: block: contextIndex': function () { var fn = this.compiler.compile( [ '{{#container1}}', '{{#container2}}', '{{#container3}}{{@2.name}}-{{@1.name}}-{{@0.name}}-{{name}}{{/container3}}', '{{/container2}}', '{{/container1}}' ].join('') ); var data = { container1: { name: 'c1', container2: { name: 'c2', container3: { name: 'c3' } } } }; var result = fn.call(this.templateContext, data, [data]); assertSame('c1-c2-c3-c3', result); }, 'test compile: block: array': function () { var fn = this.compiler.compile('{{#array}}{{name}}-{{/array}}'); var data = {array: [{name:'aaa'},{name:'bbb'}]}; var result = fn.call(this.templateContext, data, [data]); assertSame('aaa-bbb-', result); }, 'test compile: block: array: @this': function () { var fn = this.compiler.compile('{{#array}}{{@this}}-{{/array}}'); var data = {array: ['aaa', 'bbb']}; var result = fn.call(this.templateContext, data, [data]); assertSame('aaa-bbb-', result); }, 'test compile: block: array: @index': function () { var fn = this.compiler.compile('{{#array}}{{@this}}{{@index}}-{{/array}}'); var data = {array: ['aaa', 'bbb']}; var result = fn.call(this.templateContext, data, [data]); assertSame('aaa0-bbb1-', result); }, 'test compile: block: array: @hasNext': function () { var fn = this.compiler.compile('{{#array}}{{@this}}{{#@hasNext}}-{{/@hasNext}}{{/array}}'); var data = {array: ['aaa', 'bbb']}; var result = fn.call(this.templateContext, data, [data]); assertSame('aaa-bbb', result); }, 'test compile: block: array: @length': function () { var fn = this.compiler.compile('{{#array}}{{@this}}({{@index}}:{{@length}}){{/array}}'); var data = {array: ['aaa', 'bbb']}; var result = fn.call(this.templateContext, data, [data]); assertSame('aaa(0:2)bbb(1:2)', result); }, 'test compile: block: array: @root': function () { var fn = this.compiler.compile( [ '{{#container1}}', '{{#container2}}', '{{#array}}{{@root.container1.name}}({{name}})-{{/array}}', '{{/container2}}', '{{/container1}}' ].join('') ); var data = { container1: { name: 'c1', container2: { array: [{name:'aaa'},{name:'bbb'}] } } }; var result = fn.call(this.templateContext, data, [data]); assertSame('c1(aaa)-c1(bbb)-', result); }, 'test compile: block: array: @parent': function () { var fn = this.compiler.compile( [ '{{#container1}}', '{{#container2}}', '{{#array}}{{@parent.name}}({{name}})-{{/array}}', '{{/container2}}', '{{/container1}}' ].join('') ); var data = { container1: { name: 'c1', container2: { name: 'c2', array: [{name:'aaa'},{name:'bbb'}] } } }; var result = fn.call(this.templateContext, data, [data]); assertSame('c2(aaa)-c2(bbb)-', result); }, 'test compile: block: function: truthy': function () { var fn = this.compiler.compile('{{#fn}}{{name}}{{/fn}}'); var data = {name: 'aaa', fn: function () { return true; }}; var result = fn.call(this.templateContext, data, [data]); assertSame('aaa', result); }, 'test compile: block: function: falsy': function () { var fn = this.compiler.compile('{{#fn}}{{name}}{{/fn}}'); var data = {name: 'aaa', fn: function () { return false; }}; var result = fn.call(this.templateContext, data, [data]); assertSame('', result); }, 'test compile: block: boolean: true': function () { var fn = this.compiler.compile('{{#bool}}{{name}}{{/bool}}'); var data = {name: 'aaa', bool: true}; var result = fn.call(this.templateContext, data, [data]); assertSame('aaa', result); }, 'test compile: block: boolean: false': function () { var fn = this.compiler.compile('{{#bool}}{{name}}{{/bool}}'); var data = {name: 'aaa', bool: false}; var result = fn.call(this.templateContext, data, [data]); assertSame('', result); }, 'test compile: inverse: boolean: true': function () { var fn = this.compiler.compile('{{^bool}}{{name}}{{/bool}}'); var data = {name: 'aaa', bool: true}; var result = fn.call(this.templateContext, data, [data]); assertSame('', result); }, 'test compile: inverse: boolean: false': function () { var fn = this.compiler.compile('{{^bool}}{{name}}{{/bool}}'); var data = {name: 'aaa', bool: false}; var result = fn.call(this.templateContext, data, [data]); assertSame('aaa', result); }, 'test compile: inverse: empty array': function () { var fn = this.compiler.compile('{{^array}}{{name}}{{/array}}'); var data = {name: 'aaa', array: []}; var result = fn.call(this.templateContext, data, [data]); assertSame('aaa', result); }, 'test compile: partial': function () { var fn = this.compiler.compile('{{name}} | {{:link}}'); var data = {name:'foo', url: '/hoge', title: 'HOGE'}; var result; this.templateContext.partials.link = '{{url}} : {{title}}'; result = fn.call(this.templateContext, data); assertSame('foo | /hoge : HOGE', result); }, 'test compile: partial: context': function () { var fn = this.compiler.compile('{{name}} | {{:link link}}'); var data = {name:'foo', link: {url: '/hoge', title: 'HOGE'}}; var result; this.templateContext.partials.link = '{{url}} : {{title}}'; result = fn.call(this.templateContext, data, [data]); assertSame('foo | /hoge : HOGE', result); }, 'test compile: partial: index': function () { var fn = this.compiler.compile('{{name}} | {{:link link}}'); var data = {name:'foo', link: {url: '/hoge', title: 'HOGE'}}; var result; this.templateContext.partials.link = '{{url}} : {{title}}, {{@index}}'; result = fn.call(this.templateContext, data, [data], 10); assertSame('foo | /hoge : HOGE, 10', result); }, 'test compile: partial: hasNext': function () { var fn = this.compiler.compile('{{name}} | {{:link link}}'); var data = {name:'foo', link: {url: '/hoge', title: 'HOGE'}}; var result; this.templateContext.partials.link = '{{url}} : {{title}}, {{@hasNext}}'; result = fn.call(this.templateContext, data, [data], 10, true); assertSame('foo | /hoge : HOGE, true', result); }, 'test compile: partial: length': function () { var fn = this.compiler.compile('{{name}} | {{:link link}}'); var data = {name:'foo', link: {url: '/hoge', title: 'HOGE'}}; var result; this.templateContext.partials.link = '{{url}} : {{title}}, {{@length}}'; result = fn.call(this.templateContext, data, [data], 10, true, 20); assertSame('foo | /hoge : HOGE, 20', result); }, 'test parse: error': function () { try { this.compiler.parse('{{#aaa}}bbb'); fail(); } catch (e) { assertEquals('Error', e.name); assertEquals('Expected \"\\\\\", \"{{!\", \"{{\", \"{{#\", \"{{/\", \"{{:\", \"{{^\", \"{{{\" or any character but end of input found. line=1. column=12.\n{{#aaa}}bbb', e.message); } } });
1.382813
1
src/tools/tools.js
Yang-Header/node_backServer
0
15996268
const MongoClient = require('mongodb').MongoClient; // Connection URL const url = 'mongodb://localhost:27017'; // Database Name const dbName = '2018-07-10'; //封装共有的,只在此页面使用 const template = (collections,callback) => { MongoClient.connect(url,{ useNewUrlParser: true } , function(err, client) { // const db = client.db(dbName); //获取文档集 const collection = db.collection(collections); callback(collection,client) }) } exports.findOne=(collections,data,callback)=>{ MongoClient.connect(url,{ useNewUrlParser: true } , function(err, client) { // const db = client.db(dbName); //获取文档集 const collection = db.collection(collections); collection.findOne({username:data.username,password:<PASSWORD>},(err,docs)=>{ callback(err,docs) client.close() }) }) } //函数封装 const functi = (collections,callback)=>{ MongoClient.connect(url,{ useNewUrlParser: true } , function(err, client) { // const db = client.db(dbName); //获取文档集 const collection = db.collection(collections); callback(client,collection) }) } exports.findOneWithInsertOne = (collections,data,callback) => { template(collections,) collection.findOne({username:data.username},(err,docs)=>{ client.close() callback(err,docs) }) } //插入新用户 exports.insertInfo=(collections,data,callback) => {//参一与参二为型参, template(collections,(collection,client)=>{ collection.insertOne({username:data.username,password:data.password},(err,data)=>{ client.close() callback(err,data) }) }) }
1.710938
2
public/swagger-editor-helper/helper.js
phwoolcon/swagger-editor-helper
0
15996276
!function (w, d) { d.addEventListener("DOMContentLoaded", function () { var editorElement = d.getElementById("swagger-editor"); if (!editorElement) { return; } function toggleEditor(show) { editorElement.classList[show ? "remove" : "add"]("hide-editor"); w.localStorage.setItem("swagger-editor", show ? "on" : "off"); } function initialToggleButton() { var editBar = d.querySelector("#swagger-editor .topbar-wrapper"), emptyHref = "javascript:", previewBar, logoLink, previewButton, editButton; previewBar = d.createElement("div"); previewButton = d.createElement("div"); editButton = d.createElement("div"); editBar.classList.add("edit-menu"); editBar.parentNode.appendChild(previewBar); editBar.appendChild(previewButton); previewBar.className = "topbar-wrapper preview-menu"; logoLink = d.createElement("a"); previewBar.appendChild(logoLink); previewBar.appendChild(editButton); logoLink.className = "link"; logoLink.href = emptyHref; logoLink.innerHTML = d.querySelector(".edit-menu .link").innerHTML; previewButton.className = "dd-menu dd-menu-right button"; previewButton.innerHTML = "Preview"; previewButton.addEventListener("click", function () { toggleEditor(false); }); editButton.className = "dd-menu dd-menu-right button"; editButton.innerHTML = "Edit"; editButton.addEventListener("click", function () { toggleEditor(true); }); } function waitForEditor() { if (d.querySelector(".topbar-wrapper .link")) { initialToggleButton(); } else { waitingCounter++; if (waitingCounter < 100) { setTimeout(waitForEditor, 20); } else { w.console && console.error("Swagger editor not ready"); } } } function foreach(list, callback) { [].forEach.call(list, callback); } // Set default status from local storage var currentStatus = (w.localStorage.getItem("swagger-editor") === "on"); toggleEditor(currentStatus); // Wait for the editor initialization // Sorry I don't know if there is any handlers provided by swagger, so I just wait for the editor object var waitingCounter = 0; waitForEditor(); }); }(window, document);
1.1875
1
lib/errors/DriveError.js
strophy/js-drive
19
15996284
class DriveError extends Error { /** * @param {string} message */ constructor(message) { super(message); this.name = this.constructor.name; Error.captureStackTrace(this, this.constructor); } /** * Get message * * @return {string} */ getMessage() { return this.message; } } module.exports = DriveError;
0.933594
1
src/containers/Skyscrapers/Map/__tests__/index.js
dadish/skyscrapers-app
9
15996292
import React from 'react'; import { List } from 'immutable'; import { shallow } from 'enzyme'; import { SkyMap as SkyscrapersMap} from '../'; const props = { list: new List(), } test('renders without errors!', () => { shallow(<SkyscrapersMap {...props} />); });
1.117188
1
src/LoginButton.js
En-crypto/Forex-Hub-front
0
15996300
import React from 'react'; import Button from 'react-bootstrap/Button'; import { useAuth0 } from '@auth0/auth0-react'; import './css/App.css'; function LoginButton() { const { isAuthenticated, loginWithRedirect, } = useAuth0(); return !isAuthenticated && ( <Button onClick={loginWithRedirect} className = 'mybtn' variant = ''>Log in</Button> ); } export default LoginButton;
1.03125
1
rollup.config.js
AndrewGibson27/react-fixed-youtube
1
15996308
/* eslint-disable @typescript-eslint/camelcase */ // inspired by https://github.com/reduxjs/redux/blob/master/rollup.config.js import nodeResolve from 'rollup-plugin-node-resolve'; import typescript from 'rollup-plugin-typescript2'; import commonjs from 'rollup-plugin-commonjs'; import { terser } from 'rollup-plugin-terser'; import postcss from 'rollup-plugin-postcss'; import pkg from './package.json'; export default [ // CommonJS { input: 'src/index.tsx', output: { file: 'lib/rytf.js', format: 'cjs', indent: false }, external: [ ...Object.keys(pkg.dependencies || {}), ...Object.keys(pkg.peerDependencies || {}), ], plugins: [ typescript(), postcss({ extract: true, minimize: true, }), ], }, // ES { input: 'src/index.tsx', output: { file: 'es/rytf.js', format: 'es', indent: false }, external: [ ...Object.keys(pkg.dependencies || {}), ...Object.keys(pkg.peerDependencies || {}), ], plugins: [ typescript(), postcss({ extract: true, minimize: true, }), ], }, // ES for browsers { input: 'src/index.tsx', output: { file: 'es/rytf.mjs', format: 'es', indent: false, globals: { react: 'React', 'react-dom': 'ReactDOM' }, }, plugins: [ nodeResolve({ extensions: ['.mjs', '.js', '.jsx', '.json'], }), typescript({ exclude: 'node_modules/**', }), commonjs({ namedExports: { 'node_modules/react/index.js': [ 'React', 'createContext', 'useState', 'useRef', 'useEffect', ], 'node_modules/react-dom/index.js': ['render'], }, }), terser({ compress: { pure_getters: true, unsafe: true, unsafe_comps: true, warnings: false, }, }), postcss({ extract: true, minimize: true, }), ], }, // UMD production { input: 'src/index.tsx', output: { file: 'dist/rytf.min.js', format: 'umd', name: 'ReactFixedYouTube', indent: false, globals: { react: 'React', 'react-dom': 'ReactDOM' }, }, external: [...Object.keys(pkg.peerDependencies || {})], plugins: [ nodeResolve({ extensions: ['.mjs', '.js', '.jsx', '.json'], }), typescript({ exclude: 'node_modules/**', }), terser({ compress: { pure_getters: true, unsafe: true, unsafe_comps: true, warnings: false, }, }), postcss({ extract: true, minimize: true, }), ], }, ];
1.023438
1
bench/greatMathBenchWorker.js
mmomtchev/jeetah
1
15996316
const path = require('path'); const b = require('benny'); const jeetah = require('../lib'); const fns = require('./greatMathBenchFns'); const { workerData } = require('worker_threads'); const { type, size, fnNum } = workerData; const allocator = global[type + 'Array']; const expr = jeetah[type + 'Expression']; const array = new allocator(size); // array goes from -5.0 to +5.0 for (let i = 0; i < array.length; i++) array[i] = -5 + 10 * (i / (array.length - 1)); const fn = fns[fnNum]; // target array allocation is not included // benny takes care of precompiling the functions const r = new allocator(size); b.suite( `${fn.toString()}, map() ${type} arrays of ${size} elements`, b.add(`V8 for loop w/precompilation`, () => { // this is a workaround for a major V8 deficiency: // recompilation of mutable functions // once V8 inlines a function, it cannot recompile it const params = { fn, size, array, r }; const bench = new Function('params', `{ // This is the bench const { fn, size, array, r } = params; for (let j = 0; j < size; j++) r[j] = fn(array[j]); }`).bind(null, params); // run the test return bench; }), b.add(`V8 naive for loop`, () => { // run the test return () => { // This is the bench for (let j = 0; j < size; j++) r[j] = fn(array[j]); }; }), b.add(`V8 map()`, () => { // run the test return () => { // This is the bench array.map((v, j) => r[j] = fn(array[j])); }; }), b.add(`V8 forEach()`, () => { // run the test return () => { // This is the bench array.forEach((v, j) => r[j] = fn(array[j])); }; }), b.add(`jeetah map()`, () => { const e = new expr(fn); return () => { // This is the bench e.map(array, 'x', r); }; }), b.cycle(), b.complete(), b.save({ file: `00greatMathBench-${fnNum}`, folder: path.resolve(__dirname, '..', 'gh-pages', 'bench', size.toString()), version: require('../package.json').version, details: false, format: 'chart.html', }) );
2.09375
2
frontend/src/components/user-settings/list-in-address-book.js
weimens/seahub
420
15996324
import React from 'react'; import { gettext } from '../../utils/constants'; class ListInAddressBook extends React.Component { constructor(props) { super(props); const { list_in_address_book } = this.props.userInfo; this.state = { inputChecked: list_in_address_book }; } handleInputChange = (e) => { const checked = e.target.checked; this.setState({ inputChecked: checked }); this.props.updateUserInfo({ list_in_address_book: checked.toString() }); } render() { const { inputChecked } = this.state; return ( <div className="setting-item" id="list-in-address-book"> <h3 className="setting-item-heading">{gettext('Global Address Book')}</h3> <div className="d-flex align-items-center"> <input type="checkbox" id="list-in-address-book" name="list_in_address_book" className="mr-1" checked={inputChecked} onChange={this.handleInputChange} /> <label htmlFor="list-in-address-book" className="m-0">{gettext('List your account in global address book, so that others can find you by typing your name.')}</label> </div> </div> ); } } export default ListInAddressBook;
1.828125
2
index.js
lvlrSajjad/react-native-expandable-fab-menu
9
15996332
import React, {Component} from 'react'; import {Animated, StyleSheet, View, TouchableOpacity, Dimensions, ImageBackground, Image} from 'react-native'; let {width} = Dimensions.get('window'); export class ExpandableFabMenu extends Component { constructor(props) { super(props); this.state = { open: false, offsetY: new Animated.Value(100), fadeIn: new Animated.Value(0), leftOffsetX: new Animated.Value(-40), rightOffsetX: new Animated.Value(40), leftFarOffsetX: new Animated.Value(-80), rightFarOffsetX: new Animated.Value(80) }; openFab = openFab.bind(this); closeFab = closeFab.bind(this); } render() { return ( <View style={styles.container}> {(this.state.open && this.props.menuIcons[3] !== null && this.props.menuIcons[3] !== undefined) ? <Animated.View style={{ opacity: this.state.fadeIn, transform: [{translateX: this.state.leftFarOffsetX}], width: 50, height: 50, }}> <ImageBackground style={{ alignSelf: 'center', width: 48, height: 48, alignItems: 'center', justifyContent: 'center', margin: 4 }} source={require('./shadow.png')} > <TouchableOpacity onPress={() => this.props.menuItemClicked(3)} style={styles.mediumButton}> {this.props.menuIcons[3]} </TouchableOpacity> </ImageBackground> </Animated.View> : <View style={{ width: 50, height: 50, }}/> } {(this.state.open && this.props.menuIcons[1] !== null && this.props.menuIcons[1] !== undefined) ? <Animated.View style={{ opacity: this.state.fadeIn, transform: [{translateX: this.state.leftOffsetX}], width: 50, height: 50, marginTop: 32 }}> <ImageBackground style={{ alignSelf: 'center', width: 48, height: 48, alignItems: 'center', justifyContent: 'center', margin: 4 }} source={require('./shadow.png')} > <TouchableOpacity onPress={() => this.props.menuItemClicked(1)} style={[styles.mediumButton]}> {this.props.menuIcons[1]} </TouchableOpacity> </ImageBackground> </Animated.View> : <View style={{ width: 50, height: 50, }}/> } < ImageBackground style={{ alignSelf: 'center', width: 70, height: 70, alignItems: 'center', justifyContent: 'center', margin: 4, marginTop: 50 }} source={require('./shadow.png')} > <TouchableOpacity onPress={() => { if (this.state.open) { closeFab() } else { openFab() } }} style={styles.mainButton}> {this.state.open ? this.props.openIcon : this.props.closeIcon} </TouchableOpacity> </ImageBackground> {(this.state.open && this.props.menuIcons[0] !== null && this.props.menuIcons[0] !== undefined) ? <Animated.View style={{ opacity: this.state.fadeIn, transform: [{translateX: this.state.rightOffsetX}], width: 50, height: 50, marginTop: 32 }}> <ImageBackground style={{ alignSelf: 'center', width: 48, height: 48, alignItems: 'center', justifyContent: 'center', margin: 4 }} source={require('./shadow.png')} > <TouchableOpacity onPress={() => this.props.menuItemClicked(0)} style={[styles.mediumButton]}> {this.props.menuIcons[0]} </TouchableOpacity> </ImageBackground> </Animated.View> : <View style={{ width: 50, height: 50, }}/> } {(this.state.open && this.props.menuIcons[2] !== null && this.props.menuIcons[2] !== undefined) ? <Animated.View style={{ opacity: this.state.fadeIn, transform: [{translateX: this.state.rightFarOffsetX}], width: 50, height: 50, }}> <ImageBackground style={{ alignSelf: 'center', width: 48, height: 48, alignItems: 'center', justifyContent: 'center', margin: 4 }} source={require('./shadow.png')} > <TouchableOpacity onPress={() => this.props.menuItemClicked(2)} style={styles.mediumButton}> {this.props.menuIcons[2]} </TouchableOpacity> </ImageBackground> </Animated.View> : <View style={{ width: 50, height: 50, }}/> } </View> ); } } const styles = StyleSheet.create({ container: { position: 'absolute', width: width, height: 100, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', bottom: 24 }, mainButton: { width: 64, height: 64, borderRadius: 32, elevation: 16, backgroundColor: 'white', borderWidth: 0.5, borderColor: '#d4d4d4', zIndex: 999, alignItems: 'center', justifyContent: 'center' }, mediumButton: { width: 42, height: 42, borderRadius: 21, elevation: 16, backgroundColor: 'white', borderWidth: 0.5, borderColor: '#d4d4d4', margin: 4, alignItems: 'center', justifyContent: 'center' }, mediumMarginTop: {marginTop: 32} }); export function openFab() { this.setState({open: true}, () => { Animated.parallel([ Animated.timing( this.state.fadeIn, { toValue: 1, duration: 500, useNativeDriver: true } ), Animated.timing( this.state.rightOffsetX, { toValue: 0, duration: 300, useNativeDriver: true } ), Animated.timing( this.state.leftOffsetX, { toValue: 0, duration: 300, useNativeDriver: true } ), Animated.timing( this.state.rightFarOffsetX, { toValue: 0, duration: 300, useNativeDriver: true } ), Animated.timing( this.state.leftFarOffsetX, { toValue: 0, duration: 300, useNativeDriver: true } ) ]).start(); }); } export function closeFab() { Animated.parallel([ Animated.timing( this.state.fadeIn, { toValue: 0, duration: 500, useNativeDriver: true } ), Animated.timing( this.state.rightOffsetX, { toValue: 40, duration: 300, useNativeDriver: true } ), Animated.timing( this.state.leftOffsetX, { toValue: -40, duration: 300, useNativeDriver: true } ), Animated.timing( this.state.rightFarOffsetX, { toValue: 80, duration: 300, useNativeDriver: true } ), Animated.timing( this.state.leftFarOffsetX, { toValue: -80, duration: 300, useNativeDriver: true } ) ]).start(() => this.setState({open: false})); }
1.546875
2
app/schema/autoreply-compiled.js
supperbowen/bw-wechat-mgr
0
15996340
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _require = require('mongoose'), Schema = _require.Schema; var _ = require('lodash'); var _require2 = require('./baseSchema'), baseSchema = _require2.schema; var schema = new Schema(_.extend({ name: String, message: String, replyDate: Date, isReplied: Boolean }, baseSchema)); exports.schema = schema; //# sourceMappingURL=autoreply-compiled.js.map
0.992188
1