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
vue/components/ui/molecules/form-input/form-input.stories.js
ripe-tech/ripe-components-vue
8
15997948
import { storiesOf } from "@storybook/vue"; import { withKnobs, text, number, select } from "@storybook/addon-knobs"; storiesOf("Components/Molecules/Form Input", module) .addDecorator(withKnobs) .add("Form Input", () => ({ props: { variant: { default: select( "Variant", { Unset: null, Inline: "inline" }, null ) }, header: { default: text("Header", "Header") }, alignment: { default: select( "Alignment", { Left: "left", Center: "center", Right: "right" }, "left" ) }, footer: { default: text("Footer", "Footer") }, headerVariant: { default: select( "Header Variant", { Unset: null, Error: "error", Warning: "warning", Success: "success" }, null ) }, headerSize: { default: select( "Header Size", { Unset: null, Small: "small", Medium: "medium", Large: "large" }, "medium" ) }, footerVariant: { default: select( "Footer Variant", { Unset: null, Error: "error", Warning: "warning", Success: "success" }, null ) }, footerSize: { default: select( "Footer Size", { Unset: null, Small: "small", Medium: "medium", Large: "large" }, "small" ) }, headerMinWidth: { default: number("Header Minimum Width", null) }, footerMinWidth: { default: number("Footer Minimum Width", null) } }, template: ` <form-input v-bind:variant="variant" v-bind:alignment="alignment" v-bind:header="header" v-bind:footer="footer" v-bind:header-variant="headerVariant" v-bind:header-size="headerSize" v-bind:footer-variant="footerVariant" v-bind:footer-size="footerSize" v-bind:header-min-width="headerMinWidth" v-bind:footer-min-width="footerMinWidth" > <input-ripe /> </form-input> ` }));
1.546875
2
packages/narries/src/App.js
kunalkumar007/react-projects
0
15997956
import { useState } from 'react'; import './App.css'; import AddToDo from './components/addToDo'; import Filter from './components/Filter'; import ToDoList from './components/toDoList'; window.id = 0; function App() { const [value, setvalue] = useState(''); const [tasks, settasks] = useState([]); const handleChange = (e) => setvalue(e.target.value); const handleTasks = (val) => { let customTask = { text: val, completed: false, id: window.id++ }; settasks((task) => [...task, customTask]); }; const handleCleartasks = () => { settasks([]); window.location.reload(); }; const handleClick = (id) => { console.log(id); let modifiedTasks = tasks.map((task) => { if (task.id === id) { return Object.assign({}, task, { completed: !task.completed }); } return task; }); settasks(modifiedTasks); }; return ( <div className="row flex-center flex-middle flex"> <div className="border border-primary padding-large margin-large no-responsive paper"> <h3>Narries ToDo</h3> <AddToDo onChange={handleChange} value={value} onAdd={handleTasks} /> <ToDoList tasks={tasks} remove={handleClick} /> <Filter onClear={handleCleartasks} /> </div> </div> ); } export default App;
1.8125
2
src/main/resources/public/javascript/profitAndLossesReportControl.js
GerardoSant/Finbook
0
15997964
function redirectToSeeMoreBills(field){ var query; if (field=="grossSales"){ query='&billType=income' } if(field=="salesReturns"){ query='&billType=egress' } if (field=="grossPurchases"||field=="purchasesReturns"){ query='&class=received&billType=purchases' } if (field=="externalServices"){ query='&class=received&billType=services' } if (field=="salariesAndWages"){ query='&billType=payroll' } window.location ="/bills" + "?redirected=true"+ "&periodStart=" + document.getElementById('pStart').value + "&" + "periodEnd=" + document.getElementById('pEnd').value+query; }
0.945313
1
server.js
flow-build/observer
0
15997972
const { startup, settings } = require('./src'); startup(settings, (err) => { if (err) { console.log(err); process.exit(1); } console.log('server started sucessfully'); });
0.898438
1
seed.js
ymclapp/canOfBooksBack
0
15997980
const mongoose = require('mongoose'); require('dotenv').config(); mongoose.connect(process.env.MONGODB_URL); const Books = require('./models/bookRoute'); //constructor async function seed() { //Deleting all of my books and starting over console.log('Deleting existing books') await Books.deleteMany({}); const myBook1 = new Books({ title: "Where the Red Fern Grows", description: "A sad book", status: "Out", email: "<EMAIL>", }); await myBook1.save(); const myBook2 = new Books({ title: "Discovery of Witches", description: "A witch book", status: "In", email: "<EMAIL>", }); await myBook2.save(); const myBook3 = new Books({ title: "Neon Prey", description: "A Lucas Davenport book", status: "In", email: "<EMAIL>", }); await myBook3.save(); mongoose.disconnect(); } seed();
1.703125
2
src/layouts/index.js
sanjaytwisk/gatsby-starter-default
0
15997988
import React from 'react' import PropTypes from 'prop-types' import Link from 'gatsby-link' import Helmet from 'react-helmet' import Navigation from '../components/Navigation'; import '../styles/all.css'; const pages = [ { url: '', title: 'Home' }, { url: '/contact', title: 'Contact' } ]; const TemplateWrapper = ({ children }) => ( <div> <Helmet title="Gatsby starter fork" meta={[ { name: 'description', content: 'Gatsby starter fork' }, { name: 'keywords', content: 'gatsby, starter, fork' }, ]} /> <Navigation links={pages} /> <main className="page"> {children()} </main> </div> ); TemplateWrapper.propTypes = { children: PropTypes.func, data: PropTypes.object }; export default TemplateWrapper;
1.289063
1
tutorials/Web_Apps_with_Leaflet_and_D3/final/bar_chart.js
bolliger32/dam-visualization
1
15997996
function barChart() { // Various internal, private variables of the module. var margin = {top: 10, right: 20, bottom: 45, left: 50}, width = 450, height = 200; var xScale = d3.scaleBand(); var yScale = d3.scaleLinear(); var xDomain, yDomain; var xAxis = d3.axisBottom(xScale) .tickFormat(d3.timeFormat("%Y")); var yAxis = d3.axisLeft(yScale); var axisLabel = 'Axis Label'; var dispatcher = d3.dispatch("barMouseover", "barMouseleave"); // Main internal module functionality function chart(selection) { selection.each(function(data) { var chartW = width - margin.left - margin.right; var chartH = height - margin.top - margin.bottom; // Update domains xDomain = data.map(function(d) { return d.date; }); yDomain = [0, d3.max(data, function(d) { return d.value; })] // Set the domain and range of x-scale. xScale .domain(xDomain) .range([0, chartW]) .padding(0.1); // Set the domain and range of y-scale. yScale .domain(yDomain) .range([chartH, 0]); // Select the svg element, if it exists. var svg = d3.select(this).selectAll("svg").data([data]); var tooltip = d3.select(this).append("div").attr("class", "toolTip"); var svgEnter = svg.enter() .append('svg'); /** * Append the elements which need to be inserted only once to svgEnter * Following is a list of elements that area inserted into the svg once **/ var container = svgEnter .append("g") .classed('container', true); container .append("g") .attr("class", "bars"); container .append("g") .attr("class", "y axis"); container .append("g") .attr("class", "x axis"); /* * Following actions happen every time the svg is generated */ svgEnter = svgEnter.merge(svg); // Update the outer dimensions. svgEnter .attr("width", width) .attr("height", height); // Update the inner dimensions. container .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); // Place x axis at the bottom of the chart container.select(".x.axis") .attr("transform", "translate(0," + chartH + ")") .call(xAxis) .selectAll("text") .style("text-anchor", "end") .attr("dx", "-.8em") .attr("dy", "-.55em") .attr("transform", "rotate(-90)"); // Place y-axis at the left svgEnter.select(".y.axis") .call(yAxis) .append("text") .attr('transform', 'rotate(-90)') .attr('y', 0 - margin.left) .attr('x', 0 - (chartH / 2)) .attr('dy', '1em') .style('text-anchor', 'middle') .text(axisLabel); // Setup the enter, exit and update of the actual bars in the chart. var barContainer = svgEnter.select(".bars"); // Select the bars, and bind the data to the .bar elements. var bars = barContainer.selectAll(".bar").data(data); bars.exit() .transition() .duration(300) .remove(); // data that needs DOM = enter() (a set/selection, not an event!) bars.enter().append("rect") .attr("class", "bar") .attr("x", function(d) { return xScale(d.date); }) .attr("width", xScale.bandwidth()) .attr("y", function(d) { return yScale(d.value); }) .attr("height", function(d) { return chartH - yScale(d.value); }) .on("mouseover", function(d){ tooltip .style("left", d3.event.pageX + 2 + "px") .style("top", d3.event.pageY + 2 + "px") .style("display", "inline-block") .html(d.value); }) .on("mouseleave", function(d){ tooltip .style("display", "none"); }) // the "UPDATE" set: bars.transition() .duration(300) .attr("x", function(d) { return xScale(d.date); }) .attr("width", xScale.bandwidth()) .attr("y", function(d) { return yScale(d.value); }) .attr("height", function(d) { return chartH - yScale(d.value); }); }); } // A series of public getter/setter functions chart.margin = function(_) { if (!arguments.length) return margin; margin = _; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.axisLabel = function(_) { if (!arguments.length) return axisLabel; axisLabel = _; return chart; }; chart.xDomain = function(_) { if (!arguments.length) return xDomain; xDomain = _; return chart; }; chart.yDomain = function(_) { if (!arguments.length) return yDomain; yDomain = _; return chart; }; chart.on = function () { var value = dispatcher.on.apply(dispatcher, arguments); return value === dispatcher ? chart : value; }; return chart; }
2.078125
2
memory/app.js
rafavital/js-games
1
15998004
document.addEventListener('DOMContentLoaded', ()=>{ var chosen_cards = [] var chosen_cards_id = [] var won_cards = [] const cards = [ { name: 'card01', image: 'assets/tiles/001.png' }, { name: 'card01', image: 'assets/tiles/001.png' }, { name: 'card02', image: 'assets/tiles/002.png' }, { name: 'card02', image: 'assets/tiles/002.png' }, { name: 'card03', image: 'assets/tiles/003.png' }, { name: 'card03', image: 'assets/tiles/003.png' }, { name: 'card04', image: 'assets/tiles/004.png' }, { name: 'card04', image: 'assets/tiles/004.png' }, { name: 'card05', image: 'assets/tiles/005.png' }, { name: 'card05', image: 'assets/tiles/005.png' }, { name: 'card06', image: 'assets/tiles/006.png' }, { name: 'card06', image: 'assets/tiles/006.png' } ] cards.sort(()=>0.5 - Math.random()) const grid = document.querySelector('.grid') const result = document.querySelector('#result') function create_board() { for (let i = 0; i < cards.length; i++) { const card = document.createElement('img') card.setAttribute('src', 'assets/tiles/blank.png') card.setAttribute('data-id', i) card.addEventListener('click', flipcard) grid.appendChild(card) } } function check_for_match() { let all_cards = document.querySelectorAll('img') const card1 = chosen_cards_id[0] const card2 = chosen_cards_id[1] if (cards[card1].name === cards[card2].name) { alert("That's a match!") all_cards[card1].setAttribute('src', 'assets/tiles/white.png') all_cards[card2].setAttribute('src', 'assets/tiles/white.png') won_cards.push(chosen_cards) } else { all_cards[card1].setAttribute('src', 'assets/tiles/blank.png') all_cards[card2].setAttribute('src', 'assets/tiles/blank.png') } chosen_cards = [] chosen_cards_id = [] result.textContent = won_cards.length if (won_cards.length === cards.length / 2) result.textContent = 'CONGRATULATIONS! YOU GOT THEM ALL!' } function flipcard() { let card_id = this.getAttribute('data-id') chosen_cards.push(cards[card_id].name) chosen_cards_id.push(card_id) this.setAttribute('src', cards[card_id].image) if (chosen_cards.length == 2) { setTimeout(check_for_match, 500); } } create_board() })
2.109375
2
src/utils/dataMigration.js
yufeixin/automa
0
15998012
import browser from 'webextension-polyfill'; import dbLogs from '@/db/logs'; export default async function () { try { const { logs, logsCtxData, migration } = await browser.storage.local.get([ 'logs', 'migration', 'logsCtxData', ]); const hasMigrated = migration || {}; const backupData = {}; if (!hasMigrated.logs && logs) { const ids = new Set(); const items = []; const ctxData = []; const logsData = []; const histories = []; for (let index = logs.length - 1; index > 0; index -= 1) { const { data, history, ...item } = logs[index]; const logId = item.id; if (!ids.has(logId) && ids.size < 500) { items.push(item); logsData.push({ logId, data }); histories.push({ logId, data: history }); ctxData.push({ logId, data: logsCtxData[logId] }); ids.add(logId); } } await Promise.all([ dbLogs.items.bulkAdd(items), dbLogs.ctxData.bulkAdd(ctxData), dbLogs.logsData.bulkAdd(logsData), dbLogs.histories.bulkAdd(histories), ]); backupData.logs = logs; hasMigrated.logs = true; await browser.storage.local.remove('logs'); } await browser.storage.local.set({ migration: hasMigrated, ...backupData, }); } catch (error) { console.error(error); } }
1.421875
1
app/src/components/App.js
dhrumil24patel/toddler_task_client
1
15998020
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import { footer } from '../styles/footer.scss'; import Routes from '../../routes'; import { graphql, compose, withApollo } from 'react-apollo'; import GetAllUsers from '../../graphql/queries/getAllUsers'; class App extends Component { render() { console.log(this.props); return( <div> <h1>Filter table</h1> </div> ); } } // const App = () => // <div> // <h1>Filter table</h1> // { Routes } // <footer className={footer}> // <Link to="/">Filterable Table</Link> // <Link to="/about">About</Link> // <Link to="/login">Login</Link> // </footer> // </div>; export default withApollo(compose( graphql( GetAllUsers, { options: () => ({ fetchPolicy: 'cache-first', context: { version: 1 } // refetchQueries: [{ // query: SomeOtherQuery, // context: { version: 1 }, // <-- need this to split the link correctly but refetchQueries only accepts `query` and `variables`. Also context might be different than the mutate query. // variables: {/*...*/ } // }] }), props: ({ data: { users = [], loading } }) => ({ users: users, loading }) } ) )(App));
1.453125
1
src/main/webapp/karma.conf.js
saimahanth/MLL
0
15998028
module.exports = function(config) { config.set({ basePath: '', frameworks: ['jasmine'], files: [ './dist/styles/bootstrap-*.css', './dist/styles/styles-*.css', './dist/scripts/jquery-*.js', './dist/scripts/bootstrap-*.js', './dist/scripts/angular-*.js', './dist/scripts/app-templates-*.js', './dist/scripts/app-*.js', './tests/**/*.js' ], exclude: [ ], preprocessors: { }, plugins : [ 'karma-jasmine', 'karma-chrome-launcher', 'karma-junit-reporter' ], reporters: ['dots', 'junit'], colors: true, logLevel: config.LOG_INFO, autoWatch: false, browsers: ['Chrome'], singleRun: true, concurrency: Infinity, junitReporter: { outputDir: 'dist/', outputFile: 'test-results.xml', useBrowserName: false } }) };
0.914063
1
lib/db-stream.js
jarofghosts/todo
0
15998036
var through = require('through') module.exports = dbStream function dbStream(db) { var stream = through(write) return stream function write(data) { db.put(data.id, data) } }
0.738281
1
js/index.js
Njeri714/Delani-Studios
0
15998044
// what we do $(document).ready(function () { $(".design-icon").click(function () { $(".design-description").toggle(); $(".design-icon").hide(); $(".design, .design-description").click(function () { $(".design-icon").show(); $(".design-description").hide(); }); }); $(".development-icon").click(function () { $(".development-description").toggle(); $(".development-icon").hide(); $(".development, .development-description").click(function () { $(".development-description").hide(); $(".development-icon").show(); }); }); $(".product-icon").click(function () { $(".product-description").toggle(); $(".product-icon").hide(); $(".product, .product-description").click(function () { $(".product-icon").show(); $(".product-description").hide(); }); }); }); // what we do ends // contact const validation = () =>{ var name = document.getElementById("submit").value.trim(); var username = document.getElementById("username").value.trim(); var usermail = document.getElementById("usermail").value.trim(); var message = document.getElementById("message").value.trim(); if(name == "" || username == "" || usermail == "" || message == ""){ alert("please fill all fields"); return false; }else{ alert("Thank you"+ " " + username + " "+"for contacting us"); var name = document.getElementById("submit").value=""; var username = document.getElementById("username").value=""; var usermail = document.getElementById("usermail").value=""; var message = document.getElementById("message").value=""; return false; } } // contact
0.847656
1
src/components/Vocabulary/subtypes/Item/ListTemplates.js
gbif/registry-console
3
15998052
import React from "react"; import { FormattedMessage } from 'react-intl'; export const LabelListTemplate = ({item}) => <React.Fragment><span>{item.value}</span> {item.key && <span style={{color: '#bbb'}}><FormattedMessage id={`vocabulary.language.${item.key}`}/></span>}</React.Fragment> export const DefinitionListTemplate = ({item}) => <React.Fragment><span style={{color: '#bbb'}}><FormattedMessage id={`vocabulary.language.${item.key}`}/></span><br/><span>{item.value}</span></React.Fragment> export const MultiMapTemplate = ({item}) => <React.Fragment><span style={{color: '#bbb'}}><FormattedMessage id={`vocabulary.language.${item.key}`}/></span><br/>{item.value.join(" | ")}</React.Fragment>
1.132813
1
app/containers/app.js
harryhope/newshack
3
15998060
import React from 'react' import {Switch, Route, Redirect} from 'react-router-dom' import styled, {createGlobalStyle} from 'styled-components' import styledNormalize from 'styled-normalize' import Nav from 'components/nav' import Feed from 'containers/feed' import Item from 'containers/item' import Error from 'containers/error' import {colors, fonts} from 'styles/variables' const GlobalStyle = createGlobalStyle` ${styledNormalize} html { width: 100%; box-sizing: border-box; } body, #app { width: 100%; font-family: ${fonts.sans}; font-size: 16px; color: ${colors.dark}; @media (prefers-color-scheme: dark) { color: ${colors.light}; background: ${colors.dark}; } } *, *:before, *:after { box-sizing: inherit; } a { text-decoration: none; } ` const Wrapper = styled.div` width: 100%; position: relative; ` const Footer = styled.footer` padding-bottom: 40px; ` const App = () => <Wrapper> <GlobalStyle /> <Nav /> <Switch> <Route exact path='/' render={() => <Redirect to='/top' />} /> <Route exact path='/item/:id' component={Item} /> {[ '/:page(top|new|show|ask|job)', '/:page(top|new|show|ask|job)/:number' ].map((path, index) => <Route exact key={index} path={path} component={Feed} /> )} <Route component={Error} /> </Switch> <Footer /> </Wrapper> export default App
1.523438
2
week1/NumberToPattern.js
marciogurka/bioinfo-I-algorithms
0
15998068
import NumberToSymbol from './NumberToSymbol'; /** * @description Convert the number to a respective pattern. * * @param {Number} index - The value that will be converted * @param {Number} k - The k-mer that will be used to convert * @returns The pattern that represents the number. */ function NumberToPattern(index, k) { if (k === 1) return NumberToSymbol(index); const prefixIndex = Math.floor(index / 4); const remainder = index % 4; const symbol = NumberToSymbol(remainder); const prefixPattern = NumberToPattern(prefixIndex, k - 1); return prefixPattern.concat(symbol); } // console.log(NumberToPattern(5437, 7)); export default NumberToPattern;
1.648438
2
client/src/components/ProtectedRoute/ProtectedRoute.js
forgetfulmind/birdUp
1
15998076
import React, { useState, useEffect } from "react"; import { Route, Redirect } from "react-router-dom"; import { connect } from "react-redux"; function Protectedroute({isSignedIn}) { console.log(isSignedIn) return ( <hello>hello</hello> // <Route // path={path} // {...rest} // render={(props)=>{ // if(!isSignedIn){ // return Component ? <Component {...props}/> : render // }else { // console.log("redirected to") // return <Redirect to={{pathname: '/', state: {from: props.location}}}/> // } // }} /> ) } const mapStateToProps = (state) => { return { isSignedIn: state.auth.isSignedIn, userId: state.auth.userId }; }; export default connect(mapStateToProps)(Protectedroute);
1.5625
2
07-routing/lab/spa-demo/src/views/login.js
BoyanPeychinov/js-applications
0
15998084
import * as api from '../api/data.js' const section = document.getElementById('loginSection'); section.remove(); const form = section.querySelector('form'); form.addEventListener('submit', onSubmit); let ctx = null; export function showLoginPage(ctxTarget) { ctx = ctxTarget; ctx.showSection(section); } async function onSubmit(event) { event.preventDefault(); const formData = new FormData(form); const email = formData.get('email'); const password = formData.get('password'); await api.login(email, password); ctx.updateUserNav(); ctx.goTo('home'); }
1.265625
1
exercises/17/site/static/index.js
yaternovskiy/web-security-essentials
50
15998092
helloBtn.addEventListener("click", async e => { e.target.disabled = true; e.target.innerText = "Done!"; await fetch("/", { credentials: "same-origin", method: "POST", headers: { "Content-type": "application/x-www-form-urlencoded", "csrf-token": e.target.dataset.csrftoken }, body: "message=hello" }); window.location.reload(); });
1.171875
1
components/salud-mission-statement-banner/salud-mission-statement-banner.js
chtinahow/Salud-Consulting
0
15998100
const saludMissionStatementBanner = () => { const { registerHtml } = window['tram-one'] const html = registerHtml() return (props, children) => { return html` <h2 class="salud-mission-statement-banner vhs-top"> <div class="vhs-fade vhs-delay-3 vhs-duration-6"> ${children} </div> </h2> ` } }
0.9375
1
packages/babel-parser/test/fixtures/esprima/invalid-syntax/migrated_0040/input.js
wuweiweiwu/babel
42,609
15998108
/test /
-0.369141
0
sc-types-frontend-extras/compiled/src/reactLike/typeGuards.js
cancerberoSgx/suitecommerce-types
1
15998116
define('typeGuards', [], function () { return { isTextTransformer: function (n) { return n && n.transformText; }, isChildTransformer: function (n) { return n && n.transformChild; }, isReactLikeChildAddTransformer: function (n) { return n && n.addChild; }, isNode: function (n) { return n && n.nodeType; }, isReactLikeComponent: function (c) { return c.prototype && c.prototype.render; }, isHTMLElement: function (n) { return n && n.nodeType === 1 && n.outerHTML; } }; });
0.988281
1
scripts/build-copy.js
mhsattarian/nodeschool.github.io
1
15998124
#!/usr/bin/env node const Path = require('path') const Fs = require('fs') const mkdirp = require('mkdirp') const cmdwatcher = require('./util/cmdwatcher') const processing = {} const waiting = {} function process(file) { if (processing[file]) { waiting[file] = true } processing[file] = true var output = Path.join('.build', file) mkdirp.sync(Path.dirname(output)) Fs.createReadStream(file) .pipe( Fs.createWriteStream(output) .on('end', function () { delete processing[file] if (waiting[file]) { delete waiting[file] process(file) } }) ) } cmdwatcher('build-copy' , ['!(node_modules)/**/*.@(png|jpg|svg|css|gif|ico)','*.@(png|jpg|svg|css|gif|ico)', 'js/*', 'CNAME'] , function processFiles(files) { files.forEach(process) })
1.328125
1
examples/agnoster-prompt.js
lcrespom/nash
5
15998132
/** * NOTICE: this prompt plugin requires that the terminal is configured * with a font that supports the special characters used to display it. * * A good source of such fonts is the * [Powerline](https://github.com/powerline/fonts) GitHub page. */ const chalk = require(NODE_MODULES + '/chalk') const { setPrompt } = require(NASH_BASE + '/prompt') const { setTerminalTitle } = require(NASH_BASE + '/terminal') const { gitStatus, gitStatusFlags } = require(NASH_BASE + '/plugins/git-status') const SEGMENT_SEPARATOR = '\ue0b0' const GIT_SYMBOL = '\ue0a0' function err(retCode) { if (retCode == 0) return '' return ` (${retCode})` } function gitSection() { let gstatus = gitStatus() if (!gstatus) return chalk.blue(SEGMENT_SEPARATOR) let flags = gitStatusFlags(gstatus) // if (flags == '') flags = '✔' let fgcolor = gstatus.dirty ? 'yellow' : 'green' let bgcolor = gstatus.dirty ? 'bgYellow' : 'bgGreen' let sep1 = chalk.blue[bgcolor](SEGMENT_SEPARATOR) let status = ' ' + GIT_SYMBOL + ' ' + gstatus.branch + ' ' + flags + ' ' let sep2 = chalk[fgcolor](SEGMENT_SEPARATOR) return sep1 + chalk.black[bgcolor](status) + sep2 } function prompt({ cwd, username, hostname, retCode }) { let ctx = chalk.black.bgCyan(` ${username}@${hostname} `) let ss1 = chalk.cyan.bgBlue(SEGMENT_SEPARATOR) let dir = chalk.white.bgBlue(` ${cwd} `) let nsh = chalk.white.bgMagenta(err(retCode) + ' nash ') let ss3 = chalk.magenta(SEGMENT_SEPARATOR) return ctx + ss1 + dir + gitSection() + '\n' + nsh + ss3 + ' ' } setPrompt(prompt) setTerminalTitle('Nash')
1.695313
2
helpers/database.js
livio-zanardo/peoplebudget
0
15998140
/** * @module database */ const { ClientError, ServerError } = require("../helpers/error"); /** * Will check is a resource already exists * @name alreadyExists * @function * @memberof module:database * @param {Function} dbModel - Database object function * @param {Object} query - Object used to query database * @returns {Promise} returns a promise that will resolve to be a Boolean or an Error object */ alreadyExists = (dbModel, query) => { return new Promise(async (resolve, reject) => { try { const res = await dbModel.findAll({ where: query }); res.length < 1 ? resolve(true) : reject( new ClientError( 400, `Type:'${dbModel.name}', with query params:[${Object.keys( query ).join(",")}], already exists.` ) ); } catch (error) { reject(error); } }); }; module.exports = { alreadyExists };
1.664063
2
kafka-backend/services/hire-service.js
hychrisli/cmpe273-lab2
0
15998148
const Project = require('../models/project'); const Bid = require('../models/bid'); const handler = require('./handler'); exports.handleHire = (req, cb) =>{ console.log(req); Promise.all([ Project.findOne({_id: req.projectId, employerId: req.employerId}), Bid.findOne({_id: req.chosenBid}), ]) .then (([project, bid]) => { console.log(project, bid); if ( project === null) cb('Invalid Project'); else if ( bid === null ) cb(new Error('Invalid BId')); else { Promise.all([ Project.update({_id: req.projectId}, {$set: {status: 1, chosenBid: bid._id, chosenBidder: bid.userId}}), Bid.update({projectId: req.projectId}, {$set: {isActive: false}}, {multi: true}) ]) .then( data => { cb(null, data); }) .catch(err=>{ console.log(err); cb(err); }); } }).catch(err => { console.log(err); cb(err) }); };
1.289063
1
src/gifs/trending/trending.resolvers.js
Hustenbonbon/giphy-graphql
9
15998156
export const gifTrendingResolvers = { Query: { trendingGifs: (root, { limit, offset, rating }, { dataSources }) => dataSources.GifsTrendingAPI.getTrendingGifs(limit, offset, rating) } };
0.582031
1
kefir/predication.js
devismael03/kefir-js
58
15998164
/* # Turkish Predication and Copula turkish language copulas, which are called as ek-eylem which literally means 'suffix-verb' are one of the most distinct features of turkish grammar. TODO: Remove unused imports. */ const { join, skipFalsyAndJoin, NOTHING } = require('./functional') const Suffix = require('./suffix') const { getLastVowel, getVowelSymbol, Back, Front, isFront, voice, endsWithConsonant, endsWithVoiceless, UNROUNDED_BACK_VOWELS, ROUNDED_BACK_VOWELS, UNROUNDED_FRONT_VOWELS, ROUNDED_FRONT_VOWELS, harmony, swapFrontAndBack } = require('./phonology') const Person = { FIRST: 'first', SECOND: 'second', THIRD: 'third' } const Copula = { NEGATIVE: 'negative', ZERO: 'zero', TOBE: 'tobe', PERSONAL: 'personal', PERFECTIVE: 'perfective', IMPERFECTIVE: 'imperfective', PROGRESSIVE: 'progressive', NECESSITATIVE: 'necessitative', FUTURE: 'future', IMPOTENTIAL: 'impotential', CONDITIONAL: 'conditional' } const getCopulaProcessor = copula => { const CopulaProcessors = { [Copula.NEGATIVE]: negative, [Copula.ZERO]: zero, [Copula.TOBE]: tobe, [Copula.PERSONAL]: personal, [Copula.PERFECTIVE]: perfective, [Copula.IMPERFECTIVE]: imperfective, [Copula.PROGRESSIVE]: progressive, [Copula.NECESSITATIVE]: necessitative, [Copula.FUTURE]: future, [Copula.IMPOTENTIAL]: impotential, [Copula.CONDITIONAL]: conditional } return CopulaProcessors[copula] } /* #### zero copula is the rule for third person, as in hungarian and russian. that means two nouns, or a noun and an adjective can be juxtaposed to make a sentence without using any copula. third person plural might be indicated with the use of plural suffix "-lar/-ler". ✎︎ examples ``` yogurt kültür (yogurt [is-a] culture) abbas yolcu (abbas [is-a] traveller) evlerinin önü yonca (the front of their home [is-a] plant called yonca) ``` ✎︎ tests ```python >>> zero('yolcu') 'yolcu' ``` */ const zero = (predicate, person = Person.THIRD, isPlural = false) => predicate /* ''' #### negative negation is indicated by the negative copula değil. değil is never used as a suffix, but it takes suffixes according to context. ✎︎ examples ``` yogurt kültür değildir (yogurt [is-not-a] culture) abbas yolcu değildir (abbas [is-not-a] traveller) evlerinin önü yonca değildir (the front of their home [is-not-a] yonca) ``` ✎︎ tests ```python >>> negative('yolcu') 'yolcu değil' ``` ''' */ const negative = (predicate, person = Person.THIRD, isPlural = false, delimiter = Suffix.DELIMITER) => join(predicate, delimiter, Suffix.NEGATIVE) /* ### tobe turkish "to be" as regular/auxiliary verb (olmak). ✎︎ examples ``` yogurt kültürdür (yogurt [is] culture) abbas yolcudur (abbas [is] traveller) evlerinin önü yoncadır (the front of their home [is] plant called yonca) ``` ✎︎ tests ```python >>> tobe('yolcu') 'yolcudur' >>> tobe('üzüm') 'üzümdür' >>> tobe('yonca') 'yoncadır' ``` */ const tobe = (predicate, person = Person.THIRD, isPlural = false) => { const lastVowel = getLastVowel(predicate) const sound = getVowelSymbol(lastVowel) const map = [ [UNROUNDED_BACK_VOWELS, Back.I], [UNROUNDED_FRONT_VOWELS, Front.I], [ROUNDED_BACK_VOWELS, Back.U], [ROUNDED_FRONT_VOWELS, Front.U] ] for (let [vowels, affix] of map) { if (vowels.includes(sound)) { return skipFalsyAndJoin( predicate, Suffix.D, affix, Suffix.R ) } } } /* ### personification copula ✎︎ examples ``` ben buralıyım (i'm from here) sen oralısın (you're from over there) aynı gezegenliyiz (we're from same planet) ``` ✎︎ tests ```python >>> personal('uçak', Person.FIRST, is_plural=False) 'uçağım' >>> personal('oralı', Person.SECOND, is_plural=False) 'oralısın' >>> personal('gezegenli', Person.FIRST, is_plural=True) 'gezegenliyiz' ``` */ const personal = (predicate, whom = Person.THIRD, isPlural = false) => impersonate(predicate, whom, isPlural, false) /* ### inferential mood (-miş in turkish) it is used to convey information about events which were not directly observed or were inferred by the speaker. ✎︎ examples ``` elmaymışım (i was an apple as i've heard) üzülmüşsün (you were sad as i've heard) doktormuş (he/she/it was a doctor as i've heard) üzümmüşsün (you were a grape as i've heard) ``` ✎︎ tests ```python >>> inferential('öğretmen', Person.SECOND, is_plural=False) 'öğretmenmişsin' >>> inferential('üzül', Person.SECOND, is_plural=False) 'üzülmüşsün' >>> inferential('robot', Person.FIRST, is_plural=False) 'robotmuşum' >>> inferential('robot', Person.THIRD, is_plural=False) 'robotmuş' >>> inferential('ada', Person.THIRD, is_plural=False) 'adaymış' ``` */ const inferential = (predicate, whom = Person.THIRD, isPlural = false) => { const lastVowel = getLastVowel(predicate) const sound = getVowelSymbol(lastVowel) const inferenceSuffix = join('m', harmony(sound), 'ş') return skipFalsyAndJoin( predicate, // combinative consontant ⟨y⟩ !endsWithConsonant(predicate) ? Suffix.Y : NOTHING, impersonate(inferenceSuffix, whom, isPlural) ) } /* ### inferential mood (-isem in turkish) It is a grammatical mood used to express a proposition whose validity is dependent on some condition, possibly counterfactual. ✎︎ examples ``` elmaysam (if i am an apple) üzümsen (if you are a grape) bıçaklarsa (if they are a knife) ``` ✎︎ tests ```python >>> conditional('elma', Person.FIRST, is_plural=False) 'elmaysam' >>> conditional('üzüm', Person.SECOND, is_plural=False) 'üzümsen' >>> conditional('bıçak', Person.THIRD, is_plural=True) 'bıçaklarsa' ``` */ const conditional = (predicate, whom = Person.THIRD, isPlural = false) => { const conditionSuffix = isFront(predicate) ? Suffix.SE : Suffix.SA const map = [ [Person.FIRST, false, Suffix.M], [Person.SECOND, false, Suffix.N], [Person.THIRD, false, NOTHING], [Person.FIRST, true, Suffix.K], [Person.SECOND, true, Suffix.NIZ], [Person.THIRD, true, NOTHING] ] for (let [toWhom, plurality, personification] of map) { if (toWhom == whom && plurality == isPlural) { return skipFalsyAndJoin( predicate, // plural suffix for 3rd person (whom == Person.THIRD && isPlural) ? (isFront(predicate) ? Suffix.LER : Suffix.LAR) : NOTHING, // combinative consontant ⟨y⟩ !endsWithConsonant(predicate) ? Suffix.Y : NOTHING, conditionSuffix, personification ) } } } /* ### alethic modality (-idi in turkish) linguistic modality that indicates modalities of truth, in particular the modalities of logical necessity, possibility or impossibility. ✎︎ examples ``` elmaydım (i was an apple) üzümdün (you were a grape) doktordu (he/she/it was a doctor) ``` ✎︎ tests ```python >>> perfective('açık', Person.FIRST, is_plural=False) 'açıktım' >>> perfective('oralı', Person.SECOND, is_plural=False) 'oralıydın' >>> perfective('dalda', Person.FIRST, is_plural=False) 'daldaydım' >>> perfective('dalda', Person.THIRD, is_plural=False) 'daldaydı' >>> perfective('dalda', Person.FIRST, is_plural=True) 'daldaydık' >>> perfective('dalda', Person.SECOND, is_plural=True) 'daldaydınız' >>> perfective('dalda', Person.THIRD, is_plural=True) 'daldaydılar' >>> perfective('gezegende', Person.THIRD, is_plural=True) 'gezegendeydiler' ``` */ const perfective = (predicate, whom = Person.THIRD, isPlural = false) => impersonate(predicate, whom, isPlural, true) /* ### the imperfective (-iyor in turkish) grammatical aspect used to describe a situation viewed with interior composition. describes ongoing, habitual, repeated, or similar semantic roles, whether that situation occurs in the past, present, or future. ✎︎ examples ``` gidiyorum (i'm going) kayıyor (he's skating) üzümlüyor (he's graping) ``` ✎︎ tests ```python >>> imperfective('açı', Person.FIRST, is_plural=False) 'açıyorum' >>> imperfective('açık', Person.FIRST, is_plural=False) 'açıkıyorum' >>> imperfective('oralı', Person.SECOND, is_plural=False) 'oralıyorsun' >>> imperfective('dal', Person.THIRD, is_plural=False) 'dalıyor' >>> imperfective('dal', Person.FIRST, is_plural=True) 'dalıyoruz' >>> imperfective('dal', Person.FIRST, is_plural=True) 'dalıyoruz' >>> imperfective('dal', Person.SECOND, is_plural=True) 'dalıyorsunuz' >>> imperfective('dal', Person.THIRD, is_plural=True) 'dalıyorlar' ``` */ const imperfective = (predicate, whom = Person.THIRD, isPlural = false) => { const lastVowel = getLastVowel(predicate) const sound = getVowelSymbol(lastVowel) const imperfectCopula = skipFalsyAndJoin( endsWithConsonant(predicate) ? harmony(sound) : NOTHING, Suffix.IMPERFECT ) return join(predicate, impersonate(imperfectCopula, whom, isPlural, false)) } /* ''' ### the future tense (-iyor in turkish) is a verb form that generally marks the event described by the verb as not having happened yet, but expected to happen in the future. ✎︎ examples ``` gidecek (he'll go) ölecek (he'll die) can alacak (he'll kill someone) ``` ✎︎ tests ```python >>> future('gel', Person.FIRST, is_plural=False) 'geleceğim' >>> future('açık', Person.FIRST, is_plural=False) 'açıkacağım' >>> future('gel', Person.FIRST, is_plural=True) 'geleceğiz' ``` ''' */ const future = (predicate, whom = Person.THIRD, isPlural = false) => { const futureCopula = join( predicate, isFront(predicate) ? Suffix.FUTURE : swapFrontAndBack(Suffix.FUTURE), ) return impersonate(futureCopula, whom, isPlural, false) } /* ''' ### progressive tense ✎︎ examples gülmekteyim (i am in the process of laughing) ölmekteler (they are in the process of dying 👾) ✎︎ tests ```python >>> progressive('gel', Person.FIRST, is_plural=False) 'gelmekteyim' >>> progressive('açık', Person.FIRST, is_plural=False) 'açıkmaktayım' >>> progressive('gel', Person.FIRST, is_plural=True) 'gelmekteyiz' ``` ''' */ const progressive = (predicate, whom = Person.THIRD, isPlural = false) => { const progressiveCopula = join( predicate, isFront(predicate) ? Suffix.PROGRESSIVE : swapFrontAndBack(Suffix.PROGRESSIVE) ) return impersonate(progressiveCopula, whom, isPlural, false) } /* ### necessitative copula ✎︎ examples ``` gitmeliyim (i must go) kaçmalıyım (i must run away) ``` ✎︎ tests ```python >>> necessitative('git', Person.FIRST, is_plural=False) 'gitmeliyim' >>> necessitative('açık', Person.FIRST, is_plural=False) 'açıkmalıyım' >>> necessitative('uza', Person.FIRST, is_plural=True) 'uzamalıyız' ``` */ const necessitative = (predicate, whom = Person.THIRD, isPlural = false) => { const necessitativeCopula = join( predicate, isFront(predicate) ? Suffix.NECESSITY : swapFrontAndBack(Suffix.NECESSITY) ) return impersonate(necessitativeCopula, whom, isPlural, false) } /* ### impotential copula ✎︎ examples ``` gidemem (i cannot come) kaçamayız (we cannot run away) ``` ✎︎ tests ```python >>> impotential('git', Person.FIRST, is_plural=False) 'gidemem' >>> impotential('git', Person.SECOND, is_plural=False) 'gidemezsin' >>> impotential('git', Person.THIRD, is_plural=False) 'gidemez' >>> impotential('git', Person.FIRST, is_plural=True) 'gidemeyiz' >>> impotential('git', Person.FIRST, is_plural=True) 'gidemeyiz' >>> impotential('git', Person.SECOND, is_plural=True) 'gidemezsiniz' >>> impotential('git', Person.THIRD, is_plural=True) 'gidemezler' >>> impotential('al', Person.THIRD, is_plural=True) 'alamazlar' ``` */ const impotential = (predicate, whom = Person.THIRD, isPlural = false) => { let impotentialCopula = isFront(predicate) ? Suffix.IMPOTENTIAL : swapFrontAndBack(Suffix.IMPOTENTIAL) let plurality = isFront(predicate) ? Suffix.LER : Suffix.LAR const map = [ [Person.FIRST, false, Suffix.M], [Person.SECOND, false, Suffix.Z + Suffix.SIN], [Person.THIRD, false, Suffix.Z], [Person.FIRST, true, Suffix.Y + Suffix.IZ], [Person.SECOND, true, Suffix.Z + Suffix.SIN + Suffix.IZ], [Person.THIRD, true, Suffix.Z + plurality] ] for (let [toWhom, plurality, personification] of map) { if (toWhom == whom && plurality == isPlural) { return skipFalsyAndJoin( voice(predicate), // combinative consontant ⟨y⟩ !endsWithConsonant(predicate) ? Suffix.Y : NOTHING, impotentialCopula, personification ) } } } const firstPersonSingular = (text, inPast = false) => { const lastVowel = getLastVowel(text) const sound = getVowelSymbol(lastVowel) return skipFalsyAndJoin( // last vowel should not be voiced in alethic modality inPast ? text : voice(text), // combinative consontant ⟨y⟩ !endsWithConsonant(text) ? Suffix.Y : NOTHING, // ⟨d⟩ or ⟨t⟩ inPast ? (endsWithVoiceless(text) ? Suffix.T : Suffix.D) : NOTHING, // ⟨a⟩ ⟨i⟩ ⟨u⟩ ⟨ü⟩ harmony(sound), Suffix.M ) } const secondPersonSingular = (text, inPast = false) => { const lastVowel = getLastVowel(text) const sound = getVowelSymbol(lastVowel) return skipFalsyAndJoin( text, // combinative consontant ⟨y⟩ inPast ? !endsWithConsonant(text) ? Suffix.Y : NOTHING : NOTHING, // ⟨d⟩ or ⟨t⟩ inPast ? (endsWithVoiceless(text) ? Suffix.T : Suffix.D) : NOTHING, // sound ⟨s⟩ in present time !inPast ? Suffix.S : NOTHING, // # ⟨a⟩ ⟨i⟩ ⟨u⟩ ⟨ü⟩ harmony(sound), Suffix.N ) } const thirdPersonSingular = (text, inPast = false) => { const lastVowel = getLastVowel(text) const sound = getVowelSymbol(lastVowel) return skipFalsyAndJoin( text, // combinative consontant ⟨y⟩ !endsWithConsonant(text) ? Suffix.Y : NOTHING, // add ⟨t⟩ or ⟨d⟩ for alethic modality inPast ? (endsWithVoiceless(text) ? Suffix.T : Suffix.D) : NOTHING, // # ⟨a⟩ ⟨i⟩ ⟨u⟩ ⟨ü⟩ inPast ? harmony(sound) : NOTHING ) } const firstPersonPlural = (text, inPast = false) => { const lastVowel = getLastVowel(text) const sound = getVowelSymbol(lastVowel) return skipFalsyAndJoin( // last vowel should not be voiced in alethic modality inPast ? text : voice(text), // combinative consontant ⟨y⟩ !endsWithConsonant(text) ? Suffix.Y : NOTHING, // ⟨d⟩ or ⟨t⟩ inPast ? (endsWithVoiceless(text) ? Suffix.T : Suffix.D) : NOTHING, // # ⟨a⟩ ⟨i⟩ ⟨u⟩ ⟨ü⟩ harmony(sound), inPast ? Suffix.K : Suffix.Z ) } const secondPersonPlural = (text, inPast = false) => { const lastVowel = getLastVowel(text) const sound = getVowelSymbol(lastVowel) return skipFalsyAndJoin( secondPersonSingular(text, inPast), // # ⟨a⟩ ⟨i⟩ ⟨u⟩ ⟨ü⟩ harmony(sound), Suffix.Z ) } const thirdPersonPlural = (text, inPast = false) => skipFalsyAndJoin( thirdPersonSingular(text, inPast), // -lar or -ler, plural affix isFront(text) ? Suffix.LER : Suffix.LAR ) const impersonate = (text, toWhom, isPlural, inPast = false) => { const map = [ [Person.FIRST, false, firstPersonSingular], [Person.SECOND, false, secondPersonSingular], [Person.THIRD, false, thirdPersonSingular], [Person.FIRST, true, firstPersonPlural], [Person.SECOND, true, secondPersonPlural], [Person.THIRD, true, thirdPersonPlural] ] for (let [person, plurality, processor] of map) { if (person == toWhom && isPlural == plurality) { return processor(text, inPast) } } } const predicate = (text, person = Person.THIRD, copula = Copula.ZERO, isPlural = false) => { try { let processor = getCopulaProcessor(copula) return processor(text, person, isPlural) } catch (e) { throw new Error(`invalid copula. options: ${JSON.values(Copula).join(', ')}`) } } module.exports = { Person, zero, negative, tobe, personal, inferential, conditional, perfective, imperfective, future, progressive, necessitative, predicate, Copula, impotential }
2.4375
2
app/js/controllers/home-controller.js
onefen/Angular-JS-Issue-Tracking-System-AngularJS-Practical-Project
0
15998172
'use strict'; issueTrackerSystem.controller('HomeController', [ '$scope', '$location', '$window', 'authenticationService', 'authorizationService', 'notificationService', 'userService', function($scope, $location, $window, authenticationService, authorizationService, notificationService, userService) { var getCurrentUserInfo = function() { userService.getCurrentUser() .then(function(currentUser) { sessionStorage['userName'] = currentUser.Username; sessionStorage['userId'] = currentUser.Id; sessionStorage['isAdmin']= currentUser.isAdmin; $scope.currentUser = currentUser; $scope.username = currentUser.Username; $location.path('/dashboard'); }, function(error) { notificationService.showError('Request failed' + error.statusText); }); }; $scope.userData = authorizationService; $scope.login = function login(user) { authenticationService.loginUser(user) .then(function(loggedInUser) { notificationService.showInfo('Logged successful'); sessionStorage['token'] = loggedInUser.access_token; getCurrentUserInfo(); }, function(error) { notificationService.showError('Request failed' + error.statusText); }); }; $scope.register = function register(user) { authenticationService.registerUser(user) .then(function(loggedInUser) { notificationService.showInfo('Logged successful'); $scope.login(user); }, function(error) { notificationService.showError('Request failed' + error.statusText); }); }; }]);
1.109375
1
client/src/pages/Families.js
anasm23/MeetTheNewNeighbors
0
15998180
import React, { useState, useEffect } from "react"; // React-icons import { HiUserGroup } from "react-icons/hi"; import { IoInformationCircleSharp } from "react-icons/io5"; import { FaComments } from "react-icons/fa"; import { render } from 'react-dom'; import { BrowserRouter as Router, Route, Switch } from "react-router-dom"; import Jumbotron from "../components/Jumbotron"; import API from "../utils/API"; import { Link } from "react-router-dom"; import { Col, Row, Container } from "../components/Grid"; import { List, ListItem } from "../components/List"; import { Input, TextArea, FormBtn } from "../components/Form"; import "./Styles/Families.css"; import FamilyData from "../components/Table" import Profile from '../components/Profile'; import { useAuth0 } from '@auth0/auth0-react'; import ReactCalendar from "./Calendar"; function Families() { // Setting our component's initial state const [families, setFamilies] = useState([]) const [formObject, setFormObject] = useState({}) const { user, isAuthenticated } = useAuth0(); // Load all families and store them with setFamilies useEffect(() => { loadFamilies() }, []) // Loads all families and sets them to families function loadFamilies() { API.getFamilies() .then(res => setFamilies(res.data) ) .catch(err => console.log(err)); }; // Handles updating component state when the user types into the input field function handleInputChange(event) { const { name, value } = event.target; setFormObject({ ...formObject, [name]: value }) }; // When the form is submitted, use the API.saveFamily method to save the family data // Then reload families from the database function handleFormSubmit(event) { event.preventDefault(); if (formObject.family && formObject.address) { API.saveFamily({ family: formObject.family, email: formObject.email, address: formObject.address, numAdults: formObject.numAdults, adultsName: formObject.adultsName, numKids: formObject.numKids, kidsName: formObject.kidsName, numPets: formObject.numPets, petsName: formObject.petsName, likes: formObject.likes, photo: formObject.photo, }) .then(res => loadFamilies()) .catch(err => console.log(err)); } }; return ( <Container fluid> <Row> <Col size="md-12"> <Profile /> <Jumbotron /> </Col> </Row> {isAuthenticated && <Row> <Col size="md-6"> <h2 className="resInfo">Enter Residents Info. Below <IoInformationCircleSharp /></h2> <form className="res-form"> <Input onChange={handleInputChange} name="family" placeholder="Residents Name(required)" /> <Input onChange={handleInputChange} name="email" placeholder= "Make Sure You Use The Email You Sign Up With" // value= {user.email} /> <Input onChange={handleInputChange} name="address" placeholder="Home Address (required)" /> <Input onChange={handleInputChange} name="numAdults" placeholder="Number of Adults" /> <Input onChange={handleInputChange} name="adultsName" placeholder="Adults Name(s)" /> <Input onChange={handleInputChange} name="numKids" placeholder="Number of Kids" /> <Input onChange={handleInputChange} name="kidsName" placeholder="Kids Name(s)" /> <Input onChange={handleInputChange} name="numPets" placeholder="Number of Pets" /> <Input onChange={handleInputChange} name="petsName" placeholder="Pets Type and Name(s)" /> <TextArea onChange={handleInputChange} name="likes" placeholder="Family Likes / Interests" /> <Input onChange={handleInputChange} name="photo" placeholder="Copy/Paste URL of Resident Photo" /> <button type="button" className="resBtn btn btn-primary" disabled={!(formObject.address && formObject.family)} onClick={handleFormSubmit}> Add Residents </button> <Link to="/Calendar"> <button type="button" className="resBtn btn btn-primary"> Calendar </button> </Link> </form> </Col> <Col size="md-6 sm-12"> <h2 className="resInfo">Justice Community Residents <HiUserGroup /></h2> <FamilyData families={families} /> <h2 className="resInfo">Meet The Residents <FaComments /></h2> {families.length ? ( <List> {families.map(family => ( <ListItem key={family._id}> <Link to={"/families/" + family._id}> <strong> {family.family} </strong> </Link> </ListItem> ))} </List> ) : ( <h2 className="resInfo">No Results to Display</h2> )} </Col> </Row>} </Container> ); } export default Families;
1.757813
2
src/components/Header/Navbar.js
alemkahrov/insure-landing-page
0
15998188
import React, { Component } from 'react' import { Link } from 'gatsby' import logo from '../../images/logo.svg' import { IoIosMenu } from 'react-icons/io' export default class Navbar extends Component { state = { isOpen: false, } handleClick = () => { this.setState({ isOpen: !this.state.isOpen }) console.log(this.isOpen); } render() { return ( <nav className="nav"> <div className="container"> <div className="nav-inner"> <div className="nav-header"> <Link to="/" className="site-logo"> <img src={logo} alt="" /> </Link> <button type="button" className="toggleBtn" onClick={this.handleClick}> <IoIosMenu className="icon" /> </button> </div> <ul className={this.state.isOpen ? 'nav-list-mobile show-nav' : 'nav-list-desktop'}> <li><Link to="/about">how we work</Link></li> <li><Link to="/blog">blog</Link></li> <li><Link to="/account">account</Link></li> <li><Link to="/plans"> <button className="button-dark">view plans</button> </Link></li> </ul> </div> </div> </nav > ) } }
1.382813
1
src/components/footer.js
zoranstankovic/my-blog
0
15998196
import React from "react"; import Social from "./social"; const Footer = () => { return ( <footer> <div className="container"> <Social /> <p>&copy; 2020 <NAME></p> </div> </footer> ); }; export default Footer;
0.875
1
app/src/util_server/versionControlerModpacks.js
Kyri123/KAdmin-Minecraft
1
15998204
/* * ******************************************************************************************* * @author: <NAME> (Kyri123) * @copyright Copyright (c) 2020-2021, <NAME> * @license MIT License (LICENSE or https://github.com/Kyri123/KAdmin-Minecraft/blob/master/LICENSE) * Github: https://github.com/Kyri123/KAdmin-Minecraft * ******************************************************************************************* */ "use strict" const srq = require("sync-request") const download = require("download") const unzip = require("unzipper") const shell = require("./../background/server/shell") module.exports = class versionControlerModpacks { /** * Inizallisiert * @param {string|boolean} overwriteBaseURL */ constructor(overwriteBaseURL = false) { this.baseUrl = "https://addons-ecs.forgesvc.net/api/v2" } /** * Gibt Informationen über ein Modpack aus * @param {int} modpackID ID vom Modpack * @return {boolean|string} */ getModpackInfos(modpackID) { let resp = false modpackID = parseInt(modpackID) if(!isNaN(modpackID)) { try { // lese Allgemein Infos resp = JSON.parse(srq('GET', `${this.baseUrl}/addon/${modpackID}`, { json: true }).getBody()) // lese Download links resp.dFiles = [] resp.dFiles.push(JSON.parse(srq('GET', `${this.baseUrl}/addon/${modpackID}/files`, { json: true }).getBody())) // wandel in String resp = JSON.stringify(resp) } catch (e) { if(debug) console.log('[DEBUG_FAILED]', e) } } return resp } /** * Hollt die DownloadURL über versionString * @param {int} modpackID ID vom Modpack * @param {int} packID ID vom Pack * @return {boolean|string} */ getDownloadUrl(modpackID, packID) { let resp = false modpackID = parseInt(modpackID) packID = parseInt(packID) if(!isNaN(modpackID) && !isNaN(packID)) { try { // lese Allgemein Infos resp = srq('GET', `${this.baseUrl}/addon/${modpackID}/file/${packID}/download-url`).getBody() } catch (e) { if(debug) console.log('[DEBUG_FAILED]', e) } } return resp } /** * Download Server * modpackID {string} ModpackID * packID {string} PackID * server {string} Servername * @return {boolean} */ InstallPack(modpackID, packID, server) { let serv = new serverClass(server) let url = this.getDownloadUrl(modpackID, packID).toString() if(url !== false && serv.serverExsists()) { let cfg = serv.getConfig(); (async () => { globalUtil.safeFileSaveSync([cfg.path, "installing"], "true") globalUtil.safeFileRmSync([cfg.path, "mods"]) globalUtil.safeFileRmSync([cfg.path, "config"]) globalUtil.safeFileRmSync([cfg.path, "journeymap"]) globalUtil.safeFileRmSync([cfg.path, "libraries"]) globalUtil.safeFileRmSync([cfg.path, "scripts"]) globalUtil.safeFileRmSync([cfg.path, "modpack"]) globalUtil.safeFileRmSync([cfg.path, "resources"]) globalUtil.safeFileRmSync([cfg.path, "oresources"]) globalUtil.safeFileRmSync([cfg.path, "fontfiles"]) fs.readdir(pathMod.join(cfg.path), (err, files) => files.forEach(file => { if ( file.includes(".jar") || file.includes(".sh") || file.includes(".cmd") || file.includes(".bat") || file.includes(".pdf") || file.includes(".txt") ) globalUtil.safeFileRmSync([cfg.path, file]) }) ) fs.writeFileSync(pathMod.join(cfg.path, "modpack.zip"), await download(url)) fs.createReadStream(pathMod.join(cfg.path, "modpack.zip")) .pipe(unzip.Extract({ path: pathMod.join(cfg.path)})) .on("close", () => { fs.readdir(pathMod.join(cfg.path), (err, files) => files.forEach(file => { if(file.toLowerCase().includes("forge") && !file.toLowerCase().includes("install")) serv.writeConfig("jar", file) if((file.toLowerCase().includes("install") || file.toLowerCase().includes("ftbserver")) && file.toLowerCase().includes(".sh")) shell.runSHELL(`chmod 777 -R ${pathMod.join(cfg.path)} && cd ${pathMod.join(cfg.path)} && ./${file}`) }) ) serv.writeConfig("currversion", "ModPack - " + modpackID) globalUtil.safeFileRmSync([cfg.path, "modpack.zip"]) globalUtil.safeFileRmSync([cfg.path, "installing"]) globalUtil.safeFileSaveSync([cfg.path, "eula.txt"], "eula=true") }) })() return true } return url !== false } }
1.382813
1
sdk_k64f/middleware/multicore/erpc/docs/eRPC_infrastructure/eRPC/classerpc_1_1_r_p_msg_linux_transport.js
Sir-Branch/k64f-starter-template
1
15998212
var classerpc_1_1_r_p_msg_linux_transport = [ [ "RPMsgLinuxTransport", "classerpc_1_1_r_p_msg_linux_transport.html#adbf0409a3a387c522f4f3e0d421be7a8", null ], [ "~RPMsgLinuxTransport", "classerpc_1_1_r_p_msg_linux_transport.html#a3a6345d5b1f3f63c622547b12b8f12b6", null ], [ "init", "classerpc_1_1_r_p_msg_linux_transport.html#ab9114a1b32d06872a065884598bb9f38", null ], [ "receive", "classerpc_1_1_r_p_msg_linux_transport.html#ac18d51ff2ba19c8373f5f9dd9f7ca8fe", null ], [ "send", "classerpc_1_1_r_p_msg_linux_transport.html#a5dc1aa6f8d38fce9382993393d163e3f", null ] ];
0.404297
0
server/collections/placements.js
gsantoshb/Exartu-CRM
10
15998220
PlacementView = new View('placements', { collection: Placements, cursors: function (placement) { // Job with Client this.publish({ cursor: function (placement) { if (placement.job) return JobPlacementView.find(placement.job); }, to: 'jobs', observedProperties: ['job'], onChange: function (changedProps, oldSelector) { return JobPlacementView.find(changedProps.job); } }); // Employee this.publish({ cursor: function (placement) { if (placement.employee) { return Contactables.find(placement.employee); } }, to: 'contactables', observedProperties: ['employee'], onChange: function (changedProps, oldSelector) { return Contactables.find(changedProps.employee); } }); } }); Meteor.paginatedPublish(PlacementView, function () { var user = Meteor.users.findOne({ _id: this.userId }); if (!user) return []; return Utils.filterCollectionByUserHier.call(this, PlacementView.find()); }, { pageSize: 25, publicationName: 'placements' }); Meteor.publish('placementDetails', function (id) { return Utils.filterCollectionByUserHier.call(this, PlacementView.find(id)); }); Meteor.publish('allPlacements', function () { var sub = this; Meteor.Collection._publishCursor(Utils.filterCollectionByUserHier.call(this, Placements.find({}, { fields: { status: 1, employee: 1, job: 1, candidateStatus: 1 } })), sub, 'allPlacements'); sub.ready(); }); Placements.allow({ insert: function () { return true; }, update: function () { return true; } }); // Indexes Placements._ensureIndex({dateCreated: 1}); Placements._ensureIndex({activeStatus: 1}); Placements._ensureIndex({userId: 1}); Placements._ensureIndex({hierId: 1}); Placements._ensureIndex({objNameArray: 1}); Placements._ensureIndex({candidateStatus: 1}); Placements._ensureIndex({displayName: 1});
1.398438
1
js/gerard.js
guunterr/Datalogger
0
15998228
$(document).ready(function(){ $("#onbutton").click(function(){ if ($("#onbutton").css("background-color") == "red"){ $("#onbutton").css("background-color", "#5cb85c"); } if ($("#onbutton").css("background-color") == "#5cb85c"){ $("#onbutton").css("background-color", "red"); } }); });
0.980469
1
src/Lucene/In.js
adinan-cenci/js-quick-discography
0
15998236
const Expression = require('./Expression.js'); const Equal = require('./Equal.js'); class In { constructor(name, values, predicate = 'OR') { this.name = name; this.values = values; this.predicate = predicate; } __toString() { var expr = new Expression(); for (var v of this.values) { expr.addExpression(new Equal(this.name, v), this.predicate); } return '('+expr.__toString()+')'; } } module.exports = In;
1.367188
1
src/graphql/types/Jurisdiction.js
Kevinoh47/openstates-api
0
15998244
'use strict'; const GraphQL = require('graphql'); const { GraphQLObjectType, GraphQLString, GraphQLID, GraphQLInt, } = GraphQL; const JurisdictionType = new GraphQL.GraphQLObjectType({ name: 'Jurisdiction', description: 'Jurisdiction Type, for all the jurisdiction data present in openstates.', fields: () => ({ id: { type: GraphQLString, // TODO confirm not a GraphQLID description: 'ID of the jurisdiction', }, stateName: { type: GraphQLString, description: 'Nmame of the state in which the jurisdiction resides.', }, name: { type: GraphQLString, description: 'name of the jurisdiction', }, chamber: { type: GraphQLString, description: 'a classification of the jurisdiction,', }, displayName: { type: GraphQLString, description: 'An alternative to the name field, used for display.', }, type: { type: GraphQLString, description: 'used to describe contact information', }, value: { type: GraphQLString, description: 'paired with the type field', }, note: { type: GraphQLString, description: 'Provides detail for type-value pairs', }, classification: { type: GraphQLString, description: 'Typically used with the Organization object', }, label: { type: GraphQLString, description: 'A descriptor', }, role: { type: GraphQLString, description: 'Describes the typical function of the object that contains it', }, }) }); module.exports = JurisdictionType;
1.234375
1
client/src/ResponseModels/AdminResponseModel.js
PapKate/MyMaps
0
15998252
/** * Represents an admin in the database */ class AdminResponseModel{ constructor(id, username, password) { this.id = id; this.username = username; this.password = password; this.dateCreated = dateCreated; this.dateModified = dateModified; } } module.exports = AdminResponseModel;
0.871094
1
resources/js/store.js
DhavIndian/lara6
1
15998260
import Vue from 'vue' import Vuex from 'vuex' import axios from 'axios' Vue.use(Vuex) export default new Vuex.Store({ state: { status: '', token: localStorage.getItem('token') || '', username: localStorage.getItem('username'), }, mutations: { auth_request(state) { state.status = 'loading' }, auth_success(state, data) { state.status = 'success' state.username = data.email state.token = data.token }, auth_error(state) { state.status = 'error' }, logout(state) { state.status = ''; state.token = ''; state.activeTab = ''; state.activeSubTab = ''; }, }, actions: { login({ commit }, form) { return new Promise((resolve, reject) => { commit('auth_request') axios({ url: './api/login', data: form, method: 'POST' }) .then(resp => { if (resp.data.status == 200) { axios.defaults.headers.common['Authorization'] = resp.data.data.token; localStorage.setItem('token', resp.data.data.token); localStorage.setItem('username', resp.data.data.email); commit('auth_success', resp.data.data) } else { // Vue.toasted.error("Username Password Not Match"); } resolve(resp) }) .catch(err => { commit('auth_error') localStorage.removeItem('token') reject(err) }) }) }, logout({ commit }) { return new Promise((resolve, reject) => { localStorage.clear(); delete axios.defaults.headers.common['Authorization']; commit('logout') resolve() }) }, }, getters: { isLoggedIn: state => !!state.token, authStatus: state => state.status, } })
1.351563
1
src/view.options.js
tiagobarreto/octotree
1
15998268
function OptionsView($dom, store) { var self = this , $view = $dom.find('.octotree_optsview').submit(save) , $toggler = $dom.find('.octotree_opts').click(toggle) this.$view = $view if (store.get(STORE.COLLAPSE) == null) store.set(STORE.COLLAPSE, false) if (store.get(STORE.REMEMBER) == null) store.set(STORE.REMEMBER, false) if (!store.get(STORE.HOTKEYS)) store.set(STORE.HOTKEYS, '⌘+b, ⌃+b') $(document).on(EVENT.TOGGLE, function(event, visible) { // hide options view when sidebar is hidden if (!visible) toggle(false) }) function toggle(visibility) { if (visibility !== undefined) { if ($view.hasClass('current') === visibility) return return toggle() } if ($toggler.hasClass('selected')) { $toggler.removeClass('selected') $(self).trigger(EVENT.VIEW_CLOSE) } else { $toggler.addClass('selected') $view.find('[data-store]').each(function() { var $elm = $(this) , storeKey = STORE[$elm.data('store')] , value = store.get(storeKey) if ($elm.is(':checkbox')) $elm.prop('checked', value) else $elm.val(value) }) $(self).trigger(EVENT.VIEW_READY) } } function save(event) { event.preventDefault() var changes = {} $view.find('[data-store]').each(function() { var $elm = $(this) , storeKey = STORE[$elm.data('store')] , oldValue = store.get(storeKey) , newValue = $elm.is(':checkbox') ? $elm.is(':checked') : $elm.val() if (oldValue !== newValue) { changes[storeKey] = [oldValue, newValue] store.set(storeKey, newValue) } }) toggle() if (Object.keys(changes).length) $(self).trigger(EVENT.OPTS_CHANGE, changes) } }
1.40625
1
src/routes/Company/index.js
fenghome/quantity
0
15998276
import React from 'react'; import { Card, Button, Icon, Input, Table, Divider, Popconfirm } from 'antd'; import { connect } from 'dva'; import PageHeader from '../../components/PageHeader'; import CompanyForm from '../../components/Company/CompanyForm'; const Search = Input.Search; const Company = ({ dispatch, company, loading }) => { const { companys } = company; const columns = [ { title: <div style={{ textAlign: "center" }}>单位名称</div>, dataIndex: 'companyName', key: 'companyName', render: (text) => ( <div style={{ textAlign: "center" }}> {text} </div> ), width: 200 }, { title: <div style={{ textAlign: "center" }}>行政</div>, children: [ { title: <div style={{ textAlign: "center" }}>编制</div>, dataIndex: 'quantityXZ', key: 'quantityXZ', render: (text) => ( <div style={{ textAlign: "center", fontSize: 12 }}> {text} </div> ) }, { title: <div style={{ textAlign: "center" }}>实有</div>, dataIndex: 'infactXZ', key: 'infactXZ', render: (text) => ( <div style={{ textAlign: "center", fontSize: 12 }}> {text} </div> ) }, { title: <div style={{ textAlign: "center" }}>拟用</div>, dataIndex: 'applyXZ', key: 'applyXZ', render: (text) => ( <div style={{ textAlign: "center", fontSize: 12 }}> {text} </div> ) } ] }, { title: <div style={{ textAlign: "center" }}>政法</div>, children: [ { title: <div style={{ textAlign: "center" }}>编制</div>, dataIndex: 'quantityZF', key: 'quantityZF', render: (text) => ( <div style={{ textAlign: "center", fontSize: 12 }}> {text} </div> ) }, { title: <div style={{ textAlign: "center" }}>实有</div>, dataIndex: 'infactZF', key: 'infactZF', render: (text) => ( <div style={{ textAlign: "center", fontSize: 12 }}> {text} </div> ) }, { title: <div style={{ textAlign: "center" }}>拟用</div>, dataIndex: 'applyZF', key: 'applyZF', render: (text) => ( <div style={{ textAlign: "center", fontSize: 12 }}> {text} </div> ) } ] }, { title: <div style={{ textAlign: "center" }}>工勤</div>, children: [ { title: <div style={{ textAlign: "center" }}>编制</div>, dataIndex: 'quantityGQ', key: 'quantityGQ', render: (text) => ( <div style={{ textAlign: "center", fontSize: 12 }}> {text} </div> ) }, { title: <div style={{ textAlign: "center" }}>实有</div>, dataIndex: 'infactGQ', key: 'infactGQ', render: (text) => ( <div style={{ textAlign: "center", fontSize: 12 }}> {text} </div> ) }, { title: <div style={{ textAlign: "center" }}>拟用</div>, dataIndex: 'applyGQ', key: 'applyGQ', render: (text) => ( <div style={{ textAlign: "center", fontSize: 12 }}> {text} </div> ) } ] }, { title: <div style={{ textAlign: "center" }}>全额拨款</div>, children: [ { title: <div style={{ textAlign: "center" }}>编制</div>, dataIndex: 'quantityQE', key: 'quantityQE', render: (text) => ( <div style={{ textAlign: "center", fontSize: 12 }}> {text} </div> ) }, { title: <div style={{ textAlign: "center" }}>实有</div>, dataIndex: 'infactQE', key: 'infactQE', render: (text) => ( <div style={{ textAlign: "center", fontSize: 12 }}> {text} </div> ) }, { title: <div style={{ textAlign: "center" }}>拟用</div>, dataIndex: 'applyQE', key: 'applyQE', render: (text) => ( <div style={{ textAlign: "center", fontSize: 12 }}> {text} </div> ) } ] }, { title: <div style={{ textAlign: "center" }}>差额拨款</div>, children: [ { title: <div style={{ textAlign: "center" }}>编制</div>, dataIndex: 'quantityCE', key: 'quantityCE', render: (text) => ( <div style={{ textAlign: "center", fontSize: 12 }}> {text} </div> ) }, { title: <div style={{ textAlign: "center" }}>实有</div>, dataIndex: 'infactCE', key: 'infactCE', render: (text) => ( <div style={{ textAlign: "center", fontSize: 12 }}> {text} </div> ) }, { title: <div style={{ textAlign: "center" }}>拟用</div>, dataIndex: 'applyCE', key: 'applyCE', render: (text) => ( <div style={{ textAlign: "center", fontSize: 12 }}> {text} </div> ) } ] }, { title: <div style={{ textAlign: "center" }}>自收自支</div>, children: [ { title: <div style={{ textAlign: "center" }}>编制</div>, dataIndex: 'quantityZS', key: 'quantityZS', render: (text) => ( <div style={{ textAlign: "center", fontSize: 12 }}> {text} </div> ) }, { title: <div style={{ textAlign: "center" }}>实有</div>, dataIndex: 'infactZS', key: 'infactZS', render: (text) => ( <div style={{ textAlign: "center", fontSize: 12 }}> {text} </div> ) }, { title: <div style={{ textAlign: "center" }}>拟用</div>, dataIndex: 'applyZS', key: 'applySZ', render: (text) => ( <div style={{ textAlign: "center", fontSize: 12 }}> {text} </div> ) } ] }, { title: <div style={{ textAlign: "center" }}>操作</div>, key: 'option', render: (text, record, index) => ( <div style={{ textAlign: "center" }}> <a onClick={() => { showUpdateForm(record) }}>编辑</a> <Divider type="vertical" /> <Popconfirm title="确定删除该单位吗?" onConfirm={() => { deleteCompany(record) }} okText="是" cancelText="否"> <a href="#">删除</a> </Popconfirm> </div> ), width: 120 } ]; const showAddForm = () => { dispatch({ type: 'company/showAddForm', }) } const showUpdateForm = (record) => { dispatch({ type: 'company/showUpdateForm', payload: record }); } const deleteCompany = (record) => { dispatch({ type: 'company/deleteCompany', payload: record }) } const searchCompany = (value) => { dispatch({ type: 'company/searchCompany', payload: value }) } return ( <div style={{ margin: "-24px -24px 0" }}> <PageHeader title="单位管理" /> <Card style={{ margin: "24px 24px 0" }}> <div> <Button type="primary" onClick={showAddForm}><Icon type="plus" />新增</Button> <Search placeholder="请输入单位名称" onSearch={value => searchCompany(value)} style={{ width: 240, float: "right" }} /> </div> <Table columns={columns} dataSource={companys} rowKey={record => record._id} loading={loading} bordered style={{ marginTop: "24px" }} /> </Card> <CompanyForm /> </div> ) } function mapStateToProps(state) { return { company: state.company, loading: state.loading.models.company } } export default connect(mapStateToProps)(Company);
1.601563
2
src/screens/HomeScreen/components/index.js
yen-igaw/reactnative_dfinery_ecommerce_demo
0
15998284
export * from "./Carousel"; export * from "./CategorySection"; export * from "./FloatButton"; export * from "./Header"; export * from "./ProductItem"; export * from "./Categories";
-0.22168
0
Mondogb/app.js
TakiL/Udemy
0
15998292
//jshint esversion:6 const mongoose = require("mongoose"); mongoose.connect("mongodb://localhost:27017/fruitsDB", { useNewUrlParser: true, useUnifiedTopology: true }); const fruitSchema = new mongoose.Schema({ name: { type: String, required: [true, "We need a name Morty!!"] }, rating: { type: Number, min: 1, max: 10 }, review: String }); const Fruit = mongoose.model("Fruit", fruitSchema); const fruit = new Fruit({ rating: 3, review: "Peaches are the best, mostly for Moonshine." }); const pineapple = new Fruit({ name: "Pineapple", score: 9, review: "Great fruit" }); const mango = new Fruit({ name: "Mango", rating: 8, review: "Best fruit on the world, yummí!" }); // mango.save(); // fruit.save(); const personSchema = new mongoose.Schema({ name: String, age: Number, favouriteFruit: fruitSchema }); const Person = mongoose.model("Person", personSchema); const person = new Person({ name: "John", age: 37, favouriteFruit: mango }); // person.save(); const kiwi = new Fruit({ name: "Kiwi", score: 10, review: "hairy ball" }); const orange = new Fruit({ name: "Orange", score: 10, review: "Annoying" }); const banana = new Fruit({ name: "Banana", score: 10, review: "Curvy" }); /* Fruit.insertMany([kiwi, orange, banana], function (err) { if (err) { console.log(err) } else { console.log("Successfully saved all the fruits to fruitsDB") } }) */ Fruit.find(function(err, fruits) { if (err) { console.log(err); } else { mongoose.connection.close(); fruits.forEach(fruit => { console.log(fruit.name); }); } }); Person.updateOne({ name: "Taki" }, { favouriteFruit: mango }, function(err) { if (err) { console.log(err); } else { console.log("Fruit Updated"); } }); Fruit.deleteOne({ name: "Peach" }, function(err) { if (err) { console.log(err); } else { console.log("Entry has been deleted"); } }); // Person.deleteMany({ name: "Taki" }, function(err) { // if (err) { // console.log(err); // } else { // console.log("Entries has been deleted"); // } // });
2.078125
2
strategies/livefyre/assets.js
immber/talk-importer
4
15998300
const h = require('highland'); module.exports = { /** * Turn the collection into a Talk asset * * @param {Object} fyre * @return {Object} */ translate: fyre => { var asset = { id: fyre.id, url: fyre.source, // This url needs to be added in the permitted domains section of your Talk admin title: fyre.title, scraped: null, // Set to null because next visit to page will trigger scrape }; return h([asset]); }, };
1.085938
1
step-definitions/board-eventListener.js
void00/fourInARow
0
15998308
require('./_include-all')(); module.exports = function () { class FakeTestGameEvent extends Game { addEventHandler() { this.addEventListenerCalled = true; } removeEventHandlers() { this.removeEventHandlersWasCalled = true; } } class TestGame extends Game { } let game; let board; let gameEvent = new FakeTestGameEvent(); //Scenario: Board should be clickable this.Given(/^that the board has an eventhandler$/, function () { expect(gameEvent.addEventListenerCalled, 'The addEventListener was not called at start of the Game' ).to.be.true; }); this.Then(/^A click should detect what column has been clicked on$/, function () { game = new TestGame(); board = game.board; expect(game.listener, 'Game variable listener did not exist' ).to.exist; }); this.Then(/^call makeMove with the same column$/, function () { board.matrix = [ [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 2, 0, 0, 0] ]; }); this.Then(/^the eventlistener should be saved as an property in this\.listener$/, function () { expect(game.listener).to.exist;// Well not enough, but something.... board.makeMove(2);//Without render and async sleep. No falling marker today. board.matrix2 = [ [0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 2, 0, 0, 0] ]; expect(board.matrix, 'Matrix is not as the solution should be after this draw' ).to.deep.equal(board.matrix2); }); this.Then(/^the addEventListener should find that element in DOM with the help function \$$/, function () { expect($('.yellow'), 'There is no div in board from yellow players move' ).to.exist; }); //Scenario: Board should have an removeEventListeners that removes listeners after game over this.Given(/^that play is on$/, function () { expect(gameEvent, 'Play is not on' ).to.exist; }); this.Then(/^board should have an removeEventListeners$/, function () { gameEvent.removeEventHandlers();// This is stupid. expect(gameEvent.removeEventHandlersWasCalled, 'Event in game was not called').to.be.true; }); }
1.773438
2
commonjs/plugins/bindRowsWithHeaders/bindStrategies/index.js
npu-sword/handsontable
0
15998316
"use strict"; exports.__esModule = true; var _loose = _interopRequireDefault(require("./loose")); exports.Loose = _loose.default; var _strict = _interopRequireDefault(require("./strict")); exports.Strict = _strict.default; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
0.769531
1
src/App.js
dingzhengru/react-first
0
15998324
import React from 'react'; import logo from './logo.svg'; import './App.scss'; import { useState, useLayoutEffect } from 'react'; //* Class Component (過時,但官方不會移除掉) import IncreaseCount from './components/increaseCount'; import TemperatureInput from './components/TemperatureInput'; import PropsChildTest from './components/PropsChildTest'; //* Hook(官方推薦) import HookTest from './components/HookTest'; //* Context import { ThemeContext, themes } from './contexts/ThemeContext'; import ContextTest from './components/ContextTest'; //* Router import Router from './components/Router'; import { useLocation, useHistory } from 'react-router-dom'; //* FetchData import FetchDataTest from './components/FetchDataTest'; //* Transition import TransitionTest from './components/TransitionTest'; //* i18n import { useTranslation } from 'react-i18next'; import { loadLanguageAsync } from './i18n-lazy'; // useMemo import UseMemoTest from './components/UseMemoTest'; //* 測試溫度轉換,接近 vue 的 computed function toCelsius(fahrenheit) { return ((fahrenheit - 32) * 5) / 9; } function toFahrenheit(celsius) { return (celsius * 9) / 5 + 32; } function App() { const [scale, setScale] = useState('c'); const [temperature, setTemperature] = useState(0); const celsius = scale === 'f' ? toCelsius(temperature) : temperature; const fahrenheit = scale === 'c' ? toFahrenheit(temperature) : temperature; const handleCelsiusChange = temperature => { setScale('c'); setTemperature(temperature); }; const handleFahrenheitChange = temperature => { setScale('f'); setTemperature(temperature); }; //* Context const [theme, setTheme] = useState(themes.light); //* Router //* 這裡使用 useLayoutEffect,會在 render 畫面之前執行 //* 設置只有改變 route 才觸發的 useEffect (第二個參數: 只針對甚麼改變才觸發) const location = useLocation(); const history = useHistory(); useLayoutEffect(() => { console.log('[Change-Route]', location); if (location.state === undefined) { return; } //* 等同於 vue-router 裡的 meta,需於 Link 標籤的 to 內設置 console.log('[location.state.auth]', location.state.auth); //* 設定條件轉址(auth) if (location.state.auth === true) { history.push({ pathname: '/' }); } }, [location]); //* i18n const { t, i18n } = useTranslation(); const handleLangChange = lang => { loadLanguageAsync(lang); }; return ( <ThemeContext.Provider value={theme}> <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" width="100" /> <Router /> </header> <h2>基本測試 (props, state, event handle, loop, form)</h2> <IncreaseCount count={10} /> <IncreaseCount count={100} isLoggedIn={true} list={[1, 2, 3]} /> <IncreaseCount isShow={false} /> <h2> 測試數值轉換(溫度),等同於 vue 的 computed <br /> 順便也使用了等同於 vue 的 emit 的事件傳遞 (onTemperatureChange) </h2> <TemperatureInput scale="c" temperature={celsius} onTemperatureChange={handleCelsiusChange} /> <TemperatureInput scale="f" temperature={fahrenheit} onTemperatureChange={handleFahrenheitChange} /> <h2>測試 props.child ,等同於 vue 的 v-slot</h2> <PropsChildTest header={<p>props.header content</p>} footer={<p>props.footer content</p>}> <p>props.child content</p> </PropsChildTest> <h2>Hook</h2> <HookTest count={100} /> <h2>Context (全局狀態)</h2> <div> theme: {JSON.stringify(theme)} <button onClick={() => setTheme(theme == themes.light ? themes.dark : themes.light)}>切換</button> <ContextTest /> </div> <h2>FetchData</h2> <FetchDataTest /> <h2>Transition</h2> <TransitionTest /> <h2>i18n</h2> <p> {i18n.language}: {t('hi')} <br /> {i18n.language}: {t('test', { num: 1 })} </p> <button onClick={() => handleLangChange(i18n.language == 'enUs' ? 'zhTw' : 'enUs')}>變更語系</button> <h2>測試 useMemo (計算後變數,對應 vue 的 computed)</h2> <UseMemoTest /> </div> </ThemeContext.Provider> ); } export default App;
1.757813
2
src/utils/download.js
ms-ecology/ms-download
0
15998332
const download = require('download-git-repo') const dl = (path, dest, retryMain) => new Promise((resolve, reject) => { download(path, dest, function (err) { if (err && retryMain && err.statusCode === 404) { // retry if (path.includes('#')) return reject(err) return resolve(dl(path + '#main', dest)) // break code } err ? reject(err) : resolve({ timestamp: Date.now() }) }) }) // default to retry with branch main module.exports = (path, dest) => dl(path, dest, 1)
1.09375
1
js/quick_sort.js
austinjeells/matchtools.github.io
1
15998340
function qsort(array) { function qsortPart(low, high) { var i = low; var j = high; var x = array[Math.floor((low+high)/2)]; console.log(x); do { while (array[i] < x) ++i; while (array[j] > x) --j; if (i<=j) { var temp = array[i]; array[i] = array[j]; array[j] = temp; i++; j--; } } while (i<=j); if (low < j) qsortPart(low, j); if (i < high) qsortPart(i, high); } qsortPart(0, array.length-1); } function nonRecursiveQsort(array) { var stack = []; var pushSort = function(low, high) { stack.push({low: low, high: high}); }; var iterate = function(low, high) { var i = low; var j = high; var x = array[Math.floor((low+high)/2)]; do { while (array[i] < x) ++i; while (array[j] > x) --j; if (i<=j) { var temp = array[i]; array[i] = array[j]; array[j] = temp; i++; j--; } } while (i<=j); if (low < j) pushSort(low, j); if (i < high) pushSort(i, high); }; pushSort(0, array.length-1); while (stack.length > 0) { var params = stack.pop(); iterate(params.low, params.high); } } function nonBlockingQsort(array, successCallback) { var stack = []; var pushSort = function(low, high) { stack.push({low: low, high: high}); }; var asyncCompare = function(x,y, callback) { result = x>y ? 1 : (x<y ? -1 : 0); //console.log(x,y, result); callback.call(this, result); }; var asyncSwap = function(i, j, callback) { var temp = array[i]; array[i] = array[j]; array[j] = temp; callback.call(this); }; var callCount = 0; var iterate = function(params) { if (!params.nextStep) { params.i = params.low; params.j = params.high; params.x = array[Math.floor((params.low+params.high)/2)]; params.nextStep = 'i'; } //console.log([array[0], array[1], array[2], array[3]], params.low, params.high, params.i, params.j, params.x, params.nextStep); if (params.nextStep == 'i') { callCount++; asyncCompare(array[params.i], params.x, function(result) { if (result == -1) { params.i++; } else { params.nextStep = 'j'; } iterate(params); callCount--; }); } else if (params.nextStep == 'j') { callCount++; asyncCompare(array[params.j], params.x, function(result) { if (result == 1) { params.j--; } else { params.nextStep = 'swap'; } iterate(params); callCount--; }); } else if (params.nextStep == 'swap') { if (params.i <= params.j) { callCount++; asyncSwap(params.i, params.j, function () { params.i++; params.j--; params.nextStep = 'closeLoop'; iterate(params); callCount--; }); } else { params.nextStep = 'closeLoop'; iterate(params); } } else if (params.nextStep == 'closeLoop') { if (params.i <= params.j) { params.nextStep = 'i'; iterate(params); } else { if (params.low < params.j) { iterate({low: params.low, high: params.j}); } if (params.i < params.high) { iterate({low: params.i, high: params.high}); } } } if (callCount === 0) { successCallback.apply(this); } }; iterate({low: 0, high: array.length-1}); } function nonBlockingQsort2(array, successCallback) { var asyncCompare = function(x,y, callback) { result = x>y ? 1 : (x<y ? -1 : 0); //console.log(x,y, result); callback(result); }; var asyncSwap = function(i, j, callback) { var temp = array[i]; array[i] = array[j]; array[j] = temp; callback(); }; var callCount = 0; var makeParams = function(low, high) { return {low: low, high: high, i: low, j: high, x: array[Math.floor((low+high)/2)]}; }; var openLoop = function(low, high) { callCount++; convergeI(makeParams(low, high)); }; var convergeI = function(params) { asyncCompare(array[params.i], params.x, function(result) { if (result == -1) { params.i++; convergeI(params); } else { convergeJ(params); } }); }; var convergeJ = function(params) { asyncCompare(array[params.j], params.x, function(result) { if (result == 1) { params.j--; convergeJ(params); } else { performSwap(params); } }); }; var performSwap = function(params) { if (params.i <= params.j) { asyncSwap(params.i, params.j, function () { params.i++; params.j--; closeLoop(params); }); } else { closeLoop(params); } }; var closeLoop = function(params) { if (params.i <= params.j) { convergeI(params); } else { if (params.low < params.j) { openLoop(params.low, params.j); } if (params.i < params.high) { openLoop(params.i, params.high); } callCount--; if (callCount === 0) { successCallback(); } } }; openLoop(0, array.length-1); } function nonBlockingQsort3(array, successCallback) { var asyncRead = function(i, callback) { setTimeout(function() { callback(array[i]); }, Math.random()*1000); }; var asyncWrite = function(i, v, callback) { array[i] = v; setTimeout(callback, Math.random()*1000); }; var asyncWriteDouble = function(i, j, ri, rj, callback) { var wi = false, wj = false; asyncWrite(i, rj, function() { wi = true; if (wj) callback(); }); asyncWrite(j, ri, function() { wj = true; if (wi) callback(); }); }; var asyncSwap = function(i, j, callback) { var ri = false, rj = false; asyncRead(i, function(v) { ri = v; if (rj !== false) asyncWriteDouble(i, j, ri, rj, callback); }); asyncRead(j, function(v) { rj = v; if (ri !== false) asyncWriteDouble(i, j, ri, rj, callback); }); }; var callCount = 0; var openLoop = function(low, high) { callCount++; asyncRead(Math.floor((low+high)/2), function (x) { convergeI({low: low, high: high, i: low, j: high, x: x}); }); }; var convergeI = function(params) { asyncRead(params.i, function(result) { if (result < params.x) { params.i++; convergeI(params); } else { convergeJ(params); } }); }; var convergeJ = function(params) { asyncRead(params.j, function(result) { if (result > params.x) { params.j--; convergeJ(params); } else { performSwap(params); } }); }; var performSwap = function(params) { if (params.i <= params.j) { asyncSwap(params.i, params.j, function () { params.i++; params.j--; closeLoop(params); }); } else { closeLoop(params); } }; var closeLoop = function(params) { if (params.i <= params.j) { convergeI(params); } else { if (params.low < params.j) { openLoop(params.low, params.j); } if (params.i < params.high) { openLoop(params.i, params.high); } callCount--; if (callCount === 0) { successCallback(); } } }; openLoop(0, array.length-1); }
2.390625
2
embeds.js
FM-96/discord-bot-mtg-cards-rules
0
15998348
module.exports = { makeCardEmbed, makeErrorEmbed, makeRuleEmbed, }; const colors = require('./constants/colors.js'); const embedLimits = require('./constants/embedLimits.js'); const client = require('./client.js'); const botVersion = process.env.npm_package_version ? process.env.npm_package_version : require('./package.json').version; function makeCardEmbed(data, extended) { const embed = { title: data.title, type: 'rich', url: 'https://mtg.wtf/card?q=!' + encodeURIComponent(data.title), footer: { text: client.user.username + ' | v' + botVersion, icon_url: client.user.avatarURL, }, image: { url: data.image, }, fields: [], }; if (data.colors.length > 1) { embed.color = colors.MULTICOLOR; } else { if (data.colors === 'W') { embed.color = colors.WHITE; } else if (data.colors === 'U') { embed.color = colors.BLUE; } else if (data.colors === 'B') { embed.color = colors.BLACK; } else if (data.colors === 'R') { embed.color = colors.RED; } else if (data.colors === 'G') { embed.color = colors.GREEN; } } embed.fields.push({ name: 'Mana Cost', value: data.cost, inline: true, }); embed.fields.push({ name: 'CMC', value: String(data.cmc), inline: true, }); embed.fields.push({ name: 'Color(s) / Color Identity', value: data.colors + ' / ' + data.ci, inline: true, }); let mainText = ''; if (data.oracle) { mainText += data.oracle; } // fix for http://mtg.wtf/card/ust/136/Urza-Academy-Headmaster (remove the reminder text) if (data.title === 'Urza, Academy Headmaster') { mainText = mainText.replace(/\n\n\(Randomly choose one of —(?:.|\n)+?\)(?=\n\n\[|$)/g, ''); } if (data.flavor) { if (mainText) { mainText += '\n\n'; } mainText += '*' + data.flavor + '*'; } if (data.pt) { if (mainText) { mainText += '\n\n'; } mainText += '**' + data.pt.replace(/\*/g, '\\*') + '**'; } if (data.loyalty) { if (mainText) { mainText += '\n\n'; } mainText += '**' + data.loyalty + '**'; } if (!mainText) { mainText = '*(No rules text.)*'; } embed.fields.push({ name: data.types, value: mainText, inline: false, }); if (extended) { embed.fields.push({ name: 'Legalities', value: data.legalities, inline: true, }); } if (data.otherparts) { let parts = ''; for (const part of data.otherparts) { parts += '[' + part + '](https://mtg.wtf/card?q=!' + encodeURIComponent(part) + ')\n'; } embed.fields.push({ name: data.otherparts.length === 1 ? 'Other Part' : 'Other Parts', value: parts, inline: true, }); } if (extended && data.rulings) { let totalCharacters = 0; totalCharacters += embed.title.length; totalCharacters += embed.footer.text.length; for (const field of embed.fields) { totalCharacters += field.name.length + String(field.value).length; } const rulings = data.rulings.map(e => '**' + e.date + '** ' + e.text + '\n'); let rulingsCharacters = 0; let fittingRulings = 0; let remainingRulingsText; for (let i = 0; i < rulings.length; ++i) { const ruling = rulings[i]; if (rulingsCharacters + ruling.length <= embedLimits.FIELD_VALUE && totalCharacters + rulingsCharacters + ruling.length <= embedLimits.TOTAL) { // ruling fits within embed limits fittingRulings++; rulingsCharacters += ruling.length; } else { if (i === 0) { remainingRulingsText = '[' + rulings.length + ' rulings](https://mtg.wtf/card?q=!' + encodeURIComponent(data.title) + ')'; } else { remainingRulingsText = '[' + (rulings.length - i) + ' more](https://mtg.wtf/card?q=!' + encodeURIComponent(data.title) + ')'; } if (rulingsCharacters + remainingRulingsText.length > embedLimits.FIELD_VALUE || totalCharacters + rulingsCharacters + remainingRulingsText.length > embedLimits.TOTAL) { if (i === 0) { // not even 1 ruling fits into embed limits AND the "more rulings" link doesn't fit either throw new Error('Rulings don\'t fit within embed limits'); } fittingRulings--; rulingsCharacters -= rulings[i - 1].length; remainingRulingsText = '[' + (rulings.length - (i - 1)) + ' more](https://mtg.wtf/card?q=!' + encodeURIComponent(data.title) + ')'; } break; } } let rulingsText = rulings.slice(0, fittingRulings).join(''); if (fittingRulings < rulings.length) { rulingsText += remainingRulingsText; } embed.fields.push({ name: 'Rulings', value: rulingsText, inline: false, }); } return embed; } function makeErrorEmbed(error, match, type) { const embed = { title: 'Error', type: 'rich', description: `*${type}: ${match}*\n${error.message}`, color: 0x00FFFF, footer: { text: client.user.username + ' | v' + botVersion, icon_url: client.user.avatarURL, }, }; return embed; } function makeRuleEmbed(data) { const embed = { type: 'rich', color: 0xAD42F4, footer: { text: client.user.username + ' | v' + botVersion, icon_url: client.user.avatarURL, }, image: { url: data.image, }, fields: [], }; embed.description = ''; if (data.type === 'glossary') { embed.title = 'Glossary'; const glossaryEntries = data.content.map(e => '**' + e.term + '**\n' + e.text + '\n\n'); let glossaryCharacters = 0; let fittingEntries = 0; let remainingEntriesText; for (let i = 0; i < glossaryEntries.length; ++i) { const entry = glossaryEntries[i]; if (glossaryCharacters + entry.length <= embedLimits.DESCRIPTION) { // glossary entry fits within embed limits fittingEntries++; glossaryCharacters += entry.length; } else { remainingEntriesText = '*(' + (glossaryEntries.length - i) + ' more matching entries, be more specific.)*'; if (glossaryCharacters + remainingEntriesText.length > embedLimits.DESCRIPTION) { fittingEntries--; glossaryCharacters -= glossaryEntries[i - 1].length; remainingEntriesText = '*(' + (glossaryEntries.length - (i - 1)) + ' more matching entries, be more specific.)*'; } break; } } let glossaryText = glossaryEntries.slice(0, fittingEntries).join(''); if (fittingEntries < glossaryEntries.length) { glossaryText += remainingEntriesText; } embed.description = glossaryText; } else if (data.type === 'rule') { // TODO check for embed limits embed.title = 'Comprehensive Rules'; for (const item of data.content) { embed.description += '**' + item.number + '** ' + item.text + '\n\n'; } if (data.nav) { const navField = { name: 'Navigation', value: '', }; navField.value += data.nav.siblings.list.map((e, i) => (data.nav.siblings.position === i ? `**${e.number}**` : e.number)).join(' - ') + '\n\n'; if (data.nav.subrules.count > 0) { navField.value += data.nav.subrules.list.map(e => e.number).join(' - ') + '\n\n'; } embed.fields.push(navField); } } return embed; }
1.359375
1
src/index.js
protolambda/airviz-client
0
15998356
import "regenerator-runtime/runtime"; import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter as Router } from "react-router-dom"; import { AppContainer as ReactHotLoader } from "react-hot-loader"; import {Provider} from "react-redux"; import App from "./components/App"; import storeCreator from "./reducers/store"; const store = storeCreator(); const render = Component => { ReactDOM.render( <ReactHotLoader> <Provider store={store}> <Router> <Component /> </Router> </Provider> </ReactHotLoader>, document.getElementById('root'), ); }; render(App); if (module.hot) { module.hot.accept('./components/App', () => { { const Next = require("./components/App").default; render(Next) } }) }
1.226563
1
src/app/settings/settingsController-spec.js
raincatcher-beta/raincatcher-demo-portal
0
15998364
var angular = require('angular'); var sinon = require('sinon'); require('sinon-as-promised'); require('angular-mocks'); describe("Settings Controller", function() { var DataResetService, $mdDialog, $state, userClient, SettingsController; before(function() { angular.module('app.settings', []); }); before(function() { require('./settingsController'); }); var mockConfirmDialog = { type: "mockConfirm" }; var mockLogoutDialog = { type: "mockLogout" }; var mockErrorDialog = { type: "error" }; var mockAlertDialog; beforeEach(function() { mockAlertDialog = sinon.stub(); mockAlertDialog.withArgs(sinon.match({ title: sinon.match('Error Resetting Data') })).returns(mockErrorDialog); mockAlertDialog.withArgs(sinon.match({ title: sinon.match('Data Reset Complete') })).returns(mockLogoutDialog); mockAlertDialog.returns(null); angular.mock.module('app.settings', function($provide) { //Providing the DataResetService mock service $provide.service('DataResetService', function() { return { resetData: sinon.stub().resolves() }; }); $provide.service('$mdDialog', function() { return { confirm: sinon.stub().returns(mockConfirmDialog), alert: mockAlertDialog, show: sinon.stub().resolves() }; }); $provide.service('$state', function() { return { go: sinon.spy() }; }); $provide.service('userClient', function() { return { clearSession: sinon.stub().resolves() }; }); }); }); describe("Resetting Data ", function() { beforeEach(inject(function(_DataResetService_, _$mdDialog_, _$state_, _userClient_, $controller, $rootScope) { DataResetService = _DataResetService_; $mdDialog = _$mdDialog_; $state = _$state_; userClient = _userClient_; SettingsController = $controller('SettingsController', { $scope: $rootScope.$new() }); })); it("It should reset data after confirmation", function(done) { var mockEvent = { preventDefault: sinon.spy() }; SettingsController.resetData(mockEvent).then(function() { sinon.assert.calledOnce(mockEvent.preventDefault); sinon.assert.calledOnce($mdDialog.confirm); sinon.assert.calledOnce(mockAlertDialog); sinon.assert.calledWith(mockAlertDialog, sinon.match({ title: 'Data Reset Complete' })); sinon.assert.calledTwice($mdDialog.show); sinon.assert.calledWith($mdDialog.show, mockConfirmDialog); sinon.assert.calledWith($mdDialog.show, mockLogoutDialog); sinon.assert.calledOnce(DataResetService.resetData); sinon.assert.calledOnce(userClient.clearSession); sinon.assert.calledOnce($state.go); done(); }); }); }); });
1.460938
1
src/pages/Homepage.js
Arjunan95/salama_Ui
0
15998372
import React, { Component } from "react"; import { Platform, StyleSheet, Text, TouchableHighlight, TextInput, TouchableOpacity, View, Button, Image } from "react-native"; // import {DrawerNavigator} from 'react-navigation' import { Form, Content, Alert, CardItem, Card, Body, Icon, Container, Picker, Textarea } from "native-base"; import { Header } from "react-native-elements"; import { TextField } from "react-native-material-textfield"; import { CheckBox } from "react-native-elements"; import { RadioGroup, RadioButton } from "react-native-flexi-radio-button"; export default class Homepage extends Component { static navigationOptions = { // header: null }; constructor() { super(); this.state = { text: "" }; } render() { value = "salama"; return ( <View style={{ flex: 1 }}> <Header leftComponent={{ icon: "menu", onPress: () => this.props.navigation.openDrawer(), color: "black" }} containerStyle={{ backgroundColor: "white" }} centerComponent={{ text: "Home", style: { color: "black", fontSize: 20 } }} rightComponent={{ icon: "home", color: "black" }} outerContainerStyles={{ backgroundColor: "white" }} /> <View style={{ paddingTop: 30 }}> <Text style={{ fontSize: 30, color: "#bc9e6d", textAlign: "center" }}> Welcome </Text> <Text style={{ fontSize: 15, color: "#bc9e6d", textAlign: "center" }}> Our Services </Text> </View> <View style={{ flex: 0.2 }} /> <View style={{ flexDirection: "row", borderColor: "red", justifyContent: "center" }} > <View style={styles.container}> <Card style={{ width: "40%", height: 110 }}> <TouchableOpacity onPress={() => this.props.navigation.navigate("Appeal")} > <Image source={require("../images/aman-llogo-red-background-copy-3.png")} style={{ width: "100%", marginRight: 60, height: 60, borderRadius: 10, marginTop: 25 }} /> </TouchableOpacity> </Card> <View> <Text style={{ color: "white" }}>abc</Text> </View> <Card style={{ width: "40%" }}> <TouchableOpacity onPress={() => this.props.navigation.navigate("salamaLoad")} > <Image source={require("../images/salama-logo-copy-2.png")} style={{ width: "50%", height: 110, borderRadius: 10, justifyContent: "center", alignItems: "center", marginLeft: 40 }} /> </TouchableOpacity> </Card> </View> </View> <Body /> <Text style={{ fontSize: 22, color: "#9b9b9b", textAlign: "center", marginBottom: 30 }} onPress={() => this.props.navigation.navigate("Appeal")} > Want to Appeal? </Text> <View style={styles.bottom}> <Button title="Appeal" color="#bc9e6d" width="500" onPress={() => this.props.navigation.navigate("Appeal")} /> </View> <View style={{ flex: 0.2 }} /> </View> ); } } const styles = StyleSheet.create({ container: { alignItems: "center", backgroundColor: "white", flex: 1, flexDirection: "row", justifyContent: "center" }, welcome: { fontSize: 24, // textAlign:'center' marginTop: 10 }, imgbutton: { alignItems: "center", backgroundColor: "#DDDDDD", padding: 10 }, drawericon: { marginLeft: -100 }, headerWelcome: { fontSize: 24, textAlign: "center", borderColor: "black", backgroundColor: "white", borderRadius: 899, borderTopWidth: 1 // borderColor: 'white', }, addBorder: { width: 200, height: 200, resizeMode: "stretch", // Set border width. borderWidth: 2, // Set border color. borderColor: "red" }, lineStyle: { borderBottomWidth: 1, borderColor: "black", margin: 5, width: 500 }, bottom: { // marginBottom:30, width: "60%", marginLeft: 80, height: 58.7, borderRadius: 5, fontSize: 20 } });
1.5625
2
client/middleware/show-modal.js
Razz21/Nuxt-Django-E-Commerce-Demo
1
15998380
export default function({ store, route, redirect, from }) { /* auth-module does not allow to custom callback method for auth guard, this middleware use custom auth paths to open auth dialog */ if (route.meta[0].modal) { if (!process.server) { /* show modal on client */ store.commit("user/setDialog", route.name); /* stay on same page */ return redirect(from); } } /* redirect to home page */ redirect("/"); }
0.941406
1
WebVella.Erp.Site/wwwroot/js/wv-datasource-manage/index.js
IamGanesh19/WebVella-ERP
0
15998388
// WvDatasourceManage: CommonJS Main
-0.15625
0
masar_optimal/custom/pos_invoice/pos_invoice.js
karamakcsc/masar_optimal
0
15998396
frappe.ui.form.on("POS Invoice","refresh", function(frm) { frm.toggle_display("pos_profile", false); frm.toggle_display("accounting_dimensions_section", false); frm.toggle_display("address_and_contact", false); frm.toggle_display("sec_warehouse", false); //frm.toggle_display("update_stock", false); frm.toggle_display("pricing_rule_details", false); frm.toggle_display("packing_list", false); frm.toggle_display("time_sheet_list", false); frm.toggle_display("pricing_rule_details", false); frm.toggle_display("loyalty_points_redemption", false); frm.toggle_display("sales_team_section_break", false); frm.toggle_display("subscription_section", false); frm.toggle_display("customer_po_details", false); frm.toggle_display("is_pos", false); frm.toggle_display("selling_price_list", false); frm.toggle_display("ignore_pricing_rule", false); }); // frappe.ui.form.on("POS Invoice Item","item_code", function(frm,cdt,cdn) { var d = locals[cdt][cdn]; if (d.item_code) { if(frm.doc.price_type=="Retail"){ frappe.call({ "method": "frappe.client.get", args: {doctype: "Item",name: d.item_code}, callback: function (data) {d.margin_rate_or_amount = flt(data.message.retail_price)} }); } if(frm.doc.price_type=="Wholesale"){ frappe.call({ "method": "frappe.client.get", args: {doctype: "Item",name: d.item_code}, callback: function (data) {d.margin_rate_or_amount = flt(data.message.wholesale_price)} }); } if(frm.doc.price_type=="Last Price"){ frappe.call({ "method": "masar_optimal.custom.pos_invoice.pos_invoice.get_last_price", args: {item_code: d.item_code}, callback: function (last_price) { d.margin_rate_or_amount = flt(last_price.message)} }); } } }); frappe.ui.form.on("POS Invoice","price_type", function(frm) { if (frm.doc.items.length >0) { $.each(frm.doc.items, function(i, d) { if (d.item_code) { if(frm.doc.price_type=="Retail"){ frappe.call({ "method": "frappe.client.get", args: {doctype: "Item",name: d.item_code}, callback: function (data) {d.rate = flt(data.message.retail_price)} }); } if(frm.doc.price_type=="Wholesale"){ frappe.call({ "method": "frappe.client.get", args: {doctype: "Item",name: d.item_code}, callback: function (data) {d.rate = flt(data.message.wholesale_price)} }); } if(frm.doc.price_type=="Last Price"){ frappe.call({ "method": "masar_optimal.custom.pos_invoice.pos_invoice.get_last_price", args: {item_code: d.item_code}, callback: function (last_price) { d.rate = flt(last_price.message)} }); } } }); } }); frappe.ui.form.on("POS Invoice Item","item_code", function(frm,cdt,cdn) { var d = locals[cdt][cdn]; if (d.item_code) { frappe.call({ "method": "frappe.client.get", args: {doctype: "Item",name: d.item_code}, callback: function (data) { d.retail_price = flt(data.message.retail_price) d.wholesale_price = flt(data.message.wholesale_price) } }); } }); frappe.ui.form.on("POS Invoice", { onload: function(frm) { frm.set_value("ignore_pricing_rule",1); } });
1.203125
1
components/Header/Header.js
sloiselle/react-pop-tracker
0
15998404
import React from 'react'; import classnames from 'classnames/bind'; import Login from './Login/Login.js'; import PopCounter from './PopCounter/PopCounter.js'; import styles from './Header.scss'; const cx = classnames.bind(styles); const Header = () => { return ( <header> <Login /> <PopCounter /> </header> ); }; export default Header;
0.863281
1
public/js/student/declarations.js
BartlomiejTrojnar/school
0
15998412
// ---------------------- wydarzenia na stronie wyświetlania klas ucznia ----------------------- // // ------------------------------ zarządzanie deklaracjami ucznia ------------------------------ // function refreshDeclarationsTable(student_id) { // odświeżenie tabeli z deklaracjiami dla ucznia $.ajax({ method: "POST", headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, url: "http://localhost/school/public/deklaracja/refreshTable", data: { student_id: student_id, version: "forStudent" }, success: function(result) { $('section#declarationsTable').replaceWith(result); showCreateRowClick(); addClick(); editClick(); destroyClick(); }, error: function() { var error = '<p class="error">Błąd odświeżania tabeli z deklaracjami dla ucznia.</p>'; $('table#declarations').before(error); }, }); } function showCreateRowClick() { $('#showCreateRow').click(function(){ $(this).hide(); $('table#declarations').animate({width: '1100px'}, 500); var student_id = $('input#student_id').val(); showCreateRow(student_id); return false; }); } function showCreateRow(student_id) { $.ajax({ method: "GET", headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, url: "http://localhost/school/public/deklaracja/create", data: { student_id: student_id, version: "forStudent" }, success: function(result) { $('table#declarations').append(result); }, error: function() { var error = '<tr><td colspan="8"><p class="error">Błąd tworzenia wiersza z formularzem dodawania deklaracji.</p></td></tr>'; $('table#declarations tr.create').after(error); }, }); } function addClick() { // ustawienie instrukcji po kliknięciu anulowania lub potwierdzenia dodawania deklaracji $('table#declarations').delegate('#cancelAdd', 'click', function() { $('#createRow').remove(); $('#showCreateRow').show(); return false; }); $('table#declarations').delegate('#add', 'click', function() { add(); $('#createRow').remove(); $('#showCreateRow').show(); return false; }); } function add() { // zapisanie deklaracji w bazie danych var student_id = $('#createRow input[name="student_id"]').val(); var session_id = $('#createRow select[name="session_id"]').val(); var application_number = $('#createRow input[name="application_number"]').val(); var student_code = $('#createRow input[name="student_code"]').val(); $.ajax({ method: "POST", headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, url: "http://localhost/school/public/deklaracja", data: { student_id: student_id, session_id: session_id, application_number: application_number, student_code: student_code }, success: function() { refreshDeclarationsTable(student_id); }, error: function() { var error = '<tr><td colspan="8"><p class="error">Błąd dodawania deklaracji dla ucznia</p></td></tr>'; $('table#declarations tr.create').after(error); }, }); } function editClick() { // kliknięcie przycisku modyfikowania egzaminu $('button.edit').click(function() { var id = $(this).attr('data-declarationId'); $.ajax({ type: "GET", headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, url: "http://localhost/school/public/deklaracja/"+id+"/edit", data: { id: id, version: "forStudent" }, success: function(result) { $('tr[data-declarationId='+id+']').before(result).hide(); updateClick(); }, error: function(result) { var error = '<tr><td colspan="8"><p class="error">Błąd tworzenia wiersza z formularzem modyfikowania deklaracji.</p></td></tr>'; $('tr[data-declarationId='+id+']').after(error).hide(); }, }); }); } function updateClick() { // ustawienie instrukcji po kliknięciu anulowania lub potwierdzenia modyfikowania deklaracji $('.cancelUpdate').click(function() { var id = $(this).attr('data-declarationId'); $('.editRow[data-declarationId='+id+']').remove(); $('tr[data-declarationId='+id+']').show(); return false; }); $('.update').click(function(){ var id = $(this).attr('data-declarationId'); update(id); return false; }); } function update(id) { // zapisanie deklaracji w bazie danych var student_id = $('tr[data-declarationId='+id+'] input[name="student_id"]').val(); var session_id = $('tr[data-declarationId='+id+'] select[name="session_id"]').val(); var application_number = $('tr[data-declarationId='+id+'] input[name="application_number"]').val(); var student_code = $('tr[data-declarationId='+id+'] input[name="student_code"]').val(); $.ajax({ method: "PUT", headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, url: "http://localhost/school/public/deklaracja/"+id, data: { id: id, student_id: student_id, session_id: session_id, application_number: application_number, student_code: student_code }, success: function() { refreshDeclarationsTable(student_id); }, error: function() { var error = '<tr><td colspan="8"><p class="error">Błąd modyfikowania deklaracji.</p></td></tr>'; $('tr[data-declarationId='+id+'].editRow').after(error).hide(); }, }); } function destroyClick() { // usunięcie deklaracji (z bazy danych) $('.destroy').click(function() { var id = $(this).attr('data-declarationId'); $.ajax({ type: "DELETE", headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, url: "http://localhost/school/public/deklaracja/" + id, success: function() { var student_id = $('input#student_id').val(); refreshDeclarationsTable(student_id); }, error: function() { var error = '<tr><td colspan="8"><p class="error">Błąd usuwania deklaracji.</p></td></tr>'; $('tr[data-declarationId='+id+']').after(error).hide(); } }); return false; }); } // ---------------------- wydarzenia wywoływane po załadowaniu dokumnetu ----------------------- // $(document).ready(function() { showCreateRowClick(); addClick(); editClick(); destroyClick(); });
1.078125
1
src/state_management/createStore.js
Aimee-MacDonald/blauw
0
15998420
import {createStore, combineReducers} from 'redux' import controlsReducer from './reducers/controls' import navigationReducer from './reducers/navigation' import modalReducer from './reducers/modal' import bookingsReducer from './reducers/bookings' import utilReducer from './reducers/util' import datesReducer from './reducers/dates' import roomsReducer from './reducers/rooms' import notesReducer from './reducers/notes' export const store = createStore(combineReducers({ controls: controlsReducer, navigation: navigationReducer, modal: modalReducer, bookings: bookingsReducer, util: utilReducer, dates: datesReducer, rooms: roomsReducer, notes: notesReducer })) export default () => store
0.878906
1
demo2/js/base.js
MonkeyAndDog/Webpack-npm-learning
0
15998428
var open = true; //ES6写法 export {open}; //node写法 // module.exports = { // open:open // };
0.427734
0
test/tth-manager.js
jasonpaulos/rdflib.js
417
15998436
var TTH_OFFLINE_STATUS = false function isOffline () { return TTH_OFFLINE_STATUS } function goOffline () { TTH_OFFLINE_STATUS = true } function goOnline () { TTH_OFFLINE_STATUS = false }
0.300781
0
east.js
curtbrink/death-stranding-zipline-network
0
15998444
var scale = { x: [-2500, 1800], y: [2500, -2500] } var ziplines = [ { x: 1171.98, y: 833.77, level: 1, mine: false }, { x: 942.21, y: 802.66, level: 2, mine: false }, { x: 708.30, y: 1021.23, level: 2, mine: true }, { x: 418.69, y: 1189.28, level: 1, mine: true }, { x: 339.60, y: 1120.93, level: 2, mine: false }, { x: 1289.39, y: 837.90, level: 1, mine: true }, { x: 985.21, y: 651.05, level: 1, mine: false }, { x: 254.63, y: 978.81, level: 1, mine: false }, { x: 106.47, y: 893.18, level: 1, mine: false }, { x: 113.49, y: 628.92, level: 1, mine: false }, { x: -107.50, y: 511.74, level: 1, mine: true }, { x: -328.29, y: 585.64, level: 1, mine: false }, { x: 81.80, y: 553.71, level: 2, mine: true }, { x: -118.04, y: 754.84, level: 1, mine: true }, { x: -439.98, y: 382.20, level: 1, mine: true }, { x: -505.19, y: 283.57, level: 1, mine: false }, { x: -813.37, y: 359.77, level: 2, mine: false }, { x: -1499.12, y: 616.30, level: 1, mine: true }, { x: -1303.03, y: 651.83, level: 1, mine: true }, { x: -1120.76, y: 494.00, level: 1, mine: true }, { x: -895.95, y: 370.46, level: 1, mine: true }, { x: -856.09, y: 144.84, level: 1, mine: false }, { x: -626.88, y: 132.90, level: 1, mine: true }, { x: -1016.00, y: 137.38, level: 1, mine: false }, { x: -1282.40, y: 81.71, level: 1, mine: false }, { x: -1502.46, y: -16.96, level: 1, mine: true }, { x: -1611.55, y: -47.97, level: 1, mine: false }, { x: -1737.13, y: -350.76, level: 2, mine: true }, { x: -997.63, y: -119.76, level: 2, mine: false }, { x: -907.74, y: -81.88, level: 1, mine: true }, ]; // ############################################################################# // You shouldn't need to change anything below this line // ############################################################################# // Prepper details var preppers = [ { x: 1431.92, y: 701.45, name: "Capital Knot City", short: "CKC" }, { x: 304.45, y: 1157.09, name: "Waystation West of Capital Knot City", short: "WSW" }, { x: 525.71, y: 329.02, name: "Incinerator West of Capital Knot City", short: "INC" }, { x: 102.92, y: 538.83, name: "<NAME>", short: "LUD" }, { x: -441.22, y: 264.47, name: "Distribution Center West of Capital Knot City", short: "DST" }, { x: -1492.67, y: 667.10, name: "Wind Farm", short: "WDF" }, { x: -982.11, y: -121.17, name: "Musician", short: "MUS" }, { x: -982.11, y: -121.17, name: "Musician", short: "MUS" }, { x: -1985.96, y: -476.38, name: "Port Knot City", short: "PKC" }, ];
0.644531
1
src/redux/actions/dataActions.js
piyushshri01/Social-media-app
0
15998452
import { SET_SCREAMS, LOADING_DATA, LIKE_SCREAM, UNLIKE_SCREAM, DELETE_SCREAM, SET_ERRORS, LOADING_UI, POST_SCREAM, CLEAR_ERRORS, SET_SCREAM, STOP_LOADING_UI, SUBMIT_COMMENT } from '../types'; import axios from 'axios'; // Get All Screams export const getScreams = () => (dispatch) => { dispatch({ type: LOADING_DATA }); axios.get('/screams') .then(res => { dispatch({ type: SET_SCREAMS, payload: res.data }) }) .catch(err => { dispatch({ type: SET_SCREAMS, payload: [] }) }) } // Like a Scream export const likeScream = (screamId) => (dispatch) => { axios.get(`/scream/${screamId}/like`) .then(res => { dispatch({ type: LIKE_SCREAM, payload: res.data }) }) .catch(err => { console.log(err) }) } // Unlike a Scream export const unlikeScream = (screamId) => (dispatch) => { axios.get(`/scream/${screamId}/unlike`) .then(res => { dispatch({ type: UNLIKE_SCREAM, payload: res.data }) }) .catch(err => { console.log(err) }) } // submit a comment export const submitComment = (screamId, commentData) => (dispatch) => { axios.post(`/scream/${screamId}/comment`, commentData) .then(res => { dispatch({ type: SUBMIT_COMMENT, payload: res.data }) dispatch(clearErrors()); }) .catch(err => { dispatch({ type: SET_ERRORS, payload: err.response.data }) }) } // delete a scream export const deleteScream = (screamId) => (dispatch) => { axios.delete(`/scream/${screamId}`) .then(() => { dispatch({ type: DELETE_SCREAM, payload: screamId}) }) .catch(err => console.log(err)); } // get a scream export const getScream = (screamId) => (dispatch) => { dispatch({ type: LOADING_UI }); axios.get(`/scream/${screamId}`) .then(res => { dispatch({ type: SET_SCREAM, payload: res.data, }); dispatch({ type: STOP_LOADING_UI }) }) .catch(err => console.log(err)); } // post a scream export const postScream = (newScream) => (dispatch) => { dispatch({ type: LOADING_UI }); axios.post(`/scream`, newScream) .then(res => { dispatch({ type: POST_SCREAM, payload: res.data }) dispatch(clearErrors()) }) .catch(err => { dispatch({ type: SET_ERRORS, payload: err.response.data }) }) } // get user data export const getUserData = (userHandle) => dispatch => { dispatch({ type: LOADING_DATA }); axios.get(`/user/${userHandle}`) .then(res => { dispatch({ type: SET_SCREAMS, payload: res.data.screams }); }) .catch(err => { dispatch({ type: SET_SCREAMS, payload: null }); }); }; export const clearErrors = () => dispatch => { dispatch({ type: CLEAR_ERRORS }) }
1.3125
1
src/components/Footers/MobileFooter.js
TheCypher/fiver-work-template
0
15998460
import React, { useState } from "react"; // reactstrap components import { Collapse, ListGroup, ListGroupItem, Col } from "reactstrap"; import ProductsLinks from "./Mobile/ProductsLinks"; import InformationLinks from "./Mobile/InformationLinks"; import SupportLinks from "./Mobile/SupportLinks"; import CompanyLinks from "./Mobile/CompanyLinks"; import ContactInfo from "./Regular/ContactInfo"; function MobileFooter() { // collapse states and functions const [collapses, setCollapses] = useState([0]); const changeCollapse = collapse => { if (collapses.includes(collapse)) { setCollapses(collapses.filter(prop => prop !== collapse)); } else { setCollapses([...collapses, collapse]); } }; return ( <> <ListGroup flush> <ListGroupItem className="footerMobileListGroupItem" onClick={e => { e.preventDefault(); changeCollapse(1); }} > <span className="footerTitle">Products</span> {" "} <i className="now-ui-icons arrows-1_minimal-down footerDropDownLinkIcon"></i> </ListGroupItem> <Col className="footerMobileListGroupItem"> <Collapse isOpen={collapses.includes(1)}> <ProductsLinks /> </Collapse> </Col> <ListGroupItem className="footerMobileListGroupItem" onClick={e => { e.preventDefault(); changeCollapse(2); }} > <span className="footerTitle">Information & Resources</span> <i className="now-ui-icons arrows-1_minimal-down footerDropDownLinkIcon"></i> </ListGroupItem> <Col className="footerMobileListGroupItem"> <Collapse isOpen={collapses.includes(2)}> <InformationLinks /> </Collapse> </Col> <ListGroupItem className="footerMobileListGroupItem" onClick={e => { e.preventDefault(); changeCollapse(3); }} > <span className="footerTitle">Support</span> <i className="now-ui-icons arrows-1_minimal-down footerDropDownLinkIcon"></i> </ListGroupItem> <Col className="footerMobileListGroupItem"> <Collapse isOpen={collapses.includes(3)}> <SupportLinks /> </Collapse> </Col> <ListGroupItem className="footerMobileListGroupItem" onClick={e => { e.preventDefault(); changeCollapse(4); }} > <span className="footerTitle">Company</span> <i className="now-ui-icons arrows-1_minimal-down footerDropDownLinkIcon"></i> </ListGroupItem> <Col className="footerMobileListGroupItem"> <Collapse isOpen={collapses.includes(4)}> <CompanyLinks /> </Collapse> </Col> <ListGroupItem className="footerMobileListGroupItem" onClick={e => { e.preventDefault(); changeCollapse(5); }} > <span className="footerTitle">Contact Info</span> <i className="now-ui-icons arrows-1_minimal-down footerDropDownLinkIcon"></i> </ListGroupItem> <Col className="footerMobileListGroupItem"> <Collapse isOpen={collapses.includes(5)} style={{ 'padding-bottom': '70px'}}> <ContactInfo /> </Collapse> </Col> </ListGroup> </> ); } export default MobileFooter;
1.265625
1
.prettierrc.js
lizelaser/descubre-front-end
0
15998468
module.exports = { trailingComma: "es5", arrowParens: "always", pugSortAttributes: "asc", pugSortAttributesBeginning: [ "^ref$", "^span$", "^v-if$", "^v-else-if$", "^v-else$", "^v-model$", "^v-for$", "^:key$", "^v-.*$", "^:.*$", "^@.*$", ], };
0.289063
0
client/node_modules/rsuite/src/Drawer/test/DrawerSpec.js
eaclumpkens/Hearth-v2
1
15998476
import React from 'react'; import { getDOMNode } from '@test/testUtils'; import Drawer from '../Drawer'; describe('Drawer', () => { it('Should render a drawer', () => { const instance = getDOMNode( <Drawer show> <p>message</p> </Drawer> ); assert.ok(instance.querySelectorAll('.rs-drawer.rs-drawer-right')); assert.ok(instance.querySelector('[role="dialog"]')); }); it('Should be full', () => { const instance = getDOMNode( <Drawer full show> <p>message</p> </Drawer> ); assert.ok(instance.querySelectorAll('.rs-drawer.rs-drawer-full')); }); it('Should have a `top` className for placement', () => { const instance = getDOMNode( <Drawer show placement="top"> <p>message</p> </Drawer> ); assert.ok(instance.querySelectorAll('.rs-drawer-top')); }); it('Should have a custom className', () => { const instance = getDOMNode(<Drawer className="custom" show />); assert.ok(instance.querySelector('.rs-drawer.custom')); }); it('Should accept id and aria-labelledby attribute', () => { const instance = getDOMNode( <Drawer show id="drawer" aria-labelledby="drawer-title"> <h4 id="drawer-title">My Drawer</h4> <p>message</p> </Drawer> ); const dialog = instance.querySelector('[role="dialog"]'); assert.equal(dialog.getAttribute('id'), 'drawer'); assert.equal(dialog.getAttribute('aria-labelledby'), 'drawer-title'); }); it('Should have a custom style', () => { const fontSize = '12px'; const instance = getDOMNode(<Drawer style={{ fontSize }} show />); assert.equal(instance.querySelector('.rs-drawer').style.fontSize, fontSize); }); it('Should have a custom className prefix', () => { const instance = getDOMNode(<Drawer classPrefix="custom-prefix" show />); assert.ok(instance.querySelector('.fade').className.match(/\bcustom-prefix\b/)); }); });
1.609375
2
discord/handlers/channelPinsUpdate.js
r3volved/gemini
1
15998484
//Emitted whenever the pins of a channel are updated. Due to the nature of the WebSocket event, not much information can be provided easily here - you need to manually check the pins yourself module.exports = async ( channel, time ) => { }
0.710938
1
PropertyStream.js
heya/events
0
15998492
/* UMD.define */ (typeof define=="function"&&define||function(d,f,m){m={module:module,require:require};module.exports=f.apply(null,d.map(function(n){return m[n]||require(n)}))}) (["./EventSource", "./EventSink", "dcl"], function(EventSource, EventSink, dcl){ "use strict"; var Value = EventSource.Value; return dcl(EventSink, { declaredClass: "events/PropertyStream", constructor: function(){ this.micro.callback = makeCallback(this); }, on: dcl.superCall(function(sup){ return function on(channelName, callback, errback, stopback){ var result = sup.apply(this, arguments); if((typeof channelName != "string" || channelName == "default") && this.lastValue){ result.micro.send(this.lastValue); } return result; }; }), getValue: function getValue(){ return this.lastValue && this.lastValue.x; }, isValueAvailable: function isValueAvailable(){ return !!this.lastValue; } }); function makeCallback(stream){ return function(val){ if(val instanceof Value){ stream.lastValue = val; } return val; }; } });
1.414063
1
src/scripts/index.js
mkisecok/async-Promise-task
0
15998500
// The following line makes sure your styles are included in the project. Don't remove this. import '../styles/main.scss'; // Import any additional modules you want to include below \/ // \/ All of your javascript should go here \/ const section = document.querySelector('.modal'); const close=document.querySelector('.close'); console.log(close); function spendsTimeInPage(time) { return new Promise((resolve) => { setTimeout(()=> { resolve(true); }, time) }) } spendsTimeInPage(60000).then((occur) => { if(occur) { section.style.display = 'block'; } } ); close.addEventListener('click',e=> { section.style.display = 'none'; })
1.039063
1
site/assets/js/project_new.js
TUM-LIS/librecores-web
39
15998508
import $ from 'jquery'; import 'bootstrap-select'; import '../scss/project_new.scss'; // propose a name from the displayName // The name does not follow all validation rules for simplicity, i.e. it's // possible for a proposed name to fail validation. $('#form_displayName').keyup(function () { var nodeName = $('#form_name'); var proposedName = $(this).val().replace(/[\s_]/g, '-').replace(/[^a-z0-9-]/ig, '').toLowerCase(); nodeName.val(proposedName); });
1.351563
1
src/configs/webpack/development/devServer.js
wintercounter/mhy
137
15998516
export default (d, o) => ({ static: '/', host: 'localhost', port: 3000, hot: true, client: { progress: true }, compress: false, historyApiFallback: { disableDotRule: true }, allowedHosts: 'all' })
0.410156
0
static/js/login.js
Mark-ThinkPad/BookManage
1
15998524
$(function () { // 初始化input的计数器 $('input#pwd').characterCounter(); // 前端判断输入是否为空, 为空时禁用按钮 $('input#uid, input#pwd').bind('input propertychange', function (event) { let uid = $('#uid').val(); let pwd = $('#pwd').val(); if (uid && pwd) { $('#login').attr('disabled', false); } else { $('#login').attr('disabled', true); } }); // 回车触发按钮点击事件 $('#uid, #pwd').keydown(function (event) { if (event.keyCode === 13) { if ($('#login').prop('disabled') === true) { M.toast({html: '请输入完整的用户名和密码'}); } else { $('#login').click(); } } }); // 点击登录按钮后向后端API发送数据 $('#login').click(function () { $.ajax({ url: '/api/user/login', type: 'POST', data: { uid: $('#uid').val(), pwd: $('#pwd').val(), }, dataType: 'json', success: function (data) { if (data.status === 1) { alert(data.message); // 将登录信息添加到cookies Cookies.set('uid', data.uid); Cookies.set('pwd', data.pwd); Cookies.set('username', data.username); // 返回上一页并刷新 window.location.href=document.referrer||host + ''; } else if (data.status === 0) { alert(data.message); } }, error: function (jpXHR) { alert('Status Code: ' + jpXHR.status); }, }); }); });
1.25
1
webpack.test.js
chuckmersereau/mpdx_practice
0
15998532
'use strict'; /** * Webpack config for tests */ const assign = require('lodash/fp/assign'); const path = require('path'); const webpack = require('webpack'); const HappyPack = require('happypack'); const config = { devtool: 'eval-source-map', mode: 'development', module: { rules: [{ test: /\.ts$/, loader: 'happypack/loader?id=ts', exclude: /node_modules/ }, { test: /\.(json|html)$/, use: 'null-loader' }] }, resolve: { modules: [path.join(__dirname), 'node_modules', 'src'], extensions: ['.ts', '.js'] }, plugins: [ new webpack.DefinePlugin({ 'NODE_ENV': JSON.stringify(process.env.NODE_ENV) }), new webpack.NormalModuleReplacementPlugin(/\.(gif|png|jpg|jpeg|scss|css)$/, 'node-noop'), new HappyPack({ id: 'ts', loaders: [{ path: 'ts-loader', query: { happyPackMode: true } }] }) ] }; module.exports = config;
1.28125
1
cookbook.web/src/resources/lang/localization.js
kmyumyun/cookbook
0
15998540
import LocalizationStrings from "react-localization"; let loc = new LocalizationStrings({ en: { //ui username: "Username", password: "Password", email: "Email", repassword: "<PASSWORD>", firstname: "First Name", lastname: "Last Name", signin: "Sign In", signup: "Sign Up", loginpage: "Login", registerpage: "Register", home: "Home", recipes: "Recipes", //validation required: "{0} is required!", rePassword: "Please make sure passwords match!", minLength: "{0} must be at least {1} characters long!", maxLength: "{0} must be at most {1} characters long!", min: "{0} must be bigger than {1}!", max: "{0} must be lower than {1}!", }, bg: { //ui username: "Потребител", password: "<PASSWORD>", email: "<PASSWORD>", repassword: "<PASSWORD>", firstname: "Име", lastname: "Фамилия", signin: "Влез", signup: "Запази", loginpage: "Вход", registerpage: "Регистрация", home: "Начало", recipes: "Рецепти", //validation required: "Полето {0} е задължително!", rePassword: "<PASSWORD>!", minLength: "Полето {0} трябва да е с минимална дължина от {1} символа!", maxLength: "Полето {0} трябва да е с максимална дължина от {1} символа!", min: "Полето {0} трябва да е със стойност по-голяма от {1}!", max: "Полето {0} трябва да е със стойност по-малка от {1}!", }, }); export default loc;
1.351563
1
src/addons/with-dsm.js
InVisionApp/dsm-storybook-cli
14
15998548
import addons, { makeDecorator } from '@storybook/addons'; import logger from './services/client-logger'; import userMessages from '../user-messages'; import { STORY_SELECTED_EVENT, HTML_SAMPLE_CODE_CHANGED_EVENT, DSM_INFO_OBJECT_KEY, STORY_CONTENT_LOADED } from './constants'; import { getStorySampleCode } from './html-sample-code'; function isDifferentStories(current, next) { return current.kind !== next.kind || current.story !== next.story; } let currentStory = null; const emitHtmlSampleCode = (story, context) => { // In HTML framework the sample code is the story itself on runtime, the story only // if it's a string and not a JS document const { containerClass } = context.parameters['in-dsm']; let sampleCode = ''; try { sampleCode = getStorySampleCode(story, containerClass); } catch (e) { sampleCode = userMessages.failedToExtractSampleCode(); logger.error(e); } addons.getChannel().emit(HTML_SAMPLE_CODE_CHANGED_EVENT, { eventName: HTML_SAMPLE_CODE_CHANGED_EVENT, sampleCode: sampleCode }); }; const emitStoryData = (story, context) => { if (!currentStory || isDifferentStories(currentStory, context)) { // story.type won't exist for Vue, we ignore it for now (__docgenInfo is only relevant for react) const docgenInfo = story.type && story.type.__docgenInfo; const storyData = { eventName: STORY_SELECTED_EVENT, docgenInfo: docgenInfo }; addons.getChannel().emit(STORY_SELECTED_EVENT, storyData); currentStory = context; } }; const emitStoryLayoutDimensions = () => { const CONTENT_REFRESH_TIME = 200; // ms const RETRY_MAX_ATTEMPTS = 20; let retryCount = 0; const messageContentHeightInterval = setInterval(() => { const container = document.getElementById('docs-root'); // If the container does not exist we want to continue retrying in the "else" block. // Additionally if the container DOES exist but is hidden, the offsetHeight will be 0. // In this case we also continue retrying. if (container && container.offsetHeight) { addons.getChannel().emit(STORY_CONTENT_LOADED, { eventName: STORY_CONTENT_LOADED, height: container.offsetHeight }); clearInterval(messageContentHeightInterval); } else { addons.getChannel().emit(STORY_CONTENT_LOADED, { eventName: STORY_CONTENT_LOADED // We do not send a height so that web will use a default height. dsm-storybook // doesn't really care what that height is. }); // We may not ever find the container, or the container may not have an `offsetHeight`. // This may occur if the user is viewing "Canvas" instead of "Docs." In this situation // we want to just stop the interval to prevent a "memory leak." retryCount += 1; if (retryCount > RETRY_MAX_ATTEMPTS) { clearInterval(messageContentHeightInterval); } } }, CONTENT_REFRESH_TIME); }; export default makeDecorator({ name: 'withDsm', parameterName: DSM_INFO_OBJECT_KEY, skipIfNoParametersOrOptions: true, wrapper: (getStory, context) => { const story = getStory(context); emitHtmlSampleCode(story, context); emitStoryData(story, context); emitStoryLayoutDimensions(); logger.info(userMessages.decoratorStarted()); return story; } });
1.59375
2
src/lib/model/slackCommand.js
code4kit/slack_cluster_manager
0
15998556
"use strict"; require("dotenv").config(); const { WebClient } = require("@slack/client"); const cluster = require("./cluster"); const packageInfo = require("../../../package.json"); /** *SLACK_AUTHORIZE_USERS for authorizer user to cretae, update and remove the cluster */ const SLACK_AUTHORIZE_USERS = process.env.SLACK_AUTHORIZE_USERS.split(" "); const SLACK_USER_ID = process.env.SLACK_USER_ID; const SLACK_WORKSPACE = process.env.SLACK_WORKSPACE; const EMOJI = process.env.SLACK_EMOJI; const SLACK_BOT_TOKEN = process.env.SLACK_BOT_TOKEN; const webClientUi = new WebClient(SLACK_BOT_TOKEN); const SLACK_LEGACY_TOKEN = process.env.LEGACY_TOKEN; const webClientLegacy = new WebClient(SLACK_LEGACY_TOKEN); const SLACK_TOKEN = process.env.SLACK_TOKEN; const webClient = new WebClient(SLACK_TOKEN); /** * This connect to NeDB * @param {String} */ const DB_PATH = process.env.DB_PATH; const SYSTEM_MODE = process.env.SYSTEM_MODE; const nedb = require("./_nedb")(DB_PATH, SYSTEM_MODE); const createCluster = async event => { if (!authorizeOnly(event)) { return "unauthorized user."; } const clusterName = event.text.split(/create/i)[1].trim(); const isVC = clusterName.includes("--vc"); const isBatch = clusterName.includes("--batch"); if (!isBatch || !isVC) { const msg = await cluster.createCluster(nedb, clusterName); replyToThread(event.channel, event.event_ts, msg); } else { replyToThread(event.channel, event.event_ts, ':warning: Please using one flag only.'); } }; const deleteCluster = async (event) => { if (!authorizeOnly(event)) { return ''; } const clusterName = event.text.split(/delete/i)[1].trim(); const msg = await cluster.deleteCluster(nedb, clusterName); replyToThread(event.channel, event.event_ts, msg); }; const updateMembers = async (event) => { if (!authorizeOnly(event)) { return ''; } const args = event.text.split(/update|<@|>|<!/); const clusterName = args[1].trim(); let slackMembers = await webClient.users.list({ channel: event.channel }); slackMembers = slackMembers.members.filter((member) => !member.is_bot && member.id !== 'USLACKBOT').map(member => member.id); if (args.includes('here')) { const msg = await cluster.update(nedb, clusterName, slackMembers); replyToThread(event.channel, event.event_ts, msg); } else { const memberIds = args.filter((member) => { return slackMembers.includes(member); }); const msg = await cluster.update(nedb, clusterName, memberIds); replyToThread(event.channel, event.event_ts, msg); } }; const mentionCmd = async (event) => { const clusterName = event.text.split(/mention/i)[1].trim().split(' ')[0].trim(); const msgForSending = event.text.split(clusterName)[1].trim().toString(); const channel = event.channel; const threadTs = event.event_ts; const targetCluster = await cluster.findMembers(nedb, clusterName); const message = `:information_source: ${msgForSending}\n :link: https://${SLACK_WORKSPACE}.slack.com/archives/${channel}/p${threadTs}`; if (targetCluster) { if (targetCluster.members.length !== 0) { targetCluster.members.forEach((member) => { directMessage(member, message); }); } else { replyToThread(channel, threadTs, ':warning: Cluster Member does not exist.'); } } else { replyToThread(channel, threadTs, ':warning:Cluster does not exist.'); } }; const inviteCmd = async (event) => { const clusterName = event.text.split(/invite/i)[1].trim(); const targetCluster = await cluster.findMembers(nedb, clusterName); const channel = event.channel; const threadTs = event.event_ts; if (targetCluster) { if (targetCluster.members.length !== 0) { const existingMember = await webClient.conversations.members({ channel }); let inviteMembers = targetCluster.members.filter((member) => { return !existingMember.members.includes(member) && member !== event.user; }); if (inviteMembers.length !== 0) { if (inviteMembers.includes(SLACK_USER_ID)) { await webClientLegacy.conversations.join({ channel }); inviteMembers = inviteMembers.filter((member) => { return member !== SLACK_USER_ID; }); } await webClientLegacy.conversations.invite({ users: inviteMembers.join(','), channel }); replyToThread(channel, threadTs, ':tada: Successfully invited.'); } else { replyToThread(channel, threadTs, ':point_down: Members have already joined this channel.'); } } else { replyToThread(channel, threadTs, ':warning: Cluster Member does not exist.'); } } else { replyToThread(channel, threadTs, ':warning:Cluster does not exist.'); } }; const kickCmd = async (event) => { const clusterName = event.text.split(/kick/i)[1].trim().split(' ')[0].trim(); const channel = event.channel; const threadTs = event.event_ts; const channelName = await webClient.channels.info({ channel }); const targetCluster = await cluster.findMembers(nedb, clusterName); if (targetCluster) { const existingMembers = await webClient.conversations.members({ channel }); const kickMemebers = targetCluster.members.filter(member => { return existingMembers.members.includes(member); }); if (kickMemebers.length !== 0) { kickMemebers.forEach(async user => { if (user !== event.user) { await webClient.conversations .kick({ channel, user }) .catch(err => { console.log("====", err); }); const message = `<@${event.user}> kicked you from ${channelName.channel.name}\n :link: https://${SLACK_WORKSPACE}.slack.com/archives/${channel}/p${threadTs} `; await directMessage(user, message); } else if (user === event.user) { if (user === SLACK_USER_ID) { await webClient.conversations.leave({ channel }); } else { await webClientLegacy.conversations.kick({ user, channel }).catch((err) => { console.log(err); }); } } }); } else { replyToThread( channel, threadTs, `:warning: ${clusterName}'s members do not exist here.` ); } } else { replyToThread(channel, threadTs, ":warning: cluster doesn't exist."); } }; const listCmd = async slackEvent => { const gotClusterName = slackEvent.text .split(/list/i)[1] .trim() .split(" ")[0] .trim(); if (slackEvent.channel[0] !== "D") { replyToThread( slackEvent.channel, slackEvent.ts, ":warning: You can only use this command with the bot." ); return; } let infoAllCluster = await cluster.find(nedb, gotClusterName); console.log(infoAllCluster); if (!infoAllCluster) { replyToThread(slackEvent.channel, slackEvent.ts, 'Nothing to return'); } else { let msg = ''; infoAllCluster = gotClusterName ? [infoAllCluster] : infoAllCluster; for (const data of infoAllCluster) { const members = data.members.map(member => `<@${member}>`); msg += `:file_folder: Cluster_name ${data.cluster_name}\n\n Members:sunglasses: ${members}\n\n`; } replyToThread(slackEvent.channel, slackEvent.ts, msg); } }; const authorizeOnly = (event) => { if (!SLACK_AUTHORIZE_USER.includes(event.user)) { replyToThread(event.channel, event.event_ts, ':warning: Only Authorize user can use this command.'); return false; } return true; }; /** * * @param {String} ch * @param {String} ts * @param {String} msg */ const replyToThread = (ch, ts, msg) => { webClientUi.chat.postMessage({ channel: ch, username: packageInfo.name, icon_emoji: EMOJI, thread_ts: ts, text: msg }); }; const directMessage = async (userId, msg) => { const dmChannel = await webClientUi.im.open({ user: userId }); await webClientUi.chat.postMessage({ text: msg, channel: dmChannel.channel.id }); }; module.exports = { createCluster, deleteCluster, updateMembers, mentionCmd, inviteCmd, kickCmd, listCmd };
1.523438
2
src/AdminUI.Template/www/adminUI/app/js/components/errorModal/errorModal.js
pedroparmeggianiB2B/admin-ui
58
15998564
class errorModal { constructor($parent) { this.$errorModal = undefined; this.data = undefined; this.$errorModal = $parent.find('.modal.error'); this.$content = this.$errorModal.find('#modalBody'); } show(text) { if (text !== null && text !== undefined) { this.$content.text(text); } this.$errorModal.modal('show'); } hide() { this.$errorModal.modal('hide'); } }
1.226563
1
webpack.config.js
yesterday24/portfolio
0
15998572
const { merge } = require('webpack-merge'); const common = require('./webpack.common.js'); const dev = require('./webpack.dev.js'); const prod = require('./webpack.prod.js'); module.exports = ({ env }) => { switch (env) { case 'dev': return merge(common, dev); case 'prod': return merge(common, prod); default: throw new Error('No matching configuration was found'); } };
0.960938
1
fork.js
seia-soto/maskd
0
15998580
const Koa = require('koa') const useCORS = require('@koa/cors') const useJSON = require('koa-json') const debug = require('debug') const routers = require('./routers') const config = require('./config') const pkg = require('./package') const app = new Koa() app.context.config = config app.context.debug = debug(pkg.name) app.context.pkg = pkg const initFn = async () => { app .use(useJSON({ pretty: false })) .use(useCORS(/* Use request origin header. */)) .use(routers.routes()) .use(routers.allowedMethods()) .listen(config.app.port + 1, () => app.context.debug(`starting 'maskd' API server (fork, slave) at ${Date.now()}.`)) } initFn()
1.210938
1
src/generators/Sequence.js
siepra/factory-girl
391
15998588
import Generator from './Generator'; export default class Sequence extends Generator { static sequences = {}; static reset(id = null) { if (!id) { Sequence.sequences = {}; } else { Sequence.sequences[id] = undefined; } } generate(id = null, callback = null) { if (typeof id === 'function') { callback = id; id = null; } id = id || this.id || (this.id = generateId()); Sequence.sequences[id] = Sequence.sequences[id] || 1; const next = Sequence.sequences[id]++; return callback ? callback(next) : next; } } function generateId() { let id; let i = 0; do { id = `_${i++}`; } while (id in Sequence.sequences); return id; }
1.179688
1
src/components/Resume/Skills/Skill.js
rg314/ryan_cv
0
15998596
import React from 'react'; import PropTypes from 'prop-types'; const Skill = ({ data }) => ( <article className="jobs-container"> <header> <h4>{data.level}</h4> </header> <ul className="points"> {data.points.map((point) => ( <li key={point}>{point}</li> ))} </ul> </article> ); Skill.propTypes = { data: PropTypes.shape({ level: PropTypes.string.isRequired, points: PropTypes.arrayOf(PropTypes.string).isRequired, }).isRequired, }; export default Skill;
1.398438
1
src/utils/helpers.js
wearetheledger/fabric-chaincode-utils
87
15998604
"use strict"; exports.__esModule = true; var winston_1 = require("winston"); var ObjectValidationError_1 = require("./errors/ObjectValidationError"); var ChaincodeError_1 = require("./errors/ChaincodeError"); /** * helper functions */ var Helpers = /** @class */ (function () { function Helpers() { } /** * Winston Logger with default level: debug * * @static * @param {string} name * @param {string} [level] * @returns {LoggerInstance} * @memberof Helpers */ Helpers.getLoggerInstance = function (name, level) { return new winston_1.Logger({ transports: [new winston_1.transports.Console({ level: level || 'debug', prettyPrint: true, handleExceptions: true, json: false, label: name, colorize: true })], exitOnError: false }); }; /** * Check first argument * try to cast object using yup * validate arguments against predefined types using yup * return validated object * * @static * @template T * @param object * @param {*} yupSchema * @returns {Promise<T>} * @memberof Helpers */ Helpers.checkArgs = function (object, yupSchema) { if (!object || !yupSchema) { return Promise.reject(new ChaincodeError_1.ChaincodeError("CheckArgs requires an object and schema", 400)); } return yupSchema.validate(object) .then(function (validatedObject) { return validatedObject; })["catch"](function (error) { throw new ObjectValidationError_1.ObjectValidationError(error); }); }; return Helpers; }()); exports.Helpers = Helpers;
1.65625
2
src/Components/Navbar/Menu/Menu.js
SebastianTyr/OnlineWebsite
0
15998612
import React from "react"; import logo from "../../../Assets/logo.png"; import DrawerToggleButton from "../SideDrawer/DrawerToggleButton"; import "./menu.scss"; const Menu = props => ( <div> <nav className="menu"> <div><DrawerToggleButton click={props.drawerToggleClickHandler}/></div> <div><a href=""><img src={logo} alt="" id="logo"/></a></div> <ol id="nav-list"> <li id="nav-list-element">O mnie</li> <li id="nav-list-element">Co oferuję</li> <li id="nav-list-element">Projekty</li> <li id="nav-list-element">Kontakt</li> <li id="nav-list-element">Źródła</li> </ol> </nav> </div> ); export default Menu //===========NAVBAR ROUTING TODO===========// /* import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom"; import Content from "../Content"; import Contact from "../Contact"; import Sources from "../Sources"; */ /* <Router> <ol id="nav-list"> <li><Link to={'/'} id="nav-list-element">O mnie</Link></li> <li><Link to={'./Content'} id="nav-list-element">Co oferuję</Link></li> <li><Link to={'#'} id="nav-list-element">Projekty</Link></li> <li><Link to={'./Contact'} id="nav-list-element">Kontakt</Link></li> <li><Link to={'./Sources'} id="nav-list-element">Źródła</Link></li> </ol> <Switch> <Route path="/content" component={Content} /> <Route path="/contact" component={Contact} /> <Route path="/sources" component={Sources} /> </Switch> </Router> */
1.195313
1
server/src/controllers/UserController.js
EdvinTr/QA-Website
0
15998620
const { User } = require("../models") const bcrypt = require("bcrypt"); const _ = require("lodash") const { Sequelize } = require("sequelize") const Op = Sequelize.Op module.exports = { /* ---------------------------- GET methods START ------------------------------------ */ async findUserById(req, res) { try { const userId = req.params.id; const user = await User.findOne({ where: { id: userId } }) if (!user) { return res.status(403).send({ error: `Could not find user with ID of ${userId}` }) } else { res.send(user); } } catch (err) { console.log(err); res.status(424).send({ error: `Could not find user with ID of ${userId}` }) } }, async findUserByUsername(req, res) { try { const user = await User.findOne({ attributes: { exclude: ["password"] }, where: { username: { [Op.like]: '%' + req.params.username + '%' } } }) if (!user) { return res.status(403).send({ error: `Could not find user with the username: ${username}` }) } else { res.send(user.toJSON()); } } catch (err) { console.log(err); res.status(424).send({ error: `Could not find user with username: ${username}` }) } }, async findAll(req, res) { try { const users = await User.findAll(); if (!users) { return res.status(403).send({ error: `Could not fetch users` }) } else { res.send(users); } } catch (err) { console.log(err); res.status(424).send({ error: `Could not find users` }) } }, /* ---------------------------- GET methods END ------------------------------------- */ /* ---------------------------- POST methods start ---------------------------------- */ async createContributor(req, res) { try { const user = await User.create(req.body); if (!user) { return res.status(400).send({ error: `Could not create user` }) } else { res.send(user); } } catch (err) { console.log(err); res.status(424).send({ error: `Could not find users` }) } }, /* ---------------------------- POST methods END ------------------------------------ */ /* ---------------------------- PUT methods START ----------------------------------- */ async updateUser(req, res) { try { const userId = req.params.id const salt = bcrypt.genSaltSync(); const user = await User.findOne({ where: { id: req.params.id } }) const password = req.body.password != undefined ? bcrypt.hashSync(req.body.password, salt) : user.password let bodyData = { username: req.body.username, password: password, email: req.body.email, firstname: req.body.firstname, lastname: req.body.lastname, privilegeLevel: req.body.privilegeLevel } if (bodyData.email == user.email) { console.log("---------TRUE"); _.omit(bodyData, "email") } console.log(bodyData); await User.update( bodyData , { where: { id: userId } } ) const updatedUser = await User.findOne({ where: { id: userId } }) res.send(updatedUser) } catch (err) { console.log(err); res.status(424).send({ error: `Something went wrong trying to update the user with ID ${req.params.id}` }) } }, /* ---------------------------- PUT methods END ----------------------------------- */ /* ---------------------------- PATCH methods START ------------------------------- */ async blockUser(req, res) { try { const userId = req.params.id await User.update( { privilegeLevel: 0 } , { where: { id: userId } } ) const user = await User.findOne({ where: { id: userId } }) res.send(user) } catch (err) { console.log(err); res.status(424).send({ error: `Could not block the user` }) } }, async unblockUser(req, res) { try { const userId = req.params.id await User.update( { privilegeLevel: 1 } , { where: { id: userId } } ) const user = await User.findOne({ where: { id: userId } }) res.send(user) } catch (err) { console.log(err); res.status(424).send({ error: `An error occured trying to unblock the user` }) } }, /* ---------------------------- PATCH methods END --------------------------------- */ /* ---------------------------- DELETE methods START ------------------------------ */ async deleteUserById(req, res) { try { const user = await User.destroy({ where: { id: req.params.id } }) if (user) { res.status(200).send() } else { res.status(400).send({ error: `Could not find user with an ID of ${req.params.id}` }) } } catch (err) { console.log(err); res.status(400).send({ error: `Could not delete user with an ID of ${req.params.id}` }) } }, /* ---------------------------- DELETE methods END ----------------------------- */ }
1.523438
2
preprocessor.js
DylanVann/advent-of-code-2017
0
15998628
const babel = require('@babel/core') module.exports = { process(src, path) { if (path.endsWith('.ts')) { return babel.transformSync(src, { filename: path }) } return src }, }
0.921875
1
server/config/errMessage.js
AnLuoRidge/knight-frank-bookstore
12
15998636
module.exports = { booknotfound: { booknotfound: 'No books found' }, bookoutofpages: { bookoutofpages: 'The page you request is larger than the maximum number of pages' }, unauthorized: { unauthorized: 'User is not authorized' }, bookexisted: { bookexisted: 'Book has existed in the database' }, categorynotfound: { categorynotfound: 'No categories found' }, success: { success: true }, // return when create, edit or delete an object notsuccess: { success: false }, // return when create, edit or delete an object reviewexist: { reviewexist: 'Review has existed' }, reviewnotfound: { reviewnotfound: 'No Reviews found' }, noresult: { noresult: 'No result is found' }, booklistnotfound: { booklistnotfound: 'No book lists found' }, booklistoutofpages: { booklistoutofpages: 'The page you request is larger than the maximum number of pages' }, alreadyadded: { alreadyadded: 'User already added this book' }, alreadyliked: { alreadyliked: 'User already liked this book list' }, notliked: { notliked: 'User have not yet liked this booklist' }, usernotfound: { usernotfound: 'User not found' }, emailnotfound: { usernotfound: 'The email address does not existed' }, categoryexist: { categoryexist: 'Category name has existed' }, nofileselected: { nofileselected: 'No File Selected' }, emailexist: { emailexist: 'Email already exists' }, activationfail: { activationfail: 'The token is invalid. Please Re-activate your email.' }, isactive: { isactive: 'Account has activated' }, notactive: { notactive: 'Account is not activated' }, pwdincorrect: { password: '<PASSWORD>' }, };
1.179688
1
dist/functions/Auth.js
FreddyGames69/EasyFirebase
1
15998644
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Authentication = void 0; const auth_1 = require("firebase/auth"); const googleProvider = new auth_1.GoogleAuthProvider(); const GithubProvider = new auth_1.GithubAuthProvider(); const FacebookProvider = new auth_1.FacebookAuthProvider(); const TwitterProvider = new auth_1.TwitterAuthProvider(); class Authentication { constructor(app) { this.auth = (0, auth_1.getAuth)(app); } async createAccount(email, password, name) { try { const newUser = await (0, auth_1.createUserWithEmailAndPassword)(this.auth, email, password); if (name) await (0, auth_1.updateProfile)(this.auth.currentUser, { displayName: name, }); return { error: false, message: "Account created succesfully", user: newUser.user, }; } catch (error) { return { error: true, message: error.message || error, user: null, }; } } async loginAccount(email, password) { try { const res = await (0, auth_1.signInWithEmailAndPassword)(this.auth, email, password); return { error: false, message: "Login successfully", user: res.user, }; } catch (error) { return { error: true, message: error.message, user: null, }; } } async loginGoogle() { try { const result = await (0, auth_1.signInWithPopup)(this.auth, googleProvider); return { error: false, message: "Authentication successfully", user: result.user, }; } catch (error) { return { error: true, message: error.message, }; } } async loginGithub() { try { const result = await (0, auth_1.signInWithPopup)(this.auth, GithubProvider); return { error: false, message: "Authentication successfully", user: result.user, }; } catch (error) { if (error.message === "Firebase: Error (auth/account-exists-with-different-credential).") return { error: true, message: "the email already use in other provider, (github, facebook, email, etc)", user: null, }; return { error: true, message: error.message, user: null, }; } } async loginFacebook() { try { const res = await (0, auth_1.signInWithPopup)(this.auth, FacebookProvider); return { error: false, message: "Authentication successfully", user: res.user, }; } catch (error) { if (error.message === "Firebase: Error (auth/account-exists-with-different-credential).") return { error: true, message: "the email already use in other provider, (github, facebook, email, etc)", user: null, }; return { error: true, message: error.message, user: null, }; } } async loginTwitter() { try { const res = await (0, auth_1.signInWithPopup)(this.auth, TwitterProvider); return { error: false, message: "Authentication successfully", user: res.user, }; } catch (error) { if (error.message === "Firebase: Error (auth/account-exists-with-different-credential).") return { error: true, message: "the email already use in other provider, (github, facebook, email, etc)", user: null, }; return { error: true, message: error.message, user: null, }; } } async updatePass(password, newPassword, callback) { try { const user = this.auth.currentUser; await this.reAuthUser(password, () => { (0, auth_1.updatePassword)(user, newPassword) .then(() => { if (callback) callback(user); }) .catch((error) => { console.log(error); }); }); } catch (error) { console.log(error); } } async UpdateProfile(data, callback) { try { await (0, auth_1.updateProfile)(this.auth.currentUser, data) .then(() => { if (callback) callback(); }) .catch((error) => { console.log(error); }); } catch (error) { console.log(error); } } reAuthUser(password, callBack) { var _a; const user = this.auth.currentUser; const credential = auth_1.EmailAuthProvider.credential(((_a = user.email) === null || _a === void 0 ? void 0 : _a.toLowerCase()) || "null", password); return (0, auth_1.reauthenticateWithCredential)(user, credential) .then(() => { callBack(user); }) .catch((error) => { console.log(error); }); } async sendVerification(callback) { try { await (0, auth_1.sendEmailVerification)(this.auth.currentUser).then(() => { if (callback) callback(); }); } catch (error) { console.log(error); } } async sendResetPassword(email, callback) { try { await (0, auth_1.sendPasswordResetEmail)(this.auth, email) .then(() => { callback(); }) .catch((error) => { console.log(error); }); } catch (error) { console.log(error); } } async deleteAccount(password, callback) { try { await this.reAuthUser(password, async () => { await (0, auth_1.deleteUser)(this.auth.currentUser) .then(() => { callback(); }) .catch((error) => { console.log(error); }); }); } catch (error) { console.log(error); } } async updateEmail(password, newEmail, callback) { try { await this.reAuthUser(password, async () => { await (0, auth_1.updateEmail)(this.auth.currentUser, newEmail) .then(() => { if (callback) callback(); }) .catch((error) => { console.log(error); }); }); } catch (error) { console.log(error); } } async closeSession(callback) { try { await (0, auth_1.signOut)(this.auth) .then(() => { if (callback) callback(); }) .catch((error) => { console.log(error); }); } catch (error) { console.log(error); } } } exports.Authentication = Authentication;
1.578125
2
src/redux/reducers/vehicle.reducer.js
emilyschwartau/LYSTR-boat-rental
0
15998652
import { combineReducers } from 'redux'; const newVehicleInitial = { title: '', type: '', make: '', model: '', year: '', length: '', capacity: '', horsepower: '', street: '', city: '', state: '', zip: '', description: '', cabins: '', heads: '', dailyRate: '', features: [], photos: [], availability: [], }; const vehicleFormInputs = (state = newVehicleInitial, action) => { switch (action.type) { case 'SET_VEHICLE_FORM_INPUTS': if (action.payload.features === null) { action.payload.features = []; } else if (action.payload.availability === null) { action.payload.availability = []; } return action.payload; case 'VEHICLE_FORM_ONCHANGE': return { ...state, [action.payload.property]: action.payload.value }; case 'ADD_FEATURE': state.features.push(action.payload); return { ...state }; case 'REMOVE_FEATURE': const filteredFeatures = state.features.filter( (feature) => feature !== action.payload ); return { ...state, features: filteredFeatures }; case 'CLEAR_VEHICLE_FORM': return newVehicleInitial; default: return state; } }; const photoGalleryInput = (state = { photos: [] }, action) => { switch (action.type) { case 'ADD_PHOTOS': return { photos: action.payload }; case 'CLEAR_PHOTO_GALLERY_INPUT': return { photos: [] }; default: return state; } }; const photos = (state = [], action) => { switch (action.type) { case 'SET_PHOTOS': return action.payload; default: return state; } }; const listedVehiclesByOwner = (state = [], action) => { switch (action.type) { case `SET_LISTED_VEHICLES_BY_OWNER`: return action.payload; default: return state; } }; const vehicleInfo = (state = [], action) => { switch (action.type) { case 'SET_VEHICLE_INFO': return action.payload; default: return state; } }; const allReservationsById = (state = [], action) => { switch (action.type) { case `SET_ALL_RESERVATIONS_BY_ID`: return action.payload; default: return state; } }; export default combineReducers({ vehicleFormInputs, photos, listedVehiclesByOwner, photoGalleryInput, vehicleInfo, allReservationsById, });
2.03125
2
archived/manage/app/components/notifications/-message.js
gargamol/base-cms
8
15998660
import { computed } from '@ember/object'; import { inject } from '@ember/service'; import NotificationMessage from 'ember-cli-notifications/components/notification-message'; export default NotificationMessage.extend({ notifications: inject(), closeIcon: computed(function() { return 'entypo icon-cross'; }), notificationIcon: computed('notification.type', function() { switch (this.get('notification.type')){ case 'info': return 'entypo icon-info-with-circle'; case 'success': return 'entypo icon-thumbs-up'; case 'warning': return 'entypo icon-warning'; case 'error': return 'entypo icon-thumbs-down'; } }), });
1.046875
1
calc-webapp/src/main/webapp/js/bus/EventBus.js
openforis/calc
3
15998668
/** * * The MIT License (MIT) Copyright (c) 2014 <NAME> , <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ var EventBusClass = {}; EventBusClass = function() { this.listeners = {}; this.groupListeners = {}; }; EventBusClass.prototype = { addEventListener:function(type, callback, scope) { var args = []; var numOfArgs = arguments.length; for(var i=0; i<numOfArgs; i++){ args.push(arguments[i]); } args = args.length > 3 ? args.splice(3, args.length-1) : []; if(typeof this.listeners[type] != "undefined") { this.listeners[type].push({scope:scope, callback:callback, args:args}); } else { this.listeners[type] = [{scope:scope, callback:callback, args:args}]; } var group = this.getGroup(type); if( StringUtils.isNotBlank(group) ){ if(typeof this.groupListeners[group] != "undefined") { this.groupListeners[group].push({scope:scope, callback:callback, args:args, type:type}); } else { this.groupListeners[group] = [{scope:scope, callback:callback, args:args, type:type}]; } } }, removeEventListener:function(type, callback, scope) { if(typeof this.listeners[type] != "undefined") { var numOfCallbacks = this.listeners[type].length; var newArray = []; for(var i=0; i<numOfCallbacks; i++) { var listener = this.listeners[type][i]; if(listener.scope == scope && listener.callback == callback) { } else { newArray.push(listener); } } this.listeners[type] = newArray; } }, removeEventListenersByGroup:function( group ) { if(typeof this.groupListeners[group] != "undefined") { var listeners = this.groupListeners[group]; for( var i in listeners ){ var listener = listeners[ i ]; this.removeEventListener(listener.type, listener.callback, listener.scope); } this.groupListeners[group] = undefined; } }, hasEventListener:function(type, callback, scope) { if(typeof this.listeners[type] != "undefined") { var numOfCallbacks = this.listeners[type].length; if(callback === undefined && scope === undefined){ return numOfCallbacks > 0; } for(var i=0; i<numOfCallbacks; i++) { var listener = this.listeners[type][i]; if((scope ? listener.scope == scope : true) && listener.callback == callback) { return true; } } } return false; }, dispatch:function(type, target) { var numOfListeners = 0; var event = { type:type, target:target }; var args = []; var numOfArgs = arguments.length; for(var i=0; i<numOfArgs; i++){ args.push(arguments[i]); }; args = args.length > 2 ? args.splice(2, args.length-1) : []; args = [event].concat(args); if(typeof this.listeners[type] != "undefined") { var numOfCallbacks = this.listeners[type].length; for(var i=0; i<numOfCallbacks; i++) { var listener = this.listeners[type][i]; if(listener && listener.callback) { var concatArgs = args.concat(listener.args); listener.callback.apply(listener.scope, concatArgs); // console.log( type + " ---- " + listener); numOfListeners += 1; } } } }, getEvents:function() { var str = ""; for(var type in this.listeners) { var numOfCallbacks = this.listeners[type].length; for(var i=0; i<numOfCallbacks; i++) { var listener = this.listeners[type][i]; str += listener.scope && listener.scope.className ? listener.scope.className : "anonymous"; str += " listen for '" + type + "'\n"; } } return str; } , getGroup:function(type){ var group = ''; var index = type.lastIndexOf( '.' ); if( index > 0 ){ group = type.substring( 0 , index ); } return group ; } }; var EventBus = new EventBusClass();
1.6875
2
js/native.js
nexpaq/tile-usbflash-testing
0
15998676
/** ================ Handlers == */ function nativeDataUpdateHandler(data) { if(data.state=='pluggedIn') { document.getElementById('usbStatus').textContent = "Connected"; } else if(data.state=='pluggedOut') { document.getElementById('usbStatus').textContent = "Disconnected"; } }
0.949219
1
js/media.js
IfeanyiNwachukwu/Movies_Battle_v2
0
15998684
class Media{ constructor(fetchData,mediaComparer){ this.FetchData = fetchData; this.MediaComparer = mediaComparer; this.LeftMedia; this.RightMedia; } FetchAllMedia = async(searchTerm) => { const allMedia = await this.FetchData.FetchAllResources(searchTerm); return allMedia; } RenderOption = (media) => { let imgSrc = media.Poster === 'N/A' ? '' : media.Poster; return ` <img src="${imgSrc}"/> ${media.Title} ` } DisplayMediaInDetail = async (mediaID,summaryElement,side) => { document.querySelector('.tutorial').classList.add('is-hidden'); const response = await this.FetchData.GetSingleResource(mediaID); // console.log(response); this.MediaDetailTemplate(response,summaryElement); this.Side = side; if(this.Side === 'left'){ this.LeftMedia = response; } else{ this.RightMedia = response; } if(this.LeftMedia && this.RightMedia){ this.MediaComparer.RunComparison(); } } MediaDetailTemplate = (mediaDetail,summaryElement) => { const { awards, boxOfficeValue, metaScore, imdbRating, imdbVotes } = this.ExtractMediaStatistics(mediaDetail); return summaryElement.innerHTML = ` <article class="media"> <figure class="media-left"> <p class="image"> <img src="${mediaDetail.Poster}" alt=""> </p> </figure> <div class="media-content"> <div class="content"> <h1>${mediaDetail.Title}</h1> <h4>${mediaDetail.Genre}</h4> <p>${mediaDetail.Plot}</p> </div> </div> </article> <article data-value="${awards}" class="notification is-primary"> <p class="title">${mediaDetail.Awards}</p> <p class="subtitle">Awards</p> </article> <article data-value="${boxOfficeValue}" class="notification is-primary"> <p class="title">${mediaDetail.BoxOffice}</p> <p class="subtitle">Box Office</p> </article> <article data-value="${metaScore}" class="notification is-primary"> <p class="title">${mediaDetail.Metascore}</p> <p class="subtitle">Metascore</p> </article> <article data-value="${imdbRating}" class="notification is-primary"> <p class="title">${mediaDetail.imdbRating}</p> <p class="subtitle">IMDB Rating</p> </article> <article data-value="${imdbVotes}" class="notification is-primary"> <p class="title">${mediaDetail.imdbVotes}</p> <p class="subtitle">IMDB Votes</p> </article> ` } ExtractMediaStatistics = (mediaDetail) => { const awards = mediaDetail.Awards.split(' ').reduce((prev, curr) => { const value = parseInt(curr); if (isNaN(curr)) { return prev; } else { return prev + value; } }, 0); const boxOfficeValue = parseInt(mediaDetail.BoxOffice.replace(/\$/g, '').replace(/,/g, '')); const metaScore = parseInt(mediaDetail.Metascore); const imdbRating = parseFloat(mediaDetail.imdbRating); const imdbVotes = parseInt(mediaDetail.imdbVotes.replace(/,/g, '')); return { awards, boxOfficeValue, metaScore, imdbRating, imdbVotes }; } }
1.945313
2
src/main.js
PrincessRavy/sharex-image-host
4
15998692
const express = require('express'); const app = express(); const tokens = process.env.IMAGE_AUTH.split(',').map(i => i.trim()); require('dotenv').config(); const { existsSync, mkdirSync, writeFileSync, unlinkSync } = require('fs'); const { join } = require('path'); const port = parseInt(process.env.PORT) || 4000; const uploadDir = join(process.cwd(), 'images'); if (!existsSync(uploadDir)) { console.log('Created /images'); mkdirSync(uploadDir); } function handleImage(image, res) { const extension = image.name.split('.')[1]; const id = new Date().getTime().toString(36) + '.' + extension; writeFileSync(`./images/${id}`, image.data); console.log(`+ ${id} (${image.name})`); return { id }; } app.use(require('express-fileupload')()); app.use('/', express.static('images')); app.get('/', (req, res) => { return res .status(404) .send({ code: 404, message: 'Cannot GET /. Use POST /upload for image uploading.'}) }); app.post('/upload', (req, res) => { if (!tokens.includes(req.headers.authorization)) { return res .status(401) .send({ code: 401, message: 'Invalid authentication credentials!' }); } const { image } = req.files; const { id: filename } = handleImage(image, res); if (filename) return res.send({ filename }); return res .status(500) .send({ code: 500, message: 'Internal server error.' }); }); app.delete('/:file', (req, res) => { if (!tokens.includes(req.headers.authorization)) { return res .status(401) .send({ code: 401, message: 'Invalid authentication credentials!' }); } const { file } = req.params; unlinkSync(join(process.cwd(), 'images', file)); console.log(`- ${file}`); return res .status(204) .send({ code: 204, message: `Successfully deleted ${file}.` }) }) app.listen(port, () => { console.log(`Serving on port ${port}!`); });
1.476563
1
src/components/Header/gameSlice.js
andreferreiradlw/Pokestats
10
15998700
import { createSlice } from '@reduxjs/toolkit' // initial state const initialState = { version: 'red', } // slice const gameSlice = createSlice({ name: 'game', initialState, reducers: { changeVersion(state, action) { state.version = action.payload }, }, }) // export actions export const { changeVersion } = gameSlice.actions // export reducer export default gameSlice.reducer
1.226563
1
app/NotFound.js
Qwy1987/music-player-by-react
0
15998708
/** * Created by qwy on 2017/9/16. */ import React, {Component} from 'react'; class NotFound extends Component { constructor() { super(...arguments); } render() { return ( <div style={{textAlign:"center"}}> 404 <br/> 网络中断或网页不存在 </div> ); } } export default NotFound;
1.070313
1
app/controllers/AbController.js
wingify/vwo-node-sdk-example
2
15998716
const util = require('../util'); const vwoHelper = require('../vwo-helper'); const { abCampaignKey, abCampaigngoalIdentifier, customVariables, variationTargetingVariables } = require('../config'); function AbController(req, res) { let campaignKey = abCampaignKey; let variationName; let userId; let isPartOfCampaign; userId = req.query.userId || util.getRandomUser(); if (vwoHelper.vwoClientInstance) { variationName = vwoHelper.vwoClientInstance.activate(campaignKey, userId, { customVariables, variationTargetingVariables }); if (variationName) { isPartOfCampaign = true; } else { isPartOfCampaign = false; } vwoHelper.vwoClientInstance.track(campaignKey, userId, abCampaigngoalIdentifier, { customVariables, variationTargetingVariables }); } res.render('ab', { title: `VWO | A/B | Node-sdk example | ${variationName}`, userId, isPartOfCampaign, variationName, campaignKey, abCampaigngoalIdentifier, customVariables: JSON.stringify(customVariables), variationTargetingVariables: JSON.stringify(variationTargetingVariables), currentSettingsFile: util.prettyPrint(vwoHelper.vwoClientInstance.SettingsFileManager.getSettingsFile(), null, 2) }); } module.exports = AbController;
1.40625
1
misc/deprecated-api-docs/modern/modern/src/ActionSheet.js
CelestialSystem/ext-angular
39
15998724
/** * @class Ext.ActionSheet * @extend Ext.Sheet * @alias widget.actionsheet * * ActionSheet is a `Sheet` that is docked at the bottom of the screen by default. * * @example packages=[extangular] * import { Component } from '@angular/core' * declare var Ext: any; * * @Component({ * selector: 'app-root-1', * styles: [` * `], * template: ` * <container #item> * <actionsheet #item [displayed]="true"> * <button #item ui="decline" text="Delete Draft"></button> * <button #item text="Save Draft"></button> * <button #item text="Cancel"></button> * </actionsheet> * </container> * ` * }) * export class AppComponent { * * } * */ /** * @cfg [left=0] * @inheritdoc */ /** * @cfg [right=0] * @inheritdoc */ /** * @cfg [bottom=0] * @inheritdoc */ /** * @cfg [height='auto'] * @inheritdoc */ /** * @cfg [defaultType=button] * @inheritdoc */
1.210938
1
public/js/market.js
abrito393/restaurant-alegra-rest
0
15998732
$(document).ready(function(){ var tokenCsrf = $( "input[name='_token']" ).val(); var ProcessBuy = window.setInterval(function(){ $.ajax({ url: "{{route('order.buy.market')}}", type: 'GET', headers: {'X-CSRF-TOKEN': tokenCsrf}, datatype: 'json', data:{}, success:function( respuesta ){ for (let index = 0; index < respuesta.length; index++) { const element = respuesta[index]; $( ".stock"+element.id).text('Cantidad: '+element.stock); } } }); }, 20000); ProcessBuy; });
1.101563
1
src/index.js
ksenkso/vuex-hydra
5
15998740
import { Plugin } from './plugin'; export default Plugin;
0.135742
0