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
src/client/assets/javascripts/app/store/configureStore.production.js
alanszp/ticker
0
15993116
import {createStore, applyMiddleware, compose} from 'redux'; import promiseMiddleware from 'redux-promise'; import createSagaMiddleware from 'redux-saga' import rootReducer from '../reducer'; import rootSaga from '../saga' const sagaMiddleware = createSagaMiddleware(); const middlewares = [promiseMiddleware, sagaMiddleware]; const enhancer = compose( applyMiddleware(...middlewares) )(createStore); sagaMiddleware.run(rootSaga); export default function configureStore(initialState) { return enhancer(rootReducer, initialState); }
1.015625
1
src/process/example01.js
arki7n/nodejs-certification
232
15993124
/** * Description: Use beforeExit event for get when event loop has no additional work to schedule. */ /** Require generics dependences */ import 'pretty-console-colors'; process.on('beforeExit', (code) => { console.log('Process beforeExit event with code: ', code); }); process.on('exit', (code) => { console.log('Process exit event with code: ', code); }); console.log('Hi from NodeJS... go to run a setTimeout'); // Define timeout for show while console. setTimeout(() => { let i = 0; while (i <= 1000) { console.log(i); i += 1; } }, 0);
1.734375
2
SmartClient_v111p_2018-06-28_LGPL/smartclientSDK/isomorphic/system/reference/inlineExamples/grids/layout/columnHeaders.js
krisleonard-mcafee/opendxl-console
13
15993132
isc.ListGrid.create({ ID: "countryList", width:500, height:232, alternateRecordStyles:true, data: countryData, fields:[ {name:"countryCode", title:"Flag", width:50, type:"image", imageURLPrefix:"flags/16/", imageURLSuffix:".png"}, {name:"countryName", title:"Country"}, {name:"capital", title:"Capital"}, {name:"continent", title:"Continent"} ], headerHeight: 30, showHeader: false }) isc.IButton.create({ left:0, top:250, title:"Show header", click:"countryList.setShowHeader(true);" }) isc.IButton.create({ left:130, top:250, title:"Hide header", click:"countryList.setShowHeader(false);" })
1.1875
1
routes/middlewares.js
kshirish/Bookmark
0
15993140
const jwt = require('jsonwebtoken'); module.exports = (router, app) => { router.use(function(req, res, next) { const token = req.body.token || req.param('token') || req.headers['x-access-token']; if (token) jwt.verify(token, app.get('superSecret'), function(err, decoded) { if (err) { return res.status(400).json({ message: 'Failed to authenticate token.' }); } else { req.decoded = decoded; next(); } }); else return res.status(403).json({ message: 'No token provided.' }); }); };
1.296875
1
app/scripts/services/Task.js
nehemiahnewell/Blocitoff
0
15993148
/*global angular*/ /*global firebase*/ (function() { function Task($firebaseArray) { var ref = firebase.database().ref().child("task"); var task_holder = $firebaseArray(ref); return { getTasks: function () { var tasks = $firebaseArray(ref); return tasks; }, getFreshTasks: function () { var last_week = Date.now() - 604800000; var fresh = ref.orderByChild("sentAt").startAt(last_week); var tasks = $firebaseArray(fresh); return tasks; }, getOldTasks: function () { var last_week = Date.now() - 604800000; var old = ref.orderByChild("sentAt").endAt(last_week); var tasks = $firebaseArray(old); return tasks; }, send: function(postContent, postPriority) { task_holder.$add({ content: postContent, priority: postPriority, sentAt: Date.now()}); } }; } angular .module('toDoDestroy') .factory('Task', ['$firebaseArray', Task]); })();
1.484375
1
test/test.js
matjaz/upnqr
6
15993156
const { encode, decode } = require('../lib/upnqr') const assert = require('assert') const describe = require('mocha').describe const it = require('mocha').it const upn = `UPNQR <NAME> Ljubljanska cesta 1 1000 MARIBOR 00000008588 COST Pl<NAME> št. 9990029934988 20.02.2021 SI56029220020148350 SI129990029934988 SPL d.d. Frankopanska ul. 18a 1000 LJUBLJANA 205 ` describe('Test encoding and decoding', () => { it('encoded value and original UPN code should be identical', () => { const encoded = encode(decode(upn)) assert.strictEqual(encoded, upn) }) })
1.164063
1
packages/core/tests/unit/components/pick-inner-component-test.js
Ruiqian1/navi
0
15993164
import { module, test } from 'qunit'; import { setupTest } from 'ember-qunit'; module('Unit | Component | pick inner component', function(hooks) { setupTest(hooks); test('componentName must be defined', function(assert) { assert.expect(2); assert.throws( () => { this.owner.factoryFor('component:pick-inner-component').create(); }, new Error('Assertion Failed: componentName property must be defined'), 'pick-inner-component throws error when used without extending' ); this.owner.factoryFor('component:pick-inner-component').create({ componentName: 'my-fancy-component', _updateTarget() {} // Mock this to isolate test }); assert.ok(true, 'No error is thrown when component is extended with a new componentName'); }); });
1.265625
1
src/components/Layout/index.js
kgritesh/personal-site
0
15993172
import React from 'react'; import { StaticQuery, graphql, Link } from 'gatsby'; import { MDXProvider } from '@mdx-js/react'; import Footer from '../Footer'; import mdxComponents from '../Mdx'; import { StyledLayout, StyledCrumb, GlobalStyle } from './styles'; import UpdatePrompt from '../UpdatePrompt'; const renderBreadcrumb = (pathname) => { // TODO: refactor this! const parts = pathname.match(/[^\/]+/g); const crumbs = [<Link to={'/'}>Home /</Link>]; let link = '/'; for (let i = 0; i < parts.length - 1; ++i) { link = link + parts[i] + '/'; crumbs.push(<Link to={link}>{` ${parts[i]} /`}</Link>); } return ( <div> {crumbs.map((crumb, index) => ( <span key={index}>{crumb}</span> ))} </div> ); }; const Layout = ({ children, title, location }) => { const rootPath = `${__PATH_PREFIX__}/`; let header; if (location && location.pathname === rootPath) { header = ( <div> <h1 className="headline"><NAME></h1> <h2 className="description">Problem Solver | Engineering Leader | 2x Entrepreneur</h2> </div> ); } else { header = <StyledCrumb>{renderBreadcrumb(location.pathname)}</StyledCrumb>; } return ( <React.Fragment> <StyledLayout isIndex={location.pathname === rootPath}> <GlobalStyle /> {header} <MDXProvider components={mdxComponents}> <React.Fragment>{children}</React.Fragment> </MDXProvider> </StyledLayout> {location.pathname !== rootPath && <Footer />} <UpdatePrompt /> </React.Fragment> ); }; export default Layout;
1.5625
2
artifact_evaluation/data/codeCoverage/comfort_generate/134.js
weucode/COMFORT
55
15993180
var NISLFuzzingFunc = function(t, e) { var r; var n = r.substitute("M {x1} {y1} L{x2} {y2}Z", t); return r.addClass(e, n), t.path = n, t; }; var NISLParameter0 = 0; var NISLParameter1 = undefined; NISLFuzzingFunc(NISLParameter0, NISLParameter1);
0.652344
1
src/shared/reducers/marketData.js
verdipratama/trinity-wallet
514
15993188
import { MarketDataActionTypes } from '../types'; import { availableCurrencies } from '../libs/currency'; const initialState = { /** * Price data points for mapping on chart */ chartData: {}, /** * Market cap */ mcap: '0', /** * Total amount traded over twenty four hours */ volume: '0', /** * Percentage of change in IOTA price over twenty four hours */ change24h: '0.00', /** * USD equivalent price of IOTA token */ usdPrice: 0, /** * Euro equivalent price of IOTA token */ eurPrice: 0, /** * Bitcoin equivalent price of IOTA token */ btcPrice: 0, /** * Ethereum equivalent price of IOTA token */ ethPrice: 0, /** * Exchange rates */ rates: availableCurrencies, }; const marketData = (state = initialState, action) => { switch (action.type) { case MarketDataActionTypes.SET_PRICE: return { ...state, usdPrice: action.usd, eurPrice: action.eur, btcPrice: action.btc, ethPrice: action.eth, }; case MarketDataActionTypes.SET_STATISTICS: return { ...state, mcap: action.mcap, volume: action.volume, change24h: action.change24h, }; case MarketDataActionTypes.SET_CHART_DATA: return { ...state, chartData: action.chartData, }; case MarketDataActionTypes.SET_RATES_DATA: return { ...state, rates: action.payload, }; default: return state; } }; export default marketData;
1.390625
1
front-end/src/components/MyItems.js
lailaarkadan/front-end-1
0
15993196
import React, { useState, useEffect } from 'react'; import styled from 'styled-components'; import axiosWithAuth from '../utils/axiosWithAuth'; import { useHistory, useParams } from 'react-router-dom'; const MyItems = () => { const [items, setItems ] = useState([]); const { push } = useHistory(); const { item_id } = useParams(); useEffect(() => { axiosWithAuth() .get('/api/items/') .then(resp => { console.log(resp.data); setItems(resp.data); }) .catch(err => { console.log(err); }) }, []); const deleteItem = (item_id ) => { setItems(items.filter(item =>(item.item_id !== Number(item_id)))); } const handleDelete = (item_id) => { axiosWithAuth() .delete(`/api/items/${item_id}`) .then(resp => { deleteItem(item_id); push('/my-items'); }) .catch(err => { console.log(err); }) } const handleAdd = () => { push('/create-item'); } return ( <ComponentContainer> <h1>My Items</h1> <div className='body'> <div > <button className='button' onClick={() => {handleAdd()}}>Add New Item</button> </div> <div className='all-items'> { items.map(item => { return ( <div className='item' key={item.item_id}> {/* <img alt='' src={item.img}/> */} <h2>{item.item_name}</h2> <h3>Category: {item.item_category}</h3> <h3>Price: ${item.item_price}</h3> <p>Description: {item.item_description}</p> <button onClick={() => {handleDelete(item.item_id)}}>Delete</button> </div> ) }) } </div> </div> </ComponentContainer> ) } export default MyItems; const ComponentContainer = styled.div` background-color: #386FA4; display: flex; flex-direction: column; align-items: center; justify-content: center; margin: auto; font-family: 'Roboto Mono', monospace; font-size: 1rem; font-weight: 400; font-style: normal; text-decoration: none; min-width: 100%; min-height: 100vh; border: 1px solid black; h1{ font-size: 60px; font-weight: 400; padding: 20px; margin: auto; width: 100%; color: white; align-items: center; } h2 { text-decoration: underline; } p{ color: white; font-weight: bold; font-size: 1rem; } .all-items{ display: flex; flex-direction: row; flex-wrap: wrap; justify-content: center; width: 80%; } .item{ border: 1px black solid; display: flex; flex-direction: column; flex-wrap: wrap; justify-content: flex-start; align-items: center; margin: 10px; padding: 20px; width: 25%; background-color: #84D2F6; } img{ width: 100px; height: 100px; border: #386FA4 solid 1px; } button { border-radius: 10%; font-size: 1rem; } .body { display: flex; flex-direction: column; justify-content: center; align-items: center; margin: auto; } .button{ min-width: 130px; height: 40px; color: #133C55; padding: 5px 10px; font-size: 2rem; font-weight: bold; cursor: pointer; transition: all 0.3s ease; position: relative; display: inline-block; outline: none; border-radius: 5px; border: none; background: #F4B860; box-shadow: 0 5px #ffd819; margin-bottom: 40px; } .button:hover { box-shadow: 0 3px #ffd819; top: 1px; } .button:active { box-shadow: 0 0 #ffd819; top: 5px; } `
1.632813
2
test/helpers/jquery_remove.js
pri2si17/ui-layout
316
15993204
'use strict'; /* global jQuery */ var _jQuery = jQuery.noConflict(true);
0.24707
0
templates/includes/assert-error.js
generate/generate-mocha
10
15993212
it('should throw an error when invalid args are passed', function() { assert.throws(function() { <%= camelcase(alias) %>(); }); });
0.84375
1
src/components/notes/NoteDetail.js
jessyhalife/evernote-clone
0
15993220
import React from "react"; import { useSelector } from "react-redux"; import { useFirestoreConnect, isLoaded, isEmpty } from "react-redux-firebase"; import moment from "moment"; const NoteDetail = (props) => { const id = props.match.params.id; useFirestoreConnect([{ collection: "notes", doc: id }]); const note = useSelector( ({ firestore: { data } }) => data.notes && data.notes[id] ); const noteMarkup = !isLoaded(note) ? ( <div className="container section"> <div className="card z-depth-0"> <div className="card-content"> <span className="card-title"> <h5>Loading..</h5> </span> <div className="card-action grey lighten-4 grey-text"></div> </div> </div> </div> ) : isEmpty(note) ? ( <div className="container section"> <div className="card z-depth-0"> <div className="card-content"> <span className="card-title"> <h5>Not found</h5> </span> <div className="card-action grey lighten-4 grey-text"></div> </div> </div> </div> ) : ( <div className="container section"> <div className="card z-depth-0"> <div className="card-content"> <span className="card-title"> <h5>{note?.title}</h5> <p>{note?.content}</p> </span> <div className="card-action grey lighten-4 grey-text"> <div>{moment(note?.createdAt.toDate()).calendar()}</div> </div> </div> </div> </div> ); return noteMarkup ; }; export default NoteDetail;
1.507813
2
webextension-toolbox-config.js
kakunpc/slack-channels-grouping
0
15993228
const path = require('path'); const GlobEntriesPlugin = require('webpack-watched-glob-entries-plugin'); const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; module.exports = { webpack: (config, { dev, vendor }) => { const envName = dev ? 'development' : 'production'; config.resolve.extensions.push('.ts'); config.entry = GlobEntriesPlugin.getEntries( [ path.resolve('app', '*.{js,mjs,jsx,ts}'), path.resolve('app', '?(scripts)/*.{js,mjs,jsx,ts}') ] ); config.module.rules.push({ test: /\.ts$/, exclude: /node_modules/, use: [ { loader: 'babel-loader', options: { envName: envName } } ], }); config.plugins.push(new BundleAnalyzerPlugin({ openAnalyzer: false, analyzerMode: 'static', reportFilename: __dirname + '/storage/bundle-analyzer/' + vendor + '-' + envName + '.html' })); config.optimization.splitChunks = { name: 'scripts/vendor', chunks: 'initial', }; config.output.chunkFilename = '[name].js'; config.optimization.minimize = false; return config }, copyIgnore: [ '**/*.ts' ] };
1.171875
1
webapps/js/constants.js
maaxow/me-wedding
0
15993236
var deployPath = ""; var restPath = deployPath + "/rest"; angular.module('app').constant('CONSTANTS', { weddingDate: '06-29-2019' }) .constant('REST', { mailing_all : restPath + '/mailing', subscribe: restPath + '/mailing/subscribe', transaction: restPath + '/transaction', transactionAmount: restPath + '/transaction/total', reponse: restPath + '/reponse', message: restPath + '/message' } );
0.722656
1
routes/products.js
23carnies/MYM-BACKend
0
15993244
const router = require('express').Router(); const productsCtrl = require('../controllers/products'); // Public Routes router.get('/', productsCtrl.index); // Protected Routes router.use(require('../config/auth')); router.post('/:id', checkAuth, productsCtrl.create) router.get('/:id', checkAuth, productsCtrl.show) router.put('/:id/:storeId', checkAuth, productsCtrl.update); router.delete('/:storeId/:productId', checkAuth, productsCtrl.delete); function checkAuth(req, res, next) { if (req.user) return next(); return res.status(401).json({msg: 'Not Authorized'}); } module.exports = router;
1.265625
1
src/components/Header/Header.js
iamfrontender/resume
0
15993252
import React, { Component } from 'react'; import { findDOMNode } from 'react-dom'; import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment'; import styles from './Header.css'; import withStyles from '../../decorators/withStyles'; import withElements from '../../decorators/withElements'; import Link from '../Link'; import Navigation from '../Navigation'; import HttpClient from '../../core/HttpClient'; import ResizeManager from '../../core/ResizeManager'; import HeaderStore from '../../stores/HeaderStore'; import HeaderEvents from '../../constants/HeaderEvents'; /** * Header Component. */ @withStyles(styles) @withElements({ logo: '.Header__logo' }) class Header extends Component { /** * @constructor */ constructor(props) { super(props); this.state = { logo: <div>{props.logo}</div> }; } /** * Attaches required listeners and fetches the actual logo. * @see Component#componentDidMount */ componentDidMount() { this.listeners(); this.loadLogo(); } /** * Fetches the actual ascii logo text from an api. * Defines the available height for it. */ loadLogo() { HttpClient.get('/api/logo?text=' + this.props.logo) .then(res => this.setLogo(res.text)) .catch((e) => {}); } /** * Attaches required listeners. */ listeners() { HeaderStore.on(HeaderEvents.LOGO_RELOAD, this.loadLogo.bind(this)); ResizeManager.on('resize', this._resize.bind(this)); } /** * Sets the logo actual text, resizing it to the viewport. * * @param {String} text ascii figlet logo */ setLogo(text) { // For each row in original text will return a div // with row content with escaped spaces. var rows = text.split(/\n/).map(function(row, i) { return <pre dangerouslySetInnerHTML={{__html: row.replace(/\s/g, '&nbsp')}} key={"logo-row-" + i}></pre> }); this.setState({ logo: rows }, this._resize.bind(this)); } /** * Returns the supposed logo size. * * @returns {{height: number, width: number}} */ _getLogoRect() { let symbolRect = this._getSymbolSize(); return { // Simply count of rows multiplied by row's height height: symbolRect.height * this.logo.children.length, // The longest row width + additional 50px padding width: symbolRect.width * Math.max.apply(null, Array.from(this.logo.children).map(child => child.innerText.length ) ) + 50 }; } /** * Calculates the single ('W') symbol size, taking into account actual logo font * * @returns {ClientRect} */ _getSymbolSize() { var sample = document.createElement('span'); sample.innerHTML = 'W'; this.logo.appendChild(sample); var symbolRect = sample.getBoundingClientRect(); this.logo.removeChild(sample); return symbolRect; } /** * Resizes the logo to fit the current screen dimensions. */ _resize() { // Reset this.logo.style.transform = `scale(1)`; var scaleX, scaleY; var width = window.innerWidth; // Since the 'pre' makes children unshrinkable over its own // width even with content wider then themselves, we're need // to calculate the bounding rect using different approach var logoRect = this._getLogoRect(); var heightOffset = logoRect.height - this.props.maxHeight; var widthOffset = logoRect.width - width; if (heightOffset > 0 || widthOffset > 0) { scaleY = this.props.maxHeight / logoRect.height; scaleX = width / logoRect.width; var factor = scaleX > scaleY ? scaleY : scaleX; this.logo.style.transform = `scale(${factor})`; this.el.style.maxHeight = logoRect.height * factor + 'px'; } } /** * @see Component#render */ render() { return ( <div className="Header"> <section className="Header__logo">{this.state.logo}</section> </div> ); } } export default Header;
1.804688
2
web/src/modules/common/components/__tests__/Selector.spec.js
f1sh1918/integreat-app
0
15993260
// @flow import React from 'react' import { shallow } from 'enzyme' import Selector from '../Selector' import SelectorItemModel from '../../models/SelectorItemModel' const selectorItems = [ new SelectorItemModel({ code: 'en', href: '/augsburg/en/', name: 'English' }), new SelectorItemModel({ code: 'de', href: '/augsburg/de/', name: 'Deutsch' }), new SelectorItemModel({ code: 'fr', href: null, name: 'Französisch' }) ] describe('Selector', () => { it('should match snapshot', () => { const wrapper = shallow( <Selector verticalLayout={false} closeDropDown={() => {}} items={selectorItems} activeItemCode='de' disabledItemTooltip='random tooltip' /> ) expect(wrapper).toMatchSnapshot() }) it('should be vertical and match snapshot', () => { const wrapper = shallow( <Selector verticalLayout closeDropDown={() => {}} items={selectorItems} activeItemCode='de' disabledItemTooltip='random tooltip' /> ) expect(wrapper).toMatchSnapshot() }) })
1.453125
1
src/peripheral/create-peripheral.test.js
truthiswill/ble-midi
31
15993268
/* eslint-env jest */ jest.mock('bleno/lib/bleno', () => { const bleno = jest.fn(); bleno.on = jest.fn(); bleno.__mockBleno__ = true; return () => bleno; }); let createPeripheral; let mockBleno; beforeEach(() => { jest.resetAllMocks(); const Bleno = require('bleno/lib/bleno'); mockBleno = new Bleno(); createPeripheral = require('./create-peripheral').default; }); test('should createPeripheral(name)', () => { const name = jest.fn(); const peripheral = createPeripheral(name); expect(mockBleno.mock).toMatchSnapshot(); expect(mockBleno.on.mock).toMatchSnapshot(); expect(peripheral.__mockBleno__).toEqual(true); }); test('should createPeripheral(name, onIncomingPacket)', () => { const name = jest.fn(); const onIncomingPacket = jest.fn(); const peripheral = createPeripheral(name, onIncomingPacket); expect(mockBleno.mock).toMatchSnapshot(); expect(mockBleno.on.mock).toMatchSnapshot(); expect(peripheral.__mockBleno__).toEqual(true); }); test('should createPeripheral with default name', () => { const peripheral = createPeripheral(); expect(mockBleno.mock).toMatchSnapshot(); expect(mockBleno.on.mock).toMatchSnapshot(); expect(peripheral.__mockBleno__).toEqual(true); });
1.390625
1
server/routes/home.js
LuisAlavez183/fish-project-main
0
15993276
import { Router } from 'express'; //importo controlador Home import homeControllers from '@server/controllers/homeControllers'; //Creando la instancia de un router const router = new Router(); router.get(['/', '/index'], homeControllers.index); router.get('/Nosotros', homeControllers.Nosotros); router.get('/registro', homeControllers.registro); router.get('/Sesion', homeControllers.Sesion); router.get('/contacto', homeControllers.contacto); export default router;
0.917969
1
js-test-suite/testsuite/e747f04d1613b388d41e61a69b90db4f.js
hao-wang/Montage
16
15993284
function shouldBe(actual, expected) { if (actual !== expected) throw new Error(`bad value: ${String(actual)}`); } function shouldThrow(func, errorMessage) { var errorThrown = false; var error = null; try { func(); } catch (e) { errorThrown = true; error = e; } if (!errorThrown) throw new Error('not thrown'); if (String(error) !== errorMessage) throw new Error(`bad error: ${String(error)}`); } shouldThrow(() => { "Cocoa".search({ [Symbol.search]: 42 }); }, `TypeError: 42 is not a function`); shouldThrow(() => { "Cocoa".match({ [Symbol.match]: 42 }); }, `TypeError: 42 is not a function`); shouldThrow(() => { "Cocoa".search({ [Symbol.search]: {} }); }, `TypeError: Object is not a function`); shouldThrow(() => { "Cocoa".match({ [Symbol.match]: {} }); }, `TypeError: Object is not a function`); shouldBe("Cocoa".search({ [Symbol.search]: null, toString() { return "C" } }), 0); shouldBe("Cocoa".match({ [Symbol.match]: null, toString() { return "C" } })[0], "C"); shouldBe("Cocoa".search({ [Symbol.search]: undefined, toString() { return "C" } }), 0); shouldBe("Cocoa".match({ [Symbol.match]: undefined, toString() { return "C" } })[0], "C"); shouldBe("Cocoa".search({ [Symbol.search]() { return 42; } }), 42); shouldBe("Cocoa".match({ [Symbol.match]() { return 42; } }), 42); RegExp.prototype[Symbol.search] = function () { return 42; }; RegExp.prototype[Symbol.match] = function () { return 42; }; shouldBe("Cocoa".search({ [Symbol.search]: null }), 42); shouldBe("Cocoa".match({ [Symbol.match]: null }), 42); shouldBe("Cocoa".search({ [Symbol.search]: undefined }), 42); shouldBe("Cocoa".match({ [Symbol.match]: undefined }), 42);
1.710938
2
src/utils/colors.js
brg-ib/sunnyonv
0
15993292
export default { primaryColor: '#185ad2', darkPrimaryColor: '#1749a5', secondaryColor: '#2a9d8f', darkSecondaryColor: '#1c615a', black: '#000', white: '#fff', gray: '#9b9b9b', lightGray: '#d7d7d7', success: '#499149', successHover: '#6dbe6d', info: '#007bff', infoHover: '#009eff', warning: '#ffb802', warningHover: '#ffcd08', error: '#dc3545', errorHover: '#ff3445', descriptionColor: '#555', loaderBackground: '#e1e1e1' }
0.111816
0
app/components/secure/Members.js
gundlev/iungo-web
1
15993300
import React from 'react'; import Dropzone from 'react-dropzone'; import {parse} from 'papaparse'; import { Input, Button, Table } from 'react-toolbox'; import isEmail from 'validator/lib/isEmail'; class Members extends React.Component { state = { group_id: "forsam", //TODO TEMP source: [], selected: [], model: {Email: {type: String}, Navn: {type: String}}, name: "", email: "" }; shouldComponentUpdate(nextProps, nextState) { const keys = Object.keys(nextProps.groups); console.log("shouldComponentUpdate", ); return keys.indexOf(this.state.group_id) != -1; //&& nextState.group_id } componentDidUpdate(){ console.log("did update!") } onDrop = (files) => { parse(files[0], { header: true, skipEmptyLines: true, complete: ({data, meta}) => { const model = meta.fields.reduce((acc, key) => ({ [key]: {type: (typeof key)} , ...acc }), ({})); const source = [...data, ...this.state.source]; this.setState({ source, model }); const { members } = this.props.groups[this.state.group_id] // source.forEach( => ) } }); }; onInviteClick = () => { console.log("onInviteClick") }; handleChange(name, value){ this.setState({...this.state, [name]: value}); } handleSelect = (selected) => { this.setState({selected}); }; addToList = () => this.setState({ source: [ { Navn: this.state.name, Email: this.state.email } , ...this.state.source ], name: undefined, email: undefined }); componentWillReceiveProps(){ console.log("mount!") console.log(this.props.groups) } render(){ const {name, email} = this.state; console.log("state", this.state) return ( <div> <div> <Input type='text' label='Name' name='name' maxLength={16} onChange={this.handleChange.bind(this, 'name')} value={name} /> <Input type='email' label='Email' onChange={this.handleChange.bind(this, 'email')} value={email} /> <Button label="Add to list" onClick={this.addToList.bind(this)} raised primary disabled={!isValidInviteDetails(name, email)} /> </div> <div> <Dropzone accept=".csv" multiple={false} onDrop={this.onDrop}> <div style={{padding: 10}}> Drop a CSV file here or Click to select! </div> </Dropzone> { this.state.source.length ? <div> <Table model={this.state.model} onSelect={this.handleSelect} selectable selected={this.state.selected} source={this.state.source} /> <Button label="Send invitations" onClick={this.onInviteClick} raised primary disabled={this.state.selected.length === 0} /> </div> : <div> </div> } </div> </div> ) } } function isValidInviteDetails(name, email){ return (name && name.length > 1) && isEmail(email) } export default Members;
1.726563
2
test.js
michaelrhodes/u8a
1
15993308
var test = require('tape') var u8a = require('./from-string') var str = require('./to-string') var hex = require('./to-hex') test('it works', function (assert) { assert.deepEqual(u8a('hello'), new Uint8Array([104, 101, 108, 108, 111])) assert.equal(str(u8a('hello')), 'hello') assert.equal(hex(u8a('hello')), '68656c6c6f') assert.end() })
1.25
1
server-side-rendering/dist/server/sw.js
nearform/node-clinic-bubbleprof-examples
39
15993316
"use strict"; let version = 'VERSION'; workbox.setConfig({ debug: SW_DEBUG }); workbox.skipWaiting(); workbox.clientsClaim(); workbox.core.setCacheNameDetails({ prefix: 'hn-pwa', suffix: `v2.${version}`, precache: 'precache', runtime: 'runtime' }); // Application workbox.routing.registerRoute(/^\/images\/.*/, workbox.strategies.cacheFirst()); workbox.routing.registerRoute('/manifest.json', workbox.strategies.staleWhileRevalidate()); workbox.routing.registerRoute(/\/api\/.*/, workbox.strategies.networkFirst({ cacheName: `hn-pwa-api-v2.${version}` })); // Precaching workbox.precaching.precache(['/']); workbox.precaching.precacheAndRoute(self.__precacheManifest);
1.0625
1
test/unit/index.test.js
mjgs/internet-of-things-app
1
15993324
/* eslint-env mocha */ /* eslint-disable no-unused-expressions */ const debug = require('debug')('test:unit:index'); // eslint-disable-line no-unused-vars const expect = require('chai').expect; describe('testsuite', function() { it('should test that the unit tests suite is setup', function() { expect(true).to.be.true; }); });
0.972656
1
framework/test/mocha/integration/state_store/round_store.js
kplusq/lisk-sdk
1
15993332
/* * Copyright © 2019 Lisk Foundation * * See the LICENSE file at the top-level directory of this distribution * for licensing information. * * Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation, * no part of this software, including this file, may be copied, modified, * propagated, or distributed except according to the terms contained in the * LICENSE file. * * Removal or modification of this copyright notice is prohibited. */ 'use strict'; const BigNum = require('@liskhq/bignum'); const localCommon = require('../common'); const RoundStore = require('../../../../src/modules/chain/state_store/round_store.js'); describe('system test - round store', () => { let library; let roundStore; const roundInformation = { address: '1L', amount: '1000000000', delegatePublicKey: '12345', }; const voteTransaction = { id: '3729501093004464059', type: 3, timestamp: 1657012, senderPublicKey: '<KEY>', senderId: '10773624498522558426L', recipientId: '10773624498522558426L', recipientPublicKey: '<KEY>', amount: new BigNum('0'), fee: new BigNum('100000000'), signature: '8ac892e223db5cc6695563ffbbb13e86d099d62d41f86e8131f8a03082c51a3b868830a5ca4a60cdb10a63dc0605bf217798dfb00f599e37491b5e701f856704', signatures: [], asset: { votes: [ '+05e1ce75b98d6051030e4e416483515cf8360be1a1bd6d2c14d925700dae021b', ], }, }; localCommon.beforeBlock('round_state_store', lib => { library = lib; }); beforeEach(async () => { roundStore = new RoundStore(library.components.storage.entities.Round, { mutate: true, }); roundStore.add(roundInformation); }); describe('cache', () => { it('should throw ', async () => { return expect(roundStore.cache()).to.eventually.rejectedWith( 'cache cannot be called for round' ); }); }); describe('add', () => { it('should add round information to data', async () => { expect(roundStore.data[0]).to.eql(roundInformation); }); }); describe('createSnapshot', () => { it('should throw ', async () => { expect(roundStore.createSnapshot.bind(roundStore)).to.throw( 'createSnapshot cannot be called for round' ); }); }); describe('restoreSnapshot', () => { it('should throw ', async () => { expect(roundStore.restoreSnapshot.bind(roundStore)).to.throw( 'restoreSnapshot cannot be called for round' ); }); }); describe('get', () => { it('should throw ', async () => { expect(roundStore.get.bind(roundStore)).to.throw( 'get cannot be called for round' ); }); }); describe('getOrDefault', () => { it('should throw ', async () => { expect(roundStore.getOrDefault.bind(roundStore)).to.throw( 'getOrDefault cannot be called for round' ); }); }); describe('find', () => { it('should throw ', async () => { expect(roundStore.find.bind(roundStore)).to.throw( 'find cannot be called for round' ); }); }); describe('set', () => { it('should throw ', async () => { expect(roundStore.set.bind(roundStore)).to.throw( 'set cannot be called for round' ); }); }); describe('setRoundForData', () => { it('should set the round for round data', async () => { const round = 1000; roundStore.setRoundForData(round); expect(roundStore.data[0]).to.deep.equal({ ...roundInformation, round: 1000, }); }); }); describe('finalize', () => { beforeEach(async () => { roundStore.round.create = sinonSandbox.stub().resolves({ round: 1 }); roundStore = new RoundStore(library.components.storage.entities.Round, { tx: voteTransaction, }); }); it('should save the round state in the database', async () => { roundStore.add(roundInformation); await roundStore.finalize(); expect(roundStore.round.create).to.have.been.calledWithExactly( roundInformation, {}, voteTransaction ); }); }); });
1.476563
1
src/router/authHook.js
EmilyRosina/sedaily-front-end
0
15993340
import store from '../store' export default function beforeEnter (to, from, next) { return (!store.getters.isLoggedIn) ? next('/login') : next() }
0.691406
1
server/helpers/clearLogs.js
Tandoori-Momos/news-bias
0
15993348
process.env.NODE_ENV = 'maintainence' // Clear the winston logs to avoid large file sizes const fs = require('fs'); const path = require('path'); const logDir = path.join(__dirname, '../src/logs'); const logs = ['combined.log', 'error.log']; logs.forEach(function(log) { let logPath = path.join(logDir, log); fs.access(logPath, fs.constants.W_OK, (err) => { console.log(`${logPath} is ${err ? 'not writable' : 'opened'}`); try { // Clear out the log file fs.writeFile(logPath, '', (err) => { if (err) throw err; console.log(`${logPath} cleared!`) }); } catch (err) { console.error(`Error: ${err}`); } }); });
1.226563
1
src/imprint.test.processorCores.js
BitPerformance/imprintjs
87
15993356
(function(scope){ 'use strict'; imprint.registerTest("processorCores", function(){ return new Promise(function(resolve) { return resolve(navigator.hardwareConcurrency); }); }); })(window);
0.503906
1
src/lists/GatewayConsumer.js
bcgov/api-services-portal
1
15993364
const { Text, Checkbox, Relationship } = require('@keystonejs/fields'); const { Markdown } = require('@keystonejs/fields-markdown'); const { externallySourced } = require('../components/ExternalSource'); const { byTracking, atTracking } = require('@keystonejs/list-plugins'); const { EnforcementPoint } = require('../authz/enforcement'); const { lookupConsumerPlugins, lookupKongConsumerId, } = require('../services/keystone'); const { KongConsumerService } = require('../services/kong'); const { FeederService } = require('../services/feeder'); module.exports = { fields: { username: { type: Text, isRequired: true, isUnique: true, adminConfig: { isReadOnly: true, }, }, customId: { type: Text, isRequired: false, adminConfig: { isReadOnly: true, }, }, // kongConsumerId: { // type: Text, // isRequired: false, // adminConfig: { // isReadOnly: true // } // }, aclGroups: { type: Text, isRequired: false, adminConfig: { isReadOnly: true, }, }, namespace: { type: Text, isRequired: false, adminConfig: { isReadOnly: true, }, }, tags: { type: Text, isRequired: false, adminConfig: { isReadOnly: true, }, }, plugins: { type: Relationship, ref: 'GatewayPlugin', many: true }, }, access: EnforcementPoint, plugins: [externallySourced(), atTracking()], extensions: [ (keystone) => { keystone.extendGraphQLSchema({ queries: [ { schema: 'getGatewayConsumerPlugins(id: ID!): GatewayConsumer', resolver: async (item, args, context, info, { query, access }) => { const noauthContext = keystone.createContext({ skipAccessControl: true, }); return await lookupConsumerPlugins(noauthContext, args.id); }, access: EnforcementPoint, }, ], mutations: [ { schema: 'createGatewayConsumerPlugin(id: ID!, plugin: String!): GatewayConsumer', resolver: async (item, args, context, info, { query, access }) => { const kongApi = new KongConsumerService( process.env.KONG_URL, process.env.GWA_API_URL ); const feederApi = new FeederService(process.env.FEEDER_URL); const kongConsumerPK = await lookupKongConsumerId( context, args.id ); const result = await kongApi.addPluginToConsumer( kongConsumerPK, JSON.parse(args.plugin), context.req.user.namespace ); await feederApi.forceSync('kong', 'consumer', kongConsumerPK); return result; }, access: EnforcementPoint, }, { schema: 'updateGatewayConsumerPlugin(id: ID!, pluginExtForeignKey: String!, plugin: String!): GatewayConsumer', resolver: async (item, args, context, info, { query, access }) => { const noauthContext = keystone.createContext({ skipAccessControl: true, }); const kongApi = new KongConsumerService( process.env.KONG_URL, process.env.GWA_API_URL ); const feederApi = new FeederService(process.env.FEEDER_URL); const kongConsumerPK = await lookupKongConsumerId( context, args.id ); const result = await kongApi.updateConsumerPlugin( kongConsumerPK, args.pluginExtForeignKey, JSON.parse(args.plugin), context.req.user.namespace ); await feederApi.forceSync('kong', 'consumer', kongConsumerPK); return result; }, access: EnforcementPoint, }, { schema: 'deleteGatewayConsumerPlugin(id: ID!, pluginExtForeignKey: String!): GatewayConsumer', resolver: async (item, args, context, info, { query, access }) => { const noauthContext = keystone.createContext({ skipAccessControl: true, }); const kongApi = new KongConsumerService( process.env.KONG_URL, process.env.GWA_API_URL ); const feederApi = new FeederService(process.env.FEEDER_URL); const kongConsumerPK = await lookupKongConsumerId( context, args.id ); const result = await kongApi.deleteConsumerPlugin( kongConsumerPK, args.pluginExtForeignKey, context.req.user.namespace ); await feederApi.forceSync('kong', 'consumer', kongConsumerPK); return result; }, access: EnforcementPoint, }, ], }); }, ], };
1.257813
1
src/Navigation.js
397-F19/coffee-count
0
15993372
import React, { Component } from 'react'; import {Link} from 'react-router-dom'; import {BottomNavigation, BottomNavigationAction} from '@material-ui/core'; import DashboardIcon from '@material-ui/icons/BarChart'; import AddIcon from '@material-ui/icons/Add'; import HistoryIcon from '@material-ui/icons/AttachMoney'; import './App.css'; export class Navigation extends Component { render() { return ( <BottomNavigation value={this.props.value} onChange={this.props.handleChange} className="bottom-nav"> <BottomNavigationAction label="Dashboard" value="dash" component={Link} to="/dash" icon={<DashboardIcon />} /> <BottomNavigationAction value="add" disableRipple={true} onClick={this.props.toggleAdd} onClose={this.refocus} icon={<div className="center-fab">< AddIcon style={{ fontSize: 50 }}/></div>} /> <BottomNavigationAction label="Spending" value="history" component={Link} to="/history" icon={<HistoryIcon />} /> </BottomNavigation> ); } } export default Navigation;
1.414063
1
src/components/icons/Shuffle.js
emmanuelangelo/meta-sound
245
15993380
import React from 'react' const Shuffle = () => { return( <svg xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="0 0 512 512" space="preserve"> <g> <path fill="currentColor" d="M506.24,371.7l-96-80c-4.768-4-11.424-4.8-17.024-2.208c-5.632,2.656-9.216,8.288-9.216,14.496v48h-26.784 c-22.208,0-42.496-11.264-54.272-30.08l-103.616-165.76c-23.52-37.664-64.096-60.16-108.544-60.16H0v64h90.784 c22.208,0,42.496,11.264,54.272,30.08l103.616,165.76c23.552,37.664,64.128,60.16,108.544,60.16H384v48 c0,6.208,3.584,11.84,9.216,14.496c2.144,0.992,4.48,1.504,6.784,1.504c3.68,0,7.328-1.248,10.24-3.712l96-80 c3.68-3.04,5.76-7.552,5.76-12.288C512,379.252,509.92,374.74,506.24,371.7z"/> </g> <g> <path fill="currentColor" d="M506.24,115.7l-96-80c-4.768-3.968-11.424-4.8-17.024-2.176C387.584,36.116,384,41.78,384,47.988v48h-26.784 c-44.448,0-85.024,22.496-108.544,60.16l-5.792,9.28l37.728,60.384l22.336-35.744c11.776-18.816,32.064-30.08,54.272-30.08H384v48 c0,6.208,3.584,11.872,9.216,14.496c2.144,0.992,4.48,1.504,6.784,1.504c3.68,0,7.328-1.28,10.24-3.712l96-80 c3.68-3.04,5.76-7.552,5.76-12.288C512,123.252,509.92,118.74,506.24,115.7z"/> </g> <g> <path fill="currentColor" d="M167.392,286.164l-22.304,35.744c-11.776,18.816-32.096,30.08-54.304,30.08H0v64h90.784 c44.416,0,84.992-22.496,108.544-60.16l5.792-9.28L167.392,286.164z"/> </g> </svg> )} export default Shuffle
1.757813
2
modules/auth/actions/index.js
zmts/arma-api-nodejs
279
15993388
const { LoginAction } = require('./LoginAction') const { RefreshTokensAction } = require('./RefreshTokensAction') const { LogoutAction } = require('./LogoutAction') module.exports = { LoginAction, RefreshTokensAction, LogoutAction }
0.466797
0
documentation/structinp_1_1MeshDeck.js
nonlocalmodels/nonlocalmodels.github.io
0
15993396
var structinp_1_1MeshDeck = [ [ "MeshDeck", "structinp_1_1MeshDeck.html#ae13c4a396e6c20b2d1b2f1f917d09098", null ], [ "print", "structinp_1_1MeshDeck.html#aa00ff74d241c5569af82134db5248e28", null ], [ "printStr", "structinp_1_1MeshDeck.html#adf0249e67b8d4460afbb6235bb7ee55a", null ], [ "d_computeMeshSize", "structinp_1_1MeshDeck.html#a3ca449a9a104b0b75e559e6bd2c5e1de", null ], [ "d_dim", "structinp_1_1MeshDeck.html#ac43202a322edb1eeb2099699a7e1f002", null ], [ "d_filename", "structinp_1_1MeshDeck.html#aea7106cb8d2281466e07d7c83fff32b6", null ], [ "d_h", "structinp_1_1MeshDeck.html#a707e2499289b05aeec114430c8cb7df3", null ], [ "d_isCentroidBasedDiscretization", "structinp_1_1MeshDeck.html#a8542b167f24448877ad277f0adecd3ba", null ], [ "d_keepElementConn", "structinp_1_1MeshDeck.html#a003085e472d1b2d5f0a79393d76cbf4e", null ], [ "d_loadPUMData", "structinp_1_1MeshDeck.html#a39f61561b02630f519b3ebd38d17b881", null ], [ "d_spatialDiscretization", "structinp_1_1MeshDeck.html#a1361255b8d8b3f62e2aa54d160c631d0", null ] ];
0.382813
0
website/pages/en/index.js
MateusAndrade/react-ape
1,240
15993404
const React = require('react'); const CompLibrary = require('../../core/CompLibrary.js'); const MarkdownBlock = CompLibrary.MarkdownBlock; const Container = CompLibrary.Container; const GridBlock = CompLibrary.GridBlock; const siteConfig = require(`${process.cwd()}/siteConfig.js`); function imgUrl(img) { return `${siteConfig.baseUrl}img/${img}`; } function docUrl(doc, language) { return `${siteConfig.baseUrl}docs/${language ? `${language}/` : ''}${doc}`; } function pageUrl(page, language) { return siteConfig.baseUrl + (language ? `${language}/` : '') + page; } class Button extends React.Component { render() { return ( <div className="pluginWrapper buttonWrapper"> <a className="big-button" href={this.props.href} target={this.props.target}> {this.props.children} </a> </div> ); } } Button.defaultProps = { target: '_self', }; const SplashContainer = props => ( <div className="homeContainer"> <div className="homeSplashFade"> <div className="wrapper homeWrapper">{props.children}</div> </div> </div> ); const Logo = ({src}) => ( <div className="logo"> <img src={src} onError={() => {this.onerror=null; this.src=imgUrl('logo.png')}} alt="React Ape Logo" /> </div> ); const TagLine = () => (<div className='tagline'>Build apps using React Ape</div>); const PromoSection = props => ( <div className="section promoSection"> <div className="promoRow"> <div className="pluginRowBlock">{props.children}</div> </div> </div> ); class HomeSplash extends React.Component { render() { const language = this.props.language || ''; return ( <SplashContainer> <div className="inner"> <Logo src={imgUrl('logo.svg')}/> <TagLine /> <PromoSection> <Button href={docUrl('getting-started.html', language)}>Get Started</Button> <Button href={docUrl('components-and-apis.html', language)}>Learn the Basics</Button> </PromoSection> </div> </SplashContainer> ); } } const DefinitionCallout = () => ( <div className="paddingBottom"> <Container> <div className="blockElement"> <div className="blockContent"> <h1>Build UI interfaces using HTML5 Canvas/WebGL and React</h1> <p>React Ape lets you build Canvas apps using React. React Ape uses the same design as React, letting you compose a rich UI from declarative components.</p> <MarkdownBlock> {`\`\`\`javascript import React, { Component } from 'react'; import { Text, View } from 'react-ape'; class ReactApeComponent extends Component { render() { return ( <View> <Text> Render this text on Canvas </Text> <Text> You just use React Ape components like 'View' and 'Text', just like React Native. </Text> </View> ); } } \`\`\``} </MarkdownBlock> <br/> <br/> </div> </div> </Container> </div> ); const FirstFeatureCallout = () => ( <div className="container paddingBottom paddingTop lightBackground"> <div className="wrapper"> <div className="blockElement imageAlignSide imageAlignLeft twoByGridBlock"> <div className="blockImage"> <img src={imgUrl('learn-once.png')}/> </div> <div className="blockContent"> <h2>Learn Once, Write Anywhere</h2> <p>React Ape follow React Native's concept of "Learn Once Write Anywhere". So, if you have even a little bit of React experience you should be able to create things faster.</p> <p>Each platform have a different environment and look, with that in mind React Ape try to allow engineers to build applications for whatever platform they choose, without needing to learn a fundamentally different set of technologies for each.</p> </div> </div> </div> </div> ); const SecondFeatureCallout = () => ( <div className="container paddingBottom paddingTop"> <div className="wrapper"> <div className="blockElement imageAlignSide imageAlignRight twoByGridBlock"> <div className="blockContent"> <h2>Inspect and debug apps based on HTML5 Canvas using React Developer Tools</h2> <p>React Ape support in production and development environment you use the React Developer Tools, which is a tool that allows you to inspect a React tree, including the component hierarchy, props, state, and more.</p> </div> <div className="blockImage"> <img src={imgUrl('developer-tools.png')}/> </div> </div> </div> </div> ); const Showcase = props => { if ((siteConfig.users || []).length === 0) { return null; } const showcase = siteConfig.users.filter(user => user.pinned).map(user => ( <a href={user.infoLink} key={user.infoLink}> <img src={user.image} alt={user.caption} title={user.caption} /> </a> )); return ( <div className="productShowcaseSection paddingTop paddingBottom"> <h2>Who is Using This?</h2> <p>This project is used by all these people and companies</p> <div className="logos">{showcase}</div> <div className="more-users"> <a className="button" href={pageUrl('users.html', props.language)}> More {siteConfig.title} Users </a> </div> </div> ); }; const Examples = (props) => ( <div className="examplesSection"> <Container> <h1>Check some Examples using React Ape</h1> <p>Those are some examples of React Ape, but <a href="https://github.com/raphamorim/react-ape/issues/new" target="_blank">feel free to add an example.</a></p> <h2>Hello World:</h2> </Container> <div className="blockElement"> <div className="blockContent"> <iframe src="https://codesandbox.io/embed/zrqy570pjp?hidenavigation=1" style={{ width:'100%', height:'500px', border: 0, borderRadius: '4px', overflow: 'hidden' }} sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"></iframe> </div> </div> <Container> <h2>Netflix ListView:</h2> </Container> <div className="blockElement"> <div className="blockContent"> <iframe src="https://codesandbox.io/embed/2xzk61702r?hidenavigation=1" style={{ width:'100%', height:'500px', border: 0, borderRadius: '4px', overflow: 'hidden' }} sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"></iframe> </div> </div> </div> ) class Index extends React.Component { render() { const language = this.props.language || ''; return ( <div> <HomeSplash language={language} /> <div className="mainContainer"> <DefinitionCallout /> <FirstFeatureCallout /> <SecondFeatureCallout /> <Examples language={language} /> { /* <Showcase language={language} /> */ } </div> </div> ); } } module.exports = Index;
1.390625
1
client/my_libs/autoform/autofActions.js
jotakaele/meteor-agile-forms
0
15993412
/* Convierte en Array los datos de un fromulario */ formToJson = function formToJson(objForm) { // console.clear() var fields = $('[name][id]:not(.subObject)', objForm) var numberTypes = ['number', 'currency', 'range'] var dateTypes = ['date', 'datetime', 'time'] var f = objForm var res = {} fields.each(function(index, value) { dbg('value', value) if (_.indexOf(numberTypes, $('#' + this.name, f).attr('type')) >= 0) { this.save_as = $('#' + this.name, f).attr('save_as') || 'number' } else if (_.indexOf(dateTypes, $('#' + this.name, f).attr('type')) >= 0) { this.save_as = 'date' } else { this.save_as = $('#' + this.name, f).attr('save_as') || 'string' } var theValue = fieldValue($(this)) if (this.save_as == 'number') { if (_.isArray(theValue)) { theValue.forEach(function(elem, key) { theValue[key] = elem * 1 }) } else { theValue = theValue * 1 } } //TODO Refactorizar hay que extraer siempre los valores de los campos con fieldValue @urgente //procesemos los date //Los campos date los procesamos como date if (this.save_as == 'date') { if ($(value).attr("type") == 'date' || $(value).attr("type") == 'datetime') { theValue = toDate(theValue) } else if ($(value).attr("type") == 'time') { theValue = toDate('00-00-0000' + ' ' + theValue) } } else if (this.save_as == 'boolean') { theValue = eval(theValue) } //Precesamos los campos typo tags, para convertirlos en un array //dbg('this', $(this).attr('type')) if ($(this).attr('type') == 'tags') { theValue = fieldValue($(this)).split(',') } res[this.name] = theValue }) $('div.block[limit]', objForm).each(function() { _.extend(res, getBlocValues($(this))) }) return res } /* Procesa los valores de un bloque de varios campos convirtiendolo en un array */ getBlocValues = function getBlocValues($object, intLimit) { //todo Procesar la salida de getBlockValues, para que si limit=1, solo devuelva un objeto y no un array dbg('object', $object) var theBlock = $object var index = 0 var theBlockName = theBlock.attr('id') var resBV = {} var arrRow = [] var curIndex = '0' var nObj = {} $('.subObject[name]', theBlock).each(function() { var theControl = $(this) var theControlName = theControl.attr('name') var vName = _.strLeftBack(theControlName, '-') var vIndex = _.strRightBack(theControlName, '-') var vValue = fieldValue(theControl) if ($object.attr('limit') == 1) { nObj[vName] = vValue } else { nObj[vIndex] = nObj[vIndex] || {} nObj[vIndex][vName] = vValue } }) //Si limit=1 solo devolvemos un objeto if ($object.attr('limit') == 1) { dbg('nObj', nObj) resBV[theBlockName] = nObj } else { _.each(nObj, function(val) { arrRow.push(val) }) resBV[theBlockName] = arrRow } return resBV } //TODO esta operacion hay que hacerla desde un metodo de meteor, añadiendo autofecha, usuario, etc..... sendFormToMongo = function sendFormToMongo($form) { var dest = $form.attr('collection') var insertObj = formToJson($form) var insert = cCols[dest].insert(insertObj) // if (Session.get('debug') == true) { dbg(insert, o2S(insertObj)) // } return insert } // //Devuelve un array de objetos con las claves value y label, listo para ser usado en un campo tipo enum de formulario. // //Como parametro requiere un objeto con las siguientes claves: // //query.collection: la coleccion a utilizar // //query.filter: un selector al estilo mongo // //query.format: Modificadores de salida de campos al stilo meteor mongo, incluyendo campos que se muestran, orden, limit. Ejemplo: // //query.value: String. Lo que se guardara como valu en el <select>. Los nombres de campo a utilizar se encierran entre corchetes. Despues se quitan los corchetes y se le pasa la funcion eval // //query.label: String. Lo que se mostrara como label en el <select>. Los nombres de campo a utilizar se encierran entre corchetes. Despues se quitan los corchetes y se le pasa la funcion eval // Ejemplo de configuracion: // var query = {} // query.filter = { // primer_apellido: { // $exists: true // } // } // query.format = { // fields: { // _id: 0, // nombre: 1, // primer_apellido: 1, // sexo: 1 // }, // sort: { // primer_apellido: 1 // }, // limit: 10 // } // query.value = '[primer_apellido]' // query.label = '[nombre] + \' \' + [primer_apellido]' queryToEnum = function queryToEnum(query) { //sustituimos lo encerrado entre corchetes con el contenido del campo de su nombre var expresion = /\[[a-zA-Z0-9._-]+\]/g //Importante manetener query.value en la primera posicion, porque la vamos a usar despues por posicion var t = _.unique(((query.value || '') + (query.label || '') + (query.optgroup || '')).match(expresion) || []) var subst = [] t.forEach(function(k) { subst.push(k.replace(/\[|\]/g, '')) }) //vamos a definir fields, para que no haya que expresarlo innecesariamente dbg("subst", subst) var obJFields = {} query.filter = query.filter || {} subst.forEach(function(nItem) { obJFields[nItem.split('.')[0]] = 1 //TAmbien vamos a poner un filtro $exists: true a todos los campos que usamos para que solo nos devuelva filas con valores y evitar errores query.filter[nItem] = query.filter[nItem] || {} query.filter[nItem]["$exists"] = true }) //_.extend(query.filter, autoFilter) query.format = query.format || {} query.format.fields = obJFields // dbg("obJFields", o2S(obJFields)) // // dbg("query", o2S(query)) dbg("filter", o2S(query.filter)) dbg("format", o2S(query.format)) if (!query.format.sort) { query.format.sort = {} query.format.sort[subst[0]] = 1 } var qRes = cCols[query.collection].find(query.filter || {}, query.format || {}).fetch() //dbg('qRes', o2S(qRes)) var arrRes = [] var arrCompare = [] qRes.forEach(function(theRowKey) { //dbg("theRowKey", theRowKey) var itemArrCompare = '' var nObj = {} var strLabel = query.label || query.value var strValue = query.value var strOptgroup = query.optgroup || null subst.forEach(function(v) { var depthValue = eval('theRowKey.' + v) itemArrCompare = itemArrCompare + depthValue strLabel = strLabel.replace('[' + v + ']', '\'' + depthValue + '\'').replace(/\['/g, '').replace(/'\]/g, '') strValue = strValue.replace('[' + v + ']', '\'' + depthValue + '\'').replace(/\['/g, '').replace(/'\]/g, '') if (strOptgroup) { strOptgroup = strOptgroup.replace('[' + v + ']', '\'' + (depthValue || '') + '\'').replace(/\['/g, '').replace(/'\]/g, '') } }) // dbg("arrCompare", arrCompare) // dbg("itemArrCompare", arrCompare.indexOf(itemArrCompare) + ' >>> ' + itemArrCompare) if (arrCompare.indexOf(itemArrCompare) == -1) { arrCompare.push(itemArrCompare) nObj.label = eval(strLabel) nObj.value = eval(strValue) strOptgroup ? nObj.optgroup = eval(strOptgroup) : null arrRes.push(nObj) } }) // dbg("arrRes", o2S(arrRes)) return _.unique(arrRes) }
1.414063
1
SlashCommands/control/stop.js
CorwinDev/DisActyl--PterodactylControlBot
10
15993420
const { Client, CommandInteraction, MessageEmbed } = require("discord.js"); const linkJson = require('../../link.json'); const Nodeactyl = require('nodeactyl') module.exports = { name: "stop", description: "Stop your server", type: 'CHAT_INPUT', options: [ { name: "serverid", type: "STRING", description: "The serverid to stop", required: true } ], /** * * @param {Client} client * @param {CommandInteraction} interaction * @param {String[]} args */ run: async (client, interaction, args) => { await interaction.deferReply({ ephemeral: false }).catch(() => { }); var serverId = args[0]; var helpEmbed = new MessageEmbed() .setTitle(`Example - Stop`) .setColor("#F9914F") .setDescription(`/stop <ServerId>`) if (!serverId) return interaction.followUp({ embeds: [helpEmbed] }); if (!linkJson[interaction.user.id]) return client.error("notconnected", interaction) var userApi = linkJson[interaction.user.id]["userapi"]; var hostname = client.config.panelurl let client1 = new Nodeactyl.NodeactylClient(hostname, userApi); client1.stopServer(serverId).then((response) => { var errorMessage = new MessageEmbed() .setTitle(`Stop`) .setColor(`#F9914F`) .setDescription(`You succesfully stopped the server!`) interaction.followUp({ embeds: [errorMessage] }); }).catch((error) => { client.error(error, interaction) }); } }
1.601563
2
src/components/Counter_02.js
raydot/kcd-state-management
0
15993428
import React from 'react'; // So what if we do this? Where does `count` come from then? export function Counter({ count, onIncrementClick }) { return <button onClick={onIncrementClick}>{count}</button>; } function CountDisplay({ count }) { // where does `count` come from? return <div>The current counter count is {count}</div>; } // Here's the answer, right there in the React docs on Lifting State Up! // https://reactjs.org/docs/lifting-state-up.html export function Counter2() { // This part: const [count, setCount] = React.useState(0); const increment = () => setCount((c) => c + 1); return ( <div> <CountDisplay count={count} /> <Counter count={count} onIncrementClick={increment} /> </div> ); }
1.78125
2
lib/core-plugin/config-actions/permissions/revoke-user.js
chaos-core/nix-core
3
15993436
const { ChaosError } = require("../../../errors"); const ConfigAction = require("../../../models/config-action"); class RevokeUserAction extends ConfigAction { name = 'revokeUser'; description = 'remove a user from a permission level'; args = [ { name: 'user', description: 'the user to remove', required: true, }, { name: 'level', description: 'the permission level to remove', required: true, }, ]; constructor(chaos) { super(chaos); this.chaos.on('chaos.listen', () => { this.permissionsService = this.getService('core', 'permissionsService'); this.userService = this.getService('core', 'userService'); }); } get strings() { return super.strings.core.configActions.permissions.revokeUser; } async run(context) { let guild = context.guild; let userString = context.args.user; let level = context.args.level; try { let user = await this.userService.findMember(guild, userString) .then((member) => member.user); await this.permissionsService.removeUser(guild, level, user); return { status: 200, content: this.strings.removedUserFromLevel({ userName: user.username, levelName: level }), }; } catch (error) { if (error instanceof ChaosError) { return { status: 400, content: error.message }; } else { throw error; } } } } module.exports = RevokeUserAction;
1.429688
1
dist/js/controladores/loginCtrl.js
Sebasboll15/AdminLTE
0
15993444
angular.module('olimpiada_boom') .controller('MainCtrl', function(MySocket){ }) .controller('loginCtrl', function($scope, MySocket, $state, ConexionServ, $http, $filter, $uibModal, AuthServ){ $scope.user = {username: 'jorge', password: '<PASSWORD>'} if (localStorage.servidor) { $scope.servidor = localStorage.servidor } else { $scope.servidor = location.hostname } $scope.mostrarCambiarServ = function(){ $scope.mostrar_cambiar_serv = !$scope.mostrar_cambiar_serv; } $scope.cambiar_servidor = function(servidor){ localStorage.servidor = servidor; } $scope.iniciar = function(user){ AuthServ.loguear(user).then(function(){ $state.go('main'); }, function(){ alert('Datos incorrectos'); }) } });
1.179688
1
Cannonball Adderley/Jazz Workshop Revisited/m.js
littleflute/m52
0
15993452
var f = []; f[0] = "v0.0.9"; f[1] = "01 An Opening Comment by Cannonball.mp3"; f[2] = "03 Jessica's Day.mp3"; f[3] = "05 A Few Words.mp3"; f[4] = "06 Unit 7.mp3"; f[5] = "07 Another Few Words.mp3"; f[6] = "08 The Jive Samba.mp3"; f[7] = "10 Mellow Buno.mp3"; f[8] = "11 Time to Go Now-Really.mp3"; f[9] = "Lillie.mp3"; f[10] = "Marney.mp3"; f[11] = "Primitivo.mp3";
0.84375
1
hard/almost-palindrome/code.spec.js
jamoum/JavaScript_Challenges_Solutions
12
15993460
const almostPalindrome = require('./code'); describe('Tests', () => { test('Should return false if already palindrome.', () => { expect(almostPalindrome('ggggg')).toEqual(false); }); test('Should return false if already palindrome.', () => { expect(almostPalindrome('gggfggg')).toEqual(false); }); test('the tests', () => { expect(almostPalindrome('abcdcbg')).toEqual(true); expect(almostPalindrome('abccia')).toEqual(true); expect(almostPalindrome('abcdaaa')).toEqual(false); expect(almostPalindrome('gggfgig')).toEqual(true); expect(almostPalindrome('gggffff')).toEqual(false); expect(almostPalindrome('GIGGG')).toEqual(true); expect(almostPalindrome('ggggi')).toEqual(true); expect(almostPalindrome('1234312')).toEqual(false); }); });
1.234375
1
lab2_2.js
kostyniuk/RTS
0
15993468
const plotly = require('plotly')('alexandrkostyniuk', 'KmNYDnbtNicNFN9Zz5h3'); const linspace = (start, stop, num) => { let result = []; if (num === 1) { for(let i = start; i < stop; i++) { result.push(i) } } else { const step = stop/num; for(let i = start; i < stop; i=i+step) { result.push(i) } } return result } const signalGeneration = (n, w, N) => { let A, fi; let x = new Array(N); x.fill(0, 0, x.length) const frequencies = linspace(0, w, n); for(let i = 0; i < n; i++) { A = Math.random(0, 1); fi = Math.random(0, 1); for(let j = 0; j < N; j++) { x[j] += A * Math.sin(frequencies[i]*j + fi) } } return x }; const dispersion = (elements, Mx) => { let temp = 0 for(element of elements) { temp += (element - Mx) ** 2 } return temp / elements.length - 1 } const graph = (arrX, arrY, name) => { const trace1 = { x: arrY, y: arrX, type: "scatter" }; const data = [trace1]; const layout = { yaxis2: { domain: [0.6, 0.95], anchor: "x2" }, xaxis2: { domain: [0.6, 0.95], anchor: "y2" } }; const graphOptions = {layout: layout, filename: name, fileopt: "overwrite"}; plotly.plot(data, graphOptions, function (err, msg) { console.log(msg); }); return 'Successfully builded' } const dftGenerator = x => { const N = x.length; let fReal = new Array(N).fill(0); let fImaginary = new Array(N).fill(0); let fp = new Array(N).fill(0); for (let p = 0; p < N; p++) { for (let k = 0; k < N; k++) { fReal[p] += x[k] * Math.cos(((2 * Math.PI) / N) * p * k); fImaginary[p] += x[k] * Math.sin(((2 * Math.PI) / N) * p * k); } fp[p] = Math.sqrt(Math.pow(fReal[p], 2) + Math.pow(fImaginary[p], 2)); } return fp; }; const fftGenerator = x => { const N = x.length; const halfN = Math.floor(N / 2); let freal11 = new Array(halfN).fill(0); let freal12 = new Array(halfN).fill(0); let freal1 = new Array(N).fill(0); let fimage11 = new Array(halfN).fill(0); let fimage12 = new Array(halfN).fill(0); new Array(N / 2).fill(0); let fimage1 = new Array(N).fill(0); let f = new Array(N).fill(0); for (let p = 0; p < halfN; p++) { for (let m = 0; m < halfN; m++) { freal11[p] += x[2 * m + 1] * Math.cos(((4 * Math.PI) / N) * p * m); fimage11[p] += x[2 * m + 1] * Math.sin(((4 * Math.PI) / N) * p * m); freal12[p] += x[2 * m] * Math.cos(((4 * Math.PI) / N) * p * m); fimage12[p] += x[2 * m] * Math.sin(((4 * Math.PI) / N) * p * m); freal1[p] = freal12[p] + freal11[p] * Math.cos(((2 * Math.PI) / N) * p) - fimage11[p] * Math.sin(((2 * Math.PI) / N) * p); fimage1[p] = fimage12[p] + fimage11[p] * Math.cos(((2 * Math.PI) / N) * p) + freal11[p] * Math.sin(((2 * Math.PI) / N) * p); freal1[p + (N / 2)] = freal12[p] - (freal11[p] * Math.cos(((2 * Math.PI) / N) * p) - fimage11[p] * Math.sin(((2 * Math.PI) / N) * p)); fimage1[p + (N / 2)] = fimage12[p] - (fimage11[p] * Math.cos(((2 * Math.PI) / N) * p) + freal11[p] * Math.sin(((2 * Math.PI) / N) * p)); f[p] = (freal1[p] ** 2 + fimage1[p] ** 2) ** 0.5; f[p + (N / 2)] = (freal1[p + (N / 2)] ** 2 + fimage1[p + (N / 2)] ** 2) ** 0.5; } } return f; }; const n = 10; // n - number of harmonics const w = 1500; // w - max frequency let N = 256; // N - number of countings const x = signalGeneration(n, w, N); const y = linspace(0, N, 1); const dft = dftGenerator(x); const fft = fftGenerator(x); console.log({fft, dft}) graph(dft, y, 'dft'); graph(fft, y, 'fft');
1.9375
2
src/api/aws.js
llicat/OperaFront
0
15993476
import request from '@/utils/request' // 数据量少&去掉分页参数 export function fetchAccountList() { return request({ url: '/aws/account/list', method: 'get' }) } export function createAccount(data) { return request({ url: '/aws/account/save', method: 'post', params: data }) } export function updateAccount(data) { return request({ url: '/aws/account/save', method: 'post', params: data }) } export function deleteAccount(id) { return request({ url: '/aws/account/delete/' + id, method: 'post' }) } /** * ec2 */ export function fetchEc2List(data) { return request({ url: '/aws/ec2/list', method: 'post', params: data }) }
1
1
src/chat.js
cybercog/es2015-sandbox
0
15993492
'use strict'; class Chat { constructor() { this.rooms = []; } createRoom(room) { this.rooms.push(room); } destroyRoom(room) { this.rooms.splice(this.rooms.indexOf(room), 1); } } export default Chat;
0.988281
1
Javascript/year_month_day_select/year_month_day_select.js
dodoliu/HelperLibrary
0
15993500
// Generated by CoffeeScript 1.10.0 var YearMonthDaySelect; YearMonthDaySelect = (function() { var KoViewModel, gParams, koTemplateA, koTemplateB, koTemplateC; gParams = {}; function YearMonthDaySelect(args) { gParams = args; } koTemplateA = '<div data-bind="template:{name:\'sl_year_month_day_a\',data:yearObj}"></div> <div data-bind="template:{name:\'sl_year_month_day_a\',data:monthObj}"></div> <div data-bind="template:{name:\'sl_year_month_day_a\',data:dayObj}"></div> <script type="text/template" id="sl_year_month_day_a"> <select data-bind="attr:{id:$data.id,name:$data.name,class:$data.class},event:{change:$data.changeEvent},foreach:$data.dataArray,selectedOptions:[$data.selectedValue]"> <option data-bind="value:$data.key,text:$data.value"></option> </select> <span data-bind="text:$data.title"></span> </script>'; koTemplateB = '<div data-bind="template:{name:\'sl_year_month_day_b\',data:yearObj}"></div> <div data-bind="template:{name:\'sl_year_month_day_b\',data:monthObj}"></div> <script type="text/template" id="sl_year_month_day_b"> <select data-bind="attr:{id:$data.id,name:$data.name,class:$data.class},event:{change:$data.changeEvent},foreach:$data.dataArray,selectedOptions:[$data.selectedValue]"> <option data-bind="value:$data.key,text:$data.value"></option> </select> <span data-bind="text:$data.title"></span> </script>'; koTemplateC = '<div data-bind="template:{name:\'sl_year_month_day_c\',data:yearObj}"></div> <div data-bind="template:{name:\'sl_year_month_day_c\',data:monthObj}"></div> <div data-bind="template:{name:\'sl_year_month_day_c\',data:dayObj}"></div> <script type="text/template" id="sl_year_month_day_c"> <select data-bind="attr:{id:$data.id,name:$data.name,class:$data.class},event:{change:$data.changeEvent},foreach:$data.dataArray,selectedOptions:[$data.selectedValue]"> <option data-bind="value:$data.key,text:$data.value"></option> </select> </script>'; KoViewModel = function(params) { var selfVM; selfVM = this; selfVM.yearObj = ko.observableArray(); selfVM.monthObj = ko.observableArray(); selfVM.dayObj = ko.observableArray(); selfVM.GenerateYearArray = function(defaultValue) { var i, j, ref, ref1, tmpDataArray, tmpDate, tmpInterval, tmpYear, tmpYearClass, tmpYearDefault, tmpYearID, tmpYearName, tmpYearTitle; tmpDate = new Date(); tmpDataArray = []; tmpInterval = selfVM.IfThenElse(gParams.yearInterval, 5); tmpYearDefault = selfVM.IfThenElse(gParams.yearDefault, '年'); tmpYearTitle = selfVM.IfThenElse(gParams.yearTitle, '年'); tmpDataArray.push({ key: -1, value: tmpYearDefault }); for (i = j = ref = tmpDate.getFullYear() - tmpInterval, ref1 = tmpDate.getFullYear() + tmpInterval; ref <= ref1 ? j < ref1 : j > ref1; i = ref <= ref1 ? ++j : --j) { tmpDataArray.push({ key: i, value: i + gParams.yearTitle }); } tmpYearID = selfVM.IfThenElse(gParams.yearID, 'sl_year'); tmpYearName = selfVM.IfThenElse(gParams.yearName, 'sl_year_name'); tmpYearClass = selfVM.IfThenElse(gParams.yearClass, 'sl_year_class'); tmpYear = { title: tmpYearTitle, id: tmpYearID, name: tmpYearName, "class": tmpYearClass, changeEvent: selfVM.ChangeYear, selectedValue: defaultValue, dataArray: tmpDataArray }; return selfVM.yearObj(tmpYear); }; selfVM.GenerateMonthArray = function(defaultValue) { var i, j, tmpDataArray, tmpMonth, tmpMonthClass, tmpMonthDefault, tmpMonthID, tmpMonthName, tmpMonthTitle; tmpDataArray = []; tmpMonthDefault = selfVM.IfThenElse(gParams.monthDefault, '年'); tmpMonthTitle = selfVM.IfThenElse(gParams.monthTitle, '月'); tmpDataArray.push({ key: -1, value: tmpMonthDefault }); for (i = j = 1; j <= 12; i = ++j) { tmpDataArray.push({ key: i, value: i + gParams.monthTitle }); } tmpMonthID = selfVM.IfThenElse(gParams.monthID, 'sl_month'); tmpMonthName = selfVM.IfThenElse(gParams.monthName, 'sl_month_name'); tmpMonthClass = selfVM.IfThenElse(gParams.monthClass, 'sl_month_class'); tmpMonth = { title: tmpMonthTitle, id: tmpMonthID, name: tmpMonthName, "class": tmpMonthClass, changeEvent: selfVM.ChangeMonth, selectedValue: defaultValue, dataArray: tmpDataArray }; return selfVM.monthObj(tmpMonth); }; selfVM.GenerateDayArray = function(year, month, defaultValue) { var i, j, ref, tmpDataArray, tmpDay, tmpDayClass, tmpDayDefault, tmpDayID, tmpDayName, tmpDayTitle; tmpDataArray = []; tmpDayDefault = selfVM.IfThenElse(gParams.dayDefault, '日'); tmpDayTitle = selfVM.IfThenElse(gParams.dayTitle, '日'); tmpDataArray.push({ key: -1, value: tmpDayDefault }); for (i = j = 1, ref = "" + (Helper.FindDaysInMonth(year, month)); 1 <= ref ? j <= ref : j >= ref; i = 1 <= ref ? ++j : --j) { tmpDataArray.push({ key: i, value: i + gParams.dayTitle }); } tmpDayID = selfVM.IfThenElse(gParams.dayID, 'sl_day'); tmpDayName = selfVM.IfThenElse(gParams.dayName, 'sl_day_name'); tmpDayClass = selfVM.IfThenElse(gParams.dayClass, 'sl_day_class'); tmpDay = { title: tmpDayTitle, id: tmpDayID, name: tmpDayName, "class": tmpDayClass, changeEvent: selfVM.ChangeDay, selectedValue: defaultValue, dataArray: tmpDataArray }; return selfVM.dayObj(tmpDay); }; selfVM.ChangeYear = function(arg) { var currValue; currValue = $("#" + arg.id + " option:selected").val(); if (currValue === (selfVM.IfThenElse(gParams.yearDefault, '-1'))) { selfVM.GenerateMonthArray(-1); return selfVM.GenerateDayArray(1970, 1, gParams.dayDefault); } else { selfVM.GenerateMonthArray(selfVM.IfThenElse(gParams.yearDefault, '-1')); return selfVM.GenerateDayArray(currValue, -1, -1); } }; selfVM.ChangeMonth = function(arg) { var currValue, selectedMonth, selectedYear; currValue = $("#" + arg.id + " option:selected").val(); selectedYear = $("#" + gParams.yearID + " option:selected").val(); selectedMonth = $("#" + gParams.monthID + " option:selected").val(); if (currValue === (selfVM.IfThenElse(gParams.monthDefault, '-1'))) { return selfVM.GenerateDayArray(selectedYear, selectedMonth, gParams.dayDefault); } else { return selfVM.GenerateDayArray(selectedYear, selectedMonth, 1); } }; selfVM.ChangeDay = function(arg) {}; selfVM.Init = function() { var tmpDate, tmpDay, tmpMonth, tmpYear; if (gParams.initYear || gParams.initMonth || gParams.initDay) { selfVM.GenerateYearArray(gParams.initYear); selfVM.GenerateMonthArray(gParams.initMonth); return selfVM.GenerateDayArray(gParams.initYear, gParams.initMonth, gParams.initDay); } else { tmpDate = new Date(); tmpYear = tmpDate.getFullYear(); switch (gParams.initSelect) { case 3: selfVM.GenerateYearArray(tmpYear); selfVM.GenerateMonthArray(1); return selfVM.GenerateDayArray(tmpYear, 1, 1); case 2: tmpMonth = tmpDate.getMonth() + 1; tmpDay = tmpDate.getDate(); selfVM.GenerateYearArray(tmpYear); selfVM.GenerateMonthArray(tmpMonth); return selfVM.GenerateDayArray(tmpYear, tmpMonth, tmpDay); default: tmpYear = selfVM.IfThenElse(gParams.yearDefault, '-1'); tmpMonth = selfVM.IfThenElse(gParams.monthDefault, '-1'); tmpDay = selfVM.IfThenElse(gParams.dayDefault, '-1'); selfVM.GenerateYearArray(tmpYear); selfVM.GenerateMonthArray(tmpMonth); return selfVM.GenerateDayArray(tmpYear, tmpMonth, tmpDay); } } }; selfVM.IfThenElse = function(value, elseValue) { if (value != null) { return value; } else { return elseValue; } }; return selfVM.Init(); }; ko.components.register('year_month_day_select_a', { template: koTemplateA, viewModel: function(params) { return KoViewModel(params); } }); ko.components.register('year_month_day_select_b', { template: koTemplateB, viewModel: function(params) { return KoViewModel(params); } }); ko.components.register('year_month_day_select_c', { template: koTemplateC, viewModel: function(params) { return KoViewModel(params); } }); return YearMonthDaySelect; })();
1.492188
1
src/middleware/visit.js
graphql-factory/graphql-factory
54
15993508
import { print, parse, visit, buildSchema, Kind, DirectiveLocation, isSpecifiedScalarType, } from 'graphql'; import { forEachDirective, getDirectiveLocationFromAST } from './directive'; import { forEach } from '../jsutils'; import { getGraphQLTypeName, getOperationNode, printAndParse, parseSchemaIntoAST, } from '../utilities'; import { getVariableValues } from 'graphql/execution/values'; import { makeExecutableRuntimeSchema } from './runtime'; import { fixRenamed } from './fix'; /** * Visits the schema AST and applying any directives * @param {*} schema * @param {*} globalMiddleware * @param {*} variableValues */ export function directiveVisitNode(schema, globalMiddleware, variableValues) { return function enter(node, key, parent, path, ancestors) { const info = { node, key, parent, path, ancestors, schema, variableValues, }; const location = getDirectiveLocationFromAST(node, ancestors); if (!location || !node.directives || !node.directives.length) { return; } forEachDirective(location, node, schema, variableValues, directiveExec => { const { visitNode, before, after, directiveArgs, directive, } = directiveExec; if (typeof visitNode === 'function') { const visitValue = visitNode(directiveArgs, info); if (visitValue !== undefined) { return visitValue; } } let middlewareKey = null; switch (location) { case DirectiveLocation.SCHEMA: middlewareKey = 'schema'; break; case DirectiveLocation.QUERY: case DirectiveLocation.MUTATION: case DirectiveLocation.SUBSCRIPTION: middlewareKey = 'operation'; break; default: break; } if (middlewareKey && typeof before === 'function') { globalMiddleware[middlewareKey].before.push({ level: 'global', type: 'before', class: 'directive', location, name: directive.name, resolve: before, args: directiveArgs, }); } if (middlewareKey && typeof after === 'function') { globalMiddleware[middlewareKey].after.push({ level: 'global', type: 'after', class: 'directive', location, name: directive.name, resolve: after, args: directiveArgs, }); } }); }; } export function visitDefinition(location, definition, schema, variableValues) { return forEachDirective( location, definition.astNode, schema, variableValues, exec => { if (typeof exec.visit === 'function') { exec.visit(definition, exec.directiveArgs, { schema, variableValues, directive: exec.directive, }); } }, ); } export function visitValueDefinition(def, schema, vars) { visitDefinition(DirectiveLocation.ENUM_VALUE, def, schema, vars); } export function visitArgDefinition(def, schema, vars) { visitDefinition(DirectiveLocation.ARGUMENT_DEFINITION, def, schema, vars); } export function visitFieldDefinition(def, schema, vars) { visitDefinition(DirectiveLocation.FIELD_DEFINITION, def, schema, vars); forEach(def.args, arg => { visitArgDefinition(arg, schema, vars); }); } export function visitInputFieldDefinition(def, schema, vars) { visitDefinition(DirectiveLocation.INPUT_FIELD_DEFINITION, def, schema, vars); } export function visitSchemaDefinition(def, schema, vars) { visitDefinition(DirectiveLocation.SCHEMA, def, schema, vars); } export function visitScalarDefinition(def, schema, vars) { visitDefinition(DirectiveLocation.SCALAR, def, schema, vars); } export function visitObjectDefinition(def, schema, vars) { visitDefinition(DirectiveLocation.OBJECT, def, schema, vars); forEach(def.getFields(), field => { visitFieldDefinition(field, schema, vars); }); } export function visitInterfaceDefinition(def, schema, vars) { visitDefinition(DirectiveLocation.INTERFACE, def, schema, vars); forEach(def.getFields(), field => { visitFieldDefinition(field, schema, vars); }); } export function visitUnionDefinition(def, schema, vars) { visitDefinition(DirectiveLocation.UNION, def, schema, vars); } export function visitEnumDefinition(def, schema, vars) { visitDefinition(DirectiveLocation.ENUM, def, schema, vars); forEach(def.getValues(), value => { visitValueDefinition(value, schema, vars); }); } export function visitInputDefinition(def, schema, vars) { visitDefinition(DirectiveLocation.INPUT_OBJECT, def, schema, vars); forEach(def.getFields(), field => { visitInputFieldDefinition(field, schema, vars); }); } export function visitAllDefinitions(schema, variableValues) { visitSchemaDefinition(schema, schema, variableValues); forEach(schema.getTypeMap(), (type, name) => { if (!name.startsWith('__') && !isSpecifiedScalarType(type)) { switch (getGraphQLTypeName(type, true)) { case 'GraphQLScalarType': return visitScalarDefinition(type, schema, variableValues); case 'GraphQLObjectType': return visitObjectDefinition(type, schema, variableValues); case 'GraphQLInterfaceType': return visitInterfaceDefinition(type, schema, variableValues); case 'GraphQLUnionType': return visitUnionDefinition(type, schema, variableValues); case 'GraphQLEnumType': return visitEnumDefinition(type, schema, variableValues); case 'GraphQLInputObjectType': return visitInputDefinition(type, schema, variableValues); default: break; } } }); } export function applyDirectiveVisitors( schema, source, variableValues, extensionMap, operationName, ) { const globalMiddleware = { schema: { before: [], after: [], }, operation: { before: [], after: [], }, }; const schemaAST = parseSchemaIntoAST(schema); const sourceAST = parse(source); const op = getOperationNode(sourceAST, operationName); if (op.errors) { return { errors: op.errors, runtimeSchema: undefined, document: undefined, before: undefined, after: undefined, }; } const _document = printAndParse({ kind: Kind.DOCUMENT, definitions: [op.operation].concat( sourceAST.definitions.filter(definition => { return definition.kind !== Kind.OPERATION_DEFINITION; }), ), }); const vars = getVariableValues( schema, op.operation.variableDefinitions, variableValues, ); if (vars.errors) { return { errors: vars.errors, runtimeSchema: undefined, document: undefined, before: undefined, after: undefined, }; } const runtime = makeExecutableRuntimeSchema( schema, buildSchema( print( visit(schemaAST, { enter: directiveVisitNode(schema, globalMiddleware, vars.coerced), }), ), ), extensionMap, ); if (runtime.errors) { return { errors: runtime.errors, runtimeSchema: undefined, document: undefined, before: undefined, after: undefined, }; } // visit the definitions visitAllDefinitions(runtime.runtimeSchema, vars.coerced); // apply rename changes fixRenamed(runtime.runtimeSchema); // concatenate the before and after global middleware const before = globalMiddleware.schema.before.concat( globalMiddleware.operation.before, ); const after = globalMiddleware.schema.after.concat( globalMiddleware.operation.after, ); return { errors: undefined, runtimeSchema: runtime.runtimeSchema, document: printAndParse( visit(_document, { enter: directiveVisitNode(schema, globalMiddleware, vars.coerced), }), ), before, after, }; }
1.3125
1
src/pages/portfolio.js
DundarKoray/porfolio_gatsby_contentful
1
15993524
import React from "react" import Layout from "../components/layout" import { useStaticQuery, graphql } from "gatsby" import Project from "../components/Project" import SEO from "../components/seo" import SubPageHeader from "../components/SubPageHeader" import { Title2 } from "../components/Title" const portfolio = () => { const getProject = useStaticQuery(graphql` { allProject: allContentfulProject(sort: { fields: [order], order: ASC }) { edges { node { title order link image { fixed(height: 240, width: 320) { base64 aspectRatio width height src srcSet srcWebp srcSetWebp } } } } } } `) return ( <> <Layout> <SEO title="Portfolio" /> <SubPageHeader> <Title2 text="Recent Projects" styleClass="title-h2-light" /> </SubPageHeader> <section id="portfolio-page" class="portfolio"> <div class="portfolio__container"> {getProject.allProject.edges.map(({ node: item }) => { return <Project link={item.link} image={item.image.fixed} title={item.title} /> })} </div> </section> </Layout> </> ) } export default portfolio
1.3125
1
src/index.js
JoseegCr/appClima
0
15993532
import axios from 'axios'; const image = document.querySelector('img'); const clima = document.querySelector('#clima'); const ciudad = document.querySelector('#ciudad'); const temperatura = document.querySelector('#temperatura'); const search = document.querySelector('#search'); const form = document.querySelector('form'); const input = document.querySelector('input'); const apiKey = 'd23a1ce2f2961252cbdab5be4a975343'; const iconUrl = 'http://openweathermap.org/img/wn/'; const getData = async ()=>{ const res = await axios.get(`https://api.openweathermap.org/data/2.5/weather?q=Apizaco&appid=${apiKey}&units=metric`); const info = res.data.weather[0]; const icon = info.icon; const climaTemp = info.main; const cityName = res.data.name; const temp = res.data.main.temp; image.src=`${iconUrl}/${icon}@2x.png`; clima.textContent = climaTemp; ciudad.textContent = cityName; temperatura.textContent = `${temp}°C`; } form.addEventListener('submit', (e)=>{ e.preventDefault(); const city = search.value; console.log(city); }); getData();
1.46875
1
javascript/code-challenges/linkedlist/index.js
JessiVelazquez/data-structures-and-algorithms
0
15993540
'use strict'; const LinkedList = require('./lib/ll.js'); let ll = new LinkedList(); console.log('empty list', ll); ll.insert(10); console.log('single item', ll); ll.insert(20); console.log('2 items', ll);
1.320313
1
src/leaflet/core/Base.js
MapGIS/WebClient-JavaScript-Plugin
2
15993548
/** *MapGIS WebClient Leaflet基类 * 定义命名空间 * 提供公共模块 */ import L from "leaflet"; L.zondy = L.zondy || {}; L.zondy.control = L.zondy.control || {}; L.mapv = L.mapv || {}; L.echarts = L.echarts || {}; L.CRS = L.CRS || {};
0.5625
1
client/src/Objects/PostProcess.js
KishanBapodra/LunarLander
18
15993556
import { Node } from '../Engine/Renderer'; export default class PostProcess extends Node { constructor({ name, volume, zIndex }) { volume.style.zIndex = zIndex; super(name, volume); } update() {} } export class Volume { constructor(cssStyles, className) { this.node = document.createElement('div'); this.node.style.width = '100vw'; this.node.style.height = '100vh'; this.node.style.position = 'absolute'; if (className) { this.node.classList += className; } for (const key in cssStyles) { if (cssStyles.hasOwnProperty(key)) { this.node.style[key] = cssStyles[key]; } } } getVolume() { return this.node; } }
1.304688
1
backend/database.js
talesconrado/SpotPer
1
15993564
const sql = require('mssql'); exports.pool = function (envVar) { const config = { user: envVar.DB_USER, password: <PASSWORD>, server: (envVar.NODE_ENV === 'development') ? envVar.DB_DEV : envVar.DB_PROD, database: envVar.DB, pool: { max: 8, min: 0, } } const pool = new sql.ConnectionPool(config); return pool }
1.148438
1
packages/ember-simple-auth/tests/simple-auth/stores/local-storage-test.js
SafetyCulture/ember-simple-auth
0
15993572
import LocalStorage from 'simple-auth/stores/local-storage'; import itBehavesLikeAStore from './shared/store-behavior'; describe('Stores.LocalStorage', function() { beforeEach(function() { this.store = LocalStorage.create(); this.store.clear(); }); itBehavesLikeAStore(); });
1.023438
1
example.js
koajs/favicon
100
15993580
var koa = require('koa'); var favicon = require('./'); var app = koa(); app.use(favicon()); app.use(function *response (next){ this.body = 'Hello World'; }); app.listen(3000);
0.921875
1
Learn Vue/Modal Forms/main.js
burimbb/learnlaravel
0
15993588
Vue.component('modal', { template: '\ <div class="modal is-active" v-show="isActive">\ <div class="modal-background"></div>\ <div class="modal-card">\ <header class="modal-card-head">\ <p class="modal-card-title"><slot name="title"></slot></p>\ <button class="delete" aria-label="close" @click="isActive = false"></button>\ </header>\ <section class="modal-card-body">\ <slot name="content"></slot>\ </section>\ <footer class="modal-card-foot">\ <slot name="footer">\ <button class="button is-success">Save changes</button>\ <button class="button">Cancel</button>\ </slot>\ </footer>\ </div>\ </div>', data(){ return { isActive: true, } }, }); new Vue({ el: '#app' });
1.328125
1
src/utils/renderUtils.js
solo123/woyin-op
0
15993596
/* eslint-disable no-script-url */ import React from 'react'; import { Tag }from 'antd' /** * 渲染状态块 * @param {*} status 状态码 * @param {*} items 状态数组结构 * const STATUSITEMS = [ * {key: 0, describe: ['green', '未激活']}, * ] */ export const statuesRend = (status, STATUSITEMS) => { const len = STATUSITEMS.length for(let i = 0; i < len; i+=1){ if(status === STATUSITEMS[i].key){ return ( <Tag color={STATUSITEMS[i].describe[0]}>{STATUSITEMS[i].describe[1]}</Tag> ) } } return null } /** * 渲染按键 */ export const hreRend = (hreData, texts, record) =>{ return( <span> {hreData.map(ref => (<a href="javascript:void(0)" key={ref.label} onClick={()=> { ref.onClick(texts, record)}}>{ref.label}</a>))} </span> ) }
1.492188
1
index.js
alexcnichols/check-issues
3
15993604
const core = require('@actions/core'); const { GitHub, context } = require('@actions/github'); const getMessage = require('./get-message'); // most @actions toolkit packages have async methods async function run() { try { // Get authenticated GitHub client (Ocktokit) and other context const github = new GitHub(process.env.GITHUB_TOKEN); const { owner, repo } = context.repo; const actor = context.actor; // TO DO: Collect message as input parameter core.debug("Event name: " + context.eventName); core.debug("Workflow: " + context.workflow); core.debug("Action: " + context.action); core.debug("Owner: " + owner); core.debug("Repo: " + repo); core.debug("Actor: " + actor); // Check if issue event if (context.eventName === 'issues') { core.debug("Valid event: " + context.eventName); } else { core.debug("Invalid event: " + context.eventName); return; } // Check if issue event opened activity if (context.payload.action === 'opened') { core.debug("Valid event: " + context.payload.action); } else { core.debug("Invalid event: " + context.payload.action); return; } // Check if issue payload const isIssue = !!context.payload.issue; if (isIssue) { core.debug("Valid payload: " + context.payload.issue.number) } else { core.debug("Invalid payload"); return; } // Check if issue is on specified project board // If not, add to output message let found = false; const columns = await github.projects.listColumns({ project_id: 1 }); for (const column of columns) { core.debug("Reading column: " + column.name + " " + column.id + " " + column.node_id); let cards = await github.projects.listCards({ column_id: column.node_id, per_page: 100 }); cards = cards.data.filter((card) => card["content_url"] != undefined); for (const card of cards) { const { content_url } = card; const issueNumber = content_url.split("issues/")[1]; if (issueNumber == content_url.payload.issue.number) { found = true; } } } if (found) { core.debug("Found issue in project already."); } else { core.debug("Issue not found in project, posting comment."); // Post comment using output message await github.issues.createComment({ owner: owner, repo: repo, issue_number: context.payload.issue.number, body: `${getMessage(actor)}` }); } } catch (error) { core.setFailed(error.message); } } run()
1.75
2
lib/server.js
ihinsdale/mean-local-auth
8
15993612
var express = require('express'); var path = require('path'); var favicon = require('static-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var session = require('express-session'); var passport = require('passport'); var RedisStore = require('connect-redis')(session); var config = require('./config/config.json'); var app = express(); // view engine setup app.set('views', path.join(__dirname, '../public/views')); app.engine('html', require('ejs').renderFile); // We use the ejs engine to serve regular HTML app.set('view engine', 'html'); app.use(favicon()); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded()); // Enable sessions app.use(cookieParser(config.secrets.cookieParser)); app.use(session({ store: new RedisStore({ host: config.redis.host, port: config.redis.port, db: config.redis.dbs.session, pass: config.redis.pass }), secret: config.secrets.session, cookie: { path: '/', maxAge: 36000000, httpOnly: true, secure: true }, proxy: true, // necessary for the session middleware to trust the nginx server in setting secure cookies // current defaults which express-session asks be made explicit // Cf. http://stackoverflow.com/questions/24477035/express-4-0-express-session-with-odd-warning-message saveUninitialized: true, resave: true })); // Add passport.js middleware - note this must be done after enabling the session middleware app.use(passport.initialize()); app.use(passport.session()); app.use(express.static(path.join(__dirname, '../public'))); // Configure environment // Connect to Mongo db //var db = require('./config/db.js')(); // Add custom authentication middleware //var authMiddleware = require('./config/authMiddleware.js')(app); // Routes // Include core routes //var routes = require('./routes/routes.js')(app); // Add password reset routes //var passwordResetMiddleware = require('./routes/passwordReset.js')(app); module.exports = app;
1.359375
1
data/js/00/50/c2/07/00/00.36.js
p-g-krish/deepmac-tracker
0
15993620
deepmacDetailCallback("0050c2070000/36",[{"a":"5800 Creek Road Cincinnati OH US 45242","o":"Katchall Technologies Group","d":"2008-07-30","t":"add","s":"ieee","c":"US"}]);
0.458984
0
test/testImageHandler.js
DinRaf/hypermedia-pipeline
0
15993628
/* * Copyright 2018 Adobe. All rights reserved. * This file is licensed to you 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 REPRESENTATIONS * OF ANY KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ /* eslint-env mocha */ const assert = require('assert'); const image = require('../src/utils/image-handler'); describe('Test Image Handler', () => { it('Does not modify absolute URLs', () => { const node = { type: 'image', alt: 'Just an image', url: 'https://www.example.com/test.png', }; image()((orignode, tagname, params, children) => { assert.equal(params.src, orignode.url); assert.equal(children, undefined); assert.equal(tagname, 'img'); }, node); }); it('Injects Source Sets for Relative URLs', () => { const node = { type: 'image', alt: 'Just an image', url: 'test.png', title: 'Foo Bar', }; image()((orignode, tagname, params, children) => { assert.equal(params.src, orignode.url); assert.equal(children, undefined); assert.equal(tagname, 'img'); assert.equal(params.srcset, 'test.png?width=480&auto=webp 480w' + ',test.png?width=1384&auto=webp 1384w' + ',test.png?width=2288&auto=webp 2288w' + ',test.png?width=3192&auto=webp 3192w' + ',test.png?width=4096&auto=webp 4096w'); }, node); }); it('Allows overriding Image Options', () => { const node = { type: 'image', alt: 'Just an image', url: 'test.png', }; image({ widths: [100, 200, 300] })((orignode, tagname, params, children) => { assert.equal(params.src, orignode.url); assert.equal(children, undefined); assert.equal(tagname, 'img'); assert.equal(params.srcset, 'test.png?width=100&auto=webp 100w' + ',test.png?width=200&auto=webp 200w' + ',test.png?width=300&auto=webp 300w'); }, node); }); });
1.484375
1
src/Components/Privacy/Privacy.js
MartinoFenu/anon_board
0
15993636
import React from 'react'; const Privacy = () => { return ( <div className="privacyContainer"> <h4>Cookies</h4> <p> This website stores only technical information on your browser to grant you a bettere user exprerience. This information is regarding your preferences and we do not collect any personal information. This website do not use a normal cookie but ask access to the Local storage of your browser, this behaviour do not require preventive blocking as for the prefereces cookies. </p> <p> If you want more information on how to block or remove cookies or stored information directly from your browser: </p> <ul> <li><a href="http://windows.microsoft.com/it-it/windows-vista/block-or-allow-cookies">Internet Explorer</a></li> <li><a href="https://privacy.microsoft.com/it-it/windows-10-microsoft-edge-and-privacy">Microsoft Edge</a></li> <li><a href="https://support.mozilla.org/it/kb/Attivare%20e%20disattivare%20i%20cookie">Firefox</a></li> <li><a href="https://support.apple.com/kb/PH19214?viewlocale=it_IT&locale=en_US">Safari</a></li> <li><a href="https://support.google.com/chrome/answer/95647?hl=it&p=cpn_cookies">Chrome</a></li> </ul> </div> ) } export default Privacy;
1.335938
1
packages/termutil/lib/index.js
etm12/etm12
0
15993644
// @ts-check /** * @module @etm12/termutil */ import * as T from '@etm12/toolkit'; import * as S from './modules/status';
0.03418
0
test/pages/component/jag/jag.js
pinxixi/project
1
15993652
// pages/component/jag/jag.js Component({ /** * 组件的属性列表 */ properties: { num: { type: Number, value: 5 } }, /** * 组件的初始数据 */ data: { style:{ dispaly: "flex" } }, /** * 组件的方法列表 */ methods: { resetStyle(){ console.log(1) } } })
0.46875
0
src/main/webapp/js/search/search.js
TitansOrg/TitansEBPM
0
15993660
$(function() { /** * 初始化查询列表 */ $('#allFile').datagrid({ url: serverName +'search/searchAllFile.do', queryParams:{ searchName : keyWord }, striped:true//隔行变色 }); }); function getModelInfo(value,rowData) { var url = serverName + "flowInfo/flowDetail2.do?modelId=" + escape(rowData["modelId"]); return "<a href='" + url + "' target='mainFrame'>" + value + "</a>"; }
1.09375
1
app/components/SelectAllHeader/index.js
kaykhuq/stream-on
0
15993668
/** * * SelectAllHeader * */ import React from 'react'; import PropTypes from 'prop-types'; // import styled from 'styled-components'; class SelectAllHeader extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { const { onSelectAllChange, selectedRows, selectAll, CheckboxComponent, } = this.props; if (CheckboxComponent) { return ( <th> <CheckboxComponent type="checkbox" checked={selectAll} onChange={onSelectAllChange} /> <span className="text-muted">({selectedRows.length})</span> </th> ); } return ( <th> <input type="checkbox" checked={selectAll} onChange={onSelectAllChange} /> <span className="text-muted">({selectedRows.length})</span> </th> ); } } SelectAllHeader.propTypes = { onSelectAllChange: PropTypes.func.isRequired, selectAll: PropTypes.bool.isRequired, selectedRows: PropTypes.array.isRequired, CheckboxComponent: PropTypes.func, }; export default SelectAllHeader;
1.40625
1
controllers/analiseController.js
elioadriao/SGB
1
15993676
"use strict"; app.controller("analiseController", function($scope, $location, Propriedade){ var CUSTO_TOTAL_BD = []; var VARIACAO_REBANHO_AREA_BD = []; var RECEITA_BD = []; var INVENTARIO_BD = []; var TOTAL_RECEITA = 0; var TOTAL_INVENTARIO = 0; var TOTAL_AREA = 0; var TOTAL_CUSTO_TOTAL = [0, 0, 0, 0]; /* INICIA A AREA */ $scope.initRebanhoArea = function(){ var SQL = "SELECT * FROM variacao_rebanho_area WHERE propriedadeId_FK="+Propriedade.getId(); var res = false; basel.database.runAsync(SQL, function(data){ if(data[0] != null){ VARIACAO_REBANHO_AREA_BD = data[0]; res = true; }else{ res = false; } }); if(res){ console.log("Carregou Rebanho.."); $scope.initInventario(); }else{ console.log("Nao Carregou Rebanho.."); $location.path("/variacaoRebanho"); } } /* INICIA O INVENTARIO */ $scope.initInventario = function(){ var SQL = "SELECT * FROM inventario WHERE propriedadeId_FK="+Propriedade.getId(); var res = false; basel.database.runAsync(SQL, function(data){ if(data[0] != null){ INVENTARIO_BD = data; //console.log(INVENTARIO_BD); res = true; }else{ res = false; } }); if(res){ console.log("Carregou Inventario.."); $scope.initReceita(); }else{ console.log("Nao Carregou Inventario.."); $location.path("/inventario"); } } /* INICIA A RECEITA */ $scope.initReceita = function(){ var SQL = "SELECT * FROM receita WHERE propriedadeId_FK="+Propriedade.getId(); var res = false; basel.database.runAsync(SQL, function(data){ if(data[0] != null){ RECEITA_BD = data; //console.log(INVENTARIO_BD); res = true; }else{ res = false; } }); if(res){ console.log("Carregou Receita.."); $scope.initCustoTotal(); }else{ console.log("Nao Carregou Receita.."); $location.path("/receita"); } } /* INICIA O CUSTO TOTAL */ $scope.initCustoTotal = function(){ var SQL = "SELECT * FROM custo_total WHERE propriedadeId_FK="+Propriedade.getId(); var res = false; basel.database.runAsync(SQL, function(data){ if(data[0] != null){ CUSTO_TOTAL_BD = data; res = true; }else{ res = false; } }); if(res){ console.log("Carregou Custo Total.."); $scope.tratarAnalise(); }else{ console.log("Nao Carregou Custo Total.."); $location.path("/"); } } $scope.tratarInventario = function(){ for(i in INVENTARIO_BD){ TOTAL_INVENTARIO += (INVENTARIO_BD[i].valor_inicial + INVENTARIO_BD[i].valor_final)/2; } } $scope.tratarReceita = function(){ for(i in RECEITA_BD){ TOTAL_RECEITA += RECEITA_BD[i].jan; TOTAL_RECEITA += RECEITA_BD[i].fev; TOTAL_RECEITA += RECEITA_BD[i].mar; TOTAL_RECEITA += RECEITA_BD[i].abr; TOTAL_RECEITA += RECEITA_BD[i].mai; TOTAL_RECEITA += RECEITA_BD[i].jun; TOTAL_RECEITA += RECEITA_BD[i].jul; TOTAL_RECEITA += RECEITA_BD[i].ago; TOTAL_RECEITA += RECEITA_BD[i].sem; TOTAL_RECEITA += RECEITA_BD[i].out; TOTAL_RECEITA += RECEITA_BD[i].nov; TOTAL_RECEITA += RECEITA_BD[i].dez; } } $scope.tratarArea = function(){ for(i=0; i<12; i++){ TOTAL_AREA += $scope.getArea(i); } TOTAL_AREA /= 12; } $scope.tratarCustoTotal = function(){ var v; for(i in CUSTO_TOTAL_BD){ switch(CUSTO_TOTAL_BD[i].descricao){ case "Fixo" : v = 0; break; case "Variavel" : v = 1; break; case "Administrativo" : v = 2; break; case "Oportunidade" : v = 3; } TOTAL_CUSTO_TOTAL[v] += CUSTO_TOTAL_BD[i].jan; TOTAL_CUSTO_TOTAL[v] += CUSTO_TOTAL_BD[i].fev; TOTAL_CUSTO_TOTAL[v] += CUSTO_TOTAL_BD[i].mar; TOTAL_CUSTO_TOTAL[v] += CUSTO_TOTAL_BD[i].abr; TOTAL_CUSTO_TOTAL[v] += CUSTO_TOTAL_BD[i].mai; TOTAL_CUSTO_TOTAL[v] += CUSTO_TOTAL_BD[i].jun; TOTAL_CUSTO_TOTAL[v] += CUSTO_TOTAL_BD[i].jul; TOTAL_CUSTO_TOTAL[v] += CUSTO_TOTAL_BD[i].ago; TOTAL_CUSTO_TOTAL[v] += CUSTO_TOTAL_BD[i].sem; TOTAL_CUSTO_TOTAL[v] += CUSTO_TOTAL_BD[i].out; TOTAL_CUSTO_TOTAL[v] += CUSTO_TOTAL_BD[i].nov; TOTAL_CUSTO_TOTAL[v] += CUSTO_TOTAL_BD[i].dez; } } $scope.tratarAnalise = function(){ $scope.tratarInventario(); $scope.tratarCustoTotal(); $scope.tratarReceita(); $scope.tratarArea(); $scope.total_fixo = TOTAL_CUSTO_TOTAL[0]; $scope.total_variavel = TOTAL_CUSTO_TOTAL[1]; $scope.total_adm = TOTAL_CUSTO_TOTAL[2]; $scope.total_oportunidade = TOTAL_CUSTO_TOTAL[3]; $scope.total_inventario = TOTAL_INVENTARIO; $scope.total_operacional = $scope.total_fixo + $scope.total_variavel + $scope.total_adm; $scope.total_total = $scope.total_operacional + $scope.total_oportunidade; $scope.total_receita = TOTAL_RECEITA; $scope.total_caixa = $scope.total_receita - ($scope.total_variavel + $scope.total_adm); $scope.total_lucro_o = $scope.total_caixa - $scope.total_fixo; $scope.total_lucro_e = $scope.total_lucro_o - $scope.total_oportunidade; $scope.total_lucro_o_ha = $scope.total_lucro_o / TOTAL_AREA; } /* */ $scope.getArea = function(index){ switch(index){ case 0: return VARIACAO_REBANHO_AREA_BD.jan; case 1: return VARIACAO_REBANHO_AREA_BD.fev; case 2: return VARIACAO_REBANHO_AREA_BD.mar; case 3: return VARIACAO_REBANHO_AREA_BD.abr; case 4: return VARIACAO_REBANHO_AREA_BD.mai; case 5: return VARIACAO_REBANHO_AREA_BD.jun; case 6: return VARIACAO_REBANHO_AREA_BD.jul; case 7: return VARIACAO_REBANHO_AREA_BD.ago; case 8: return VARIACAO_REBANHO_AREA_BD.sem; case 9: return VARIACAO_REBANHO_AREA_BD.out; case 10: return VARIACAO_REBANHO_AREA_BD.nov; case 11: return VARIACAO_REBANHO_AREA_BD.dez; default: return 0.0; } } });
1.359375
1
eureka2-write-ui/app/utils/__tests__/query-test.js
Netflix/eureka-ui
29
15993684
jest.dontMock('../query'); describe('queryParser', function () { it('parses query string into a map', function () { var q = require("../query") var input = "id=i-a.* and app=eureka2-write"; var expected = { id: "i-a.*", app: "eureka2-write" }; var result = q.queryParser(input); Object.keys(expected).forEach((key) => expect(result[key]).toBe(expected[key]) ); }); }); describe('queryUriFormatter', function () { it('builds query URI', function () { var q = require("../query") var input = { id: "i-a.*", app: "eureka2-write" }; var result = q.queryUriFormatter(input); expect(result).toBe("id=i-a.*&app=eureka2-write"); }); });
1.539063
2
imports/api/settings/methods.js
dtekcth/dnollkse-2018
0
15993692
import { Meteor } from "meteor/meteor"; import { Roles } from "meteor/alanning:roles"; import { ValidatedMethod } from "meteor/mdg:validated-method"; import _ from "lodash"; import SimpleSchema from "simpl-schema"; import Settings from "./collections"; export const settingsSetupMethod = new ValidatedMethod({ name: "settings.setup", validate: new SimpleSchema({}).validator({}), run({}) { if (!this.userId) { throw new Meteor.Error("settings.methods.setup.noUser", "Need to be signed in to setup website"); } const settings = Settings.findOne(process.env.NODE_ENV); if (settings && settings.setup) { throw new Meteor.Error("settings.methods.setup.alreadySetup", "Website has already been set up"); } Roles.addUsersToRoles(this.userId, [ "admin" ]); Settings.upsert({ _id: process.env.NODE_ENV }, { $set: { setup: true } }, { removeEmptyStrings: false }); } }); export const settingsUpdateMethod = new ValidatedMethod({ name: "settings.update", validate: new SimpleSchema({ committee : Settings.simpleSchema().schema("committee"), gcalId : Settings.simpleSchema().schema("gcalId"), gcalKey : Settings.simpleSchema().schema("gcalKey"), navigation : Settings.simpleSchema().schema("navigation"), "navigation.$" : Settings.simpleSchema().schema("navigation.$"), questions : Settings.simpleSchema().schema("questions"), "questions.$" : Settings.simpleSchema().schema("questions.$"), links : Settings.simpleSchema().schema("links"), "links.$" : Settings.simpleSchema().schema("links.$"), documents : Settings.simpleSchema().schema("documents"), "documents.$" : Settings.simpleSchema().schema("documents.$"), contacts : Settings.simpleSchema().schema("contacts") }).validator({}), run({ committee, gcalId, gcalKey, questions, navigation, links, documents, contacts }) { if (!this.userId || !Roles.userIsInRole(this.userId, ["ADMIN_SETTINGS"])) { throw new Meteor.Error("settings.methods.update.notAuthorized", "Not authorized to update settings"); } const foundEmptyNav = _.find(navigation, i => { return _.isEmpty(i.text) || _.isEmpty(i.link); }); if (foundEmptyNav) { throw new Meteor.Error("settings.methods.update.navInvalid", "Nav links must have a name and a link!"); } const foundEmptyQuestion = _.find(questions, i => { return _.isEmpty(i.question) || _.isEmpty(i.answer); }); if (foundEmptyQuestion) { throw new Meteor.Error("settings.methods.update.questionInvalid", "FAQ questions must have a question and an answer!"); } const foundEmptyLink = _.find(links, i => { return _.isEmpty(i.title) || _.isEmpty(i.link); }); if (foundEmptyLink) { throw new Meteor.Error("settings.methods.update.linkInvalid", "Links must have a title and a link!"); } const foundEmptyDoc = _.find(documents, i => { return _.isEmpty(i.title) || _.isEmpty(i.text); }); if (foundEmptyDoc) { throw new Meteor.Error("settings.methods.update.docInvalid", "Documents must have a title and a text!"); } const foundEmptyContact = _.find(contacts.list, i => { return _.isEmpty(i.name) || _.isEmpty(i.value); }); if (foundEmptyContact) { throw new Meteor.Error("settings.methods.update.contactInvalid", "Contacts must have a name and a value!"); } Settings.upsert({ _id: process.env.NODE_ENV}, { $set: { committee, gcalId, gcalKey, navigation, questions, links, documents, contacts } }); } });
1.554688
2
client/src/redux/action/index.js
Hadzhi95/Marusya
2
15993700
// Add Item to Basket export const addCart = (product) => { return { type: 'ADDITEM', payload: product } } // For Delete Item in Basket export const deleteCart = (product) => { return { type: 'DELITEM', payload: product } }
1.28125
1
Airdrop/errorAirdropList.js
huybekool/TokenAirdrop
0
15993708
/** * Created by zhaoyiyu on 2018/2/13. */ var airdropList = require('./airdrop_list/airdropList.js'); airdropList.getErrorList();
0.464844
0
DIO-codificando-o-futuro/Map-filter-reduce/Map.js
JoaoVictor2000/Focando-o-futuro
0
15993716
function mapSemThis(array){//BEM MAIS FACIL return array.map(function(item){ return item*2;//multiplicando o item por dois }); } const num = [5,4,7,8,89,5]; console.log(mapSemThis(num));
1.90625
2
myfirst.js
tanyagarg2509/HACKBVP
0
15993724
// var http = require('http'); // http.createServer(function (req, res) { // res.writeHead(200, {'Content-Type': 'text/html'}); // res.end('Hello World!'); // }).listen(8080); console.log("hello"); // make a new file and write data on it const fs = require('fs'); fs.writeFileSync('hello.txt', 'hello from nodejs');
1.695313
2
src/redux/reducers/session.js
matanasow/ReduxTestProject
0
15993732
const defaultState = { userId: null, sessionId: null, error: null }; export default (state = defaultState, { type, payload }) => { switch (type) { case `SET_USER`: return { ...state, userId: payload.userId, sessionId: payload.sessionId }; case `EXECUTE_LOGIN_USER`: return { ...state, sessionId: payload.userInfo.sessionId }; case `LOGOUT_USER`: return { ...state, sessionId: null }; case `FETCH_USER_SUCCESS`: return { ...state, sessionId: payload.userInfo.sessionId, error: null }; case `FETCH_USER_FAILURE`: return { ...state, sessionId: null, error: payload.error }; case 'SHOW_NAME': return { ...state, name: payload.name } default: return state; } };
1.148438
1
communicator/extension/webcam/elements/js/wb-cam-app.63d34b8d-38.js
Traderlynk/Etherlynk
3
15993740
Polymer({ is: "fade-in-animation", behaviors: [Polymer.NeonAnimationBehavior], configure: function(i) { var e = i.node; return this._effect = new KeyframeEffect(e, [{ opacity: "0" }, { opacity: "1" }], this.timingFromConfig(i)), this._effect } }); Polymer({ is: "fade-out-animation", behaviors: [Polymer.NeonAnimationBehavior], configure: function(e) { var i = e.node; return this._effect = new KeyframeEffect(i, [{ opacity: "1" }, { opacity: "0" }], this.timingFromConfig(e)), this._effect } }); Polymer({ is: "paper-menu-grow-height-animation", behaviors: [Polymer.NeonAnimationBehavior], configure: function(e) { var i = e.node, t = i.getBoundingClientRect(), n = t.height; return this._effect = new KeyframeEffect(i, [{ height: n / 2 + "px" }, { height: n + "px" }], this.timingFromConfig(e)), this._effect } }), Polymer({ is: "paper-menu-grow-width-animation", behaviors: [Polymer.NeonAnimationBehavior], configure: function(e) { var i = e.node, t = i.getBoundingClientRect(), n = t.width; return this._effect = new KeyframeEffect(i, [{ width: n / 2 + "px" }, { width: n + "px" }], this.timingFromConfig(e)), this._effect } }), Polymer({ is: "paper-menu-shrink-width-animation", behaviors: [Polymer.NeonAnimationBehavior], configure: function(e) { var i = e.node, t = i.getBoundingClientRect(), n = t.width; return this._effect = new KeyframeEffect(i, [{ width: n + "px" }, { width: n - n / 20 + "px" }], this.timingFromConfig(e)), this._effect } }), Polymer({ is: "paper-menu-shrink-height-animation", behaviors: [Polymer.NeonAnimationBehavior], configure: function(e) { var i = e.node, t = i.getBoundingClientRect(), n = t.height; t.top; return this.setPrefixedProperty(i, "transformOrigin", "0 0"), this._effect = new KeyframeEffect(i, [{ height: n + "px", transform: "translateY(0)" }, { height: n / 2 + "px", transform: "translateY(-20px)" }], this.timingFromConfig(e)), this._effect } });
1.1875
1
src/game/uinterfaces/components/party/Slot.js
ivopc/mv-client
3
15993748
import DraggableGridSlot from "../generics/DraggableGridSlot"; class Slot extends DraggableGridSlot { constructor (scene, gridListData, gridSlotIndex) { super(scene, gridListData, gridSlotIndex); scene.add.existing(this); } }; export default Slot;
0.675781
1
src/Globals.js
weblineindia/React-Native-Custom-Alert-View
1
15993756
import {Dimensions} from 'react-native'; const { width, height }: { width: number, height: number } = Dimensions.get('window'); export const ScreenWidth: number = width; export const ScreenHeight: number = height; export const DarkGrapeFruit = 'rgb(255, 102, 102)'; export const Black30 = 'rgba(0,0,0,0.3)'; export const White = '#FFFFFF';
0.960938
1
dist/logging.js
acanto95/evabackendchallenge
0
15993764
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const config_1 = require("./config"); const winston_1 = __importDefault(require("winston")); function logger(winstonInstance) { winstonInstance.configure({ level: config_1.config.debugLogging ? 'debug' : 'info', transports: [ // // - Write all logs error (and below) to `error.log`. new winston_1.default.transports.File({ filename: 'error.log', level: 'error' }), // // - Write to all logs with specified level to console. new winston_1.default.transports.Console({ format: winston_1.default.format.combine(winston_1.default.format.colorize(), winston_1.default.format.simple()) }) ] }); return async (ctx, next) => { const start = new Date().getTime(); await next(); const ms = new Date().getTime() - start; let logLevel; if (ctx.status >= 500) { logLevel = 'error'; } else if (ctx.status >= 400) { logLevel = 'warn'; } else if (ctx.status >= 100) { logLevel = 'info'; } const msg = `${ctx.method} ${ctx.originalUrl} ${ctx.status} ${ms}ms`; winstonInstance.log(logLevel, msg); }; } exports.logger = logger; //# sourceMappingURL=logging.js.map
1.421875
1
src/ast.js
Kocisov/kyblik
0
15993772
import langFunctions from './functions'; const functionCallers = []; const fis = []; const outs = []; const variables = []; function callFunction(n, c) { const match = functionCallers.find(x => x.num === n); if (match) { if (c) { return `${match.fn}(${c})`; } return `${match.fn}()`; } return ``; } function createFunction({ name, content, index, callable }) { let _input = ``, _content = ``; const matchInput = fis.filter(x => x.index === index); const matchOutput = outs.filter(x => x.index === index); if (matchInput) { let len = matchInput.length; matchInput.map((x, ic) => { if (len === ic) { _input += `${x.name}`; } else { _input += `${x.name}, `; } _content += `if (typeof ${x.name} !== '${x.type}') { return console.log('Error: ${x.name} is not ${x.type}!'); }\n`; }); } _content += content; const _mo = matchOutput[0]; if (_mo && _mo.value.length > 1) { _content += `return ${_mo.value};`; } if (callable) { functionCallers.push({ num: callable, fn: name }); } return `function ${name}(${_input}) { ${_content} }`; } function createFunctionInput(name, type, index) { fis.push({ name, type, index }); return ``; } function createFunctionOutput(value, index) { outs.push({ value, index }); return ``; } function createIf(block, content, _else) { let _block = `if (${block}) { ${content} }`; if (_else) { _block += ` else { ${_else} }`; } return _block; } function createProgram(content) { return `(function() { 'use strict'; ${printVariables()} ${printLangFunctions()} ${content} })()`; } function createVariable(name, value) { variables.push(name); return `${name} = ${value}`; } function _debounce(fn, num) { const match = langFunctions.find(x => x.name === 'debounce'); if (match) { match.use = true; } return `debounce(${fn}, ${num})`; } function _isNumber(num) { const match = langFunctions.find(x => x.name === 'isNumber'); if (match) { match.use = true; } return `isNumber(${num})`; } function jsBlock(block) { return `${block.slice(1, -1)}`; } function log(value) { return `console.log(${value})`; } function random(start, end) { const match = langFunctions.find(x => x.name === 'random'); if (match) { match.use = true; } return `random(${start}, ${end})`; } function printLangFunctions() { let _langFunctions = ``; langFunctions.forEach(fn => { if (fn.use) { _langFunctions += `${fn.fn}\n`; } }); return `${_langFunctions}`; } function printVariables() { const u = new Set(variables); return `var ${Array.from(u)}`; } export default { callFunction, createFunction, createFunctionInput, createFunctionOutput, createIf, createProgram, createVariable, debounce: _debounce, isNumber: _isNumber, jsBlock, log, random };
2.359375
2
lib/clases/Item.js
phipex/programa-2
0
15993780
"use strict"; class Item { constructor (payload,index,next) { this.payload = payload; this.index = index this.next = next; } getPayload(){ return this.payload } setPayload(obj){ this.payload = obj } } module.exports = Item;
0.902344
1
src/ext/events.js
rauenzi/Experientia
4
15993788
const {Constants} = require("discord.js"); // Adds Commando-specific events into the Events constant. module.exports = () => { Object.assign(Constants.Events, { COMMAND_BLOCK: "commandBlock", COMMAND_CANCEL: "commandCancel", COMMAND_ERROR: "commandError", COMMAND_PREFIX_CHANGE: "commandPrefixChange", COMMAND_REGISTER: "commandRegister", COMMAND_REREGISTER: "commandReregister", COMMAND_RUN: "commandRun", COMMAND_STATUS_CHANGE: "commandStatusChange", COMMAND_UNREGISTER: "commandUnregister", GROUP_REGISTER: "groupRegister", GROUP_STATUS_CHANGE: "groupStatusChange", PROVIDER_READY: "providerReady", TYPE_REGISTER: "typeRegister", UNKNOWN_COMMAND: "unknownCommand", }); };
1.117188
1
tests/middlewares/customerSession.spec.js
tomsta93/caelus
0
15993796
var customerSession = require('../../middlewares/customerSession.js'); describe('customerSession', function() { // Same as in script var userId = 1231; // Mock objects var req = { cookies: { customerId: userId } }; var res = { cookie: function () {}, redirect: function () {} }; beforeEach(function () { this.next = function () {}; }); it('should equal a function', function () { expect(customerSession).toEqual(jasmine.any(Function)); }); it('should set a cookie if the customerId is not set', function () { var cookieParams = { maxAge: 900000, httpOnly: true }; spyOn(res, 'cookie'); req.cookies.customerId = undefined; customerSession(req, res, this.next); expect(res.cookie).toHaveBeenCalledWith('customerId', userId, cookieParams); }); it('should redirect if a cookie has been set', function () { spyOn(res, 'redirect'); req.cookies.customerId = undefined; customerSession(req, res, this.next); expect(res.redirect).toHaveBeenCalledWith('back'); }); it('should call the next callback if there is a cookie set', function () { spyOn(this, 'next'); req.cookies.customerId = userId; customerSession(req, res, this.next); expect(this.next).toHaveBeenCalled(); }); });
1.367188
1
server/controllers/api-controllers.js
Onariaginosa/GRNsight
17
15993804
module.exports = function (app) { const request = require("request"); const UNIPROT_HOST = " http://www.uniprot.org"; const JASPAR_HOST = "http://jaspar.genereg.net"; const YEASTMINE_HOST = "https://www.yeastgenome.org"; const NCBI_HOST = "https://eutils.ncbi.nlm.nih.gov"; const ENSEMBL_HOST = "http://rest.ensembl.org"; const relay = (req, res, host) => { const url = host + req.url; res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); req.pipe(request(url)).pipe(res); }; app.use("/uniprot/", (req, res) => { relay(req, res, UNIPROT_HOST); }); app.use("/jaspar/", (req, res) => { relay(req, res, JASPAR_HOST); }); app.use("/yeastmine/", (req, res) => { relay(req, res, YEASTMINE_HOST); }); app.use("/ncbi/", (req, res) => { relay(req, res, NCBI_HOST); }); app.use("/ensembl/", (req, res) => { relay(req, res, ENSEMBL_HOST); }); };
1.015625
1
packages/server/body-parser/index.js
skazkajs/skazka
2
15993812
const express = require('@skazka/server-express'); const moduleBuilder = require('@skazka/server-module'); const { json, raw, text, urlencoded, } = require('body-parser'); const setBody = (context) => { const { body } = context.req; const request = context.get('request'); if (request) { request.set('body', body); } return body; }; exports.json = moduleBuilder(async (context, options = {}) => { await express(context, json(options)); return setBody(context); }); exports.raw = moduleBuilder(async (context, options = {}) => { await express(context, raw(options)); return setBody(context); }); exports.text = moduleBuilder(async (context, options = {}) => { await express(context, text(options)); return setBody(context); }); exports.urlencoded = moduleBuilder(async (context, options) => { await express(context, urlencoded(options)); return setBody(context); });
1.257813
1
util/templates/component.js
michael-langley/tw-react
0
15993820
module.exports = (componentName) => ({ content: `// Generated with util/create-component.js import React from "react"; interface Props { } const ${componentName} = (props: Props) => { const {foo} = props return ( <div data-testid="${componentName}" className="foo-bar">{componentName}</div> ) }; export default ${componentName}; `, extension: `.tsx`, });
1.03125
1
db/userdb.js
DhanaPriyaCSE/research
0
15993828
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const userSchema = new Schema({ userName : String, Name : String, Email : String, Password : <PASSWORD>, Thumbnail : String, admin : { type: Boolean , default: false} }); const paper = new Schema({ name: { type: String, required: true }, conferencevenue: { type: String, required: true }, link: { type: String, required: true }, description: { type: String, required: true }, typeofpaper: { type: Schema.Types.ObjectId, ref: 'typeofpaper' }, indexedin: { type: Schema.Types.ObjectId, ref: 'indexedin' }, publishdate: { type: Date, required: true }, lastdatesubmission: { type: Date, required: true } }); const proposal = new Schema({ name: { type: String, required: true }, description: { type: String, required: true }, link: { type: String, required: true }, discipline: [{ type: Schema.Types.ObjectId, ref: 'discipline' }], fundingagency: [{ type: Schema.Types.ObjectId, ref: 'fundingagency' }], publishdate: { type: Date, required: true }, lastdate: { type: Date, required: true } }); const fellowship = new Schema({ researchtopic : { type : String, required: true }, description: { type: String, required: true }, lastdateapplication : { type : String, required: true }, publishdate: { type: String, required: true }, link: { type: String, required: true }, typeoffellowship: { type : Schema.Types.ObjectId, ref:'typeoffellowship' }, university : { type : Schema.Types.ObjectId, ref:'university' } }); const fundingagencydb = new Schema({ name : String }); const disciplinedb = new Schema({ name: String }); const tpeofpaperdb = new Schema({ name: String }); const indexedindb = new Schema({ name: String }); const typeoffellowshipdb = new Schema({ name: String }); const universitydb = new Schema({ name: String }); paper.index({'name' : 1, 'ministry' : 1, 'discipline' : 1},{unique : true}); // paper.on('index',(err)=>{ // console.log(err.message); // }) // mongoose.set('useCreateIndex',true); const User = mongoose.model('user',userSchema); const callpaper = mongoose.model('callforpaper',paper); const callproposal = mongoose.model('callforproposal', proposal); const callfellowship = mongoose.model('callforfellowship',fellowship); const fundingagency = mongoose.model('fundingagency',fundingagencydb); const discipline = mongoose.model('discipline',disciplinedb); const typeofpaper = mongoose.model('typeofpaper',tpeofpaperdb); const indexedin = mongoose.model('indexedin',indexedindb); const typeoffellowship = mongoose.model('typeoffellowship',typeoffellowshipdb); const university = mongoose.model('university',universitydb); module.exports = {callpaper,User,callfellowship,callproposal,fundingagency,discipline,typeofpaper,indexedin,typeoffellowship,university}; // module.exports = callpaper; // module.exports = callproposal; // module.exports = callfellowship; // module.exports = ministry; // module.exports = discipline;
1.335938
1
js/main-tags.js
oknalv/linky
0
15993836
tags = { "login-text" : "text", "save-button" : "text", "new-link" : "text", "no-links" : "text", "new-link-name" : "placeholder", "new-link-url" : "placeholder", "no-results" : "text", "tags-text" : "placeholder" }
0.089355
0
prosolo-main/src/main/webapp/resources/javascript/dashboard/dashboard-chart.js
prosolotechnologies/prosolo
0
15993844
var chart = (function() { var patterns = ["pattern-one", "pattern-two", "pattern-three", "pattern-four", "pattern-five", "pattern-six"]; function destroy(container, charts) { container.innerHTML = ""; charts.forEach(function(chart) { chart.destroy(); }); charts = []; } function setPositions(objects, config) { objects.reduce(function(y, e) { e.y = y; return y + config.step; }, config.start); } function setPatterns(objects, patterns) { objects.reduce(function(index, e) { e.pattern = patterns[index]; return index + 1; }, 0); } function renderLegendTo(selector, data) { document.querySelector(selector).innerHTML = ""; setPositions(data, {start: 40, step: 20}); setPatterns(data, patterns); var svg = d3.select(selector).append("svg"); svg.append("text") .text("Click on legend item to show/hide statistic.") .attr("x", "0") .attr("y", "20"); var paths = svg.selectAll("path") .data(data) .enter(); var node = paths.append("g").attr("class", function(d) { return d["class"]; }); node.append("svg:path") .attr("d", function(d) { return "M0 " + d.y + " l36 0"; }) .attr("class", function(d) { return d["pattern"]; }); node.append("text") .text(function(d) { return d.name; }) .attr("x", "50") .attr("y", function(d) { return d.y + 4; }) .attr("class", function(d) { return d["class"]; }); } function displayLines(container, legend) { patterns.forEach(function(pattern) { $(container + " g." + pattern).each(function() { this.classList.remove(pattern); }); }); $(legend + " svg > g").each(function() { var elementClass = $(this).attr("class"); var pattern = $(this).children("path").attr("class"); $(container + " g." + elementClass).each(function() { this.classList.add(pattern); }); }); } return { create : function(configuration) { var charts = []; var container = document.querySelector(configuration.container); return { show : function(data, from, to) { destroy(container, charts); var chart = new tauCharts.Chart({ autoResize : false, guide : { x : { label : { padding : 33 }, autoScale: false, min: from, max: to }, y : { label : { padding : 33 } }, color:{ brewer: configuration.brewer(data) } }, data : data, type : 'line', x : configuration.x, y : configuration.y, color : configuration.color, plugins : [ tauCharts.api.plugins.get('tooltip')({ fields : configuration.tooltip.fields }) ] }); chart.renderTo(configuration.container); charts.push(chart); }, renderLegend : function(data) { renderLegendTo(configuration.legend.selector, data); displayLines(configuration.container, configuration.legend.selector); $(configuration.legend.selector + " g").each(function() { var $g = $(configuration.container + " g." + $(this).attr("class")); $g.css("opacity", "100"); }); $(configuration.legend.selector + " g").click(function() { var $g = $(configuration.container + " g." + $(this).attr("class")); if ($g.size() == 0) { return; } if ($g.css("opacity") == "0") { $g.get(0).classList.add($(this).children("path").attr("class")); $g.css("opacity", "100"); $(this).children("text").get(0).classList.remove("selected"); } else { $g.removeClass(patterns); $g.css("opacity", "0"); $(this).children("text").get(0).classList.add("selected"); } }); } }; } }; })();
2.15625
2
src/token_kinds.js
tiagosr/tscc
0
15993852
const TokenKind = require("./tokens").TokenKind /** @type {TokenKind[]} */ let keyword_kinds = [] /** @type {TokenKind[]} */ let symbol_kinds = [] /** @type {TokenKind[]} */ let error_kinds = [] // keywords for base types exports.bool_kw = new TokenKind("_Bool", keyword_kinds) exports.char_kw = new TokenKind("char", keyword_kinds) exports.short_kw = new TokenKind("short", keyword_kinds) exports.int_kw = new TokenKind("int", keyword_kinds) exports.long_kw = new TokenKind("long", keyword_kinds) exports.short_kw = new TokenKind("short", keyword_kinds) exports.signed_kw = new TokenKind("signed", keyword_kinds) exports.unsigned_kw = new TokenKind("unsigned", keyword_kinds) exports.void_kw = new TokenKind("void", keyword_kinds) // keywords for data structure and storage classes exports.auto_kw = new TokenKind("auto", keyword_kinds) exports.static_kw = new TokenKind("static", keyword_kinds) exports.extern_kw = new TokenKind("extern", keyword_kinds) exports.struct_kw = new TokenKind("struct", keyword_kinds) exports.enum_kw = new TokenKind("enum", keyword_kinds) exports.union_kw = new TokenKind("union", keyword_kinds) exports.register_kw = new TokenKind("register", keyword_kinds) exports.volatile_kw = new TokenKind("volatile", keyword_kinds) exports.const_kw = new TokenKind("const", keyword_kinds) exports.typedef_kw = new TokenKind("typedef", keyword_kinds) exports.sizeof_kw = new TokenKind("sizeof", keyword_kinds) // keywords for control flow structures exports.return_kw = new TokenKind("return", keyword_kinds) exports.if_kw = new TokenKind("if", keyword_kinds) exports.else_kw = new TokenKind("else", keyword_kinds) exports.while_kw = new TokenKind("while", keyword_kinds) exports.for_kw = new TokenKind("for", keyword_kinds) exports.break_kw = new TokenKind("break", keyword_kinds) exports.continue_kw = new TokenKind("continue", keyword_kinds) exports.do_kw = new TokenKind("do", keyword_kinds) exports.switch_kw = new TokenKind("switch", keyword_kinds) exports.case_kw = new TokenKind("case", keyword_kinds) exports.default_kw = new TokenKind("default", keyword_kinds) exports.goto_kw = new TokenKind("goto", keyword_kinds) // symbols for operations exports.plus = new TokenKind("+", symbol_kinds) exports.minus = new TokenKind("-", symbol_kinds) exports.star = new TokenKind("*", symbol_kinds) exports.slash = new TokenKind("/", symbol_kinds) exports.mod = new TokenKind("%", symbol_kinds) exports.incr = new TokenKind("++", symbol_kinds) exports.decr = new TokenKind("--", symbol_kinds) exports.equals = new TokenKind("=", symbol_kinds) exports.plusequals = new TokenKind("+=", symbol_kinds) exports.minusequals = new TokenKind("-=", symbol_kinds) exports.starequals = new TokenKind("*=", symbol_kinds) exports.divequals = new TokenKind("/=", symbol_kinds) exports.modequals = new TokenKind("%=", symbol_kinds) exports.xorequals = new TokenKind("^=", symbol_kinds) exports.complequals = new TokenKind("~=", symbol_kinds) exports.equalequal = new TokenKind("==", symbol_kinds) exports.notequal = new TokenKind("!=", symbol_kinds) exports.bool_and = new TokenKind("&&", symbol_kinds) exports.bool_or = new TokenKind("||", symbol_kinds) exports.bool_not = new TokenKind("!", symbol_kinds) exports.lt = new TokenKind("<", symbol_kinds) exports.gt = new TokenKind(">", symbol_kinds) exports.lt_eq = new TokenKind("<=", symbol_kinds) exports.gt_eq = new TokenKind(">=", symbol_kinds) exports.amp = new TokenKind("&", symbol_kinds) exports.xor = new TokenKind("^", symbol_kinds) exports.pound = new TokenKind("#", symbol_kinds) exports.lshift = new TokenKind("<<", symbol_kinds) exports.rshift = new TokenKind(">>", symbol_kinds) exports.lshiftequals = new TokenKind("<<=", symbol_kinds) exports.rshiftequals = new TokenKind(">>=", symbol_kinds) exports.compl = new TokenKind("~", symbol_kinds) // symbols for character sequences exports.dquote = new TokenKind('"', symbol_kinds) exports.squote = new TokenKind("'", symbol_kinds) exports.open_paren = new TokenKind("(", symbol_kinds) exports.close_paren = new TokenKind(")", symbol_kinds) exports.open_brack = new TokenKind("{", symbol_kinds) exports.close_brack = new TokenKind("}", symbol_kinds) exports.open_sq_brack = new TokenKind("[", symbol_kinds) exports.close_sq_brack = new TokenKind("]", symbol_kinds) exports.q_mark = new TokenKind("?", symbol_kinds) exports.colon = new TokenKind(":", symbol_kinds) exports.comma = new TokenKind(",", symbol_kinds) exports.semicolon = new TokenKind(";", symbol_kinds) exports.dot = new TokenKind(".", symbol_kinds) exports.arrow = new TokenKind("->", symbol_kinds) exports.identifier = new TokenKind() exports.number = new TokenKind() exports.string = new TokenKind() exports.char_string = new TokenKind() exports.include_file = new TokenKind() exports.define_placeholder = new TokenKind() exports.error_char_string_size = new TokenKind("", error_kinds) exports.keyword_kinds = keyword_kinds exports.symbol_kinds = symbol_kinds exports.error_kinds = error_kinds
1.296875
1
src/main.js
azieger/covap-frontend
0
15993860
import './plugins/vuex' import Vue from 'vue' import VueRouter from "vue-router"; import UIkit from 'uikit'; import Icons from 'uikit/dist/js/uikit-icons'; import store from './store' import routes from "./routes"; import App from "./App"; import i18n from './i18n' Vue.config.productionTip = false; Vue.use(VueRouter); UIkit.use(Icons); const router = new VueRouter({ routes }); new Vue({ render: h => h(App), i18n, store, router }).$mount('#app');
0.992188
1
ui/raidboss/data/triggers/general.js
Amiral-Benson/cactbot
0
15993868
// Triggers for all occasions and zones. [{ zoneRegex: /.*/, triggers: [ { id: 'General Provoke', regex: /:(\y{Name}):1D6D:Provoke:/, condition: function(data) { return data.role == 'tank' }, infoText: function(data, matches) { return 'Provoke: ' + data.ShortName(matches[1]); }, tts: function(data, matches) { return 'provoke ' + data.ShortName(matches[1]); }, }, { id: 'General Ultimatum', regex: /:(\y{Name}):1D73:Ultimatum:/, condition: function(data) { return data.role == 'tank' }, infoText: function(data, matches) { return 'Ultimatum: ' + data.ShortName(matches[1]); }, tts: function(data, matches) { return 'ultimatum ' + data.ShortName(matches[1]); }, }, { id: 'General Shirk', regex: /:(\y{Name}):1D71:Shirk:/, condition: function(data) { return data.role == 'tank' }, infoText: function(data, matches) { return 'Shirk: ' + data.ShortName(matches[1]); }, tts: function(data, matches) { return 'shirk ' + data.ShortName(matches[1]); }, }, { id: 'General Holmgang', regex: /:(\y{Name}):2B:Holmgang:/, condition: function(data) { return data.role == 'tank' }, infoText: function(data, matches) { return 'Holmgang: ' + data.ShortName(matches[1]); }, tts: function(data, matches) { return 'holmgang ' + data.ShortName(matches[1]); }, }, { id: 'General Hallowed', regex: /:(\y{Name}):1E:Hallowed Ground:/, condition: function(data) { return data.role == 'tank' }, infoText: function(data, matches) { return 'Hallowed: ' + data.ShortName(matches[1]); }, tts: function(data, matches) { return 'hallowed ' + data.ShortName(matches[1]); }, }, { id: 'General Living', regex: /:(\y{Name}):E36:Living Dead:/, condition: function(data) { return data.role == 'tank' }, infoText: function(data, matches) { return 'Living: ' + data.ShortName(matches[1]); }, tts: function(data, matches) { return 'living ' + data.ShortName(matches[1]); }, }, { id: 'General Walking', regex: /:(\y{Name}) gains the effect of Walking Dead/, condition: function(data) { return data.role == 'tank' }, infoText: function(data, matches) { return 'Walking: ' + data.ShortName(matches[1]); }, tts: function(data, matches) { return 'walking ' + data.ShortName(matches[1]); }, }, { id: 'General Ready check', regex: /:(?:(\y{Name}) has initiated|You have commenced) a ready check\./, sound: '../../resources/sounds/Overwatch/D.Va_-_Game_on.ogg', soundVolume: 0.6, }, ], }];
0.863281
1
src/view/items/Component.js
thomsbg/ractive
0
15993876
import runloop from '../../global/runloop'; import { fatal, warnIfDebug, warnOnceIfDebug } from '../../utils/log'; import { COMPONENT, INTERPOLATOR, YIELDER } from '../../config/types'; import Item from './shared/Item'; import construct from '../../Ractive/construct'; import initialise from '../../Ractive/initialise'; import render from '../../Ractive/render'; import { create } from '../../utils/object'; import { removeFromArray } from '../../utils/array'; import { isArray } from '../../utils/is'; import resolve from '../resolvers/resolve'; import { cancel, rebind, unbind } from '../../shared/methodCallers'; import Hook from '../../events/Hook'; import Fragment from '../Fragment'; import parseJSON from '../../utils/parseJSON'; import fireEvent from '../../events/fireEvent'; import updateLiveQueries from './component/updateLiveQueries'; function removeFromLiveComponentQueries ( component ) { let instance = component.ractive; while ( instance ) { const query = instance._liveComponentQueries[ `_${component.name}` ]; if ( query ) query.remove( component ); instance = instance.parent; } } function makeDirty ( query ) { query.makeDirty(); } const teardownHook = new Hook( 'teardown' ); export default class Component extends Item { constructor ( options, ComponentConstructor ) { super( options ); this.type = COMPONENT; // override ELEMENT from super const instance = create( ComponentConstructor.prototype ); this.instance = instance; this.name = options.template.e; this.parentFragment = options.parentFragment; this.complexMappings = []; this.liveQueries = []; if ( instance.el ) { warnIfDebug( `The <${this.name}> component has a default 'el' property; it has been disregarded` ); } let partials = options.template.p || {}; if ( !( 'content' in partials ) ) partials.content = options.template.f || []; this._partials = partials; // TEMP this.yielders = {}; construct( this.instance, { partials }); // find container let fragment = options.parentFragment; let container; while ( fragment ) { if ( fragment.owner.type === YIELDER ) { container = fragment.owner.container; break; } fragment = fragment.parent; } // add component-instance-specific properties instance.parent = this.parentFragment.ractive; instance.container = container || null; instance.root = instance.parent.root; instance.component = this; // for hackability, this could be an open option // for any ractive instance, but for now, just // for components and just for ractive... instance._inlinePartials = partials; if ( this.template.v ) this.setupEvents(); } bind () { const viewmodel = this.instance.viewmodel; const childData = viewmodel.value; // determine mappings if ( this.template.a ) { Object.keys( this.template.a ).forEach( localKey => { const template = this.template.a[ localKey ]; if ( template === 0 ) { // empty attributes are `true` viewmodel.joinKey( localKey ).set( true ); } else if ( typeof template === 'string' ) { const parsed = parseJSON( template ); viewmodel.joinKey( localKey ).set( parsed ? parsed.value : template ); } else if ( isArray( template ) ) { if ( template.length === 1 && template[0].t === INTERPOLATOR ) { let model = resolve( this.parentFragment, template[0] ); if ( !model ) { warnOnceIfDebug( `The ${localKey}='{{${template[0].r}}}' mapping is ambiguous, and may cause unexpected results. Consider initialising your data to eliminate the ambiguity`, { ractive: this.instance }); // TODO add docs page explaining this this.parentFragment.ractive.get( localKey ); // side-effect: create mappings as necessary model = this.parentFragment.findContext().joinKey( localKey ); } viewmodel.map( localKey, model ); if ( model.get() === undefined && localKey in childData ) { model.set( childData[ localKey ] ); } } else { const fragment = new Fragment({ owner: this, template }).bind(); const model = viewmodel.joinKey( localKey ); model.set( fragment.valueOf() ); // this is a *bit* of a hack fragment.bubble = () => { Fragment.prototype.bubble.call( fragment ); model.set( fragment.valueOf() ); }; this.complexMappings.push( fragment ); } } }); } initialise( this.instance, { partials: this._partials }, { indexRefs: this.instance.isolated ? {} : this.parentFragment.indexRefs, keyRefs: this.instance.isolated ? {} : this.parentFragment.keyRefs, cssIds: this.parentFragment.cssIds }); } bubble () { if ( !this.dirty ) { this.dirty = true; this.parentFragment.bubble(); } } checkYielders () { Object.keys( this.yielders ).forEach( name => { if ( this.yielders[ name ].length > 1 ) { runloop.end(); throw new Error( `A component template can only have one {{yield${name ? ' ' + name : ''}}} declaration at a time` ); } }); } detach () { return this.instance.fragment.detach(); } find ( selector ) { return this.instance.fragment.find( selector ); } findAll ( selector, query ) { this.instance.fragment.findAll( selector, query ); } findComponent ( name ) { if ( !name || this.name === name ) return this.instance; if ( this.instance.fragment ) { return this.instance.fragment.findComponent( name ); } } findAllComponents ( name, query ) { if ( query.test( this ) ) { query.add( this.instance ); if ( query.live ) { this.liveQueries.push( query ); } } this.instance.fragment.findAllComponents( name, query ); } firstNode () { return this.instance.fragment.firstNode(); } rebind () { this.complexMappings.forEach( rebind ); this.liveQueries.forEach( makeDirty ); // update relevant mappings if ( this.template.a ) { const viewmodel = this.instance.viewmodel; Object.keys( this.template.a ).forEach( localKey => { const template = this.template.a[ localKey ]; if ( isArray( template ) && template.length === 1 && template[0].t === INTERPOLATOR ) { let model = resolve( this.parentFragment, template[0] ); if ( !model ) { // TODO is this even possible? warnOnceIfDebug( `The ${localKey}='{{${template[0].r}}}' mapping is ambiguous, and may cause unexpected results. Consider initialising your data to eliminate the ambiguity`, { ractive: this.instance }); this.parentFragment.ractive.get( localKey ); // side-effect: create mappings as necessary model = this.parentFragment.findContext().joinKey( localKey ); } viewmodel.map( localKey, model ); } }); } this.instance.fragment.rebind( this.instance.viewmodel ); } render ( target ) { render( this.instance, target, null ); this.checkYielders(); updateLiveQueries( this ); this.rendered = true; } setupEvents () { Object.keys( this.template.v ).forEach( name => { const template = this.template.v[ name ]; if ( typeof template !== 'string' ) { fatal( 'Components currently only support simple events - you cannot include arguments. Sorry!' ); } const ractive = this.ractive; this.instance.on( name, function () { let event; // semi-weak test, but what else? tag the event obj ._isEvent ? if ( arguments.length && arguments[0] && arguments[0].node ) { event = Array.prototype.shift.call( arguments ); } const args = Array.prototype.slice.call( arguments ); fireEvent( ractive, template, { event, args }); // cancel bubbling return false; }); }); } toString () { return this.instance.toHTML(); } unbind () { this.complexMappings.forEach( unbind ); const instance = this.instance; instance.viewmodel.teardown(); instance.fragment.unbind(); instance._observers.forEach( cancel ); removeFromLiveComponentQueries( this ); if ( instance.fragment.rendered && instance.el.__ractive_instances__ ) { removeFromArray( instance.el.__ractive_instances__, instance ); } teardownHook.fire( instance ); } unrender ( shouldDestroy ) { this.shouldDestroy = shouldDestroy; this.instance.unrender(); this.liveQueries.forEach( query => query.remove( this.instance ) ); } update () { this.instance.fragment.update(); this.checkYielders(); this.dirty = false; } }
1.257813
1
src/containers/app/sidebars/topology/machine/UnitListContainer.js
atlarge-research/opendc-frontend
3
15993884
import { connect } from "react-redux"; import UnitListComponent from "../../../../../components/app/sidebars/topology/machine/UnitListComponent"; const mapStateToProps = (state, ownProps) => { return { unitIds: state.objects.machine[ state.objects.rack[ state.objects.tile[state.interactionLevel.tileId].objectId ].machineIds[state.interactionLevel.position - 1] ][ownProps.unitType + "Ids"], inSimulation: state.currentExperimentId !== -1 }; }; const UnitListContainer = connect(mapStateToProps)(UnitListComponent); export default UnitListContainer;
1.101563
1
events/ready.js
selfbot33/bot
0
15993892
module.exports = class { constructor(client) { this.client = client; } async run() { await this.client.wait(1000); this.client.appInfo = await this.client.fetchApplication(); setInterval(async () => { this.client.appInfo = await this.client.fetchApplication(); }, 60000); this.client.user.setActivity("with Alex"); const channel = this.client.channels.get("539467117939130398"); channel.send(":gear: Le bot est redémarré !"); this.client.logger.log( `Flareon est prêt à espionner ${ this.client.users.size } utilisateurs sur ${this.client.channels.size} salons.`, "ready" ); } };
1.25
1
8-kyu/Who is going to pay for the wall?/index.js
ayessetova/codeW
314
15993900
/* Title: Who is going to pay for the wall? Description: <NAME> lives in a nice neighborhood, but one of his neighbors has started to let his house go. <NAME> wants to build a wall between his house and his neighbor’s, and is trying to get the neighborhood association to pay for it. He begins to solicit his neighbors to petition to get the association to build the wall. Unfortunately for <NAME>het, he cannot read very well, has a very limited attention span, and can only remember two letters from each of his neighbors’ names. As he collects signatures, he insists that his neighbors keep truncating their names until two letters remain, and he can finally read them. Your code will show Full name of the neighbor and the truncated version of the name as an array. If the number of the characters in name is equal or less than two, it will return an array containing only the name as is" Kata Link: https://www.codewars.com/kata/who-is-going-to-pay-for-the-wall Discuss Link: https://www.codewars.com/kata/who-is-going-to-pay-for-the-wall/discuss Solutions Link: https://www.codewars.com/kata/who-is-going-to-pay-for-the-wall/solutions */ // Long Solution const whoIsPaying = name => name.length <= 2 ? [name] : [name, name.slice(0, 2)] // Function Export module.exports = whoIsPaying
2.953125
3
lib/validation/ValidationsStudyRequestBulk.js
CityofToronto/bdit_flashcrow
6
15993908
import { email, required } from 'vuelidate/lib/validators'; const ValidationsStudyRequestBulk = { ccEmails: { $each: { required, torontoInternal(ccEmail) { return email(ccEmail) && ccEmail.endsWith('@toronto.ca'); }, }, }, name: { required, }, notes: {}, }; export default ValidationsStudyRequestBulk;
1.015625
1
js/formatos/OtrosCriterios.js
mercedes06/progrmas_presupuestales
0
15993916
var id_cuantificacion; $(document).ready(function () { /**Inicializar variables**/ url = $("#url").val(); id_cuantificacion = $("#id_cuantificacion").val().trim(); listar_Criterios(); }); function agregar_criterio() { var nombre = $("#nombre_criterio").val().trim(); var descripcion_criterio = $("#descripcion_criterio").val().trim(); if (nombre == "" || descripcion_criterio == "" ) { new PNotify({ title: 'Por favor llene todos los campos correctamente', type: 'error', }) } else { /**Seguir aqui la insercion de datos**/ var recurso = "acciones/criterios/agregar"; var data = {nombre_criterio:nombre,descripcion:descripcion_criterio,idCuantificacion:id_cuantificacion}; $.ajax({ type: "POST", url: url + recurso, data: data, success: function (data) { if (data == "correcto") { var nombre = $("#nombre_criterio").val(""); var descripcion_criterio = $("#descripcion_criterio").val(""); listar_Criterios(); new PNotify({ title: 'Criterio agregado correctamente', type: 'success', }) } else { new PNotify({ title: 'Error al insertar los datos, comuníquese con soporte', type: 'error', }) } } }); } } function listar_Criterios() { var recurso = "acciones/criterios/listar/"+id_cuantificacion; $.ajax({ type: "GET", url: url + recurso, success: function (data) { $("#listado_criterios_body").empty(); $("#listado_criterios_body").append(data); } }); } function EliminarCriterio(id_criterio) { new PNotify({ title: 'Eliminar', text: '¿Esta seguro de eliminar este criterio?', icon: 'fa fa-question-circle', type: 'warning', hide: false, confirm: { confirm: true }, buttons: { closer: false, sticker: false }, history: { history: false }, addclass: 'stack-modal', stack: {'dir1': 'down', 'dir2': 'right', 'modal': true} }).get().on('pnotify.confirm', function () { var recurso = "acciones/criterios/eliminar"; var data_recurso = {idCriterio:id_criterio}; $.ajax({ type: "POST", url: url + recurso, data: data_recurso, success: function (data) { if (data == "correcto") { listar_Criterios(); new PNotify({ title: 'Criterio eliminado correctamente', type: 'success', }) } else { new PNotify({ title: 'Error en la petición, comuniquese con soporte', type: 'error', }) } } }); }).on('pnotify.cancel', function () { // alert('Cancelado'); }) } function ActualizarCriterio(id_criterio) { var nombre = $("#nombre_criterio"+id_criterio).val().trim(); var descripcion_criterio = $("#descripcion_criterio"+id_criterio).val().trim(); if (nombre == "" || descripcion_criterio == "" ) { new PNotify({ title: 'Por favor llene todos los campos correctamente', type: 'error', }) } else { /**Seguir aqui la insercion de datos**/ var recurso = "acciones/criterios/actualizar"; var data_recurso = {nombre_criterio:nombre,descripcion:descripcion_criterio,idcriterio:id_criterio}; $.ajax({ type: "POST", url: url + recurso, data: data_recurso, success: function (data) { if (data == "correcto") { listar_Criterios(); new PNotify({ title: 'Servicio actualizado correctamente', type: 'success', }) } else { new PNotify({ title: 'No hay cambios detectados en la actualización de su criterio', type: 'info', }) } } }); } }
1.414063
1
Lingang.City.Brain/Scripts/Modules/Society/s_RightLayer.js
lingangcitybrain/Lingang3DScreen
0
15993924
define(["config", "common", "util","s_layerMenuData", "s_LayerMenuAjax"], function (con, com,util, s_layerMenuData, s_LayerMenuAjax) { /**************************************右侧显示图层**************************************/ return { EventData: new util.HashMap, //加载右侧DIV loadRithHtml: function () { var url = con.HtmlUrl + 'Society/Right_Container.html'; require(['text!' + url], function (template) { $("#right_02").html(template); $("#right_02").show('drop', 1000);//左侧 ; require("s_RightLayer").loadEventList();//加载事件列表 }) }, //加载事件列表 loadEventList: function (){ $("#right_EventList").hide(); var url = con.HtmlUrl + 'Society/R_EventList.html'; require(['text!' + url], function (template) { $("#right_EventList").html(template); $("#right_EventList").slideDown("fast"); //$("#right_EventList").stop().animate({ right: "0px" }, 300); require("s_RightLayer").generateEventList(); }) }, //生成事件列表 generateEventList: function (post_data) { require("s_LayerMenuAjax").getEventList(post_data, function (result) { var data = require("sl_Event").POIData; var html = ''; var num = 0; for (var i = 0; i < data.length; i++) { num++; var poiName = "POISociety" + require("s_Main").LayerCatalog.Event.List[data[i].communityId].Name + "_" + data[i].id;//POIIOT_01 html += '<li class="sjxx-li" onclick="require(&apos;sl_Event&apos;).loadEventDetail(' + poiName + ')">' + '<div class="sjxx-li-line1">' + '<span class="sjxx-id counter">' + num + '</span>' + '<span class="sjxx-event">' + data[i].eventName + '</span>' + '<span class="fr sjxx-state">' + data[i].statusName + '</span>' + '</div>' + '<div class="sjxx-address">' + data[i].address + '<span class="fr sjxx-time">' + con.getNowFormatDate(data[i].createTime) + '<span>' + data[i].dealPerson + '</span></span>' + '</div>' + '</li>'; require("s_RightLayer").EventData.put(data[i].id, data[i]); } $("#ul_eventlist").html(html); }); }, loadEventDetail: function (poiName) { var layeractive = $("#bottom_menu ul li.active").text(); console.log(layeractive); switch (layeractive) { case "传感器": require("sl_IOT").Revert(); //加载事件POI和事件详情 require("sl_Event").loadEvent(); break; case "摄像头": require("sl_Camera").Revert(); //加载事件POI和事件详情 require("sl_Event").loadEvent(); break; case "无人机": require("sl_Drone").Revert(); //加载事件POI和事件详情 require("sl_Event").loadEvent(); break; case "村居工作站": require("sl_WorkStation").Revert(); //加载事件POI和事件详情 require("sl_Event").loadEvent(); break; case "海岸线": require("sl_SeaboardLine").Revert(); //加载事件POI和事件详情 require("sl_Event").loadEvent(); break; case "工地": require("sl_WorkSite").Revert(); //加载事件POI和事件详情 require("sl_Event").loadEvent(); break; case "街面": require("sl_Street").Revert(); //加载事件POI和事件详情 require("sl_Event").loadEvent(); break; case "网格": require("sl_Grid").Revert(); //加载事件POI和事件详情 require("sl_Event").loadEvent(); break; default://事件 break; } //显示左侧社区页面 $("#society_twocolright").hide() $("#society_twocolright").show('drop', 1000); //var data = this.EventData.get(id); //图层选中事件 $("#full_container #bottom_menu ul li").removeClass("active"); $("#full_container #bottom_menu ul li").eq(6).addClass("active"); //加载事件POI和事件详情 setTimeout(function () { require("sl_Event").loadEventDetial(poiName) }, 1500); }, loadEventPOI: function (nodename) { } } });
1.492188
1