hexsha string | size int64 | ext string | lang string | max_stars_repo_path string | max_stars_repo_name string | max_stars_repo_head_hexsha string | max_stars_repo_licenses list | max_stars_count int64 | max_stars_repo_stars_event_min_datetime string | max_stars_repo_stars_event_max_datetime string | max_issues_repo_path string | max_issues_repo_name string | max_issues_repo_head_hexsha string | max_issues_repo_licenses list | max_issues_count int64 | max_issues_repo_issues_event_min_datetime string | max_issues_repo_issues_event_max_datetime string | max_forks_repo_path string | max_forks_repo_name string | max_forks_repo_head_hexsha string | max_forks_repo_licenses list | max_forks_count int64 | max_forks_repo_forks_event_min_datetime string | max_forks_repo_forks_event_max_datetime string | content string | avg_line_length float64 | max_line_length int64 | alphanum_fraction float64 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
433424027855bbed38efba903dd0aa6f56d66583 | 6,654 | js | JavaScript | lib/extend/tag.js | wlphp/hexo-1 | 5977928c240beb714a1e90c1286ecc8290daa7cf | [
"MIT"
] | 35,651 | 2015-01-01T08:06:14.000Z | 2022-03-31T22:05:55.000Z | lib/extend/tag.js | wlphp/hexo-1 | 5977928c240beb714a1e90c1286ecc8290daa7cf | [
"MIT"
] | 4,087 | 2015-01-01T01:21:27.000Z | 2022-03-31T17:28:31.000Z | lib/extend/tag.js | wlphp/hexo-1 | 5977928c240beb714a1e90c1286ecc8290daa7cf | [
"MIT"
] | 6,371 | 2015-01-01T05:07:53.000Z | 2022-03-31T13:09:40.000Z | 'use strict';
const { stripIndent } = require('hexo-util');
const { cyan, magenta, red, bold } = require('picocolors');
const { Environment } = require('nunjucks');
const Promise = require('bluebird');
const rSwigRawFullBlock = /{% *raw *%}/;
const rCodeTag = /<code[^<>]*>[\s\S]+?<\/code>/g;
const escapeSwigTag = str => str.replace(/{/g, '{').replace(/}/g, '}');
class NunjucksTag {
constructor(name, fn) {
this.tags = [name];
this.fn = fn;
}
parse(parser, nodes, lexer) {
const node = this._parseArgs(parser, nodes, lexer);
return new nodes.CallExtension(this, 'run', node, []);
}
_parseArgs(parser, nodes, lexer) {
const tag = parser.nextToken();
const node = new nodes.NodeList(tag.lineno, tag.colno);
const argarray = new nodes.Array(tag.lineno, tag.colno);
let token;
let argitem = '';
while ((token = parser.nextToken(true))) {
if (token.type === lexer.TOKEN_WHITESPACE || token.type === lexer.TOKEN_BLOCK_END) {
if (argitem !== '') {
const argnode = new nodes.Literal(tag.lineno, tag.colno, argitem.trim());
argarray.addChild(argnode);
argitem = '';
}
if (token.type === lexer.TOKEN_BLOCK_END) {
break;
}
} else {
argitem += token.value;
}
}
node.addChild(argarray);
return node;
}
run(context, args) {
return this._run(context, args, '');
}
_run(context, args, body) {
return Reflect.apply(this.fn, context.ctx, [args, body]);
}
}
const trimBody = body => {
return stripIndent(body()).replace(/^\n?|\n?$/g, '');
};
class NunjucksBlock extends NunjucksTag {
parse(parser, nodes, lexer) {
const node = this._parseArgs(parser, nodes, lexer);
const body = this._parseBody(parser, nodes, lexer);
return new nodes.CallExtension(this, 'run', node, [body]);
}
_parseBody(parser, nodes, lexer) {
const body = parser.parseUntilBlocks(`end${this.tags[0]}`);
parser.advanceAfterBlockEnd();
return body;
}
run(context, args, body) {
return this._run(context, args, trimBody(body));
}
}
class NunjucksAsyncTag extends NunjucksTag {
parse(parser, nodes, lexer) {
const node = this._parseArgs(parser, nodes, lexer);
return new nodes.CallExtensionAsync(this, 'run', node, []);
}
run(context, args, callback) {
return this._run(context, args, '').then(result => {
callback(null, result);
}, callback);
}
}
class NunjucksAsyncBlock extends NunjucksBlock {
parse(parser, nodes, lexer) {
const node = this._parseArgs(parser, nodes, lexer);
const body = this._parseBody(parser, nodes, lexer);
return new nodes.CallExtensionAsync(this, 'run', node, [body]);
}
run(context, args, body, callback) {
// enable async tag nesting
body((err, result) => {
// wrapper for trimBody expecting
// body to be a function
body = () => result || '';
this._run(context, args, trimBody(body)).then(result => {
callback(err, result);
});
});
}
}
const getContextLineNums = (min, max, center, amplitude) => {
const result = [];
let lbound = Math.max(min, center - amplitude);
const hbound = Math.min(max, center + amplitude);
while (lbound <= hbound) result.push(lbound++);
return result;
};
const LINES_OF_CONTEXT = 5;
const getContext = (lines, errLine, location, type) => {
const message = [
location + ' ' + red(type),
cyan(' ===== Context Dump ====='),
cyan(' === (line number probably different from source) ===')
];
message.push(
// get LINES_OF_CONTEXT lines surrounding `errLine`
...getContextLineNums(1, lines.length, errLine, LINES_OF_CONTEXT)
.map(lnNum => {
const line = ' ' + lnNum + ' | ' + lines[lnNum - 1];
if (lnNum === errLine) {
return cyan(bold(line));
}
return cyan(line);
})
);
message.push(cyan(
' ===== Context Dump Ends ====='));
return message;
};
/**
* Provide context for Nunjucks error
* @param {Error} err Nunjucks error
* @param {string} str string input for Nunjucks
* @return {Error} New error object with embedded context
*/
const formatNunjucksError = (err, input, source = '') => {
const match = err.message.match(/Line (\d+), Column \d+/);
if (!match) return err;
const errLine = parseInt(match[1], 10);
if (isNaN(errLine)) return err;
// trim useless info from Nunjucks Error
const splited = err.message.replace('(unknown path)', source ? magenta(source) : '').split('\n');
const e = new Error();
e.name = 'Nunjucks Error';
e.line = errLine;
e.location = splited[0];
e.type = splited[1].trim();
e.message = getContext(input.split(/\r?\n/), errLine, e.location, e.type).join('\n');
return e;
};
class Tag {
constructor() {
this.env = new Environment(null, {
autoescape: false
});
}
register(name, fn, options) {
if (!name) throw new TypeError('name is required');
if (typeof fn !== 'function') throw new TypeError('fn must be a function');
if (options == null || typeof options === 'boolean') {
options = { ends: options };
}
let tag;
if (options.async) {
if (fn.length > 2) {
fn = Promise.promisify(fn);
} else {
fn = Promise.method(fn);
}
if (options.ends) {
tag = new NunjucksAsyncBlock(name, fn);
} else {
tag = new NunjucksAsyncTag(name, fn);
}
} else if (options.ends) {
tag = new NunjucksBlock(name, fn);
} else {
tag = new NunjucksTag(name, fn);
}
this.env.addExtension(name, tag);
}
unregister(name) {
if (!name) throw new TypeError('name is required');
const { env } = this;
if (env.hasExtension(name)) env.removeExtension(name);
}
render(str, options = {}, callback) {
if (!callback && typeof options === 'function') {
callback = options;
options = {};
}
// Get path of post from source
const { source = '' } = options;
return Promise.fromCallback(cb => {
this.env.renderString(
str.replace(rCodeTag, s => {
// https://hexo.io/docs/tag-plugins#Raw
// https://mozilla.github.io/nunjucks/templating.html#raw
// Only escape code block when there is no raw tag included
return s.match(rSwigRawFullBlock) ? s : escapeSwigTag(s);
}),
options,
cb
);
}).catch(err => Promise.reject(formatNunjucksError(err, str, source)))
.asCallback(callback);
}
}
module.exports = Tag;
| 26.404762 | 99 | 0.592876 |
43348b1a39c7f9c43111b7ee7eb1620814b26a02 | 2,203 | js | JavaScript | staticHome/static/staticHome/javascript/validinput.js | SatwikRudra/Caramelit_DJango | b564f285d2ae1e967f08a7aad24b04cb01e33fe4 | [
"MIT"
] | 1 | 2021-08-06T08:36:40.000Z | 2021-08-06T08:36:40.000Z | staticHome/static/staticHome/javascript/validinput.js | SatwikRudra/Caramelit_DJango | b564f285d2ae1e967f08a7aad24b04cb01e33fe4 | [
"MIT"
] | 7 | 2021-04-08T21:58:03.000Z | 2022-01-13T03:09:17.000Z | staticHome/static/staticHome/javascript/validinput.js | SatwikRudra/Caramelit_DJango | b564f285d2ae1e967f08a7aad24b04cb01e33fe4 | [
"MIT"
] | 3 | 2020-07-21T07:01:31.000Z | 2021-01-16T10:47:30.000Z | // This file implements several checks on input elements
var fname = document.getElementById('fname');
var email = document.getElementById('email');
var phone = document.getElementById('phone');
var pincode = document.getElementById('pincode');
var nameVal = false;
var phoneVal = false;
var emailVal = false;
var pincodeVal = false;
// If name, email, phone and pincode are in desirable range then this function will enable the submit button otherwise disable it
function submitButton() {
if(nameVal & phoneVal & pincodeVal & emailVal) {
document.getElementById('submitButton').disabled = false;
} else {
document.getElementById('submitButton').disabled = true;
}
}
// Applies a simple length check on name input
function validateName(e) {
if(fname.value.length < 3) {
fname.style.borderColor = 'red';
nameVal = false;
} else {
fname.style.borderColor = 'green';
nameVal = true;
}
submitButton();
}
// Applies a simple length check on phone input
function validatePhone(e) {
if(phone.value.length < 10) {
phone.style.borderColor = 'red';
phoneVal = false;
} else {
phone.style.borderColor = 'green';
phoneVal = true;
}
submitButton();
}
// Applies a simple length check on pincode input
function validatePincode(e) {
if(pincode.value.length < 6) {
pincode.style.borderColor = 'red';
pincodeVal = false;
} else {
pincode.style.borderColor = 'green';
pincodeVal = true;
}
submitButton();
}
// Applies a set of checks including length and existence of '@' and '.' on email input
function validateEmail(e) {
if(email.value.length > 5 & email.value.indexOf('@') >= 0 & email.value.indexOf('.') >= 0) {
email.style.borderColor = 'green';
emailVal = true;
} else {
email.style.borderColor = 'red';
emailVal = false;
}
submitButton();
}
// Adding event listeners on all the input elements
fname.addEventListener("keyup", validateName);
phone.addEventListener("keyup", validatePhone);
email.addEventListener("keyup", validateEmail);
pincode.addEventListener("keyup", validatePincode); | 30.178082 | 129 | 0.662733 |
4334a3e9b9ee8de07894022e64068acb6601f35b | 4,579 | js | JavaScript | packages/mongo/collection_tests.js | theosp/meteor | e2a6f397e7f537e46a47e4bca37ad597c4633f40 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | null | null | null | packages/mongo/collection_tests.js | theosp/meteor | e2a6f397e7f537e46a47e4bca37ad597c4633f40 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | null | null | null | packages/mongo/collection_tests.js | theosp/meteor | e2a6f397e7f537e46a47e4bca37ad597c4633f40 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | null | null | null | Tinytest.add(
'collection - call Mongo.Collection without new',
function (test) {
test.throws(
function () {
Mongo.Collection(null);
},
/use "new" to construct a Mongo\.Collection/
);
}
);
Tinytest.add('collection - call new Mongo.Collection multiple times',
function (test) {
var collectionName = 'multiple_times_1_' + test.id;
new Mongo.Collection(collectionName);
test.throws(
function () {
new Mongo.Collection(collectionName);
},
/There is already a collection named/
);
}
);
Tinytest.add('collection - call new Mongo.Collection multiple times with _suppressSameNameError=true',
function (test) {
var collectionName = 'multiple_times_2_' + test.id;
new Mongo.Collection(collectionName);
try {
new Mongo.Collection(collectionName, {_suppressSameNameError: true});
test.ok();
} catch (error) {
console.log(error);
test.fail('Expected new Mongo.Collection not to throw an error when called twice with the same name');
}
}
);
Tinytest.add('collection - call new Mongo.Collection with defineMutationMethods=false',
function (test) {
var handlerPropName = Meteor.isClient ? '_methodHandlers' : 'method_handlers';
var methodCollectionName = 'hasmethods' + test.id;
var hasmethods = new Mongo.Collection(methodCollectionName);
test.equal(typeof hasmethods._connection[handlerPropName]['/' + methodCollectionName + '/insert'], 'function');
var noMethodCollectionName = 'nomethods' + test.id;
var nomethods = new Mongo.Collection(noMethodCollectionName, {defineMutationMethods: false});
test.equal(nomethods._connection[handlerPropName]['/' + noMethodCollectionName + '/insert'], undefined);
}
);
Tinytest.add('collection - call find with sort function',
function (test) {
var initialize = function (collection) {
collection.insert({a: 2});
collection.insert({a: 3});
collection.insert({a: 1});
};
var sorter = function (a, b) {
return a.a - b.a;
};
var getSorted = function (collection) {
return collection.find({}, {sort: sorter}).map(function (doc) { return doc.a; });
};
var collectionName = 'sort' + test.id;
var localCollection = new Mongo.Collection(null);
var namedCollection = new Mongo.Collection(collectionName, {connection: null});
initialize(localCollection);
test.equal(getSorted(localCollection), [1, 2, 3]);
initialize(namedCollection);
test.equal(getSorted(namedCollection), [1, 2, 3]);
}
);
Tinytest.add('collection - call native find with sort function',
function (test) {
var collectionName = 'sortNative' + test.id;
var nativeCollection = new Mongo.Collection(collectionName);
if (Meteor.isServer) {
test.throws(
function () {
nativeCollection
.find({}, {
sort: function () {},
})
.map(function (doc) {
return doc.a;
});
},
/Illegal sort clause/
);
}
}
);
Tinytest.add('collection - calling native find with maxTimeMs should timeout',
function(test) {
var collectionName = 'findOptions1' + test.id;
var collection = new Mongo.Collection(collectionName);
collection.insert({a: 1});
function doTest() {
return collection.find({$where: "sleep(100) || true"}, {maxTimeMs: 50}).count();
}
if (Meteor.isServer) {
test.throws(doTest);
}
}
);
Tinytest.add('collection - calling native find with $reverse hint should reverse on server',
function(test) {
var collectionName = 'findOptions2' + test.id;
var collection = new Mongo.Collection(collectionName);
collection.insert({a: 1});
collection.insert({a: 2});
function m(doc) { return doc.a; }
var fwd = collection.find({}, {hint: {$natural: 1}}).map(m);
var rev = collection.find({}, {hint: {$natural: -1}}).map(m);
if (Meteor.isServer) {
test.equal(fwd, rev.reverse());
} else {
// NOTE: should be documented that hints don't work on client
test.equal(fwd, rev);
}
}
);
Tinytest.add('collection - calling native find with good hint and maxTimeMs should succeed',
function(test) {
var collectionName = 'findOptions3' + test.id;
var collection = new Mongo.Collection(collectionName);
collection.insert({a: 1});
if (Meteor.isServer) {
collection.rawCollection().createIndex({a: 1});
}
test.equal(collection.find({}, {hint: {a: 1}, maxTimeMs: 1000}).count(), 1);
}
);
| 29.928105 | 115 | 0.641188 |
4334ebd0410957e542cecad854c6bcc61a62b862 | 667 | js | JavaScript | node_modules/aurelia-cli/build/tasks/release-checks/tasks/install-node-modules.js | Rohzek/CSC435-635-NotesApp | a66c685e72ea98ab8193f62b11a81d9a9d559879 | [
"MIT"
] | 2 | 2017-05-23T15:18:09.000Z | 2018-02-01T02:34:51.000Z | node_modules/aurelia-cli/build/tasks/release-checks/tasks/install-node-modules.js | Rohzek/CSC435-635-NotesApp | a66c685e72ea98ab8193f62b11a81d9a9d559879 | [
"MIT"
] | 1 | 2017-05-30T10:18:58.000Z | 2017-06-01T08:46:55.000Z | node_modules/aurelia-cli/build/tasks/release-checks/tasks/install-node-modules.js | Rohzek/CSC435-635-NotesApp | a66c685e72ea98ab8193f62b11a81d9a9d559879 | [
"MIT"
] | 2 | 2017-05-24T23:02:07.000Z | 2018-01-20T04:15:09.000Z | 'use strict';
const Task = require('./task');
const Yarn = require('../../../../lib/package-managers/yarn').Yarn;
const LogManager = require('aurelia-logging');
const logger = LogManager.getLogger('install-node-modules');
module.exports = class InstallNodeModules extends Task {
constructor() {
super('Install node modules');
}
execute(context) {
logger.debug('installing packages using yarn in ' + context.workingDirectory);
let yarn = new Yarn();
return yarn.install([], { cwd: context.workingDirectory })
.then(() => {
return [
{ message: 'installed the package in ' + context.workingDirectory }
];
});
}
};
| 26.68 | 82 | 0.646177 |
433567563f793848c6f5ef0eaed76beb2c69a908 | 14,856 | js | JavaScript | WB04HF123/reactjs/src/components/Elements/Notifications.js | saifabushamma/laravelTask | 5a7d773e710861e689217c99a939b83424090a0a | [
"MIT"
] | null | null | null | WB04HF123/reactjs/src/components/Elements/Notifications.js | saifabushamma/laravelTask | 5a7d773e710861e689217c99a939b83424090a0a | [
"MIT"
] | null | null | null | WB04HF123/reactjs/src/components/Elements/Notifications.js | saifabushamma/laravelTask | 5a7d773e710861e689217c99a939b83424090a0a | [
"MIT"
] | null | null | null | import React, { Component } from 'react';
import ContentWrapper from '../Layout/ContentWrapper';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { Row,
Col,
Card,
CardHeader,
CardBody,
FormGroup,
Label,
Input,
Button,
Alert,
Modal,
ModalHeader,
ModalBody,
ModalFooter,
Popover,
PopoverHeader,
PopoverBody,
Tooltip,
Progress } from 'reactstrap';
// example component to show popovers
class PopoverItem extends Component {
state = { popoverOpen: false }
toggle = () => this.setState({
popoverOpen: !this.state.popoverOpen
})
render() {
return (
<span>
<Button className="mr-1" color="secondary" id={'Popover-' + this.props.id} onClick={this.toggle}>{this.props.item.text}</Button>
<Popover placement={this.props.item.placement} isOpen={this.state.popoverOpen} target={'Popover-' + this.props.id} toggle={this.toggle}>
<PopoverHeader>Popover Title</PopoverHeader>
<PopoverBody>Proin posuere gravida ipsum, a pretium augue commodo eget. Fusce pellentesque congue justo.</PopoverBody>
</Popover>
</span>
)
}
}
// example component to show tooltip
class TooltipItem extends Component {
// static propTypes { content: PropTypes.string }
state = {
_id: 'id4tooltip_'+new Date().getUTCMilliseconds()+(Math.floor(Math.random()*10) + 1),
tooltipOpen: false
}
toggle = e => this.setState({tooltipOpen: !this.state.tooltipOpen})
render() {
return [
<Tooltip {...this.props} isOpen={this.state.tooltipOpen} toggle={this.toggle} target={this.state._id} key='1'>
{this.props.content}
</Tooltip>,
React.cloneElement(React.Children.only(this.props.children), {
id: this.state._id,
key: '2'
})
]
}
}
class Notifications extends Component {
constructor(props, context) {
super(props, context);
this.state = {
modal: false,
toasterPos: 'top-right',
toasterType: 'info'
};
}
componentDidMount() {
}
toggleModal = () => {
this.setState({
modal: !this.state.modal
});
}
notify = () => toast("Wow so easy !", {
type: this.state.toasterType,
position: this.state.toasterPos
})
onToastPosChanged = e => {
this.setState({
toasterPos: e.currentTarget.value
})
}
onToastTypeChanged = e => {
this.setState({
toasterType: e.currentTarget.value
});
}
render() {
const TOAST_POSITIONS=['top-left', 'top-right', 'top-center', 'bottom-left', 'bottom-right', 'bottom-center']
const TOAST_TYPES=['info', 'success', 'warning', 'error', 'default']
const PLACEMENTS = [
{ placement: 'top', text: 'Top' },
{ placement: 'bottom', text: 'Bottom' },
{ placement: 'left', text: 'Left' },
{ placement: 'right',text: 'Right' }
]
return (
<ContentWrapper>
<div className="content-heading">
<div>Notifications
<span className="text-sm d-none d-sm-block">A complete set of notification posibilities</span>
{/* Breadcrumb below title */}
<ol className="breadcrumb breadcrumb px-0 pb-0">
<li className="breadcrumb-item"><a href="">Home</a>
</li>
<li className="breadcrumb-item"><a href="">Elements</a>
</li>
<li className="breadcrumb-item active">Notifications</li>
</ol>
</div>
{/* Breadcrumb right aligned */}
<ol className="breadcrumb ml-auto">
<li className="breadcrumb-item"><a href="">Home</a>
</li>
<li className="breadcrumb-item"><a href="">Elements</a>
</li>
<li className="breadcrumb-item active">Notifications</li>
</ol>
</div>
{/* Breadcrumb next to view title */}
<ol className="breadcrumb">
<li className="breadcrumb-item"><a href="">Home</a>
</li>
<li className="breadcrumb-item"><a href="">Elements</a>
</li>
<li className="breadcrumb-item active">Notifications</li>
</ol>
<ol className="breadcrumb">
<li className="breadcrumb-item"><a href="">Home</a>
</li>
<li className="breadcrumb-item"><a href="">Elements</a>
</li>
<li className="breadcrumb-item active">Notifications</li>
</ol>
{/* START card */}
<Card className="card-default">
<CardHeader>React Toastify</CardHeader>
<CardBody>
<Row>
<Col md="6">
<Row>
<Col md="6">
<p><strong>Position</strong></p>
{TOAST_POSITIONS.map((pos, i) => (
<FormGroup check key={i}>
<Label check>
<Input type="radio" name="tPosition" value={pos} checked={this.state.toasterPos === pos} onChange={this.onToastPosChanged}/>{' '}
{pos}
</Label>
</FormGroup>
))}
</Col>
<Col md="6">
<p className="mt-3 mt-sm-0"><strong>Type</strong></p>
{TOAST_TYPES.map((type, i) => (
<FormGroup check key={i}>
<Label check>
<Input type="radio" name="tType" value={type} checked={this.state.toasterType === type} onChange={this.onToastTypeChanged}/>{' '}
{type}
</Label>
</FormGroup>
))}
</Col>
</Row>
</Col>
<Col md="6">
<Button color="primary" className="mt-3 mt-sm-0" onClick={this.notify}>Notify !</Button>
<ToastContainer />
</Col>
</Row>
</CardBody>
</Card>
{/* END card */}
{/* START row */}
<div className="row">
<div className="col-xl-6">
{/* START card */}
<Card className="card-default">
<CardHeader>Alert Styles</CardHeader>
<CardBody>
<Alert color="primary">
This is a primary alert — check it out!
</Alert>
<Alert color="secondary">
This is a secondary alert — check it out!
</Alert>
<Alert color="success">
This is a success alert — check it out!
</Alert>
<Alert color="danger">
This is a danger alert — check it out!
</Alert>
<Alert color="warning">
This is a warning alert — check it out!
</Alert>
<Alert color="info">
This is a info alert — check it out!
</Alert>
</CardBody>
</Card>
{/* END card */}
</div>
<div className="col-xl-6">
{/* START card */}
<Card className="card-default">
<CardHeader>Modals</CardHeader>
<CardBody>
{/* Button trigger modal */}
<Button color="primary" onClick={this.toggleModal}>Open Modal Example</Button>
<Modal isOpen={this.state.modal} toggle={this.toggleModal}>
<ModalHeader toggle={this.toggleModal}>Modal title</ModalHeader>
<ModalBody>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</ModalBody>
<ModalFooter>
<Button color="primary" onClick={this.toggleModal}>Do Something</Button>{' '}
<Button color="secondary" onClick={this.toggleModal}>Cancel</Button>
</ModalFooter>
</Modal>
</CardBody>
</Card>
{/* END card */}
{/* START card */}
<Card className="card-default">
<CardHeader>Popovers</CardHeader>
<CardBody>
{ PLACEMENTS.map((popover, i) => (
<PopoverItem key={i} item={popover} id={i} />
))}
</CardBody>
</Card>
{/* END card */}
{/* START card */}
<Card className="card-default">
<CardHeader>Tooltips</CardHeader>
<CardBody>
{ PLACEMENTS.map((item, i) => (
<TooltipItem id={`tooltip-${i}}`} key={i} placement={item.placement} content={`Tooltip on ${item.text}`}>
<Button>Tooltip {item.text}</Button>
</TooltipItem>
))}
</CardBody>
</Card>
{/* END card */}
</div>
</div>
{/* END row */}
{/* START card */}
<Card className="card-default">
<CardHeader>Progress Bar</CardHeader>
<CardBody>
<Progress value={2 * 5} />
<Progress color="success" value="25" />
<Progress color="info" value={50} />
<Progress color="warning" value={75} />
<Progress color="danger" value="100" />
</CardBody>
<CardBody>
<Progress striped value={2 * 5} />
<Progress striped color="success" value="25" />
<Progress striped color="info" value={50} />
<Progress striped color="warning" value={75} />
<Progress striped color="danger" value="100" />
<Progress multi>
<Progress striped bar value="10" />
<Progress striped bar color="success" value="30" />
<Progress striped bar color="warning" value="20" />
<Progress striped bar color="danger" value="20" />
</Progress>
</CardBody>
<CardBody>
<div className="text-center">Plain</div>
<Progress multi>
<Progress bar value="15" />
<Progress bar color="success" value="20" />
<Progress bar color="info" value="25" />
<Progress bar color="warning" value="20" />
<Progress bar color="danger" value="15" />
</Progress>
<div className="text-center">With Labels</div>
<Progress multi>
<Progress bar value="15">Meh</Progress>
<Progress bar color="success" value="35">Wow!</Progress>
<Progress bar color="warning" value="25">25%</Progress>
<Progress bar color="danger" value="25">LOOK OUT!!</Progress>
</Progress>
<div className="text-center">Stripes and Animations</div>
<Progress multi>
<Progress bar striped value="15">Stripes</Progress>
<Progress bar animated color="success" value="30">Animated Stripes</Progress>
<Progress bar color="info" value="25">Plain</Progress>
</Progress>
</CardBody>
</Card>
{/* END card */}
</ContentWrapper>
);
}
}
export default Notifications;
| 45.993808 | 479 | 0.407041 |
43357d4501560bb0e52ac483271354443d6ebbe3 | 12,845 | js | JavaScript | public/js/cityPicker-1.0.0.js | zhangyux/-zdy | 69543f7de6227c084215a745104ec71fd754ec63 | [
"Apache-2.0"
] | null | null | null | public/js/cityPicker-1.0.0.js | zhangyux/-zdy | 69543f7de6227c084215a745104ec71fd754ec63 | [
"Apache-2.0"
] | null | null | null | public/js/cityPicker-1.0.0.js | zhangyux/-zdy | 69543f7de6227c084215a745104ec71fd754ec63 | [
"Apache-2.0"
] | null | null | null | /**
* cityPicker
* v-1.0.0
* dataJson [Json] json数据,是html显示的列表数据
* selectpattern [Array] 用于存储的字段名和默认提示 { 字段名,默认提示 }
* shorthand [Boolean] 用于城市简写功能,默认是不开启(false)
* storage [Boolean] 存储的值是数字还是中文,默认是(true)数字
* linkage [Boolean] 是否联动,默认(true)
* renderMode [Boolean] 是模拟的还是原生的;只在type是selector才有效,默认是(true)模拟
* code [Boolean] 是否输出城市区号值,默认(false),开启就是传字段名('code')
* search [Boolean] 是否开启搜索功能,默认(true)
* level [Number] 多少列 默认是一列/级 (3)
* onInitialized [Attachable] 组件初始化后触发的回调函数
* onClickBefore [Attachable] 组件点击显示列表触发的回调函数(除原生select)
* onForbid [Attachable] 存在class名forbid的禁止点击的回调
* choose-xx [Attachable] 点击组件选项后触发的回调函数 xx(级名称/province/city/district)是对应的级的回调
*/
(function ($, window) {
var $selector;
var grade = ['province', 'city', 'district'];
var defaults = {
dataJson: null,
selectpattern: [{
field: 'userProvinceId',
placeholder: '请选择省份'
},
{
field: 'userCityId',
placeholder: '请选择城市'
},
{
field: 'userDistrictId',
placeholder: '请选择区县'
}
],
shorthand: false,
storage: true,
linkage: true,
renderMode: true,
code: false,
search: true,
level: 3,
onInitialized: function () {},
onClickBefore: function () {},
onForbid: function () {}
};
function Citypicker(options, selector) {
this.options = $.extend({}, defaults, options);
this.$selector = $selector = $(selector);
this.init();
this.events();
}
//功能模块函数
var effect = {
montage: function (data, pid, reg) {
var self = this,
config = self.options,
leng = data.length,
html = '',
code, name, reverse, storage;
for (var i = 0; i < leng; i++) {
if (data[i].parentId === pid) {
//判断是否要输出区号
code = config.code && data[i].cityCode !== '' ? 'data-code=' + data[i].cityCode : '';
//判断是否开启了简写,是就用输出简写,否则就输出全称
name = config.shorthand ? data[i].shortName : data[i].name;
//反向:判断是否开启了简写,是就用输出简写,否则就输出全称
reverse = !config.shorthand ? data[i].shortName : data[i].name;
//存储的是数字还是中文
storage = config.storage ? data[i].id : name;
if (config.renderMode) {
//模拟
html += '<li class="caller" data-id="' + data[i].id + '" data-title="' + reverse + '" ' + code + '>' + name + '</li>';
} else {
//原生
html += '<option class="caller" value="' + storage + '" data-title="' + reverse + '" ' + code + '>' + name + '</option>';
}
}
}
html = data.length > 0 && html ? html : '<li class="forbid">您查找的没有此城市...</li>';
return html;
},
seTemplet: function () {
var config = this.options,
selectemplet = '',
placeholder, field, forbid, citygrade, active, hide,
searchStr = config.search ? '<div class="selector-search">'
+'<input type="text" class="input-search" value="" placeholder="拼音、中文搜索" />'
+'</div>' : '';
for (var i = 0; i < config.level; i++) { //循环定义的级别
placeholder = config.selectpattern[i].placeholder; //默认提示语
field = config.selectpattern[i].field; //字段名称
citygrade = grade[i]; //城市级别名称
forbid = i > 0 ? 'forbid' : ''; //添加鼠标不可点击状态
active = i < 1 ? 'active' : ''; //添加选中状态
hide = i > 0 ? ' hide' : ''; //添加隐藏状态
if (config.renderMode) {
//模拟
selectemplet += '<div class="selector-item storey ' + citygrade + '" data-index="' + i + '">'
+'<a href="javascript:;" class="selector-name reveal df-color ' + forbid + '">' + placeholder + '</a>'
+'<input type=hidden name="' + field + '" class="input-price val-error" value="" data-required="' + field + '">'
+'<div class="selector-list listing hide">'+ searchStr +'<ul></ul></div>'
+'</div>';
} else {
//原生
if(field == 'userProvinceId')
{
selectemplet += '<select id = "province" name="' + field + '" data-index="' + i + '" class="' + citygrade + '">'
+'<option value="0">' + placeholder + '</option>'
+'</select>';
}
if(field == 'userCityId')
{
selectemplet += '<select id = "city" name="' + field + '" data-index="' + i + '" class="' + citygrade + '">'
+'<option value="0">' + placeholder + '</option>'
+'</select>';
}
if(field == 'userDistrictId')
{
selectemplet += '<select id = "district" name="' + field + '" data-index="' + i + '" class="' + citygrade + '">'
+'<option value="0">' + placeholder + '</option>'
+'</select>';
}
}
}
return selectemplet;
},
obtain: function (event) {
var self = this,
config = self.options,
$target = $(event.target),
$parent = $target.parents('.listing'),
index = config.renderMode ? $target.parents('.storey').data('index') : $target.data('index'),
id = config.renderMode ? $target.attr('data-id') : $target.val(),
name = config.shorthand ? $target.data('title') : $target.text(), //开启了简写就拿简写,否则就拿全称中文
storage = config.storage ? id : name, //存储的是数字还是中文
code = config.renderMode ? $target.data('code') : $target.find('.caller:selected').data('code'),
placeholder = index+1 < config.level ? config.selectpattern[index+1].placeholder : '',
placeStr = !config.renderMode ? '<option class="caller">'+placeholder+'</option>'+ effect.montage.apply(self, [config.dataJson, id]) : '<li class="caller hide">'+placeholder+'</li>'+ effect.montage.apply(self, [config.dataJson, id]),
linkage = !config.linkage ? placeStr : effect.montage.apply(self, [config.dataJson, id]),
$storey = $selector.find('.storey').eq(index + 1),
$listing = $selector.find('.listing').eq(index + 1);
$selector = self.$selector;
//选择选项后触发自定义事件choose(选择)事件
$selector.trigger('choose-' + grade[index] +'.citypicker', [$target, storage]);
//赋值给隐藏域-区号
$selector.find('[role="code"]').val(code);
if (config.renderMode) {
//模拟: 添加选中的样式
$parent.find('.caller').removeClass('active');
$target.addClass('active');
//给选中的级-添加值和文字
$parent.siblings('.reveal').removeClass('df-color forbid').text(name).siblings('.input-price').val(storage);
$listing.data('id', id).find('ul').html(linkage).find('.caller').eq(0).trigger('click');
if (!config.linkage) {
$storey.find('.reveal').text(placeholder).addClass('df-color').siblings('.input-price').val('');
$listing.find('.caller').eq(0).remove();
}
} else {
//原生: 下一级附上对应的城市选项,执行点击事件
$target.next().html(linkage).trigger('change').find('.caller').eq(0).prop('selected', true);
}
},
show: function (event) {
var config = this.options,
$target = $(event);
$selector = this.$selector;
$selector.find('.listing').addClass('hide');
$target.siblings('.listing').removeClass('hide');
//点击的回调函数
config.onClickBefore.call($target);
},
hide: function (event) {
var config = this.options,
$target = $(event);
effect.obtain.apply(this, $target);
$selector.find('.listing').addClass('hide');
},
search: function (event) {
var self = this,
$target = $(event.target),
$parent = $target.parents('.listing'),
inputVal = $target.val(),
id = $parent.data('id'),
result = [];
//如果是按下shift/ctr/左右/command键不做事情
if (event.keyCode === 16 || event.keyCode === 17 || event.keyCode === 18 || event.keyCode === 37 || event.keyCode === 39 || event.keyCode === 91 || event.keyCode === 93) {
return false;
}
$.each(this.options.dataJson, function(key, value) {
//拼音或者名称搜索
if(value.pinyin.toLocaleLowerCase().search(inputVal) > -1 || value.name.search(inputVal) > -1 || value.id.search(inputVal) > -1 ){
result.push(value);
}
});
$parent.find('ul').html(effect.montage.apply(self, [result, id]));
}
};
Citypicker.prototype = {
init: function () {
var self = this,
config = self.options,
code = config.code ? '<input type="hidden" role="code" name="' + config.code + '" value="">' : '';
//是否开启存储区号,是就加入一个隐藏域
//添加拼接好的模板
$selector.html(effect.seTemplet.call(self) + code);
//html模板
if (config.renderMode) {
//模拟>添加数据
$selector.find('.listing').data('id', '100000').eq(0).find('ul').html(effect.montage.apply(self, [config.dataJson, '100000']));
} else {
//原生>添加数据
$selector.find('.province').append(effect.montage.apply(self, [config.dataJson, '100000']));
}
//初始化后的回调函数
config.onInitialized.call(self);
},
events: function () {
var self = this,
config = self.options;
//点击显示对应的列表
$selector.on('click.citypicker', '.reveal', function (event) {
var $this = $(this);
if ($this.is('.forbid')) {
config.onForbid.call($this);
return false;
}
effect.show.apply(self, $this);
});
//点击选项事件
$selector.on('click.citypicker', '.caller', $.proxy(effect.hide, self));
//原生选择事件
$selector.on('change.citypicker', 'select', $.proxy(effect.obtain, self));
//文本框搜索事件
$selector.on('keyup.citypicker', '.input-search', $.proxy(effect.search, self));
},
setCityVal: function (val) {
var self = this,
config = self.options,
arrayVal = val;
$.each(arrayVal, function (key, value) {
var $original = $selector.find('.'+grade[key]);
var $forward = $selector.find('.'+grade[key+1]);
if (config.renderMode) {
$original.find('.reveal').text(value.name).removeClass('df-color forbid').siblings('.input-price').val(value.id);
$forward.find('ul').html(effect.montage.apply(self, [config.dataJson, value.id]));
$original.find('.caller[data-id="'+value.id+'"]').addClass('active');
} else {
$forward.html(effect.montage.apply(self, [config.dataJson, value.id]));
$original.find('.caller[value="'+value.id+'"]').prop('selected', true);
}
});
}
};
//模拟:执行点击区域外的就隐藏列表;
$(document).on('click.citypicker', function (event){
if($selector && $selector.find(event.target).length < 1) {
$selector.find('.listing').addClass('hide');
}
});
$.fn.cityPicker = function (options) {
return new Citypicker(options, this);
};
})(jQuery, window); | 41.569579 | 249 | 0.461658 |
4335acab6f6f6ebbe4e305ec0dce3fb0bae9c9ac | 24,684 | js | JavaScript | src/symbols/define-libraries.js | julianjensen/inference | 44457f19b8534392791fe6337101f5c207add38e | [
"MIT"
] | null | null | null | src/symbols/define-libraries.js | julianjensen/inference | 44457f19b8534392791fe6337101f5c207add38e | [
"MIT"
] | null | null | null | src/symbols/define-libraries.js | julianjensen/inference | 44457f19b8534392791fe6337101f5c207add38e | [
"MIT"
] | null | null | null | /** ******************************************************************************************************************
* @file Describe what define-libraries does.
* @author Julian Jensen <jjdanois@gmail.com>
* @since 1.0.0
* @date 04-Feb-2018
*********************************************************************************************************************/
"use strict";
import { inspect } from 'util';
import { nodeName } from "../ts/ts-helpers";
import { array } from "convenience";
import { output } from "../utils/source-code";
import { NodeFlags } from "../types";
import {
get_type,
create_type_alias,
create_constructor,
parser,
context
} from "../earlier/declaration";
const
is_keyword = ( mods, kw ) => !!mods && !!mods.find( n => nodeName( n ) === kw ),
is_optional = node => !!node && !!node.questionToken,
interfaces = new Map(),
visitors = {
SourceFile,
InterfaceDeclaration,
ModuleDeclaration,
ClassDeclaration,
MethodSignature,
CallSignature,
ConstructSignature,
PropertyDeclaration: PropertySignature,
PropertySignature,
VariableDeclaration,
VariableStatement,
IndexSignature,
Parameter,
FunctionDeclaration: parse_function_declaration,
TypeReference: parse_type_reference,
TypeParameter: parse_type_parameter,
TypeOperator: parse_type_operator,
TypePredicate: parse_type_predicate,
TypeAliasDeclaration: parse_type_alias_declaration,
UnionType: parse_union_type,
IntersectionType: parse_intersection_type,
TupleType: parse_tuple_type,
ParenthesizedType: parse_parenthesized_type,
MappedType: parse_mapped_type,
IndexedAccessType: parse_indexed_access_type,
TypeLiteral: parse_type_literal,
Constructor: ConstructSignature,
ConstructorType: ConstructSignature,
ArrayType: parse_array_type,
FunctionType: parse_function_type,
StringKeyword: () => get_type( '""' ),
NumberKeyword: () => get_type( 'number' ),
BooleanKeyword: () => get_type( 'boolean' ),
VoidKeyword: () => get_type( 'undefined' ).as_void(),
AnyKeyword: () => get_type( 'any' )
};
/**
* @param {Node} node
* @param {?Node} parent
* @param {string} field
* @param {number} index
* @param {function} recurse
*/
function Parameter( node, parent, field, index, recurse )
{
const p = {
name: node.name.escapedText,
rest: !!node.dotDotDotToken,
type: !!node.type && parse_type( node.type ),
initializer: node.initializer && ( recurse ? recurse( node.initializer ) : parse_type( node.initializer ) ),
optional: is_optional( node ),
toString() { return `${this.rest ? '...' : ''}${this.name}${this.optional ? '?' : ''}: ${this.type}${this.initializer ? ` = ${this.initializer} : ''` : ''}`; }
};
return parser.parameter( p.name, p.type );
}
/**
* @param {Node} node
* @param {?Node} parent
* @param {string} field
* @param {number} index
* @param {function} recurse
*/
function VariableStatement( node, parent, field, index, recurse )
{
const
decls = node.declarationList,
vars = decls.declarations.map( ( n, i ) => VariableDeclaration( n, decls, 'declarationList', i, recurse ) );
if ( decls.flags & ( NodeFlags.Let | NodeFlags.Const ) )
vars.forEach( v => v.general_type( decls.flags & NodeFlags.Let ? 'let' : decls.flags & NodeFlags.Const ? 'const' : 'var' ) );
// console.log( vars.map( v => `${v}` ).join( ';\n' ) );
return vars;
}
// /**
// * @class
// */
// class Variable
// {
// /**
// * @param name
// * @param type
// * @param init
// * @param ro
// */
// constructor( name, type, init, ro = 'var' )
// {
// this.name = name;
// this.type = type;
// this.init = init;
// this.varType = ro;
// }
//
// /**
// * 536870914
// * 536870914
// * @return {string}
// */
// toString()
// {
// const
// init = this.init ? ` = ${this.init}` : '';
//
// return `declare ${this.varType} ${this.name}: ${this.type}${init};`;
// }
// }
/**
* @param {Node} node
* @param {?Node} parent
* @param {string} field
* @param {number} index
* @param {function} recurse
*/
function VariableDeclaration( node, parent, field, index, recurse )
{
const v = context.current().add( node.name.escapedText, parse_type( node.type ) ).decl_node( node ).general_type( 'var' );
if ( node.initializer )
v.initializer( recurse( node.initializer ) );
return v;
// return new Variable( node.name.escapedText, parse_type( node.type ), node.initializer && recurse( node.initializer ) );
// return {
// name: node.name.escapedText,
// type: parse_type( node.type ),
// initializer: node.initializer && recurse( node.initializer )
// };
}
/**
* @param {Node} node
*/
function IndexSignature( node )
{
return {
readOnly: is_keyword( node.modifiers, 'ReadonlyKeyword' ),
parameters: node.parameters.map( parse_type ),
type: parse_type( node.type ),
declType: 'index',
toString()
{
return `${this.readOnly ? 'readonly ' : ''}[ ${this.parameters.map( p => `${p}` ).join( '; ' )} ]: ${this.type}`;
}
};
}
// /**
// * @param {string} name
// * @return {{name: *, returns: null, params: Array, types: Array, type: null}}
// */
// function create_signature( name )
// {
// return {
// name,
// returns: null,
// params: [],
// types: [],
// type: null
// };
// }
// /**
// * @param {string} name
// * @param {string} iname
// * @return {*}
// */
// function add_interface_member( name, iname = currentOwner )
// {
// let intr;
//
// if ( string( iname ) )
// intr = interfaces.get( iname );
// else if ( !iname )
// intr = currentOwner;
//
// if ( !intr ) return null;
//
// const member = create_signature( name );
//
// const slot = intr.members.get( name );
//
// if ( !slot )
// intr.members.set( name, member );
// else if ( object( slot ) )
// intr.set( name, [ slot, member ] );
// else if ( array( slot ) )
// slot.push( member );
// else
// return null;
//
// return member;
// }
/**
* @param {Node} node
* @param {?Node} parent
* @param {string} field
* @param {number} index
* @param {function} recurse
*/
export function visitor( node, parent, field, index, recurse )
{
const type = nodeName( node );
return visitors[ type ] ? visitors[ type ]( node, parent, field, index, recurse ) : true;
}
/**
* @param {Node} node
* @param {?Node} parent
* @param {string} field
* @param {number} index
* @param {function} recurse
*/
function SourceFile( node, parent, field, index, recurse )
{
// console.log( 'idents:', node.identifiers );
const flatten = arr => arr.reduce( ( list, cur ) => list.concat( array( cur ) ? flatten( cur ) : cur ), [] );
console.log( `${flatten( recurse( node.statements ) ).join( '\n\n' )}` );
}
/**
* @param {Node} node
* @param {?Node} parent
* @param {string} field
* @param {number} i
* @param {function} recurse
*/
function InterfaceDeclaration( node, parent, field, i, recurse )
{
const
name = node.name.escapedText,
types = node.typeParameters && node.typeParameters.map( parse_type );
parser.interface( name, types );
if ( node.members ) node.members.map( recurse );
context.pop();
}
/**
* @param {Node} node
* @param {?Node} parent
* @param {string} field
* @param {number} i
* @param {function} recurse
*/
function ClassDeclaration( node, parent, field, i, recurse )
{
const
name = node.name.escapedText,
types = node.typeParameters && node.typeParameters.map( parse_type );
parser.interface( name, types );
if ( node.members ) node.members.map( recurse );
context.pop();
}
/**
* @param {Node} node
* @param {?Node} parent
* @param {string} field
* @param {number} i
* @param {function} recurse
*/
function ModuleDeclaration( node, parent, field, i, recurse )
{
parser.object( node.name.escapedText );
if ( node.body.statements ) node.body.statements.map( recurse );
context.pop();
}
/**
* @param {Node} node
* @param {?Node} parent
* @param {string} field
* @param {number} i
* @param {function} recurse
*/
function MethodSignature( node, parent, field, i, recurse )
{
const
// fn = parse_function_type( node ),
m = parser.method(); // fn.name, fn.type, fn.parameters, fn.typeParameters );
return function_bit_by_bit( node, m );
// m.isType = false;
//
// return fn.general_type( 'method' ).decl_node( node );
}
/**
* @param {Node} node
* @param {?Node} parent
* @param {string} field
* @param {number} i
* @param {function} recurse
*/
function CallSignature( node, parent, field, i, recurse )
{
const
fn = parse_function_type( node, false ),
c = parser.call( fn.type, fn.parameters, fn.typeParameters );
c.general_type( 'call' ).decl_node( node );
return c;
}
/**
* @param {Node} node
* @param {?Node} parent
* @param {string} field
* @param {number} i
* @param {function} recurse
*/
function ConstructSignature( node, parent, field, i, recurse )
{
const
fn = parse_function_type( node, false ),
c = parser.construct( fn.type, fn.args, fn.typeParameters );
c.general_type( 'constructor' ).decl_node( node );
return c;
}
const
owners = [];
/**
* @param {Node} node
* @param {{fn: *, add_type_params: function(*=): ObjectDeclaration, add_type: function(*=): (ObjectDeclaration|*), add_params: function(*=): ObjectDeclaration, add_name: function(*=): (*|ObjectDeclaration|{enum})}} fn
* @return {ObjectDeclaration}
*/
function function_bit_by_bit( node, fn )
{
if ( node.name ) fn.add_name( node.name.escapedText );
if ( node.typeParameters ) fn.add_type_params( node.typeParameters.map( parse_type ) );
if ( node.type ) fn.add_type( parse_type( node.type ) );
if ( node.parameters ) fn.add_params( node.parameters.map( parse_type ) );
fn.type.isType = true;
params.forEach( p => p.owner( fn ) );
return fn;
}
/**
* @todo This becomes a new type, we should add it properly and wire up the proto chain
*
* @param {Node} node
* @param {boolean} [hasName=true]
*/
function parse_function_type( node, hasName = true )
{
return {
name: hasName && node.name ? node.name.escapedText : null,
typeParameters: node.typeParameters && node.typeParameters.map( parse_type ),
parameters: node.parameters ? node.parameters.map( parse_type ) : [],
type: node.type && parse_type( node.type )
};
}
/**
* members[ 0 ]: "PropertySignature" => InterfaceDeclaration
* modifiers[ 0 ]: "ReadonlyKeyword" => PropertySignature
* name: "Identifier ("length")" => PropertySignature
* type: "NumberKeyword" => PropertySignature
* jsDoc[ 0 ]: "JSDocComment" => PropertySignature
*
* @param {Node} node
*/
function PropertySignature( node )
{
// return {
// name: node.name.escapedText,
// readOnly: is_keyword( node.modifiers, 'ReadonlyKeyword' ),
// type: parse_type( node.type ),
// declType: 'property',
// toString()
// {
// return `${this.readOnly ? 'readonly ' : ''}${this.name}: ${this.type}`;
// }
// };
const
prop = parser.property( node.name.escapedText, prop.type );
prop.readOnly = is_keyword( node.modifiers, 'ReadonlyKeyword' );
return prop;
}
/**
* @class
*/
class TypeDefinition
{
/**
*
*/
constructor()
{
this.parent = null;
}
}
/**
* In typeParameters:
* "K extends keyof T"
* TypeParameter
* name: Identifier
* constraint: TypeOperator
* type: TypeReference
* typeName: Identifier
*
* In MappedType.typeParameter
* "P in keyof T"
* TypeParameter
* name: Identifier
* constraint: TypeOperator
* type: TypeReference
* typename: Identifier
*
* "P in K"
* TypeParameter
* name: Identifier
* constraint: TypeReference
* typeName: Identifer
*
* @class
*/
export class TypeParameter extends TypeDefinition
{
/**
* @param {string} name
* @param {?(TypeReference|BaseType)} [constraint]
* @param {?(TypeReference|TypeOperator|BaseType|string|number)} [defaultVal]
* @param {boolean} [inMappedType=false]
*/
constructor( name, constraint, defaultVal, inMappedType = false )
{
super();
this.name = name;
this.constraint = constraint;
this.default = defaultVal;
this.inMappedType = inMappedType;
this.owner = null;
}
/**
* @param {object<string, { type: BaseType, constraint: BaseType | TypeReference }>} types
* @param {BaseType} [type]
*/
materialize( types, type = this.default )
{
types[ this.name ] = {
type,
constraint: this.constraint
};
}
/**
* @return {string}
*/
toString()
{
let str = this.name,
connect = this.inMappedType ? ' in ' : ' extends ';
if ( this.constraint )
str += connect + this.constraint;
if ( this.default )
str += ' = ' + this.default;
return str;
}
}
/**
* @class
*/
export class TypeReference extends TypeDefinition
{
/**
* @param {string} name
* @param {(TypeReference)[]} args
*/
constructor( name, ...args )
{
super();
this.name = name;
this.typeArguments = args;
this.refTarget = null;
}
/**
* @return {string}
*/
toString()
{
let str = this.name;
if ( this.typeArguments.length )
str += '<' + this.typeArguments.join( ', ' ) + '>';
return str;
}
}
/**
* @class
*/
export class TypePredicate extends TypeDefinition
{
/**
* @param {string} paramName
* @param {?(TypeReference|BaseType)} type
*/
constructor( paramName, type )
{
super();
this.name = paramName;
this.type = type;
this.refTarget = null;
}
/**
* @return {string}
*/
toString()
{
return this.name + ' ' + this.type;
}
}
/**
* Prints as `keyof`
* @class
*/
export class TypeOperator extends TypeDefinition
{
/**
* @param {TypeReference} ref
*/
constructor( ref )
{
super();
this.type = ref;
this.refTarget = null;
}
/**
* @param {Array<TypeParameter>} refs
* @return {Array<string>}
*/
refName( refs )
{
if ( refs )
this.refTarget = refs[ 0 ];
else
return [ this.type.refName ];
}
/**
* @return {string}
*/
toString()
{
return 'keyof ' + this.type;
}
}
/**
* @class
*/
export class UnionType extends TypeDefinition
{
/**
* @param {(TypeReference|BaseType)[]} types
*/
constructor( ...types )
{
super();
this.types = types;
}
resolve( res )
{
this.types.forEach( t => t.resolve( res ) );
}
/**
* @return {string}
*/
toString()
{
return this.types.join( ' | ' );
}
}
/**
* @class
*/
export class IntersectionType extends TypeDefinition
{
/**
* @param {(TypeReference|BaseType)[]} types
*/
constructor( ...types )
{
super();
this.types = types;
}
resolve( res )
{
this.types.forEach( t => t.resolve( res ) );
}
/**
* @return {string}
*/
toString()
{
return this.types.join( ' & ' );
}
}
/**
* @class
*/
export class TupleType extends TypeDefinition
{
/**
* @param {(TypeReference|BaseType)[]} types
*/
constructor( ...types )
{
super();
this.types = types;
}
/**
* @param {Array<TypeParameter>} refs
* @return {Array<string>}
*/
refName( refs )
{
if ( refs )
refs.forEach( ( rn, i ) => this.types[ i ].refName( rn ) );
else
return this.types.map( t => t.refName() );
}
/**
* @return {string}
*/
toString()
{
return '[ ' + this.types.join( ', ' ) + ' ]';
}
}
/**
* @class
*/
export class ParenthesizedType extends TypeDefinition
{
/**
* @param {(TypeReference|BaseType)} type
*/
constructor( type )
{
super();
this.type = type;
}
/**
* @return {string}
*/
toString()
{
return '( ' + this.type + ' )';
}
}
/**
* @class
*/
export class TypeAliasDeclaration extends TypeDefinition
{
/**
* @param {string} name
* @param {Array<TypeParameter>|TypeParameter} typeParameters
* @param {TypeReference|BaseType} type
*/
constructor( name, typeParameters, type )
{
super();
this.name = name;
this.typeParameters = typeParameters ? ( Array.isArray( typeParameters ) ? typeParameters : [ typeParameters ] ) : null;
this.type = type;
let underlyingName;
switch ( type.constructor.name )
{
case 'MappedType':
underlyingName = 'object';
break;
case 'FunctionType':
underlyingName = 'function';
break;
case 'ArrayType':
underlyingName = 'array';
break;
default:
if ( type instanceof TypeDefinition )
underlyingName = 'typedef';
else
underlyingName = type.name;
break;
}
this.typeAlias = create_type_alias( name, typeParameters, type.name );
if ( underlyingName === 'typedef' )
this.typeAlias.underlying = type;
}
/**
*
* @return {string}
*/
toString()
{
const
tp = this.typeParameters ? `<${this.typeParameters.join( ', ' )}>` : '';
if ( this.type instanceof MappedType )
return `type ${this.name}${tp} = {\n ${this.type}\n};\n`;
else
return `type ${this.name}${tp} = ${this.type};\n`;
}
}
/**
* @class
*/
export class MappedType extends TypeDefinition
{
/**
* @param {TypeParameter} typeParam
* @param {IndexedAccessType} type
* @param {boolean} [ro=false]
*/
constructor( typeParam, type, ro = false )
{
super();
this.typeParam = typeParam;
this.type = type;
this.readOnly = ro;
this.typeParam.inMappedType = true;
this.typeAlias = create_type_alias();
}
/**
* @return {string}
*/
toString()
{
return `{ ${this.readOnly ? 'readonly ' : ''}[ ${this.typeParam} ]: ${this.type} }`;
}
}
/**
* @class
*/
export class IndexedAccessType extends TypeDefinition
{
/**
* @param objectType
* @param indexType
*/
constructor( objectType, indexType )
{
super();
this.objectType = objectType;
this.indexType = indexType;
}
/**
* @return {string}
*/
toString()
{
return `${this.objectType}[ ${this.indexType} ]`;
}
}
/**
* @param {Node} node
* @return {*}
*/
function parse_type( node )
{
if ( !node ) return null;
if ( array( node ) )
return node.map( n => parse_type( n ) );
const type = nodeName( node );
if ( visitors[ type ] ) return visitors[ type ]( node );
else if ( type.endsWith( 'Type' ) || type.endsWith( 'Keyword' ) ) return type.replace( /^(.*)(?:Type|Keyword)$/, '$1' );
output.warn( `Parsing type, missing handler for ${type}`, node );
return null;
}
/**
* @param {Node} node
* @return {ArrayType}
*/
function parse_array_type( node )
{
return new ArrayType( null, parse_type( node.elementType ) );
}
/**
* @param {Node} node
* @return {UnionType}
* @constructor
*/
function parse_union_type( node )
{
return new UnionType( ...node.types.map( parse_type ) );
}
/**
* @param {Node} node
* @return {IntersectionType}
*/
function parse_intersection_type( node )
{
return new IntersectionType( ...node.types.map( parse_type ) );
}
/**
* @param {Node} node
* @return {TupleType}
*/
function parse_tuple_type( node )
{
return new TupleType( node.elementTypes.map( parse_type ) );
}
/**
* @param {Node} node
* @return {ParenthesizedType}
*/
function parse_parenthesized_type( node )
{
return new ParenthesizedType( parse_type( node.type ) );
}
/**
* @param {Node} node
* @return {MappedType}
*/
function parse_mapped_type( node )
{
const
typeParam = parse_type( node.typeParameter ),
type = parse_type( node.type );
return new MappedType( typeParam, type, !!node.readonlyToken );
}
/**
* @param {Node] node
* @return {IndexedAccessType}
*/
function parse_indexed_access_type( node )
{
return new IndexedAccessType( parse_type( node.objectType ), parse_type( node.indexType ) );
}
/**
* @param {Node} node
* @return {TypeParameter}
*/
function parse_type_parameter( node )
{
let name = nodeName( node ),
n = node.parent,
stopName = n && nodeName( n );
while ( n && name !== 'MappedType' && stopName !== 'TypeAliasDefinition' )
{
n = n.parent;
name = stopName;
stopName = nodeName( n );
}
const
inMappedType = name === 'MappedType',
id = node.name.escapedText,
constraint = parse_type( node.constraint ),
defaultVal = parse_type( node.default );
return new TypeParameter( id, constraint, defaultVal, inMappedType );
}
/**
* @param {Node} node
* @return {TypeReference}
*/
function parse_type_reference( node )
{
const
name = node.typeName.escapedText,
args = node.typeArguments ? node.typeArguments.map( parse_type ) : [];
return new TypeReference( name, ...args );
}
/**
* @param {Node} node
* @return {TypeOperator}
*/
function parse_type_operator( node )
{
return new TypeOperator( parse_type( node.type ) );
}
/**
* @param {Node} node
* @return {TypePredicate}
*/
function parse_type_predicate( node )
{
const
name = node.parameterName.escapedText,
ref = parse_type( node.type );
return new TypePredicate( name, ref );
}
/**
* @param {Node} node
* @return {TypeAliasDeclaration}
*/
function parse_type_alias_declaration( node )
{
const
name = node.name.escapedText,
tp = node.typeParameters && node.typeParameters.map( parse_type ),
type = node.type && parse_type( node.type );
const r = new TypeAliasDeclaration( name, tp, type );
// console.log( `${r}` );
return r;
}
/**
* @param {Node} node
* @param {?Node} parent
* @param {string} field
* @param {number} i
* @param {function} recurse
*/
function parse_type_literal( node, parent, field, i, recurse )
{
const
name = '$$type_literal_' + ( ~~( Math.random() * 1e7 ) ).toString( 16 ),
members = node.members && node.members.map( parse_type ),
joiner = members.length > 3 ? ';\n ' : '; ';
interfaces.set( name,
{
name,
members,
declType: 'typeliteral'
} );
return {
name,
members,
declType: "typeLiteral",
toString()
{
return `{ ${members.join( joiner )} }`;
}
};
// console.log( `type literal "${name}":\n ${members.join( '\n ' )}` );
}
function resolve_type_references( decl )
{
let t = decl.typeParameters;
t = array( t ) ? t : t ? [ t ] : [];
if ( !t.length ) return;
t.forEach( type => {
} );
}
| 23.026119 | 218 | 0.545779 |
4335bcfeaee42c80b6140daf43481f96ef11a330 | 2,562 | js | JavaScript | index.js | s0kil/tiny-map | 99e47db1f3256b01512972c53da1d04e2ba775d8 | [
"BSD-2-Clause"
] | 1 | 2020-09-15T22:13:28.000Z | 2020-09-15T22:13:28.000Z | index.js | s0kil/tiny-map | 99e47db1f3256b01512972c53da1d04e2ba775d8 | [
"BSD-2-Clause"
] | null | null | null | index.js | s0kil/tiny-map | 99e47db1f3256b01512972c53da1d04e2ba775d8 | [
"BSD-2-Clause"
] | null | null | null | /**
* A tiny script for displaying a static map with tiles.
* You can't interact with the map.
* /
/**
* @typedef {Object} options
* @property {number[]} center Geographical center of the map, contains two numbers: [longitude, latitude]
* @property {number} zoom Zoom of the map
* @property {string} tileUrl URL template for tiles, ex: `//tile{s}.maps.2gis.com/tiles?x={x}&y={y}&z={z}`
* @property {?string} subdomains Subdomains of the tile server, ex: `0123`
* @property {?number} size Size of the map container. This is an optional parameter, set it if you don't want additional reflow.
*/
/**
* @param {HTMLElement} container HTML Element that will contain the map
* @param {options} options
*/
export function tinyMap(container, options) {
const tileSize = 256;
const R = 6378137;
const maxLat = 85.0511287798;
let pixelCenter = lngLatToPoint(options.center, options.zoom);
let size = options.size || [container.offsetWidth, container.offsetHeight];
let halfSize = [size[0] / 2, size[1] / 2];
let minTile = [
(pixelCenter[0] - halfSize[0]) / tileSize | 0,
(pixelCenter[1] - halfSize[1]) / tileSize | 0
];
let maxTile = [
(pixelCenter[0] + halfSize[0]) / tileSize + 1 | 0,
(pixelCenter[1] + halfSize[1]) / tileSize + 1 | 0
];
for (let y = minTile[1]; y < maxTile[1]; y++) {
for (let x = minTile[0]; x < maxTile[0]; x++) {
let tile = new Image();
tile.style.cssText = "position: absolute;" +
"left:" + (halfSize[0] + x * tileSize - pixelCenter[0] | 0) + "px;" +
"top:" + (halfSize[1] + y * tileSize - pixelCenter[1] | 0) + "px;" +
"width:" + tileSize + "px;" +
"height:" + tileSize + "px;";
tile.src = getUrl(x, y);
container.appendChild(tile);
}
}
function getUrl(x, y) {
return options.tileUrl
.replace("{s}",
options.subdomains ? options.subdomains[Math.abs(x + y) % options.subdomains.length] : ""
)
.replace("{x}", x)
.replace("{y}", y)
.replace("{z}", options.zoom);
}
function lngLatToPoint(lngLat, zoom) {
let point = project(lngLat);
let scale = 256 * Math.pow(2, zoom);
let k = 0.5 / (Math.PI * R);
point[0] = scale * (k * point[0] + 0.5);
point[1] = scale * (-k * point[1] + 0.5);
return point;
}
function project(lngLat) {
let d = Math.PI / 180;
let lat = Math.max(Math.min(maxLat, lngLat[1]), -maxLat);
let sin = Math.sin(lat * d);
return [
R * lngLat[0] * d,
R * Math.log((1 + sin) / (1 - sin)) / 2
];
}
}
| 31.243902 | 129 | 0.588993 |
4336357bdaed706a7536e0b31c0d1883d01b915a | 571 | js | JavaScript | src/components/ResultLabel.js | Ranjana-Kambhammettu/currency-converter | 9aa17977b357bf5e655fe3f5d5f1a457ae748575 | [
"MIT"
] | 6 | 2021-09-16T11:32:17.000Z | 2021-10-01T12:26:23.000Z | src/components/ResultLabel.js | Ranjana-Kambhammettu/currency-converter | 9aa17977b357bf5e655fe3f5d5f1a457ae748575 | [
"MIT"
] | 4 | 2021-10-01T12:15:07.000Z | 2021-10-17T08:50:57.000Z | src/components/ResultLabel.js | Ranjana-Kambhammettu/currency-converter | 9aa17977b357bf5e655fe3f5d5f1a457ae748575 | [
"MIT"
] | 6 | 2021-09-17T05:46:52.000Z | 2021-10-05T12:47:47.000Z | import React from "react"
import styles from "./ResultLabel.module.css"
class ResultLabel extends React.Component {
render() {
return(
<div className={styles.result}>
<button
className={styles.convert}
onClick={this.handleChange}
>
Convert
</button>
<label className={styles.label}>
Amount: {this.props.result}
</label>
</div>
);
}
}
export default ResultLabel
| 24.826087 | 48 | 0.474606 |
433652ea3b03d4ffa99ae988b286507736e1dfa4 | 678 | js | JavaScript | Courses 2016-spring/JavaScript-Fundamentals/05ConditionalStatements/06QuadraticEquasion.js | nmarazov/TA-Homework | 4a4fcb1abd2123536742461a64c0363151c4ee0a | [
"MIT"
] | null | null | null | Courses 2016-spring/JavaScript-Fundamentals/05ConditionalStatements/06QuadraticEquasion.js | nmarazov/TA-Homework | 4a4fcb1abd2123536742461a64c0363151c4ee0a | [
"MIT"
] | 1 | 2016-09-27T20:17:09.000Z | 2016-12-18T09:54:01.000Z | Courses 2016-spring/JavaScript-Fundamentals/05ConditionalStatements/06QuadraticEquasion.js | nmarazov/TA-Homework | 4a4fcb1abd2123536742461a64c0363151c4ee0a | [
"MIT"
] | null | null | null | function equasion(args) {
var a = +args[0];
var b = +args[1];
var c = +args[2];
var x1;
var x2;
var d = (b * b) - (4 * a * c);
var sqrD = Math.sqrt(d);
if (d > 0) {
x1 = -(-b - sqrD) / (2 * a);
x2 = -(-b + sqrD) / (2 * a);
if (x1 > x2) {
console.log('x1=' + x2.toFixed(2) + "; x2=" + x1.toFixed(2));
}
else {
console.log('x1=' + x1.toFixed(2) + "; x2=" + x2.toFixed(2));
}
}
else if (d === 0) {
x1 = b / (2 * a);
console.log('x1=x2='+ x1.toFixed(2));
}
else if(d < 0){
console.log('no real roots');
}
}
equasion(["2", "5", "-3"]);
| 21.870968 | 71 | 0.382006 |
43366378a581fface7a227ac348c55eb88ae4d28 | 2,986 | js | JavaScript | native/packages/react-native-bpk-component-button/src/utils-test.js | RCiesielczuk/backpack | d8e252165e446e92b513a2f5ffdededc8f57b731 | [
"Apache-2.0"
] | null | null | null | native/packages/react-native-bpk-component-button/src/utils-test.js | RCiesielczuk/backpack | d8e252165e446e92b513a2f5ffdededc8f57b731 | [
"Apache-2.0"
] | null | null | null | native/packages/react-native-bpk-component-button/src/utils-test.js | RCiesielczuk/backpack | d8e252165e446e92b513a2f5ffdededc8f57b731 | [
"Apache-2.0"
] | null | null | null | /*
* Backpack - Skyscanner's Design System
*
* Copyright 2018 Skyscanner Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* @flow */
import React from 'react';
import BpkText from 'react-native-bpk-component-text';
import { iconPropType, themePropType } from './utils';
describe('utils', () => {
describe('iconPropType', () => {
it('should accept iconOnly prop when icon prop is supplied', () => {
expect(
iconPropType(
{
iconOnly: true,
icon: 'baggage',
},
'icon',
'BpkButton',
),
).toBeFalsy();
});
it('should accept elements as the icon property', () => {
expect(
iconPropType(
{
iconOnly: true,
icon: <BpkText>foo</BpkText>,
},
'icon',
'BpkButton',
),
).toBeFalsy();
});
it('should reject iconOnly prop when icon prop is not supplied', () => {
const result = iconPropType(
{
iconOnly: true,
},
'icon',
'BpkButton',
);
const errorString =
result instanceof Error ? result.toString() : 'Expected an error';
expect(errorString).toEqual(
'Error: Invalid prop `icon` supplied to `BpkButton`. When `iconOnly` is enabled, `icon` must be supplied.',
);
});
});
describe('themePropType', () => {
it('should reject theme property when some theme attributes are omitted', () => {
const result = themePropType(
{
type: 'primary',
theme: {},
},
'theme',
'BpkButton',
);
const errorString =
result instanceof Error ? result.toString() : 'Expected an error';
expect(errorString).toEqual(
'Error: Invalid prop `theme` supplied to `BpkButton`. For buttons of type `primary`, the `theme` prop must include `buttonPrimaryTextColor, buttonPrimaryGradientStartColor, buttonPrimaryGradientEndColor`',
);
});
it('should accept theme property when correct attributes are supplied', () => {
expect(
themePropType(
{
type: 'primary',
theme: {
buttonPrimaryGradientStartColor: 'red',
buttonPrimaryGradientEndColor: 'green',
buttonPrimaryTextColor: 'blue',
},
},
'theme',
'BpkButton',
),
).toBeFalsy();
});
});
});
| 27.394495 | 213 | 0.572003 |
4337055ead8989970701529341b7a0a814924d25 | 566 | js | JavaScript | app/client/templates/appLogin2Layout.js | DevsignStudio/docare | 79257c4d88b0cbd4521364c19e50e3f417c4df56 | [
"MIT"
] | 1 | 2015-11-19T16:25:28.000Z | 2015-11-19T16:25:28.000Z | app/client/templates/appLogin2Layout.js | DevsignStudio/docare | 79257c4d88b0cbd4521364c19e50e3f417c4df56 | [
"MIT"
] | null | null | null | app/client/templates/appLogin2Layout.js | DevsignStudio/docare | 79257c4d88b0cbd4521364c19e50e3f417c4df56 | [
"MIT"
] | null | null | null | Meteor.startup(function() {
Template.appLogin2Layout.helpers({
phoneNumber: function() {
return Session.get("phoneNumber");
}
});
Template.appLogin2Layout.events({
"submit #loginForm2": function(event) {
event.preventDefault();
Meteor.call("usernameExists",Session.get("phoneNumber"), function(err,data) {
if (err)
console.log("err");
Session.set("existsID", data);
});
Router.go("/login-3");
}
});
});
| 25.727273 | 89 | 0.508834 |
43374e22334228b3d67a69be1f650f09c273741a | 2,839 | js | JavaScript | public/Mobile/Functions/generate_semester_content.js | BlackPyro1994/syp_pmti | ac5c59b1091dfb417f512e4effe04263e26f0c2e | [
"CC0-1.0"
] | null | null | null | public/Mobile/Functions/generate_semester_content.js | BlackPyro1994/syp_pmti | ac5c59b1091dfb417f512e4effe04263e26f0c2e | [
"CC0-1.0"
] | null | null | null | public/Mobile/Functions/generate_semester_content.js | BlackPyro1994/syp_pmti | ac5c59b1091dfb417f512e4effe04263e26f0c2e | [
"CC0-1.0"
] | null | null | null | /**
* Erstellt den Inhalt der Semester und speichert diese Daten
* (in blocked, catalog_array, content_html)
*
*/
function generate_semester_content()
{
var length = content.length;
var sem_id;
var inner_length;
var sem_content = "";
var inner_content = "";
for (i = 0; i < length; i++)
{
sem_id = i + 1;
inner_length = content[i].length;
sem_content = "";
inner_content = "";
update_semester_ects(sem_id);
for (j = 0; j < inner_length; j++)
{
var mod_id = content[i][j][0];
if (mod_id == "M07_WPP" || mod_id.includes("ALM"))
{
var string = ('<div id="' + mod_id + '" class="row modules_border class_click_modules_in_semester margin-top"><button id="' + mod_id + '" class="btn btn-block"><div id="' + mod_id + '" class="row text-left"><div id="' + mod_id + '" class="col fett"><p>' + (mod_id.includes("ALM") ? "ALM" : mod_id) + '</p></div><div id="' + mod_id + '" class="col text-right"><p id="' + mod_id + '">ECTS: ' + content[i][j][9] + '</p></div></div><div id="' + mod_id + '" class="row normal text-left"><div id="' + mod_id + '" class="col"><p id="' + mod_id + '">Dozent: ' + content[i][j][8] + '</p></div></div></button></div>');
inner_content = inner_content + string;
if (mod_id == "M07_WPP")
{
blocked.push(mod_id);
catalog_array.push(content[i][j][11]);
}
} else
{
var string = '<div id="' + mod_id + '" class="row modules_border class_click_modules_in_semester margin-top">' +
'<button id="' + mod_id + '" class="btn btn-block"><div id="' + mod_id + '" class="row text-left">' +
'<div id="' + mod_id + '" class="col fett">' +
'<p>' + mod_id + '</p></div>' +
'<div id="' + mod_id + '" class="col text-right">' +
'<p id="' + mod_id + '">ECTS: ' + content[i][j][9] + '</p></div>' + '</div>' +
'<div id="' + mod_id + '" class="row normal text-left">' +
'<div id="' + mod_id + '" class="col">' +
'<p id="' + mod_id + '">Dozent: ' + content[i][j][8] + '</p></div></div></button></div>';
inner_content = inner_content + string;
blocked.push(mod_id);
catalog_array.push(content[i][j][11]);
}
}
sem_content = inner_content;
content_html[sem_id] = $(sem_content);
}
$("#ects_text").text("Master ECTS: ");
$("#ects_punkte").text(master_ects);
$("#regeln").show();
} | 45.063492 | 624 | 0.462487 |
4337a896ab94c9550dbab89dd910baa4771046c9 | 431 | js | JavaScript | dashboard/static/dist/js/app/app.min.js | robertsimmons514/isthislegit | aa8f2b6cb2ac3de2b0fe03bb93dbceccc4c1f495 | [
"BSD-3-Clause"
] | 282 | 2017-07-01T03:47:54.000Z | 2022-02-25T00:58:40.000Z | dashboard/static/dist/js/app/app.min.js | robertsimmons514/isthislegit | aa8f2b6cb2ac3de2b0fe03bb93dbceccc4c1f495 | [
"BSD-3-Clause"
] | 46 | 2017-07-26T22:54:13.000Z | 2022-02-14T21:39:52.000Z | dashboard/static/dist/js/app/app.min.js | robertsimmons514/isthislegit | aa8f2b6cb2ac3de2b0fe03bb93dbceccc4c1f495 | [
"BSD-3-Clause"
] | 53 | 2017-07-22T15:04:16.000Z | 2022-03-16T03:36:28.000Z | "use strict";$.fn.serializeObject=function(){var t={},e=this.serializeArray();return $.each(e,function(){void 0!==t[this.name]?(t[this.name].push||(t[this.name]=[t[this.name]]),t[this.name].push(this.value||"")):t[this.name]=this.value||""}),t},$.fn.dataTable.moment("MMMM Do YYYY, h:mm:ss a"),$.fn.select2.defaults.set("theme","bootstrap"),String.prototype.capitalize=function(){return this.charAt(0).toUpperCase()+this.slice(1)}; | 431 | 431 | 0.696056 |
4338a1014c4c86e64c50f0c9e948ceb0ce84050f | 3,432 | js | JavaScript | components/edit-collective/UpdateBankDetailsForm.js | Betree/opencollective-frontend | 7666fd5f2e6665b9c7c22e518a90ab8ecf4822d6 | [
"MIT"
] | null | null | null | components/edit-collective/UpdateBankDetailsForm.js | Betree/opencollective-frontend | 7666fd5f2e6665b9c7c22e518a90ab8ecf4822d6 | [
"MIT"
] | 2 | 2019-06-20T18:01:54.000Z | 2019-08-05T16:31:15.000Z | components/edit-collective/UpdateBankDetailsForm.js | Betree/opencollective-frontend | 7666fd5f2e6665b9c7c22e518a90ab8ecf4822d6 | [
"MIT"
] | null | null | null | import React from 'react';
import PropTypes from 'prop-types';
import { get } from 'lodash';
import { defineMessages, injectIntl } from 'react-intl';
import styled from 'styled-components';
import Container from '../Container';
import { Box, Flex } from '../Grid';
import StyledTextarea from '../StyledTextarea';
import { H4, P, Span } from '../Text';
const List = styled.ul`
margin: 0;
padding: 0;
position: relative;
list-style: none;
`;
class UpdateBankDetailsForm extends React.Component {
static propTypes = {
intl: PropTypes.object.isRequired,
profileType: PropTypes.string, // USER or ORGANIZATION
error: PropTypes.string,
value: PropTypes.string,
onChange: PropTypes.func,
};
static defaultProps = {};
constructor(props) {
super(props);
this.state = { form: {} };
this.onChange = this.onChange.bind(this);
this.messages = defineMessages({
'bankaccount.instructions.label': {
id: 'paymentMethods.manual.instructions',
defaultMessage: 'Bank transfer instructions',
},
'bankaccount.instructions.default': {
id: 'paymentMethods.manual.instructions.default',
defaultMessage: `Please make a bank transfer as follows:
<code>
Amount: {amount}
Reference/Communication: {OrderId}
IBAN/Account Number: BE61310126985517
BIC: TRIOBEBB
Bank name: Triodos
</code>
Please note that it will take a few days to process your payment.`,
},
});
}
onChange(field, value) {
const newState = this.state;
newState.form[field] = value;
this.setState(newState);
this.props.onChange(newState.form);
}
render() {
const { intl, value, error } = this.props;
return (
<Flex flexDirection="column">
<Container as="fieldset" border="none" width={1} py={3}>
<Flex flexDirection="row">
<Box mb={3}>
<StyledTextarea
label={intl.formatMessage(this.messages['bankaccount.instructions.label'])}
htmlFor="instructions"
width={500}
height={300}
onChange={e => this.onChange('instructions', e.target.value)}
defaultValue={
get(value, 'instructions') || intl.formatMessage(this.messages['bankaccount.instructions.default'])
}
/>
</Box>
<Container fontSize="1.4rem" ml={3}>
<H4 fontSize="1.4rem">Variables:</H4>
<P>Make sure you are using the following variables in the instructions.</P>
<List>
<li>
<code>{amount}</code>: total amount of the order
</li>
<li>
<code>{collective}</code>: slug of the collective for which the donation is earmarked
</li>
<li>
<code>{OrderId}</code>: unique id of the order to help you mark it as paid when you receive
the money
</li>
</List>
</Container>
</Flex>
</Container>
{error && (
<Span display="block" color="red.500" pt={2} fontSize="Tiny">
{error}
</Span>
)}
</Flex>
);
}
}
UpdateBankDetailsForm.propTypes = {
intl: PropTypes.object,
};
export default injectIntl(UpdateBankDetailsForm);
| 29.586207 | 119 | 0.579545 |
43392aaaf80b149c463ee2521b7cad62ba4e090e | 6,856 | js | JavaScript | src/views/auth/Login.js | badlee/stream-io-admin | 288516e80acd80dbafb0040ec5800a63eeacf6ea | [
"MIT"
] | null | null | null | src/views/auth/Login.js | badlee/stream-io-admin | 288516e80acd80dbafb0040ec5800a63eeacf6ea | [
"MIT"
] | null | null | null | src/views/auth/Login.js | badlee/stream-io-admin | 288516e80acd80dbafb0040ec5800a63eeacf6ea | [
"MIT"
] | null | null | null | import http, { feedClient } from "../../http";
import React, { useCallback, useEffect, useState } from "react";
import { useAuth } from "auth";
import { store } from 'react-notifications-component';
import { useHistory, useParams } from "react-router";
export default function Login() {
const auth = useAuth();
const params = useParams()
const history = useHistory()
const [remeberValue] = useState("yes");
const [login, _login] = useState("");
const [pwd, _pwd] = useState("");
const [remember, _remember] = useState("yes");
const [initate, setInitate] = useState(false);
const [initalData, setInitalData] = useState(undefined);
const signIn = useCallback(async ()=>{
try{
await auth.login(login, pwd, remember === remeberValue)
history.push(params.from || "/")
}catch(e){
store.addNotification({
title: 'Sign In Error',
message: e.message || e,
type: "danger",
insert: "top",
container: "bottom-right",
animationIn: ["animate__animated", "animate__fadeIn"],
animationOut: ["animate__animated", "animate__fadeOut"],
dismiss: {
duration: 5000,
onScreen: true
}
});
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[login, pwd])
useEffect(()=>{
http.get('get-inital-data').then(async res => {
try {
if (res && typeof res === 'object') {
setInitalData(res.data)
setInitate(res.data.done === false) // show dialog
}
} catch (e) {
//
setInitate(false)
}
})
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[])
return (
<>
<div className="container mx-auto px-4 h-full">
<div className="flex content-center items-center justify-center h-full">
<div className="w-full lg:w-4/12 px-4">
<div className="relative flex flex-col min-w-0 break-words w-full mb-6 shadow-lg rounded-lg bg-blueGray-200 border-0">
{initate && initalData && initalData.done === false && <div className="rounded-t mb-0 px-6 py-6" >
<div className="text-center mb-3">
<h6 className="text-blueGray-500 text-sm font-bold">
Default user
</h6>
</div>
<div className="btn-wrapper text-center">
<button
onClick={()=>_login(initalData.users.root.login)}
className="bg-white active:bg-blueGray-50 text-blueGray-700 font-normal px-4 py-2 rounded outline-none focus:outline-none mr-2 mb-1 shadow hover:shadow-md inline-flex items-center font-bold text-xs ease-linear transition-all duration-150"
type="button"
>
<i className="fas fa-user text-emerald-500 w-5 mr-1"></i>
{ initalData.users.root.login }
</button>
<button
onClick={()=>_pwd(initalData.users.root.pwd)}
className="bg-white active:bg-blueGray-50 text-blueGray-700 font-normal px-4 py-2 rounded outline-none focus:outline-none mr-1 mb-1 shadow hover:shadow-md inline-flex items-center font-bold text-xs ease-linear transition-all duration-150"
type="button"
>
<i className="fas fa-key text-emerald-500 w-5 mr-1"></i>
{ initalData.users.root.pwd }
</button>
</div>
<hr className="mt-6 border-b-1 border-blueGray-300" />
</div>}
<div className="flex-auto px-4 lg:px-10 py-10 pt-0">
<div className="text-blueGray-500 text-center mb-3 font-bold">
Sign in
</div>
<form>
<div className="relative w-full mb-3">
<label
className="block uppercase text-blueGray-600 text-xs font-bold mb-2"
htmlFor="grid-password"
>
Login - {login}
</label>
<input
value={login}
onChange={event=>_login(event.target.value)}
type="text"
className="border-0 px-3 py-3 placeholder-blueGray-300 text-blueGray-600 bg-white rounded text-sm shadow focus:outline-none focus:ring w-full ease-linear transition-all duration-150"
placeholder="Login"
/>
</div>
<div className="relative w-full mb-3">
<label
className="block uppercase text-blueGray-600 text-xs font-bold mb-2"
htmlFor="grid-password"
>
Password - {pwd}
</label>
<input
value={pwd}
onChange={event=>_pwd(event.target.value)}
type="password"
className="border-0 px-3 py-3 placeholder-blueGray-300 text-blueGray-600 bg-white rounded text-sm shadow focus:outline-none focus:ring w-full ease-linear transition-all duration-150"
placeholder="Password"
/>
</div>
<div>
<label className="inline-flex items-center cursor-pointer">
<input
checked={remember === remeberValue}
onChange={event=>_remember(event.target.checked ? event.target.value : "")}
id="customCheckLogin"
type="checkbox"
value={remeberValue}
className="form-checkbox border-0 rounded text-blueGray-700 ml-1 w-5 h-5 ease-linear transition-all duration-150"
/>
<span className="ml-2 text-sm font-semibold text-blueGray-600">
Remember me
</span>
</label>
</div>
<div className="text-center mt-6">
<button
onClick={signIn}
disabled={login === "" || pwd === ""}
className="bg-blueGray-800 text-white active:bg-blueGray-600 text-sm font-bold uppercase px-6 py-3 rounded shadow hover:shadow-lg outline-none focus:outline-none mr-1 mb-1 w-full ease-linear transition-all duration-150"
type="button"
>
Sign In
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</>
);
}
| 43.948718 | 258 | 0.508168 |
4339b5df3424de4b63205acfbc80c7fec65a394b | 1,748 | js | JavaScript | modules/ajax/script.js | vrinceanuv/devanilla | 2cbc4b88ea347cff82c1e100bf599c1e5c60a59a | [
"MIT"
] | null | null | null | modules/ajax/script.js | vrinceanuv/devanilla | 2cbc4b88ea347cff82c1e100bf599c1e5c60a59a | [
"MIT"
] | null | null | null | modules/ajax/script.js | vrinceanuv/devanilla | 2cbc4b88ea347cff82c1e100bf599c1e5c60a59a | [
"MIT"
] | null | null | null | /**
* Does an ajax get
* @param {string} url - The url for the ajax call
* @param {function} callback - The callback after the call is done
*/
export const get = (url) => {
/* eslint-disable */
return new Promise(function(resolve, reject) {
const request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = function() {
if (request.status === 200 && request.status < 400) {
resolve(request.response);
} else {
reject(Error(request.statusText));
}
};
request.onerror = function() {
reject(Error('Network Error'));
};
request.send();
});
/* eslint-enable */
};
/**
* Does an ajax post
* @param {string} url - The url for the ajax call
* @param {function} callback - The callback after the call is done
* @param {object} data - The data that we send
* @param {string} headers - Optional headers that we send
*/
export const post = (url, data, headers) => {
/* eslint-disable */
const dataToSend = data ? JSON.stringify(data) : undefined;
return new Promise(function(resolve, reject) {
const request = new XMLHttpRequest();
if (!dataToSend) {
reject(Error('You want to make a POST request with no data. Add data as the second parameter of the request'));
}
request.open('POST', url, true);
if (headers) {
request.setRequestHeader(headers);
}
request.onload = function() {
if (request.status === 200 && request.status < 400) {
resolve(request.response);
} else {
reject(Error(request.statusText));
}
};
request.onerror = function() {
reject(Error('Network Error'));
};
request.send(dataToSend);
});
/* eslint-enable */
};
| 24.971429 | 117 | 0.607551 |
433a1f80c1a7f11e1e4f2609ba3f8f4b58282ba3 | 219 | js | JavaScript | helpers/index.js | methe-1/User-microservice | 8de090b9e8bfe24df6966f0c4dc964084de509c3 | [
"MIT"
] | null | null | null | helpers/index.js | methe-1/User-microservice | 8de090b9e8bfe24df6966f0c4dc964084de509c3 | [
"MIT"
] | null | null | null | helpers/index.js | methe-1/User-microservice | 8de090b9e8bfe24df6966f0c4dc964084de509c3 | [
"MIT"
] | null | null | null | import RequireParam from './RequireParam'
import httpError from './httpError'
import httpResponse from './httpResponse'
import empty from './empty'
export {
RequireParam,
httpError,
httpResponse,
empty
} | 21.9 | 41 | 0.730594 |
433a9b116932c8f4530900bf1cfffc7c7e86c20d | 5,677 | js | JavaScript | shared/js/contacts/import/utilities/overlay.js | pivanov/gaia | 5a1c36d5523c50828bb39b10721fcfd42754ec9b | [
"Apache-2.0"
] | null | null | null | shared/js/contacts/import/utilities/overlay.js | pivanov/gaia | 5a1c36d5523c50828bb39b10721fcfd42754ec9b | [
"Apache-2.0"
] | null | null | null | shared/js/contacts/import/utilities/overlay.js | pivanov/gaia | 5a1c36d5523c50828bb39b10721fcfd42754ec9b | [
"Apache-2.0"
] | null | null | null | /* global _ */
'use strict';
var utils = window.utils || {};
(function() {
utils.overlay = {};
var overlay = document.querySelector('#loading-overlay'),
statusContainer = overlay.querySelector('p[role="status"]'),
progressActivity = document.querySelector('#progress-activity'),
progressTitle = document.querySelector('#progress-title'),
progressElement = document.querySelector('#progress-element'),
progressMsg = document.querySelector('#progress-msg'),
menu = document.querySelector('#loading-overlay menu'),
cancelButton = document.querySelector('#cancel-overlay');
// Constructor for the progress element
function ProgressBar(pMsgId, pClass) {
var counter = 0;
var total = 0;
var progressTextId = pMsgId || 'genericProgress';
var clazz = pClass;
progressElement.setAttribute('value', 0);
function showMessage() {
progressMsg.textContent = _(progressTextId, {
current: counter,
total: total
});
}
/**
* Updates progress bar and message. It takes an optional `value` parameter
* to overwrite the internal counter with this value.
* @param {Number} value Overrides internal counter.
*/
this.update = function(value) {
if (value && value <= total && value >= counter) {
counter = value;
progressElement.setAttribute('value', (counter * 100) / total);
} else {
progressElement.setAttribute('value', (++counter * 100) / total);
}
showMessage();
};
this.setTotal = function(ptotal) {
total = ptotal;
};
this.setClass = function(clazzName) {
setClass(clazzName);
clazz = clazzName;
// To refresh the message according to the new clazzName
if (clazzName === 'activityBar' || clazzName === 'spinner') {
progressMsg.textContent = null;
}
};
this.setHeaderMsg = function(headerMsg) {
progressTitle.textContent = headerMsg;
};
} // ProgressBar
utils.overlay.isAnimationPlaying = false;
utils.overlay.isShown = false;
utils.overlay._show = function _show(message, progressClass, textId) {
progressActivity.classList.remove('hide');
progressTitle.textContent = message;
progressMsg.textContent = null;
if (utils.overlay.isShown) {
return;
}
overlay.classList.remove('hide');
overlay.classList.remove('fade-out');
overlay.classList.add('fade-in');
utils.overlay.isAnimationPlaying = true;
overlay.addEventListener('animationend', function ov_onFadeIn(ev) {
utils.overlay.isAnimationPlaying = false;
overlay.removeEventListener('animationend', ov_onFadeIn);
overlay.classList.remove('no-opacity');
utils.overlay.isShown = true;
});
};
utils.overlay.show = function show(message, progressClass, textId) {
var out;
// In the case of an spinner this object will not be really used
out = new ProgressBar(textId, progressClass);
setClass(progressClass);
utils.overlay.hideMenu(); // By default
if (!utils.overlay.isAnimationPlaying) {
utils.overlay._show(message, progressClass, textId);
return out;
}
overlay.addEventListener('animationend',
function ov_showWhenFinished(ev) {
overlay.removeEventListener('animationend', ov_showWhenFinished);
utils.overlay._show(message, progressClass, textId);
}
);
return out;
};
utils.overlay.showMenu = function showMenu() {
menu.classList.add('showed');
};
utils.overlay.hideMenu = function hideMenu() {
menu.classList.remove('showed');
};
Object.defineProperty(utils.overlay, 'oncancel', {
set: function(cancelCb) {
if (typeof cancelCb === 'function') {
cancelButton.disabled = false;
cancelButton.onclick = function on_cancel(e) {
delete cancelButton.onclick;
cancelCb();
return false;
};
}
}
});
function setAsProgress() {
statusContainer.classList.remove('loading-icon');
progressElement.setAttribute('max', '100');
progressElement.setAttribute('value', '0');
}
function setClass(clazzName) {
switch (clazzName) {
case 'spinner':
progressElement.classList.remove('pack-activity');
statusContainer.classList.add('loading-icon');
progressElement.removeAttribute('max');
progressElement.removeAttribute('value');
break;
case 'activityBar':
case 'progressActivity':
progressElement.classList.add('pack-activity');
setAsProgress();
break;
case 'progressBar':
progressElement.classList.remove('pack-activity');
setAsProgress();
break;
}
}
utils.overlay._hide = function ov__hide() {
if (!utils.overlay.isShown) {
return;
}
overlay.classList.remove('fade-in');
overlay.classList.add('fade-out');
utils.overlay.isAnimationPlaying = true;
overlay.addEventListener('animationend', function ov_onFadeOut(ev) {
utils.overlay.isAnimationPlaying = false;
overlay.removeEventListener('animationend', ov_onFadeOut);
progressActivity.classList.add('hide');
overlay.classList.add('no-opacity');
overlay.classList.add('hide');
utils.overlay.isShown = false;
});
};
utils.overlay.hide = function ov_hide() {
if (!utils.overlay.isAnimationPlaying) {
utils.overlay._hide();
return;
}
overlay.addEventListener('animationend',
function ov_hideWhenFinished(ev) {
overlay.removeEventListener('animationend', ov_hideWhenFinished);
utils.overlay._hide();
}
);
};
})();
| 31.192308 | 79 | 0.651048 |
433b5b37b8f77d57b9d46cdfebe2ca590168d99c | 7,281 | js | JavaScript | droidlet/dashboard/web/src/components/Navigator.js | ali-senguel/fairo | 1ec5d8ecbdfc782de63a92aad9bf8534110ce762 | [
"MIT"
] | 669 | 2020-11-21T01:20:20.000Z | 2021-09-13T13:25:16.000Z | droidlet/dashboard/web/src/components/Navigator.js | ali-senguel/fairo | 1ec5d8ecbdfc782de63a92aad9bf8534110ce762 | [
"MIT"
] | 324 | 2020-12-07T18:20:34.000Z | 2021-09-14T17:17:18.000Z | droidlet/dashboard/web/src/components/Navigator.js | ali-senguel/fairo | 1ec5d8ecbdfc782de63a92aad9bf8534110ce762 | [
"MIT"
] | 56 | 2021-01-04T19:57:40.000Z | 2021-09-13T21:20:08.000Z | /*
Copyright (c) Facebook, Inc. and its affiliates.
*/
import React from "react";
import stateManager from "../StateManager";
import "status-indicator/styles.css";
import Slider from "rc-slider";
import "rc-slider/assets/index.css";
let slider_style = { width: 600, margin: 50 };
const labelStyle = { minWidth: "60px", display: "inline-block" };
/**
* Currently just a keybinding wrapper that hooks
* into the state manager and sends events upstream.
* Later, has to be expanded to visually acknowledge
* the keys pressed, along with their successful receipt by
* the backend.
*/
class Navigator extends React.Component {
constructor(props) {
super(props);
this.initialState = {
move: 0.3,
yaw: 0.01,
velocity: 0.1,
data_logging_time: 30,
keyboard_enabled: false,
};
this.state = this.initialState;
this.handleSubmit = this.handleSubmit.bind(this);
this.onYawChange = this.onYawChange.bind(this);
this.onDataLoggingTimeChange = this.onDataLoggingTimeChange.bind(this);
this.onMoveChange = this.onMoveChange.bind(this);
this.onVelocityChange = this.onVelocityChange.bind(this);
this.navRef = React.createRef();
this.keyCheckRef = React.createRef();
this.handleClick = this.handleClick.bind(this);
this.logData = this.logData.bind(this);
this.stopRobot = this.stopRobot.bind(this);
this.unstopRobot = this.unstopRobot.bind(this);
this.keyboardToggle = this.keyboardToggle.bind(this);
this.addKeyListener = this.addKeyListener.bind(this);
this.removeKeyListener = this.removeKeyListener.bind(this);
}
keyboardToggle = () => {
if (this.keyCheckRef.current.checked == true) {
this.addKeyListener();
} else {
this.removeKeyListener();
}
this.setState({ keyboard_enabled: this.keyCheckRef.current.checked });
};
handleSubmit(event) {
stateManager.setUrl(this.state.url);
event.preventDefault();
}
logData(event) {
stateManager.socket.emit("logData", this.state.data_logging_time);
console.log("logData", this.state.data_logging_time);
}
stopRobot(event) {
stateManager.socket.emit("stopRobot");
console.log("Robot Stopped");
}
unstopRobot(event) {
stateManager.socket.emit("unstopRobot");
console.log("Robot UnStopped");
}
addKeyListener() {
var map = {};
this.onkey = function (e) {
map[e.keyCode] = true;
};
document.addEventListener("keyup", this.onkey);
let interval = 33.33;
// keyHandler gets called every interval milliseconds
this.intervalHandle = setInterval(stateManager.keyHandler, interval, map);
}
removeKeyListener() {
document.removeEventListener("keyup", this.onkey);
clearInterval(this.intervalHandle);
}
componentDidMount() {
if (stateManager) stateManager.connect(this);
}
onDataLoggingTimeChange(value) {
this.setState({ data_logging_time: value });
}
onYawChange(value) {
this.setState({ yaw: value });
}
onMoveChange(value) {
this.setState({ move: value });
}
onVelocityChange(value) {
this.setState({ velocity: value });
}
handleClick(event) {
const id = event.target.id;
if (id === "key_up") {
stateManager.keyHandler({ 38: true });
} else if (id === "key_down") {
stateManager.keyHandler({ 40: true });
} else if (id === "key_left") {
stateManager.keyHandler({ 37: true });
} else if (id === "key_right") {
stateManager.keyHandler({ 39: true });
} else if (id === "pan_left") {
stateManager.keyHandler({ 49: true });
} else if (id === "pan_right") {
stateManager.keyHandler({ 50: true });
} else if (id === "tilt_up") {
stateManager.keyHandler({ 51: true });
} else if (id === "tilt_down") {
stateManager.keyHandler({ 52: true });
}
}
// <button
// id="stop_robot"
// style={{ fontSize: 48 + "px" }}
// onClick={this.stopRobot}
// >
// <strike>STOP ROBOT</strike>
// </button>
// <button id="unstop_robot" onClick={this.unstopRobot}>
// Clear Runstop
// </button>
render() {
return (
<div ref={this.navRef}>
<br />
<br />
<div>
<label> Base </label>
<button id="key_up" onClick={this.handleClick}>
Up
</button>
</div>
<div>
<button id="key_left" onClick={this.handleClick}>
Left
</button>
<button id="key_down" onClick={this.handleClick}>
Down
</button>
<button id="key_right" onClick={this.handleClick}>
Right
</button>
</div>
<br />
<br />
<div>
<label> Camera </label>
<button id="tilt_up" onClick={this.handleClick}>
Up
</button>
</div>
<div>
<button id="pan_left" onClick={this.handleClick}>
Left
</button>
<button id="tilt_down" onClick={this.handleClick}>
Down
</button>
<button id="pan_right" onClick={this.handleClick}>
Right
</button>
</div>
<br />
<input
type="checkbox"
defaultChecked={this.state.keyboard_enabled}
ref={this.keyCheckRef}
onChange={this.keyboardToggle}
/>
<label>
{" "}
Enable Keyboard control (Use the arrow keys to move the robot, keys{" "}
{(1, 2)} and {(3, 4)} to move camera){" "}
</label>
<div style={slider_style}>
<label style={labelStyle}>Rotation (radians): </label>
<span>{this.state.yaw}</span>
<br />
<br />
<Slider
value={this.state.yaw}
min={0}
max={6.28}
step={0.01}
onChange={this.onYawChange}
/>
<br />
<label style={labelStyle}>Move Distance (metres): </label>
<span>{this.state.move}</span>
<br />
<br />
<Slider
value={this.state.move}
min={0}
max={10}
step={0.1}
onChange={this.onMoveChange}
/>
</div>
<div style={slider_style}>
<label style={labelStyle}>Velocity: </label>
<span>{this.state.velocity}</span>
<br />
<br />
<Slider
value={this.state.velocity}
min={0}
max={1}
step={0.05}
onChange={this.onVelocityChange}
/>
</div>
<div>
<div style={slider_style}>
<label style={labelStyle}>
Data Logging Time (seconds):
</label>
<span>{this.state.data_logging_time}</span>
<br />
<br />
<Slider
value={this.state.data_logging_time}
min={0}
max={300}
step={1}
onChange={this.onDataLoggingTimeChange}
/>
</div>
<button id="log_data" onClick={this.logData}>
Log Data
</button>
</div>
</div>
);
}
}
export default Navigator;
| 27.684411 | 82 | 0.558302 |
433ba7e5485efc32f6826fd6b9dd08deaeb3228a | 22,991 | js | JavaScript | testing/tests/DevExpress.ui.widgets.editors/calendarViews.tests.js | natashaash/DevExtreme | 361864653fc9e89391d09fb6c57c2c59267a2b85 | [
"Apache-2.0"
] | 1 | 2019-12-26T17:49:30.000Z | 2019-12-26T17:49:30.000Z | testing/tests/DevExpress.ui.widgets.editors/calendarViews.tests.js | KorzhovAlexander/DevExtreme | c4f93f1eddf137c92e840c986b81e3de42e94326 | [
"Apache-2.0"
] | null | null | null | testing/tests/DevExpress.ui.widgets.editors/calendarViews.tests.js | KorzhovAlexander/DevExtreme | c4f93f1eddf137c92e840c986b81e3de42e94326 | [
"Apache-2.0"
] | null | null | null | var $ = require('jquery'),
noop = require('core/utils/common').noop,
dateUtils = require('core/utils/date'),
BaseView = require('ui/calendar/ui.calendar.base_view'),
Views = require('ui/calendar/ui.calendar.views'),
pointerMock = require('../../helpers/pointerMock.js'),
fx = require('animation/fx'),
dateSerialization = require('core/utils/date_serialization'),
dateLocalization = require('localization/date');
require('common.css!');
require('ui/calendar');
var CALENDAR_EMPTY_CELL_CLASS = 'dx-calendar-empty-cell',
CALENDAR_CELL_CLASS = 'dx-calendar-cell',
CALENDAR_SELECTED_DATE_CLASS = 'dx-calendar-selected-date',
CALENDAR_CONTOURED_DATE_CLASS = 'dx-calendar-contoured-date',
UP_ARROW_KEY_CODE = 'ArrowUp',
DOWN_ARROW_KEY_CODE = 'ArrowDown';
var getShortDate = function(date) {
return dateSerialization.serializeDate(date, dateUtils.getShortDateFormat());
};
function triggerKeydown(key, $element) {
var e = $.Event('keydown', { key: key });
$element.find('table').trigger(e);
}
var FakeView = BaseView.inherit({
_isTodayCell: noop,
_isDateOutOfRange: function() {
return false;
},
_isOtherView: noop,
_getCellText: noop,
_getFirstCellData: noop,
_getNextCellData: noop,
_getCellByDate: noop,
isBoundary: noop,
_renderValue: noop
});
QUnit.module('Basics');
QUnit.test('onCellClick action should be fired on cell click', function(assert) {
var $element = $('<div>').appendTo('body');
try {
var spy = sinon.spy();
new FakeView($element, {
onCellClick: spy
});
$element.find('td').eq(4).trigger('dxclick');
assert.ok(spy.calledOnce, 'onCellClick fired once');
} finally {
$element.remove();
}
});
QUnit.test('no contouredDate is set by default', function(assert) {
var $element = $('<div>').appendTo('body');
try {
var view = new FakeView($element, {});
assert.equal(view.option('contouredDate'), null, 'contoured Date is null');
} finally {
$element.remove();
}
});
QUnit.test('onCellClick should not be fired on out of range cells', function(assert) {
var $element = $('<div>').appendTo('body');
try {
var spy = sinon.spy();
new FakeView($element, {
onCellClick: spy
});
$element.find('.' + CALENDAR_CELL_CLASS).addClass(CALENDAR_EMPTY_CELL_CLASS);
$element.find('.' + CALENDAR_CELL_CLASS).eq(5).trigger('dxclick');
assert.equal(spy.callCount, 0, 'onCellClick was not called');
} finally {
$element.remove();
}
});
QUnit.test('Calendar should set first day by firstDayOfWeek option if it is setted and this is different in localization', function(assert) {
var $element = $('<div>').appendTo('body'),
spy = sinon.spy(dateLocalization, 'firstDayOfWeekIndex');
this.view = new Views['month']($element, {
date: new Date(2017, 11, 11),
firstDayOfWeek: 0
});
assert.notOk(spy.called, 'firstDayOfWeekIndex wasn\'t called');
});
QUnit.module('MonthView', {
beforeEach: function() {
fx.off = true;
this.$element = $('<div>').appendTo('body');
this.view = new Views['month'](this.$element, {
date: new Date(2013, 9, 16),
firstDayOfWeek: 1,
focusStateEnabled: true
});
},
reinit: function(options) {
this.$element.remove();
this.$element = $('<div>').appendTo('body');
this.view = new Views['month'](this.$element, options);
},
afterEach: function() {
this.$element.remove();
fx.off = false;
}
});
QUnit.test('getNavigatorCaption must return a proper caption', function(assert) {
assert.equal(this.view.getNavigatorCaption(), 'October 2013', 'caption is correct');
});
QUnit.test('getNavigatorCaption must return a proper caption in RTL mode', function(assert) {
this.view.option('rtl', true);
assert.equal(this.view.getNavigatorCaption(), 'October 2013', 'caption is correct');
});
QUnit.test('change value option must add a CSS class to a cell', function(assert) {
var secondDate = new Date(2013, 9, 1),
secondDateCell = this.$element.find('table').find('td').eq(1);
this.view.option('value', secondDate);
assert.ok(secondDateCell.hasClass(CALENDAR_SELECTED_DATE_CLASS));
});
QUnit.test('it should be possible to specify contouredDate via the constructor', function(assert) {
var date = new Date(2013, 9, 1);
this.reinit({
date: new Date(2013, 9, 16),
contouredDate: date
});
assert.strictEqual(this.view.option('contouredDate'), date);
});
QUnit.test('changing contouredDate must add CALENDAR_CONTOURED_DATE_CLASS class to a cell', function(assert) {
var date = new Date(2013, 9, 1),
dateCell = this.$element.find('table').find('td').eq(1);
this.view.option('contouredDate', date);
assert.ok(dateCell.hasClass(CALENDAR_CONTOURED_DATE_CLASS));
});
QUnit.test('changing contouredDate must remove CALENDAR_CONTOURED_DATE_CLASS class from the old cell', function(assert) {
var date = new Date(2013, 9, 1),
newDate = new Date(2013, 9, 2),
dateCell = this.$element.find('table').find('td').eq(1);
this.view.option('contouredDate', date);
assert.ok(dateCell.hasClass(CALENDAR_CONTOURED_DATE_CLASS));
this.view.option('contouredDate', newDate);
assert.ok(!dateCell.hasClass(CALENDAR_CONTOURED_DATE_CLASS));
});
QUnit.test('if option.disabled is set in a constructor, cells should not be clickable', function(assert) {
assert.expect(0);
this.reinit({
disabled: true
});
this.view.cellClickHandler = function() { assert.ok(false); };
var date = this.$element.find('table').find('td')[0];
pointerMock(date).click();
});
QUnit.module('YearView', {
beforeEach: function() {
fx.off = true;
this.$element = $('<div>').appendTo('body');
this.view = new Views['year'](this.$element, {
date: new Date(2013, 9, 16),
firstDayOfWeek: 1,
focusStateEnabled: true
});
},
reinit: function(options) {
this.$element.remove();
this.$element = $('<div>').appendTo('body');
this.view = new Views['year'](this.$element, options);
},
afterEach: function() {
this.$element.remove();
fx.off = false;
}
});
QUnit.test('getNavigatorCaption must return a proper caption', function(assert) {
assert.ok(this.view.getNavigatorCaption().toString() === '2013');
});
QUnit.test('change value option must add a CSS class to a cell', function(assert) {
var secondDate = new Date(2013, 1, 1),
secondDateCell = this.$element.find('table').find('td').eq(1);
this.view.option('value', secondDate);
assert.ok(secondDateCell.hasClass(CALENDAR_SELECTED_DATE_CLASS));
});
QUnit.test('changing contouredDate must add CALENDAR_CONTOURED_DATE_CLASS class to a cell', function(assert) {
var date = new Date(2013, 4, 1),
dateCell = this.$element.find('table').find('td').eq(4);
this.view.option('contouredDate', date);
assert.ok(dateCell.hasClass(CALENDAR_CONTOURED_DATE_CLASS));
});
QUnit.test('changing contouredDate must remove CALENDAR_CONTOURED_DATE_CLASS class from the old cell', function(assert) {
var date = new Date(2013, 9, 1),
newDate = new Date(2013, 4, 1),
dateCell = this.$element.find('table').find('td').eq(9);
this.view.option('contouredDate', date);
assert.ok(dateCell.hasClass(CALENDAR_CONTOURED_DATE_CLASS));
this.view.option('contouredDate', newDate);
assert.ok(!dateCell.hasClass(CALENDAR_CONTOURED_DATE_CLASS));
});
QUnit.module('DecadeView', {
beforeEach: function() {
fx.off = true;
this.$element = $('<div>').appendTo('body');
this.view = new Views['decade'](this.$element, {
date: new Date(2013, 9, 16),
value: new Date(2013, 9, 16),
firstDayOfWeek: 1,
focusStateEnabled: true
});
},
reinit: function(options) {
this.$element.remove();
this.$element = $('<div>').appendTo('body');
this.view = new Views['decade'](this.$element, options);
},
afterEach: function() {
this.$element.remove();
fx.off = false;
}
});
QUnit.test('getNavigatorCaption must return a proper caption', function(assert) {
assert.ok(this.view.getNavigatorCaption() === '2010-2019');
});
QUnit.test('change value option must add a CSS class to a cell', function(assert) {
var secondDate = new Date(2010, 1, 1),
secondDateCell = this.$element.find('table').find('td').eq(1);
this.view.option('value', secondDate);
assert.ok(secondDateCell.hasClass(CALENDAR_SELECTED_DATE_CLASS));
});
QUnit.test('changing contouredDate must add CALENDAR_CONTOURED_DATE_CLASS class to a cell', function(assert) {
var date = new Date(2012, 1, 1),
dateCell = this.$element.find('table').find('td').eq(3);
this.view.option('contouredDate', date);
assert.ok(dateCell.hasClass(CALENDAR_CONTOURED_DATE_CLASS));
});
QUnit.test('changing contouredDate must remove CALENDAR_CONTOURED_DATE_CLASS class from the old cell', function(assert) {
var date = new Date(2012, 1, 1),
newDate = new Date(2016, 1, 1),
dateCell = this.$element.find('table').find('td').eq(3);
this.view.option('contouredDate', date);
assert.ok(dateCell.hasClass(CALENDAR_CONTOURED_DATE_CLASS));
this.view.option('contouredDate', newDate);
assert.ok(!dateCell.hasClass(CALENDAR_CONTOURED_DATE_CLASS));
});
QUnit.test('data-value after render for cells in decade view', function(assert) {
var dateCells = this.$element.find('table').find('td'),
startYear = 2009;
$.each(dateCells, function(_, dateCell) {
var shortDate = getShortDate(new Date(startYear, 0, 1));
assert.equal(shortDate, $(dateCell).data().value, 'data-value has a current value');
startYear++;
});
});
QUnit.module('CenturyView', {
beforeEach: function() {
fx.off = true;
this.$element = $('<div>').appendTo('body');
this.view = new Views['century'](this.$element, {
date: new Date(2013, 9, 16),
value: new Date(2013, 9, 16),
firstDayOfWeek: 1,
focusStateEnabled: true
});
},
reinit: function(options) {
this.$element.remove();
this.$element = $('<div>').appendTo('body');
this.view = new Views['century'](this.$element, options);
},
afterEach: function() {
this.$element.remove();
fx.off = false;
}
});
QUnit.test('getNavigatorCaption must return a proper caption', function(assert) {
assert.ok(this.view.getNavigatorCaption() === '2000-2099');
});
QUnit.test('data-value after render for cells in century view', function(assert) {
var dateCells = this.$element.find('table').find('td'),
startYear = 1990;
$.each(dateCells, function(_, dateCell) {
var shortDate = getShortDate(new Date(startYear, 0, 1));
assert.equal(shortDate, $(dateCell).data().value, 'data-value has a current value');
startYear += 10;
});
});
QUnit.test('changing contouredDate must add CALENDAR_CONTOURED_DATE_CLASS class to a cell', function(assert) {
var date = new Date(2030, 1, 1),
dateCell = this.$element.find('table').find('td').eq(4);
this.view.option('contouredDate', date);
assert.ok(dateCell.hasClass(CALENDAR_CONTOURED_DATE_CLASS));
});
QUnit.test('changing contouredDate must remove CALENDAR_CONTOURED_DATE_CLASS class from the old cell', function(assert) {
var date = new Date(2030, 1, 1),
newDate = new Date(2050, 1, 1),
dateCell = this.$element.find('table').find('td').eq(4);
this.view.option('contouredDate', date);
assert.ok(dateCell.hasClass(CALENDAR_CONTOURED_DATE_CLASS));
this.view.option('contouredDate', newDate);
assert.ok(!dateCell.hasClass(CALENDAR_CONTOURED_DATE_CLASS));
});
QUnit.module('MonthView min/max', {
beforeEach: function() {
fx.off = true;
this.min = new Date(2010, 10, 5);
this.max = new Date(2010, 10, 25);
this.$element = $('<div>').appendTo('body');
this.view = new Views['month'](this.$element, {
min: this.min,
date: new Date(2010, 10, 10),
value: new Date(2010, 10, 10),
max: this.max
});
},
afterEach: function() {
this.$element.remove();
fx.off = false;
}
});
QUnit.test('monthView should not allow to select dates earlier than min and later than max via pointer events', function(assert) {
var dateCells = this.$element.find('table').find('td');
pointerMock(dateCells[0]).click();
assert.ok(this.min.valueOf() < this.view.option('value').valueOf());
pointerMock(dateCells[dateCells.length - 1]).click();
assert.ok(this.max.valueOf() > this.view.option('value').valueOf());
});
QUnit.test('monthView should not allow to navigate to a date earlier than min and later than max via keyboard events', function(assert) {
var $element = this.$element,
view = this.view;
view.option('contouredDate', this.min);
triggerKeydown(UP_ARROW_KEY_CODE, $element);
assert.deepEqual(view.option('contouredDate'), this.min);
view.option('contouredDate', this.max);
triggerKeydown(DOWN_ARROW_KEY_CODE, $element);
assert.deepEqual(view.option('contouredDate'), this.max);
});
QUnit.module('MonthView disabledDates', {
beforeEach: function() {
fx.off = true;
this.disabledDates = function(args) {
if(args.date.getDate() < 5) {
return true;
}
};
this.$element = $('<div>').appendTo('body');
this.view = new Views['month'](this.$element, {
disabledDates: this.disabledDates,
date: new Date(2010, 10, 10),
value: new Date(2010, 10, 10)
});
},
afterEach: function() {
this.$element.remove();
fx.off = false;
}
});
QUnit.test('monthView should not allow to select disabled dates via pointer events', function(assert) {
var disabledDays = [1, 2, 3, 4],
dateCells = this.$element.find('table').find('td');
pointerMock(dateCells[0]).click();
assert.ok(disabledDays.indexOf(this.view.option('value').getDate()));
});
QUnit.test('monthView should not allow to navigate to a disabled date', function(assert) {
var $element = this.$element,
view = this.view;
view.option('contouredDate', new Date(2010, 10, 5));
triggerKeydown(UP_ARROW_KEY_CODE, $element);
assert.deepEqual(view.option('contouredDate'), new Date(2010, 10, 5));
});
QUnit.module('MonthView disabledDates as array', {
beforeEach: function() {
fx.off = true;
this.disabledDates = [
new Date(2010, 10, 1),
new Date(2010, 10, 2),
new Date(2010, 10, 3),
new Date(2010, 10, 4)
];
this.$element = $('<div>').appendTo('body');
this.view = new Views['month'](this.$element, {
disabledDates: this.disabledDates,
date: new Date(2010, 10, 10),
value: new Date(2010, 10, 10)
});
},
afterEach: function() {
this.$element.remove();
fx.off = false;
}
});
QUnit.test('monthView should not allow to select disabled dates via pointer events', function(assert) {
var disabledDays = [1, 2, 3, 4],
dateCells = this.$element.find('table').find('td');
pointerMock(dateCells[0]).click();
assert.ok(disabledDays.indexOf(this.view.option('value').getDate()));
});
QUnit.test('monthView should not allow to navigate to a disabled date', function(assert) {
var $element = this.$element,
view = this.view;
view.option('contouredDate', new Date(2010, 10, 5));
triggerKeydown(UP_ARROW_KEY_CODE, $element);
assert.deepEqual(view.option('contouredDate'), new Date(2010, 10, 5));
});
QUnit.module('YearView min/max', {
beforeEach: function() {
fx.off = true;
this.min = new Date(2015, 0, 18);
this.max = new Date(2015, 6, 18);
this.$element = $('<div>').appendTo('body');
this.view = new Views['year'](this.$element, {
min: this.min,
date: new Date(2015, 3, 15),
max: this.max
});
},
afterEach: function() {
this.$element.remove();
fx.off = false;
}
});
QUnit.test('yearView should not allow to navigate to a date earlier than min and later than max via keyboard events', function(assert) {
var $element = this.$element,
view = this.view;
view.option('contouredDate', this.min);
triggerKeydown(UP_ARROW_KEY_CODE, $element);
assert.deepEqual(view.option('contouredDate'), this.min);
view.option('contouredDate', this.max);
triggerKeydown(DOWN_ARROW_KEY_CODE, $element);
assert.deepEqual(view.option('contouredDate'), this.max);
});
QUnit.module('YearView disabledDates', {
beforeEach: function() {
fx.off = true;
this.disabledDates = function(args) {
if(args.date.getMonth() < 3) {
return true;
}
};
this.$element = $('<div>').appendTo('body');
this.view = new Views['year'](this.$element, {
disabledDates: this.disabledDates,
date: new Date(2015, 3, 15)
});
},
afterEach: function() {
this.$element.remove();
fx.off = false;
}
});
QUnit.test('yearView should not allow to navigate to a disabled date via keyboard events', function(assert) {
var $element = this.$element,
view = this.view;
view.option('contouredDate', new Date(2015, 3, 15));
triggerKeydown(UP_ARROW_KEY_CODE, $element);
assert.deepEqual(view.option('contouredDate'), new Date(2015, 3, 15));
});
QUnit.module('DecadeView min/max', {
beforeEach: function() {
fx.off = true;
this.min = new Date(2013, 0, 18);
this.max = new Date(2018, 6, 18);
this.$element = $('<div>').appendTo('body');
this.view = new Views['decade'](this.$element, {
min: this.min,
value: new Date(2015, 3, 15),
max: this.max
});
},
afterEach: function() {
this.$element.remove();
fx.off = false;
}
});
QUnit.test('decadeView should not allow to navigate to a date earlier than min and later than max via keyboard events', function(assert) {
var $element = this.$element,
view = this.view;
view.option('contouredDate', this.min);
triggerKeydown(UP_ARROW_KEY_CODE, $element);
assert.deepEqual(view.option('contouredDate'), this.min);
view.option('contouredDate', this.max);
triggerKeydown(DOWN_ARROW_KEY_CODE, $element);
assert.deepEqual(view.option('contouredDate'), this.max);
});
QUnit.module('DecadeView disabledDates', {
beforeEach: function() {
fx.off = true;
this.disabledDates = function(args) {
if(args.date.getFullYear() < 2013) {
return true;
}
};
this.$element = $('<div>').appendTo('body');
this.view = new Views['decade'](this.$element, {
disabledDates: this.disabledDates,
value: new Date(2015, 3, 15),
});
},
afterEach: function() {
this.$element.remove();
fx.off = false;
}
});
QUnit.test('decadeView should not allow to navigate to a disabled date via keyboard events', function(assert) {
var $element = this.$element,
view = this.view;
view.option('contouredDate', new Date(2015, 3, 15));
triggerKeydown(UP_ARROW_KEY_CODE, $element);
assert.deepEqual(view.option('contouredDate'), new Date(2015, 3, 15));
});
QUnit.module('CenturyView min/max', {
beforeEach: function() {
fx.off = true;
this.min = new Date(2005, 0, 18);
this.max = new Date(2075, 6, 18);
this.$element = $('<div>').appendTo('body');
this.view = new Views['century'](this.$element, {
min: this.min,
value: new Date(2015, 3, 15),
max: this.max
});
},
afterEach: function() {
this.$element.remove();
fx.off = false;
}
});
QUnit.test('centuryView should not allow to navigate to a date earlier than min and later than max via keyboard events', function(assert) {
var $element = this.$element,
view = this.view;
view.option('contouredDate', this.min);
triggerKeydown(UP_ARROW_KEY_CODE, $element);
assert.deepEqual(view.option('contouredDate'), this.min);
view.option('contouredDate', this.max);
triggerKeydown(DOWN_ARROW_KEY_CODE, $element);
assert.deepEqual(view.option('contouredDate'), this.max);
});
QUnit.module('CenturyView disabledDates', {
beforeEach: function() {
fx.off = true;
this.disabledDates = function(args) {
if(args.date.getFullYear() < 2010) {
return true;
}
};
this.$element = $('<div>').appendTo('body');
this.view = new Views['century'](this.$element, {
disabledDates: this.disabledDates,
value: new Date(2015, 3, 15)
});
},
afterEach: function() {
this.$element.remove();
fx.off = false;
}
});
QUnit.test('centuryView should not allow to navigate to a disabled date via keyboard events', function(assert) {
var $element = this.$element,
view = this.view;
view.option('contouredDate', new Date(2070, 0, 15));
triggerKeydown(UP_ARROW_KEY_CODE, $element);
assert.deepEqual(view.option('contouredDate'), new Date(2070, 0, 15));
});
QUnit.module('Aria accessibility', {
beforeEach: function() {
fx.off = true;
},
afterEach: function() {
fx.off = false;
}
});
QUnit.test('getCellAriaLabel method', function(assert) {
var expectations = {
'month': 'Monday, June 1, 2015',
'year': 'June 2015',
'decade': '2015',
'century': '2010 - 2019'
};
$.each(['month', 'year', 'decade', 'century'], function(_, type) {
var $element = $('<div>').appendTo('body');
new Views[type]($element, {
date: new Date(2015, 5, 1),
value: new Date(2015, 5, 1),
contouredDate: new Date(2015, 5, 1),
firstDayOfWeek: 1,
focusStateEnabled: true
});
try {
var $cell = $element.find('.' + CALENDAR_CONTOURED_DATE_CLASS);
assert.equal($cell.attr('aria-label'), expectations[type], 'aria label is correct');
} finally {
$element.remove();
}
});
});
| 31.537723 | 141 | 0.61411 |
433be8e80df90dccffa7e1c2583523e1059c7042 | 130 | js | JavaScript | libs/emmiter.js | viniciusm2001/dl-from-yt | c57989acde62bb81a2a50800f318168727b40139 | [
"MIT"
] | null | null | null | libs/emmiter.js | viniciusm2001/dl-from-yt | c57989acde62bb81a2a50800f318168727b40139 | [
"MIT"
] | null | null | null | libs/emmiter.js | viniciusm2001/dl-from-yt | c57989acde62bb81a2a50800f318168727b40139 | [
"MIT"
] | null | null | null | var events = require('events');
var eventEmitter = new events();
eventEmitter.setMaxListeners(0);
module.exports = eventEmitter; | 21.666667 | 32 | 0.761538 |
433bf06761b6fc694c4fca3a793c099941ea4cc5 | 170 | js | JavaScript | server/lib/app/ApplicationStart.js | asyncfinkd/blog | dd78b9f6bdcac4746c2fcf53088f86bfe1eaafa8 | [
"MIT"
] | 5 | 2021-10-19T13:50:43.000Z | 2022-01-10T19:36:01.000Z | server/lib/app/ApplicationStart.js | asyncfinkd/blog | dd78b9f6bdcac4746c2fcf53088f86bfe1eaafa8 | [
"MIT"
] | null | null | null | server/lib/app/ApplicationStart.js | asyncfinkd/blog | dd78b9f6bdcac4746c2fcf53088f86bfe1eaafa8 | [
"MIT"
] | 1 | 2021-10-12T14:36:44.000Z | 2021-10-12T14:36:44.000Z | module.exports.start = function (port, app) {
const PORT = process.env.PORT || port;
app.listen(PORT, () => {
console.log(`server started at ${PORT}`);
});
};
| 21.25 | 45 | 0.6 |
433c3367569d2206001b745cef5ae67e95f6af4a | 1,151 | js | JavaScript | index.js | FH-Potsdam/ct-mtm-a-joseph14 | 17d41fba81bdb30fa24556e080ced44907fbd110 | [
"MIT"
] | null | null | null | index.js | FH-Potsdam/ct-mtm-a-joseph14 | 17d41fba81bdb30fa24556e080ced44907fbd110 | [
"MIT"
] | null | null | null | index.js | FH-Potsdam/ct-mtm-a-joseph14 | 17d41fba81bdb30fa24556e080ced44907fbd110 | [
"MIT"
] | null | null | null | /**
* Mandatory tasks
* @todo Connect a servo and draw something
*
* Possible tasks
* @todo Connect two servos and draw something
* @todo Attach one servo to another and draw something
* @todo Attach a DC Motor and a servo and draw something
* @todo Make the DC motor move the papar and the servo move the pen
* @todo Make the above ☝️ - work the other way around
* @todo Attach a stepper motor and a servo and draw something
* @todo Attach a stepper, a servo and a dc motor and draw
* @todo …
* you get the gist! Draw something
*
* See for more docs
* Servos http://johnny-five.io/examples/#servo
* DC Motors http://johnny-five.io/examples/#motor
* Stepper http://johnny-five.io/examples/#stepper-motor
*
*
*/
const five = require("johnny-five"); // this is a module installed in the node_modules by running `npm install johnny-five`
// const myFunkyModule = require("./lib/example"); // this is a module you write the difference is the relative path
// myFunkyModule.log("He Ho - Let's go!");
const board = new five.Board();
let led = undefined;
board.on("ready", function() {
led = new five.Led(13);
led.blink(200);
});
| 32.885714 | 123 | 0.701998 |
433c6c1aeccb52757901be6c785f12c29e2e8f85 | 337 | js | JavaScript | certificate_check/resources/config.js | ccmjs/rmuel12s-components | a54a03c170aa611c6e7b13bd995ca9ed9436cac2 | [
"MIT"
] | null | null | null | certificate_check/resources/config.js | ccmjs/rmuel12s-components | a54a03c170aa611c6e7b13bd995ca9ed9436cac2 | [
"MIT"
] | null | null | null | certificate_check/resources/config.js | ccmjs/rmuel12s-components | a54a03c170aa611c6e7b13bd995ca9ed9436cac2 | [
"MIT"
] | null | null | null | /**
* @component ccm-certificate_check
* @author René Müller <rene.mueller@smail.inf.h-brs.de> 2019
* @license MIT License
*/
ccm.files ['config.js'] = {
"live": {
"data": {}
},
"develop": {
"data": {
"studentContractAddress" : "0x1363c80e00a852e5e0ea8af0e3d78e1355dbd314"
}
}
};
| 19.823529 | 83 | 0.563798 |
433c97a3040965cbc8a91cffbae647dcde5452ba | 7,668 | js | JavaScript | src/blizzard/wow/lib/community.js | kendinikertenkelebek/cyberpoints | d08ddac4f4533a688780169ac2294e33a462b31d | [
"Apache-2.0"
] | 8 | 2020-08-02T03:36:10.000Z | 2021-11-26T10:11:03.000Z | src/blizzard/wow/lib/community.js | kendinikertenkelebek/cyberpoints | d08ddac4f4533a688780169ac2294e33a462b31d | [
"Apache-2.0"
] | 12 | 2018-08-27T12:32:41.000Z | 2019-08-20T12:03:00.000Z | src/blizzard/wow/lib/community.js | kendinikertenkelebek/cyberpoints | d08ddac4f4533a688780169ac2294e33a462b31d | [
"Apache-2.0"
] | 4 | 2018-12-04T21:01:30.000Z | 2021-06-22T19:17:15.000Z | 'use strict';
/* eslint-disable max-len */
exports.Endpoints = {
Community({ root, token, locale }) {
return {
Profile: () => `${root}/wow/user/characters?access_token=${token}`,
Achievement: id => `${root}/wow/achievement/${id}?locale=${locale}&access_token=${token}`,
Auction: realm => `${root}/wow/auction/data/${realm}?locale=${locale}&access_token=${token}`,
Boss: {
MasterList: () => `${root}/wow/boss/?locale=${locale}&access_token=${token}`,
Boss: bossId => `${root}/wow/boss/${bossId}?locale=${locale}&access_token=${token}`,
},
Challenge: {
Realm: realm => `${root}/wow/challenge/${realm}?locale=${locale}&access_token=${token}`,
Region: () => `${root}/wow/challenge/region?locale=${locale}&access_token=${token}`,
},
Character: {
Profile: (realm, characterName, fields) =>
`${root}/wow/character/${realm}/${characterName}?fields=${fields}&locale=${locale}&access_token=${token}`,
Achievements: (realm, characterName, fields) =>
`${root}/wow/character/${realm}/${characterName}?fields=${fields}&locale=${locale}&access_token=${token}`,
Appearance: (realm, characterName, fields) =>
`${root}/wow/character/${realm}/${characterName}?fields=${fields}&locale=${locale}&access_token=${token}`,
Feed: (realm, characterName, fields) =>
`${root}/wow/character/${realm}/${characterName}?fields=${fields}&locale=${locale}&access_token=${token}`,
Guild: (realm, characterName, fields) =>
`${root}/wow/character/${realm}/${characterName}?fields=${fields}&locale=${locale}&access_token=${token}`,
HunterPets: (realm, characterName, fields) =>
`${root}/wow/character/${realm}/${characterName}?fields=${fields}&locale=${locale}&access_token=${token}`,
Items: (realm, characterName, fields) =>
`${root}/wow/character/${realm}/${characterName}?fields=${fields}&locale=${locale}&access_token=${token}`,
Mounts: (realm, characterName, fields) =>
`${root}/wow/character/${realm}/${characterName}?fields=${fields}&locale=${locale}&access_token=${token}`,
Pets: (realm, characterName, fields) =>
`${root}/wow/character/${realm}/${characterName}?fields=${fields}&locale=${locale}&access_token=${token}`,
PetStlots: (realm, characterName, fields) =>
`${root}/wow/character/${realm}/${characterName}?fields=${fields}&locale=${locale}&access_token=${token}`,
Professions: (realm, characterName, fields) =>
`${root}/wow/character/${realm}/${characterName}?fields=${fields}&locale=${locale}&access_token=${token}`,
Progression: (realm, characterName, fields) =>
`${root}/wow/character/${realm}/${characterName}?fields=${fields}&locale=${locale}&access_token=${token}`,
Pvp: (realm, characterName, fields) =>
`${root}/wow/character/${realm}/${characterName}?fields=${fields}&locale=${locale}&access_token=${token}`,
Quests: (realm, characterName, fields) =>
`${root}/wow/character/${realm}/${characterName}?fields=${fields}&locale=${locale}&access_token=${token}`,
Reputation: (realm, characterName, fields) =>
`${root}/wow/character/${realm}/${characterName}?fields=${fields}&locale=${locale}&access_token=${token}`,
Statistics: (realm, characterName, fields) =>
`${root}/wow/character/${realm}/${characterName}?fields=${fields}&locale=${locale}&access_token=${token}`,
Stats: (realm, characterName, fields) =>
`${root}/wow/character/${realm}/${characterName}?fields=${fields}&locale=${locale}&access_token=${token}`,
Talents: (realm, characterName, fields) =>
`${root}/wow/character/${realm}/${characterName}?fields=${fields}&locale=${locale}&access_token=${token}`,
Titles: (realm, characterName, fields) =>
`${root}/wow/character/${realm}/${characterName}?fields=${fields}&locale=${locale}&access_token=${token}`,
Audit: (realm, characterName, fields) =>
`${root}/wow/character/${realm}/${characterName}?fields=${fields}&locale=${locale}&access_token=${token}`,
},
Guild: {
Profile: (realm, guildName, fields) =>
`${root}/wow/guild/${realm}/${guildName}?fields=${fields}&locale=${locale}&access_token=${token}`,
Members: (realm, guildName, fields) =>
`${root}/wow/guild/${realm}/${guildName}?fields=${fields}&locale=${locale}&access_token=${token}`,
Achievements: (realm, guildName, fields) =>
`${root}/wow/guild/${realm}/${guildName}?fields=${fields}&locale=${locale}&access_token=${token}`,
News: (realm, guildName, fields) =>
`${root}/wow/guild/${realm}/${guildName}?fields=${fields}&locale=${locale}&access_token=${token}`,
Challenge: (realm, guildName, fields) =>
`${root}/wow/guild/${realm}/${guildName}?fields=${fields}&locale=${locale}&access_token=${token}`,
},
Item: {
Item: itemId => `${root}/wow/item/${itemId}?locale=${locale}&access_token=${token}`,
Set: setId => `${root}/wow/item/set/${setId}?locale=${locale}&access_token=${token}`,
},
Mount: () => `${root}/wow/mount/?locale=${locale}&access_token=${token}`,
Pet: {
MasterList: () => `${root}/wow/pet/?locale=${locale}&access_token=${token}`,
Abilities: abilityId => `${root}/wow/pet/ability/${abilityId}?locale=${locale}&access_token=${token}`,
Species: speciesId => `${root}/wow/pet/species/${speciesId}?locale=${locale}&access_token=${token}`,
Stats: (speciesId, level, breedId, qualityId) =>
`${root}/wow/pet/stats/${speciesId}?level=${level}&breedId=${breedId}&qualityId=${qualityId}&locale=${locale}&access_token=${token}`,
},
Pvp: bracket => `${root}/wow/leaderboard/${bracket}?locale=e${locale}&access_token=${token}`,
Quest: questId => `${root}/wow/quest/${questId}?locale=${locale}&access_token=${token}`,
RealmStatus: () => `${root}/wow/realm/status?locale=${locale}&access_token=${token}`,
Recipe: recipeId => `${root}/wow/recipe/${recipeId}?locale=${locale}&access_token=${token}`,
Spell: spellId => `${root}/wow/spell/${spellId}?locale=${locale}&access_token=${token}`,
User: () => `${root}/wow/user/characters?locale=${locale}&access_token=${token}`,
Resources: {
BattleGroups: () => `${root}/wow/data/battlegroups/?locale=${locale}&access_token=${token}`,
CharacterRaces: () => `${root}/wow/data/character/races?locale=${locale}&access_token=${token}`,
CharacterClasses: () => `${root}/wow/data/character/classes?locale=${locale}&access_token=${token}`,
CharacterAchievements: () => `${root}/wow/data/character/achievements?locale=${locale}&access_token=${token}`,
GuildRewards: () => `${root}/wow/data/guild/rewards?locale=${locale}&access_token=${token}`,
GuildPerks: () => `${root}/wow/data/guild/perks?locale=${locale}&access_token=${token}`,
GuildAchievements: () => `${root}/wow/data/guild/achievements?locale=${locale}&access_token=${token}`,
ItemClasses: () => `${root}/wow/data/item/classes?locale=${locale}&access_token=${token}`,
Talents: () => `${root}/wow/data/talents?locale=${locale}&access_token=${token}`,
PetTypes: () => `${root}/wow/data/pet/types?locale=${locale}&access_token=${token}`,
},
Zone: {
MasterList: () => `${root}/wow/zone/?locale=${locale}&access_token=${token}`,
Zone: zoneId => `${root}/wow/zone/${zoneId}?locale=${locale}&access_token=${token}`,
},
};
},
};
| 70.348624 | 143 | 0.615415 |
433dc155d9e636342dd8a2258cfc36f55eb1c500 | 7,083 | js | JavaScript | routes/userHub.js | JC-2020/capstone-frontend | f850badacab7f7bd497c326ced533152889493ca | [
"MIT"
] | 2 | 2020-12-10T18:23:42.000Z | 2021-04-12T03:47:39.000Z | routes/userHub.js | JC-2020/capstone-frontend | f850badacab7f7bd497c326ced533152889493ca | [
"MIT"
] | 7 | 2020-11-23T18:08:25.000Z | 2020-12-07T19:16:34.000Z | routes/userHub.js | JC-2020/capstone-frontend | f850badacab7f7bd497c326ced533152889493ca | [
"MIT"
] | 4 | 2020-12-10T20:43:37.000Z | 2020-12-13T19:17:00.000Z | var express = require('express');
var router = express.Router();
const models = require('../models')
const bcrypt = require('bcrypt')
const session = require('express-session')
const multer = require('multer');
const checkAuth = require('../checkAuth');
const db = require('../models');
const uploadToS3 = require('../upload-to-S3');
// multer storage
const storage = multer.diskStorage({
destination: function(req, file, cb){
cb(null, './uploads/');
},
filename: function(req,file,cb){
cb(null, new Date().toISOString() + file.originalname);
}
})
// filter types of images that multer will accept
const fileFilter = (req,file,cb) => {
if(file.mimetype === 'image/jpeg' || file.mimetype === 'image/png'){
// accept a file
cb(null, true)
}else{
// reject a file
cb(null, false)
}
}
const upload = multer({
storage: storage,
limits:{
fileSize: 1024 * 1024 * 5
},
fileFilter: fileFilter
});
//get profile
//* Added a section that includes the projects that the current user owns and is a teamMember of
router.get('/current', checkAuth, (req,res) => {
models.User.findOne({
where: {
id: req.session.user.id
},
include: [
{
primaryKey: 'owner',
model: db.Project,
required: false,
include:[
db.Skill
]
},
{
as: "MemberProjects",
model: db.Project,
required: false,
include:[
db.Skill
]
},
db.Skill]
})
.then((user) =>{
if(user){
res.json(user)
}else {
res.status(401).json({
error:'No User logged in'
})
}
})
})
// all info by user id
router.get('/user/:id', checkAuth, (req,res) => {
const {id} = req.params
models.User.findOne({
where: {
id
},
include: [
{
primaryKey: 'owner',
model: db.Project,
required: false,
},
{
as: "MemberProjects",
model: db.Project,
required: false
},
db.Skill]
})
.then((user) =>{
if(user){
res.json(user)
}else {
res.status(401).json({
error:'No User logged in'
})
}
})
})
//update profile
router.patch('/',upload.single('profilePicture'), checkAuth, (req,res) => {
const updateObject = {}
if(!req.body.firstName && !req.body.lastName && !req.body.email && !req.body.password && !req.body.title && !req.file){
res.status(400).json({
error: 'Please pick a field to change'
})
}
const { firstName, lastName, email, password, title, userSkillsArray } = req.body
let profilePicture = req.file && req.file.path ? "/" + req.file.path : null
const params = { firstName, lastName, password, profilePicture, email, title }
uploadToS3(req.file && req.file.path).then(url => {
if (url) {
params.profilePicture = url.Location
}
Object.keys(params).forEach(key => {params[key] ? updateObject[key] = params[key] : ''})
models.User.update(updateObject, {
where: {
id: req.session.user.id
}
})
.then((updated) => {
if(updated && updated[0] > 0){
return updated
}else{
res.status(404).json({
error: 'Profile not found'
})
}
})
.then(updated => {
return db.User.findOne({
where: {
id: req.session.user.id
}
})
.then(user => user)
})
.then(user => {
return db.Skill.findAll({
where: {id: userSkillsArray}
})
.then(skills => {
if(!skills){
res.status(404).json({error: 'A certain skill wasn\'t found'})
}
return user.setSkills(skills)
.then(() => user)
})
})
.then(user => {
res.status(201).json({success: 'User updated'})
})
.catch((e) => {
res.status(500).json({
error: 'Database error occurred' + e
})
})
})
})
//* Add skill(s) to the currently logged in user --> send over as an array of the skillId's
router.post('/userSkill', checkAuth, (req, res) => {
const { userSkillsArray } = req.body;
db.User.findOne({
where: {
id: req.session.user.id
}
})
.then(user => {
return db.Skill.findAll({
where: {id: userSkillsArray}
})
.then(skills => {
if(!skills){
res.status(404).json({error: 'A certain skill wasn\'t found'})
}
return user.setSkills(skills)
.then(() => user)
})
})
.then(user => {
res.status(201).json(user)
})
.catch(e => {
res.status(500).json({error: 'A database error: ' + e})
})
})
//* Remove skill(s) to the currently logged in user --> send over as an array of the skillId's
router.delete('/userSkill', checkAuth, (req, res) => {
const { userSkillsArray } = req.body;
db.User.findOne({
where: {
id: req.session.user.id
}
})
.then(user => {
return db.Skill.findAll({
where: {id: userSkillsArray}
})
.then(skills => {
if(!skills){
res.status(404).json({error: 'A certain skill wasn\'t found'})
}
return user.removeSkills(skills)
.then(() => user)
})
})
.then(user => {
res.status(201).json(user)
})
.catch(e => {
res.status(500).json({error: 'A database error: ' + e})
})
})
router.delete('/:userId', (req, res) => {
db.User.destroy({
where:{
id: req.params.userId
}
})
.then(deleted=>{
if(deleted === 1){
res.status(202).json({
success: "Account deleted"
})
}else{
res.status(404).json({
error: "Account Not Found"
})
}
})
})
module.exports = router
| 27.667969 | 124 | 0.435409 |
433dd4bc9b4cbb25eb1e72eb4999c57d492b60d9 | 9,827 | js | JavaScript | client/src/core/polls/__test__/pollSagas.test.js | kashaf12/Vote-redux-mern | 98ffb8fa81cdbabe416e2abdbde6f90741c20a8e | [
"MIT"
] | 3 | 2018-10-17T19:56:03.000Z | 2021-01-17T09:33:35.000Z | client/src/core/polls/__test__/pollSagas.test.js | kashaf12/Vote-redux-mern | 98ffb8fa81cdbabe416e2abdbde6f90741c20a8e | [
"MIT"
] | 2 | 2021-05-06T22:54:06.000Z | 2021-05-06T23:22:14.000Z | client/src/core/polls/__test__/pollSagas.test.js | kashaf12/Vote-redux-mern | 98ffb8fa81cdbabe416e2abdbde6f90741c20a8e | [
"MIT"
] | 1 | 2018-10-17T20:00:53.000Z | 2018-10-17T20:00:53.000Z | import { call, put, select, takeLatest } from 'redux-saga/effects';
import { SubmissionError, reset } from 'redux-form';
import { cloneableGenerator } from 'redux-saga/utils';
// Import compoenents
import history from '../../history';
import { mockUser, mockPoll, mockPolls } from '../../../utils/__test__';
import { getAuthedUser } from '../../users';
import {
getActivePoll, getViewedPoll,
pollRequestActions, pollReducer, pollSagas,
getPollsApi, postPollApi, updatePollApi, updatePollVoteApi, deletePollApi
} from '../../polls';
import {
GET_POLLS, GET_POLLS_SUCCESS, GET_POLLS_FAILURE,
POST_POLL, POST_POLL_SUCCESS, POST_POLL_FAILURE,
UPDATE_POLL_STATUS, UPDATE_POLL_VOTE,
UPDATE_POLL_SUCCESS, UPDATE_POLL_FAILURE,
DELETE_POLL, DELETE_POLL_SUCCESS, DELETE_POLL_FAILURE
} from '../../constants';
describe('pollSagas', () => {
describe('watchers', () => {
it('watchGetPollsSaga() calls takeLatest on GET_POLLS action', () => {
const gen = cloneableGenerator(pollSagas.watchGetPollsSaga)();
expect(gen.next().value).toEqual(
takeLatest(GET_POLLS, pollSagas.getPollsSaga));
expect(gen.next().done).toEqual(true);
});
it('watchPostPollSaga() calls takeLatest on POST_POLL action', () => {
const gen = cloneableGenerator(pollSagas.watchPostPollSaga)();
expect(gen.next().value).toEqual(
takeLatest(POST_POLL, pollSagas.postPollSaga));
expect(gen.next().done).toEqual(true);
});
it('watchPostPollSuccessSaga() calls takeLatest on POST_POLL_SUCCESS action', () => {
const gen = cloneableGenerator(pollSagas.watchPostPollSuccessSaga)();
expect(gen.next().value).toEqual(
takeLatest(POST_POLL_SUCCESS, pollSagas.postPollSuccessSaga));
expect(gen.next().done).toEqual(true);
});
it('watchUpdatePollStatusSaga() calls takeLatest on UPDATE_POLL_STATUS action', () => {
const gen = cloneableGenerator(pollSagas.watchUpdatePollStatusSaga)();
expect(gen.next().value).toEqual(
takeLatest(UPDATE_POLL_STATUS, pollSagas.updatePollStatusSaga));
expect(gen.next().done).toEqual(true);
});
it('watchUpdatePollVoteSaga() calls takeLatest on UPDATE_POLL_VOTE action', () => {
const gen = cloneableGenerator(pollSagas.watchUpdatePollVoteSaga)();
expect(gen.next().value).toEqual(
takeLatest(UPDATE_POLL_VOTE, pollSagas.updatePollVoteSaga));
expect(gen.next().done).toEqual(true);
});
it('watchUpdatePollSuccess() calls takeLatest on UPDATE_POLL_SUCCESS action', () => {
const gen = cloneableGenerator(pollSagas.watchUpdatePollSuccessSaga)();
expect(gen.next().value).toEqual(
takeLatest(UPDATE_POLL_SUCCESS, pollSagas.updatePollSuccessSaga));
expect(gen.next().done).toEqual(true);
});
it('watchDeletePollSaga() calls takeLatest on DELETE_POLL action', () => {
const gen = cloneableGenerator(pollSagas.watchDeletePollSaga)();
expect(gen.next().value).toEqual(
takeLatest(DELETE_POLL, pollSagas.deletePollSaga));
expect(gen.next().done).toEqual(true);
});
});
describe('watched sagas', () => {
let promises;
beforeAll(() => {
promises = {};
var grabPromises = new Promise(function(resolve, reject) {
promises.resolve = resolve;
promises.reject = reject;
});
});
describe('get polls flow', () => {
let getPollsAction, clone;
beforeAll(() => getPollsAction = pollRequestActions.getPending());
beforeEach(() => clone = (cloneableGenerator(pollSagas.getPollsSaga)(getPollsAction)).clone());
it('completes successfully on success', () => {
expect(clone.next().value).toEqual(
call(getPollsApi));
expect(clone.next({ polls: mockPolls }).value).toEqual(
put(pollRequestActions.getFulfilled({
polls: mockPolls
}))
);
expect(clone.next().done).toEqual(true);
});
it('throws successfully on failure', () => {
clone.next();
const error = 'Error creating poll.';
expect(clone.throw(error).value).toEqual(
put(pollRequestActions.getFailed(error)));
expect(clone.next().done).toEqual(true);
});
});
describe('post poll flow', () => {
let postPollAction, clone;
beforeAll(() => postPollAction = pollRequestActions.postPending(
mockPoll,
promises
));
beforeEach(() => clone = (cloneableGenerator(pollSagas.postPollSaga)(postPollAction)).clone());
it('completes successfully on success', () => {
expect(clone.next().value).toEqual(
select(getAuthedUser));
expect(clone.next({ ...mockUser }).value).toEqual(
call(postPollApi, {
title: mockPoll.title,
choices: mockPoll.choices,
user_id: mockUser.cuid,
user_name: mockUser.name
})
);
expect(clone.next({ poll: mockPoll, message: 'success' }).value).toEqual(
put(pollRequestActions.postFulfilled({
poll: mockPoll,
message: 'success'
}))
);
expect(clone.next().value).toEqual(
put(reset('newPoll')));
expect(clone.next().value).toEqual(
call(promises.resolve));
expect(clone.next().done).toEqual(true);
});
it('throws successfully on failure', () => {
clone.next();
const error = 'Error creating poll.';
expect(clone.throw(error).value).toEqual(
put(pollRequestActions.postFailed(error)));
expect(clone.next().value).toEqual(
call(promises.reject, (new SubmissionError(error))));
expect(clone.next().done).toEqual(true);
});
});
describe('update poll status flow', () => {
let updatePollStatusAction, clone;
beforeAll(() => updatePollStatusAction = pollRequestActions.updateStatusPending());
beforeEach(() => clone = (cloneableGenerator(pollSagas.updatePollStatusSaga)(updatePollStatusAction)).clone());
it('completes successfully on success', () => {
expect(clone.next().value).toEqual(
select(getViewedPoll));
expect(clone.next({ ...mockPoll }).value).toEqual(
call(updatePollApi,
mockPoll.cuid,
{ open: (mockPoll.open ? false : true) }
)
);
expect(clone.next({ poll: mockPoll, message: 'success' }).value).toEqual(
put(pollRequestActions.updateFulfilled({
message: 'success',
poll: {
open: false,
...mockPoll
}
}))
);
expect(clone.next().done).toEqual(true);
});
it('throws successfully on failure', () => {
clone.next();
const error = 'Error updating poll.';
expect(clone.throw(error).value).toEqual(
put(pollRequestActions.updateFailed(error)));
expect(clone.next().done).toEqual(true);
});
});
describe('update poll vote flow', () => {
let updatePollVoteAction, clone;
beforeAll(() => updatePollVoteAction = pollRequestActions.updateVotePending(
{ choice: mockPoll.choices[0].label },
promises
));
beforeEach(() => clone = (cloneableGenerator(pollSagas.updatePollVoteSaga)(updatePollVoteAction)).clone());
it('completes successfully on success', () => {
expect(clone.next().value).toEqual(
select(getAuthedUser));
expect(clone.next({ ...mockUser }).value).toEqual(
select(getActivePoll));
expect(clone.next({ ...mockPoll }).value).toEqual(
call(updatePollVoteApi,
mockPoll.cuid,
{
voterId: mockUser.cuid,
choicesLabel: mockPoll.choices[0].label
}
)
);
expect(clone.next({ poll: mockPoll, message: 'success' }).value).toEqual(
put(pollRequestActions.updateFulfilled({
message: 'success',
poll: mockPoll
})
));
expect(clone.next().value).toEqual(
put(reset('votePoll')));
expect(clone.next().value).toEqual(
call(promises.resolve));
expect(clone.next().done).toEqual(true);
});
it('throws successfully on failure', () => {
clone.next();
const error = 'Error updating poll.';
expect(clone.throw(error).value).toEqual(
put(pollRequestActions.updateFailed(error)));
expect(clone.next().value).toEqual(
call(promises.reject, (new SubmissionError(error))));
expect(clone.next().done).toEqual(true);
});
});
describe('delete poll flow', () => {
let deletePollAction, clone;
beforeAll(() => deletePollAction = pollRequestActions.deletePending(
mockPoll.cuid
));
beforeEach(() => clone = (cloneableGenerator(pollSagas.deletePollSaga)(deletePollAction)).clone());
it('completes successfully on success', () => {
expect(clone.next().value).toEqual(
call(deletePollApi,
mockPoll.cuid
));
const message = 'Poll deleted.';
expect(clone.next({ message }).value).toEqual(
put(pollRequestActions.deleteFulfilled({
id: mockPoll.cuid,
message
})
));
expect(clone.next().value).toEqual(
history.push('/account'));
expect(clone.next().done).toEqual(true);
});
it('throws successfully on failure', () => {
clone.next();
const error = 'Error creating poll.';
expect(clone.throw(error).value).toEqual(
put(pollRequestActions.deleteFailed(error)));
expect(clone.next().done).toEqual(true);
});
});
});
});
| 35.864964 | 117 | 0.609647 |
433df1ccf28735e0c96aaeab60fb82ca1091b14b | 2,024 | js | JavaScript | packages/one-app-bundler/webpack/loaders/ssr-css-loader/index.js | markbello/one-app-cli | 70c5b85c9d494e019811215ffeef35ba9926beec | [
"Apache-2.0"
] | 23 | 2019-12-19T16:26:28.000Z | 2022-01-04T22:00:26.000Z | packages/one-app-bundler/webpack/loaders/ssr-css-loader/index.js | markbello/one-app-cli | 70c5b85c9d494e019811215ffeef35ba9926beec | [
"Apache-2.0"
] | 307 | 2019-12-23T17:38:46.000Z | 2022-03-31T09:28:22.000Z | packages/one-app-bundler/webpack/loaders/ssr-css-loader/index.js | markbello/one-app-cli | 70c5b85c9d494e019811215ffeef35ba9926beec | [
"Apache-2.0"
] | 32 | 2019-12-20T03:11:37.000Z | 2021-09-30T20:20:06.000Z | /*
* Copyright 2019 American Express Travel Related Services Company, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations
* under the License.
*/
const path = require('path');
// stringify handles win32 path slashes too
// so `C:\path\node_modules` doesn't turn into something with a newline
const cssBasePathString = JSON.stringify(path.resolve(__dirname, 'css-base.js'));
const CSS_LOADER_FINDER = /var ___CSS_LOADER_API_IMPORT___ = (__webpack_){0,1}require(__){0,1}\([.a-zA-Z0-9/_*!\s-]*"[.a-zA-Z0-9/_]+\/css-loader\/dist\/runtime\/api.js"\);\n\s*exports = ___CSS_LOADER_API_IMPORT___\((undefined|false)?\);/;
// The following two regex patterns split the above regex in two
// this is due to some UI libraries injecting their own vars between
// var ___CSS_LOADER_API_IMPORT___ and exports = ___CS_LOADER_API_IMPORT___
const CSS_RUNTIME_FINDER = /var ___CSS_LOADER_API_IMPORT___ = (__webpack_){0,1}require(__){0,1}\([.a-zA-Z0-9/_*!\s-]*"[.a-zA-Z0-9/_]+\/css-loader\/dist\/runtime\/api.js"\);/;
const CSS_EXPORTS_FINDER = /exports = ___CSS_LOADER_API_IMPORT___\((undefined|false)?\);/;
module.exports = function ssrCssLoader(content) {
if (!CSS_RUNTIME_FINDER.test(content) || !CSS_EXPORTS_FINDER.test(content)) {
throw new Error(`could not find the css-loader in\n${content}`);
}
return content
.replace(
CSS_LOADER_FINDER,
''
)
.replace(
'exports.push',
`require(${cssBasePathString})().push`
)
.replace(
'exports.locals =',
'exports = module.exports ='
);
};
| 41.306122 | 238 | 0.711957 |
433e7ba3b2a724b621f24509144570311e8f685f | 483 | js | JavaScript | documentation/struct_state.js | NoelCE14/CE2007 | 37122a25cad2ccc33116f1984dc4a6b7637540b3 | [
"BSD-2-Clause-FreeBSD"
] | 2 | 2021-08-21T05:50:12.000Z | 2021-09-08T07:37:04.000Z | documentation/struct_state.js | NoelCE14/CE2007 | 37122a25cad2ccc33116f1984dc4a6b7637540b3 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | documentation/struct_state.js | NoelCE14/CE2007 | 37122a25cad2ccc33116f1984dc4a6b7637540b3 | [
"BSD-2-Clause-FreeBSD"
] | 2 | 2020-10-25T08:42:34.000Z | 2021-11-01T16:05:02.000Z | var struct_state =
[
[ "delay", "struct_state.html#a458421a43d4f6dc515faf427bf579d00", null ],
[ "Next", "struct_state.html#af0784c8d3bbecfb9ddf716949423c68b", null ],
[ "next", "struct_state.html#ad30e2f0a484727bb04f48d9715f16376", null ],
[ "Out", "struct_state.html#a88553592388cd23aab5fb5d7a6c16cb4", null ],
[ "out", "struct_state.html#ab27775f0ed2b042b439a7431fbe311eb", null ],
[ "Time", "struct_state.html#afb4952bec365dc441b645a2ba0fc0379", null ]
]; | 53.666667 | 77 | 0.73706 |
433e93be45f9671dbbef079e5411a7a458f76c2d | 2,451 | js | JavaScript | public/js/public.min.js | elvendor/TypiCMS | dd6ff71ca237f2334ee5d864b6005ac02001cae3 | [
"MIT"
] | null | null | null | public/js/public.min.js | elvendor/TypiCMS | dd6ff71ca237f2334ee5d864b6005ac02001cae3 | [
"MIT"
] | null | null | null | public/js/public.min.js | elvendor/TypiCMS | dd6ff71ca237f2334ee5d864b6005ac02001cae3 | [
"MIT"
] | null | null | null | $(document).ready(function(){function e(){if(i.length<=3)for(var e=0;e<i.length;e++)setTimeout(function(){t(google.maps.Animation.DROP)},200*e);else for(var e=0;e<i.length;e++)t(!1)}function t(e){for(var t=0,a=i.length-1;a>=0;a--)s[g].lat()==s[a].lat()&&s[g].lng()==s[a].lng()&&t++;var n;n=t>=2?new google.maps.LatLng(s[g].lat(),s[g].lng()+Math.random()/4e3+1e-5):s[g],l[g]=new google.maps.Marker({shape:m,position:n,map:p,draggable:!1,animation:e}),l[g].html=i[g].html,l[g].id=i[g].id,google.maps.event.addListener(l[g],"click",d),g++}function a(e){var t=$("#item-"+e);t.length&&!t.hasClass("active")&&($(".addresses .active").removeClass("active"),t.addClass("active"))}function n(){var e=new google.maps.LatLngBounds;$.each(i,function(t){e.extend(s[t])}),p.fitBounds(e);var t=google.maps.event.addListener(p,"idle",function(){p.getZoom()>17&&p.setZoom(17),google.maps.event.removeListener(t)})}if($("#map").length){var o=new google.maps.InfoWindow,i=[],l=[],s=[],g=0,r={mapTypeId:google.maps.MapTypeId.ROADMAP,center:new google.maps.LatLng(50.85,4.36),mapTypeControl:!1,streetViewControl:!1,zoom:12},m={coord:[0,0,27,0,27,37,0,37],type:"poly"},p=new google.maps.Map(document.getElementById("map"),r);google.maps.event.addListener(p,"click",function(){o.close()});var d=function(){a(this.id),o.setContent(this.html),o.open(p,this)};$.getJSON(window.location.href,function(t){$.isArray(t)||(t=[t]);for(var a=0;a<t.length;a++){s[a]=new google.maps.LatLng(t[a].latitude,t[a].longitude),i[a]={};var o=[];i[a].id=t[a].id,i[a].shape=t[a].shape,i[a].html="<h4>"+t[a].title+"</h4>",i[a].html+="<p>",t[a].address&&o.push(t[a].address),t[a].phone&&o.push("T "+t[a].phone),t[a].fax&&o.push("F "+t[a].fax),t[a].email&&o.push('<a href="mailto:'+t[a].email+'">'+t[a].email+"</a>"),t[a].website&&o.push('<a href="'+t[a].website+'" target="_blank">'+t[a].website+"</a>"),i[a].html+=o.join("<br>"),i[a].html+="</p>"}i.length>0&&(e(),n())})}$(".btn-map").click(function(){for(var e=$(this).closest("li").attr("id").replace(/item-/gi,""),t=i.length-1;t>=0;t--)if(i[t].id==e){var a=new google.maps.LatLng(s[t].lat(),s[t].lng());p.panTo(a),google.maps.event.trigger(l[t],"click")}return!1})});
function translate(n){return n}var lang=$("html").attr("lang"),langues=["fr","nl","en"],content=[];!function(n){"use strict";n(function(){n(".fancybox").fancybox({prevEffect:"fade",nextEffect:"fade",openEffect:"elastic",closeEffect:"elastic"})})}(window.jQuery||window.ender); | 1,225.5 | 2,174 | 0.649123 |
433e9c5e8ec0d19a005beffc89896fc63cce382b | 1,867 | js | JavaScript | src/global/nominateSuper.js | jareer12/grepper | dd3d694f1211eed2a9c492dc6261b76718db2e4d | [
"MIT"
] | 7 | 2021-12-19T15:06:01.000Z | 2022-02-23T09:27:08.000Z | src/global/nominateSuper.js | jareer12/grepper | dd3d694f1211eed2a9c492dc6261b76718db2e4d | [
"MIT"
] | 1 | 2021-12-22T13:18:44.000Z | 2021-12-22T13:19:57.000Z | src/global/nominateSuper.js | jareer12/grepper | dd3d694f1211eed2a9c492dc6261b76718db2e4d | [
"MIT"
] | null | null | null | const fetch = require("node-fetch");
const FormData = require("form-data");
async function nominateSuper(data) {
const super_badges = {
most_helpful: {
award_id: 1,
},
hard_worker: {
award_id: 2,
},
class_clown: {
award_id: 3,
},
best_smile: {
award_id: 4,
},
most_likely_billion: {
award_id: 5,
},
best_hair: {
award_id: 6,
},
most_intelligent: {
award_id: 7,
},
best_coder: {
award_id: 8,
},
most_attractive: {
award_id: 9,
},
most_creative: {
award_id: 10,
},
};
const token = data.token;
const userId = data.userId;
if (!super_badges[data.awardName]) {
return {
Success: false,
Message: `No Such Award Exists`,
};
}
const DataToSend = new FormData();
DataToSend.append("award", 1);
DataToSend.append("user_id", data.nomineeId);
DataToSend.append("award_id", super_badges[data.awardName].award_id);
return fetch(`https://www.codegrepper.com/api/nominate_super.php`, {
method: "POST",
body: DataToSend,
headers: {
"x-auth-token": token,
"x-auth-id": userId,
},
})
.then((response) => {
return response.text();
})
.then((results) => {
try {
if (results == "1") {
return {
Success: true,
Message: `Successfuly Nominated`,
};
} else {
return {
Success: false,
Message: `Unable To Nominate`,
Error: results,
};
}
} catch {
return {
Success: false,
Message: `Couldn't fetch data, server may be down temporarily`,
};
}
})
.catch((err) => {
return {
Success: false,
Message: err,
};
});
}
module.exports = nominateSuper;
| 20.516484 | 73 | 0.519014 |
433eaaffbcb7385f0fca20f3ae2cd022023644d2 | 10,571 | js | JavaScript | documentation/search/all_11.js | nonlocalmodels/nonlocalmodels.github.io | f3530a405d3b9e7cb02c869015ce5b24b9cb3ae5 | [
"BSL-1.0"
] | null | null | null | documentation/search/all_11.js | nonlocalmodels/nonlocalmodels.github.io | f3530a405d3b9e7cb02c869015ce5b24b9cb3ae5 | [
"BSL-1.0"
] | null | null | null | documentation/search/all_11.js | nonlocalmodels/nonlocalmodels.github.io | f3530a405d3b9e7cb02c869015ce5b24b9cb3ae5 | [
"BSL-1.0"
] | null | null | null | var searchData=
[
['readcelldata_662',['readCellData',['../classrw_1_1reader_1_1VtkReader.html#ac5b14afc5c86757b0f6be7b3a1bf2b0f',1,'rw::reader::VtkReader::readCellData(const std::string &name, std::vector< float > *data)'],['../classrw_1_1reader_1_1VtkReader.html#a5371342f9637608365eb54aed4dca949',1,'rw::reader::VtkReader::readCellData(const std::string &name, std::vector< double > *data)'],['../classrw_1_1reader_1_1VtkReader.html#ae96287a475016eb42c52b8560b64381a',1,'rw::reader::VtkReader::readCellData(const std::string &name, std::vector< util::Point3 > *data)'],['../classrw_1_1reader_1_1VtkReader.html#a6a7762ac3f77f7c76f4a195f16c44ead',1,'rw::reader::VtkReader::readCellData(const std::string &name, std::vector< util::SymMatrix3 > *data)'],['../classrw_1_1reader_1_1VtkReader.html#a23c24d2cd646a18bbaf52ac4dc78739b',1,'rw::reader::VtkReader::readCellData(const std::string &name, std::vector< util::Matrix33 > *data)']]],
['readcells_663',['readCells',['../classrw_1_1reader_1_1VtkReader.html#a5664cf1c2290fcd82cf59ceba9f49f78',1,'rw::reader::VtkReader']]],
['readcomputeinstruction_664',['readComputeInstruction',['../classtools_1_1pp_1_1Compute.html#a1dcac10ff27b995833dbdc1875265c69',1,'tools::pp::Compute']]],
['readcracktipdata_665',['readCrackTipData',['../classtools_1_1pp_1_1Compute.html#a6c426a5d5b5b70cee92bdc7aa1df3f08',1,'tools::pp::Compute']]],
['readcsvfile_666',['readCsvFile',['../namespacerw_1_1reader.html#a4390356883ad2a4f14cb41c69cf3e5ca',1,'rw::reader']]],
['reader_667',['reader',['../namespacerw_1_1reader.html',1,'rw']]],
['readfromfile_668',['readFromFile',['../classfe_1_1Mesh.html#a4c165934ae64f6cf5450805ac54f924c',1,'fe::Mesh']]],
['readmesh_669',['readMesh',['../classrw_1_1reader_1_1MshReader.html#a7d8a018026e3f439899ea3caab7191d6',1,'rw::reader::MshReader::readMesh()'],['../classrw_1_1reader_1_1VtkReader.html#ae5d7706b762ee7af7c5f0165a26e148f',1,'rw::reader::VtkReader::readMesh()']]],
['readmshfile_670',['readMshFile',['../namespacerw_1_1reader.html#ae1d467da75a47df964d46c85fc1cd2ea',1,'rw::reader']]],
['readmshfilepointdata_671',['readMshFilePointData',['../namespacerw_1_1reader.html#a0a732cb07bfea4ab6b044c7621e2ce39',1,'rw::reader']]],
['readmshfilerestart_672',['readMshFileRestart',['../namespacerw_1_1reader.html#afe2a171561ea5b5bb89c8e2afa4323ea',1,'rw::reader']]],
['readnodes_673',['readNodes',['../classrw_1_1reader_1_1MshReader.html#a3c29c35b10628e148f5eda9976997d97',1,'rw::reader::MshReader::readNodes()'],['../classrw_1_1reader_1_1VtkReader.html#a47122a3aced153939640f1d1ae999abd',1,'rw::reader::VtkReader::readNodes()']]],
['readpointdata_674',['readPointData',['../classrw_1_1reader_1_1MshReader.html#a9ae92fd2ba5631983e838b3349ef9d72',1,'rw::reader::MshReader::readPointData(const std::string &name, std::vector< util::Point3 > *data)'],['../classrw_1_1reader_1_1MshReader.html#abee01698ed60dbdfad349832cff46500',1,'rw::reader::MshReader::readPointData(const std::string &name, std::vector< double > *data)'],['../classrw_1_1reader_1_1VtkReader.html#a8da04949df05118cfd030e7523099c3f',1,'rw::reader::VtkReader::readPointData(const std::string &name, std::vector< uint8_t > *data)'],['../classrw_1_1reader_1_1VtkReader.html#ab6336bc7a4afe0f7fccc2dd30e95d33e',1,'rw::reader::VtkReader::readPointData(const std::string &name, std::vector< size_t > *data)'],['../classrw_1_1reader_1_1VtkReader.html#a001acc51d7767a63de29a8bd78a9f4e2',1,'rw::reader::VtkReader::readPointData(const std::string &name, std::vector< int > *data)'],['../classrw_1_1reader_1_1VtkReader.html#ab7ce7f66de9e1a1187445a843cd17544',1,'rw::reader::VtkReader::readPointData(const std::string &name, std::vector< float > *data)'],['../classrw_1_1reader_1_1VtkReader.html#acbd4a7caf9742cb49a87dc32a7442844',1,'rw::reader::VtkReader::readPointData(const std::string &name, std::vector< double > *data)'],['../classrw_1_1reader_1_1VtkReader.html#a821ebab48b01275775d5c7de49a92e7b',1,'rw::reader::VtkReader::readPointData(const std::string &name, std::vector< util::Point3 > *data)'],['../classrw_1_1reader_1_1VtkReader.html#a7b8e4a2231e938ceb071039acae03c0f',1,'rw::reader::VtkReader::readPointData(const std::string &name, std::vector< util::SymMatrix3 > *data)'],['../classrw_1_1reader_1_1VtkReader.html#a9e169663e4b7f42981afa15771719a18',1,'rw::reader::VtkReader::readPointData(const std::string &name, std::vector< util::Matrix33 > *data)']]],
['readvtufile_675',['readVtuFile',['../namespacerw_1_1reader.html#a06f5f2e42c7507cb34b9b7f4817af82b',1,'rw::reader']]],
['readvtufilecelldata_676',['readVtuFileCellData',['../namespacerw_1_1reader.html#ab69467872346984da99aa7ebc17e35d2',1,'rw::reader::readVtuFileCellData(const std::string &filename, const std::string &tag, std::vector< float > *data)'],['../namespacerw_1_1reader.html#aac429b09d673ed8da41a6d321c8dd6e1',1,'rw::reader::readVtuFileCellData(const std::string &filename, const std::string &tag, std::vector< double > *data)'],['../namespacerw_1_1reader.html#af4c9e6d04a36645c42832c6518c70172',1,'rw::reader::readVtuFileCellData(const std::string &filename, const std::string &tag, std::vector< util::Point3 > *data)'],['../namespacerw_1_1reader.html#ae05044466d3b40f7af894db95bdf2609',1,'rw::reader::readVtuFileCellData(const std::string &filename, const std::string &tag, std::vector< util::SymMatrix3 > *data)'],['../namespacerw_1_1reader.html#aaabd35065633ffc6f1bfabcaca345190',1,'rw::reader::readVtuFileCellData(const std::string &filename, const std::string &tag, std::vector< util::Matrix33 > *data)']]],
['readvtufilecells_677',['readVtuFileCells',['../namespacerw_1_1reader.html#a79098cecf3c77855498e8322ec1bf3a8',1,'rw::reader']]],
['readvtufilecelltags_678',['readVtuFileCellTags',['../namespacerw_1_1reader.html#a351e2cd7512e9c8eb18866db1786d217',1,'rw::reader::readVtuFileCellTags()'],['../classrw_1_1reader_1_1VtkReader.html#a566b96c2f901e049f9f0dc42947f39c0',1,'rw::reader::VtkReader::readVtuFileCellTags()']]],
['readvtufilenodes_679',['readVtuFileNodes',['../namespacerw_1_1reader.html#a809c0856da41218f67c61b7d21f68464',1,'rw::reader']]],
['readvtufilepointdata_680',['readVtuFilePointData',['../namespacerw_1_1reader.html#ae911e20d8494352c2de082b59dc88f11',1,'rw::reader::readVtuFilePointData(const std::string &filename, const std::string &tag, std::vector< uint8_t > *data)'],['../namespacerw_1_1reader.html#a8b2fd65cdae6ebbd0620c2dde55b0cd2',1,'rw::reader::readVtuFilePointData(const std::string &filename, const std::string &tag, std::vector< size_t > *data)'],['../namespacerw_1_1reader.html#a9ed4175b553d8a84e9caa21d5367c1bd',1,'rw::reader::readVtuFilePointData(const std::string &filename, const std::string &tag, std::vector< int > *data)'],['../namespacerw_1_1reader.html#a2e0a4925a26e79eb96515a4075210d21',1,'rw::reader::readVtuFilePointData(const std::string &filename, const std::string &tag, std::vector< float > *data)'],['../namespacerw_1_1reader.html#a53c2eff4f3372c0d4c643ffe3168272d',1,'rw::reader::readVtuFilePointData(const std::string &filename, const std::string &tag, std::vector< double > *data)'],['../namespacerw_1_1reader.html#a647a1916f5c27c85d4961fcf973b9d5b',1,'rw::reader::readVtuFilePointData(const std::string &filename, const std::string &tag, std::vector< util::Point3 > *data)'],['../namespacerw_1_1reader.html#acaff43ac5e97f5e080a47bc6910f3454',1,'rw::reader::readVtuFilePointData(const std::string &filename, const std::string &tag, std::vector< util::SymMatrix3 > *data)'],['../namespacerw_1_1reader.html#a625e2d593153c7f7504ee62fa4568569',1,'rw::reader::readVtuFilePointData(const std::string &filename, const std::string &tag, std::vector< util::Matrix33 > *data)']]],
['readvtufilepointtags_681',['readVtuFilePointTags',['../classrw_1_1reader_1_1VtkReader.html#ae8f472ae777603486884d87ba95622c5',1,'rw::reader::VtkReader::readVtuFilePointTags()'],['../namespacerw_1_1reader.html#a47452c6ec3ac459c27a37a89d4ad740c',1,'rw::reader::readVtuFilePointTags(const std::string &filename)']]],
['readvtufilerestart_682',['readVtuFileRestart',['../namespacerw_1_1reader.html#a145f9e3db271e418c25360ed4ab9459a',1,'rw::reader']]],
['removecol_683',['removeCol',['../group__Explicit.html#ga7420df0b97bef4759947b658b2260a57',1,'model::QuasiStaticModel']]],
['removerow_684',['removeRow',['../group__Explicit.html#gae8a1667a95aaeab0d32b6fdcad0f82b2',1,'model::QuasiStaticModel::removeRow(util::VectorXi &vector, size_t rowToRemove)'],['../group__Explicit.html#ga5d66c94e53b43b66e0a8684c37539267',1,'model::QuasiStaticModel::removeRow(util::Matrixij &matrix, size_t rowToRemove)']]],
['removetag_685',['removeTag',['../classinp_1_1Policy.html#a0f6e7399c60681658fa74347c26532c6',1,'inp::Policy']]],
['restart_686',['restart',['../classmodel_1_1FDModel.html#a05cbcddf90fcffc26f86390deaf01230',1,'model::FDModel']]],
['restartdeck_687',['RestartDeck',['../structinp_1_1RestartDeck.html',1,'inp::RestartDeck'],['../structinp_1_1RestartDeck.html#a33fc2224af89023b25b27a532e7d687a',1,'inp::RestartDeck::RestartDeck()']]],
['rnpbond_688',['RNPBond',['../classmaterial_1_1pd_1_1RNPBond.html',1,'material::pd::RNPBond'],['../classmaterial_1_1pd_1_1RNPBond.html#ac1817c8cd0dbd9005eccad098bc76ad4',1,'material::pd::RNPBond::RNPBond()']]],
['rotateacw2d_689',['rotateACW2D',['../namespaceutil_1_1transformation.html#acada277e948679152446dcea24b449f1',1,'util::transformation::rotateACW2D(const std::vector< double > &x, const double &theta)'],['../namespaceutil_1_1transformation.html#aadcaf54bef5d358189f9892f0c6e0731',1,'util::transformation::rotateACW2D(const util::Point3 &x, const double &theta)']]],
['rotatecw2d_690',['rotateCW2D',['../namespaceutil_1_1transformation.html#a10bd0d2065228b5c152f9ff7cb4dddf1',1,'util::transformation::rotateCW2D(const std::vector< double > &x, const double &theta)'],['../namespaceutil_1_1transformation.html#a0df800f31abfc605d4ec8d214322404e',1,'util::transformation::rotateCW2D(const util::Point3 &x, const double &theta)']]],
['run_691',['run',['../classmodel_1_1FDModel.html#ab99804717b8a022da4ba4e4aece2f58b',1,'model::FDModel']]],
['rw_692',['rw',['../namespacerw.html',1,'']]],
['writer_693',['writer',['../namespacerw_1_1writer.html',1,'rw']]]
];
| 293.638889 | 1,889 | 0.773342 |
433f21d6113433839ac6c09b376486c2bb69262f | 4,732 | js | JavaScript | stock/app/src/views/__ListView.js | NextZeus/beyond-webapp | 06b16e0e3e0efd67a8f90c25468b1ed42ced4ac9 | [
"MIT"
] | null | null | null | stock/app/src/views/__ListView.js | NextZeus/beyond-webapp | 06b16e0e3e0efd67a8f90c25468b1ed42ced4ac9 | [
"MIT"
] | null | null | null | stock/app/src/views/__ListView.js | NextZeus/beyond-webapp | 06b16e0e3e0efd67a8f90c25468b1ed42ced4ac9 | [
"MIT"
] | 1 | 2019-06-28T18:46:20.000Z | 2019-06-28T18:46:20.000Z | var _ = require('underscore');
var $ = require('jquery'),
Backbone = require('backbone'),
loadMoreTemplate = _.template(require('../templates/__load-more.tpl'));
Backbone.$ = $;
exports = module.exports = Backbone.View.extend({
el: '#list',
isScrollUp: false, //默认向下滚动
contentH: 0, //向上滚动需要
page: 0,
hasmore: true,
collectionUrl: '',
initialize: function(options) {
this.collectionUrl = (this.collection.url instanceof Function) ? (this.collection.url)() : this.collection.url;
this.collection.on('reset', this.onCollectonAppend, this);
this.collection.on('update', this.onCollectonAppend, this);
this.on('append', this.onModelAppend, this);
this.on('prepend', this.onModelPrepend, this);
this.on('load', this.load, this);
this.on('refresh', this.refresh, this);
this.on('scroll:up', this.scrollUp, this);
this.on('scroll:down', this.scroll, this);
},
load: function() {
this.loaded = true;
this.render();
this.collection.fetch({
reset: true,
xhrFields: {
withCredentials: true
},
});
},
refresh: function(query){
this.$el.empty();
this.collection.url = this.collectionUrl + (query ? ('?' + query) : '');
this.collection.fetch({
reset: true,
xhrFields: {
withCredentials: true
},
});
},
onCollectonAppend: function(collection) {
var that = this;
if (that.isScrollUp) {
collection.each(function(model) {
var itemHtml = that.getNewItemView(model);
that.$el.prepend(itemHtml);
that.collection.add(model, {
at: 0
});
});
that.contentH = that.$el.get(0).scrollHeight - that.contentH;
$('#content').animate({
scrollTop: that.contentH
}, 1);
} else {
collection.each(function(model) {
var itemHtml = that.getNewItemView(model);
that.$el.append(itemHtml);
});
}
},
onModelAppend: function(model) {
var itemHtml = this.getNewItemView(model);
this.$el.append(itemHtml);
return this;
},
onModelPrepend: function(model) {
var itemHtml = this.getNewItemView(model);
this.$el.prepend(itemHtml);
},
nextPage: function() {
var that = this;
if (this.hasmore) {
if (this.$('.load-more').length == 0) {
this.$el.append(loadMoreTemplate({
loading: true
}));
}
++this.page;
this.collection.fetch({
xhrFields: {
withCredentials: true
},
data: {
page: that.page,
},
success: function(collection, response) {
if (that.$('.load-more').length > 0) {
that.$('.load-more').remove();
}
if (collection.length == 0) {
that.$el.append(loadMoreTemplate({
loading: false
}));
that.hasmore = false;
} else {
that.collection.add(collection.models);
that.hasmore = true;
}
},
error: function(collection, response) {
if (that.$('.load-more').length > 0) {
that.$('.load-more').remove();
}
that.hasmore = false;
}
});
} else {
if (that.$('.load-more').length == 0) {
that.$el.append(loadMoreTemplate({
loading: false
}));
}
}
},
prevPage: function() {
var that = this;
if (this.hasmore) {
if (this.$('.load-more').length == 0) {
this.$el.prepend(loadMoreTemplate({
loading: true
}));
}
++this.page;
this.collection.fetch({
xhrFields: {
withCredentials: true
},
data: {
page: that.page,
},
success: function(collection, response) {
if (that.$('.load-more').length > 0) {
that.$('.load-more').remove();
}
if (collection.length == 0) {
that.$el.prepend(loadMoreTemplate({
loading: false
}));
that.hasmore = false;
} else {
that.collection.add(collection.models);
that.hasmore = true;
}
},
error: function(collection, response) {
if (that.$('.load-more').length > 0) {
that.$('.load-more').remove();
}
that.hasmore = false;
}
});
} else {
if (that.$('.load-more').length == 0) {
that.$el.prepend(loadMoreTemplate({
loading: false
}));
}
}
},
scroll: function() {
var scrollTop = $('#content').scrollTop(); //可滚动容器的当前滚动高度
var viewH = $(window).height(); //当前window可见高度
var contentH = this.$el.get(0).scrollHeight; //内容高度
// console.log(contentH + '-' + viewH + '-' + scrollTop);
if (contentH - viewH - scrollTop <= 100) { //到达底部100px时,加载新内容
this.nextPage();
}
},
scrollUp: function() {
var scrollTop = $('#content').scrollTop(); //滚动高度
// var viewH =$(window).height();//当前window可见高度
// var contentH =this.$el.get(0).scrollHeight;//内容高度
// console.log(contentH + '-' + viewH + '-' + scrollTop);
if (scrollTop <= 100) {
this.prevPage();
}
},
render: function() {
return this;
},
}); | 23.425743 | 113 | 0.591082 |
433fb99c2a745ac83474cfba8b0d053a756ac9c4 | 2,386 | js | JavaScript | src/templates/_macros/collection/__test__/collection-content.test.js | cgsunkel/data-hub-frontend | 8f57590e0ff9b8e84cab16dc590c88a4c160234f | [
"MIT"
] | null | null | null | src/templates/_macros/collection/__test__/collection-content.test.js | cgsunkel/data-hub-frontend | 8f57590e0ff9b8e84cab16dc590c88a4c160234f | [
"MIT"
] | 625 | 2021-01-04T17:11:43.000Z | 2022-01-25T09:16:17.000Z | src/templates/_macros/collection/__test__/collection-content.test.js | cgsunkel/data-hub-frontend | 8f57590e0ff9b8e84cab16dc590c88a4c160234f | [
"MIT"
] | null | null | null | const { getMacros } = require('../../../../../test/unit/macro-helper')
const entitiesMacros = getMacros('collection')
describe('Collection macro', () => {
it('should render results summary component', () => {
const component = entitiesMacros.renderToDom('CollectionContent')
expect(component.tagName).to.equal('ARTICLE')
expect(component.className).to.equal('c-collection')
expect(component.querySelector('.c-collection__header')).to.exist
expect(
component
.querySelector('.c-collection__result-count')
.parentNode.textContent.trim()
).to.match(/0[\n ]results/)
})
it('should render results summary component with correct count', () => {
const component = entitiesMacros.renderToDom('CollectionContent', {
count: 10,
countLabel: 'cat',
})
expect(
component
.querySelector('.c-collection__result-count')
.parentNode.textContent.trim()
).to.match(/10[\n ]cats/)
})
context('when filters are selected', () => {
beforeEach(() => {
this.component = entitiesMacros.renderToDom('CollectionContent', {
count: 2,
query: {
stage: 's1',
type: 't1',
},
selectedFilters: {
stage: { label: 'Stage', valueLabel: 'Initial' },
type: { label: 'Type', valueLabel: 'Manual' },
},
})
})
it('should render selected filters', () => {
const selectedFilters = this.component.querySelectorAll(
'.c-collection__filter-tag'
)
expect(selectedFilters).to.have.length(2)
})
it('should render remove filters link', () => {
expect(this.component.querySelector('.c-collection__filter-remove-all'))
.to.exist
})
})
context('when an action button is present', () => {
beforeEach(() => {
this.component = entitiesMacros.renderToDom('CollectionContent', {
count: 2000,
actionButtons: {
action: {
prop: 1,
},
},
})
})
it('should render an action button header', () => {
const actionHeader = this.component.querySelectorAll(
'.c-collection__header-actions'
)
const actionButton = this.component.querySelectorAll(
'.govuk-button--secondary'
)
expect(actionHeader).to.exist
expect(actionButton).to.exist
})
})
})
| 28.404762 | 78 | 0.594719 |
4340c9318aa50f0d5143fe4bda3cd8a59813cd2a | 407 | js | JavaScript | examples/6-isomorphic-react-styled-components-backbone-pug-webpack/apps/styled-components/components/App.js | zephraph/stitch | f219102e731416baf45dd62188e789950ee6e8e7 | [
"MIT"
] | 11 | 2017-08-28T17:50:47.000Z | 2022-02-24T01:23:21.000Z | examples/6-isomorphic-react-styled-components-backbone-pug-webpack/apps/styled-components/components/App.js | zephraph/stitch | f219102e731416baf45dd62188e789950ee6e8e7 | [
"MIT"
] | 118 | 2017-08-26T01:40:25.000Z | 2021-12-10T20:38:35.000Z | examples/6-isomorphic-react-styled-components-backbone-pug-webpack/apps/styled-components/components/App.js | zephraph/stitch | f219102e731416baf45dd62188e789950ee6e8e7 | [
"MIT"
] | 4 | 2018-04-26T17:48:27.000Z | 2021-06-22T20:09:14.000Z | import React from 'react'
import styled from 'styled-components'
const Layout = styled.div`
background: rgb(233, 255, 205);
border: 1px solid black;
height: 200px;
padding: 50px;
`
export default function App (props, context) {
const { title } = props
return (
<Layout>
<h3>
{title}
</h3>
<p>
Hello from Styled Components!
</p>
</Layout>
)
}
| 16.28 | 46 | 0.589681 |
4340eb45346d5e16ee8c421416d08dce4fab7f87 | 1,704 | js | JavaScript | assets/js/data/swcache.js | Karol-Hotar/onlinehilfe-eltako | a3b67c2203c354d0307dfdf067c052ea6776cef4 | [
"MIT"
] | null | null | null | assets/js/data/swcache.js | Karol-Hotar/onlinehilfe-eltako | a3b67c2203c354d0307dfdf067c052ea6776cef4 | [
"MIT"
] | null | null | null | assets/js/data/swcache.js | Karol-Hotar/onlinehilfe-eltako | a3b67c2203c354d0307dfdf067c052ea6776cef4 | [
"MIT"
] | null | null | null | ---
layout: compress
# The list to be cached by PWA
---
const resource = [
/* --- CSS --- */
'{{ "/assets/css/style.css" | relative_url }}',
/* --- JavaScripts --- */
{% assign js_path = "/assets/js" | relative_url %}
'{{ js_path }}/dist/home.min.js',
'{{ js_path }}/dist/page.min.js',
'{{ js_path }}/dist/post.min.js',
'{{ js_path }}/dist/categories.min.js',
'{{ js_path }}/data/search.json',
'{{ "/app.js" | relative_url }}',
'{{ "/sw.js" | relative_url }}',
/* --- HTML --- */
'{{ "/homepage.html" | relative_url }}',
'{{ "/404.html" | relative_url }}',
{% for tab in site.tabs %}
'{{ tab.url | relative_url }}',
{% endfor %}
/* --- Favicons --- */
{% assign favicon_path = "/assets/img/favicons" | relative_url %}
'{{ favicon_path }}/android-chrome-192x192.png',
'{{ favicon_path }}/android-chrome-512x512.png',
'{{ favicon_path }}/apple-touch-icon.png',
'{{ favicon_path }}/favicon-16x16.png',
'{{ favicon_path }}/favicon-32x32.png',
'{{ favicon_path }}/favicon.ico',
'{{ favicon_path }}/mstile-150x150.png',
'{{ favicon_path }}/site.webmanifest',
'{{ favicon_path }}/browserconfig.xml'
];
/* The request url with below domain will be cached */
const allowedDomains = [
{% if site.google_analytics.id != '' %}
'www.googletagmanager.com',
'www.google-analytics.com',
{% endif %}
'{{ site.url | split: "//" | last }}',
'fonts.gstatic.com',
'fonts.googleapis.com',
'cdn.jsdelivr.net',
'polyfill.io'
];
/* Requests that include the following path will be banned */
const denyUrls = [
{% if site.google_analytics.pv.cache_path %}
'{{ site.google_analytics.pv.cache_path | absolute_url }}'
{% endif %}
];
| 26.215385 | 67 | 0.593897 |
4341b371fd5ff1059375a9bb3394a6b6b60b9603 | 2,610 | js | JavaScript | miniprogram/pages/cloudEntrance/ChineseTestCloud/IndexCHNCloud/IndexCHNCloud.js | CodeShockWave/Wechat-Mini-Program | 70bc7ab429ce712bdfcc8d2951583d0cda4c6b85 | [
"Apache-2.0"
] | null | null | null | miniprogram/pages/cloudEntrance/ChineseTestCloud/IndexCHNCloud/IndexCHNCloud.js | CodeShockWave/Wechat-Mini-Program | 70bc7ab429ce712bdfcc8d2951583d0cda4c6b85 | [
"Apache-2.0"
] | null | null | null | miniprogram/pages/cloudEntrance/ChineseTestCloud/IndexCHNCloud/IndexCHNCloud.js | CodeShockWave/Wechat-Mini-Program | 70bc7ab429ce712bdfcc8d2951583d0cda4c6b85 | [
"Apache-2.0"
] | null | null | null | //这是起始页
const app = getApp()
//相当于自己服务器上的数据库连接字段 192.172.0.1/database/user
const DBuser = wx.cloud.database().collection("user")
Page({
//初始化变量
data: {
id: '',
password: '',
week: '',
message1:'',
practiceNumber:'',
},
//获取输入值的id user
uesrInput: function (e) {
this.data.id = e.detail.value;
},
//获取输入值的密码 password
passwordInput: function (e) {
this.data.password = e.detail.value;
},
//跳转到体验主页
visitorLogin: function () {
wx.navigateTo({
url: '../vspCHNCloud/vspCHNCloud'
})
},
//登陆操作
userLoginDB: function () {
var that = this;
//打印账号和密码
console.log('输入账号为: ', this.data.id);
console.log('输入密码为: ', this.data.password);
//条件查询,判断账号密码是否对应
DBuser.where({
Id:this.data.id,
}).get({
success(res){
if(res.data[0] != null){
}
else{
console.log('失败,账号错误')
//账号密码错误后弹出提示
wx.showToast({
title: 'Account or password error login failed',
icon: 'none',
duration:1500,
mask:true
})
}
},
})
DBuser.where({
Id:this.data.id,
password:this.data.password,
}).get({
success(res){
if(res.data[0] != null){
console.log("欢迎登录",res.data[0].Id)
app.globalData.id = that.data.id
that.getServerPracticeNo(app.globalData.id)
wx.showToast({
title: 'Welcome',
icon: 'success',
duration:1500,
mask:true
})
}
else{
console.log('失败,密码错误')
wx.showToast({
title: 'Welcome',
icon: 'none',
duration:1500,
mask:true
})
}
},
})
},
getServerPracticeNo: function (e) {
wx.cloud.callFunction({
//调用云函数名
name: 'getPracticeNo',
// 传给云函数的参数
data: {
id: app.globalData.id,
},
success: function(res) {
//console.log(res.result.data.list[0].practiceNo)
app.globalData.practiceNumber = res.result.data.list[0].practiceNo;
console.log(app.globalData.practiceNumber)
//根据剩余测试次数选择跳转的页面
if(app.globalData.practiceNumber > 0){
wx.navigateTo({
url: '../smpCHNCloud/smpCHNCloud'
})
}else{
wx.navigateTo({
url: '../smp2CHNCloud/smp2CHNCloud'
})
}
},
fail: console.error
})
},
})
| 18.913043 | 75 | 0.48659 |
43420c8405c7726559461d919ce7fc089139e81f | 250 | js | JavaScript | ticket-app/src/constants/routes.js | BramLobbens/TicketingApp | 7e7d89a8d3bf0e7f2062478e95f5ee24d3fb5e54 | [
"MIT"
] | 1 | 2021-01-24T20:20:08.000Z | 2021-01-24T20:20:08.000Z | ticket-app/src/constants/routes.js | BramLobbens/TicketingApp | 7e7d89a8d3bf0e7f2062478e95f5ee24d3fb5e54 | [
"MIT"
] | null | null | null | ticket-app/src/constants/routes.js | BramLobbens/TicketingApp | 7e7d89a8d3bf0e7f2062478e95f5ee24d3fb5e54 | [
"MIT"
] | null | null | null | export const HOME = "/";
export const TICKETS = "/tickets";
export const MY_TICKETS = "/mytickets";
export const CREATE_TICKET = "/createticket";
export const SIGN_UP = "/signup";
export const SIGN_IN = "/signin";
export const SIGN_OUT = "/signout";
| 31.25 | 45 | 0.72 |
43434af248e38e9b8f5dac7c80e2a9e7fe5c4c9f | 244 | js | JavaScript | src/pages/Error404.js | MauricioCarmona/100tifico | c5b6adfcf5bbf7e05158d85bb306655de3242e63 | [
"MIT"
] | null | null | null | src/pages/Error404.js | MauricioCarmona/100tifico | c5b6adfcf5bbf7e05158d85bb306655de3242e63 | [
"MIT"
] | 4 | 2021-08-31T20:04:57.000Z | 2022-02-19T04:50:27.000Z | src/pages/Error404.js | MauricioCarmona/100tifico | c5b6adfcf5bbf7e05158d85bb306655de3242e63 | [
"MIT"
] | null | null | null | const Error404 = () => {
const view = `
<div class="Error404">
<h2>Error 404</h2>
<p>Lo sentimos, esta página no existe o fue eliminada.</p>
</div>
`;
return view;
};
export default Error404; | 22.181818 | 70 | 0.520492 |
4343ded5b93c278fa09ce5684021b5e1c60a1f9a | 132 | js | JavaScript | public/javascripts/search.js | chandl/ZAStream | 0770b49963c4e16a6b6f99782eb88931690b8d4c | [
"Apache-2.0"
] | null | null | null | public/javascripts/search.js | chandl/ZAStream | 0770b49963c4e16a6b6f99782eb88931690b8d4c | [
"Apache-2.0"
] | null | null | null | public/javascripts/search.js | chandl/ZAStream | 0770b49963c4e16a6b6f99782eb88931690b8d4c | [
"Apache-2.0"
] | null | null | null | function search(){
var searchTerm = document.getElementById("searchInput").value;
window.location = "/search/"+searchTerm;
} | 33 | 66 | 0.719697 |
4344496e7c22e8eeb4fc644affac4822b481449a | 295 | js | JavaScript | core-ui/src/components/Predefined/Details/Application/CreateBindingModal/createApplicationBinding.js | dariadomagala/busola | 47c7cf1198971cfbb6903d201e0beacce2a5308a | [
"Apache-2.0"
] | 12 | 2021-03-12T06:28:33.000Z | 2022-03-07T09:35:54.000Z | core-ui/src/components/Predefined/Details/Application/CreateBindingModal/createApplicationBinding.js | parostatkiem/busola | edf8b4bfd81dfc94d5502745ec0a02a1431e611d | [
"Apache-2.0"
] | 1,066 | 2021-03-15T10:32:45.000Z | 2022-03-31T12:11:33.000Z | core-ui/src/components/Predefined/Details/Application/CreateBindingModal/createApplicationBinding.js | parostatkiem/busola | edf8b4bfd81dfc94d5502745ec0a02a1431e611d | [
"Apache-2.0"
] | 25 | 2021-03-15T08:34:59.000Z | 2022-03-30T11:25:51.000Z | export function createApplicationBinding(application, namespace, services) {
return {
apiVersion: 'applicationconnector.kyma-project.io/v1alpha1',
kind: 'ApplicationMapping',
metadata: {
name: application.metadata.name,
namespace,
},
spec: { services },
};
}
| 24.583333 | 76 | 0.681356 |
43451937d20e0277a97841ffcd33d91085152ac1 | 5,979 | js | JavaScript | steffslip.js | phamhoaithuong/thuongphps04032 | 35e8c7f80439f272cbcaf2ea319e112c5c36dbac | [
"Apache-2.0"
] | null | null | null | steffslip.js | phamhoaithuong/thuongphps04032 | 35e8c7f80439f272cbcaf2ea319e112c5c36dbac | [
"Apache-2.0"
] | null | null | null | steffslip.js | phamhoaithuong/thuongphps04032 | 35e8c7f80439f272cbcaf2ea319e112c5c36dbac | [
"Apache-2.0"
] | null | null | null | /*================================================================
ORC_JS, JavaScript Class Framework
version:3.00.70809
Copyright 2007 by SourceTec Software Co.,LTD
For more information, see:www.sothink.com
================================================================*/
if(typeof _STNS!="undefined"&&_STNS.EFFECT&&!_STNS.EFFECT.CEffSlip){with(_STNS.EFFECT){_STNS.EFFECT.CEffSlip=_STNS.Class(_STNS.EFFECT.CEffect);CEffSlip.register("EFFECT/CEffect>CEffSlip");CEffSlip.construct=function(n,id,w,_4,o){this._tTid=0;this._iX=0;this._iY=0;this._iCurWid=0;this._iCurHei=0;this._bShow=0;this._iGid=-1;this._iFms=12;this._iDt=50;this._iDx=0;this._iDy=0;this.iDir=2;this.iDur=_4;with(_STNS.EFFECT.CEffSlip){this.fbApply=fbApply;this.fbPlay=fbPlay;this.fbStop=fbStop;this.fbSet=fbSet;this.fbSetStyle=fbSetStyle;this.fbShow=fbShow;this.fbHide=fbHide;this.faParse=faParse;}if(o){this.fbSetStyle(o);}};CEffSlip.fbSet=function(){var _r=_STNS,e,n;if(e=_r.fdmGetEleById(this.sDmId,this.dmWin)){if(e.style.position!="absolute"){return false;}if(this._iGid==-1){n=_r.EFFECT.CEffSlip._aGlobal.length;_r.EFFECT.CEffSlip._aGlobal.push(this);this._iGid=n;}this._iStat=0;return true;}return false;};CEffSlip.fbDel=function(){if(this._iGid!=-1){delete _STNS.EFFECT.CEffSlip._aGlobal[this._iGid];}this._iStat=-1;return true;};CEffSlip.fbApply=function(){var _r=_STNS;if(!_r.EFFECT.CEffSlip._aGlobal[this._iGid]){_r.EFFECT.CEffSlip._aGlobal[this._iGid]=this;}if(e=_r.fdmGetEleById(this.sDmId,this.dmWin)){this._iCurWid=_r.fiGetEleWid(e);this._iCurHei=_r.fiGetEleHei(e);this._iDt=Math.ceil(this.iDur/this._iFms);this._iDx=Math.floor(this._iCurWid/this._iFms);this._iDy=Math.floor(this._iCurHei/this._iFms);}this._iStat=1;return true;};CEffSlip.fbPlay=function(){var e=_STNS.fdmGetEleById(this.sDmId,this.dmWin);if(!this._bShow){if(!e.style.clip||e.style.clip.indexOf("auto")!=-1){e.style.clip="rect(0px "+this._iCurWid+"px "+this._iCurHei+"px 0px)";}this.fbHide();}else{if(!e.style.clip||e.style.clip.indexOf("auto")!=-1){e.style.clip="rect("+this._iCurHei+"px 0px 0px "+this._iCurWid+"px)";}this.fbShow();}this._iStat=2;return true;};CEffSlip._aGlobal=[];CEffSlip.fbStop=function(){if(this._iStat>0){clearTimeout(this._tTid);var e=_STNS.fdmGetEleById(this.sDmId,this.dmWin);e.style.left=this._iX+"px";e.style.top=this._iY+"px";e.style.clip="rect(auto auto auto auto)";if(this._bShow){e.style.visibility="visible";}else{e.style.visibility="hidden";}delete _STNS.EFFECT.CEffSlip._aGlobal[this._iGid];this._iStat=0;}return true;};CEffSlip.fbSetStyle=function(s){var _r=_STNS,ss;ss=_r.foCss2Style(s);if(ss["visibility"]=="hidden"){this._bShow=0;}else{if(ss["visibility"]=="visible"){this._bShow=1;}}if(ss["left"]){this._iX=parseInt(ss["left"]);}if(ss["top"]){this._iY=parseInt(ss["top"]);}if(ss["direction"]){this.iDir=parseInt(ss["direction"]);}};CEffSlip.fbShow=function(t){var e=_STNS.fdmGetEleById(this.sDmId,this.dmWin);if(!t){var cc=this.faParse(e.style.clip);switch(this.iDir){case 1:t=Math.floor(cc[1]/this._iDx);e.style.top=this._iY+"px";break;case 2:t=Math.floor((this._iCurWid-cc[3])/this._iDx);e.style.top=this._iY+"px";break;case 3:t=Math.floor(cc[2]/this._iDy);e.style.left=this._iX+"px";break;case 4:t=Math.floor((this._iCurHei-cc[0])/this._iDy);e.style.left=this._iX+"px";break;}this._tTid=setTimeout("_STNS.EFFECT.CEffSlip._aGlobal["+this._iGid+"].fbShow("+(++t)+")",this._iDt);return true;}if(t>=this._iFms){e.style.left=this._iX+"px";e.style.top=this._iY+"px";e.style.clip="rect(auto auto auto auto)";delete _STNS.EFFECT.CEffSlip._aGlobal[this._iGid];this._iStat=0;return true;}else{switch(this.iDir){case 1:e.style.left=(this._iX+this._iCurWid-t*this._iDx)+"px";e.style.clip="rect(0px "+t*this._iDx+"px "+this._iCurHei+"px 0px)";break;case 2:e.style.left=(this._iX-this._iCurWid+t*this._iDx)+"px";e.style.clip="rect(0px "+this._iCurWid+"px "+this._iCurHei+"px "+(this._iCurWid-t*this._iDx)+"px)";break;case 3:e.style.top=(this._iY+this._iCurHei-t*this._iDy)+"px";e.style.clip="rect(0px "+this._iCurWid+"px "+t*this._iDy+"px 0px)";break;case 4:e.style.top=(this._iY-this._iCurHei+t*this._iDy)+"px";e.style.clip="rect("+(this._iCurHei-t*this._iDy)+"px "+this._iCurWid+"px "+this._iCurHei+"px 0px)";break;}e.style.visibility="visible";}this._tTid=setTimeout("_STNS.EFFECT.CEffSlip._aGlobal["+this._iGid+"].fbShow("+(++t)+")",this._iDt);return true;};CEffSlip.fbHide=function(t){var e=_STNS.fdmGetEleById(this.sDmId,this.dmWin);if(!t){var cc=this.faParse(e.style.clip);switch(this.iDir){case 1:t=Math.floor((this._iCurWid-cc[1])/this._iDx);e.style.top=this._iY+"px";break;case 2:t=Math.floor(cc[3]/this._iDx);e.style.top=this._iY+"px";break;case 3:t=Math.floor((this._iCurHei-cc[2])/this._iDy);e.style.left=this._iX+"px";break;case 4:t=Math.floor(cc[0]/this._iDy);e.style.left=this._iX+"px";break;}this._tTid=setTimeout("_STNS.EFFECT.CEffSlip._aGlobal["+this._iGid+"].fbHide("+(++t)+")",this._iDt);e.style.visibility="visible";return true;}if(t>=this._iFms){e.style.left=this._iX+"px";e.style.top=this._iY+"px";e.style.clip="rect(auto auto auto auto)";e.style.visibility="hidden";delete _STNS.EFFECT.CEffSlip._aGlobal[this._iGid];this._iStat=0;return true;}else{switch(this.iDir){case 1:e.style.left=(this._iX+t*this._iDx)+"px";e.style.clip="rect(0px "+(this._iCurWid-t*this._iDx)+"px "+this._iCurHei+"px 0px)";break;case 2:e.style.left=(this._iX-t*this._iDx)+"px";e.style.clip="rect(0px "+this._iCurWid+"px "+this._iCurHei+"px "+t*this._iDx+"px)";break;case 3:e.style.top=(this._iY+t*this._iDy)+"px";e.style.clip="rect(0px "+this._iCurWid+"px "+(this._iCurHei-t*this._iDy)+"px 0px)";break;case 4:e.style.top=(this._iY-t*this._iDy)+"px";e.style.clip="rect("+t*this._iDy+"px "+this._iCurWid+"px "+this._iCurHei+"px 0px)";break;}this._tTid=setTimeout("_STNS.EFFECT.CEffSlip._aGlobal["+this._iGid+"].fbHide("+(++t)+")",this._iDt);}return true;};CEffSlip.faParse=function(s){var t=s.split(" ");t[0]=parseInt(t[0].substr(5));for(var j=1;j<t.length;j++){t[j]=parseInt(t[j]);}return t;};}}
| 5,979 | 5,979 | 0.720187 |
43456d66fe70657aff77f452e6405da18721bbb9 | 253 | js | JavaScript | src/core/redux/reducer.js | hbehkamal/react-map | fcdce48851190d005c15d5c4c7c499e862ac33eb | [
"MIT"
] | null | null | null | src/core/redux/reducer.js | hbehkamal/react-map | fcdce48851190d005c15d5c4c7c499e862ac33eb | [
"MIT"
] | null | null | null | src/core/redux/reducer.js | hbehkamal/react-map | fcdce48851190d005c15d5c4c7c499e862ac33eb | [
"MIT"
] | null | null | null | import { ZOOM } from "./constants";
const reducer = (state = {}, action) => {
switch (action.type) {
case ZOOM:
return { ...state, zoom: action.zoom, center: action.center };
default:
return state;
}
};
export default reducer;
| 19.461538 | 68 | 0.596838 |
4345e47e60ce5680af2448c9aa774529e4772a97 | 315 | js | JavaScript | example/src/Counter.js | ahonn/react-hot-entry-loader | f49b612e97807c0cea1cb2719cbcc29291be5d3f | [
"MIT"
] | 7 | 2019-07-15T01:05:11.000Z | 2021-02-24T19:35:00.000Z | example/src/Counter.js | ahonn/react-hot-entry-loader | f49b612e97807c0cea1cb2719cbcc29291be5d3f | [
"MIT"
] | 30 | 2019-10-09T03:25:52.000Z | 2021-02-22T21:15:04.000Z | example/src/Counter.js | ahonn/react-hot-entry-loader | f49b612e97807c0cea1cb2719cbcc29291be5d3f | [
"MIT"
] | 1 | 2021-01-20T06:11:38.000Z | 2021-01-20T06:11:38.000Z | import React from 'react';
const Counter = () => {
const [count, setCount] = React.setState(0);
return (
<div>
<p>count: {count}</p>
<button onClick={() => setCount(count + 1)}>+</button>
<button onClick={() => setCount(count - 1)}>-</button>
</div>
);
};
export default Counter;
| 19.6875 | 60 | 0.552381 |
4346255a318e704e4890b30c1def5d1d74a495ee | 4,727 | js | JavaScript | koans/08_SpreadSyntax.js | Captainjack-kor/pre_js_koans | b6a8562eda92323590217b8ba118b8c8adb06b88 | [
"MIT"
] | null | null | null | koans/08_SpreadSyntax.js | Captainjack-kor/pre_js_koans | b6a8562eda92323590217b8ba118b8c8adb06b88 | [
"MIT"
] | null | null | null | koans/08_SpreadSyntax.js | Captainjack-kor/pre_js_koans | b6a8562eda92323590217b8ba118b8c8adb06b88 | [
"MIT"
] | null | null | null | describe('Spread syntax에 대해 학습합니다.', function () {
it('전개 문법(spread syntax)을 학습합니다.', function () {
const spread = [1, 2, 3];
// TODO: 전개 문법을 사용해 테스트 코드를 완성합니다. spread를 지우지 않고 해결할 수 있습니다.
const arr = [0, ...spread, 4];
expect(arr).to.deep.equal([0, 1, 2, 3, 4]);
});
it('빈 배열에 전개 문법을 사용할 경우, 아무것도 전달되지 않습니다.', function () {
const spread = [];
// TODO: 전개 문법을 사용해 테스트 코드를 완성합니다. spread를 지우지 않고 해결할 수 있습니다.
const arr = [0, ...spread, 1];
expect(arr).to.deep.equal([0, 1]);
});
it('여러 개의 배열을 이어붙일 수 있습니다.', function () {
const arr1 = [0, 1, 2];
const arr2 = [3, 4, 5];
const concatenated = [...arr1, ...arr2];
expect(concatenated).to.deep.equal([0, 1, 2, 3, 4, 5]);
// 아래 코드도 같은 동작을 수행합니다.
// arr1.concat(arr2);
});
it('여러 개의 객체를 병합할 수 있습니다.', function () {
const fullPre = {
cohort: 7,
duration: 4,
mentor: 'hongsik',
};
const me = {
time: '0156',
status: 'sleepy',
todos: ['coplit', 'koans'],
};
const merged = {...fullPre,...me};
// 변수 'merged'에 할당된 것은 'obj1'과 'obj2'의 value일까요, reference일까요?
//! merged에 할당된 것은 reference값이다
// 만약 값(value, 데이터)이 복사된 것이라면, shallow copy일까요, deep copy일까요?
//! merged에 할당된 것은 주소값이기에 merged에 값을 변경해도 기존 객체의 값은 변함이없다.
//! 고로, 복사된 것은 shallow copy이다.
expect(merged).to.deep.equal({
cohort: 7,
duration: 4,
mentor: 'hongsik',
time: '0156',
status: 'sleepy',
todos: ['coplit', 'koans'],
});
});
it('Rest Parameter는 함수의 인자를 배열로 다룰 수 있게 합니다.', function () {
// 자바스크립트는 (named parameter를 지원하지 않기 때문에) 함수 호출 시 인자의 순서가 중요합니다.
function returnFirstArg(firstArg) {
return firstArg;
}
expect(returnFirstArg('first', 'second', 'third')).to.equal('first');
function returnSecondArg(firstArg, secondArg) {
return secondArg;
}
expect(returnSecondArg('only give first arg')).to.equal(undefined);
// rest parameter는 spread syntax를 통해 간단하게 구현됩니다.
function getAllParamsByRestParameter(...args) {
return args;
}
// arguments를 통해 '비슷하게' 함수의 인자들을 다룰 수 있습니다. (spread syntax 도입 이전)
// arguments는 모든 함수의 실행 시 자동으로 생성되는 '객체'입니다.
function getAllParamsByArgumentsObj() {
return arguments;
}
const restParams = getAllParamsByRestParameter('first', 'second', 'third');
const argumentsObj = getAllParamsByArgumentsObj('first', 'second', 'third');
expect(restParams).to.deep.equal(['first', 'second', 'third']);
expect(Object.keys(argumentsObj)).to.deep.equal(['0','1','2']);
expect(Object.values(argumentsObj)).to.deep.equal(['first', 'second', 'third']);
// argumetns와 rest parmeter를 통해 배열로 된 인자(args)의 차이를 확인하시기 바랍니다.
expect(restParams === argumentsObj).to.deep.equal(false);
expect(typeof restParams).to.deep.equal('object');
expect(typeof argumentsObj).to.deep.equal('object');
expect(Array.isArray(restParams)).to.deep.equal(true);
//!rest parameter
expect(Array.isArray(argumentsObj)).to.deep.equal(false);
//!spread syntax
const argsArr = Array.from(argumentsObj);
expect(Array.isArray(argsArr)).to.deep.equal(true);
//!Array.from을 통해 배열을 다시 만들어서 저장해도 배열로써 인정해준다.
expect(argsArr).to.deep.equal(['first', 'second', 'third']);
expect(argsArr === restParams).to.deep.equal(false);
//!복사된 값은 얕은 복사이기때문에 주소값만 참조하게 됨.
//!기존의 값과 같을 수가 없다.
});
it('Rest Parameter는 인자의 수가 정해져 있지 않은 경우에도 유용하게 사용할 수 있습니다.', function () {
function sum(...nums) {
let sum = 0;
for (let i = 0; i < nums.length; i++) {
sum = sum + nums[i];
}
return sum;
}
expect(sum(1, 2, 3)).to.equal(6);
//! ...nums에 의하여 1,2,3이 차례대로 다 들어가서 sum연산을 거치게된다.
expect(sum(1, 2, 3, 4)).to.equal(10);
});
it('Rest Parameter는 인자의 일부에만 적용할 수도 있습니다.', function () {
// rest parameter는 항상 배열입니다.
//! *****겁나중요하다 ****
//! 신텍스랑 햇갈리지말게나 !!
function getAllParams(required1, required2, ...args) {
return [required1, required2, args];
}
expect(getAllParams(123)).to.deep.equal([123,undefined,[]]);
function makePizza(dough, name, ...toppings) {
const order = `You ordered ${name} pizza with ${dough} dough and ${toppings.length} extra toppings!`;
return order;
}
expect(makePizza('original')).to.equal('You ordered undefined pizza with original dough and 0 extra toppings!');
//! length 연산자는 값을 못받아도 0은 뿌린다 '_';
expect(makePizza('thin', 'pepperoni')).to.equal('You ordered pepperoni pizza with thin dough and 0 extra toppings!');
expect(makePizza('napoli', 'meat', 'extra cheese', 'onion', 'bacon')).to.equal('You ordered meat pizza with napoli dough and 3 extra toppings!');
});
});
| 34.253623 | 149 | 0.611805 |
4346294bc89ff21876fd26f046c849a4ff209803 | 2,251 | js | JavaScript | web/application/src/main/java/org/artifactory/addon/wicket/disabledaddon/AddonNeededBehavior.js | alancnet/artifactory | 7ac3ea76471a00543eaf60e82b554d8edd894c0f | [
"Apache-2.0"
] | 3 | 2016-01-21T11:49:08.000Z | 2018-12-11T21:02:11.000Z | web/application/src/main/java/org/artifactory/addon/wicket/disabledaddon/AddonNeededBehavior.js | alancnet/artifactory | 7ac3ea76471a00543eaf60e82b554d8edd894c0f | [
"Apache-2.0"
] | null | null | null | web/application/src/main/java/org/artifactory/addon/wicket/disabledaddon/AddonNeededBehavior.js | alancnet/artifactory | 7ac3ea76471a00543eaf60e82b554d8edd894c0f | [
"Apache-2.0"
] | 5 | 2015-12-08T10:22:21.000Z | 2021-06-15T16:14:00.000Z | /*
* Artifactory is a binaries repository manager.
* Copyright (C) 2012 JFrog Ltd.
*
* Artifactory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Artifactory is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Artifactory. If not, see <http://www.gnu.org/licenses/>.
*/
var DisabledAddon = {
create: function (id, position, iconClassName, addon, serverToken) {
// create only once
var node = dojo.byId(id);
if (node.DisabledAddon) {
return;
}
node.DisabledAddon = true;
// add tooltip
var widgets = DojoUtils.instantiate(id + '_bubble');
if (position) {
widgets[0].position = position;
}
// add icon
var icon = document.createElement('span');
icon.className = iconClassName;
node.insertBefore(icon, node.firstChild);
// Set link css class
this.setChecked(dojo.byId(id + '_hide'), addon, serverToken);
},
toogle: function (link, id, serverToken, addon) {
// toggle show/hide
if (!link.className.match(/checked/)) {
dojo.cookie('addon-' + addon, serverToken, {expires: 3650, path: artApp});
} else {
dojo.cookie('addon-' + addon, null, {expires: -1, path: artApp});
}
this.setChecked(link, addon, serverToken);
// sync className
dojo.byId(id + '_hide').className = link.className;
return false;
},
setChecked: function (link, addon, serverToken) {
// set show/hide of link
var cookie = dojo.cookie('addon-' + addon);
if (cookie == serverToken) {
link.className = 'hide-link hide-link-checked';
} else {
link.className = 'hide-link';
}
}
};
| 33.597015 | 86 | 0.616171 |
4346590455cc369737ba22505dd3d1a74aace86e | 785 | js | JavaScript | test/unit/instance/to-json.test.js | RobertYoung/sequelize | 783fc80628d422d5c483d571518679a690d31ea1 | [
"MIT"
] | 1 | 2018-10-01T12:02:19.000Z | 2018-10-01T12:02:19.000Z | test/unit/instance/to-json.test.js | Munter/sequelize | 053145cd38c16a62b46bc29ccdd5e7d7c195852a | [
"MIT"
] | null | null | null | test/unit/instance/to-json.test.js | Munter/sequelize | 053145cd38c16a62b46bc29ccdd5e7d7c195852a | [
"MIT"
] | null | null | null | 'use strict';
const chai = require('chai'),
expect = chai.expect,
Support = require('../support'),
DataTypes = require('../../../lib/data-types'),
current = Support.sequelize;
describe(Support.getTestDialectTeaser('Instance'), () => {
describe('toJSON', () => {
it('returns copy of json', () => {
const User = current.define('User', {
name: DataTypes.STRING
});
const user = User.build({ name: 'my-name' });
const json1 = user.toJSON();
expect(json1).to.have.property('name').and.be.equal('my-name');
// remove value from json and ensure it's not changed in the instance
delete json1.name;
const json2 = user.toJSON();
expect(json2).to.have.property('name').and.be.equal('my-name');
});
});
});
| 29.074074 | 75 | 0.592357 |
4346cd8d1ac47c72232e97d72287bd46a86046ed | 2,169 | js | JavaScript | LEETCODE/leetcode-javascript-master/Easy/160-IntersectionofTwoLinkedLists.js | bgoonz/DS-n-Algos-Mega-Archive | 54f41b5a73d67a35bddb911736f0f88c49b7b895 | [
"MIT",
"Unlicense"
] | 1 | 2019-03-18T06:57:33.000Z | 2019-03-18T06:57:33.000Z | Easy/160-IntersectionofTwoLinkedLists.js | Ahmetburhan/LeetCode-JavaScript-AirBNB_style | 045b3040a59c10ad2b206028904271671edb893e | [
"MIT"
] | 25 | 2021-05-02T10:59:18.000Z | 2021-05-14T10:02:22.000Z | Easy/160-IntersectionofTwoLinkedLists.js | Ahmetburhan/LeetCode-JavaScript-AirBNB_style | 045b3040a59c10ad2b206028904271671edb893e | [
"MIT"
] | 1 | 2021-11-26T20:43:19.000Z | 2021-11-26T20:43:19.000Z | /**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* because there is an intersection btw two linkedlists, first align the head of longer list with
* the shorter one's head. Then just keep moving the heads of both linkedlists
* @param {ListNode} headA
* @param {ListNode} headB
* @return {ListNode}
*/
var getIntersectionNode = function(headA, headB) {
var lenA = getLength(headA);
var lenB = getLength(headB);
while(lenA < lenB) {
headB = headB.next;
lenB--;
}
while(lenB < lenA) {
headA = headA.next;
lenA--;
}
while(headA !== headB) {
headA = headA.next;
headB = headB.next;
}
return headA;
};
var getLength = function(listHead) {
var length = 0;
while (listHead) {
length++;
listHead = listHead.next;
}
return length;
};
// 2nd try without knowing the length
var getIntersectionNode = function(headA, headB) {
var intersection = null;
var pa = headA;
var pb = headB;
if (!pa || !pb) {
return intersection;
}
while (pa || pb) {
if (pa && pb && pa.val === pb.val) {
intersection = pa;
}
// this can be replace by pa === pb
while (pa && pb && pa.val === pb.val) {
pa = pa.next;
pb = pb.next;
}
if (pa === null && pb === null) {
break;
} else if (pa === null) {
pa = headB;
} else if (pb === null) {
pb = headA;
} else {
pa = pa.next;
pb = pb.next;
}
}
return intersection;
};
// more concise version, compared to version 2
var getIntersectionNode = function(headA, headB) {
var pa = headA;
var pb = headB;
if (!pa || !pb) {
return null;
}
while (pa && pb && pa !== pb) {
pa = pa.next;
pb = pb.next;
if (pa === pb) {
return pa;
}
if (!pa) {
pa = headB;
}
if (!pb) {
pb = headA;
}
}
return pa;
};
| 19.540541 | 97 | 0.485938 |
4347297d78676f6b326ff7413b53bc17616b8ce8 | 1,207 | js | JavaScript | parsem/utils/assert.js | nalourie/parsem | 447b69dfbd6e7d99dd00c79a0554ef59f705cd1e | [
"MIT"
] | 2 | 2020-04-28T21:35:18.000Z | 2021-03-04T19:19:05.000Z | parsem/utils/assert.js | nalourie/parsem | 447b69dfbd6e7d99dd00c79a0554ef59f705cd1e | [
"MIT"
] | null | null | null | parsem/utils/assert.js | nalourie/parsem | 447b69dfbd6e7d99dd00c79a0554ef59f705cd1e | [
"MIT"
] | 1 | 2020-04-28T21:35:20.000Z | 2020-04-28T21:35:20.000Z | /* utilities for making assertions. */
import { BaseError } from './error';
import {
check,
checkRaises,
suite,
test
} from './test';
/**
* AssertionError
* ==============
* An error thrown when a condition is not satisfied.
*/
class AssertionError extends BaseError {}
/**
* assert : (Boolean, String) => null
* ==================================
* Assert that a condition is satisfied.
*
* Assert that condition is true, if condition is false then throw an
* error with message.
*
* @param {Boolean} condition - a boolean that should be true.
* @param {String} message - the error message to display if condition
* is false.
*/
function assert(condition, message) {
if (!condition) {
throw new AssertionError(message);
}
}
suite('assert', [
test('assert', function () {
checkRaises(
"assert should raise assertion errors when condition is false.",
function(){
assert(false, "This message should print to check the 'assert' function.")
},
AssertionError
);
assert(true, "This message should not print.")
})
]);
export {
AssertionError,
assert
};
| 21.945455 | 90 | 0.589892 |
43476100896f503dc91008acabd66bbbdd51865e | 1,063 | js | JavaScript | src/client.js | wolfoxco/caravel | 4326ad4213aed68e9ead7f1856786be8b80bb9dd | [
"MIT"
] | 4 | 2019-03-05T17:43:20.000Z | 2019-03-11T18:39:53.000Z | src/client.js | wolfoxco/caravel | 4326ad4213aed68e9ead7f1856786be8b80bb9dd | [
"MIT"
] | 3 | 2019-03-06T11:02:45.000Z | 2019-04-04T16:18:36.000Z | src/client.js | wolfoxco/caravel | 4326ad4213aed68e9ead7f1856786be8b80bb9dd | [
"MIT"
] | 2 | 2020-03-04T20:19:53.000Z | 2021-03-29T13:22:04.000Z | require('dotenv').config()
const helpers = require('./helpers')
const path = require('path')
const { Client } = require('pg')
const createClientFromEnv = () => {
const { DATABASE_URL } = process.env
if (DATABASE_URL) {
return new Client({
connectionString: DATABASE_URL
})
} else {
return null
}
}
const createClientFromConfigFile = configFilePath => {
if (configFilePath) {
const filePath = path.resolve(configFilePath)
const config = require(filePath)
return new Client(config)
} else {
return null
}
}
const create = configFilePath => {
return (
createClientFromConfigFile(configFilePath)
|| createClientFromEnv()
|| new Client()
)
}
const connect = async client => {
try {
await client.connect()
console.log('🎆 Connected to DB.')
return true
} catch (error) {
console.error(error)
return false
}
}
Client.prototype.databaseURL = Client.prototype.databaseURL || function() {
return helpers.generateDatabaseURL(this)
}
module.exports = {
create,
connect,
}
| 19.327273 | 75 | 0.661336 |
43486ac9ecd5792a2dff3e386faa4286224b9a05 | 1,024 | js | JavaScript | api/src/routes/sitemap.js | jgretz/jgretzio | 6ef2f257a00a376bd6bc85d0d4d52efd2d8859e0 | [
"MIT"
] | null | null | null | api/src/routes/sitemap.js | jgretz/jgretzio | 6ef2f257a00a376bd6bc85d0d4d52efd2d8859e0 | [
"MIT"
] | 1 | 2020-07-16T23:33:22.000Z | 2020-07-16T23:33:22.000Z | api/src/routes/sitemap.js | jgretz/joshgretzio | 6ef2f257a00a376bd6bc85d0d4d52efd2d8859e0 | [
"MIT"
] | null | null | null | import {GET} from 'node-bits';
import sm from 'sitemap';
import {urlForTitle} from '../services';
import blogArticles from '../blog/map.json';
const SITE = 'https://www.joshgretz.io';
export default class Sitemap {
getRoute(verb) {
if (verb === GET) {
return 'sitemap.xml';
}
return null; // will use the folder structure for all other verbs
}
async get(req, res) {
const sitemap = sm.createSitemap({
hostname: SITE,
urls: [
{url: '/', changefreq: 'weekly', priority: 1.0, img: 'https://i.imgur.com/FrQNZnN.jpg'},
{url: '/about', changefreq: 'monthly', priority: 0.4},
{url: '/resume', changefreq: 'monthly', priority: 0.4},
...blogArticles.map(article => ({
url: urlForTitle(article.title),
changefreq: 'monthly',
priority: 0.4,
img: `${SITE}/api/blog/images?name=${article.image}`,
})),
],
});
res.header('Content-Type', 'text/xml');
res.status(200).send(sitemap.toXML());
}
}
| 27.675676 | 96 | 0.579102 |
43498b931c8c390505aef6ae3c0f958f4318778f | 6,159 | js | JavaScript | node_modules/svg.panzoom.js/dist/svg.panzoom.js | geometor/geometor-explorer | 7f61f9932e9133f86703a849ac967143961c9a2f | [
"MIT"
] | 4 | 2019-10-21T12:59:04.000Z | 2021-11-09T19:03:57.000Z | save_test/SVG Draw_files/svg.panzoom.js | geometor/three-golden-sections | 397f70635f25680a9c3f5d94e28ab432df47251b | [
"MIT"
] | 2 | 2020-06-22T22:50:47.000Z | 2021-05-03T08:03:32.000Z | save_test/SVG Draw_files/svg.panzoom.js | geometor/three-golden-sections | 397f70635f25680a9c3f5d94e28ab432df47251b | [
"MIT"
] | null | null | null | /*!
* svg.panzoom.js - A plugin for svg.js that enables panzoom for viewport elements
* @version 1.1.1
* https://github.com/svgdotjs/svg.panzoom.js#readme
*
* @copyright Ulrich-Matthias Schäfer
* @license MIT
*/;
;(function() {
"use strict";
var normalizeEvent = function(ev) {
if(!ev.touches) {
ev.touches = [{clientX: ev.clientX, clientY: ev.clientY}]
}
return ev.touches
}
SVG.extend(SVG.Doc, SVG.Nested, {
panZoom: function(options) {
this.off('.panZoom')
// when called with false, disable panZoom
if(options === false) return this
options = options || {}
var zoomFactor = options.zoomFactor || 0.03
var zoomMin = options.zoomMin || Number.MIN_VALUE
var zoomMax = options.zoomMax || Number.MAX_VALUE
var lastP, lastTouches, zoomInProgress = false
var wheelZoom = function(ev) {
ev.preventDefault()
// touchpads can give ev.deltaY == 0, which skews the lvl calculation
if(ev.deltaY == 0) return
var lvl = this.zoom() - zoomFactor * ev.deltaY/Math.abs(ev.deltaY)
, p = this.point(ev.clientX, ev.clientY)
if(lvl > zoomMax)
lvl = zoomMax
if(lvl < zoomMin)
lvl = zoomMin
this.zoom(lvl, p)
}
var pinchZoomStart = function(ev) {
lastTouches = normalizeEvent(ev)
if(lastTouches.length < 2) return
ev.preventDefault()
if(this.fire('pinchZoomStart', {event: ev}).event().defaultPrevented)
return
this.off('touchstart.panZoom', pinchZoomStart)
zoomInProgress = true
SVG.on(document, 'touchmove.panZoom', pinchZoom, this, {passive:false})
SVG.on(document, 'touchend.panZoom', pinchZoomStop, this, {passive:false})
}
var pinchZoomStop = function(ev) {
ev.preventDefault()
zoomInProgress = false
this.fire('pinchZoomEnd', {event: ev})
SVG.off(document,'touchmove.panZoom', pinchZoom)
SVG.off(document,'touchend.panZoom', pinchZoomStop)
this.on('touchstart.panZoom', pinchZoomStart)
}
var pinchZoom = function(ev) {
ev.preventDefault()
var currentTouches = normalizeEvent(ev)
, zoom = this.zoom()
// Distance Formula
var lastDelta = Math.sqrt(
Math.pow(lastTouches[0].clientX - lastTouches[1].clientX, 2) +
Math.pow(lastTouches[0].clientY - lastTouches[1].clientY, 2)
)
var currentDelta = Math.sqrt(
Math.pow(currentTouches[0].clientX - currentTouches[1].clientX, 2) +
Math.pow(currentTouches[0].clientY - currentTouches[1].clientY, 2)
)
var zoomAmount = lastDelta/currentDelta
if((zoom < zoomMin && zoomAmount > 1) || (zoom > zoomMax && zoomAmount < 1))
zoomAmount = 1
var currentFocus = {
x: currentTouches[0].clientX + 0.5 * (currentTouches[1].clientX - currentTouches[0].clientX),
y: currentTouches[0].clientY + 0.5 * (currentTouches[1].clientY - currentTouches[0].clientY)
}
var lastFocus = {
x: lastTouches[0].clientX + 0.5 * (lastTouches[1].clientX - lastTouches[0].clientX),
y: lastTouches[0].clientY + 0.5 * (lastTouches[1].clientY - lastTouches[0].clientY)
}
var p = this.point(currentFocus.x, currentFocus.y)
var focusP = this.point(2*currentFocus.x-lastFocus.x, 2*currentFocus.y-lastFocus.y)
var box = new SVG.Box(this.viewbox()).transform(
new SVG.Matrix()
.translate(p.x, p.y)
.scale(zoomAmount, 0, 0)
.translate(-focusP.x, -focusP.y)
)
this.viewbox(box)
lastTouches = currentTouches
this.fire('zoom', {box: box, focus: focusP})
}
var panStart = function(ev) {
ev.preventDefault()
this.off('mousedown.panZoom', panStart)
lastTouches = normalizeEvent(ev)
if(zoomInProgress) return
this.fire('panStart', {event: ev})
lastP = {x: lastTouches[0].clientX, y: lastTouches[0].clientY }
SVG.on(document, 'mousemove.panZoom', panning, this)
SVG.on(document, 'mouseup.panZoom', panStop, this)
}
var panStop = function(ev) {
ev.preventDefault()
this.fire('panEnd', {event: ev})
SVG.off(document,'mousemove.panZoom', panning)
SVG.off(document,'mouseup.panZoom', panStop)
this.on('mousedown.panZoom', panStart)
}
var panning = function(ev) {
ev.preventDefault()
var currentTouches = normalizeEvent(ev)
var currentP = {x: currentTouches[0].clientX, y: currentTouches[0].clientY }
, p1 = this.point(currentP.x, currentP.y)
, p2 = this.point(lastP.x, lastP.y)
, deltaP = [p2.x - p1.x, p2.y - p1.y]
, box = new SVG.Box(this.viewbox()).transform(new SVG.Matrix().translate(deltaP[0], deltaP[1]))
this.viewbox(box)
lastP = currentP
}
this.on('wheel.panZoom', wheelZoom)
this.on('touchstart.panZoom', pinchZoomStart, this, {passive:false})
this.on('mousedown.panZoom', panStart, this)
return this
},
zoom: function(level, point) {
var style = window.getComputedStyle(this.node)
, width = parseFloat(style.getPropertyValue('width'))
, height = parseFloat(style.getPropertyValue('height'))
, v = this.viewbox()
, zoomX = width / v.width
, zoomY = height / v.height
, zoom = Math.min(zoomX, zoomY)
if(level == null) {
return zoom
}
var zoomAmount = zoom / level
if(zoomAmount === Infinity) zoomAmount = Number.MIN_VALUE
point = point || new SVG.Point(width/2 / zoomX + v.x, height/2 / zoomY + v.y)
var box = new SVG.Box(v)
.transform(new SVG.Matrix()
.scale(zoomAmount, point.x, point.y)
)
if(this.fire('zoom', {box: box, focus: point}).event().defaultPrevented)
return this
return this.viewbox(box)
}
})
SVG.extend(SVG.FX, {
zoom: function(level, point) {
return this.add('zoom', [new SVG.Number(level)].concat(point || []))
}
})
}());
| 28.780374 | 104 | 0.601559 |
4349c0d54a836b5a376224096ca4a7c8d9bb0a94 | 527 | js | JavaScript | src/[bb]/bb_connect/nui/ui.js | cedricalpatch/Badges-n-Bandits | 419494457b53b0a7ac958aed51dab18903410654 | [
"Unlicense"
] | 4 | 2020-05-29T00:41:50.000Z | 2021-11-08T12:47:04.000Z | src/[bb]/bb_connect/nui/ui.js | cedricalpatch/Badges-n-Bandits | 419494457b53b0a7ac958aed51dab18903410654 | [
"Unlicense"
] | null | null | null | src/[bb]/bb_connect/nui/ui.js | cedricalpatch/Badges-n-Bandits | 419494457b53b0a7ac958aed51dab18903410654 | [
"Unlicense"
] | null | null | null |
$(function() {
var connect = $("#connect-menu");
window.addEventListener('message', function(event) {
var item = event.data;
if (item.showconnect) { connect.show(); }
if (item.hideconnect) { connect.hide(); }
});
// Pressing the ESC key with the menu open closes it
document.onkeyup = function (data) {
if (data.which == 27) {
if (connect.is( ":visible" )) {ExitMenu();}
}
};
});
function ExitMenu() {
$.post('http://bb_connect/ConnectMenu', JSON.stringify({action:"exit"}));
}
| 20.269231 | 74 | 0.601518 |
4349da55d23f9d44d5edd1f61ec8b65d1998b3d7 | 2,034 | js | JavaScript | game/no-scroll.js | dsmontgomery/dsmontgomery.github.io | a97cb60022e609f257eec32f49a77ab643e065a0 | [
"MIT"
] | null | null | null | game/no-scroll.js | dsmontgomery/dsmontgomery.github.io | a97cb60022e609f257eec32f49a77ab643e065a0 | [
"MIT"
] | null | null | null | game/no-scroll.js | dsmontgomery/dsmontgomery.github.io | a97cb60022e609f257eec32f49a77ab643e065a0 | [
"MIT"
] | null | null | null | var map = {
cols: 16,
rows: 16,
tsize: 36,
tiles: [
2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2, 2, 2, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2, 2, 2, 2, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2, 2, 1, 1, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 3, 3, 1, 1, 1, 3, 1, 1, 3,
1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 4, 3, 3, 4,
1, 1, 1, 1, 1, 1, 1, 1, 3, 4, 4, 4, 4, 4, 4, 4,
1, 1, 1, 1, 1, 1, 1, 3, 4, 4, 4, 3, 4, 3, 3, 3,
1, 1, 1, 1, 1, 1, 1, 3, 4, 4, 3, 1, 3, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 3, 4, 3, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 3, 4, 4, 3, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 3, 4, 4, 4, 3, 1, 1, 1, 1, 1,
],
getTile: function (col, row) {
return this.tiles[row * map.cols + col];
}
};
Game.load = function () {
return [
Loader.loadImage('tiles', 'http://dsmontgomery.com/game/assets/tileset.png')
];
};
Game.init = function () {
this.tileAtlas = Loader.getImage('tiles');
};
Game.update = function (delta) {
};
Game.render = function () {
for (var c = 0; c < map.cols; c++) {
for (var r = 0; r < map.rows; r++) {
var tile = map.getTile(c, r);
if (tile !== 0) { // 0 => empty tile
this.ctx.drawImage(
this.tileAtlas, // image
(tile - 1) * map.tsize, // source x
0, // source y
map.tsize, // source width
map.tsize, // source height
c * map.tsize, // target x
r * map.tsize, // target y
map.tsize, // target width
map.tsize // target height
);
}
}
}
};
| 33.344262 | 84 | 0.367257 |
434a1520c2a538711d54a2d3fc54b1d0bd5857e2 | 2,246 | js | JavaScript | src/server/standards/stu3/base/StructureMap_Rule.js | dominathan/node-fhir-server-core | 956270260df6bb921721d92c178c41c8accb95a4 | [
"MIT"
] | null | null | null | src/server/standards/stu3/base/StructureMap_Rule.js | dominathan/node-fhir-server-core | 956270260df6bb921721d92c178c41c8accb95a4 | [
"MIT"
] | null | null | null | src/server/standards/stu3/base/StructureMap_Rule.js | dominathan/node-fhir-server-core | 956270260df6bb921721d92c178c41c8accb95a4 | [
"MIT"
] | null | null | null | const BackboneElement = require('./BackboneElement');
const StructureMap_Source = require('./StructureMap_Source');
const StructureMap_Target = require('./StructureMap_Target');
const StructureMap_Dependent = require('./StructureMap_Dependent');
class StructureMap_Rule extends BackboneElement {
constructor ( opts ) {
super();
Object.assign(this, opts);
}
static get __resourceType () {
return 'StructureMap_Rule';
}
// Name of the rule for internal references.
get name () {
return this._name;
}
set name ( new_value ) {
// Throw if new value does not match the pattern
let pattern = /[A-Za-z0-9\-\.]{1,64}/;
if ( !pattern.test(new_value) ) {
throw new Error(`Invalid format for ${new_value} on field name`);
}
this._name = new_value;
}
// Source inputs to the mapping.
get source () {
return this._source;
}
set source ( new_value ) {
this._source = Array.isArray(new_value) ? new_value.map(val => new StructureMap_Source(val)) : [new StructureMap_Source(new_value)];
}
// Content to create because of this mapping rule.
get target () {
return this._target;
}
set target ( new_value ) {
this._target = Array.isArray(new_value) ? new_value.map(val => new StructureMap_Target(val)) : [new StructureMap_Target(new_value)];
}
// Rules contained in this rule.
get rule () {
return this._rule;
}
set rule ( new_value ) {
this._rule = Array.isArray(new_value) ? new_value.map(val => new StructureMap_Rule(val)) : [new StructureMap_Rule(new_value)];
}
// Which other rules to apply in the context of this rule.
get dependent () {
return this._dependent;
}
set dependent ( new_value ) {
this._dependent = Array.isArray(new_value) ? new_value.map(val => new StructureMap_Dependent(val)) : [new StructureMap_Dependent(new_value)];
}
// Documentation for this instance of data.
get documentation () {
return this._documentation;
}
set documentation ( new_value ) {
this._documentation = new_value;
}
toJSON () {
return Object.assign(super.toJSON(), {
name: this._name,
source: this._source,
target: this._target,
rule: this._rule,
dependent: this._dependent,
documentation: this._documentation
});
}
}
module.exports = StructureMap_Rule;
| 24.955556 | 143 | 0.701247 |
434a2e6463483111db3d448af3f666d6e0e41efb | 17,702 | js | JavaScript | frontend_manager/js/utils/PanZoomBox.js | IftachSadeh/ctaOperatorGUI | f6365a86440dd2404da0bc139cd9345eb3dcb566 | [
"MIT"
] | 3 | 2018-08-28T22:44:23.000Z | 2018-10-24T09:16:34.000Z | frontend_manager/js/utils/PanZoomBox.js | IftachSadeh/ctaOperatorGUI | f6365a86440dd2404da0bc139cd9345eb3dcb566 | [
"MIT"
] | 28 | 2020-04-02T14:48:29.000Z | 2021-05-27T08:10:36.000Z | frontend_manager/js/utils/PanZoomBox.js | IftachSadeh/ctaOperatorGUI | f6365a86440dd2404da0bc139cd9345eb3dcb566 | [
"MIT"
] | null | null | null | /* global d3 */
/* global get_d3_node_box */
/* global load_script */
// ------------------------------------------------------------------
//
// ------------------------------------------------------------------
load_script({
source: 'utils_panZoomBox',
script: '/js/utils/common_d3.js',
})
window.PanZoomBox = function() {
let reserved
function get_default_template() {
return {
main: {
tag: 'tag',
g: undefined,
box: {
x: -1,
y: -1,
w: -1,
h: -1,
},
},
interaction: {
wheel: {
shiftKey: {
type: 'zoom',
end: () => {},
},
default: {
type: 'scroll_y',
end: () => {},
},
},
drag: {
default: {
type: 'drag_trans',
start: () => {
console.log('drag_trans_fun_callback-start')
},
drag: () => {
console.log('drag_trans_fun_callback-drag')
},
end: () => {
console.log('drag_trans_fun_callback-end')
},
},
shiftKey: {
type: 'zoom_rect',
start: () => {
console.log('drag_trans_fun_callback-start')
},
drag: () => {
console.log('drag_trans_fun_callback-drag')
},
end: () => {
console.log('drag_trans_fun_callback-end')
},
},
},
db_click: {
default: {
type: 'fit',
end: () => {},
},
},
},
}
}
this.get_default_template = get_default_template
function get_background() {
return reserved.background
}
this.get_background = get_background
function get_content() {
return reserved.content
}
this.get_content = get_content
function get_clipping() {
return reserved.clipping.g
}
this.get_clipping = get_clipping
function get_focus() {
return reserved.focus.relative
}
this.get_focus = get_focus
function init_background() {
reserved.background = reserved.main.g
.append('g')
.attr('id', reserved.main.tag + '_background')
.attr('transform', 'translate('
+ reserved.main.box.x
+ ','
+ reserved.main.box.y
+ ')')
}
function init_clipping() {
reserved.clipping = {
}
reserved.clipping.g = reserved.main.g.append('g')
.attr('transform', 'translate('
+ reserved.main.box.x
+ ','
+ reserved.main.box.y
+ ')')
reserved.clipping.g
.append('defs')
.append('svg:clipPath')
.attr('id', reserved.main.tag + '_clip')
.append('svg:rect')
.attr('id', reserved.main.tag + '_clip-rect')
.attr('x', 0)
.attr('y', 0)
.attr('width', reserved.main.box.w)
.attr('height', reserved.main.box.h)
reserved.clipping.clipBody = reserved.clipping.g
.append('g')
.attr('clip-path', 'url(#' + reserved.main.tag + '_clip)')
}
function init_content() {
reserved.content = reserved.clipping.clipBody
.append('g')
.attr('id', reserved.main.tag + '_content')
}
function init_focus() {
reserved.focus = {
dimension: {
w: reserved.main.box.w,
h: reserved.main.box.h,
},
// PX
absolute: {
zoom: {
kx: 1,
ky: 1,
},
translate: {
x: 0,
y: 0,
},
},
//PERCENT
relative: {
zoom: {
kx: 1,
ky: 1,
},
translate: {
x: 0,
y: 0,
},
},
olds: [],
}
}
function init(opt_in) {
reserved = window.merge_obj(get_default_template(), opt_in)
init_background()
init_clipping()
init_content()
init_focus()
interaction_drag()
interaction_wheel()
interaction_dbclick()
}
this.init = init
function interaction_dbclick() {
reserved.main.g.on('dblclick', function(event) {
event.preventDefault()
set_content_rel({
zoom: {
kx: 1,
ky: 1,
},
trans: {
x: 0,
y: 0,
},
})
})
}
function interaction_wheel() {
let wheel_var = {
x: 0,
y: 0,
key: undefined,
coef_zoom: 1.2,
coef_trans: 0.05,
}
let wheel_function_bib = {
zoom: {
end: function(event) {
var direction = event.wheelDelta < 0 ? 'down' : 'up'
let new_zoom = {
kx: reserved.focus.relative.zoom.kx
* (direction === 'down'
? wheel_var.coef_zoom
: (1 / wheel_var.coef_zoom)),
ky: reserved.focus.relative.zoom.ky
* (direction === 'down'
? wheel_var.coef_zoom
: (1 / wheel_var.coef_zoom)),
}
set_content_rel({
zoom: {
kx: new_zoom.kx,
ky: new_zoom.ky,
},
trans: {
x: reserved.focus.relative.translate.x
- (new_zoom.kx - reserved.focus.relative.zoom.kx) * 0.5,
y: reserved.focus.relative.translate.y
- (new_zoom.ky - reserved.focus.relative.zoom.ky) * 0.5,
},
})
},
},
scroll_y: {
end: function(event) {
var direction = event.wheelDelta < 0 ? 'down' : 'up'
let new_y = reserved.focus.relative.translate.y
+ (direction === 'down'
? wheel_var.coef_trans
: (-wheel_var.coef_trans))
if (new_y < 0) {
new_y = 0
}
if (new_y > (1 - reserved.focus.relative.zoom.ky)) {
new_y = (1 - reserved.focus.relative.zoom.ky)
}
console.log(new_y)
set_content_rel({
trans: {
x: reserved.focus.relative.translate.x,
y: new_y,
},
})
},
},
}
reserved.main.g.on('wheel', function(event) {
for (var key in reserved.interaction.wheel) {
if (event[key]) {
wheel_var.key = key
wheel_function_bib[reserved.interaction.wheel[key].type].end(event)
reserved.interaction.wheel[key].end(event)
return
}
}
key = 'default'
wheel_var.key = key
wheel_function_bib[reserved.interaction.wheel[key].type].end(event)
reserved.interaction.wheel[key].end(event)
})
}
function interaction_drag() {
let drag_var = {
x: 0,
y: 0,
key: undefined,
}
let drag_function_bib = {
zoom_rect: {
start: function(event) {
drag_var.x = event.x
drag_var.y = event.y
reserved.main.g.append('rect')
.attr('id', 'zoom_rect')
.attr('x', drag_var.x)
.attr('y', drag_var.y)
.attr('width', 0)
.attr('height', 0)
.attr('fill', 'none')
.attr('stroke', '#000000')
.attr('stroke-width', 2)
.attr('stroke-dasharray', [ 8, 2 ])
},
drag: function(event) {
reserved.main.g.select('rect#zoom_rect')
.attr('x', event.x > drag_var.x
? drag_var.x
: event.x)
.attr('y', event.y > drag_var.y
? drag_var.y
: event.y)
.attr('width', Math.abs(event.x - drag_var.x))
.attr('height', Math.abs(event.y - drag_var.y))
},
end: function(event) {
reserved.main.g.select('rect#zoom_rect')
.remove()
let vertical_values = {
y: (event.y > drag_var.y
? drag_var.y - reserved.main.box.y
: event.y - reserved.main.box.y) / reserved.main.box.h,
ky: Math.abs(event.y - drag_var.y) / reserved.main.box.h,
}
let horizontal_values = {
x: (event.x > drag_var.x
? drag_var.x - reserved.main.box.x
: event.x - reserved.main.box.x) / reserved.main.box.w,
kx: Math.abs(event.x - drag_var.x) / reserved.main.box.w,
}
// console.log(reserved.focus.relative.zoom)
// console.log(reserved.focus.relative.translate)
// console.log(vertical_values, horizontal_values)
set_content_rel({
zoom: {
kx: reserved.focus.relative.zoom.kx * horizontal_values.kx,
ky: reserved.focus.relative.zoom.ky * vertical_values.ky,
},
trans: {
x: reserved.focus.relative.translate.x
+ (reserved.focus.relative.zoom.kx * horizontal_values.x),
y: reserved.focus.relative.translate.y
+ (reserved.focus.relative.zoom.ky * vertical_values.y),
},
})
drag_var.x = 0
drag_var.y = 0
update_focus()
},
},
drag_trans: {
start: function(event){
drag_var.x = event.x
drag_var.y = event.y
},
drag: function(event) {
set_content_abs({
trans: {
x: reserved.focus.absolute.translate.x
+ (event.x - drag_var.x),
y: reserved.focus.absolute.translate.y
+ (event.y - drag_var.y),
},
})
drag_var.x = event.x
drag_var.y = event.y
},
end: function(event) {
drag_var.x = 0
drag_var.y = 0
},
},
}
reserved.main.g
.on('mouseover', function() {
d3.select(this).style('cursor', 'crosshair')
})
.on('mouseout', function() {
d3.select(this).style('cursor', 'default')
})
let interactions = d3.drag()
.on('start', function(event) {
for (var key in reserved.interaction.drag) {
if (event.sourceEvent[key]) {
drag_var.key = key
drag_function_bib[reserved.interaction.drag[key].type].start()
reserved.interaction.drag[key].start()
return
}
}
key = 'default'
drag_var.key = key
drag_function_bib[reserved.interaction.drag[key].type].start()
reserved.interaction.drag[key].start()
})
.on('drag', function(event) {
drag_function_bib[reserved.interaction.drag[drag_var.key].type].drag()
reserved.interaction.drag[drag_var.key].drag()
})
.on('end', function(event) {
drag_function_bib[reserved.interaction.drag[drag_var.key].type].end()
reserved.interaction.drag[drag_var.key].end()
})
reserved.main.g
.call(interactions)
}
function update_focus() {
reserved.content
.transition()
.duration(100)
.attr('transform', 'scale('
+ reserved.focus.absolute.zoom.kx
+ ','
+ reserved.focus.absolute.zoom.ky
+ '),translate('
+ reserved.focus.absolute.translate.x
+ ','
+ reserved.focus.absolute.translate.y
+ ')')
}
function set_content_rel(opt_in) {
// console.log('opt_in', opt_in)
if (opt_in.zoom) {
reserved.focus.relative.zoom = opt_in.zoom
reserved.focus.absolute.zoom = {
kx: reserved.main.box.w
/ (reserved.focus.relative.zoom.kx
* reserved.focus.dimension.w),
ky: reserved.main.box.h
/ (reserved.focus.relative.zoom.ky
* reserved.focus.dimension.h),
}
}
if (opt_in.trans) {
reserved.focus.relative.translate = opt_in.trans
reserved.focus.absolute.translate = {
x: -reserved.focus.dimension.w
* reserved.focus.relative.translate.x,
y: -reserved.focus.dimension.h
* reserved.focus.relative.translate.y,
}
}
// console.log(reserved.focus.relative)
// console.log(reserved.focus.absolute)
// console.log(reserved.main.box)
// console.log('relative', reserved.focus.relative)
update_focus()
}
this.set_content_rel = set_content_rel
function set_content_abs(opt_in) {
if (opt_in.zoom) {
reserved.focus.absolute.zoom = opt_in.zoom
reserved.focus.relative.zoom = {
kx: reserved.focus.absolute.zoom.kx
* (reserved.main.box.w / reserved.focus.dimension.w),
ky: reserved.focus.absolute.zoom.ky
* (reserved.main.box.h / reserved.focus.dimension.h),
}
}
if (opt_in.trans) {
reserved.focus.absolute.translate = opt_in.trans
reserved.focus.relative.translate = {
x: -reserved.focus.absolute.translate.x / reserved.focus.dimension.w,
y: -reserved.focus.absolute.translate.y / reserved.focus.dimension.h,
}
}
update_focus()
}
this.set_content_abs = set_content_abs
function set_content_dim(dimension) {
let old_dim = reserved.focus.dimension
if (!dimension) {
let content_box = get_d3_node_box(reserved.content)
reserved.focus.dimension = {
w: content_box.width,
h: content_box.height,
}
if (content_box.width === 0) {
reserved.focus.dimension.w = old_dim.w
}
if (content_box.height === 0) {
reserved.focus.dimension.h = old_dim.h
}
if (old_dim.w === content_box.width
&& old_dim.h === content_box.height) {
return
}
}
else {
reserved.focus.dimension = {
w: dimension.w,
h: dimension.h,
}
}
set_content_rel({
zoom: {
kx: (reserved.focus.relative.zoom.kx * old_dim.w)
/ reserved.focus.dimension.w,
ky: (reserved.focus.relative.zoom.ky * old_dim.h)
/ reserved.focus.dimension.h,
},
trans: {
x: (reserved.focus.relative.translate.x * old_dim.w)
/ reserved.focus.dimension.w,
y: (reserved.focus.relative.translate.y * old_dim.h)
/ reserved.focus.dimension.h,
},
})
}
this.set_content_dim = set_content_dim
}
| 35.192843 | 87 | 0.408315 |
434a5044107a113a6301c354c0cbcacecaf7899d | 818 | js | JavaScript | Web_Site/Steel15/login/js/simpleCanvas.js | IoTcat/archive | b43dd5c01c3b38cde97bbdbb87bfc51847303e58 | [
"MIT"
] | 1 | 2020-09-26T03:22:27.000Z | 2020-09-26T03:22:27.000Z | www/yimian.xyz/public_html/student_id/developer/login/js/simpleCanvas.js | IoTcat/ushio-cn | 8eaa890e0e5af3afe2db212becf6a61eb5ce84fa | [
"Apache-2.0"
] | 3 | 2020-06-11T09:20:06.000Z | 2020-06-11T09:30:51.000Z | www/yimian.xyz/public_html/student_id/developer/login/js/simpleCanvas.js | IoTcat/ushio-cn | 8eaa890e0e5af3afe2db212becf6a61eb5ce84fa | [
"Apache-2.0"
] | null | null | null | var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var txt = 'http://security.tencent.com/';
ctx.textBaseline = "top";
ctx.font = "14px 'Arial'";
ctx.textBaseline = "tencent";
ctx.fillStyle = "#f60";
ctx.fillRect(125,1,62,20);
ctx.fillStyle = "#069";
ctx.fillText(txt, 2, 15);
ctx.fillStyle = "rgba(102, 204, 0, 0.7)";
ctx.fillText(txt, 4, 17);
var b64 = canvas.toDataURL();
b64 = b64.replace("data:image/png;base64,","");
var bin = atob(b64).slice(-16,-12);
var simpleCanvas = bin2hex(bin);
function bin2hex(s) {
var i, l, o = '',
n;
s += '';
for (i = 0, l = s.length; i < l; i++) {
n = s.charCodeAt(i)
.toString(16);
o += n.length < 2 ? '0' + n : n;
}
return o;
} | 25.5625 | 50 | 0.52934 |
434a8d16c41174757775626dac75d1403d8a9dbe | 15,523 | js | JavaScript | client/src/sagas/tests/service.test.js | tes/kubernaut | 360d74a2cf31bf399ae75ba4e7ceaf1e9a55c8f3 | [
"MIT"
] | null | null | null | client/src/sagas/tests/service.test.js | tes/kubernaut | 360d74a2cf31bf399ae75ba4e7ceaf1e9a55c8f3 | [
"MIT"
] | 10 | 2021-05-13T16:48:03.000Z | 2022-03-16T07:15:22.000Z | client/src/sagas/tests/service.test.js | tes/kubernaut | 360d74a2cf31bf399ae75ba4e7ceaf1e9a55c8f3 | [
"MIT"
] | 3 | 2021-03-09T14:59:34.000Z | 2022-03-15T17:07:41.000Z | import { put, call, select } from 'redux-saga/effects';
import { push, getLocation, replace } from 'connected-react-router';
import {
initServiceDetailPageSaga,
fetchReleasesDataSaga,
fetchDeploymentsDataSaga,
fetchLatestDeploymentsByNamespaceForServiceSaga,
fetchHasDeploymentNotesSaga,
paginationSaga,
canManageSaga,
fetchTeamForServiceSaga,
} from '../service';
import {
initServiceDetailPage,
fetchReleasesPagination,
fetchReleases,
fetchDeployments,
FETCH_RELEASES_REQUEST,
FETCH_RELEASES_SUCCESS,
FETCH_RELEASES_ERROR,
FETCH_DEPLOYMENTS_REQUEST,
FETCH_DEPLOYMENTS_SUCCESS,
FETCH_DEPLOYMENTS_ERROR,
FETCH_LATEST_DEPLOYMENTS_BY_NAMESPACE_REQUEST,
FETCH_LATEST_DEPLOYMENTS_BY_NAMESPACE_SUCCESS,
FETCH_LATEST_DEPLOYMENTS_BY_NAMESPACE_ERROR,
FETCH_HAS_DEPLOYMENT_NOTES_SUCCESS,
selectReleasesPaginationState,
selectDeploymentsPaginationState,
setReleasesPagination,
setDeploymentsPagination,
setCanManage,
setCurrentService,
clearCurrentService,
selectCurrentService,
FETCH_TEAM_REQUEST,
FETCH_TEAM_SUCCESS,
fetchTeamForService,
} from '../../modules/service';
import {
getReleases,
getDeployments,
getLatestDeploymentsByNamespaceForService,
getCanManageAnyNamespace,
getTeamForService,
} from '../../lib/api';
describe('Service sagas', () => {
describe('releases', () => {
it('should error without required parameters', () => {
[{}, { registry: 'a' }, { service: 'a' }].forEach(payload => {
expect(() => fetchReleasesDataSaga(fetchReleases(payload)).next()).toThrow();
});
});
it('should fetch releases', () => {
const releasesData = { limit: 50, offset: 0, count: 3, items: [1, 2, 3] };
const gen = fetchReleasesDataSaga(fetchReleases({ service: 'a', registry: 'b' }));
expect(gen.next().value).toMatchObject(select(selectReleasesPaginationState));
expect(gen.next({ page: 1, limit: 10 }).value).toMatchObject(put(FETCH_RELEASES_REQUEST()));
expect(gen.next().value).toMatchObject(call(getReleases, { service: 'a', registry: 'b', limit: 10, offset: 0, sort: 'created', order: 'desc' }));
expect(gen.next(releasesData).value).toMatchObject(put(FETCH_RELEASES_SUCCESS({ data: releasesData } )));
expect(gen.next().done).toBe(true);
});
it('should tolerate errors fetching releases', () => {
const error = new Error('ouch');
const gen = fetchReleasesDataSaga(fetchReleases({ service: 'a', registry: 'b', quiet: true }));
expect(gen.next().value).toMatchObject(select(selectReleasesPaginationState));
expect(gen.next({ page: 1, limit: 10 }).value).toMatchObject(put(FETCH_RELEASES_REQUEST()));
expect(gen.next().value).toMatchObject(call(getReleases, { service: 'a', registry: 'b', limit: 10, offset: 0, sort: 'created', order: 'desc' }));
expect(gen.throw(error).value).toMatchObject(put(FETCH_RELEASES_ERROR({ error: error.message })));
expect(gen.next().done).toBe(true);
});
it('should fetch releases pagination', () => {
const releasesData = { limit: 50, offset: 50, count: 3, items: [1, 2, 3] };
const gen = fetchReleasesDataSaga(fetchReleases({ service: 'a', registry: 'b'}));
expect(gen.next().value).toMatchObject(select(selectReleasesPaginationState));
expect(gen.next({ page: 2, limit: 10 }).value).toMatchObject(put(FETCH_RELEASES_REQUEST()));
expect(gen.next().value).toMatchObject(call(getReleases, { service: 'a', registry: 'b', limit: 10, offset: 10, sort: 'created', order: 'desc' }));
expect(gen.next(releasesData).value).toMatchObject(put(FETCH_RELEASES_SUCCESS({ data: releasesData } )));
expect(gen.next().done).toBe(true);
});
});
describe('deployments', () => {
it('should error without required parameters', () => {
[{}, { registry: 'a' }, { service: 'a' }].forEach(payload => {
expect(() => fetchDeploymentsDataSaga(fetchDeployments(payload)).next()).toThrow();
});
});
it('should fetch deployments', () => {
const deploymentsData = { limit: 50, offset: 0, count: 3, items: [1, 2, 3] };
const gen = fetchDeploymentsDataSaga(fetchDeployments({ service: 'a', registry: 'b' }));
expect(gen.next().value).toMatchObject(select(selectDeploymentsPaginationState));
expect(gen.next({ page: 1, limit: 10 }).value).toMatchObject(put(FETCH_DEPLOYMENTS_REQUEST()));
expect(gen.next().value).toMatchObject(call(getDeployments, { service: 'a', registry: 'b', limit: 10, offset: 0, sort: 'created', order: 'desc' }));
expect(gen.next(deploymentsData).value).toMatchObject(put(FETCH_DEPLOYMENTS_SUCCESS({ data: deploymentsData } )));
expect(gen.next().done).toBe(true);
});
it('should tolerate errors fetching deployments', () => {
const error = new Error('ouch');
const gen = fetchDeploymentsDataSaga(fetchDeployments({ service: 'a', registry: 'b', quiet: true }));
expect(gen.next().value).toMatchObject(select(selectDeploymentsPaginationState));
expect(gen.next({ page: 1, limit: 10 }).value).toMatchObject(put(FETCH_DEPLOYMENTS_REQUEST()));
expect(gen.next().value).toMatchObject(call(getDeployments, { service: 'a', registry: 'b', limit: 10, offset: 0, sort: 'created', order: 'desc' }));
expect(gen.throw(error).value).toMatchObject(put(FETCH_DEPLOYMENTS_ERROR({ error: error.message })));
expect(gen.next().done).toBe(true);
});
it('should fetch deployments pagination', () => {
const deploymentsData = { limit: 50, offset: 50, count: 3, items: [1, 2, 3] };
const gen = fetchDeploymentsDataSaga(fetchDeployments({ service: 'a', registry: 'b', page: 2 }));
expect(gen.next().value).toMatchObject(select(selectDeploymentsPaginationState));
expect(gen.next({ page: 2, limit: 10 }).value).toMatchObject(put(FETCH_DEPLOYMENTS_REQUEST()));
expect(gen.next().value).toMatchObject(call(getDeployments, { service: 'a', registry: 'b', limit: 10, offset: 10, sort: 'created', order: 'desc' }));
expect(gen.next(deploymentsData).value).toMatchObject(put(FETCH_DEPLOYMENTS_SUCCESS({ data: deploymentsData } )));
expect(gen.next().done).toBe(true);
});
});
describe('latest deployments', () => {
it('should error without required parameters', () => {
[{}, { registry: 'a' }, { service: 'a' }].forEach(payload => {
expect(() => fetchLatestDeploymentsByNamespaceForServiceSaga(fetchReleasesPagination(payload)).next()).toThrow();
});
});
it('should fetch latest deployments', () => {
const deploymentsData = { items: [1, 2, 3] };
const gen = fetchLatestDeploymentsByNamespaceForServiceSaga(fetchReleasesPagination({ service: 'a', registry: 'b' }));
expect(gen.next().value).toMatchObject(put(FETCH_LATEST_DEPLOYMENTS_BY_NAMESPACE_REQUEST()));
expect(gen.next().value).toMatchObject(call(getLatestDeploymentsByNamespaceForService, { service: 'a', registry: 'b' }));
expect(gen.next(deploymentsData).value).toMatchObject(put(FETCH_LATEST_DEPLOYMENTS_BY_NAMESPACE_SUCCESS({ data: deploymentsData } )));
expect(gen.next().done).toBe(true);
});
it('should tolerate errors fetching latest deployments', () => {
const error = new Error('ouch');
const gen = fetchLatestDeploymentsByNamespaceForServiceSaga(fetchReleasesPagination({ service: 'a', registry: 'b', quiet: true }));
expect(gen.next().value).toMatchObject(put(FETCH_LATEST_DEPLOYMENTS_BY_NAMESPACE_REQUEST()));
expect(gen.next().value).toMatchObject(call(getLatestDeploymentsByNamespaceForService, { service: 'a', registry: 'b' }));
expect(gen.throw(error).value).toMatchObject(put(FETCH_LATEST_DEPLOYMENTS_BY_NAMESPACE_ERROR({ error: error.message })));
expect(gen.next().done).toBe(true);
});
});
describe('pagination', () => {
it('sets releases & deployments pagination in url', () => {
const releasesPagination = { page: 2, limit: 10 };
const deploymentsPagination = { page: 4, limit: 12 };
const gen = paginationSaga(fetchReleasesPagination());
expect(gen.next().value).toMatchObject(select(getLocation));
expect(gen.next({
pathname: '/services/a/b',
search: 'abc=123',
}).value).toMatchObject(select(selectReleasesPaginationState));
expect(gen.next(releasesPagination).value).toMatchObject(select(selectDeploymentsPaginationState));
expect(gen.next(deploymentsPagination).value).toMatchObject(put(push('/services/a/b?abc=123&d-pagination=limit%3D12%26page%3D4&r-pagination=limit%3D10%26page%3D2')));
expect(gen.next().done).toBe(true);
});
});
describe('page init', () => {
it('should push (default) releases pagination state to url on page open if missing', () => {
const initPayload = {
match: { params: { registry: 'a', name: 'b' } },
location: { pathname: '/service/a/b', search: '' },
};
const gen = initServiceDetailPageSaga(initServiceDetailPage(initPayload));
expect(gen.next().value).toMatchObject(put(clearCurrentService()));
expect(gen.next().value).toMatchObject(put(replace('/service/a/b?r-pagination=limit%3D10%26page%3D1')));
expect(gen.next().done).toBe(true);
});
it('should push (default) deployments pagination state to url on page open if missing', () => {
const initPayload = {
match: { params: { registry: 'a', name: 'b' } },
location: { pathname: '/service/a/b', search: 'r-pagination=page%3D1%26limit%3D10' },
};
const gen = initServiceDetailPageSaga(initServiceDetailPage(initPayload));
expect(gen.next().value).toMatchObject(put(clearCurrentService()));
expect(gen.next().value).toMatchObject(put(replace('/service/a/b?d-pagination=limit%3D10%26page%3D1&r-pagination=page%3D1%26limit%3D10')));
expect(gen.next().done).toBe(true);
});
it('should kick off releases & deployments request if url service/registry doesn\'t match state', () => {
const initPayload = {
match: { params: { registry: 'a', name: 'b' } },
location: { pathname: '/service/a/b', search: 'r-pagination=page%3D1%26limit%3D10&d-pagination=page%3D1%26limit%3D10' },
};
const currentStateService = { registryName: 'a', name: 'c' };
const requestPayload = { registry: 'a', service: 'b' };
const gen = initServiceDetailPageSaga(initServiceDetailPage(initPayload));
expect(gen.next().value).toMatchObject(select(selectCurrentService));
expect(gen.next(currentStateService).value).toMatchObject(select(selectReleasesPaginationState));
expect(gen.next({ page: '1', limit: '10' }).value).toMatchObject(put(setReleasesPagination({ page: '1', limit: '10' })));
expect(gen.next().value).toMatchObject(put(fetchReleases(requestPayload)));
expect(gen.next().value).toMatchObject(select(selectDeploymentsPaginationState));
expect(gen.next({ page: '1', limit: '10' }).value).toMatchObject(put(setDeploymentsPagination({ page: '1', limit: '10' })));
expect(gen.next().value).toMatchObject(put(fetchDeployments(requestPayload)));
expect(gen.next().value).toMatchObject(put(fetchTeamForService(requestPayload)));
expect(gen.next().value).toMatchObject(put(setCurrentService(requestPayload)));
expect(gen.next().done).toBe(true);
});
it('should kick off releases request if url pagination doesn\'t match state', () => {
const initPayload = {
match: { params: { registry: 'a', name: 'b' } },
location: { pathname: '/service/a/b', search: 'r-pagination=page%3D2%26limit%3D10&d-pagination=page%3D1%26limit%3D10' },
};
const currentStateService = { registryName: 'a', name: 'b' };
const requestPayload = { registry: 'a', service: 'b' };
const gen = initServiceDetailPageSaga(initServiceDetailPage(initPayload));
expect(gen.next().value).toMatchObject(select(selectCurrentService));
expect(gen.next(currentStateService).value).toMatchObject(select(selectReleasesPaginationState));
expect(gen.next({ page: '1', limit: '10' }).value).toMatchObject(put(setReleasesPagination({ page: '2', limit: '10' })));
expect(gen.next().value).toMatchObject(put(fetchReleases(requestPayload)));
expect(gen.next().value).toMatchObject(select(selectDeploymentsPaginationState));
expect(gen.next({ page: '1', limit: '10' }).done).toBe(true);
});
it('should kick off deployments request if url pagination doesn\'t match state', () => {
const initPayload = {
match: { params: { registry: 'a', name: 'b' } },
location: { pathname: '/service/a/b', search: 'r-pagination=page%3D1%26limit%3D10&d-pagination=page%3D4%26limit%3D10' },
};
const currentStateService = { registryName: 'a', name: 'b' };
const requestPayload = { registry: 'a', service: 'b' };
const gen = initServiceDetailPageSaga(initServiceDetailPage(initPayload));
expect(gen.next().value).toMatchObject(select(selectCurrentService));
expect(gen.next(currentStateService).value).toMatchObject(select(selectReleasesPaginationState));
expect(gen.next({ page: '1', limit: '10' }).value).toMatchObject(select(selectDeploymentsPaginationState));
expect(gen.next({ page: '1', limit: '10' }).value).toMatchObject(put(setDeploymentsPagination({ page: '4', limit: '10' })));
expect(gen.next().value).toMatchObject(put(fetchDeployments(requestPayload)));
expect(gen.next().done).toBe(true);
});
it('should fetch deployment notes', () => {
const releases = {
count: 2,
items: [
{
service: {
name: 'bob',
registry: {
name: 'default',
},
},
version: '123'
},
{
version: '456'
}
],
};
const gen = fetchHasDeploymentNotesSaga(FETCH_RELEASES_SUCCESS({ data: releases }));
expect(gen.next().value).toMatchObject(call(getDeployments, {
sort: 'created',
order: 'desc',
hasNotes: true,
limit: 50,
filters: {
registry: [{ value: releases.items[0].service.registry.name, exact: true }],
service: [{ value: releases.items[0].service.name, exact: true }],
version: [{ value: releases.items.map(r => r.version), exact: true }],
}
}));
expect(gen.next({ a: 1 }).value).toMatchObject(put(FETCH_HAS_DEPLOYMENT_NOTES_SUCCESS({ data: { a: 1 } })));
expect(gen.next().done).toBe(true);
});
});
describe('Can manage', () => {
it('should fetch and set can manage status', () => {
const gen = canManageSaga(initServiceDetailPage());
expect(gen.next().value).toMatchObject(call(getCanManageAnyNamespace));
expect(gen.next({ answer: true }).value).toMatchObject(put(setCanManage(true)));
});
});
describe('Team', () => {
it('should fetch team info for a service', () => {
const registry = 'default';
const service = 'bob';
const team = { name: 'abc', services: [{ name: service }]};
const gen = fetchTeamForServiceSaga(fetchTeamForService({ registry, service }));
expect(gen.next().value).toMatchObject(put(FETCH_TEAM_REQUEST()));
expect(gen.next().value).toMatchObject(call(getTeamForService, { registry, service}));
expect(gen.next(team).value).toMatchObject(put(FETCH_TEAM_SUCCESS({ data: team })));
});
});
});
| 49.594249 | 172 | 0.663081 |
434ada24edfa71745d5510d649b1c47546b7bd61 | 2,518 | js | JavaScript | tests/tests.js | KaiRo-at/truffle-flattener | 6935a19a6811130db5370d5ccdcc5a0590630311 | [
"MIT"
] | 107 | 2020-06-22T07:21:40.000Z | 2021-07-13T05:09:10.000Z | tests/tests.js | KaiRo-at/truffle-flattener | 6935a19a6811130db5370d5ccdcc5a0590630311 | [
"MIT"
] | 1 | 2020-05-24T10:35:42.000Z | 2020-05-24T10:35:42.000Z | tests/tests.js | KaiRo-at/truffle-flattener | 6935a19a6811130db5370d5ccdcc5a0590630311 | [
"MIT"
] | 34 | 2020-08-10T09:10:17.000Z | 2020-08-10T22:08:35.000Z | const assert = require("chai").assert;
const flatten = require("../index");
function getFilesInFlattenedOrder(flattenOutput) {
const regex = /\/\/ File: (.*)/;
return flattenOutput
.split(/[\n\r]+/)
.filter(line => line.match(regex))
.map(line => line.match(regex)[1]);
}
describe("flattening", function() {
before(function() {
process.chdir(__dirname);
});
it("Should include the parent if the only entry is the child", async function() {
const files = getFilesInFlattenedOrder(
await flatten(["./contracts/child.sol"])
);
assert.include(files, "contracts/parent.sol");
});
it("Should give a topological order of the files and dependencies", async function() {
const files = getFilesInFlattenedOrder(
await flatten(["./contracts/child.sol"])
);
assert.deepEqual(files, [
"openzeppelin-solidity/contracts/access/Roles.sol",
"contracts/parent.sol",
"openzeppelin-solidity/contracts/access/roles/PauserRole.sol",
"contracts/child.sol"
]);
});
it("Shouldn't repeat contracts", async function() {
const files = getFilesInFlattenedOrder(
await flatten([
"./contracts/child.sol",
"./contracts/child.sol",
"./contracts/parent.sol"
])
);
assert.deepEqual(files, [
"openzeppelin-solidity/contracts/access/Roles.sol",
"contracts/parent.sol",
"openzeppelin-solidity/contracts/access/roles/PauserRole.sol",
"contracts/child.sol"
]);
});
it("Should fail if there's a cycle", async function() {
try {
await flatten(["./contracts/cycle1.sol"]);
assert.fail("This should have failed");
} catch (error) {
assert.include(error.message, "There is a cycle in the dependency");
}
});
it("Should leave multiple solidity pragmas", async function() {
const flattened = await flatten([
"./contracts/child.sol",
"./contracts/child.sol",
"./contracts/parent.sol"
]);
assert.include(flattened, "pragma solidity ^0.5.0;");
assert.include(flattened, "pragma solidity >=0.4.24 <0.6.0;");
assert.include(flattened, "pragma solidity ^0.5.2;");
});
it("Should fail if the provided root directory does not exist", async function() {
try {
await flatten(["./contracts/child.sol"], "no valid directory");
assert.fail("This should have failed");
} catch (error) {
assert.strictEqual(error.message, "The specified root directory does not exist");
}
});
});
| 28.942529 | 88 | 0.636219 |
434b8cf64635e2d4cd2c5bd3cea369708dfa0b5e | 198 | js | JavaScript | examples/next/store/reducers/index.js | rooxim-uehara/ruui | b87758c34c700f3f099270d43a54bd55bfc94558 | [
"MIT"
] | null | null | null | examples/next/store/reducers/index.js | rooxim-uehara/ruui | b87758c34c700f3f099270d43a54bd55bfc94558 | [
"MIT"
] | null | null | null | examples/next/store/reducers/index.js | rooxim-uehara/ruui | b87758c34c700f3f099270d43a54bd55bfc94558 | [
"MIT"
] | null | null | null | import { combineReducers } from 'redux';
import { ruuiReducer } from '../../../../dist';
import appReducer from './app';
export default combineReducers({
app: appReducer,
ruui: ruuiReducer,
});
| 19.8 | 47 | 0.676768 |
434bd73e54bd91ad274f1261b651d72dc43d791e | 17,715 | js | JavaScript | modules/xmpp/XmppConnection.js | krupa-project/lib-jitsi-meet | 4a98a10630b94e2ba894b6b984fc7f3cd516f42d | [
"Apache-2.0"
] | 2 | 2020-11-03T19:37:23.000Z | 2021-03-21T03:25:34.000Z | modules/xmpp/XmppConnection.js | krupa-project/lib-jitsi-meet | 4a98a10630b94e2ba894b6b984fc7f3cd516f42d | [
"Apache-2.0"
] | 1 | 2022-02-14T02:16:03.000Z | 2022-02-14T02:16:03.000Z | modules/xmpp/XmppConnection.js | krupa-project/lib-jitsi-meet | 4a98a10630b94e2ba894b6b984fc7f3cd516f42d | [
"Apache-2.0"
] | 2 | 2021-02-26T06:52:50.000Z | 2021-08-05T13:30:35.000Z | import { getLogger } from 'jitsi-meet-logger';
import { $pres, Strophe } from 'strophe.js';
import 'strophejs-plugin-stream-management';
import Listenable from '../util/Listenable';
import ResumeTask from './ResumeTask';
import LastSuccessTracker from './StropheLastSuccess';
import PingConnectionPlugin from './strophe.ping';
const logger = getLogger(__filename);
/**
* The lib-jitsi-meet layer for {@link Strophe.Connection}.
*/
export default class XmppConnection extends Listenable {
/**
* The list of {@link XmppConnection} events.
*
* @returns {Object}
*/
static get Events() {
return {
CONN_STATUS_CHANGED: 'CONN_STATUS_CHANGED'
};
}
/**
* The list of Xmpp connection statuses.
*
* @returns {Strophe.Status}
*/
static get Status() {
return Strophe.Status;
}
/**
* Initializes new connection instance.
*
* @param {Object} options
* @param {String} options.serviceUrl - The BOSH or WebSocket service URL.
* @param {String} [options.enableWebsocketResume=true] - True/false to control the stream resumption functionality.
* It will enable automatically by default if supported by the XMPP server.
* @param {Number} [options.websocketKeepAlive=240000] - The websocket keep alive interval. It's 4 minutes by
* default with jitter. Pass -1 to disable. The actual interval equation is:
* jitterDelay = (interval * 0.2) + (0.8 * interval * Math.random())
* The keep alive is HTTP GET request to the {@link options.serviceUrl}.
*/
constructor({ enableWebsocketResume, websocketKeepAlive, serviceUrl }) {
super();
this._options = {
enableWebsocketResume: typeof enableWebsocketResume === 'undefined' ? true : enableWebsocketResume,
websocketKeepAlive: typeof websocketKeepAlive === 'undefined' ? 4 * 60 * 1000 : Number(websocketKeepAlive)
};
this._stropheConn = new Strophe.Connection(serviceUrl);
this._usesWebsocket = serviceUrl.startsWith('ws:') || serviceUrl.startsWith('wss:');
// The default maxRetries is 5, which is too long.
this._stropheConn.maxRetries = 3;
this._lastSuccessTracker = new LastSuccessTracker();
this._lastSuccessTracker.startTracking(this, this._stropheConn);
this._resumeTask = new ResumeTask(this._stropheConn);
/**
* @typedef DeferredSendIQ Object
* @property {Element} iq - The IQ to send.
* @property {function} resolve - The resolve method of the deferred Promise.
* @property {function} reject - The reject method of the deferred Promise.
* @property {number} timeout - The ID of the timeout task that needs to be cleared, before sending the IQ.
*/
/**
* Deferred IQs to be sent upon reconnect.
* @type {Array<DeferredSendIQ>}
* @private
*/
this._deferredIQs = [];
// Ping plugin is mandatory for the Websocket mode to work correctly. It's used to detect when the connection
// is broken (WebSocket/TCP connection not closed gracefully).
this.addConnectionPlugin(
'ping',
new PingConnectionPlugin({
onPingThresholdExceeded: () => this._onPingErrorThresholdExceeded()
}));
}
/**
* A getter for the connected state.
*
* @returns {boolean}
*/
get connected() {
const websocket = this._stropheConn && this._stropheConn._proto && this._stropheConn._proto.socket;
return (this._status === Strophe.Status.CONNECTED || this._status === Strophe.Status.ATTACHED)
&& (!this.isUsingWebSocket || (websocket && websocket.readyState === WebSocket.OPEN));
}
/**
* Retrieves the feature discovery plugin instance.
*
* @returns {Strophe.Connection.disco}
*/
get disco() {
return this._stropheConn.disco;
}
/**
* A getter for the disconnecting state.
*
* @returns {boolean}
*/
get disconnecting() {
return this._stropheConn.disconnecting === true;
}
/**
* A getter for the domain.
*
* @returns {string|null}
*/
get domain() {
return this._stropheConn.domain;
}
/**
* Tells if Websocket is used as the transport for the current XMPP connection. Returns true for Websocket or false
* for BOSH.
* @returns {boolean}
*/
get isUsingWebSocket() {
return this._usesWebsocket;
}
/**
* A getter for the JID.
*
* @returns {string|null}
*/
get jid() {
return this._stropheConn.jid;
}
/**
* Returns headers for the last BOSH response received.
*
* @returns {string}
*/
get lastResponseHeaders() {
return this._stropheConn._proto && this._stropheConn._proto.lastResponseHeaders;
}
/**
* A getter for the logger plugin instance.
*
* @returns {*}
*/
get logger() {
return this._stropheConn.logger;
}
/**
* A getter for the connection options.
*
* @returns {*}
*/
get options() {
return this._stropheConn.options;
}
/**
* A getter for the service URL.
*
* @returns {string}
*/
get service() {
return this._stropheConn.service;
}
/**
* Returns the current connection status.
*
* @returns {Strophe.Status}
*/
get status() {
return this._status;
}
/**
* Adds a connection plugin to this instance.
*
* @param {string} name - The name of the plugin or rather a key under which it will be stored on this connection
* instance.
* @param {ConnectionPluginListenable} plugin - The plugin to add.
*/
addConnectionPlugin(name, plugin) {
this[name] = plugin;
plugin.init(this);
}
/**
* See {@link Strophe.Connection.addHandler}
*
* @returns {void}
*/
addHandler(...args) {
this._stropheConn.addHandler(...args);
}
/* eslint-disable max-params */
/**
* Wraps {@link Strophe.Connection.attach} method in order to intercept the connection status updates.
* See {@link Strophe.Connection.attach} for the params description.
*
* @returns {void}
*/
attach(jid, sid, rid, callback, ...args) {
this._stropheConn.attach(jid, sid, rid, this._stropheConnectionCb.bind(this, callback), ...args);
}
/**
* Wraps Strophe.Connection.connect method in order to intercept the connection status updates.
* See {@link Strophe.Connection.connect} for the params description.
*
* @returns {void}
*/
connect(jid, pass, callback, ...args) {
this._stropheConn.connect(jid, pass, this._stropheConnectionCb.bind(this, callback), ...args);
}
/* eslint-enable max-params */
/**
* Handles {@link Strophe.Status} updates for the current connection.
*
* @param {function} targetCallback - The callback passed by the {@link XmppConnection} consumer to one of
* the connect methods.
* @param {Strophe.Status} status - The new connection status.
* @param {*} args - The rest of the arguments passed by Strophe.
* @private
*/
_stropheConnectionCb(targetCallback, status, ...args) {
this._status = status;
let blockCallback = false;
if (status === Strophe.Status.CONNECTED || status === Strophe.Status.ATTACHED) {
this._maybeEnableStreamResume();
this._maybeStartWSKeepAlive();
this._processDeferredIQs();
this._resumeTask.cancel();
this.ping.startInterval(this.domain);
} else if (status === Strophe.Status.DISCONNECTED) {
this.ping.stopInterval();
// FIXME add RECONNECTING state instead of blocking the DISCONNECTED update
blockCallback = this._tryResumingConnection();
if (!blockCallback) {
clearTimeout(this._wsKeepAlive);
}
}
if (!blockCallback) {
targetCallback(status, ...args);
this.eventEmitter.emit(XmppConnection.Events.CONN_STATUS_CHANGED, status);
}
}
/**
* Clears the list of IQs and rejects deferred Promises with an error.
*
* @private
*/
_clearDeferredIQs() {
for (const deferred of this._deferredIQs) {
deferred.reject(new Error('disconnect'));
}
this._deferredIQs = [];
}
/**
* The method is meant to be used for testing. It's a shortcut for closing the WebSocket.
*
* @returns {void}
*/
closeWebsocket() {
if (this._stropheConn && this._stropheConn._proto) {
this._stropheConn._proto._closeSocket();
this._stropheConn._proto._onClose(null);
}
}
/**
* See {@link Strophe.Connection.disconnect}.
*
* @returns {void}
*/
disconnect(...args) {
this._resumeTask.cancel();
clearTimeout(this._wsKeepAlive);
this._clearDeferredIQs();
this._stropheConn.disconnect(...args);
}
/**
* See {@link Strophe.Connection.flush}.
*
* @returns {void}
*/
flush(...args) {
this._stropheConn.flush(...args);
}
/**
* See {@link LastRequestTracker.getTimeSinceLastSuccess}.
*
* @returns {number|null}
*/
getTimeSinceLastSuccess() {
return this._lastSuccessTracker.getTimeSinceLastSuccess();
}
/**
* Requests a resume token from the server if enabled and all requirements are met.
*
* @private
*/
_maybeEnableStreamResume() {
if (!this._options.enableWebsocketResume) {
return;
}
const { streamManagement } = this._stropheConn;
if (!this.isUsingWebSocket) {
logger.warn('Stream resume enabled, but WebSockets are not enabled');
} else if (!streamManagement) {
logger.warn('Stream resume enabled, but Strophe streamManagement plugin is not installed');
} else if (!streamManagement.isSupported()) {
logger.warn('Stream resume enabled, but XEP-0198 is not supported by the server');
} else if (!streamManagement.getResumeToken()) {
logger.info('Enabling XEP-0198 stream management');
streamManagement.enable(/* resume */ true);
}
}
/**
* Starts the Websocket keep alive if enabled.
*
* @private
* @returns {void}
*/
_maybeStartWSKeepAlive() {
const { websocketKeepAlive } = this._options;
if (this._usesWebsocket && websocketKeepAlive > 0) {
this._wsKeepAlive || logger.info(`WebSocket keep alive interval: ${websocketKeepAlive}ms`);
clearTimeout(this._wsKeepAlive);
const intervalWithJitter
= /* base */ (websocketKeepAlive * 0.2) + /* jitter */ (Math.random() * 0.8 * websocketKeepAlive);
logger.debug(`Scheduling next WebSocket keep-alive in ${intervalWithJitter}ms`);
this._wsKeepAlive = setTimeout(() => {
const url = this.service.replace('wss://', 'https://').replace('ws://', 'http://');
fetch(url).catch(
error => {
logger.error(`Websocket Keep alive failed for url: ${url}`, { error });
})
.then(() => this._maybeStartWSKeepAlive());
}, intervalWithJitter);
}
}
/**
* Goes over the list of {@link DeferredSendIQ} tasks and sends them.
*
* @private
* @returns {void}
*/
_processDeferredIQs() {
for (const deferred of this._deferredIQs) {
if (deferred.iq) {
clearTimeout(deferred.timeout);
const timeLeft = Date.now() - deferred.start;
this.sendIQ(
deferred.iq,
result => deferred.resolve(result),
error => deferred.reject(error),
timeLeft);
}
}
this._deferredIQs = [];
}
/**
* Send a stanza. This function is called to push data onto the send queue to go out over the wire.
*
* @param {Element|Strophe.Builder} stanza - The stanza to send.
* @returns {void}
*/
send(stanza) {
if (!this.connected) {
throw new Error('Not connected');
}
this._stropheConn.send(stanza);
}
/**
* Helper function to send IQ stanzas.
*
* @param {Element} elem - The stanza to send.
* @param {Function} callback - The callback function for a successful request.
* @param {Function} errback - The callback function for a failed or timed out request. On timeout, the stanza will
* be null.
* @param {number} timeout - The time specified in milliseconds for a timeout to occur.
* @returns {number} - The id used to send the IQ.
*/
sendIQ(elem, callback, errback, timeout) {
if (!this.connected) {
errback('Not connected');
return;
}
return this._stropheConn.sendIQ(elem, callback, errback, timeout);
}
/**
* Sends an IQ immediately if connected or puts it on the send queue otherwise(in contrary to other send methods
* which would fail immediately if disconnected).
*
* @param {Element} iq - The IQ to send.
* @param {number} timeout - How long to wait for the response. The time when the connection is reconnecting is
* included, which means that the IQ may never be sent and still fail with a timeout.
*/
sendIQ2(iq, { timeout }) {
return new Promise((resolve, reject) => {
if (this.connected) {
this.sendIQ(
iq,
result => resolve(result),
error => reject(error),
timeout);
} else {
const deferred = {
iq,
resolve,
reject,
start: Date.now(),
timeout: setTimeout(() => {
// clears the IQ on timeout and invalidates the deferred task
deferred.iq = undefined;
// Strophe calls with undefined on timeout
reject(undefined);
}, timeout)
};
this._deferredIQs.push(deferred);
}
});
}
/**
* Called by the ping plugin when ping fails too many times.
*
* @returns {void}
*/
_onPingErrorThresholdExceeded() {
if (this.isUsingWebSocket) {
logger.warn('Ping error threshold exceeded - killing the WebSocket');
this.closeWebsocket();
}
}
/**
* Helper function to send presence stanzas. The main benefit is for sending presence stanzas for which you expect
* a responding presence stanza with the same id (for example when leaving a chat room).
*
* @param {Element} elem - The stanza to send.
* @param {Function} callback - The callback function for a successful request.
* @param {Function} errback - The callback function for a failed or timed out request. On timeout, the stanza will
* be null.
* @param {number} timeout - The time specified in milliseconds for a timeout to occur.
* @returns {number} - The id used to send the presence.
*/
sendPresence(elem, callback, errback, timeout) {
if (!this.connected) {
errback('Not connected');
return;
}
this._stropheConn.sendPresence(elem, callback, errback, timeout);
}
/**
* The method gracefully closes the BOSH connection by using 'navigator.sendBeacon'.
*
* @returns {boolean} - true if the beacon was sent.
*/
sendUnavailableBeacon() {
if (!navigator.sendBeacon || this._stropheConn.disconnecting || !this._stropheConn.connected) {
return false;
}
this._stropheConn._changeConnectStatus(Strophe.Status.DISCONNECTING);
this._stropheConn.disconnecting = true;
const body = this._stropheConn._proto._buildBody()
.attrs({
type: 'terminate'
});
const pres = $pres({
xmlns: Strophe.NS.CLIENT,
type: 'unavailable'
});
body.cnode(pres.tree());
const res = navigator.sendBeacon(
this.service.indexOf('https://') === -1 ? `https:${this.service}` : this.service,
Strophe.serialize(body.tree()));
logger.info(`Successfully send unavailable beacon ${res}`);
this._stropheConn._proto._abortAllRequests();
this._stropheConn._doDisconnect();
return true;
}
/**
* Tries to use stream management plugin to resume dropped XMPP connection. The streamManagement plugin clears
* the resume token if any connection error occurs which would put it in unrecoverable state, so as long as
* the token is present it means the connection can be resumed.
*
* @private
* @returns {boolean}
*/
_tryResumingConnection() {
const { streamManagement } = this._stropheConn;
const resumeToken = streamManagement && streamManagement.getResumeToken();
if (resumeToken) {
this._resumeTask.schedule();
return true;
}
return false;
}
}
| 31.465364 | 120 | 0.586339 |
434bffff42aa5d7ddee40b8d158605938fbcc1fb | 1,081 | js | JavaScript | src/main/components/buttonGroups/personalMenu/buttons/dropDown/DropDownButton.test.js | gzacharski/AGH-Praca-inzynierska-front-end | 66ee5b2459cf371464a7576be99a484c2d0ea51e | [
"MIT"
] | null | null | null | src/main/components/buttonGroups/personalMenu/buttons/dropDown/DropDownButton.test.js | gzacharski/AGH-Praca-inzynierska-front-end | 66ee5b2459cf371464a7576be99a484c2d0ea51e | [
"MIT"
] | 138 | 2021-03-20T20:19:59.000Z | 2022-03-28T04:53:44.000Z | src/main/components/buttonGroups/personalMenu/buttons/dropDown/DropDownButton.test.js | gzacharski/AGH-praca-inzynierska | 66ee5b2459cf371464a7576be99a484c2d0ea51e | [
"MIT"
] | null | null | null | import React from 'react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter } from 'react-router-dom';
import { render, screen, act } from 'src/testUtils';
import DropDownButton from './DropDownButton';
describe('Message button', () => {
beforeEach(() => {
render(
<MemoryRouter>
<DropDownButton />
</MemoryRouter>,
);
});
test('should have button', () => {
expect(screen.getByRole('button')).toBeInTheDocument();
});
describe('once clicked, a popper should show up and', () => {
beforeEach(() => {
act(() => userEvent.click(screen.getByRole('button')));
});
test('should have "Moje konto" item', () => {
expect(screen.getByText(/Moje konto/)).toBeInTheDocument();
});
test('should have "Ustawienia" item', () => {
expect(screen.getByText(/Ustawienia/)).toBeInTheDocument();
});
test('should have "Wyloguj się" item', () => {
expect(screen.getByText(/Wyloguj się/)).toBeInTheDocument();
});
});
});
| 28.447368 | 69 | 0.580019 |
434c8920b2c1bac0ace28b42dbd075b60dcd028e | 63 | js | JavaScript | __mocks__/uniqid.js | ambisign-gavin/todo-sticker | 8e4395325155fbde554554f5e703414288d17abe | [
"MIT"
] | 26 | 2019-03-15T10:57:31.000Z | 2021-10-19T17:10:49.000Z | __mocks__/uniqid.js | ambisign-gavin/todo-sticker | 8e4395325155fbde554554f5e703414288d17abe | [
"MIT"
] | null | null | null | __mocks__/uniqid.js | ambisign-gavin/todo-sticker | 8e4395325155fbde554554f5e703414288d17abe | [
"MIT"
] | 4 | 2019-04-28T11:19:49.000Z | 2020-03-22T18:14:56.000Z | // @flow
export default function uniqid() {
return '1';
}
| 10.5 | 34 | 0.603175 |
434d468d1e03d2e6848c16f5231d6b9e6f6f5575 | 2,827 | js | JavaScript | test/testToken.js | chkyass/ICO | f61660edc48428a4b24d1d406bbc75a3fdaa161f | [
"MIT"
] | null | null | null | test/testToken.js | chkyass/ICO | f61660edc48428a4b24d1d406bbc75a3fdaa161f | [
"MIT"
] | null | null | null | test/testToken.js | chkyass/ICO | f61660edc48428a4b24d1d406bbc75a3fdaa161f | [
"MIT"
] | null | null | null | 'use strict';
const Token = artifacts.require("./Token.sol");
contract('TokenTest', function(accounts) {
let token;
beforeEach(async function() {
token = await Token.new(1000);
});
describe('Token primary functions', function() {
it("Check initialisation", async function() {
let creator = await token.creator.call();
assert.equal(creator, accounts[0]);
let totalSuply = await token.totalSupply.call();
assert.equal(totalSuply.valueOf(), 1000);
let creatorBalance = await token.balanceOf(accounts[0]);
assert.equal(creatorBalance.valueOf(), 1000);
});
it("Check purchase", async function() {
/* Normal purchase*/
await token.purchase(accounts[1], 100);
let buyerBalance = await token.balanceOf(accounts[1]);
let unsold = await token.balanceOf(accounts[0]);
assert.equal(buyerBalance, 100);
assert.equal(unsold, 900)
/*Purchase more than available */
await token.purchase(accounts[1], 2000);
buyerBalance = await token.balanceOf(accounts[1]);
unsold = await token.balanceOf(accounts[0]);
assert.equal(buyerBalance, 100);
assert.equal(unsold, 900);
/*Try to purchase with another account that the creator */
let error = false;
try {
await token.purchase(accounts[1], 5000, {from: accounts[2]});
}
catch(e){
error = true;
}
assert.equal(error, true);
});
});
describe('Token Creator functions', function() {
it("Destroy tokens", async function() {
await token.burn(200);
let unsold = await token.balanceOf(accounts[0]);
let total = await token.totalSupply();
assert.equal(unsold,800);
assert.equal(total, 800);
await token.purchase(accounts[1], 100);
await token.burn(50,{from: accounts[1]});
unsold = await token.balanceOf(accounts[1]);
total = await token.totalSupply();
assert.equal(unsold, 50);
assert.equal(total, 750);
});
it("Create tokens", async function() {
await token.mint(2000);
let total = await token.totalSupply();
let unsold = await token.balanceOf(accounts[0]);
assert.equal(total, 3000);
assert.equal(unsold, 3000);
});
});
describe('Allowance', function() {
it("Transfer From", async function() {
await token.purchase(accounts[1], 50);
await token.approve(accounts[2], 25,{from:accounts[1]});
let allowance = await token.allowance(accounts[1], accounts[2]);
assert.equal(allowance, 25);
await token.transferFrom(accounts[1], accounts[2], 25);
await token.transferFrom(accounts[1], accounts[2], 1);
let acc1bal = await token.balanceOf(accounts[1]);
let acc2bal = await token.balanceOf(accounts[2]);
allowance = await token.allowance(accounts[1], accounts[2]);
assert.equal(acc1bal, 25);
assert.equal(acc2bal, 25);
assert.equal(allowance, 0);
});
});
});
| 31.065934 | 67 | 0.664308 |
434df33fe906893f963118007a0ce96a6e32c6fe | 5,298 | js | JavaScript | node_modules/vscode-nls/lib/main.js | jabsatz/gml-support | c055f67b285eeef610a7f478b851921be50e81ec | [
"MIT"
] | 28 | 2018-07-11T15:38:12.000Z | 2022-03-25T21:27:23.000Z | node_modules/vscode-nls/lib/main.js | gml-support/gml-support-thirdparty | 040ea7095946d16f90daa8e284b89a01d7e375c3 | [
"MIT"
] | 11 | 2018-07-23T09:42:52.000Z | 2022-02-27T17:24:49.000Z | node_modules/vscode-nls/lib/main.js | gml-support/gml-support-thirdparty | 040ea7095946d16f90daa8e284b89a01d7e375c3 | [
"MIT"
] | 14 | 2018-07-23T01:46:48.000Z | 2022-02-27T17:01:00.000Z | /* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
'use strict';
var path = require("path");
var fs = require("fs");
var _options = { locale: undefined, cacheLanguageResolution: true };
var _isPseudo = false;
var _resolvedLanguage = null;
var toString = Object.prototype.toString;
function isDefined(value) {
return typeof value !== 'undefined';
}
function isNumber(value) {
return toString.call(value) === '[object Number]';
}
function isString(value) {
return toString.call(value) === '[object String]';
}
function isBoolean(value) {
return value === true || value === false;
}
function format(message, args) {
var result;
if (_isPseudo) {
// FF3B and FF3D is the Unicode zenkaku representation for [ and ]
message = '\uFF3B' + message.replace(/[aouei]/g, '$&$&') + '\uFF3D';
}
if (args.length === 0) {
result = message;
}
else {
result = message.replace(/\{(\d+)\}/g, function (match, rest) {
var index = rest[0];
return typeof args[index] !== 'undefined' ? args[index] : match;
});
}
return result;
}
function createScopedLocalizeFunction(messages) {
return function (key, message) {
var args = [];
for (var _i = 2; _i < arguments.length; _i++) {
args[_i - 2] = arguments[_i];
}
if (isNumber(key)) {
if (key >= messages.length) {
console.error("Broken localize call found. Index out of bounds. Stacktrace is\n: " + new Error('').stack);
return;
}
return format(messages[key], args);
}
else {
if (isString(message)) {
console.warn("Message " + message + " didn't get externalized correctly.");
return format(message, args);
}
else {
console.error("Broken localize call found. Stacktrace is\n: " + new Error('').stack);
}
}
};
}
function localize(key, message) {
var args = [];
for (var _i = 2; _i < arguments.length; _i++) {
args[_i - 2] = arguments[_i];
}
return format(message, args);
}
function resolveLanguage(file) {
var ext = path.extname(file);
if (ext) {
file = file.substr(0, file.length - ext.length);
}
var resolvedLanguage;
if (_options.cacheLanguageResolution && _resolvedLanguage) {
resolvedLanguage = _resolvedLanguage;
}
else {
if (_isPseudo || !_options.locale) {
resolvedLanguage = '.nls.json';
}
else {
var locale = _options.locale;
while (locale) {
var candidate = '.nls.' + locale + '.json';
if (fs.existsSync(file + candidate)) {
resolvedLanguage = candidate;
break;
}
else {
var index = locale.lastIndexOf('-');
if (index > 0) {
locale = locale.substring(0, index);
}
else {
resolvedLanguage = '.nls.json';
locale = null;
}
}
}
}
if (_options.cacheLanguageResolution) {
_resolvedLanguage = resolvedLanguage;
}
}
return file + resolvedLanguage;
}
function loadMessageBundle(file) {
if (!file) {
return localize;
}
else {
var resolvedFile = resolveLanguage(file);
try {
var json = require(resolvedFile);
if (Array.isArray(json)) {
return createScopedLocalizeFunction(json);
}
else {
if (isDefined(json.messages) && isDefined(json.keys)) {
return createScopedLocalizeFunction(json.messages);
}
else {
console.error("String bundle '" + file + "' uses an unsupported format.");
return localize;
}
}
}
catch (e) {
console.error("Can't load string bundle for " + file);
return localize;
}
}
}
exports.loadMessageBundle = loadMessageBundle;
function config(opt) {
var options;
if (isString(opt)) {
try {
options = JSON.parse(opt);
}
catch (e) {
console.error("Error parsing nls options: " + opt);
}
}
else {
options = opt;
}
if (options) {
if (isString(options.locale)) {
_options.locale = options.locale.toLowerCase();
_resolvedLanguage = null;
}
if (isBoolean(options.cacheLanguageResolution)) {
_options.cacheLanguageResolution = options.cacheLanguageResolution;
}
}
_isPseudo = _options.locale === 'pseudo';
return loadMessageBundle;
}
exports.config = config;
//# sourceMappingURL=main.js.map | 32.109091 | 122 | 0.507739 |
434e63cf8dced63a314fa98daaf82e723455734d | 526 | js | JavaScript | client/scripts/home.js | henryboston/overwatchly | 61b33b2ae1c6737cfc13aa01e29386bdc23d4c9a | [
"MIT"
] | null | null | null | client/scripts/home.js | henryboston/overwatchly | 61b33b2ae1c6737cfc13aa01e29386bdc23d4c9a | [
"MIT"
] | null | null | null | client/scripts/home.js | henryboston/overwatchly | 61b33b2ae1c6737cfc13aa01e29386bdc23d4c9a | [
"MIT"
] | null | null | null | var React = require('react');
var ReactDOM = require('react-dom');
/** Attendees */
//var AttendingApp = require('../components/AttendingApp.js');
//var attendingAppTarget = document.getElementById('react-attending');
//if (attendingAppTarget) {
ReactDOM.render(<AttendingApp />, attendingAppTarget);
}
/** Hero (RSVP Button) */
//var HeroApp = require('../components/HeroApp.js');
//var heroAppTarget = document.getElementById('react-hero-button');
//if (heroAppTarget) {
ReactDOM.render(<HeroApp />, heroAppTarget);
}
| 27.684211 | 70 | 0.711027 |
434e86bc0c47169785a4d7f02c4f9fb49604709e | 9,960 | js | JavaScript | klient/js/UI.js | MStabryla/GwentZSL | 2e81345a4a608747ddd519857d8b3b042c668ae2 | [
"MIT"
] | null | null | null | klient/js/UI.js | MStabryla/GwentZSL | 2e81345a4a608747ddd519857d8b3b042c668ae2 | [
"MIT"
] | null | null | null | klient/js/UI.js | MStabryla/GwentZSL | 2e81345a4a608747ddd519857d8b3b042c668ae2 | [
"MIT"
] | null | null | null | function _UI() {
var that = this;
this.Login = function(){
LoginDisp.stop = true;
Net.Http.Login(document.getElementById("Login").value,document.getElementById("Pass").value);
}
this.Hidden = function(id){
document.getElementById(id).style.display= "none";
}
this.Show = function(id){
document.getElementById(id).style.display= "block";
}
this.GenPanel = function(){
document.getElementById("UserName").innerText = Data.actuser.login;
document.getElementById("Panel").style.display= "block";
document.getElementById("ShowCards").onclick = function(){
if(Data.cards)
{
document.getElementById("CardsList").innerHTML = "";
for(var i=0;i<Data.cards.length;i++)
{
var card = Data.cards[i];
var elem = document.createElement("div");
elem.setAttribute("class","block-12 card");
var img = document.createElement("img");
img.setAttribute("src",card.Image);
img.setAttribute("class","card-img block-4");
img.style.transform = "rotate(180deg)";
var main = document.createElement("div");
main.setAttribute("class","card-con block-8");
var name = document.createElement("span");
name.setAttribute("class","card-title");
name.innerText = card.Name;
var desc = document.createElement("span");
desc.setAttribute("class","card-desc");
desc.innerText = card.Desc;
switch(card.Nation)
{
case "inf":
elem.style.backgroundColor = "rgba(10, 14, 91,0.5)";
break;
case "neutral":
elem.style.backgroundColor = "rgba(0, 0, 0,0.5)";
break;
}
var power = document.createElement("span");
switch(card.Quality)
{
case "gold":
elem.style.border = "2px groove gold";
break;
case "silver":
elem.style.border = "2px groove #898a9e";
}
power.setAttribute("class","card-power");
power.innerText = card.Power;
elem.appendChild(img);
main.appendChild(name);
main.appendChild(desc);
main.appendChild(power);
elem.appendChild(main);
document.getElementById("CardsList").appendChild(elem);
}
that.Show("Cards");
}
}
document.getElementById("ShowDecks").onclick = function(){
if(Data.decks)
{
document.getElementById("DeckList").innerHTML = "";
for(var i=0;i<Data.decks.length;i++)
{
var deck = Data.decks[i];
var deckElem = document.createElement("div");
deckElem.setAttribute("class","deck");
var deckT = document.createElement("span");
deckT.setAttribute("class","deck-title");
deckT.innerText = "Talia " + i;
deckElem.appendChild(deckT);
var lcard = Data.cards.find(function(elem){return elem.Id == deck.Leader})
var lelem = document.createElement("div");
lelem.setAttribute("class","block-12 card");
var limg = document.createElement("img");
limg.setAttribute("src",lcard.Image);
limg.setAttribute("class","card-img block-4");
limg.style.transform = "rotate(180deg)";
var lmain = document.createElement("div");
lmain.setAttribute("class","card-con block-8");
var lname = document.createElement("span");
lname.setAttribute("class","card-title");
lname.innerText = lcard.Name;
var ldesc = document.createElement("span");
ldesc.setAttribute("class","card-desc");
ldesc.innerText = lcard.Desc;
switch(lcard.Nation)
{
case "inf":
lelem.style.backgroundColor = "rgba(10, 14, 91,0.5)";
break;
case "neutral":
lelem.style.backgroundColor = "rgba(0, 0, 0,0.5)";
break;
}
var lpower = document.createElement("span");
switch(lcard.Quality)
{
case "gold":
lelem.style.border = "2px groove gold";
break;
case "silver":
lelem.style.border = "2px groove #898a9e";
}
lpower.setAttribute("class","card-power");
lpower.innerText = lcard.Power;
lelem.appendChild(limg);
lmain.appendChild(lname);
lmain.appendChild(ldesc);
lmain.appendChild(lpower);
lelem.appendChild(lmain);
deckElem.appendChild(lelem);
for(var j=0;j<deck.Cards.length;j++)
{
var card = Data.cards.find(function(elem){return elem.Id == deck.Cards[j]})
var elem = document.createElement("div");
elem.setAttribute("class","block-12 card");
var img = document.createElement("img");
img.setAttribute("src",card.Image);
img.setAttribute("class","card-img block-4");
img.style.transform = "rotate(180deg)";
var main = document.createElement("div");
main.setAttribute("class","card-con block-8");
var name = document.createElement("span");
name.setAttribute("class","card-title");
name.innerText = card.Name;
var desc = document.createElement("span");
desc.setAttribute("class","card-desc");
desc.innerText = card.Desc;
switch(card.Nation)
{
case "inf":
elem.style.backgroundColor = "rgba(10, 14, 91,0.5)";
break;
case "neutral":
elem.style.backgroundColor = "rgba(0, 0, 0,0.5)";
break;
}
var power = document.createElement("span");
switch(card.Quality)
{
case "gold":
elem.style.border = "2px groove gold";
break;
case "silver":
elem.style.border = "2px groove #898a9e";
}
power.setAttribute("class","card-power");
power.innerText = card.Power;
elem.appendChild(img);
main.appendChild(name);
main.appendChild(desc);
main.appendChild(power);
elem.appendChild(main);
deckElem.appendChild(elem);
}
document.getElementById("DeckList").appendChild(deckElem);
}
that.Show("Decks");
}
}
document.getElementById("Play").onclick = function(){
that.Show("ChoiseDeck");
for(var i=0;i<Data.decks.length;i++)
{
var elem = document.createElement("div");
elem.setAttribute("class","block-12 c-deck");
elem.setAttribute("value",Data.decks[i]._id);
elem.innerText = "Talia " + i;
switch(Data.decks[i].Nation.toLowerCase())
{
case "inf":
elem.style.backgroundColor = "rgba(10, 14, 91,0.5)";
break;
case "neutral":
elem.style.backgroundColor = "rgba(0, 0, 0,0.5)";
break;
}
var title = document.createElement("span");
title.setAttribute("class","deck-title");
elem.appendChild(title);
elem.onclick = function(){
UI.Hidden("ChoiseDeck");
UI.Hidden("Panel");
UI.Show("Waiting");
Net.socket.emit("queue",{user:Data.actuser,deck:this.getAttribute("value")});
Net.Listening();
}
document.getElementById("ChoiseDeckList").appendChild(elem);
}
}
}
this.Alert = function(text){
document.getElementById("Alert-Con").innerText = text;
that.Show("Alert");
document.getElementById("Alert").oncontextmenu = function(e){
e.preventDefault();
that.Hidden("Alert");
}
}
}
var UI = new _UI(); | 46.542056 | 101 | 0.435542 |
434e9d6ce41f05fd3ca973df6c3bd6fc329afa3b | 14,056 | js | JavaScript | flow-typed/npm/eslint-plugin-node_vx.x.x.js | Biboba/arcgis-js-cli | 7bcfe54fe3b3d9bd1477fe5716ec5364e4cd61f6 | [
"Apache-2.0"
] | null | null | null | flow-typed/npm/eslint-plugin-node_vx.x.x.js | Biboba/arcgis-js-cli | 7bcfe54fe3b3d9bd1477fe5716ec5364e4cd61f6 | [
"Apache-2.0"
] | null | null | null | flow-typed/npm/eslint-plugin-node_vx.x.x.js | Biboba/arcgis-js-cli | 7bcfe54fe3b3d9bd1477fe5716ec5364e4cd61f6 | [
"Apache-2.0"
] | null | null | null | // flow-typed signature: 2dae8fd868e7a1ac9a0083ab2a0b74ee
// flow-typed version: <<STUB>>/eslint-plugin-node_v^9.1.0/flow_v0.102.0
/**
* This is an autogenerated libdef stub for:
*
* 'eslint-plugin-node'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'eslint-plugin-node' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
declare module 'eslint-plugin-node/lib/configs/_commons' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/configs/recommended-module' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/configs/recommended-script' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/configs/recommended' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/index' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/rules/exports-style' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/rules/file-extension-in-import' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/rules/no-deprecated-api' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/rules/no-extraneous-import' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/rules/no-extraneous-require' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/rules/no-hide-core-modules' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/rules/no-missing-import' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/rules/no-missing-require' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/rules/no-unpublished-bin' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/rules/no-unpublished-import' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/rules/no-unpublished-require' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/rules/no-unsupported-features' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/rules/no-unsupported-features/es-builtins' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/rules/no-unsupported-features/es-syntax' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/rules/no-unsupported-features/node-builtins' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/rules/prefer-global/buffer' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/rules/prefer-global/console' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/rules/prefer-global/process' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/rules/prefer-global/text-decoder' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/rules/prefer-global/text-encoder' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/rules/prefer-global/url-search-params' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/rules/prefer-global/url' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/rules/prefer-promises/dns' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/rules/prefer-promises/fs' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/rules/process-exit-as-throw' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/rules/shebang' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/util/cache' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/util/check-existence' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/util/check-extraneous' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/util/check-prefer-global' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/util/check-publish' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/util/check-unsupported-builtins' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/util/enumerate-property-names' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/util/exists' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/util/get-allow-modules' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/util/get-configured-node-version' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/util/get-convert-path' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/util/get-import-export-targets' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/util/get-npmignore' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/util/get-package-json' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/util/get-require-targets' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/util/get-resolve-paths' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/util/get-semver-range' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/util/get-try-extensions' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/util/import-target' {
declare module.exports: any;
}
declare module 'eslint-plugin-node/lib/util/strip-import-path-params' {
declare module.exports: any;
}
// Filename aliases
declare module 'eslint-plugin-node/lib/configs/_commons.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/configs/_commons'>;
}
declare module 'eslint-plugin-node/lib/configs/recommended-module.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/configs/recommended-module'>;
}
declare module 'eslint-plugin-node/lib/configs/recommended-script.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/configs/recommended-script'>;
}
declare module 'eslint-plugin-node/lib/configs/recommended.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/configs/recommended'>;
}
declare module 'eslint-plugin-node/lib/index.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/index'>;
}
declare module 'eslint-plugin-node/lib/rules/exports-style.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/rules/exports-style'>;
}
declare module 'eslint-plugin-node/lib/rules/file-extension-in-import.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/rules/file-extension-in-import'>;
}
declare module 'eslint-plugin-node/lib/rules/no-deprecated-api.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/rules/no-deprecated-api'>;
}
declare module 'eslint-plugin-node/lib/rules/no-extraneous-import.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/rules/no-extraneous-import'>;
}
declare module 'eslint-plugin-node/lib/rules/no-extraneous-require.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/rules/no-extraneous-require'>;
}
declare module 'eslint-plugin-node/lib/rules/no-hide-core-modules.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/rules/no-hide-core-modules'>;
}
declare module 'eslint-plugin-node/lib/rules/no-missing-import.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/rules/no-missing-import'>;
}
declare module 'eslint-plugin-node/lib/rules/no-missing-require.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/rules/no-missing-require'>;
}
declare module 'eslint-plugin-node/lib/rules/no-unpublished-bin.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/rules/no-unpublished-bin'>;
}
declare module 'eslint-plugin-node/lib/rules/no-unpublished-import.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/rules/no-unpublished-import'>;
}
declare module 'eslint-plugin-node/lib/rules/no-unpublished-require.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/rules/no-unpublished-require'>;
}
declare module 'eslint-plugin-node/lib/rules/no-unsupported-features.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/rules/no-unsupported-features'>;
}
declare module 'eslint-plugin-node/lib/rules/no-unsupported-features/es-builtins.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/rules/no-unsupported-features/es-builtins'>;
}
declare module 'eslint-plugin-node/lib/rules/no-unsupported-features/es-syntax.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/rules/no-unsupported-features/es-syntax'>;
}
declare module 'eslint-plugin-node/lib/rules/no-unsupported-features/node-builtins.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/rules/no-unsupported-features/node-builtins'>;
}
declare module 'eslint-plugin-node/lib/rules/prefer-global/buffer.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/rules/prefer-global/buffer'>;
}
declare module 'eslint-plugin-node/lib/rules/prefer-global/console.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/rules/prefer-global/console'>;
}
declare module 'eslint-plugin-node/lib/rules/prefer-global/process.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/rules/prefer-global/process'>;
}
declare module 'eslint-plugin-node/lib/rules/prefer-global/text-decoder.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/rules/prefer-global/text-decoder'>;
}
declare module 'eslint-plugin-node/lib/rules/prefer-global/text-encoder.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/rules/prefer-global/text-encoder'>;
}
declare module 'eslint-plugin-node/lib/rules/prefer-global/url-search-params.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/rules/prefer-global/url-search-params'>;
}
declare module 'eslint-plugin-node/lib/rules/prefer-global/url.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/rules/prefer-global/url'>;
}
declare module 'eslint-plugin-node/lib/rules/prefer-promises/dns.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/rules/prefer-promises/dns'>;
}
declare module 'eslint-plugin-node/lib/rules/prefer-promises/fs.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/rules/prefer-promises/fs'>;
}
declare module 'eslint-plugin-node/lib/rules/process-exit-as-throw.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/rules/process-exit-as-throw'>;
}
declare module 'eslint-plugin-node/lib/rules/shebang.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/rules/shebang'>;
}
declare module 'eslint-plugin-node/lib/util/cache.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/util/cache'>;
}
declare module 'eslint-plugin-node/lib/util/check-existence.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/util/check-existence'>;
}
declare module 'eslint-plugin-node/lib/util/check-extraneous.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/util/check-extraneous'>;
}
declare module 'eslint-plugin-node/lib/util/check-prefer-global.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/util/check-prefer-global'>;
}
declare module 'eslint-plugin-node/lib/util/check-publish.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/util/check-publish'>;
}
declare module 'eslint-plugin-node/lib/util/check-unsupported-builtins.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/util/check-unsupported-builtins'>;
}
declare module 'eslint-plugin-node/lib/util/enumerate-property-names.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/util/enumerate-property-names'>;
}
declare module 'eslint-plugin-node/lib/util/exists.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/util/exists'>;
}
declare module 'eslint-plugin-node/lib/util/get-allow-modules.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/util/get-allow-modules'>;
}
declare module 'eslint-plugin-node/lib/util/get-configured-node-version.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/util/get-configured-node-version'>;
}
declare module 'eslint-plugin-node/lib/util/get-convert-path.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/util/get-convert-path'>;
}
declare module 'eslint-plugin-node/lib/util/get-import-export-targets.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/util/get-import-export-targets'>;
}
declare module 'eslint-plugin-node/lib/util/get-npmignore.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/util/get-npmignore'>;
}
declare module 'eslint-plugin-node/lib/util/get-package-json.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/util/get-package-json'>;
}
declare module 'eslint-plugin-node/lib/util/get-require-targets.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/util/get-require-targets'>;
}
declare module 'eslint-plugin-node/lib/util/get-resolve-paths.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/util/get-resolve-paths'>;
}
declare module 'eslint-plugin-node/lib/util/get-semver-range.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/util/get-semver-range'>;
}
declare module 'eslint-plugin-node/lib/util/get-try-extensions.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/util/get-try-extensions'>;
}
declare module 'eslint-plugin-node/lib/util/import-target.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/util/import-target'>;
}
declare module 'eslint-plugin-node/lib/util/strip-import-path-params.js' {
declare module.exports: $Exports<'eslint-plugin-node/lib/util/strip-import-path-params'>;
}
| 36.699739 | 105 | 0.762166 |
434eeaaf18436e2c3fd52dc74981b0cd3bfe6c3f | 77 | js | JavaScript | javascript_algorithms_and_data_structures_certification/basic_javascript/write-reusable-javascript-with-functions.js | mohanprasath/freecodecamp | 94663d0f23b46e952c9389e6db4c287772e981d4 | [
"MIT"
] | null | null | null | javascript_algorithms_and_data_structures_certification/basic_javascript/write-reusable-javascript-with-functions.js | mohanprasath/freecodecamp | 94663d0f23b46e952c9389e6db4c287772e981d4 | [
"MIT"
] | null | null | null | javascript_algorithms_and_data_structures_certification/basic_javascript/write-reusable-javascript-with-functions.js | mohanprasath/freecodecamp | 94663d0f23b46e952c9389e6db4c287772e981d4 | [
"MIT"
] | null | null | null | function reusableFunction() {
console.log("Hi World");
}
reusableFunction() | 19.25 | 29 | 0.74026 |
435147b1b55a72294608f5d1c88926c61f2b815e | 2,901 | js | JavaScript | src/referenceLines/renderActiveReferenceLine.js | wenggh/cornerstoneTools | 048d94a5b6d34e86c396936322db083762da02c3 | [
"MIT"
] | null | null | null | src/referenceLines/renderActiveReferenceLine.js | wenggh/cornerstoneTools | 048d94a5b6d34e86c396936322db083762da02c3 | [
"MIT"
] | null | null | null | src/referenceLines/renderActiveReferenceLine.js | wenggh/cornerstoneTools | 048d94a5b6d34e86c396936322db083762da02c3 | [
"MIT"
] | 1 | 2019-10-04T01:02:28.000Z | 2019-10-04T01:02:28.000Z | import external from '../externalModules.js';
import calculateReferenceLine from './calculateReferenceLine.js';
import toolColors from '../stateManagement/toolColors.js';
import convertToVector3 from '../util/convertToVector3.js';
import { draw, drawLine } from '../util/drawing.js';
// Renders the active reference line
export default function (context, eventData, targetElement, referenceElement) {
const cornerstone = external.cornerstone;
const targetImage = cornerstone.getEnabledElement(targetElement).image;
const referenceImage = cornerstone.getEnabledElement(referenceElement).image;
// Make sure the images are actually loaded for the target and reference
if (!targetImage || !referenceImage) {
return;
}
const targetImagePlane = cornerstone.metaData.get('imagePlaneModule', targetImage.imageId);
const referenceImagePlane = cornerstone.metaData.get('imagePlaneModule', referenceImage.imageId);
// Make sure the target and reference actually have image plane metadata
if (!targetImagePlane ||
!referenceImagePlane ||
!targetImagePlane.rowCosines ||
!targetImagePlane.columnCosines ||
!targetImagePlane.imagePositionPatient ||
!referenceImagePlane.rowCosines ||
!referenceImagePlane.columnCosines ||
!referenceImagePlane.imagePositionPatient) {
return;
}
// The image planes must be in the same frame of reference
if (targetImagePlane.frameOfReferenceUID !== referenceImagePlane.frameOfReferenceUID) {
return;
}
targetImagePlane.rowCosines = convertToVector3(targetImagePlane.rowCosines);
targetImagePlane.columnCosines = convertToVector3(targetImagePlane.columnCosines);
targetImagePlane.imagePositionPatient = convertToVector3(targetImagePlane.imagePositionPatient);
referenceImagePlane.rowCosines = convertToVector3(referenceImagePlane.rowCosines);
referenceImagePlane.columnCosines = convertToVector3(referenceImagePlane.columnCosines);
referenceImagePlane.imagePositionPatient = convertToVector3(referenceImagePlane.imagePositionPatient);
// The image plane normals must be > 30 degrees apart
const targetNormal = targetImagePlane.rowCosines.clone().cross(targetImagePlane.columnCosines);
const referenceNormal = referenceImagePlane.rowCosines.clone().cross(referenceImagePlane.columnCosines);
let angleInRadians = targetNormal.angleTo(referenceNormal);
angleInRadians = Math.abs(angleInRadians);
if (angleInRadians < 0.5) { // 0.5 radians = ~30 degrees
return;
}
const referenceLine = calculateReferenceLine(targetImagePlane, referenceImagePlane);
if (!referenceLine) {
return;
}
const color = toolColors.getReferenceActiveColor();
// Draw the referenceLines
context.setTransform(1, 0, 0, 1, 0, 0);
draw(context, (context) => {
drawLine(context, eventData.element, referenceLine.start, referenceLine.end, { color });
});
}
| 41.442857 | 106 | 0.773182 |
43516d387ea8f004ca931cd3c6996087395048bc | 1,829 | js | JavaScript | src/services/PageLayoutService/PageLayoutService.js | atcwells/servicenowUItest | 3286c01a29ea8bbf328f25df0cecf6a20360406c | [
"MIT"
] | null | null | null | src/services/PageLayoutService/PageLayoutService.js | atcwells/servicenowUItest | 3286c01a29ea8bbf328f25df0cecf6a20360406c | [
"MIT"
] | null | null | null | src/services/PageLayoutService/PageLayoutService.js | atcwells/servicenowUItest | 3286c01a29ea8bbf328f25df0cecf6a20360406c | [
"MIT"
] | null | null | null | module.exports = PageLayoutService = function () {
var components = {
header: {},
main: {
seaWindow: {
position: 'right',
gridSize: 'ten'
},
reportWindow: {
position: 'left',
gridSize: 'six'
}
},
footer: {}
}
var semanticGridNumberMappings = [
'one',
'two',
'three',
'four',
'five',
'six',
'seven',
'eight',
'nine',
'ten',
'eleven',
'twelve',
'thirteen',
'fourteen',
'fifteen',
'sixteen'
];
return {
getPosition: function (section, component) {
return 'align ' + components[section][component].position;
},
getGridSize: function (section, component) {
return components[section][component].gridSize + ' wide column';
},
increaseBox: function (direction) {
if (direction == 'left') {
if (semanticGridNumberMappings.indexOf($scope['right']) <= 0) {
return;
}
$scope['left'] = semanticGridNumberMappings[semanticGridNumberMappings.indexOf($scope['left']) + 1];
$scope['right'] = semanticGridNumberMappings[semanticGridNumberMappings.indexOf($scope['right']) - 1];
} else {
if (semanticGridNumberMappings.indexOf($scope['left']) <= 0) {
return;
}
$scope['left'] = semanticGridNumberMappings[semanticGridNumberMappings.indexOf($scope['left']) - 1];
$scope['right'] = semanticGridNumberMappings[semanticGridNumberMappings.indexOf($scope['right']) + 1];
}
}
}
} | 30.483333 | 118 | 0.482231 |
4352354131a3518233c9a1adebdf1db2ed56ecf9 | 3,675 | js | JavaScript | ApiReserved/models/comments.js | danibeam/Reserved | 1ec2a082c234e2ca8a0fd227537d1773abcb476c | [
"MIT"
] | 1 | 2019-12-13T08:24:48.000Z | 2019-12-13T08:24:48.000Z | ApiReserved/models/comments.js | danibeam/Reserved | 1ec2a082c234e2ca8a0fd227537d1773abcb476c | [
"MIT"
] | null | null | null | ApiReserved/models/comments.js | danibeam/Reserved | 1ec2a082c234e2ca8a0fd227537d1773abcb476c | [
"MIT"
] | null | null | null | var mysql=require("mysql");
var configDB=require("../config/configdb");
/* Conectar con la DB */
connection=mysql.createConnection({
host: configDB.dbreserved.host,
user: configDB.dbreserved.user,
password: configDB.dbreserved.password,
database: configDB.dbreserved.database
});
var Comments={};
/* Mostar la media de los comentarios de un restaurante */
Comments.valorationcomments=function(id, callback){
if (connection){
var sql=("SELECT SUM(valoracion) as valoracion,count(*) as comentarios FROM comentarios WHERE RestauranteC="+connection.escape(id));
connection.query(sql,function(error,rows){
if (error){
throw error;
}else{
return callback(null,rows);
}
})
}
}
/* Mostar los comentarios de un usuario */
Comments.findCommentsUser=function(id, callback){
if (connection){
var sql=("SELECT c.contenido, c.fecha, c.valoracion, r.nombre FROM restaurantes r, comentarios c, usuarios u WHERE c.UsuarioC="+connection.escape(id)+" AND r.IdRestaurante=c.RestauranteC");
connection.query(sql,function(error,rows){
if (error){
throw error;
}else{
return callback(null,rows);
}
})
}
}
/* Mostar los comentarios de un restaurante */
Comments.findCommentsRestaurant=function(id, callback){
if (connection){
var sql=("SELECT DISTINCT c.idComentario, u.idUsuario, c.contenido, c.valoracion, c.fecha, u.nombre, c.denunciado FROM restaurantes r, comentarios c, usuarios u WHERE c.RestauranteC="+connection.escape(id)+" AND u.IdUsuario=c.UsuarioC");
connection.query(sql,function(error,rows){
if (error){
throw error;
}else{
return callback(null,rows);
}
})
}
}
Comments.changecommentestado=function(id,comentario, callback){
if (connection){
var sql=("update comentarios set denunciado='si' where idComentario="+connection.escape(comentario));
connection.query(sql,function(error,rows){
if (error){
throw error;
}else{
return callback(null,rows);
}
})
}
}
/* Crear un comentario */
Comments.insert=function(commentData,callback){
if(connection){
connection.query("INSERT INTO comentarios SET ?",commentData,function(error,result){
if (error){
throw error;
}else{
return callback(null,result.insertid);
}
})
}
}
/* Eliminar un Comentario */
Comments.remove=function(Id,callback){
if(connection){
var sql= "DELETE FROM comentarios WHERE idComentario=" + connection.escape(Id);
connection.query(sql,function(error,result){
if(error){
throw error;
}else{
return callback(null,"Comentario eliminado");
}
})
}
}
/* Mostar los comentarios de un restaurante */
Comments.findcomment=function(id,contenido, callback){
if (connection){
var sql="SELECT DISTINCT c.idComentario, u.idUsuario, c.contenido, c.fecha, u.nombre, c.denunciado FROM restaurantes r, comentarios c, usuarios u WHERE usuarioC=idUsuario and restauranteC=idRestaurante and c.RestauranteC="+connection.escape(id)+" AND contenido like '%"+contenido+"%'";
connection.query(sql,function(error,rows){
if (error){
throw error;
}else{
return callback(null,rows);
}
})
}
}
module.exports=Comments;
| 32.522124 | 293 | 0.607619 |
4353ad2ba651a5ca3e4e9b7c61b97d97b91f10a4 | 927 | js | JavaScript | node_modules/@ionic/core/dist/ionic/p-0c976852.js | PacoEstrada18/moodle127 | b9b1671c57be4d6e1e597b2139e1d8dc9cd78f4e | [
"Apache-2.0"
] | null | null | null | node_modules/@ionic/core/dist/ionic/p-0c976852.js | PacoEstrada18/moodle127 | b9b1671c57be4d6e1e597b2139e1d8dc9cd78f4e | [
"Apache-2.0"
] | 45 | 2021-11-03T20:48:50.000Z | 2021-12-14T21:22:12.000Z | staticfiles/ionic/p-0c976852.js | NiklasMerz/shoppinglist | 38c494b2a2f80a0c543beaf0d9d9a75870bdbb22 | [
"MIT"
] | null | null | null | import{c as t}from"./p-613c0939.js";import{g as o}from"./p-d3682733.js";import"./p-f4d641a6.js";import"./p-3df3e749.js";const r=(r,i)=>{const a="back"===i.direction,s=i.leavingEl,p=o(i.enteringEl),e=p.querySelector("ion-toolbar"),n=t();if(n.addElement(p).fill("both").beforeRemoveClass("ion-page-invisible"),a?n.duration(i.duration||200).easing("cubic-bezier(0.47,0,0.745,0.715)"):n.duration(i.duration||280).easing("cubic-bezier(0.36,0.66,0.04,1)").fromTo("transform","translateY(40px)","translateY(0px)").fromTo("opacity",.01,1),e){const o=t();o.addElement(e),n.addAnimation(o)}if(s&&a){n.duration(i.duration||200).easing("cubic-bezier(0.47,0,0.745,0.715)");const r=t();r.addElement(o(s)).onFinish((t=>{1===t&&r.elements.length>0&&r.elements[0].style.setProperty("display","none")})).fromTo("transform","translateY(0px)","translateY(40px)").fromTo("opacity",1,0),n.addAnimation(r)}return n};export{r as mdTransitionAnimation} | 927 | 927 | 0.70658 |
4353f03dabe2b23dbe67ddcf3637defa0c9ebfaa | 1,375 | js | JavaScript | pub-examples/iWlz_Splits/data/view_30701_data.js | onnohaldar/istd-ld-voorbeelden | f2d949db39193ac1b52c897a6dd0ce5ce1a94c7e | [
"MIT"
] | null | null | null | pub-examples/iWlz_Splits/data/view_30701_data.js | onnohaldar/istd-ld-voorbeelden | f2d949db39193ac1b52c897a6dd0ce5ce1a94c7e | [
"MIT"
] | null | null | null | pub-examples/iWlz_Splits/data/view_30701_data.js | onnohaldar/istd-ld-voorbeelden | f2d949db39193ac1b52c897a6dd0ce5ce1a94c7e | [
"MIT"
] | null | null | null | var viewData = {"id":30701,"isExpandedObject":false};
var objectRelations = {
};
var objectData = {
"30701" : {
"id":30701,
"typeIconPath":"data/icons/UML/UML_ClassDiagram.png",
"data" : [
{
"lang":"nl",
"name":"LDT_Duur",
"type":"Klassendiagram",
"categories":[]
}
]
}
};
var viewReferences = {};
var objectReferences = {
"37594" : 28908
,
"37592" : 37593
,
"37587" : 37588
,
"37599" : 37600
,
"37595" : 37596
,
"37597" : 37598
,
"37601" : 37602
,
"37589" : 37590
,
"37591" : 30065
,
"49565" : 49565
};
var viewpointsData =
[
{"id":"viewpoint42336","name":"Datatype details view","presentationType":"FmtLabelView"}
,{"id":"viewpoint42327","name":"Retourcode is gekoppeld aan regel","presentationType":"FmtLabelView"}
];
var vp_legends =
{
"viewpoint42336": {
"labels" : new Array(),
"content" : new Array()
}
,
"viewpoint42327": {
"labels" : new Array(),
"content" : new Array()
}
};
vp_legends.viewpoint42336.labels[0] = "Labelview";
vp_legends.viewpoint42336.content[0] = new Array();
vp_legends.viewpoint42336.content[0][0] = {value1: "1) ", value2: "Datatype details view"};
vp_legends.viewpoint42327.labels[0] = "Labelview";
vp_legends.viewpoint42327.content[0] = new Array();
vp_legends.viewpoint42327.content[0][0] = {value1: "1) ", value2: "Retourcode is gekoppeld aan regel"};
| 21.825397 | 104 | 0.633455 |
43543c9aaca8966464f53a7470aca2b6e6d5d68b | 4,153 | js | JavaScript | calendar.js | Shivam-999/hrmsf13 | adb06c035935e907f343319be20be7e15303563e | [
"MIT"
] | null | null | null | calendar.js | Shivam-999/hrmsf13 | adb06c035935e907f343319be20be7e15303563e | [
"MIT"
] | null | null | null | calendar.js | Shivam-999/hrmsf13 | adb06c035935e907f343319be20be7e15303563e | [
"MIT"
] | null | null | null | function generate_year_range(start, end) {
var years = "";
for (var year = start; year <= end; year++) {
years += "<option value='" + year + "'>" + year + "</option>";
}
return years;
}
today = new Date();
currentMonth = today.getMonth();
currentYear = today.getFullYear();
selectYear = document.getElementById("year");
selectMonth = document.getElementById("month");
createYear = generate_year_range(1970, 2050);
/** or
* createYear = generate_year_range( 1970, currentYear );
*/
document.getElementById("year").innerHTML = createYear;
var calendar = document.getElementById("calendar");
var lang = calendar.getAttribute('data-lang');
var months = "";
var days = "";
var monthDefault = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var dayDefault = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
if (lang == "en") {
months = monthDefault;
days = dayDefault;
} else if (lang == "id") {
months = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"];
days = ["Ming", "Sen", "Sel", "Rab", "Kam", "Jum", "Sab"];
} else if (lang == "fr") {
months = ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"];
days = ["dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi"];
} else {
months = monthDefault;
days = dayDefault;
}
var $dataHead = "<tr>";
for (dhead in days) {
$dataHead += "<th data-days='" + days[dhead] + "'>" + days[dhead] + "</th>";
}
$dataHead += "</tr>";
//alert($dataHead);
document.getElementById("thead-month").innerHTML = $dataHead;
monthAndYear = document.getElementById("monthAndYear");
showCalendar(currentMonth, currentYear);
function next() {
currentYear = (currentMonth === 11) ? currentYear + 1 : currentYear;
currentMonth = (currentMonth + 1) % 12;
showCalendar(currentMonth, currentYear);
}
function previous() {
currentYear = (currentMonth === 0) ? currentYear - 1 : currentYear;
currentMonth = (currentMonth === 0) ? 11 : currentMonth - 1;
showCalendar(currentMonth, currentYear);
}
function jump() {
currentYear = parseInt(selectYear.value);
currentMonth = parseInt(selectMonth.value);
showCalendar(currentMonth, currentYear);
}
function showCalendar(month, year) {
var firstDay = (new Date(year, month)).getDay();
tbl = document.getElementById("calendar-body");
tbl.innerHTML = "";
monthAndYear.innerHTML = months[month] + " " + year;
selectYear.value = year;
selectMonth.value = month;
// creating all cells
var date = 1;
for (var i = 0; i < 6; i++) {
var row = document.createElement("tr");
for (var j = 0; j < 7; j++) {
if (i === 0 && j < firstDay) {
cell = document.createElement("td");
cellText = document.createTextNode("");
cell.appendChild(cellText);
row.appendChild(cell);
} else if (date > daysInMonth(month, year)) {
break;
} else {
cell = document.createElement("td");
cell.setAttribute("data-date", date);
cell.setAttribute("data-month", month + 1);
cell.setAttribute("data-year", year);
cell.setAttribute("data-month_name", months[month]);
cell.className = "date-picker";
cell.innerHTML = "<span>" + date + "</span>";
if (date === today.getDate() && year === today.getFullYear() && month === today.getMonth()) {
cell.className = "date-picker selected";
}
row.appendChild(cell);
date++;
}
}
tbl.appendChild(row);
}
}
function daysInMonth(iMonth, iYear) {
return 32 - new Date(iYear, iMonth, 32).getDate();
} | 30.536765 | 143 | 0.560318 |
4354c451fca6ae87533854aee05e665368cc2069 | 4,584 | js | JavaScript | commands/Commands/top.gg.js | Diswumpus/slash-commands | f80b2e8408699f53d26bc7c75b6f926e710034c1 | [
"MIT"
] | 2 | 2022-01-18T06:57:35.000Z | 2022-03-25T18:10:47.000Z | commands/Commands/top.gg.js | Diswumpus/slash-commands | f80b2e8408699f53d26bc7c75b6f926e710034c1 | [
"MIT"
] | null | null | null | commands/Commands/top.gg.js | Diswumpus/slash-commands | f80b2e8408699f53d26bc7c75b6f926e710034c1 | [
"MIT"
] | null | null | null | const Discord = require('discord.js');
const color = require('../../color.json').color;
const { SlashCommandBuilder } = require('@discordjs/builders');
const du = require("discord.js-util");
const { createPremiumCode } = require("../../functions");
const UsrVts = require("../../models/user");
const buyItems = [
{
name: "Slashr Premium",
description: "Slashr Premium! Check out https://slashr.xyz/premium to learn more!",
use: "PREMIUM",
price: 50,
id: "PREMIUM_MONTH"
}
]
module.exports = {
name: 'topgg',
c: "Commands",
description: 'Top.gg',
usage: ``,
data: new SlashCommandBuilder()
.setName(`topgg`)
.setDescription("Top.gg")
.addSubcommand(o => {
return o.setName("vote")
.setDescription("Vote for the bot!")
})
.addSubcommandGroup(sg => {
return sg.setName("store")
.setDescription(`The vote store!`)
.addSubcommand(s => {
return s.setName("buy")
.setDescription(`Buy something from the shop.`)
.addStringOption(o => o.setName("id").setDescription("The ID of the item.").setRequired(true))
})
.addSubcommand(s => {
return s.setName("browse")
.setDescription(`Browse the shop.`)
})
}),
/**
*
* @param {Discord.Client} client
* @param {Discord.CommandInteraction} interaction
*/
async execute(client, interaction) {
/**
* @type {"browse" | "buy" | "vote"}
*/
const subcommand = interaction.options.getSubcommand();
if (subcommand === "browse") {
const embeds = [];
let i = 1;
let i2 = 0;
let text = "";
let textLengths = []
let pages = []
let currentPage = "";
let msgCount = 0;
for (const c of buyItems) {
let content = `**Item**: ${c.name}\n**Price:** ${c.price} credits\n**Description:** ${c.description}\n**ID:** \`${c.id}\`\n\n`
let textToAdd = content
currentPage += textToAdd;
msgCount++;
if (msgCount % 10 == 0) {
pages.push(currentPage)
currentPage = []
}
}
if (currentPage.length > 0) pages.push(currentPage)
let ii = 0
for (const textt of pages) {
embeds.push(new Discord.MessageEmbed().setColor("BLURPLE").setAuthor(interaction.user.tag, interaction.user.displayAvatarURL()).setDescription(textt))
}
await new du.pages()
.setEmojis(client.botEmojis.leave.show, client.botEmojis.join.show)
.setInteraction(interaction)
.setPages(embeds)
.send({ ephemeral: true });
} else if (subcommand === "buy") {
const ID = interaction.options.getString("id");
const userVotes = UsrVts.findOne({
id: interaction.user.id
});
if (ID === buyItems[0].id) {
if (userVotes.votes >= buyItems[0].price) {
const preCode = await createPremiumCode("month");
await interaction.reply({
embeds: [
new Discord.MessageEmbed()
.setColor("BLURPLE")
.setDescription(`Created premium code with code: \`${preCode.code}\`. Enable it with \`/enable-premium code:${preCode.code}\`!`)
], ephemeral: true
})
} else {
await interaction.reply({
embeds: [
new Discord.MessageEmbed()
.setColor("BLURPLE")
.setDescription(`You don't have enough vote credits! You must have \`${buyItems[0].price} vote credits\``)
], ephemeral: true
})
}
}
} else if (subcommand === "vote") {
await interaction.reply({ content: `You can vote here!`, ephemeral: true, components: [new Discord.MessageActionRow().addComponents(new Discord.MessageButton().setURL(require('../../color.json').vote).setStyle("LINK").setEmoji(client.botEmojis.topgg.show))] });
}
}
} | 39.517241 | 273 | 0.487784 |
4354c69ce81288cde2f2a217a5b354a1fd4a230f | 1,492 | js | JavaScript | src/transform-array.js | DronKarpenko/basic-js | fd96d36c974e9c22baa5ef4c2091caeb337f39f3 | [
"MIT"
] | null | null | null | src/transform-array.js | DronKarpenko/basic-js | fd96d36c974e9c22baa5ef4c2091caeb337f39f3 | [
"MIT"
] | null | null | null | src/transform-array.js | DronKarpenko/basic-js | fd96d36c974e9c22baa5ef4c2091caeb337f39f3 | [
"MIT"
] | null | null | null | const CustomError = require("../extensions/custom-error");
module.exports = function transform(arr) {
if (Array.isArray(arr)) {
let newArr = arr.slice();
if(newArr.every(elem => elem !== '--discard-next' && elem !== '--discard-prev' && elem !== '--double-next' && elem !== '--double-prev')) {
return newArr;
} else {
for (let index = 0; index <= newArr.length - 1; index++) {
if (newArr[index + 2] === '--discard-prev' && newArr[index] === '--discard-next') {
newArr.splice(index, 3);
index -= 1;
} else if (newArr[index + 2] === '--double-prev' && newArr[index] === '--discard-next') {
newArr.splice(index, 3);
index -= 1;
} else if (newArr[index] === '--discard-next') {
newArr[index + 1] !== undefined ? newArr.splice(index, 2) : newArr.splice(index, 1);
index -= 1;
} else if (newArr[index] === '--discard-prev') {
index - 1 >= 0 ? newArr.splice(index - 1, 2) : newArr.splice(index, 1);
index -= 1;
} else if (newArr[index] === '--double-next') {
newArr[index + 1] !== undefined ? newArr[index] = newArr[index + 1] : newArr.splice(index, 1);
index -= 1;
} else if (newArr[index] === '--double-prev') {
index - 1 >=0 ? newArr[index] = newArr[index - 1] : newArr.splice(index, 1);
index -= 1;
}
}
return transform(newArr);
}
} else {
throw Error;
}
};
| 41.444444 | 142 | 0.510724 |
43552f3bd35936b4ece3d11412321be59ecde35d | 754 | js | JavaScript | docs/src/components/modals/Modal.js | MintKudos/mintflow | 091b2790c4eeafaa3e302490c568c5c837684cb2 | [
"MIT"
] | 2 | 2021-12-07T06:03:15.000Z | 2022-01-09T06:54:02.000Z | docs/src/components/modals/Modal.js | MintKudos/mintflow | 091b2790c4eeafaa3e302490c568c5c837684cb2 | [
"MIT"
] | null | null | null | docs/src/components/modals/Modal.js | MintKudos/mintflow | 091b2790c4eeafaa3e302490c568c5c837684cb2 | [
"MIT"
] | 2 | 2021-06-14T13:34:13.000Z | 2021-09-24T22:14:35.000Z | import React from "react";
function Modal() {
return (
<div>
<label for="my-modal-2" class="btn btn-primary modal-button">open modal</label>
<input type="checkbox" id="my-modal-2" class="modal-toggle" />
<div class="modal">
<div class="modal-box">
<p>Enim dolorem dolorum omnis atque necessitatibus. Consequatur aut adipisci qui iusto illo eaque. Consequatur repudiandae et. Nulla ea quasi eligendi. Saepe velit autem minima.</p>
<div class="modal-action">
<label for="my-modal-2" class="btn btn-primary">Accept</label>
<label for="my-modal-2" class="btn">Close</label>
</div>
</div>
</div>
</div>
);
}
export default Modal; | 35.904762 | 192 | 0.595491 |
4356e1f189a9af127a38c50c453ff288df72424f | 7,673 | js | JavaScript | Forecast.lbaction/Contents/Scripts/location.js | jwhitley/launchbar | 23a947f3b4b168c6cf4c1c0cbc9be8f980605e27 | [
"Apache-2.0"
] | 130 | 2015-01-05T17:36:23.000Z | 2022-03-12T12:54:02.000Z | Forecast.lbaction/Contents/Scripts/location.js | jwhitley/launchbar | 23a947f3b4b168c6cf4c1c0cbc9be8f980605e27 | [
"Apache-2.0"
] | 20 | 2015-09-11T22:19:06.000Z | 2022-01-18T14:29:37.000Z | Forecast.lbaction/Contents/Scripts/location.js | jwhitley/launchbar | 23a947f3b4b168c6cf4c1c0cbc9be8f980605e27 | [
"Apache-2.0"
] | 15 | 2015-04-08T18:13:47.000Z | 2022-01-17T11:12:55.000Z | var EXISTS_FILTER = function(x){return (x && x!== undefined && x !== false)};
var LOC_FILE = Action.supportPath + '/locations.json';
var HOME_ICON = '/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/HomeFolderIcon.icns';
var DEFAULT_ICON = 'ABLocation.icns';
var FOLLOW_NBR = 9999;
var FOLLOW_ICON = '/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/MagnifyingGlassIcon.icns';
var FOLLOW_NAME = 'Follow-Me';
var FOLLOW_SUB = 'Dynamic location that follows your current whereabouts';
var PLANE_ICON = 'airplane.png';
function getLocations() {
var kids = [];
var locs = readLocations();
var followMe = false;
for (var i = 0; i < locs.length; i++) {
var loc = locs[i];
var admin = [];
if (loc.latitude == FOLLOW_NBR)
followMe = true;
admin.push({'title':'Forecast'
,'name':loc.name,'latitude':loc.latitude,'longitude':loc.longitude,'ico':loc.icon
,'icon':'Sun-Low.png'
,'actionReturnsItems':true
,'action':'actionForecast'});
admin.push({'title':'Set as Default Location'
,'name':loc.name,'latitude':loc.latitude,'longitude':loc.longitude,'ico':loc.icon
,'icon':loc.icon
,'actionRunsInBackground':true
,'action':'actionSelect'});
admin.push({'title':'Rename ' + loc.name
,'name':loc.name,'latitude':loc.latitude,'longitude':loc.longitude,'ico':loc.icon
,'icon':'Text.icns'
,'actionRunsInBackground':true
,'action':'actionRename'});
admin.push({'title':'Change Icon'
,'name':loc.name,'latitude':loc.latitude,'longitude':loc.longitude,'ico':loc.icon
,'icon':'Text.icns'
,'actionRunsInBackground':true
,'action':'actionIcon'});
admin.push({'title':'Set Home Icon'
,'name':loc.name,'latitude':loc.latitude,'longitude':loc.longitude,'ico':loc.icon
,'icon':HOME_ICON
,'action':'actionHome'});
admin.push({'title':'Set Airplane Icon'
,'name':loc.name,'latitude':loc.latitude,'longitude':loc.longitude,'ico':loc.icon
,'icon':PLANE_ICON
,'action':'actionPlane'});
admin.push({'title':'Remove ' + loc.name
,'name':loc.name,'latitude':loc.latitude,'longitude':loc.longitude,'ico':loc.icon
,'actionRunsInBackground':true
,'icon':'/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/TrashIcon.icns'
,'action':'actionRemove'});
kids.push({'title':loc.name
,'name':loc.name,'latitude':loc.latitude,'longitude':loc.longitude,'ico':loc.icon
,'subtitle':(loc.latitude == FOLLOW_NBR?FOLLOW_SUB:'Latitude ' + loc.latitude + ' Longitude:' + loc.longitude)
,'actionRunsInBackground':true
,'icon':loc.icon
,'action':'actionSelect'
,'children':admin});
}
if (!followMe) {
kids.push({'title':'Add Follow-Me Current Location'
,'subtitle':FOLLOW_SUB
,'name':FOLLOW_NAME,'latitude':FOLLOW_NBR,'longitude':FOLLOW_NBR,'ico':FOLLOW_ICON
,'icon':FOLLOW_ICON
,'actionRunsInBackground':true
,'action':'actionSelect'});
}
var curr = getCurrentLocation();
if (curr == null) {
kids.push({'title':'Current Location not available','icon':'NotFound.icns'});
} else {
var f = [];
f.push({'title':'Forecast'
,'name':curr.name,'latitude':curr.latitude,'longitude':curr.longitude,'ico':curr.icon
,'icon':'Sun-Low.png'
,'actionReturnsItems':true
,'action':'actionForecast'});
kids.push({'title':'Add ' + curr.name + ' Location'
,'name':curr.name,'latitude':curr.latitude,'longitude':curr.longitude,'ico':curr.icon
,'icon':DEFAULT_ICON
,'actionRunsInBackground':true
,'children':f
,'action':'actionSelect'});
}
if (isDebug()) {
kids.push({'title':'Edit locations.json'
,'actionRunsInBackground':true
,'path':LOC_FILE
,'action':'actionJSON'});
}
return kids;
}
function selectedLoc() {
var locs = readLocations();
if (locs && locs != undefined && locs.length > 0) {
var loc = locs[0];
if (loc.latitude == FOLLOW_NBR) {
var curr = getCurrentLocation();
if (curr == null)
return null;
curr.icon = loc.icon;
return curr;
} else {
return loc;
}
}
}
function actionSelect(item) {
locationAdd(item.name, item.latitude, item.longitude, item.ico);
}
function actionForecast(item) {
return forecast({'name':item.name, 'latitude':item.latitude, 'longitude':item.longitude, 'icon':item.ico});
}
function actionRename(item) {
var n = LaunchBar.executeAppleScript(
'return text returned of (display dialog "Name:" default answer "' + item.name + '" giving up after 15 with icon note)');
if (n && n.length > 0) {
var locs = readLocations();
for (var i=0; i < locs.length; i++) {
var loc = locs[i];
if (loc.latitude == item.latitude && loc.longitude == item.longitude) {
loc.name = n.trim();
writeLocations(locs);
break;
}
}
}
}
function actionIcon(item) {
var ico = LaunchBar.executeAppleScript(
'return text returned of (display dialog "Icon:" default answer "' + item.icon + '" giving up after 15 with icon note)');
if (ico && ico.length > 0) {
var locs = readLocations();
for (var i=0; i < locs.length; i++) {
var loc = locs[i];
if (loc.latitude == item.latitude && loc.longitude == item.longitude) {
loc.icon = ico.trim();
writeLocations(locs);
break;
}
}
}
}
function actionHome(item) {
var locs = readLocations();
for (var i=0; i < locs.length; i++) {
var loc = locs[i];
if (loc.latitude == item.latitude && loc.longitude == item.longitude) {
loc.icon = HOME_ICON;
writeLocations(locs);
break;
}
}
}
function actionPlane(item) {
var locs = readLocations();
for (var i=0; i < locs.length; i++) {
var loc = locs[i];
if (loc.latitude == item.latitude && loc.longitude == item.longitude) {
loc.icon = PLANE_ICON;
writeLocations(locs);
break;
}
}
}
function actionRemove(item) {
var locs = readLocations();
for (var i=0; i < locs.length; i++) {
var loc = locs[i];
if (loc.latitude == item.latitude && loc.longitude == item.longitude) {
locs[i] = false;
writeLocations(locs);
break;
}
}
}
function actionJSON(item) {
LaunchBar.openURL('file:/' + encodeURIComponent(LOC_FILE), 'TextEdit');
}
// add a new location to the top (selected) position
function locationAdd(name, latitude, longitude, icon) {
var locs = [];
locs.push({'name':name,'latitude':latitude,'longitude':longitude
,'icon':(icon && icon != undefined && icon.length > 0?icon:DEFAULT_ICON)});
locs = locs.concat(readLocations());
writeLocations(locs);
}
function readLocations() {
// locations file is a json Array, of object containing name,latitude,longitude
if (File.exists(LOC_FILE)) {
try {
return File.readJSON(LOC_FILE);
} catch (exception) {
LaunchBar.log('Error readLocations ' + exception);
LaunchBar.alert('Error readLocations', exception);
}
} else {
writeLocations([]);
}
return [];
}
function writeLocations(locations) {
var locs = locations.filter(EXISTS_FILTER);
// remove duplicates
for (var i=0; i < locs.length; i++) {
var loc = locs[i];
for (var j=i+1; j < locs.length; j++) {
var other = locs[j];
if (other !== false && loc.latitude == other.latitude && loc.longitude == other.longitude) {
locs[j] = false;
}
}
}
try {
File.writeJSON(locs.filter(EXISTS_FILTER), LOC_FILE);
} catch (exception) {
LaunchBar.log('Error writeLocations ' + exception);
LaunchBar.alert('Error writeLocations', exception);
}
return loc;
}
| 32.104603 | 125 | 0.63352 |
435724956ffdc0b9fe4faaf054c05571f51a9832 | 1,161 | js | JavaScript | build-config/rollup.node.js | shuckster/compose-paths | e7fe65e10ec76fe420441360905cc40328cc9feb | [
"MIT"
] | null | null | null | build-config/rollup.node.js | shuckster/compose-paths | e7fe65e10ec76fe420441360905cc40328cc9feb | [
"MIT"
] | null | null | null | build-config/rollup.node.js | shuckster/compose-paths | e7fe65e10ec76fe420441360905cc40328cc9feb | [
"MIT"
] | null | null | null | //
// Build with Rollup
//
const json = require('@rollup/plugin-json')
const commonjs = require('@rollup/plugin-commonjs')
const replace = require('@rollup/plugin-replace')
const { nodeResolve } = require('@rollup/plugin-node-resolve')
const { terser } = require('rollup-plugin-terser')
const cleanup = require('rollup-plugin-cleanup')
const pkg = require('../package.json')
const { paths, banner, outputs } = require('./common')
const terserConfig = {
output: {
ecma: 5,
comments: (node, comment) => {
var text = comment.value
var type = comment.type
if (type == 'comment2') {
// multiline comment
return /License: /.test(text)
}
}
}
}
module.exports = {
input: paths.SRC,
output: outputs
.filter(output => output.format === 'cjs')
.map(output => ({
...output,
banner: banner(pkg),
plugins: [terser(terserConfig)],
exports: 'named'
})),
plugins: [
json(),
replace({
preventAssignment: true,
'process.env.RUNNING_JEST': '"false"',
'process.env.BUILD_FOR_NODE': `"true"`
}),
nodeResolve(),
commonjs(),
cleanup()
]
}
| 22.764706 | 62 | 0.598622 |
4357343f34cbad862b9d1daf32063a1e0ff9e376 | 216,346 | js | JavaScript | app-0b88e009ca55689864e7.js | jeanarjean/rorscharg.github.io | 4b9b3566ef1e418671e8334b705fd50f7f19390f | [
"MIT"
] | null | null | null | app-0b88e009ca55689864e7.js | jeanarjean/rorscharg.github.io | 4b9b3566ef1e418671e8334b705fd50f7f19390f | [
"MIT"
] | null | null | null | app-0b88e009ca55689864e7.js | jeanarjean/rorscharg.github.io | 4b9b3566ef1e418671e8334b705fd50f7f19390f | [
"MIT"
] | null | null | null | /*! For license information please see app-0b88e009ca55689864e7.js.LICENSE.txt */
;(window.webpackJsonp = window.webpackJsonp || []).push([
[6],
{
'+ZDr': function (e, t, n) {
'use strict'
var r = n('5NKs')
;(t.__esModule = !0),
(t.withPrefix = h),
(t.withAssetPrefix = function (e) {
return h(e, m())
}),
(t.navigateTo =
t.replace =
t.push =
t.navigate =
t.default =
void 0)
var o = r(n('uDP2')),
a = r(n('j8BX')),
i = r(n('v06X')),
u = r(n('XEEL')),
c = r(n('17x9')),
s = r(n('q1tI')),
l = n('YwZP'),
p = n('LYrO'),
f = n('cu4x')
t.parsePath = f.parsePath
var d = function (e) {
return null == e ? void 0 : e.startsWith('/')
}
function h(e, t) {
var n, r
if ((void 0 === t && (t = v()), !g(e))) return e
if (e.startsWith('./') || e.startsWith('../')) return e
var o =
null !== (n = null !== (r = t) && void 0 !== r ? r : m()) &&
void 0 !== n
? n
: '/'
return (
'' +
((null == o ? void 0 : o.endsWith('/'))
? o.slice(0, -1)
: o) +
(e.startsWith('/') ? e : '/' + e)
)
}
var m = function () {
return ''
},
v = function () {
return ''
},
g = function (e) {
return (
e &&
!e.startsWith('http://') &&
!e.startsWith('https://') &&
!e.startsWith('//')
)
}
var y = function (e, t) {
return 'number' == typeof e
? e
: g(e)
? d(e)
? h(e)
: (function (e, t) {
return d(e) ? e : (0, p.resolve)(e, t)
})(e, t)
: e
},
b = {
activeClassName: c.default.string,
activeStyle: c.default.object,
partiallyActive: c.default.bool
},
w = (function (e) {
function t(t) {
var n
;(n = e.call(this, t) || this).defaultGetProps =
function (e) {
var t = e.isPartiallyCurrent,
r = e.isCurrent
return (n.props.partiallyActive ? t : r)
? {
className: [
n.props.className,
n.props.activeClassName
]
.filter(Boolean)
.join(' '),
style: (0, a.default)(
{},
n.props.style,
n.props.activeStyle
)
}
: null
}
var r = !1
return (
'undefined' != typeof window &&
window.IntersectionObserver &&
(r = !0),
(n.state = { IOSupported: r }),
(n.handleRef = n.handleRef.bind((0, i.default)(n))),
n
)
}
;(0, u.default)(t, e)
var n = t.prototype
return (
(n.componentDidUpdate = function (e, t) {
this.props.to === e.to ||
this.state.IOSupported ||
___loader.enqueue(
(0, f.parsePath)(
y(
this.props.to,
window.location.pathname
)
).pathname
)
}),
(n.componentDidMount = function () {
this.state.IOSupported ||
___loader.enqueue(
(0, f.parsePath)(
y(
this.props.to,
window.location.pathname
)
).pathname
)
}),
(n.componentWillUnmount = function () {
if (this.io) {
var e = this.io,
t = e.instance,
n = e.el
t.unobserve(n), t.disconnect()
}
}),
(n.handleRef = function (e) {
var t,
n,
r,
o = this
this.props.innerRef &&
this.props.innerRef.hasOwnProperty('current')
? (this.props.innerRef.current = e)
: this.props.innerRef && this.props.innerRef(e),
this.state.IOSupported &&
e &&
(this.io =
((t = e),
(n = function () {
___loader.enqueue(
(0, f.parsePath)(
y(
o.props.to,
window.location.pathname
)
).pathname
)
}),
(r = new window.IntersectionObserver(
function (e) {
e.forEach(function (e) {
t === e.target &&
(e.isIntersecting ||
e.intersectionRatio >
0) &&
(r.unobserve(t),
r.disconnect(),
n())
})
}
)).observe(t),
{ instance: r, el: t }))
}),
(n.render = function () {
var e = this,
t = this.props,
n = t.to,
r = t.getProps,
i = void 0 === r ? this.defaultGetProps : r,
u = t.onClick,
c = t.onMouseEnter,
p =
(t.activeClassName,
t.activeStyle,
t.innerRef,
t.partiallyActive,
t.state),
d = t.replace,
h = (0, o.default)(t, [
'to',
'getProps',
'onClick',
'onMouseEnter',
'activeClassName',
'activeStyle',
'innerRef',
'partiallyActive',
'state',
'replace'
])
return s.default.createElement(
l.Location,
null,
function (t) {
var r = t.location,
o = y(n, r.pathname)
return g(o)
? s.default.createElement(
l.Link,
(0, a.default)(
{
to: o,
state: p,
getProps: i,
innerRef: e.handleRef,
onMouseEnter: function (
e
) {
c && c(e),
___loader.hovering(
(0,
f.parsePath)(
o
).pathname
)
},
onClick: function (t) {
if (
(u && u(t),
!(
0 !==
t.button ||
e.props
.target ||
t.defaultPrevented ||
t.metaKey ||
t.altKey ||
t.ctrlKey ||
t.shiftKey
))
) {
t.preventDefault()
var n = d,
r =
encodeURI(
o
) ===
window
.location
.pathname
'boolean' !=
typeof d &&
r &&
(n = !0),
window.___navigate(
o,
{
state: p,
replace:
n
}
)
}
return !0
}
},
h
)
)
: s.default.createElement(
'a',
(0, a.default)({ href: o }, h)
)
}
)
}),
t
)
})(s.default.Component)
w.propTypes = (0, a.default)({}, b, {
onClick: c.default.func,
to: c.default.string.isRequired,
replace: c.default.bool,
state: c.default.object
})
var P = function (e, t, n) {
return console.warn(
'The "' +
e +
'" method is now deprecated and will be removed in Gatsby v' +
n +
'. Please use "' +
t +
'" instead.'
)
},
O = s.default.forwardRef(function (e, t) {
return s.default.createElement(
w,
(0, a.default)({ innerRef: t }, e)
)
})
t.default = O
t.navigate = function (e, t) {
window.___navigate(y(e, window.location.pathname), t)
}
var S = function (e) {
P('push', 'navigate', 3),
window.___push(y(e, window.location.pathname))
}
t.push = S
t.replace = function (e) {
P('replace', 'navigate', 3),
window.___replace(y(e, window.location.pathname))
}
t.navigateTo = function (e) {
return P('navigateTo', 'navigate', 3), S(e)
}
},
'/MKj': function (e, t, n) {
'use strict'
n.d(t, 'a', function () {
return l
}),
n.d(t, 'b', function () {
return q
})
var r = n('q1tI'),
o = n.n(r),
a = o.a.createContext(null)
var i = function (e) {
e()
},
u = { notify: function () {} }
function c() {
var e = i,
t = null,
n = null
return {
clear: function () {
;(t = null), (n = null)
},
notify: function () {
e(function () {
for (var e = t; e; ) e.callback(), (e = e.next)
})
},
get: function () {
for (var e = [], n = t; n; ) e.push(n), (n = n.next)
return e
},
subscribe: function (e) {
var r = !0,
o = (n = { callback: e, next: null, prev: n })
return (
o.prev ? (o.prev.next = o) : (t = o),
function () {
r &&
null !== t &&
((r = !1),
o.next
? (o.next.prev = o.prev)
: (n = o.prev),
o.prev
? (o.prev.next = o.next)
: (t = o.next))
}
)
}
}
}
var s = (function () {
function e(e, t) {
;(this.store = e),
(this.parentSub = t),
(this.unsubscribe = null),
(this.listeners = u),
(this.handleChangeWrapper =
this.handleChangeWrapper.bind(this))
}
var t = e.prototype
return (
(t.addNestedSub = function (e) {
return this.trySubscribe(), this.listeners.subscribe(e)
}),
(t.notifyNestedSubs = function () {
this.listeners.notify()
}),
(t.handleChangeWrapper = function () {
this.onStateChange && this.onStateChange()
}),
(t.isSubscribed = function () {
return Boolean(this.unsubscribe)
}),
(t.trySubscribe = function () {
this.unsubscribe ||
((this.unsubscribe = this.parentSub
? this.parentSub.addNestedSub(
this.handleChangeWrapper
)
: this.store.subscribe(
this.handleChangeWrapper
)),
(this.listeners = c()))
}),
(t.tryUnsubscribe = function () {
this.unsubscribe &&
(this.unsubscribe(),
(this.unsubscribe = null),
this.listeners.clear(),
(this.listeners = u))
}),
e
)
})()
var l = function (e) {
var t = e.store,
n = e.context,
i = e.children,
u = Object(r.useMemo)(
function () {
var e = new s(t)
return (
(e.onStateChange = e.notifyNestedSubs),
{ store: t, subscription: e }
)
},
[t]
),
c = Object(r.useMemo)(
function () {
return t.getState()
},
[t]
)
Object(r.useEffect)(
function () {
var e = u.subscription
return (
e.trySubscribe(),
c !== t.getState() && e.notifyNestedSubs(),
function () {
e.tryUnsubscribe(), (e.onStateChange = null)
}
)
},
[u, c]
)
var l = n || a
return o.a.createElement(l.Provider, { value: u }, i)
}
function p() {
return (p =
Object.assign ||
function (e) {
for (var t = 1; t < arguments.length; t++) {
var n = arguments[t]
for (var r in n)
Object.prototype.hasOwnProperty.call(n, r) &&
(e[r] = n[r])
}
return e
}).apply(this, arguments)
}
function f(e, t) {
if (null == e) return {}
var n,
r,
o = {},
a = Object.keys(e)
for (r = 0; r < a.length; r++)
(n = a[r]), t.indexOf(n) >= 0 || (o[n] = e[n])
return o
}
var d = n('2mql'),
h = n.n(d),
m = n('0vxD'),
v =
'undefined' != typeof window &&
void 0 !== window.document &&
void 0 !== window.document.createElement
? r.useLayoutEffect
: r.useEffect,
g = [],
y = [null, null]
function b(e, t) {
var n = e[1]
return [t.payload, n + 1]
}
function w(e, t, n) {
v(function () {
return e.apply(void 0, t)
}, n)
}
function P(e, t, n, r, o, a, i) {
;(e.current = r),
(t.current = o),
(n.current = !1),
a.current && ((a.current = null), i())
}
function O(e, t, n, r, o, a, i, u, c, s) {
if (e) {
var l = !1,
p = null,
f = function () {
if (!l) {
var e,
n,
f = t.getState()
try {
e = r(f, o.current)
} catch (d) {
;(n = d), (p = d)
}
n || (p = null),
e === a.current
? i.current || c()
: ((a.current = e),
(u.current = e),
(i.current = !0),
s({
type: 'STORE_UPDATED',
payload: { error: n }
}))
}
}
;(n.onStateChange = f), n.trySubscribe(), f()
return function () {
if (
((l = !0),
n.tryUnsubscribe(),
(n.onStateChange = null),
p)
)
throw p
}
}
}
var S = function () {
return [null, 0]
}
function j(e, t) {
void 0 === t && (t = {})
var n = t,
i = n.getDisplayName,
u =
void 0 === i
? function (e) {
return 'ConnectAdvanced(' + e + ')'
}
: i,
c = n.methodName,
l = void 0 === c ? 'connectAdvanced' : c,
d = n.renderCountProp,
v = void 0 === d ? void 0 : d,
j = n.shouldHandleStateChanges,
E = void 0 === j || j,
R = n.storeKey,
C = void 0 === R ? 'store' : R,
x = (n.withRef, n.forwardRef),
_ = void 0 !== x && x,
k = n.context,
T = void 0 === k ? a : k,
D = f(n, [
'getDisplayName',
'methodName',
'renderCountProp',
'shouldHandleStateChanges',
'storeKey',
'withRef',
'forwardRef',
'context'
]),
L = T
return function (t) {
var n = t.displayName || t.name || 'Component',
a = u(n),
i = p({}, D, {
getDisplayName: u,
methodName: l,
renderCountProp: v,
shouldHandleStateChanges: E,
storeKey: C,
displayName: a,
wrappedComponentName: n,
WrappedComponent: t
}),
c = D.pure
var d = c
? r.useMemo
: function (e) {
return e()
}
function j(n) {
var a = Object(r.useMemo)(
function () {
var e = n.reactReduxForwardedRef,
t = f(n, ['reactReduxForwardedRef'])
return [n.context, e, t]
},
[n]
),
u = a[0],
c = a[1],
l = a[2],
h = Object(r.useMemo)(
function () {
return u &&
u.Consumer &&
Object(m.isContextConsumer)(
o.a.createElement(u.Consumer, null)
)
? u
: L
},
[u, L]
),
v = Object(r.useContext)(h),
j =
Boolean(n.store) &&
Boolean(n.store.getState) &&
Boolean(n.store.dispatch)
Boolean(v) && Boolean(v.store)
var R = j ? n.store : v.store,
C = Object(r.useMemo)(
function () {
return (function (t) {
return e(t.dispatch, i)
})(R)
},
[R]
),
x = Object(r.useMemo)(
function () {
if (!E) return y
var e = new s(R, j ? null : v.subscription),
t = e.notifyNestedSubs.bind(e)
return [e, t]
},
[R, j, v]
),
_ = x[0],
k = x[1],
T = Object(r.useMemo)(
function () {
return j ? v : p({}, v, { subscription: _ })
},
[j, v, _]
),
D = Object(r.useReducer)(b, g, S),
M = D[0][0],
N = D[1]
if (M && M.error) throw M.error
var I = Object(r.useRef)(),
A = Object(r.useRef)(l),
U = Object(r.useRef)(),
F = Object(r.useRef)(!1),
W = d(
function () {
return U.current && l === A.current
? U.current
: C(R.getState(), l)
},
[R, M, l]
)
w(P, [A, I, F, l, W, U, k]),
w(O, [E, R, _, C, A, I, F, U, k, N], [R, _, C])
var q = Object(r.useMemo)(
function () {
return o.a.createElement(
t,
p({}, W, { ref: c })
)
},
[c, t, W]
)
return Object(r.useMemo)(
function () {
return E
? o.a.createElement(
h.Provider,
{ value: T },
q
)
: q
},
[h, q, T]
)
}
var R = c ? o.a.memo(j) : j
if (((R.WrappedComponent = t), (R.displayName = a), _)) {
var x = o.a.forwardRef(function (e, t) {
return o.a.createElement(
R,
p({}, e, { reactReduxForwardedRef: t })
)
})
return (
(x.displayName = a),
(x.WrappedComponent = t),
h()(x, t)
)
}
return h()(R, t)
}
}
function E(e, t) {
return e === t
? 0 !== e || 0 !== t || 1 / e == 1 / t
: e != e && t != t
}
function R(e, t) {
if (E(e, t)) return !0
if (
'object' != typeof e ||
null === e ||
'object' != typeof t ||
null === t
)
return !1
var n = Object.keys(e),
r = Object.keys(t)
if (n.length !== r.length) return !1
for (var o = 0; o < n.length; o++)
if (
!Object.prototype.hasOwnProperty.call(t, n[o]) ||
!E(e[n[o]], t[n[o]])
)
return !1
return !0
}
var C = n('ANjH')
function x(e) {
return function (t, n) {
var r = e(t, n)
function o() {
return r
}
return (o.dependsOnOwnProps = !1), o
}
}
function _(e) {
return null !== e.dependsOnOwnProps &&
void 0 !== e.dependsOnOwnProps
? Boolean(e.dependsOnOwnProps)
: 1 !== e.length
}
function k(e, t) {
return function (t, n) {
n.displayName
var r = function (e, t) {
return r.dependsOnOwnProps
? r.mapToProps(e, t)
: r.mapToProps(e)
}
return (
(r.dependsOnOwnProps = !0),
(r.mapToProps = function (t, n) {
;(r.mapToProps = e), (r.dependsOnOwnProps = _(e))
var o = r(t, n)
return (
'function' == typeof o &&
((r.mapToProps = o),
(r.dependsOnOwnProps = _(o)),
(o = r(t, n))),
o
)
}),
r
)
}
}
var T = [
function (e) {
return 'function' == typeof e ? k(e) : void 0
},
function (e) {
return e
? void 0
: x(function (e) {
return { dispatch: e }
})
},
function (e) {
return e && 'object' == typeof e
? x(function (t) {
return Object(C.a)(e, t)
})
: void 0
}
]
var D = [
function (e) {
return 'function' == typeof e ? k(e) : void 0
},
function (e) {
return e
? void 0
: x(function () {
return {}
})
}
]
function L(e, t, n) {
return p({}, n, e, t)
}
var M = [
function (e) {
return 'function' == typeof e
? (function (e) {
return function (t, n) {
n.displayName
var r,
o = n.pure,
a = n.areMergedPropsEqual,
i = !1
return function (t, n, u) {
var c = e(t, n, u)
return (
i
? (o && a(c, r)) || (r = c)
: ((i = !0), (r = c)),
r
)
}
}
})(e)
: void 0
},
function (e) {
return e
? void 0
: function () {
return L
}
}
]
function N(e, t, n, r) {
return function (o, a) {
return n(e(o, a), t(r, a), a)
}
}
function I(e, t, n, r, o) {
var a,
i,
u,
c,
s,
l = o.areStatesEqual,
p = o.areOwnPropsEqual,
f = o.areStatePropsEqual,
d = !1
function h(o, d) {
var h,
m,
v = !p(d, i),
g = !l(o, a)
return (
(a = o),
(i = d),
v && g
? ((u = e(a, i)),
t.dependsOnOwnProps && (c = t(r, i)),
(s = n(u, c, i)))
: v
? (e.dependsOnOwnProps && (u = e(a, i)),
t.dependsOnOwnProps && (c = t(r, i)),
(s = n(u, c, i)))
: g
? ((h = e(a, i)),
(m = !f(h, u)),
(u = h),
m && (s = n(u, c, i)),
s)
: s
)
}
return function (o, l) {
return d
? h(o, l)
: ((u = e((a = o), (i = l))),
(c = t(r, i)),
(s = n(u, c, i)),
(d = !0),
s)
}
}
function A(e, t) {
var n = t.initMapStateToProps,
r = t.initMapDispatchToProps,
o = t.initMergeProps,
a = f(t, [
'initMapStateToProps',
'initMapDispatchToProps',
'initMergeProps'
]),
i = n(e, a),
u = r(e, a),
c = o(e, a)
return (a.pure ? I : N)(i, u, c, e, a)
}
function U(e, t, n) {
for (var r = t.length - 1; r >= 0; r--) {
var o = t[r](e)
if (o) return o
}
return function (t, r) {
throw new Error(
'Invalid value of type ' +
typeof e +
' for ' +
n +
' argument when connecting component ' +
r.wrappedComponentName +
'.'
)
}
}
function F(e, t) {
return e === t
}
function W(e) {
var t = void 0 === e ? {} : e,
n = t.connectHOC,
r = void 0 === n ? j : n,
o = t.mapStateToPropsFactories,
a = void 0 === o ? D : o,
i = t.mapDispatchToPropsFactories,
u = void 0 === i ? T : i,
c = t.mergePropsFactories,
s = void 0 === c ? M : c,
l = t.selectorFactory,
d = void 0 === l ? A : l
return function (e, t, n, o) {
void 0 === o && (o = {})
var i = o,
c = i.pure,
l = void 0 === c || c,
h = i.areStatesEqual,
m = void 0 === h ? F : h,
v = i.areOwnPropsEqual,
g = void 0 === v ? R : v,
y = i.areStatePropsEqual,
b = void 0 === y ? R : y,
w = i.areMergedPropsEqual,
P = void 0 === w ? R : w,
O = f(i, [
'pure',
'areStatesEqual',
'areOwnPropsEqual',
'areStatePropsEqual',
'areMergedPropsEqual'
]),
S = U(e, a, 'mapStateToProps'),
j = U(t, u, 'mapDispatchToProps'),
E = U(n, s, 'mergeProps')
return r(
d,
p(
{
methodName: 'connect',
getDisplayName: function (e) {
return 'Connect(' + e + ')'
},
shouldHandleStateChanges: Boolean(e),
initMapStateToProps: S,
initMapDispatchToProps: j,
initMergeProps: E,
pure: l,
areStatesEqual: m,
areOwnPropsEqual: g,
areStatePropsEqual: b,
areMergedPropsEqual: P
},
O
)
)
}
}
var q = W()
var $,
H = n('i8i4')
;($ = H.unstable_batchedUpdates), (i = $)
},
'/hTd': function (e, t, n) {
'use strict'
;(t.__esModule = !0), (t.SessionStorage = void 0)
var r = (function () {
function e() {}
var t = e.prototype
return (
(t.read = function (e, t) {
var n = this.getStateKey(e, t)
try {
var r = window.sessionStorage.getItem(n)
return r ? JSON.parse(r) : 0
} catch (o) {
return window &&
window.___GATSBY_REACT_ROUTER_SCROLL &&
window.___GATSBY_REACT_ROUTER_SCROLL[n]
? window.___GATSBY_REACT_ROUTER_SCROLL[n]
: 0
}
}),
(t.save = function (e, t, n) {
var r = this.getStateKey(e, t),
o = JSON.stringify(n)
try {
window.sessionStorage.setItem(r, o)
} catch (a) {
;(window && window.___GATSBY_REACT_ROUTER_SCROLL) ||
(window.___GATSBY_REACT_ROUTER_SCROLL = {}),
(window.___GATSBY_REACT_ROUTER_SCROLL[r] =
JSON.parse(o))
}
}),
(t.getStateKey = function (e, t) {
var n = '@@scroll|' + e.pathname
return null == t ? n : n + '|' + t
}),
e
)
})()
t.SessionStorage = r
},
'0vxD': function (e, t, n) {
'use strict'
e.exports = n('DUzY')
},
'2mql': function (e, t, n) {
'use strict'
var r = n('TOwV'),
o = {
childContextTypes: !0,
contextType: !0,
contextTypes: !0,
defaultProps: !0,
displayName: !0,
getDefaultProps: !0,
getDerivedStateFromError: !0,
getDerivedStateFromProps: !0,
mixins: !0,
propTypes: !0,
type: !0
},
a = {
name: !0,
length: !0,
prototype: !0,
caller: !0,
callee: !0,
arguments: !0,
arity: !0
},
i = {
$$typeof: !0,
compare: !0,
defaultProps: !0,
displayName: !0,
propTypes: !0,
type: !0
},
u = {}
function c(e) {
return r.isMemo(e) ? i : u[e.$$typeof] || o
}
;(u[r.ForwardRef] = {
$$typeof: !0,
render: !0,
defaultProps: !0,
displayName: !0,
propTypes: !0
}),
(u[r.Memo] = i)
var s = Object.defineProperty,
l = Object.getOwnPropertyNames,
p = Object.getOwnPropertySymbols,
f = Object.getOwnPropertyDescriptor,
d = Object.getPrototypeOf,
h = Object.prototype
e.exports = function e(t, n, r) {
if ('string' != typeof n) {
if (h) {
var o = d(n)
o && o !== h && e(t, o, r)
}
var i = l(n)
p && (i = i.concat(p(n)))
for (var u = c(t), m = c(n), v = 0; v < i.length; ++v) {
var g = i[v]
if (
!(a[g] || (r && r[g]) || (m && m[g]) || (u && u[g]))
) {
var y = f(n, g)
try {
s(t, g, y)
} catch (b) {}
}
}
}
return t
}
},
'30RF': function (e, t, n) {
'use strict'
n.d(t, 'd', function () {
return l
}),
n.d(t, 'a', function () {
return p
}),
n.d(t, 'c', function () {
return f
}),
n.d(t, 'b', function () {
return d
})
var r = n('LYrO'),
o = n('cSJ8'),
a = function (e) {
return void 0 === e
? e
: '/' === e
? '/'
: '/' === e.charAt(e.length - 1)
? e.slice(0, -1)
: e
},
i = new Map(),
u = [],
c = function (e) {
var t = decodeURIComponent(e)
return Object(o.a)(t, '').split('#')[0].split('?')[0]
}
function s(e) {
return e.startsWith('/') ||
e.startsWith('https://') ||
e.startsWith('http://')
? e
: new URL(
e,
window.location.href +
(window.location.href.endsWith('/') ? '' : '/')
).pathname
}
var l = function (e) {
u = e
},
p = function (e) {
var t = h(e),
n = u.map(function (e) {
var t = e.path
return { path: e.matchPath, originalPath: t }
}),
o = Object(r.pick)(n, t)
return o ? a(o.route.originalPath) : null
},
f = function (e) {
var t = h(e),
n = u.map(function (e) {
var t = e.path
return { path: e.matchPath, originalPath: t }
}),
o = Object(r.pick)(n, t)
return o ? o.params : {}
},
d = function (e) {
var t = c(s(e))
if (i.has(t)) return i.get(t)
var n = p(t)
return n || (n = h(e)), i.set(t, n), n
},
h = function (e) {
var t = c(s(e))
return '/index.html' === t && (t = '/'), (t = a(t))
}
},
'3UD+': function (e, t) {
e.exports = function (e) {
if (!e.webpackPolyfill) {
var t = Object.create(e)
t.children || (t.children = []),
Object.defineProperty(t, 'loaded', {
enumerable: !0,
get: function () {
return t.l
}
}),
Object.defineProperty(t, 'id', {
enumerable: !0,
get: function () {
return t.i
}
}),
Object.defineProperty(t, 'exports', { enumerable: !0 }),
(t.webpackPolyfill = 1)
}
return t
}
},
'3uz+': function (e, t, n) {
'use strict'
;(t.__esModule = !0),
(t.useScrollRestoration = function (e) {
var t = (0, a.useLocation)(),
n = (0, o.useContext)(r.ScrollContext),
i = (0, o.useRef)()
return (
(0, o.useLayoutEffect)(function () {
if (i.current) {
var r = n.read(t, e)
i.current.scrollTo(0, r || 0)
}
}, []),
{
ref: i,
onScroll: function () {
i.current && n.save(t, e, i.current.scrollTop)
}
}
)
})
var r = n('Enzk'),
o = n('q1tI'),
a = n('YwZP')
},
'5NKs': function (e, t) {
e.exports = function (e) {
return e && e.__esModule ? e : { default: e }
}
},
'5yr3': function (e, t, n) {
'use strict'
var r = (function (e) {
return (
(e = e || Object.create(null)),
{
on: function (t, n) {
;(e[t] || (e[t] = [])).push(n)
},
off: function (t, n) {
e[t] && e[t].splice(e[t].indexOf(n) >>> 0, 1)
},
emit: function (t, n) {
;(e[t] || []).slice().map(function (e) {
e(n)
}),
(e['*'] || []).slice().map(function (e) {
e(t, n)
})
}
}
)
})()
t.a = r
},
'7hJ6': function (e, t, n) {
'use strict'
;(t.__esModule = !0),
(t.useScrollRestoration =
t.ScrollContainer =
t.ScrollContext =
void 0)
var r = n('Enzk')
t.ScrollContext = r.ScrollHandler
var o = n('hd9s')
t.ScrollContainer = o.ScrollContainer
var a = n('3uz+')
t.useScrollRestoration = a.useScrollRestoration
},
'94VI': function (e, t) {
t.polyfill = function (e) {
return e
}
},
'9Hrx': function (e, t, n) {
'use strict'
function r(e, t) {
;(e.prototype = Object.create(t.prototype)),
(e.prototype.constructor = e),
(e.__proto__ = t)
}
n.d(t, 'a', function () {
return r
})
},
'9Xx/': function (e, t, n) {
'use strict'
n.d(t, 'c', function () {
return c
}),
n.d(t, 'd', function () {
return s
}),
n.d(t, 'a', function () {
return a
}),
n.d(t, 'b', function () {
return i
})
var r =
Object.assign ||
function (e) {
for (var t = 1; t < arguments.length; t++) {
var n = arguments[t]
for (var r in n)
Object.prototype.hasOwnProperty.call(n, r) &&
(e[r] = n[r])
}
return e
},
o = function (e) {
var t = e.location,
n = t.search,
r = t.hash,
o = t.href,
a = t.origin,
i = t.protocol,
c = t.host,
s = t.hostname,
l = t.port,
p = e.location.pathname
!p && o && u && (p = new URL(o).pathname)
return {
pathname: encodeURI(decodeURI(p)),
search: n,
hash: r,
href: o,
origin: a,
protocol: i,
host: c,
hostname: s,
port: l,
state: e.history.state,
key:
(e.history.state && e.history.state.key) ||
'initial'
}
},
a = function (e, t) {
var n = [],
a = o(e),
i = !1,
u = function () {}
return {
get location() {
return a
},
get transitioning() {
return i
},
_onTransitionComplete: function () {
;(i = !1), u()
},
listen: function (t) {
n.push(t)
var r = function () {
;(a = o(e)), t({ location: a, action: 'POP' })
}
return (
e.addEventListener('popstate', r),
function () {
e.removeEventListener('popstate', r),
(n = n.filter(function (e) {
return e !== t
}))
}
)
},
navigate: function (t) {
var c =
arguments.length > 1 &&
void 0 !== arguments[1]
? arguments[1]
: {},
s = c.state,
l = c.replace,
p = void 0 !== l && l
if ('number' == typeof t) e.history.go(t)
else {
s = r({}, s, { key: Date.now() + '' })
try {
i || p
? e.history.replaceState(s, null, t)
: e.history.pushState(s, null, t)
} catch (d) {
e.location[p ? 'replace' : 'assign'](t)
}
}
;(a = o(e)), (i = !0)
var f = new Promise(function (e) {
return (u = e)
})
return (
n.forEach(function (e) {
return e({ location: a, action: 'PUSH' })
}),
f
)
}
}
},
i = function () {
var e =
arguments.length > 0 && void 0 !== arguments[0]
? arguments[0]
: '/',
t = e.indexOf('?'),
n = {
pathname: t > -1 ? e.substr(0, t) : e,
search: t > -1 ? e.substr(t) : ''
},
r = 0,
o = [n],
a = [null]
return {
get location() {
return o[r]
},
addEventListener: function (e, t) {},
removeEventListener: function (e, t) {},
history: {
get entries() {
return o
},
get index() {
return r
},
get state() {
return a[r]
},
pushState: function (e, t, n) {
var i = n.split('?'),
u = i[0],
c = i[1],
s = void 0 === c ? '' : c
r++,
o.push({
pathname: u,
search: s.length ? '?' + s : s
}),
a.push(e)
},
replaceState: function (e, t, n) {
var i = n.split('?'),
u = i[0],
c = i[1],
s = void 0 === c ? '' : c
;(o[r] = { pathname: u, search: s }), (a[r] = e)
},
go: function (e) {
var t = r + e
t < 0 || t > a.length - 1 || (r = t)
}
}
}
},
u = !(
'undefined' == typeof window ||
!window.document ||
!window.document.createElement
),
c = a(u ? window : i()),
s = c.navigate
},
ANjH: function (e, t, n) {
'use strict'
n.d(t, 'a', function () {
return s
}),
n.d(t, 'b', function () {
return u
})
var r = n('bCCX'),
o = function () {
return Math.random()
.toString(36)
.substring(7)
.split('')
.join('.')
},
a = {
INIT: '@@redux/INIT' + o(),
REPLACE: '@@redux/REPLACE' + o(),
PROBE_UNKNOWN_ACTION: function () {
return '@@redux/PROBE_UNKNOWN_ACTION' + o()
}
}
function i(e) {
if ('object' != typeof e || null === e) return !1
for (var t = e; null !== Object.getPrototypeOf(t); )
t = Object.getPrototypeOf(t)
return Object.getPrototypeOf(e) === t
}
function u(e, t, n) {
var o
if (
('function' == typeof t && 'function' == typeof n) ||
('function' == typeof n &&
'function' == typeof arguments[3])
)
throw new Error(
'It looks like you are passing several store enhancers to createStore(). This is not supported. Instead, compose them together to a single function.'
)
if (
('function' == typeof t &&
void 0 === n &&
((n = t), (t = void 0)),
void 0 !== n)
) {
if ('function' != typeof n)
throw new Error(
'Expected the enhancer to be a function.'
)
return n(u)(e, t)
}
if ('function' != typeof e)
throw new Error('Expected the reducer to be a function.')
var c = e,
s = t,
l = [],
p = l,
f = !1
function d() {
p === l && (p = l.slice())
}
function h() {
if (f)
throw new Error(
'You may not call store.getState() while the reducer is executing. The reducer has already received the state as an argument. Pass it down from the top reducer instead of reading it from the store.'
)
return s
}
function m(e) {
if ('function' != typeof e)
throw new Error(
'Expected the listener to be a function.'
)
if (f)
throw new Error(
'You may not call store.subscribe() while the reducer is executing. If you would like to be notified after the store has been updated, subscribe from a component and invoke store.getState() in the callback to access the latest state. See https://redux.js.org/api-reference/store#subscribelistener for more details.'
)
var t = !0
return (
d(),
p.push(e),
function () {
if (t) {
if (f)
throw new Error(
'You may not unsubscribe from a store listener while the reducer is executing. See https://redux.js.org/api-reference/store#subscribelistener for more details.'
)
;(t = !1), d()
var n = p.indexOf(e)
p.splice(n, 1), (l = null)
}
}
)
}
function v(e) {
if (!i(e))
throw new Error(
'Actions must be plain objects. Use custom middleware for async actions.'
)
if (void 0 === e.type)
throw new Error(
'Actions may not have an undefined "type" property. Have you misspelled a constant?'
)
if (f) throw new Error('Reducers may not dispatch actions.')
try {
;(f = !0), (s = c(s, e))
} finally {
f = !1
}
for (var t = (l = p), n = 0; n < t.length; n++) {
;(0, t[n])()
}
return e
}
function g(e) {
if ('function' != typeof e)
throw new Error(
'Expected the nextReducer to be a function.'
)
;(c = e), v({ type: a.REPLACE })
}
function y() {
var e,
t = m
return (
((e = {
subscribe: function (e) {
if ('object' != typeof e || null === e)
throw new TypeError(
'Expected the observer to be an object.'
)
function n() {
e.next && e.next(h())
}
return n(), { unsubscribe: t(n) }
}
})[r.a] = function () {
return this
}),
e
)
}
return (
v({ type: a.INIT }),
((o = {
dispatch: v,
subscribe: m,
getState: h,
replaceReducer: g
})[r.a] = y),
o
)
}
function c(e, t) {
return function () {
return t(e.apply(this, arguments))
}
}
function s(e, t) {
if ('function' == typeof e) return c(e, t)
if ('object' != typeof e || null === e)
throw new Error(
'bindActionCreators expected an object or a function, instead received ' +
(null === e ? 'null' : typeof e) +
'. Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?'
)
var n = {}
for (var r in e) {
var o = e[r]
'function' == typeof o && (n[r] = c(o, t))
}
return n
}
},
DUzY: function (e, t, n) {
'use strict'
var r = 'function' == typeof Symbol && Symbol.for,
o = r ? Symbol.for('react.element') : 60103,
a = r ? Symbol.for('react.portal') : 60106,
i = r ? Symbol.for('react.fragment') : 60107,
u = r ? Symbol.for('react.strict_mode') : 60108,
c = r ? Symbol.for('react.profiler') : 60114,
s = r ? Symbol.for('react.provider') : 60109,
l = r ? Symbol.for('react.context') : 60110,
p = r ? Symbol.for('react.async_mode') : 60111,
f = r ? Symbol.for('react.concurrent_mode') : 60111,
d = r ? Symbol.for('react.forward_ref') : 60112,
h = r ? Symbol.for('react.suspense') : 60113,
m = r ? Symbol.for('react.suspense_list') : 60120,
v = r ? Symbol.for('react.memo') : 60115,
g = r ? Symbol.for('react.lazy') : 60116,
y = r ? Symbol.for('react.block') : 60121,
b = r ? Symbol.for('react.fundamental') : 60117,
w = r ? Symbol.for('react.responder') : 60118,
P = r ? Symbol.for('react.scope') : 60119
function O(e) {
if ('object' == typeof e && null !== e) {
var t = e.$$typeof
switch (t) {
case o:
switch ((e = e.type)) {
case p:
case f:
case i:
case c:
case u:
case h:
return e
default:
switch ((e = e && e.$$typeof)) {
case l:
case d:
case g:
case v:
case s:
return e
default:
return t
}
}
case a:
return t
}
}
}
function S(e) {
return O(e) === f
}
;(t.AsyncMode = p),
(t.ConcurrentMode = f),
(t.ContextConsumer = l),
(t.ContextProvider = s),
(t.Element = o),
(t.ForwardRef = d),
(t.Fragment = i),
(t.Lazy = g),
(t.Memo = v),
(t.Portal = a),
(t.Profiler = c),
(t.StrictMode = u),
(t.Suspense = h),
(t.isAsyncMode = function (e) {
return S(e) || O(e) === p
}),
(t.isConcurrentMode = S),
(t.isContextConsumer = function (e) {
return O(e) === l
}),
(t.isContextProvider = function (e) {
return O(e) === s
}),
(t.isElement = function (e) {
return (
'object' == typeof e && null !== e && e.$$typeof === o
)
}),
(t.isForwardRef = function (e) {
return O(e) === d
}),
(t.isFragment = function (e) {
return O(e) === i
}),
(t.isLazy = function (e) {
return O(e) === g
}),
(t.isMemo = function (e) {
return O(e) === v
}),
(t.isPortal = function (e) {
return O(e) === a
}),
(t.isProfiler = function (e) {
return O(e) === c
}),
(t.isStrictMode = function (e) {
return O(e) === u
}),
(t.isSuspense = function (e) {
return O(e) === h
}),
(t.isValidElementType = function (e) {
return (
'string' == typeof e ||
'function' == typeof e ||
e === i ||
e === f ||
e === c ||
e === u ||
e === h ||
e === m ||
('object' == typeof e &&
null !== e &&
(e.$$typeof === g ||
e.$$typeof === v ||
e.$$typeof === s ||
e.$$typeof === l ||
e.$$typeof === d ||
e.$$typeof === b ||
e.$$typeof === w ||
e.$$typeof === P ||
e.$$typeof === y))
)
}),
(t.typeOf = O)
},
Enzk: function (e, t, n) {
'use strict'
var r = n('jGDn'),
o = n('5NKs')
;(t.__esModule = !0), (t.ScrollHandler = t.ScrollContext = void 0)
var a = o(n('v06X')),
i = o(n('XEEL')),
u = r(n('q1tI')),
c = o(n('17x9')),
s = n('/hTd'),
l = u.createContext(new s.SessionStorage())
;(t.ScrollContext = l), (l.displayName = 'GatsbyScrollContext')
var p = (function (e) {
function t() {
for (
var t, n = arguments.length, r = new Array(n), o = 0;
o < n;
o++
)
r[o] = arguments[o]
return (
((t =
e.call.apply(e, [this].concat(r)) ||
this)._stateStorage = new s.SessionStorage()),
(t.scrollListener = function () {
var e = t.props.location.key
e &&
t._stateStorage.save(
t.props.location,
e,
window.scrollY
)
}),
(t.windowScroll = function (e, n) {
t.shouldUpdateScroll(n, t.props) &&
window.scrollTo(0, e)
}),
(t.scrollToHash = function (e, n) {
var r = document.getElementById(e.substring(1))
r &&
t.shouldUpdateScroll(n, t.props) &&
r.scrollIntoView()
}),
(t.shouldUpdateScroll = function (e, n) {
var r = t.props.shouldUpdateScroll
return !r || r.call((0, a.default)(t), e, n)
}),
t
)
}
;(0, i.default)(t, e)
var n = t.prototype
return (
(n.componentDidMount = function () {
var e
window.addEventListener('scroll', this.scrollListener)
var t = this.props.location,
n = t.key,
r = t.hash
n &&
(e = this._stateStorage.read(
this.props.location,
n
)),
e
? this.windowScroll(e, void 0)
: r && this.scrollToHash(decodeURI(r), void 0)
}),
(n.componentWillUnmount = function () {
window.removeEventListener(
'scroll',
this.scrollListener
)
}),
(n.componentDidUpdate = function (e) {
var t,
n = this.props.location,
r = n.hash,
o = n.key
o &&
(t = this._stateStorage.read(
this.props.location,
o
)),
r && 0 === t
? this.scrollToHash(decodeURI(r), e)
: this.windowScroll(t, e)
}),
(n.render = function () {
return u.createElement(
l.Provider,
{ value: this._stateStorage },
this.props.children
)
}),
t
)
})(u.Component)
;(t.ScrollHandler = p),
(p.propTypes = {
shouldUpdateScroll: c.default.func,
children: c.default.element.isRequired,
location: c.default.object.isRequired
})
},
GddB: function (e, t, n) {
'use strict'
n.r(t),
n.d(t, 'wrapRootElement', function () {
return l
})
var r = n('q1tI'),
o = n.n(r),
a = n('/MKj'),
i = n('ANjH'),
u = function (e, t) {
var n,
r =
(null == t || null === (n = t.item) || void 0 === n
? void 0
: n.itemId) + t.size
if ('ADD_TO_CART' === t.type)
((a = {
itemsInCart: Object.assign({}, e.itemsInCart)
}).itemsInCart[r] = {
itemId: t.item.itemId,
quantity: 1,
imagePath: t.item.imagePath,
title: t.item.title,
price: t.item.price,
size: t.size
}),
(e = Object.assign({}, e, a))
else if ('MODIFY_ITEM_QUANTITY' === t.type) {
var o = parseInt(t.quantity),
a = {
itemsInCart: Object.assign({}, e.itemsInCart)
}
0 == o
? delete a.itemsInCart[r]
: (a.itemsInCart[r] = {
itemId: t.item.itemId,
quantity: o,
imagePath: t.item.imagePath,
title: t.item.title,
price: t.item.price,
size: t.size
}),
(e = Object.assign({}, e, a))
}
var i = 0
Object.keys(e.itemsInCart).map(function (t) {
var n = e.itemsInCart[t]
i += n.price * n.quantity
})
var u = { price: i }
return (e = Object.assign({}, e, u))
},
c = { itemsInCart: {}, price: 0 },
s = function () {
return Object(i.b)(u, c)
},
l = function (e) {
var t = e.element,
n = s()
return o.a.createElement(a.a, { store: n }, t)
}
},
IOVJ: function (e, t, n) {
'use strict'
var r = n('9Hrx'),
o = n('q1tI'),
a = n.n(o),
i = n('emEt'),
u = n('xtsi'),
c = n('30RF'),
s = (function (e) {
function t() {
return e.apply(this, arguments) || this
}
return (
Object(r.a)(t, e),
(t.prototype.render = function () {
var e = Object.assign({}, this.props, {
params: Object.assign(
{},
Object(c.c)(
this.props.location.pathname
),
this.props.pageResources.json
.pageContext.__params
),
pathContext: this.props.pageContext
}),
t =
Object(u.apiRunner)(
'replaceComponentRenderer',
{
props: this.props,
loader: i.publicLoader
}
)[0] ||
Object(o.createElement)(
this.props.pageResources.component,
Object.assign({}, e, {
key:
this.props.path ||
this.props.pageResources.page
.path
})
)
return Object(u.apiRunner)(
'wrapPageElement',
{ element: t, props: e },
t,
function (t) {
return { element: t.result, props: e }
}
).pop()
}),
t
)
})(a.a.Component)
t.a = s
},
JeVI: function (e) {
e.exports = JSON.parse('[]')
},
LYrO: function (e, t, n) {
'use strict'
n.r(t),
n.d(t, 'startsWith', function () {
return a
}),
n.d(t, 'pick', function () {
return i
}),
n.d(t, 'match', function () {
return u
}),
n.d(t, 'resolve', function () {
return c
}),
n.d(t, 'insertParams', function () {
return s
}),
n.d(t, 'validateRedirect', function () {
return l
}),
n.d(t, 'shallowCompare', function () {
return b
})
var r = n('QLaP'),
o = n.n(r),
a = function (e, t) {
return e.substr(0, t.length) === t
},
i = function (e, t) {
for (
var n = void 0,
r = void 0,
a = t.split('?')[0],
i = v(a),
u = '' === i[0],
c = m(e),
s = 0,
l = c.length;
s < l;
s++
) {
var f = !1,
h = c[s].route
if (h.default) r = { route: h, params: {}, uri: t }
else {
for (
var g = v(h.path),
b = {},
w = Math.max(i.length, g.length),
P = 0;
P < w;
P++
) {
var O = g[P],
S = i[P]
if (d(O)) {
b[O.slice(1) || '*'] = i
.slice(P)
.map(decodeURIComponent)
.join('/')
break
}
if (void 0 === S) {
f = !0
break
}
var j = p.exec(O)
if (j && !u) {
;-1 === y.indexOf(j[1]) || o()(!1)
var E = decodeURIComponent(S)
b[j[1]] = E
} else if (O !== S) {
f = !0
break
}
}
if (!f) {
n = {
route: h,
params: b,
uri: '/' + i.slice(0, P).join('/')
}
break
}
}
}
return n || r || null
},
u = function (e, t) {
return i([{ path: e }], t)
},
c = function (e, t) {
if (a(e, '/')) return e
var n = e.split('?'),
r = n[0],
o = n[1],
i = t.split('?')[0],
u = v(r),
c = v(i)
if ('' === u[0]) return g(i, o)
if (!a(u[0], '.')) {
var s = c.concat(u).join('/')
return g(('/' === i ? '' : '/') + s, o)
}
for (
var l = c.concat(u), p = [], f = 0, d = l.length;
f < d;
f++
) {
var h = l[f]
'..' === h ? p.pop() : '.' !== h && p.push(h)
}
return g('/' + p.join('/'), o)
},
s = function (e, t) {
var n = e.split('?'),
r = n[0],
o = n[1],
a = void 0 === o ? '' : o,
i =
'/' +
v(r)
.map(function (e) {
var n = p.exec(e)
return n ? t[n[1]] : e
})
.join('/'),
u = t.location,
c = (u = void 0 === u ? {} : u).search,
s = (void 0 === c ? '' : c).split('?')[1] || ''
return (i = g(i, a, s))
},
l = function (e, t) {
var n = function (e) {
return f(e)
}
return (
v(e).filter(n).sort().join('/') ===
v(t).filter(n).sort().join('/')
)
},
p = /^:(.+)/,
f = function (e) {
return p.test(e)
},
d = function (e) {
return e && '*' === e[0]
},
h = function (e, t) {
return {
route: e,
score: e.default
? 0
: v(e.path).reduce(function (e, t) {
return (
(e += 4),
!(function (e) {
return '' === e
})(t)
? f(t)
? (e += 2)
: d(t)
? (e -= 5)
: (e += 3)
: (e += 1),
e
)
}, 0),
index: t
}
},
m = function (e) {
return e.map(h).sort(function (e, t) {
return e.score < t.score
? 1
: e.score > t.score
? -1
: e.index - t.index
})
},
v = function (e) {
return e.replace(/(^\/+|\/+$)/g, '').split('/')
},
g = function (e) {
for (
var t = arguments.length,
n = Array(t > 1 ? t - 1 : 0),
r = 1;
r < t;
r++
)
n[r - 1] = arguments[r]
return (
e +
((n = n.filter(function (e) {
return e && e.length > 0
})) && n.length > 0
? '?' + n.join('&')
: '')
)
},
y = ['uri', 'path'],
b = function (e, t) {
var n = Object.keys(e)
return (
n.length === Object.keys(t).length &&
n.every(function (n) {
return t.hasOwnProperty(n) && e[n] === t[n]
})
)
}
},
LeKB: function (e, t, n) {
e.exports = [
{ plugin: n('q9nr'), options: { plugins: [], maxWidth: 590 } },
{ plugin: n('e/UW'), options: { plugins: [] } },
{ plugin: n('GddB'), options: { plugins: [] } }
]
},
MMVs: function (e, t, n) {
e.exports = (function () {
var e = !1
;-1 !== navigator.appVersion.indexOf('MSIE 10') && (e = !0)
var t,
n = [],
r = 'object' == typeof document && document,
o = e
? r.documentElement.doScroll('left')
: r.documentElement.doScroll,
a =
r &&
(o ? /^loaded|^c/ : /^loaded|^i|^c/).test(r.readyState)
return (
!a &&
r &&
r.addEventListener(
'DOMContentLoaded',
(t = function () {
for (
r.removeEventListener(
'DOMContentLoaded',
t
),
a = 1;
(t = n.shift());
)
t()
})
),
function (e) {
a ? setTimeout(e, 0) : n.push(e)
}
)
})()
},
NSX3: function (e, t, n) {
'use strict'
n.r(t)
var r = n('xtsi')
'https:' !== window.location.protocol &&
'localhost' !== window.location.hostname
? console.error(
'Service workers can only be used over HTTPS, or on localhost for development'
)
: 'serviceWorker' in navigator &&
navigator.serviceWorker
.register('/sw.js')
.then(function (e) {
e.addEventListener('updatefound', function () {
Object(r.apiRunner)(
'onServiceWorkerUpdateFound',
{ serviceWorker: e }
)
var t = e.installing
console.log('installingWorker', t),
t.addEventListener(
'statechange',
function () {
switch (t.state) {
case 'installed':
navigator.serviceWorker
.controller
? ((window.___swUpdated =
!0),
Object(r.apiRunner)(
'onServiceWorkerUpdateReady',
{ serviceWorker: e }
),
window.___failedResources &&
(console.log(
'resources failed, SW updated - reloading'
),
window.location.reload()))
: (console.log(
'Content is now available offline!'
),
Object(r.apiRunner)(
'onServiceWorkerInstalled',
{ serviceWorker: e }
))
break
case 'redundant':
console.error(
'The installing service worker became redundant.'
),
Object(r.apiRunner)(
'onServiceWorkerRedundant',
{ serviceWorker: e }
)
break
case 'activated':
Object(r.apiRunner)(
'onServiceWorkerActive',
{ serviceWorker: e }
)
}
}
)
})
})
.catch(function (e) {
console.error(
'Error during service worker registration:',
e
)
})
},
NsGk: function (e, t, n) {
t.components = {
'component---node-modules-gatsby-plugin-offline-app-shell-js':
function () {
return n.e(7).then(n.t.bind(null, 'MqWW', 7))
},
'component---src-pages-404-jsx': function () {
return Promise.all([n.e(0), n.e(1), n.e(2), n.e(8)]).then(
n.bind(null, 'pssB')
)
},
'component---src-pages-about-index-jsx': function () {
return Promise.all([n.e(0), n.e(1), n.e(2), n.e(9)]).then(
n.bind(null, 'E+R4')
)
},
'component---src-pages-blog-index-jsx': function () {
return Promise.all([
n.e(0),
n.e(1),
n.e(2),
n.e(3),
n.e(10)
]).then(n.bind(null, 'RJk/'))
},
'component---src-pages-index-jsx': function () {
return Promise.all([
n.e(0),
n.e(1),
n.e(2),
n.e(3),
n.e(11)
]).then(n.bind(null, 'Dtc0'))
},
'component---src-pages-projects-index-jsx': function () {
return Promise.all([
n.e(0),
n.e(1),
n.e(2),
n.e(3),
n.e(12)
]).then(n.bind(null, 'G18J'))
},
'component---src-pages-projects-photography-2017-fall-montreal-jsx':
function () {
return Promise.all([
n.e(0),
n.e(1),
n.e(2),
n.e(13)
]).then(n.bind(null, '0Jp9'))
},
'component---src-pages-projects-photography-2017-summer-beauce-jsx':
function () {
return Promise.all([
n.e(0),
n.e(1),
n.e(2),
n.e(14)
]).then(n.bind(null, 'm89W'))
},
'component---src-pages-projects-photography-2017-summer-montreal-jsx':
function () {
return Promise.all([
n.e(0),
n.e(1),
n.e(2),
n.e(15)
]).then(n.bind(null, 'IVi8'))
},
'component---src-pages-projects-photography-2018-fall-montreal-jsx':
function () {
return Promise.all([
n.e(0),
n.e(1),
n.e(2),
n.e(16)
]).then(n.bind(null, 'Pr+L'))
},
'component---src-pages-projects-photography-2018-summer-beauce-jsx':
function () {
return Promise.all([
n.e(0),
n.e(1),
n.e(2),
n.e(17)
]).then(n.bind(null, 'YKHd'))
},
'component---src-pages-projects-photography-2018-summer-montreal-jsx':
function () {
return Promise.all([
n.e(0),
n.e(1),
n.e(2),
n.e(18)
]).then(n.bind(null, '7gmi'))
},
'component---src-pages-projects-photography-2018-summer-travel-jsx':
function () {
return Promise.all([
n.e(0),
n.e(1),
n.e(2),
n.e(19)
]).then(n.bind(null, 'TvoZ'))
},
'component---src-pages-projects-photography-2019-spring-montreal-jsx':
function () {
return Promise.all([
n.e(0),
n.e(1),
n.e(2),
n.e(20)
]).then(n.bind(null, '7zL2'))
},
'component---src-pages-projects-photography-2019-summer-montreal-jsx':
function () {
return Promise.all([
n.e(0),
n.e(1),
n.e(2),
n.e(21)
]).then(n.bind(null, 'Gunm'))
},
'component---src-pages-projects-photography-2019-winter-montreal-jsx':
function () {
return Promise.all([
n.e(0),
n.e(1),
n.e(2),
n.e(22)
]).then(n.bind(null, 't9nt'))
},
'component---src-pages-projects-photography-index-jsx':
function () {
return Promise.all([
n.e(0),
n.e(1),
n.e(2),
n.e(23)
]).then(n.bind(null, 'KKkP'))
},
'component---src-pages-projects-programming-index-jsx':
function () {
return Promise.all([
n.e(0),
n.e(1),
n.e(2),
n.e(24)
]).then(n.bind(null, 'eiTz'))
},
'component---src-pages-store-add-to-cart-button-jsx':
function () {
return n.e(25).then(n.bind(null, 'TXCg'))
},
'component---src-pages-store-cart-jsx': function () {
return Promise.all([n.e(0), n.e(4), n.e(26)]).then(
n.bind(null, 'Otp9')
)
},
'component---src-pages-store-checkout-button-jsx': function () {
return Promise.all([n.e(0), n.e(4)]).then(
n.bind(null, 'HzL/')
)
},
'component---src-pages-store-index-jsx': function () {
return Promise.all([
n.e(0),
n.e(1),
n.e(2),
n.e(4),
n.e(27)
]).then(n.bind(null, 'xKUt'))
},
'component---src-pages-store-store-item-jsx': function () {
return Promise.all([n.e(0), n.e(28)]).then(
n.bind(null, 'gbBP')
)
},
'component---src-pages-store-success-jsx': function () {
return Promise.all([n.e(0), n.e(1), n.e(2), n.e(29)]).then(
n.bind(null, 'XWIR')
)
},
'component---src-pages-tags-jsx': function () {
return Promise.all([n.e(0), n.e(1), n.e(2), n.e(30)]).then(
n.bind(null, 'PcuZ')
)
},
'component---src-templates-blog-post-jsx': function () {
return Promise.all([
n.e(0),
n.e(1),
n.e(2),
n.e(3),
n.e(31)
]).then(n.bind(null, 'lRrx'))
},
'component---src-templates-tags-jsx': function () {
return Promise.all([n.e(0), n.e(1), n.e(2), n.e(32)]).then(
n.bind(null, 'hlvJ')
)
}
}
},
QLaP: function (e, t, n) {
'use strict'
e.exports = function (e, t, n, r, o, a, i, u) {
if (!e) {
var c
if (void 0 === t)
c = new Error(
'Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.'
)
else {
var s = [n, r, o, a, i, u],
l = 0
;(c = new Error(
t.replace(/%s/g, function () {
return s[l++]
})
)).name = 'Invariant Violation'
}
throw ((c.framesToPop = 1), c)
}
}
},
SLVX: function (e, t, n) {
'use strict'
function r(e) {
var t,
n = e.Symbol
return (
'function' == typeof n
? n.observable
? (t = n.observable)
: ((t = n('observable')), (n.observable = t))
: (t = '@@observable'),
t
)
}
n.d(t, 'a', function () {
return r
})
},
TOwV: function (e, t, n) {
'use strict'
e.exports = n('qT12')
},
UxWs: function (e, t, n) {
'use strict'
n.r(t)
var r = n('9Hrx'),
o = n('xtsi'),
a = n('q1tI'),
i = n.n(a),
u = n('i8i4'),
c = n.n(u),
s = n('YwZP'),
l = n('7hJ6'),
p = n('MMVs'),
f = n.n(p),
d = n('Wbzz'),
h = n('emEt'),
m = n('YLt+'),
v = n('5yr3'),
g = {
id: 'gatsby-announcer',
style: {
position: 'absolute',
top: 0,
width: 1,
height: 1,
padding: 0,
overflow: 'hidden',
clip: 'rect(0, 0, 0, 0)',
whiteSpace: 'nowrap',
border: 0
},
'aria-live': 'assertive',
'aria-atomic': 'true'
},
y = n('9Xx/'),
b = n('+ZDr'),
w = m.reduce(function (e, t) {
return (e[t.fromPath] = t), e
}, {})
function P(e) {
var t = w[e]
return null != t && (window.___replace(t.toPath), !0)
}
var O = function (e, t) {
P(e.pathname) ||
Object(o.apiRunner)('onPreRouteUpdate', {
location: e,
prevLocation: t
})
},
S = function (e, t) {
P(e.pathname) ||
Object(o.apiRunner)('onRouteUpdate', {
location: e,
prevLocation: t
})
},
j = function (e, t) {
if ((void 0 === t && (t = {}), 'number' != typeof e)) {
var n = Object(b.parsePath)(e).pathname,
r = w[n]
if (
(r &&
((e = r.toPath),
(n = Object(b.parsePath)(e).pathname)),
window.___swUpdated)
)
window.location = n
else {
var a = setTimeout(function () {
v.a.emit('onDelayedLoadPageResources', {
pathname: n
}),
Object(o.apiRunner)(
'onRouteUpdateDelayed',
{ location: window.location }
)
}, 1e3)
h.default.loadPage(n).then(function (r) {
if (
!r ||
r.status === h.PageResourceStatus.Error
)
return (
window.history.replaceState(
{},
'',
location.href
),
(window.location = n),
void clearTimeout(a)
)
r &&
r.page.webpackCompilationHash !==
window.___webpackCompilationHash &&
('serviceWorker' in navigator &&
null !==
navigator.serviceWorker
.controller &&
'activated' ===
navigator.serviceWorker.controller
.state &&
navigator.serviceWorker.controller.postMessage(
{ gatsbyApi: 'clearPathResources' }
),
console.log(
'Site has changed on server. Reloading browser'
),
(window.location = n)),
Object(s.navigate)(e, t),
clearTimeout(a)
})
}
} else y.c.navigate(e)
}
function E(e, t) {
var n = this,
r = t.location,
a = r.pathname,
i = r.hash,
u = Object(o.apiRunner)('shouldUpdateScroll', {
prevRouterProps: e,
pathname: a,
routerProps: { location: r },
getSavedScrollPosition: function (e) {
return n._stateStorage.read(e)
}
})
if (u.length > 0) return u[u.length - 1]
if (e && e.location.pathname === a)
return i ? decodeURI(i.slice(1)) : [0, 0]
return !0
}
var R = (function (e) {
function t(t) {
var n
return (
((n = e.call(this, t) || this).announcementRef =
i.a.createRef()),
n
)
}
Object(r.a)(t, e)
var n = t.prototype
return (
(n.componentDidUpdate = function (e, t) {
var n = this
requestAnimationFrame(function () {
var e =
'new page at ' + n.props.location.pathname
document.title && (e = document.title)
var t = document.querySelectorAll(
'#gatsby-focus-wrapper h1'
)
t && t.length && (e = t[0].textContent)
var r = 'Navigated to ' + e
n.announcementRef.current &&
n.announcementRef.current.innerText !== r &&
(n.announcementRef.current.innerText = r)
})
}),
(n.render = function () {
return i.a.createElement(
'div',
Object.assign({}, g, {
ref: this.announcementRef
})
)
}),
t
)
})(i.a.Component),
C = (function (e) {
function t(t) {
var n
return (
(n = e.call(this, t) || this),
O(t.location, null),
n
)
}
Object(r.a)(t, e)
var n = t.prototype
return (
(n.componentDidMount = function () {
S(this.props.location, null)
}),
(n.shouldComponentUpdate = function (e) {
return (
this.props.location.href !== e.location.href &&
(O(this.props.location, e.location), !0)
)
}),
(n.componentDidUpdate = function (e) {
this.props.location.href !== e.location.href &&
S(this.props.location, e.location)
}),
(n.render = function () {
return i.a.createElement(
i.a.Fragment,
null,
this.props.children,
i.a.createElement(R, { location: location })
)
}),
t
)
})(i.a.Component),
x = n('IOVJ'),
_ = n('NsGk'),
k = n.n(_)
function T(e, t) {
for (var n in e) if (!(n in t)) return !0
for (var r in t) if (e[r] !== t[r]) return !0
return !1
}
var D = (function (e) {
function t(t) {
var n
n = e.call(this) || this
var r = t.location,
o = t.pageResources
return (
(n.state = {
location: Object.assign({}, r),
pageResources:
o || h.default.loadPageSync(r.pathname)
}),
n
)
}
Object(r.a)(t, e),
(t.getDerivedStateFromProps = function (e, t) {
var n = e.location
return t.location.href !== n.href
? {
pageResources: h.default.loadPageSync(
n.pathname
),
location: Object.assign({}, n)
}
: { location: Object.assign({}, n) }
})
var n = t.prototype
return (
(n.loadResources = function (e) {
var t = this
h.default.loadPage(e).then(function (n) {
n && n.status !== h.PageResourceStatus.Error
? t.setState({
location: Object.assign(
{},
window.location
),
pageResources: n
})
: (window.history.replaceState(
{},
'',
location.href
),
(window.location = e))
})
}),
(n.shouldComponentUpdate = function (e, t) {
return t.pageResources
? this.state.pageResources !==
t.pageResources ||
this.state.pageResources.component !==
t.pageResources.component ||
this.state.pageResources.json !==
t.pageResources.json ||
!(
this.state.location.key ===
t.location.key ||
!t.pageResources.page ||
(!t.pageResources.page.matchPath &&
!t.pageResources.page.path)
) ||
(function (e, t, n) {
return T(e.props, t) || T(e.state, n)
})(this, e, t)
: (this.loadResources(e.location.pathname), !1)
}),
(n.render = function () {
return this.props.children(this.state)
}),
t
)
})(i.a.Component),
L = n('cSJ8'),
M = n('JeVI'),
N = new h.ProdLoader(k.a, M)
Object(h.setLoader)(N),
N.setApiRunner(o.apiRunner),
(window.asyncRequires = k.a),
(window.___emitter = v.a),
(window.___loader = h.publicLoader),
y.c.listen(function (e) {
e.location.action = e.action
}),
(window.___push = function (e) {
return j(e, { replace: !1 })
}),
(window.___replace = function (e) {
return j(e, { replace: !0 })
}),
(window.___navigate = function (e, t) {
return j(e, t)
}),
P(window.location.pathname),
Object(o.apiRunnerAsync)('onClientEntry').then(function () {
Object(o.apiRunner)('registerServiceWorker').length > 0 &&
n('NSX3')
var e = function (e) {
return i.a.createElement(
s.BaseContext.Provider,
{ value: { baseuri: '/', basepath: '/' } },
i.a.createElement(x.a, e)
)
},
t = i.a.createContext({}),
a = (function (e) {
function n() {
return e.apply(this, arguments) || this
}
return (
Object(r.a)(n, e),
(n.prototype.render = function () {
var e = this.props.children
return i.a.createElement(
s.Location,
null,
function (n) {
var r = n.location
return i.a.createElement(
D,
{ location: r },
function (n) {
var r = n.pageResources,
o = n.location,
a = Object(
h.getStaticQueryResults
)()
return i.a.createElement(
d.c.Provider,
{ value: a },
i.a.createElement(
t.Provider,
{
value: {
pageResources:
r,
location: o
}
},
e
)
)
}
)
}
)
}),
n
)
})(i.a.Component),
u = (function (n) {
function o() {
return n.apply(this, arguments) || this
}
return (
Object(r.a)(o, n),
(o.prototype.render = function () {
var n = this
return i.a.createElement(
t.Consumer,
null,
function (t) {
var r = t.pageResources,
o = t.location
return i.a.createElement(
C,
{ location: o },
i.a.createElement(
l.ScrollContext,
{
location: o,
shouldUpdateScroll: E
},
i.a.createElement(
s.Router,
{
basepath: '',
location: o,
id: 'gatsby-focus-wrapper'
},
i.a.createElement(
e,
Object.assign(
{
path:
'/404.html' ===
r.page
.path
? Object(
L.a
)(
o.pathname,
''
)
: encodeURI(
r
.page
.matchPath ||
r
.page
.path
)
},
n.props,
{
location: o,
pageResources:
r
},
r.json
)
)
)
)
)
}
)
}),
o
)
})(i.a.Component),
p = window,
m = p.pagePath,
v = p.location
m &&
'' + m !== v.pathname &&
!(
N.findMatchPath(Object(L.a)(v.pathname, '')) ||
'/404.html' === m ||
m.match(/^\/404\/?$/) ||
m.match(/^\/offline-plugin-app-shell-fallback\/?$/)
) &&
Object(s.navigate)('' + m + v.search + v.hash, {
replace: !0
}),
h.publicLoader.loadPage(v.pathname).then(function (e) {
if (!e || e.status === h.PageResourceStatus.Error)
throw new Error(
'page resources for ' +
v.pathname +
' not found. Not rendering React'
)
window.___webpackCompilationHash =
e.page.webpackCompilationHash
var t = Object(o.apiRunner)(
'wrapRootElement',
{ element: i.a.createElement(u, null) },
i.a.createElement(u, null),
function (e) {
return { element: e.result }
}
).pop(),
n = function () {
return i.a.createElement(a, null, t)
},
r = Object(o.apiRunner)(
'replaceHydrateFunction',
void 0,
c.a.hydrate
)[0]
f()(function () {
r(
i.a.createElement(n, null),
'undefined' != typeof window
? document.getElementById('___gatsby')
: void 0,
function () {
Object(o.apiRunner)(
'onInitialClientRender'
)
}
)
})
})
})
},
Wbzz: function (e, t, n) {
'use strict'
n.d(t, 'c', function () {
return u
}),
n.d(t, 'b', function () {
return s
})
var r = n('q1tI'),
o = n.n(r),
a = n('+ZDr'),
i = n.n(a)
n.d(t, 'a', function () {
return i.a
})
n('7hJ6'), n('lw3w'), n('emEt').default.enqueue
var u = o.a.createContext({})
function c(e) {
var t = e.staticQueryData,
n = e.data,
r = e.query,
a = e.render,
i = n ? n.data : t[r] && t[r].data
return o.a.createElement(
o.a.Fragment,
null,
i && a(i),
!i &&
o.a.createElement('div', null, 'Loading (StaticQuery)')
)
}
var s = function (e) {
var t = e.data,
n = e.query,
r = e.render,
a = e.children
return o.a.createElement(u.Consumer, null, function (e) {
return o.a.createElement(c, {
data: t,
query: n,
render: r || a,
staticQueryData: e
})
})
}
},
XEEL: function (e, t) {
e.exports = function (e, t) {
;(e.prototype = Object.create(t.prototype)),
(e.prototype.constructor = e),
(e.__proto__ = t)
}
},
'YLt+': function (e) {
e.exports = JSON.parse('[]')
},
YVoz: function (e, t, n) {
'use strict'
e.exports = Object.assign
},
YwZP: function (e, t, n) {
'use strict'
n.r(t),
n.d(t, 'Link', function () {
return D
}),
n.d(t, 'Location', function () {
return b
}),
n.d(t, 'LocationProvider', function () {
return w
}),
n.d(t, 'Match', function () {
return U
}),
n.d(t, 'Redirect', function () {
return A
}),
n.d(t, 'Router', function () {
return S
}),
n.d(t, 'ServerLocation', function () {
return P
}),
n.d(t, 'isRedirect', function () {
return M
}),
n.d(t, 'redirectTo', function () {
return N
}),
n.d(t, 'useLocation', function () {
return F
}),
n.d(t, 'useNavigate', function () {
return W
}),
n.d(t, 'useParams', function () {
return q
}),
n.d(t, 'useMatch', function () {
return $
}),
n.d(t, 'BaseContext', function () {
return O
})
var r = n('q1tI'),
o = n.n(r),
a = (n('17x9'), n('QLaP')),
i = n.n(a),
u = n('nqlD'),
c = n.n(u),
s = n('94VI'),
l = n('LYrO')
n.d(t, 'matchPath', function () {
return l.match
})
var p = n('9Xx/')
n.d(t, 'createHistory', function () {
return p.a
}),
n.d(t, 'createMemorySource', function () {
return p.b
}),
n.d(t, 'navigate', function () {
return p.d
}),
n.d(t, 'globalHistory', function () {
return p.c
})
var f =
Object.assign ||
function (e) {
for (var t = 1; t < arguments.length; t++) {
var n = arguments[t]
for (var r in n)
Object.prototype.hasOwnProperty.call(n, r) &&
(e[r] = n[r])
}
return e
}
function d(e, t) {
var n = {}
for (var r in e)
t.indexOf(r) >= 0 ||
(Object.prototype.hasOwnProperty.call(e, r) &&
(n[r] = e[r]))
return n
}
function h(e, t) {
if (!(e instanceof t))
throw new TypeError('Cannot call a class as a function')
}
function m(e, t) {
if (!e)
throw new ReferenceError(
"this hasn't been initialised - super() hasn't been called"
)
return !t || ('object' != typeof t && 'function' != typeof t)
? e
: t
}
function v(e, t) {
if ('function' != typeof t && null !== t)
throw new TypeError(
'Super expression must either be null or a function, not ' +
typeof t
)
;(e.prototype = Object.create(t && t.prototype, {
constructor: {
value: e,
enumerable: !1,
writable: !0,
configurable: !0
}
})),
t &&
(Object.setPrototypeOf
? Object.setPrototypeOf(e, t)
: (e.__proto__ = t))
}
var g = function (e, t) {
var n = c()(t)
return (n.displayName = e), n
},
y = g('Location'),
b = function (e) {
var t = e.children
return o.a.createElement(y.Consumer, null, function (e) {
return e ? t(e) : o.a.createElement(w, null, t)
})
},
w = (function (e) {
function t() {
var n, r
h(this, t)
for (
var o = arguments.length, a = Array(o), i = 0;
i < o;
i++
)
a[i] = arguments[i]
return (
(n = r =
m(this, e.call.apply(e, [this].concat(a)))),
(r.state = {
context: r.getContext(),
refs: { unlisten: null }
}),
m(r, n)
)
}
return (
v(t, e),
(t.prototype.getContext = function () {
var e = this.props.history
return {
navigate: e.navigate,
location: e.location
}
}),
(t.prototype.componentDidCatch = function (e, t) {
if (!M(e)) throw e
;(0, this.props.history.navigate)(e.uri, {
replace: !0
})
}),
(t.prototype.componentDidUpdate = function (e, t) {
t.context.location !==
this.state.context.location &&
this.props.history._onTransitionComplete()
}),
(t.prototype.componentDidMount = function () {
var e = this,
t = this.state.refs,
n = this.props.history
n._onTransitionComplete(),
(t.unlisten = n.listen(function () {
Promise.resolve().then(function () {
requestAnimationFrame(function () {
e.unmounted ||
e.setState(function () {
return {
context: e.getContext()
}
})
})
})
}))
}),
(t.prototype.componentWillUnmount = function () {
var e = this.state.refs
;(this.unmounted = !0), e.unlisten()
}),
(t.prototype.render = function () {
var e = this.state.context,
t = this.props.children
return o.a.createElement(
y.Provider,
{ value: e },
'function' == typeof t ? t(e) : t || null
)
}),
t
)
})(o.a.Component)
w.defaultProps = { history: p.c }
var P = function (e) {
var t = e.url,
n = e.children,
r = t.indexOf('?'),
a = void 0,
i = ''
return (
r > -1
? ((a = t.substring(0, r)), (i = t.substring(r)))
: (a = t),
o.a.createElement(
y.Provider,
{
value: {
location: {
pathname: a,
search: i,
hash: ''
},
navigate: function () {
throw new Error(
"You can't call navigate on the server."
)
}
}
},
n
)
)
},
O = g('Base', { baseuri: '/', basepath: '/' }),
S = function (e) {
return o.a.createElement(O.Consumer, null, function (t) {
return o.a.createElement(b, null, function (n) {
return o.a.createElement(j, f({}, t, n, e))
})
})
},
j = (function (e) {
function t() {
return h(this, t), m(this, e.apply(this, arguments))
}
return (
v(t, e),
(t.prototype.render = function () {
var e = this.props,
t = e.location,
n = e.navigate,
r = e.basepath,
a = e.primary,
i = e.children,
u = (e.baseuri, e.component),
c = void 0 === u ? 'div' : u,
s = d(e, [
'location',
'navigate',
'basepath',
'primary',
'children',
'baseuri',
'component'
]),
p = o.a.Children.toArray(i).reduce(function (
e,
t
) {
var n = B(r)(t)
return e.concat(n)
},
[]),
h = t.pathname,
m = Object(l.pick)(p, h)
if (m) {
var v = m.params,
g = m.uri,
y = m.route,
b = m.route.value
r = y.default ? r : y.path.replace(/\*$/, '')
var w = f({}, v, {
uri: g,
location: t,
navigate: function (e, t) {
return n(Object(l.resolve)(e, g), t)
}
}),
P = o.a.cloneElement(
b,
w,
b.props.children
? o.a.createElement(
S,
{ location: t, primary: a },
b.props.children
)
: void 0
),
j = a ? R : c,
E = a
? f(
{
uri: g,
location: t,
component: c
},
s
)
: s
return o.a.createElement(
O.Provider,
{ value: { baseuri: g, basepath: r } },
o.a.createElement(j, E, P)
)
}
return null
}),
t
)
})(o.a.PureComponent)
j.defaultProps = { primary: !0 }
var E = g('Focus'),
R = function (e) {
var t = e.uri,
n = e.location,
r = e.component,
a = d(e, ['uri', 'location', 'component'])
return o.a.createElement(E.Consumer, null, function (e) {
return o.a.createElement(
_,
f({}, a, {
component: r,
requestFocus: e,
uri: t,
location: n
})
)
})
},
C = !0,
x = 0,
_ = (function (e) {
function t() {
var n, r
h(this, t)
for (
var o = arguments.length, a = Array(o), i = 0;
i < o;
i++
)
a[i] = arguments[i]
return (
(n = r =
m(this, e.call.apply(e, [this].concat(a)))),
(r.state = {}),
(r.requestFocus = function (e) {
!r.state.shouldFocus && e && e.focus()
}),
m(r, n)
)
}
return (
v(t, e),
(t.getDerivedStateFromProps = function (e, t) {
if (null == t.uri) return f({ shouldFocus: !0 }, e)
var n = e.uri !== t.uri,
r =
t.location.pathname !==
e.location.pathname &&
e.location.pathname === e.uri
return f({ shouldFocus: n || r }, e)
}),
(t.prototype.componentDidMount = function () {
x++, this.focus()
}),
(t.prototype.componentWillUnmount = function () {
0 === --x && (C = !0)
}),
(t.prototype.componentDidUpdate = function (e, t) {
e.location !== this.props.location &&
this.state.shouldFocus &&
this.focus()
}),
(t.prototype.focus = function () {
var e = this.props.requestFocus
e
? e(this.node)
: C
? (C = !1)
: this.node &&
(this.node.contains(document.activeElement) ||
this.node.focus())
}),
(t.prototype.render = function () {
var e = this,
t = this.props,
n = (t.children, t.style),
r = (t.requestFocus, t.component),
a = void 0 === r ? 'div' : r,
i =
(t.uri,
t.location,
d(t, [
'children',
'style',
'requestFocus',
'component',
'uri',
'location'
]))
return o.a.createElement(
a,
f(
{
style: f({ outline: 'none' }, n),
tabIndex: '-1',
ref: function (t) {
return (e.node = t)
}
},
i
),
o.a.createElement(
E.Provider,
{ value: this.requestFocus },
this.props.children
)
)
}),
t
)
})(o.a.Component)
Object(s.polyfill)(_)
var k = function () {},
T = o.a.forwardRef
void 0 === T &&
(T = function (e) {
return e
})
var D = T(function (e, t) {
var n = e.innerRef,
r = d(e, ['innerRef'])
return o.a.createElement(O.Consumer, null, function (e) {
e.basepath
var a = e.baseuri
return o.a.createElement(b, null, function (e) {
var i = e.location,
u = e.navigate,
c = r.to,
s = r.state,
p = r.replace,
h = r.getProps,
m = void 0 === h ? k : h,
v = d(r, ['to', 'state', 'replace', 'getProps']),
g = Object(l.resolve)(c, a),
y = encodeURI(g),
b = i.pathname === y,
w = Object(l.startsWith)(i.pathname, y)
return o.a.createElement(
'a',
f(
{
ref: t || n,
'aria-current': b ? 'page' : void 0
},
v,
m({
isCurrent: b,
isPartiallyCurrent: w,
href: g,
location: i
}),
{
href: g,
onClick: function (e) {
if ((v.onClick && v.onClick(e), J(e))) {
e.preventDefault()
var t = p
if ('boolean' != typeof p && b) {
var n = f({}, i.state),
r = (n.key, d(n, ['key']))
t = Object(l.shallowCompare)(
f({}, s),
r
)
}
u(g, { state: s, replace: t })
}
}
}
)
)
})
})
})
function L(e) {
this.uri = e
}
D.displayName = 'Link'
var M = function (e) {
return e instanceof L
},
N = function (e) {
throw new L(e)
},
I = (function (e) {
function t() {
return h(this, t), m(this, e.apply(this, arguments))
}
return (
v(t, e),
(t.prototype.componentDidMount = function () {
var e = this.props,
t = e.navigate,
n = e.to,
r = (e.from, e.replace),
o = void 0 === r || r,
a = e.state,
i = (e.noThrow, e.baseuri),
u = d(e, [
'navigate',
'to',
'from',
'replace',
'state',
'noThrow',
'baseuri'
])
Promise.resolve().then(function () {
var e = Object(l.resolve)(n, i)
t(Object(l.insertParams)(e, u), {
replace: o,
state: a
})
})
}),
(t.prototype.render = function () {
var e = this.props,
t = (e.navigate, e.to),
n = (e.from, e.replace, e.state, e.noThrow),
r = e.baseuri,
o = d(e, [
'navigate',
'to',
'from',
'replace',
'state',
'noThrow',
'baseuri'
]),
a = Object(l.resolve)(t, r)
return n || N(Object(l.insertParams)(a, o)), null
}),
t
)
})(o.a.Component),
A = function (e) {
return o.a.createElement(O.Consumer, null, function (t) {
var n = t.baseuri
return o.a.createElement(b, null, function (t) {
return o.a.createElement(
I,
f({}, t, { baseuri: n }, e)
)
})
})
},
U = function (e) {
var t = e.path,
n = e.children
return o.a.createElement(O.Consumer, null, function (e) {
var r = e.baseuri
return o.a.createElement(b, null, function (e) {
var o = e.navigate,
a = e.location,
i = Object(l.resolve)(t, r),
u = Object(l.match)(i, a.pathname)
return n({
navigate: o,
location: a,
match: u
? f({}, u.params, { uri: u.uri, path: t })
: null
})
})
})
},
F = function () {
var e = Object(r.useContext)(y)
if (!e)
throw new Error(
'useLocation hook was used but a LocationContext.Provider was not found in the parent tree. Make sure this is used in a component that is a child of Router'
)
return e.location
},
W = function () {
var e = Object(r.useContext)(y)
if (!e)
throw new Error(
'useNavigate hook was used but a LocationContext.Provider was not found in the parent tree. Make sure this is used in a component that is a child of Router'
)
return e.navigate
},
q = function () {
var e = Object(r.useContext)(O)
if (!e)
throw new Error(
'useParams hook was used but a LocationContext.Provider was not found in the parent tree. Make sure this is used in a component that is a child of Router'
)
var t = F(),
n = Object(l.match)(e.basepath, t.pathname)
return n ? n.params : null
},
$ = function (e) {
if (!e)
throw new Error(
'useMatch(path: string) requires an argument of a string to match against'
)
var t = Object(r.useContext)(O)
if (!t)
throw new Error(
'useMatch hook was used but a LocationContext.Provider was not found in the parent tree. Make sure this is used in a component that is a child of Router'
)
var n = F(),
o = Object(l.resolve)(e, t.baseuri),
a = Object(l.match)(o, n.pathname)
return a ? f({}, a.params, { uri: a.uri, path: e }) : null
},
H = function (e) {
return e.replace(/(^\/+|\/+$)/g, '')
},
B = function e(t) {
return function (n) {
if (!n) return null
if (n.type === o.a.Fragment && n.props.children)
return o.a.Children.map(n.props.children, e(t))
if (
(n.props.path ||
n.props.default ||
n.type === A ||
i()(!1),
n.type !== A ||
(n.props.from && n.props.to) ||
i()(!1),
n.type !== A ||
Object(l.validateRedirect)(
n.props.from,
n.props.to
) ||
i()(!1),
n.props.default)
)
return { value: n, default: !0 }
var r = n.type === A ? n.props.from : n.props.path,
a = '/' === r ? t : H(t) + '/' + H(r)
return {
value: n,
default: n.props.default,
path: n.props.children ? H(a) + '/*' : a
}
}
},
J = function (e) {
return (
!e.defaultPrevented &&
0 === e.button &&
!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey)
)
}
},
bCCX: function (e, t, n) {
'use strict'
;(function (e, r) {
var o,
a = n('SLVX')
o =
'undefined' != typeof self
? self
: 'undefined' != typeof window
? window
: void 0 !== e
? e
: r
var i = Object(a.a)(o)
t.a = i
}.call(this, n('yLpj'), n('3UD+')(e)))
},
cSJ8: function (e, t, n) {
'use strict'
function r(e, t) {
return (
void 0 === t && (t = ''),
t
? e === t
? '/'
: e.startsWith(t + '/')
? e.slice(t.length)
: e
: e
)
}
n.d(t, 'a', function () {
return r
})
},
cjBy: function (e, t) {
function n(t) {
return (
'function' == typeof Symbol &&
'symbol' == typeof Symbol.iterator
? (e.exports = n =
function (e) {
return typeof e
})
: (e.exports = n =
function (e) {
return e &&
'function' == typeof Symbol &&
e.constructor === Symbol &&
e !== Symbol.prototype
? 'symbol'
: typeof e
}),
n(t)
)
}
e.exports = n
},
cu4x: function (e, t, n) {
'use strict'
;(t.__esModule = !0),
(t.parsePath = function (e) {
var t = e || '/',
n = '',
r = '',
o = t.indexOf('#')
;-1 !== o && ((r = t.substr(o)), (t = t.substr(0, o)))
var a = t.indexOf('?')
;-1 !== a && ((n = t.substr(a)), (t = t.substr(0, a)))
return {
pathname: t,
search: '?' === n ? '' : n,
hash: '#' === r ? '' : r
}
})
},
'e/UW': function (e, t, n) {
'use strict'
t.registerServiceWorker = function () {
return !0
}
var r = [],
o = []
;(t.onServiceWorkerActive = function (e) {
var t = e.getResourceURLsForPathname,
n = e.serviceWorker
if (window.___swUpdated)
n.active.postMessage({ gatsbyApi: 'resetWhitelist' })
else {
var a = document.querySelectorAll(
'\n head > script[src],\n head > link[href],\n head > style[data-href]\n '
),
i = [].slice.call(a).map(function (e) {
return (
e.src || e.href || e.getAttribute('data-href')
)
}),
u = []
r.forEach(function (e) {
return t(e).forEach(function (e) {
return u.push(e)
})
}),
i.concat(u).forEach(function (e) {
var t = document.createElement('link')
;(t.rel = 'prefetch'),
(t.href = e),
(t.onload = t.remove),
(t.onerror = t.remove),
document.head.appendChild(t)
}),
n.active.postMessage({
gatsbyApi: 'whitelistPathnames',
pathnames: o
})
}
}),
(t.onPostPrefetchPathname = function (e) {
var t = e.pathname
window.___swUpdated ||
(!(function (e, t) {
if ('serviceWorker' in navigator) {
var n = navigator.serviceWorker
null !== n.controller
? n.controller.postMessage({
gatsbyApi: 'whitelistPathnames',
pathnames: [
{ pathname: e, includesPrefix: t }
]
})
: o.push({ pathname: e, includesPrefix: t })
}
})(t, !1),
!('serviceWorker' in navigator) ||
(null !== navigator.serviceWorker.controller &&
'activated' ===
navigator.serviceWorker.controller.state) ||
r.push(t))
})
},
emEt: function (e, t, n) {
'use strict'
n.r(t),
n.d(t, 'PageResourceStatus', function () {
return p
}),
n.d(t, 'BaseLoader', function () {
return g
}),
n.d(t, 'ProdLoader', function () {
return b
}),
n.d(t, 'setLoader', function () {
return w
}),
n.d(t, 'publicLoader', function () {
return P
}),
n.d(t, 'getStaticQueryResults', function () {
return O
})
var r = n('9Hrx')
function o(e, t) {
;(null == t || t > e.length) && (t = e.length)
for (var n = 0, r = new Array(t); n < t; n++) r[n] = e[n]
return r
}
function a(e) {
return (
(function (e) {
if (Array.isArray(e)) return o(e)
})(e) ||
(function (e) {
if (
'undefined' != typeof Symbol &&
Symbol.iterator in Object(e)
)
return Array.from(e)
})(e) ||
(function (e, t) {
if (e) {
if ('string' == typeof e) return o(e, t)
var n = Object.prototype.toString
.call(e)
.slice(8, -1)
return (
'Object' === n &&
e.constructor &&
(n = e.constructor.name),
'Map' === n || 'Set' === n
? Array.from(e)
: 'Arguments' === n ||
/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(
n
)
? o(e, t)
: void 0
)
}
})(e) ||
(function () {
throw new TypeError(
'Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.'
)
})()
)
}
var i = (function (e) {
if ('undefined' == typeof document) return !1
var t = document.createElement('link')
try {
if (
t.relList &&
'function' == typeof t.relList.supports
)
return t.relList.supports(e)
} catch (n) {
return !1
}
return !1
})('prefetch')
? function (e, t) {
return new Promise(function (n, r) {
if ('undefined' != typeof document) {
var o = document.createElement('link')
o.setAttribute('rel', 'prefetch'),
o.setAttribute('href', e),
Object.keys(t).forEach(function (e) {
o.setAttribute(e, t[e])
}),
(o.onload = n),
(o.onerror = r),
(
document.getElementsByTagName(
'head'
)[0] ||
document.getElementsByName(
'script'
)[0].parentNode
).appendChild(o)
} else r()
})
}
: function (e) {
return new Promise(function (t, n) {
var r = new XMLHttpRequest()
r.open('GET', e, !0),
(r.onload = function () {
200 === r.status ? t() : n()
}),
r.send(null)
})
},
u = {},
c = function (e, t) {
return new Promise(function (n) {
u[e]
? n()
: i(e, t)
.then(function () {
n(), (u[e] = !0)
})
.catch(function () {})
})
},
s = n('5yr3'),
l = n('30RF'),
p = { Error: 'error', Success: 'success' },
f = function (e) {
return (e && e.default) || e
},
d = function (e) {
var t
return (
'/page-data/' +
('/' === e
? 'index'
: (t = (t =
'/' === (t = e)[0] ? t.slice(1) : t).endsWith(
'/'
)
? t.slice(0, -1)
: t)) +
'/page-data.json'
)
}
function h(e, t) {
return (
void 0 === t && (t = 'GET'),
new Promise(function (n, r) {
var o = new XMLHttpRequest()
o.open(t, e, !0),
(o.onreadystatechange = function () {
4 == o.readyState && n(o)
}),
o.send(null)
})
)
}
var m,
v = function (e, t) {
void 0 === t && (t = null)
var n = {
componentChunkName: e.componentChunkName,
path: e.path,
webpackCompilationHash: e.webpackCompilationHash,
matchPath: e.matchPath,
staticQueryHashes: e.staticQueryHashes
}
return { component: t, json: e.result, page: n }
},
g = (function () {
function e(e, t) {
;(this.inFlightNetworkRequests = new Map()),
(this.pageDb = new Map()),
(this.inFlightDb = new Map()),
(this.staticQueryDb = {}),
(this.pageDataDb = new Map()),
(this.prefetchTriggered = new Set()),
(this.prefetchCompleted = new Set()),
(this.loadComponent = e),
Object(l.d)(t)
}
var t = e.prototype
return (
(t.memoizedGet = function (e) {
var t = this,
n = this.inFlightNetworkRequests.get(e)
return (
n ||
((n = h(e, 'GET')),
this.inFlightNetworkRequests.set(e, n)),
n
.then(function (n) {
return (
t.inFlightNetworkRequests.delete(e),
n
)
})
.catch(function (n) {
throw (
(t.inFlightNetworkRequests.delete(
e
),
n)
)
})
)
}),
(t.setApiRunner = function (e) {
;(this.apiRunner = e),
(this.prefetchDisabled = e(
'disableCorePrefetching'
).some(function (e) {
return e
}))
}),
(t.fetchPageDataJson = function (e) {
var t = this,
n = e.pagePath,
r = e.retries,
o = void 0 === r ? 0 : r,
a = d(n)
return this.memoizedGet(a).then(function (r) {
var a = r.status,
i = r.responseText
if (200 === a)
try {
var u = JSON.parse(i)
if (void 0 === u.path)
throw new Error(
'not a valid pageData response'
)
return Object.assign(e, {
status: p.Success,
payload: u
})
} catch (c) {}
return 404 === a || 200 === a
? '/404.html' === n
? Object.assign(e, { status: p.Error })
: t.fetchPageDataJson(
Object.assign(e, {
pagePath: '/404.html',
notFound: !0
})
)
: 500 === a
? Object.assign(e, { status: p.Error })
: o < 3
? t.fetchPageDataJson(
Object.assign(e, { retries: o + 1 })
)
: Object.assign(e, { status: p.Error })
})
}),
(t.loadPageDataJson = function (e) {
var t = this,
n = Object(l.b)(e)
return this.pageDataDb.has(n)
? Promise.resolve(this.pageDataDb.get(n))
: this.fetchPageDataJson({ pagePath: n }).then(
function (e) {
return t.pageDataDb.set(n, e), e
}
)
}),
(t.findMatchPath = function (e) {
return Object(l.a)(e)
}),
(t.loadPage = function (e) {
var t = this,
n = Object(l.b)(e)
if (this.pageDb.has(n)) {
var r = this.pageDb.get(n)
return Promise.resolve(r.payload)
}
if (this.inFlightDb.has(n))
return this.inFlightDb.get(n)
var o = Promise.all([
this.loadAppData(),
this.loadPageDataJson(n)
]).then(function (e) {
var r = e[1]
if (r.status === p.Error)
return { status: p.Error }
var o = r.payload,
a = o,
i = a.componentChunkName,
u = a.staticQueryHashes,
c = void 0 === u ? [] : u,
l = {},
f = t.loadComponent(i).then(function (t) {
var n
return (
(l.createdAt = new Date()),
t
? ((l.status = p.Success),
!0 === r.notFound &&
(l.notFound = !0),
(o = Object.assign(o, {
webpackCompilationHash:
e[0]
? e[0]
.webpackCompilationHash
: ''
})),
(n = v(o, t)))
: (l.status = p.Error),
n
)
}),
d = Promise.all(
c.map(function (e) {
if (t.staticQueryDb[e]) {
var n = t.staticQueryDb[e]
return {
staticQueryHash: e,
jsonPayload: n
}
}
return t
.memoizedGet(
'/page-data/sq/d/' +
e +
'.json'
)
.then(function (t) {
var n = JSON.parse(
t.responseText
)
return {
staticQueryHash: e,
jsonPayload: n
}
})
})
).then(function (e) {
var n = {}
return (
e.forEach(function (e) {
var r = e.staticQueryHash,
o = e.jsonPayload
;(n[r] = o),
(t.staticQueryDb[r] = o)
}),
n
)
})
return Promise.all([f, d]).then(function (e) {
var r,
o = e[0],
a = e[1]
return (
o &&
((r = Object.assign({}, o, {
staticQueryResults: a
})),
(l.payload = r),
s.a.emit(
'onPostLoadPageResources',
{ page: r, pageResources: r }
)),
t.pageDb.set(n, l),
r
)
})
})
return (
o
.then(function (e) {
t.inFlightDb.delete(n)
})
.catch(function (e) {
throw (t.inFlightDb.delete(n), e)
}),
this.inFlightDb.set(n, o),
o
)
}),
(t.loadPageSync = function (e) {
var t = Object(l.b)(e)
if (this.pageDb.has(t))
return this.pageDb.get(t).payload
}),
(t.shouldPrefetch = function (e) {
return (
!!(function () {
if (
'connection' in navigator &&
void 0 !== navigator.connection
) {
if (
(
navigator.connection
.effectiveType || ''
).includes('2g')
)
return !1
if (navigator.connection.saveData)
return !1
}
return !0
})() && !this.pageDb.has(e)
)
}),
(t.prefetch = function (e) {
var t = this
if (!this.shouldPrefetch(e)) return !1
if (
(this.prefetchTriggered.has(e) ||
(this.apiRunner('onPrefetchPathname', {
pathname: e
}),
this.prefetchTriggered.add(e)),
this.prefetchDisabled)
)
return !1
var n = Object(l.b)(e)
return (
this.doPrefetch(n).then(function () {
t.prefetchCompleted.has(e) ||
(t.apiRunner('onPostPrefetchPathname', {
pathname: e
}),
t.prefetchCompleted.add(e))
}),
!0
)
}),
(t.doPrefetch = function (e) {
throw new Error('doPrefetch not implemented')
}),
(t.hovering = function (e) {
this.loadPage(e)
}),
(t.getResourceURLsForPathname = function (e) {
var t = Object(l.b)(e),
n = this.pageDataDb.get(t)
if (n) {
var r = v(n.payload)
return [].concat(
a(y(r.page.componentChunkName)),
[d(t)]
)
}
return null
}),
(t.isPageNotFound = function (e) {
var t = Object(l.b)(e),
n = this.pageDb.get(t)
return !n || n.notFound
}),
(t.loadAppData = function (e) {
var t = this
return (
void 0 === e && (e = 0),
this.memoizedGet(
'/page-data/app-data.json'
).then(function (n) {
var r,
o = n.status,
a = n.responseText
if (200 !== o && e < 3)
return t.loadAppData(e + 1)
if (200 === o)
try {
var i = JSON.parse(a)
if (
void 0 ===
i.webpackCompilationHash
)
throw new Error(
'not a valid app-data response'
)
r = i
} catch (u) {}
return r
})
)
}),
e
)
})(),
y = function (e) {
return (window.___chunkMapping[e] || []).map(function (e) {
return '' + e
})
},
b = (function (e) {
function t(t, n) {
return (
e.call(
this,
function (e) {
return t.components[e]
? t.components[e]()
.then(f)
.catch(function () {
return null
})
: Promise.resolve()
},
n
) || this
)
}
Object(r.a)(t, e)
var n = t.prototype
return (
(n.doPrefetch = function (e) {
var t = this,
n = d(e)
return c(n, {
crossOrigin: 'anonymous',
as: 'fetch'
})
.then(function () {
return t.loadPageDataJson(e)
})
.then(function (e) {
if (e.status !== p.Success)
return Promise.resolve()
var t = e.payload,
n = t.componentChunkName,
r = y(n)
return Promise.all(r.map(c)).then(
function () {
return t
}
)
})
}),
(n.loadPageDataJson = function (t) {
return e.prototype.loadPageDataJson
.call(this, t)
.then(function (e) {
return e.notFound
? h(t, 'HEAD').then(function (t) {
return 200 === t.status
? { status: p.Error }
: e
})
: e
})
}),
t
)
})(g),
w = function (e) {
m = e
},
P = {
getResourcesForPathname: function (e) {
return (
console.warn(
'Warning: getResourcesForPathname is deprecated. Use loadPage instead'
),
m.i.loadPage(e)
)
},
getResourcesForPathnameSync: function (e) {
return (
console.warn(
'Warning: getResourcesForPathnameSync is deprecated. Use loadPageSync instead'
),
m.i.loadPageSync(e)
)
},
enqueue: function (e) {
return m.prefetch(e)
},
getResourceURLsForPathname: function (e) {
return m.getResourceURLsForPathname(e)
},
loadPage: function (e) {
return m.loadPage(e)
},
loadPageSync: function (e) {
return m.loadPageSync(e)
},
prefetch: function (e) {
return m.prefetch(e)
},
isPageNotFound: function (e) {
return m.isPageNotFound(e)
},
hovering: function (e) {
return m.hovering(e)
},
loadAppData: function () {
return m.loadAppData()
}
}
t.default = P
function O() {
return m.staticQueryDb
}
},
hd9s: function (e, t, n) {
'use strict'
var r = n('jGDn'),
o = n('5NKs')
;(t.__esModule = !0), (t.ScrollContainer = void 0)
var a = o(n('j8BX')),
i = o(n('XEEL')),
u = r(n('q1tI')),
c = o(n('i8i4')),
s = o(n('17x9')),
l = n('Enzk'),
p = n('YwZP'),
f = {
scrollKey: s.default.string.isRequired,
shouldUpdateScroll: s.default.func,
children: s.default.element.isRequired
},
d = (function (e) {
function t(t) {
return e.call(this, t) || this
}
;(0, i.default)(t, e)
var n = t.prototype
return (
(n.componentDidMount = function () {
var e = this,
t = c.default.findDOMNode(this),
n = this.props,
r = n.location,
o = n.scrollKey
if (t) {
t.addEventListener('scroll', function () {
e.props.context.save(r, o, t.scrollTop)
})
var a = this.props.context.read(r, o)
t.scrollTo(0, a || 0)
}
}),
(n.render = function () {
return this.props.children
}),
t
)
})(u.Component),
h = function (e) {
return u.createElement(p.Location, null, function (t) {
var n = t.location
return u.createElement(
l.ScrollContext.Consumer,
null,
function (t) {
return u.createElement(
d,
(0, a.default)({}, e, {
context: t,
location: n
})
)
}
)
})
}
;(t.ScrollContainer = h), (h.propTypes = f)
},
j8BX: function (e, t) {
function n() {
return (
(e.exports = n =
Object.assign ||
function (e) {
for (var t = 1; t < arguments.length; t++) {
var n = arguments[t]
for (var r in n)
Object.prototype.hasOwnProperty.call(
n,
r
) && (e[r] = n[r])
}
return e
}),
n.apply(this, arguments)
)
}
e.exports = n
},
jGDn: function (e, t, n) {
var r = n('cjBy')
function o() {
if ('function' != typeof WeakMap) return null
var e = new WeakMap()
return (
(o = function () {
return e
}),
e
)
}
e.exports = function (e) {
if (e && e.__esModule) return e
if (null === e || ('object' !== r(e) && 'function' != typeof e))
return { default: e }
var t = o()
if (t && t.has(e)) return t.get(e)
var n = {},
a = Object.defineProperty && Object.getOwnPropertyDescriptor
for (var i in e)
if (Object.prototype.hasOwnProperty.call(e, i)) {
var u = a ? Object.getOwnPropertyDescriptor(e, i) : null
u && (u.get || u.set)
? Object.defineProperty(n, i, u)
: (n[i] = e[i])
}
return (n.default = e), t && t.set(e, n), n
}
},
lw3w: function (e, t, n) {
var r
e.exports = ((r = n('rzlk')) && r.default) || r
},
nqlD: function (e, t, n) {
var r = n('q1tI').createContext
;(e.exports = r), (e.exports.default = r)
},
nwwn: function (e, t, n) {
'use strict'
;(t.DEFAULT_OPTIONS = {
maxWidth: 650,
wrapperStyle: '',
backgroundColor: 'white',
linkImagesToOriginal: !0,
showCaptions: !1,
withWebp: !1,
tracedSVG: !1
}),
(t.imageClass = 'gatsby-resp-image-image'),
(t.imageWrapperClass = 'gatsby-resp-image-wrapper'),
(t.imageBackgroundClass = 'gatsby-resp-image-background-image')
},
q9nr: function (e, t, n) {
'use strict'
var r = n('nwwn'),
o = r.DEFAULT_OPTIONS,
a = r.imageClass,
i = r.imageBackgroundClass,
u = r.imageWrapperClass
t.onRouteUpdate = function (e) {
for (
var t = e.pluginOptions,
n = Object.assign({}, o, t),
r = document.querySelectorAll('.' + u),
c = function (e) {
var t = r[e],
o = t.querySelector('.' + i),
u = t.querySelector('.' + a),
c = function () {
;(o.style.transition = 'opacity 0.5s 0.5s'),
(u.style.transition = 'opacity 0.5s'),
s()
},
s = function e() {
;(o.style.opacity = 0),
(u.style.opacity = 1),
(u.style.color = 'inherit'),
(u.style.boxShadow =
'inset 0px 0px 0px 400px ' +
n.backgroundColor),
u.removeEventListener('load', c),
u.removeEventListener('error', e)
}
;(u.style.opacity = 0),
u.addEventListener('load', c),
u.addEventListener('error', s),
u.complete && s()
},
s = 0;
s < r.length;
s++
)
c(s)
}
},
qT12: function (e, t, n) {
'use strict'
Object.defineProperty(t, '__esModule', { value: !0 })
var r = 'function' == typeof Symbol && Symbol.for,
o = r ? Symbol.for('react.element') : 60103,
a = r ? Symbol.for('react.portal') : 60106,
i = r ? Symbol.for('react.fragment') : 60107,
u = r ? Symbol.for('react.strict_mode') : 60108,
c = r ? Symbol.for('react.profiler') : 60114,
s = r ? Symbol.for('react.provider') : 60109,
l = r ? Symbol.for('react.context') : 60110,
p = r ? Symbol.for('react.async_mode') : 60111,
f = r ? Symbol.for('react.concurrent_mode') : 60111,
d = r ? Symbol.for('react.forward_ref') : 60112,
h = r ? Symbol.for('react.suspense') : 60113,
m = r ? Symbol.for('react.memo') : 60115,
v = r ? Symbol.for('react.lazy') : 60116
function g(e) {
if ('object' == typeof e && null !== e) {
var t = e.$$typeof
switch (t) {
case o:
switch ((e = e.type)) {
case p:
case f:
case i:
case c:
case u:
case h:
return e
default:
switch ((e = e && e.$$typeof)) {
case l:
case d:
case s:
return e
default:
return t
}
}
case v:
case m:
case a:
return t
}
}
}
function y(e) {
return g(e) === f
}
;(t.typeOf = g),
(t.AsyncMode = p),
(t.ConcurrentMode = f),
(t.ContextConsumer = l),
(t.ContextProvider = s),
(t.Element = o),
(t.ForwardRef = d),
(t.Fragment = i),
(t.Lazy = v),
(t.Memo = m),
(t.Portal = a),
(t.Profiler = c),
(t.StrictMode = u),
(t.Suspense = h),
(t.isValidElementType = function (e) {
return (
'string' == typeof e ||
'function' == typeof e ||
e === i ||
e === f ||
e === c ||
e === u ||
e === h ||
('object' == typeof e &&
null !== e &&
(e.$$typeof === v ||
e.$$typeof === m ||
e.$$typeof === s ||
e.$$typeof === l ||
e.$$typeof === d))
)
}),
(t.isAsyncMode = function (e) {
return y(e) || g(e) === p
}),
(t.isConcurrentMode = y),
(t.isContextConsumer = function (e) {
return g(e) === l
}),
(t.isContextProvider = function (e) {
return g(e) === s
}),
(t.isElement = function (e) {
return (
'object' == typeof e && null !== e && e.$$typeof === o
)
}),
(t.isForwardRef = function (e) {
return g(e) === d
}),
(t.isFragment = function (e) {
return g(e) === i
}),
(t.isLazy = function (e) {
return g(e) === v
}),
(t.isMemo = function (e) {
return g(e) === m
}),
(t.isPortal = function (e) {
return g(e) === a
}),
(t.isProfiler = function (e) {
return g(e) === c
}),
(t.isStrictMode = function (e) {
return g(e) === u
}),
(t.isSuspense = function (e) {
return g(e) === h
})
},
rzlk: function (e, t, n) {
'use strict'
n.r(t)
var r = n('q1tI'),
o = n.n(r),
a = n('emEt'),
i = n('IOVJ')
t.default = function (e) {
var t = e.location,
n = a.default.loadPageSync(t.pathname)
return n
? o.a.createElement(
i.a,
Object.assign(
{ location: t, pageResources: n },
n.json
)
)
: null
}
},
uDP2: function (e, t) {
e.exports = function (e, t) {
if (null == e) return {}
var n,
r,
o = {},
a = Object.keys(e)
for (r = 0; r < a.length; r++)
(n = a[r]), t.indexOf(n) >= 0 || (o[n] = e[n])
return o
}
},
v06X: function (e, t) {
e.exports = function (e) {
if (void 0 === e)
throw new ReferenceError(
"this hasn't been initialised - super() hasn't been called"
)
return e
}
},
xtsi: function (e, t, n) {
var r = n('LeKB'),
o = n('emEt').publicLoader,
a = o.getResourcesForPathname,
i = o.getResourcesForPathnameSync,
u = o.getResourceURLsForPathname,
c = o.loadPage,
s = o.loadPageSync
;(t.apiRunner = function (e, t, n, o) {
void 0 === t && (t = {})
var l = r.map(function (n) {
if (n.plugin[e]) {
;(t.getResourcesForPathnameSync = i),
(t.getResourcesForPathname = a),
(t.getResourceURLsForPathname = u),
(t.loadPage = c),
(t.loadPageSync = s)
var r = n.plugin[e](t, n.options)
return (
r &&
o &&
(t = o({ args: t, result: r, plugin: n })),
r
)
}
})
return (l = l.filter(function (e) {
return void 0 !== e
})).length > 0
? l
: n
? [n]
: []
}),
(t.apiRunnerAsync = function (e, t, n) {
return r.reduce(function (n, r) {
return r.plugin[e]
? n.then(function () {
return r.plugin[e](t, r.options)
})
: n
}, Promise.resolve())
})
},
yLpj: function (e, t) {
var n
n = (function () {
return this
})()
try {
n = n || new Function('return this')()
} catch (r) {
'object' == typeof window && (n = window)
}
e.exports = n
}
},
[['UxWs', 5, 33]]
])
//# sourceMappingURL=app-0b88e009ca55689864e7.js.map
| 43.644543 | 343 | 0.242223 |
43574a51bb2a2479c1cb38a54cecd56e32007f7b | 231 | js | JavaScript | src/containers/home/style.js | leadhomesa/carbon | f948af41ecb52c3ea036382a1f9d8e135faa1db2 | [
"MIT"
] | 7 | 2019-02-15T10:46:39.000Z | 2019-12-10T12:14:35.000Z | src/containers/home/style.js | leadhomesa/carbon | f948af41ecb52c3ea036382a1f9d8e135faa1db2 | [
"MIT"
] | 21 | 2019-02-19T12:03:38.000Z | 2022-02-26T09:55:10.000Z | src/containers/home/style.js | leadhomesa/carbon | f948af41ecb52c3ea036382a1f9d8e135faa1db2 | [
"MIT"
] | 1 | 2019-10-09T06:56:10.000Z | 2019-10-09T06:56:10.000Z | import styled from 'styled-components';
import { Link } from 'react-router-dom';
import { colors } from 'styles/index';
export const StyledLink = styled(Link)`
display: block;
margin-bottom: 10px;
color: ${colors.coral};
`;
| 23.1 | 40 | 0.701299 |
4358e19b9f1b98297ba597c6d3c1c01bf1fb0675 | 4,821 | js | JavaScript | dist/migration/BaseDatabaseMigration.js | nxtep-io/ts-framework-migration | 5e61f3c043712cb44dc0eb3ffcb5db49efd1ff67 | [
"MIT"
] | 2 | 2018-09-18T13:33:33.000Z | 2018-12-04T12:56:04.000Z | dist/migration/BaseDatabaseMigration.js | nxtep-io/ts-framework-migration | 5e61f3c043712cb44dc0eb3ffcb5db49efd1ff67 | [
"MIT"
] | null | null | null | dist/migration/BaseDatabaseMigration.js | nxtep-io/ts-framework-migration | 5e61f3c043712cb44dc0eb3ffcb5db49efd1ff67 | [
"MIT"
] | 1 | 2018-11-22T19:12:55.000Z | 2018-11-22T19:12:55.000Z | "use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
class BaseDatabaseMigration {
constructor(name, options = {}) {
this.name = name;
this.options = options;
}
/**
* Runs the migration step safely, reverting the changes in the case of errors.
*
* @returns List of ids of the documents migrated.
*/
run() {
return __awaiter(this, void 0, void 0, function* () {
let data;
try {
data = yield this.map();
}
catch (error) {
// TODO: Handle mapping errors properly
throw error;
}
if (data && data.length) {
try {
yield this.migrate(data);
return data;
}
catch (error) {
// TODO: Handle this case properly
yield this.revert(error, data);
throw error;
}
}
});
}
}
exports.default = BaseDatabaseMigration;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiQmFzZURhdGFiYXNlTWlncmF0aW9uLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vbGliL21pZ3JhdGlvbi9CYXNlRGF0YWJhc2VNaWdyYXRpb24udHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7OztBQUFBO0lBQ0UsWUFBbUIsSUFBWSxFQUFTLFVBQWUsRUFBRTtRQUF0QyxTQUFJLEdBQUosSUFBSSxDQUFRO1FBQVMsWUFBTyxHQUFQLE9BQU8sQ0FBVTtJQUV6RCxDQUFDO0lBMEJEOzs7O09BSUc7SUFDVSxHQUFHOztZQUNkLElBQUksSUFBYyxDQUFDO1lBRW5CLElBQUksQ0FBQztnQkFDSCxJQUFJLEdBQUcsTUFBTSxJQUFJLENBQUMsR0FBRyxFQUFFLENBQUM7WUFDMUIsQ0FBQztZQUFDLEtBQUssQ0FBQyxDQUFDLEtBQUssQ0FBQyxDQUFDLENBQUM7Z0JBQ2YsdUNBQXVDO2dCQUN2QyxNQUFNLEtBQUssQ0FBQztZQUNkLENBQUM7WUFFRCxFQUFFLENBQUMsQ0FBQyxJQUFJLElBQUksSUFBSSxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUM7Z0JBQ3hCLElBQUksQ0FBQztvQkFDSCxNQUFNLElBQUksQ0FBQyxPQUFPLENBQUMsSUFBSSxDQUFDLENBQUM7b0JBQ3pCLE1BQU0sQ0FBQyxJQUFJLENBQUM7Z0JBQ2QsQ0FBQztnQkFBQyxLQUFLLENBQUMsQ0FBQyxLQUFLLENBQUMsQ0FBQyxDQUFDO29CQUNmLGtDQUFrQztvQkFDbEMsTUFBTSxJQUFJLENBQUMsTUFBTSxDQUFDLEtBQUssRUFBRSxJQUFJLENBQUMsQ0FBQztvQkFDL0IsTUFBTSxLQUFLLENBQUM7Z0JBQ2QsQ0FBQztZQUNILENBQUM7UUFDSCxDQUFDO0tBQUE7Q0FDRjtBQXZERCx3Q0F1REMiLCJzb3VyY2VzQ29udGVudCI6WyJleHBvcnQgZGVmYXVsdCBhYnN0cmFjdCBjbGFzcyBCYXNlRGF0YWJhc2VNaWdyYXRpb24ge1xuICBjb25zdHJ1Y3RvcihwdWJsaWMgbmFtZTogU3RyaW5nLCBwdWJsaWMgb3B0aW9uczogYW55ID0ge30pIHtcblxuICB9XG5cbiAgLyoqXG4gICAqIFRoaXMgbWV0aG9kIGRldGVybWluZXMgd2hldGhlciB0aGlzIHNjcmlwdCBoYXMgYW55IHdvcmsgdG8gYmUgZG9uZS5cbiAgICovXG4gIHB1YmxpYyBhYnN0cmFjdCBhc3luYyBoYXNXb3JrKCk6IFByb21pc2U8Ym9vbGVhbj47XG5cbiAgLyoqXG4gICAqIE1hcHMgdGhlIHRoZSBkb2N1bWVudHMgdGhhdCBzaG91bGQgYmUgbWlncmF0ZWQsIHdpbGwgb25seSBiZSBjYWxsZWQgaXMgYGBgaGFzV29yaygpYGBgIGhhdmUgcmV0dXJuZWQgYGBgdHJ1ZWBgYC5cbiAgICovXG4gIHB1YmxpYyBhYnN0cmFjdCBhc3luYyBtYXAoKTogUHJvbWlzZTxhbnlbXT47XG5cbiAgLyoqXG4gICAqIEhhbmRsZXMgdGhlIG1pZ3JhdGlvbnMgb2YgdGhlIG1hcHBlZCBkb2N1bWVudHMuXG4gICAqIFxuICAgKiBAcGFyYW0gZGF0YSBUaGUgZGF0YSBtYXBwZWQgYnkgdGhlIG1pZ3JhdGlvbiBzdGVwXG4gICAqL1xuICBwdWJsaWMgYWJzdHJhY3QgYXN5bmMgbWlncmF0ZShkYXRhOiBhbnlbXSk6IFByb21pc2U8dm9pZD47XG5cbiAgLyoqXG4gICAqIEhhbmRsZXMgdGhlIG1pZ3JhdGlvbnMgb2YgdGhlIG1hcHBlZCBkb2N1bWVudHMuXG4gICAqIFxuICAgKiBAcGFyYW0gZGF0YSBUaGUgZGF0YSBtYXBwZWQgYnkgdGhlIG1pZ3JhdGlvbiBzdGVwXG4gICAqL1xuICBwdWJsaWMgYWJzdHJhY3QgYXN5bmMgcmV2ZXJ0KGVycm9yOiBFcnJvciwgZGF0YTogYW55W10pOiBQcm9taXNlPHZvaWQ+O1xuXG4gIC8qKlxuICAgKiBSdW5zIHRoZSBtaWdyYXRpb24gc3RlcCBzYWZlbHksIHJldmVydGluZyB0aGUgY2hhbmdlcyBpbiB0aGUgY2FzZSBvZiBlcnJvcnMuXG4gICAqIFxuICAgKiBAcmV0dXJucyBMaXN0IG9mIGlkcyBvZiB0aGUgZG9jdW1lbnRzIG1pZ3JhdGVkLlxuICAgKi9cbiAgcHVibGljIGFzeW5jIHJ1bigpOiBQcm9taXNlPGFueVtdPiB7XG4gICAgbGV0IGRhdGE6IHN0cmluZ1tdO1xuXG4gICAgdHJ5IHtcbiAgICAgIGRhdGEgPSBhd2FpdCB0aGlzLm1hcCgpO1xuICAgIH0gY2F0Y2ggKGVycm9yKSB7XG4gICAgICAvLyBUT0RPOiBIYW5kbGUgbWFwcGluZyBlcnJvcnMgcHJvcGVybHlcbiAgICAgIHRocm93IGVycm9yO1xuICAgIH1cblxuICAgIGlmIChkYXRhICYmIGRhdGEubGVuZ3RoKSB7XG4gICAgICB0cnkge1xuICAgICAgICBhd2FpdCB0aGlzLm1pZ3JhdGUoZGF0YSk7XG4gICAgICAgIHJldHVybiBkYXRhO1xuICAgICAgfSBjYXRjaCAoZXJyb3IpIHtcbiAgICAgICAgLy8gVE9ETzogSGFuZGxlIHRoaXMgY2FzZSBwcm9wZXJseVxuICAgICAgICBhd2FpdCB0aGlzLnJldmVydChlcnJvciwgZGF0YSk7XG4gICAgICAgIHRocm93IGVycm9yO1xuICAgICAgfVxuICAgIH1cbiAgfVxufSJdfQ== | 104.804348 | 3,130 | 0.829081 |
435a870d9575d6de588501f891ac87206ae0b5f9 | 2,078 | js | JavaScript | ch05/mother-child-age-difference.js | dotnetCarpenter/eloquent | cfe0f33e6d8b0ca837d587d70962e24425d653c4 | [
"Apache-2.0"
] | 1 | 2015-04-21T17:11:06.000Z | 2015-04-21T17:11:06.000Z | ch05/mother-child-age-difference.js | dotnetCarpenter/eloquent | cfe0f33e6d8b0ca837d587d70962e24425d653c4 | [
"Apache-2.0"
] | null | null | null | ch05/mother-child-age-difference.js | dotnetCarpenter/eloquent | cfe0f33e6d8b0ca837d587d70962e24425d653c4 | [
"Apache-2.0"
] | null | null | null | "use strict"
const ancestry = JSON.parse(require("./ancestry"))
let byName = {};
ancestry.forEach(function(person) {
byName[person.name] = person;
});
const log = console.log;
/* compute the average age difference between mothers and children (the age of the mother when the child is born) */
function isInSet(set, value) {
return set.indexOf(value) > -1;
}
function average(array) {
let plus = (a,b) => a + b;
return array.reduce(plus) / array.length
}
function zipWith(f, xs, ys) {
if(xs.length === 0) return []
if(ys.length === 0) return []
let x = xs[0],
y = ys[0]
xs = xs.slice(1)
ys = ys.slice(1)
return [f(x, y)].concat(zipWith(f, xs, ys))
}
var mothers = ancestry.map(person => person.mother ) // get all the mother names as many times as they appear (duplicates)
.filter(name => byName[name]); // remove names of mothers not in set
var hasMotherInSet = isInSet.bind(null, mothers);
// everyone who has a mother property that correspond to a name in the mothers set
var children = ancestry.filter(person => hasMotherInSet(person.mother));
// since we got all the mother names in the same order as children (we got the mother names from the children), we zip the two sets
var motherChildPair = zipWith(
(mother, child) => [mother, child],
mothers.map(m => byName[m]), // convert mothers to person object
children
);
/*log("mothers", mothers.length);
log("children", children.length);
log(
motherChildPair.map(pair => `mother: ${pair[0].name} child: ${pair[1].name} has mother: ${pair[1].mother}`)
);*/
let averageAgeDifference = average(motherChildPair.map(pair => pair[1].born - pair[0].born));
log("The average age difference between mother and child is " + averageAgeDifference.toFixed(1) + " years")
// FROM Marijn Haverbeke
var differences = ancestry.filter(function(person) {
return byName[person.mother] != null;
}).map(function(person) {
return person.born - byName[person.mother].born;
});
log("The average age difference between mother and child is " + average(differences).toFixed(1) + " years")
| 34.633333 | 131 | 0.690087 |
435ab154733ef6979b06955cc6877d7ffbb19720 | 497 | js | JavaScript | tests/unit/wontae1.js | ChangXiaoning/jalangi2 | 08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110 | [
"Apache-2.0"
] | 357 | 2015-01-07T05:49:05.000Z | 2022-03-27T07:52:06.000Z | tests/unit/wontae1.js | ChangXiaoning/jalangi2 | 08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110 | [
"Apache-2.0"
] | 130 | 2015-01-10T04:48:53.000Z | 2022-01-07T18:42:44.000Z | tests/unit/wontae1.js | ChangXiaoning/jalangi2 | 08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110 | [
"Apache-2.0"
] | 135 | 2015-01-12T21:48:25.000Z | 2022-03-18T03:45:22.000Z | if (typeof window === "undefined") {
require('../../src/js/InputManager');
require(process.cwd()+'/inputs');
}
var x1 = J$.readInput(0);
var x2 = J$.readInput(0);
var x3 = J$.readInput(0);
var f1 = function (a, b){ return (a== b)?1:2; }
var f2 = function(f, c){ return function(d){return f(c,d);}; };
var f3 = f2(f1, x1);
var f4 = f2(f1, x2);
var v1 = f3(x3);
var v2 = f4(x3);
if (v1 == v2) {
console.log("Reached destination 1");
} else {
console.log("Reached destination 2");
}
| 24.85 | 63 | 0.583501 |
435afe12dd2a3f0bad6a7da86d0a98edaf395ff6 | 521 | js | JavaScript | 06.JavaScriptFundamentals/08.Array-Methods/scripts/02.People-of-age.js | ykomitov/Homeworks-TA | 37f6ab7ffbff4e8e2eb4903bcb272e7f283ae9b8 | [
"MIT"
] | null | null | null | 06.JavaScriptFundamentals/08.Array-Methods/scripts/02.People-of-age.js | ykomitov/Homeworks-TA | 37f6ab7ffbff4e8e2eb4903bcb272e7f283ae9b8 | [
"MIT"
] | null | null | null | 06.JavaScriptFundamentals/08.Array-Methods/scripts/02.People-of-age.js | ykomitov/Homeworks-TA | 37f6ab7ffbff4e8e2eb4903bcb272e7f283ae9b8 | [
"MIT"
] | null | null | null | var pr2 = function () {
var personArr = makeArray();
console.log('=== Problem 2 ===');
console.log('Array contains only people of age: ' + personArr.every(ageGreaterThan18));
jsConsole.writeLine('<br>=================== Problem 2 ===================');
jsConsole.writeLine('Array contains only people of age: ' + personArr.every(ageGreaterThan18));
jsConsole.writeLine('=================================================');
};
function ageGreaterThan18(object) {
return object.age > 18;
} | 30.647059 | 99 | 0.556622 |
435b64b322fdcf9481094bce1a706eae929fbab7 | 154 | js | JavaScript | docs/html/search/files_a.js | j9263178/Cytnx | cf7fb1cff75c1cea14fbbc370fd8e4d86d0ddc8b | [
"Apache-2.0"
] | 11 | 2020-04-14T15:45:42.000Z | 2022-03-31T14:37:03.000Z | docs/html/search/files_a.js | j9263178/Cytnx | cf7fb1cff75c1cea14fbbc370fd8e4d86d0ddc8b | [
"Apache-2.0"
] | 38 | 2019-08-02T15:15:51.000Z | 2022-03-04T19:07:02.000Z | docs/html/search/files_a.js | j9263178/Cytnx | cf7fb1cff75c1cea14fbbc370fd8e4d86d0ddc8b | [
"Apache-2.0"
] | 7 | 2019-07-17T07:50:55.000Z | 2021-07-03T06:44:52.000Z | var searchData=
[
['physics_2ecpp',['Physics.cpp',['../Physics_8cpp.html',1,'']]],
['physics_2ehpp',['Physics.hpp',['../Physics_8hpp.html',1,'']]]
];
| 25.666667 | 66 | 0.603896 |
435b6866c7ea9cb08d506a9f19b9897cbd7a8306 | 110 | js | JavaScript | examples/koa-es6/src/api/interfaces.js | s-shin/IsoProxy | 97e07dc8cc3d4e6ce843f8211600b933e9dac3e3 | [
"MIT"
] | null | null | null | examples/koa-es6/src/api/interfaces.js | s-shin/IsoProxy | 97e07dc8cc3d4e6ce843f8211600b933e9dac3e3 | [
"MIT"
] | 4 | 2015-05-22T14:18:43.000Z | 2015-08-23T13:55:53.000Z | examples/koa-es6/src/api/interfaces.js | s-shin/isoproxy | 97e07dc8cc3d4e6ce843f8211600b933e9dac3e3 | [
"MIT"
] | null | null | null |
const interfaces = {
"*": ["hello"],
"math": ["add", "sub", "mul", "div"]
};
export default interfaces;
| 13.75 | 38 | 0.536364 |
435bbdd2155372cede8e5a389751e669a6d3f7f6 | 2,464 | js | JavaScript | src/components/Lab/styles.js | codder404/fernando-blog | 26b04f5e556f439cb0b5382ae7fdc00d4f9d2902 | [
"MIT"
] | 1 | 2020-07-10T11:45:17.000Z | 2020-07-10T11:45:17.000Z | src/components/Lab/styles.js | codder404/fernando-blog | 26b04f5e556f439cb0b5382ae7fdc00d4f9d2902 | [
"MIT"
] | 1 | 2020-10-28T19:44:09.000Z | 2020-10-28T19:44:09.000Z | src/components/Lab/styles.js | codder404/fernando-blog | 26b04f5e556f439cb0b5382ae7fdc00d4f9d2902 | [
"MIT"
] | null | null | null | import styled from 'styled-components';
import Image from 'gatsby-image';
export const Section = styled.section`
`;
export const Avatar = styled(Image)`
height: 14rem;
`;
export const Card = styled.div`
padding: 2rem;
background: transparent;
text-decoration: none;
font-weight: 400;
position: relative;
border: 1px solid #202124;
margin-bottom: .9rem;
&:before {
content: '';
position: absolute;
width: calc(1.2rem + 100%);
height: calc(1rem + 100%);
background: transparent;
border-radius: .3rem;
z-index: -1;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
@media (min-width: 66.667em) {
width: calc(1.8rem + 100%);
height: calc(1.4rem + 100%);
}
}
@media (max-width: 41.667em) {
width: 100%;
}
&:hover {
cursor: pointer;
}
@media (min-width: 66.667) {
border-bottom: 0;
margin: 0 0 2rem;
flex-direction: row;
align-items: center;
padding: 0;
&:hover {
&:before {
background: #202124;
}
}
}
`;
export const ListCategory = styled.div`
display: block;
flex: 1;
@media (min-width: 66.667em) {
text-align: left;
}
`;
export const Category = styled.p`
display: inline-flex;
font-weight: 500;
background: rgba(193, 193, 193, 0.6);
color: #FFF;
margin-top: .7rem;
margin-right: .2rem;
padding: 0.4rem 0.8rem;
font-size: 0.8rem;
border-radius: 3rem;
border-bottom: 0;
white-space: nowrap;
line-height: 1;
@media (min-width: 66.667em) {
background: linear-gradient(transparent 0, #636e9a 0);
}
`;
export const ListSocial = styled.div`
width: 100%;
margin: 0 -.35rem;
`;
export const ItemSocial = styled.a `
padding: .75rem 1rem .75rem 1rem;
letter-spacing: .05em;
margin: .5rem .35rem;
font-weight: 500;
display: inline-flex;
align-items: center;
justify-content: flex;
cursor: pointer;
border-radius: .5rem;
background: rgba(0, 119, 181, .1);
-webkit-text-fill-color: #0077b5;
text-decoration: none;
color: #0077b5;
opacity: 1;
transition: all 300ms ease-in-out;
&:hover {
transform: scale(1.02);
opacity: .8;
}
> svg {
fill: rgb(0,119,181);
width: 21px;
height: 21px;
vertical-align: middle;
margin-right: .5rem;
}
&.github {
background: rgba(193, 193, 193, 0.06);
-webkit-text-fill-color: #FFF;
color: #FFF;
svg {
fill: #FFF;
}
}
`; | 18.251852 | 58 | 0.599432 |
435c444e914e12e0e21a16171a924d937a468eab | 1,582 | js | JavaScript | test/plugins/auth/header.js | linaro-its/thelounge | c04b20a60ab6bdb88a3d653c547a39c60e6af9f8 | [
"MIT"
] | null | null | null | test/plugins/auth/header.js | linaro-its/thelounge | c04b20a60ab6bdb88a3d653c547a39c60e6af9f8 | [
"MIT"
] | null | null | null | test/plugins/auth/header.js | linaro-its/thelounge | c04b20a60ab6bdb88a3d653c547a39c60e6af9f8 | [
"MIT"
] | null | null | null | "use strict";
const log = require("../../../src/log");
const headerAuth = require("../../../src/plugins/auth/header");
const Helper = require("../../../src/helper");
const expect = require("chai").expect;
const stub = require("sinon").stub;
const user = "toby";
const correctHeader = "proxy-user";
function testHeaderAuth() {
// Create mock manager and client. When client is true, manager should not
// be used. But ideally the auth plugin should not use any of those.
const manager = {};
const client = true;
it("should successfully authenticate with any user passed", function (done) {
headerAuth.auth(manager, client, user, null, function (valid) {
expect(valid).to.equal(true);
done();
});
});
}
describe("Header authentication plugin", function () {
before(function () {
stub(log, "info");
});
after(function () {
log.info.restore();
});
beforeEach(function () {
Helper.config.public = false;
Helper.config.headerAuth.enable = true;
Helper.config.headerAuth.header = correctHeader;
});
afterEach(function () {
Helper.config.public = true;
Helper.config.headerAuth.enable = false;
});
describe("Header authentication availibility", function () {
it("checks that the configuration is correctly tied to isEnabled()", function () {
Helper.config.headerAuth.enable = false;
expect(headerAuth.isEnabled()).to.equal(false);
Helper.config.headerAuth.enable = true;
expect(headerAuth.isEnabled()).to.equal(true);
});
});
describe("Header authentication internal user test", function () {
testHeaderAuth();
});
});
| 26.366667 | 84 | 0.682048 |
435c4e642cc4e467151486e6fc3501b2fbdc2fa0 | 499 | js | JavaScript | core/components/atoms/select/components/clear-indicator.js | kuldeepkeshwar/cosmos | aa1559835882581021e9fcba869ca36fad4e76c6 | [
"MIT"
] | null | null | null | core/components/atoms/select/components/clear-indicator.js | kuldeepkeshwar/cosmos | aa1559835882581021e9fcba869ca36fad4e76c6 | [
"MIT"
] | null | null | null | core/components/atoms/select/components/clear-indicator.js | kuldeepkeshwar/cosmos | aa1559835882581021e9fcba869ca36fad4e76c6 | [
"MIT"
] | null | null | null | import React from 'react'
import { components } from 'react-select'
import { spacing } from '@auth0/cosmos-tokens'
import styled from '@auth0/cosmos/styled'
import Icon from '../../icon'
const StyledCloseIcon = styled(Icon)`
pointer-events: none;
margin-right: ${spacing.unit}px;
svg {
display: block;
}
`
export const ClearIndicator = props => (
<components.ClearIndicator {...props}>
<StyledCloseIcon name="close" size="14" color="default" />
</components.ClearIndicator>
)
| 23.761905 | 62 | 0.695391 |
435c82fcdec4d8dbf0c32f135c70c84ae803c516 | 4,489 | js | JavaScript | lib/database/mergerdb.js | Miz-umi/Discord-Trivia-Bot | 41616519e63a9f9fcb7260c0bf9b48d9aa352a80 | [
"Apache-2.0"
] | 1 | 2019-02-01T21:06:37.000Z | 2019-02-01T21:06:37.000Z | lib/database/mergerdb.js | Miz-umi/Discord-Trivia-Bot | 41616519e63a9f9fcb7260c0bf9b48d9aa352a80 | [
"Apache-2.0"
] | null | null | null | lib/database/mergerdb.js | Miz-umi/Discord-Trivia-Bot | 41616519e63a9f9fcb7260c0bf9b48d9aa352a80 | [
"Apache-2.0"
] | null | null | null | var Database = {};
var DatabaseInfo = { tokens: { } };
module.exports = (input) => {
const FileDB = require("./filedb.js")(input);
// File DB tokens are passed through. OpenTDB tokens will be handled later.
Database.tokens = FileDB.tokens;
// Override the URL without affecting the actual value. This forces the default URL.
input = JSON.parse(JSON.stringify(input));
input.databaseURL = "https://opentdb.com";
const OpenTDB = require("./opentdb.js")(input, true);
Database.getCategories = async () => {
var opentdb_result = await OpenTDB.getCategories();
var filedb_result = await FileDB.getCategories();
return filedb_result.concat(opentdb_result);
};
Database.getGlobalCounts = async () => {
var opentdb_result = await OpenTDB.getGlobalCounts();
var filedb_result = await FileDB.getGlobalCounts();
var output = {};
// Combine the category count lists.
output.categories = Object.assign({}, opentdb_result.categories, filedb_result.categories);
// Add up the total question count between both databases.
// Currently only returns total and verified.
output.overall = {
total_num_of_questions: filedb_result.overall.total_num_of_questions+opentdb_result.overall.total_num_of_questions,
total_num_of_verified_questions: filedb_result.overall.total_num_of_verified_questions+opentdb_result.overall.total_num_of_verified_questions
};
return output;
};
// # Token Functions # //
// getTokenByIdentifier
Database.getTokenByIdentifier = async (tokenChannelID) => {
// Use the file DB token as our identifier and pair it to an OpenTDB token.
var fileDBToken = await FileDB.getTokenByIdentifier(tokenChannelID);
var openTDBToken = await OpenTDB.getTokenByIdentifier(tokenChannelID);
// Pair the OpenTDB token to this File DB token.
DatabaseInfo.tokens[fileDBToken] = openTDBToken;
return fileDBToken;
};
// resetTriviaToken
Database.resetToken = async (token) => {
var fileDBReset = await FileDB.resetToken(token);
await OpenTDB.resetToken(DatabaseInfo.tokens[token]);
return fileDBReset;
};
// TODO: Mix questions from both databases if random questions have been reqeuested.
Database.fetchQuestions = async (options) => {
var databases = [ FileDB, OpenTDB ];
// If the request is for random questions...
if(typeof options.category === "undefined") {
// Pick a random database based on the number of categories in each one.
// This keeps the number of questions balanced for both databases.
var opentdb_categories = await OpenTDB.getCategories();
var filedb_categories = await FileDB.getCategories();
var total_length = opentdb_categories.length + filedb_categories.length;
var qCount = Math.floor(Math.random() * total_length);
// Based on the random count, pick which database to pull from.
if(qCount > filedb_categories.length) {
databases.reverse();
}
}
var isLastDB = 0;
for(var i in databases) {
try {
if(databases[i] === OpenTDB && typeof options.token !== "undefined") {
// Use the OpenTDB token associated with the token we've received.
options.token = DatabaseInfo.tokens[options.token];
}
var res1 = await databases[i].fetchQuestions(options);
return res1;
} catch(error) {
// Attempt to fall back to the next database if one of the following conditions are met:
// A. The "No results" error code has been received and we're using the File DB.
// (This means we need to check OpenTDB instead)
// B. There is no specified category and the current database returns a "Token empty" response.
if((error.code === 1 && databases[i] === FileDB) || (error.code === 4 && typeof options.category === "undefined")) {
// If there are no questions or the token has run out, fall back to OpenTDB.
if(!isLastDB) {
// Since this database returned nothing, try the next one.
isLastDB = 1;
continue;
}
else {
// The only usable database(s) returned invalid, throw the error.
throw error;
}
}
else {
// The error appears to be fatal or unrecoverable, throw immediately.
throw error;
}
}
}
};
Database.destroy = () => {
return OpenTDB.destroy();
};
return Database;
};
| 35.346457 | 147 | 0.666295 |
435dea398852338e9dc9450f9193ee03c69464aa | 4,044 | js | JavaScript | src/utils/commons.js | zhang-pn25/zuihou | 794de99260af96db0e0cba104b83497f15b8beda | [
"Apache-2.0"
] | null | null | null | src/utils/commons.js | zhang-pn25/zuihou | 794de99260af96db0e0cba104b83497f15b8beda | [
"Apache-2.0"
] | 1 | 2021-01-31T09:51:23.000Z | 2021-01-31T09:51:23.000Z | src/utils/commons.js | zhang-pn25/zuihou | 794de99260af96db0e0cba104b83497f15b8beda | [
"Apache-2.0"
] | null | null | null | import commonApi from '@/api/Common'
import stationApi from '@/api/Station'
import dictionaryItemApi from '@/api/DictionaryItem.js'
export const loadEnums = (codes, enums = {}) => {
if (typeof (codes) === 'string') {
codes = [codes]
}
if (codes && codes.length > 0) {
commonApi.enums({codes: codes}).then(response => {
const res = response.data
for (const code of codes) {
enums[code] = res.data[code]
}
})
}
}
/**
* 初始化权限服务枚举
* @param codes
* @param enums
*/
export const initEnums = (codes, enums = {}) => {
loadEnums(codes, enums)
}
/**
* 初始化文件服务枚举
* @param codes
* @param enums
*/
export const initFileEnums = (codes, enums = {}) => {
loadEnums(codes, enums)
}
/**
* 初始化消息服务枚举
* @param codes
* @param enums
*/
export const initMsgsEnums = (codes, enums = {}) => {
loadEnums(codes, enums)
}
/**
* 初始化字典
* @param codes
* @param dicts
*/
export const initDicts = (codes, dicts = {}) => {
if (typeof (codes) === 'string') {
codes = [codes]
}
if (codes && codes.length > 0) {
dictionaryItemApi.list({codes: codes}).then(response => {
const res = response.data
for (const code of codes) {
dicts[code] = res.data[code]
}
})
}
}
/**
* 下载方法
* @param response
*/
export const downloadFile = (response) => {
const res = response.data;
const type = res.type;
if (type.includes("application/json")) {
let reader = new FileReader();
reader.onload = e => {
if (e.target.readyState === 2) {
let data = JSON.parse(e.target.result);
this.$message({
message: data.msg,
type: "warning"
});
}
};
reader.readAsText(res);
} else {
let disposition = response.headers["content-disposition"];
let fileName = "下载文件.zip";
if (disposition) {
let respcds = disposition.split(";");
for (let i = 0; i < respcds.length; i++) {
let header = respcds[i];
if (header !== null && header !== "") {
let headerValue = header.split("=");
if (headerValue !== null && headerValue.length > 0) {
if (headerValue[0].trim().toLowerCase() === "filename") {
fileName = decodeURI(headerValue[1]);
break;
}
}
}
}
}
//处理引号
if ((fileName.startsWith("'") || fileName.startsWith('"')) && (fileName.endsWith("'") || fileName.endsWith('"'))) {
fileName = fileName.substring(1, fileName.length - 1)
}
if (
!!window.ActiveXObject ||
"ActiveXObject" in window ||
navigator.userAgent.indexOf("Edge") > -1
) {
let blob = new Blob([res], { type: "application/vnd.ms-excel" });
navigator.msSaveBlob(blob, fileName);
} else{
let blob = new Blob([res]);
let link = document.createElement("a");
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
window.URL.revokeObjectURL(link.href);
}
}
}
/**
* 获取字典key
* @param codes
* @param dicts
*/
export const getDictsKey = (codes,dicts = {}) => {
if(codes){
for(const code of codes){
let data = {
dictionaryType: code,
sort: "sortValue",
current: 1,
map: {},
order: "ascending",
timeRange: null,
}
stationApi.findStandardInfo(data).then(response => {
const res = response.data;
dicts[code] = res.data;
});
}
}
}
// 字符串截取与拼接
export const assignment = (list,val) => {
let stringResult = list.split(',');
switch (stringResult.length) {
case 2 :
return [val,'',''];
case 3:
return [stringResult[1],val,'']
case 4:
return [stringResult[1],stringResult[2],val]
}
}
// 初始化查询参数
export const initQueryParams = params => {
const defParams = {
size: 10,
current: 1,
sort: 'id',
order: 'descending',
model: {
},
map: {},
timeRange: null
};
return params ? { ...defParams, ...params } : defParams;
}
| 22.847458 | 119 | 0.551187 |
435e1292ab15de8d11bacbcca342740ad90a0525 | 5,562 | js | JavaScript | src/pages/caseStudies.js | wetarteam/wetar-org-1.0 | d17d3ac18518bb2963cd5b1e1ee54ff7cc239581 | [
"MIT"
] | null | null | null | src/pages/caseStudies.js | wetarteam/wetar-org-1.0 | d17d3ac18518bb2963cd5b1e1ee54ff7cc239581 | [
"MIT"
] | null | null | null | src/pages/caseStudies.js | wetarteam/wetar-org-1.0 | d17d3ac18518bb2963cd5b1e1ee54ff7cc239581 | [
"MIT"
] | null | null | null | import React from "react";
import theme from "theme";
import { Theme, Link, Strong, Text, Section } from "@quarkly/widgets";
import { Helmet } from "react-helmet";
import { GlobalQuarklyPageStyles } from "global-page-styles";
import { RawHtml, Override, StackItem, Stack } from "@quarkly/components";
import * as Components from "components";
export default (() => {
return <Theme theme={theme}>
<GlobalQuarklyPageStyles pageUrl={"case-studies"} />
<Helmet>
<title>
Wetar
</title>
<meta name={"description"} content={"starts at Rs.99\nWebsite , tamilnadu, pondicherry, tamil"} />
<link rel={"shortcut icon"} href={"https://uploads.quarkly.io/60d350285179a1001e683fe8/images/Untitled%20story%20%2817%29.png?v=2021-09-04T16:14:25.304Z"} type={"image/x-icon"} />
<link rel={"apple-touch-icon"} href={"https://uploads.quarkly.io/60d350285179a1001e683fe8/images/Untitled%20story%20%2817%29.png?v=2021-09-04T16:14:25.304Z"} />
<link rel={"apple-touch-icon"} sizes={"76x76"} href={"https://uploads.quarkly.io/60d350285179a1001e683fe8/images/Untitled%20story%20%2817%29.png?v=2021-09-04T16:14:25.304Z"} />
<link rel={"apple-touch-icon"} sizes={"152x152"} href={"https://uploads.quarkly.io/60d350285179a1001e683fe8/images/Untitled%20story%20%2817%29.png?v=2021-09-04T16:14:25.304Z"} />
<link rel={"apple-touch-startup-image"} href={"https://uploads.quarkly.io/60d350285179a1001e683fe8/images/Untitled%20story%20%2817%29.png?v=2021-09-04T16:14:25.304Z"} />
<meta name={"msapplication-TileImage"} content={"https://uploads.quarkly.io/60d350285179a1001e683fe8/images/Untitled%20story%20%2817%29.png?v=2021-09-04T16:14:25.304Z"} />
</Helmet>
<Components.Menu3>
<Override slot="text" font="normal 500 28px/1.2 --fontFamily-googleIbmPlexMono" letter-spacing="1.5px">
<Strong>
WETAR SITES
</Strong>
</Override>
</Components.Menu3>
<Section
padding="60px 0"
sm-padding="40px 0"
min-height="600px"
sm-min-height="auto"
display="flex"
flex-direction="column"
>
<Text font="--headline1">
<Strong
overflow-wrap="normal"
word-break="normal"
white-space="normal"
text-indent="0"
text-overflow="clip"
hyphens="manual"
>
CUSTOMER STORIES
</Strong>
</Text>
<Stack
margin-top="40px"
flex-wrap="wrap"
align-items="center"
justify-content="center"
display="flex"
grid-auto-rows="2"
grid-auto-flow="2"
margin="0px 20px 0 20px"
>
<StackItem lg-width="50%" sm-width="100%" width="50%">
<Override
slot="StackItemContent"
flex-direction="column"
border-style="solid"
border-width="3px"
text-align="center"
/>
<Text
color="#1808da"
font="--headline3"
letter-spacing="inherit"
margin="5px 0px 0px 15px"
text-align="left"
border-color="#020200"
>
<Strong
overflow-wrap="normal"
word-break="normal"
white-space="normal"
text-indent="0"
text-overflow="clip"
hyphens="manual"
>
Tamil stores
</Strong>
</Text>
<Link
href="https://wetar001.pages.dev/"
font="--headline3"
text-align="left"
text-decoration-line="initial"
padding="10px 0px 10px 15px"
color="#000"
>
<Strong
overflow-wrap="normal"
word-break="normal"
white-space="normal"
text-indent="0"
text-overflow="clip"
hyphens="manual"
>
Quick and Modern design{" "}
<br />
<br />
</Strong>
</Link>
</StackItem>
<StackItem lg-width="50%" sm-width="100%" width="50%">
<Override
slot="StackItemContent"
flex-direction="column"
border-style="solid"
border-width="3px"
text-align="center"
/>
<Text
color="#1808da"
font="--headline3"
letter-spacing="inherit"
margin="5px 0px 0px 15px"
text-align="left"
border-color="#020200"
>
<Strong
overflow-wrap="normal"
word-break="normal"
white-space="normal"
text-indent="0"
text-overflow="clip"
hyphens="manual"
>
8090s cafe , Pondicherry
</Strong>
</Text>
<Link
href="https://wetar001.pages.dev/"
font="--headline3"
text-align="left"
text-decoration-line="initial"
padding="10px 0px 10px 15px"
color="#000"
>
<Strong>
Increased my business.
<br />
Thank you
</Strong>
</Link>
</StackItem>
</Stack>
<Text font="--headline3" color="#1808da">
<Strong
overflow-wrap="normal"
word-break="normal"
white-space="normal"
text-indent="0"
text-overflow="clip"
hyphens="manual"
>
More.....
</Strong>
</Text>
</Section>
<Components.Footer5 />
<Components.Footer3 />
<Link
font={"--capture"}
font-size={"10px"}
position={"fixed"}
bottom={"12px"}
right={"12px"}
z-index={"4"}
border-radius={"4px"}
padding={"5px 12px 4px"}
background-color={"--dark"}
opacity={"0.6"}
hover-opacity={"1"}
color={"--light"}
cursor={"pointer"}
transition={"--opacityOut"}
quarkly-title={"Badge"}
text-decoration-line={"initial"}
href={"https://quarkly.io/"}
target={"_blank"}
>
Made on Quarkly
</Link>
<RawHtml>
<style place={"endOfHead"} rawKey={"60d350285179a1001e683fe6"}>
{":root {\n box-sizing: border-box;\n}\n\n* {\n box-sizing: inherit;\n}"}
</style>
</RawHtml>
</Theme>;
}); | 28.523077 | 182 | 0.606616 |
435e82be3a0d51df8db377d67b1afc135527cb26 | 578 | js | JavaScript | app/views/floors.js | john-holland/day-maker | fef8ed77189886d0947f9639db5de2a2fb108960 | [
"MIT"
] | null | null | null | app/views/floors.js | john-holland/day-maker | fef8ed77189886d0947f9639db5de2a2fb108960 | [
"MIT"
] | null | null | null | app/views/floors.js | john-holland/day-maker | fef8ed77189886d0947f9639db5de2a2fb108960 | [
"MIT"
] | null | null | null | //import document from "document"
import { Alarm } from "../common/alarm"
import * as util from "../common/utils"
import { today as todayActivity, goals } from "user-activity"
import { $, $at } from '../../common/view'
import { UserInterface } from '../ui'
let document = require("document");
const $ = $at('#floors');
export class FloorsUI extends UserInterface {
name = 'floors'
constructor() {
super()
this.$ = $
this.el = this.$()
}
onRender() {
super.onRender()
this.$("#time").text = `${todayActivity.local.elevationGain || 0} floors`
}
}
| 22.230769 | 77 | 0.626298 |
435ef6ea6f379b2d0c44ea0ee48bc602ff317713 | 940 | js | JavaScript | day2.js | moeishaa/adventofcode2021 | db5d58676ba4d96e5a771c91acb14abc45ae593c | [
"MIT"
] | null | null | null | day2.js | moeishaa/adventofcode2021 | db5d58676ba4d96e5a771c91acb14abc45ae593c | [
"MIT"
] | null | null | null | day2.js | moeishaa/adventofcode2021 | db5d58676ba4d96e5a771c91acb14abc45ae593c | [
"MIT"
] | null | null | null | /**
* @param {string[]} input
* @returns number
*/
const part1 = input => {
const [position, depth] = input.reduce((soFar, current) => {
const [action, amount] = current.split(' ');
if (action === 'forward') {
soFar[0] = soFar[0] + Number(amount);
} else {
soFar[1] = soFar[1] + ((action === 'down' ? 1 : -1) * Number(amount));
}
return soFar;
}, [0, 0]);
return position * depth;
};
/**
* @param {string[]} input
* @returns number
*/
const part2 = input => {
let aim = 0;
const [position, depth] = input.reduce((soFar, current) => {
const [action, amount] = current.split(' ');
const amountInt = Number(amount);
if (action === 'forward') {
soFar[0] = soFar[0] + amountInt;
soFar[1] = soFar[1] + (aim * amountInt);
} else {
aim = aim + ((action === 'down' ? 1 : -1) * amountInt);
}
return soFar;
}, [0, 0]);
return position * depth;
};
| 21.363636 | 76 | 0.526596 |
435ef8b1d2a1e181cb123eb2226bd72afc231c6a | 2,474 | js | JavaScript | client/web-admin/src/page/shop/orderDetailsPrint.js | lxh888/openshop | 62e81d913d8fdbde70e4b8b5ad5f3cda6e445614 | [
"Apache-2.0"
] | null | null | null | client/web-admin/src/page/shop/orderDetailsPrint.js | lxh888/openshop | 62e81d913d8fdbde70e4b8b5ad5f3cda6e445614 | [
"Apache-2.0"
] | null | null | null | client/web-admin/src/page/shop/orderDetailsPrint.js | lxh888/openshop | 62e81d913d8fdbde70e4b8b5ad5f3cda6e445614 | [
"Apache-2.0"
] | null | null | null | av({
id:'page-shop-orderDetailsPrint',//工程ID
// selector:'view',//筛选器,指定渲染到哪个父节点。默认是全局那个 BUG
include : ["src/common/content.js","src/page/shop/orderDetails/shippingSen.js","src/page/shop/orderDetails/checkArea.js"],//获取js文件
extend : ["common-content"],//继承该js,只获取不继承无法获取该对象的属性
'export' : {
template: "src/page/shop/orderDetailsPrint.html",},
'import' : function(e){
this.template(e.template);//绑定模版
},
main: function(){
this.data.shop_order_id = (function(){try{ return av.router().anchor.query.id;}catch(e){return '';}}());
if( !this.data.shop_order_id ){
return av.router(av.router().url, '#/shop-orderList/').request();
}
this.data.request.data = ['SHOPADMINORDERDETAILS', [{shop_order_id:this.data.shop_order_id}]];
this.data.request.expressType=['APPLICATIONADMINSHIPPINGOPTIONS',[{module:'express_order_shipping'}]];
if( this.data.applicationCheckYouli() ){
this.data.request.areaList=['SHOPORDERSELFREGIONIDLIST'];
}
},
event: {
error : function(error){
console.log('error 跳转', error);
return av.router(av.router().url, '#/').request();
},
},
//数据对象
data:{
request: {},
data: null,
shop_order_id : "",
submitLock:false,
eventCountNumber:function(){
var eventCountNumber=0;
this.data.shop_order_goods.forEach(element => {
eventCountNumber=eventCountNumber+parseInt(element.shop_order_goods_number);
});
console.log('2222',eventCountNumber);
return eventCountNumber
},
eventPrint:function(){
// var headstr = "<html><head><title></title></head><body>";
// var footstr = "</body>";
// var printData = document.getElementById("dvData").innerHTML; //获得 div 里的所有 html 数据
// var oldstr = document.body.innerHTML;
// document.body.innerHTML = headstr+newstr+footstr;
// window.print();
// document.body.innerHTML = oldstr;
// return false;
console.log("231231")
let go = confirm("是否需要打印?");
// setInterval(function(){
// console.log(document.execCommand("print"));
// },2000);
if(go){
var oldstr = document.body.innerHTML;
var headStr = "<html><head><title></title></head><body>";
var footStr = "</body>";
var content = $("#dvData").html();
var newStr = headStr + content + footStr;
document.body.innerHTML = headStr + content + footStr;
window.print();
document.body.innerHTML = oldstr;
//console.log(1111, document.execCommand("print"));
av.router().reload();
}
},
},
}); | 30.925 | 131 | 0.656831 |
435efab853550bc476259834a0fc6d9441b652ca | 478 | js | JavaScript | DVP-TrunkApp/scripts/IndexController.js | DuoSoftware/DVP-Apps | ae68868ed5c56a4bb26b5da58b0303b1d004ae96 | [
"Apache-2.0"
] | null | null | null | DVP-TrunkApp/scripts/IndexController.js | DuoSoftware/DVP-Apps | ae68868ed5c56a4bb26b5da58b0303b1d004ae96 | [
"Apache-2.0"
] | null | null | null | DVP-TrunkApp/scripts/IndexController.js | DuoSoftware/DVP-Apps | ae68868ed5c56a4bb26b5da58b0303b1d004ae96 | [
"Apache-2.0"
] | null | null | null | /**
* Created by Achintha on 1/19/2016.
*/
(function(){
var app = angular.module("trunkApp");
var IndexController = function($scope,$location){
$scope.selectedIndex = 0;
$scope.$watch('selectedIndex', function(current) {
switch (current) {
case 0:
$location.url("/trunk");
break;
case 1:
$location.url("/phoneNumber");
break;
}});
};
app.controller("IndexController",IndexController);
}());
| 22.761905 | 54 | 0.566946 |
435f15bb4e823330bfdb553f879b7edf98b93a62 | 368 | js | JavaScript | pages/api/account/signin.js | twowheelstogo/storefront-lulis | a78848583ef54d3923fe149c81b45a48cea1215f | [
"Apache-2.0"
] | null | null | null | pages/api/account/signin.js | twowheelstogo/storefront-lulis | a78848583ef54d3923fe149c81b45a48cea1215f | [
"Apache-2.0"
] | null | null | null | pages/api/account/signin.js | twowheelstogo/storefront-lulis | a78848583ef54d3923fe149c81b45a48cea1215f | [
"Apache-2.0"
] | null | null | null | import passportMiddleware, { passport } from "apiUtils/passportMiddleware";
const singIn = async (req, res) => {
req.session.redirectTo = req.headers.Referer;
passport.authenticate("oauth2", {
loginAction: "signin",
failureRedirect: "/"
// eslint-disable-next-line no-unused-vars
})(req, res, (...args) => {});
};
export default passportMiddleware(singIn);
| 28.307692 | 75 | 0.703804 |