text
stringlengths 2
6.14k
|
|---|
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _Plate = require('./Plate');
var _Plate2 = _interopRequireDefault(_Plate);
var _deepEqual = require('deep-equal');
var _deepEqual2 = _interopRequireDefault(_deepEqual);
var _utilsAttachEventBindings = require('./utils/attachEventBindings');
var _utilsAttachEventBindings2 = _interopRequireDefault(_utilsAttachEventBindings);
var _utilsGetFirstDupInArray = require('./utils/getFirstDupInArray');
var _utilsGetFirstDupInArray2 = _interopRequireDefault(_utilsGetFirstDupInArray);
var _tcombReact = require('tcomb-react');
var _interfaces = require('./interfaces');
var _tcombValidation = require('tcomb-validation');
var _tcombValidation2 = _interopRequireDefault(_tcombValidation);
var _tcomb = require('tcomb');
var _tcomb2 = _interopRequireDefault(_tcomb);
var Folio = (function (_Component) {
_inherits(Folio, _Component);
function Folio() {
_classCallCheck(this, _Folio);
_Component.apply(this, arguments);
}
Folio.prototype.componentDidMount = function componentDidMount() {
var _props$schema = this.props.schema;
var options = _props$schema.options;
var config = _props$schema.config;
var on = _props$schema.on;
var adapter = this.props.schema.adapter({ options: options, config: config });
if (process.env.NODE_ENV !== 'production') {
_tcombValidation2['default'].assert(_tcombValidation2['default'].validate(adapter, _interfaces.IAdapterReturn).isValid(), '[folio] Invalid type returned from adapter. Must be an object defining create, update and remove functions.');
}
this.map = adapter.create({ node: this.refs.map });
this.map.decks = {};
this.map.deckStack = {};
if (on) {
_utilsAttachEventBindings2['default'](on, this.map, undefined);
}
if (config.ready && _tcomb2['default'].Function.is(config.ready)) {
config.ready({ map: this.map });
}
this.forceUpdate();
};
Folio.prototype.componentWillReceiveProps = function componentWillReceiveProps(np) {
// NOTE: Unable to test this due to a feature of React that causes problems
// with JSDOM instances.
// @see: https://github.com/facebook/react/issues/4025#issuecomment-109067628
if (this.map) {
if (!_deepEqual2['default'](np.schema.options, this.props.schema.options) || !_deepEqual2['default'](np.schema.config, this.props.schema.config)) {
var _np$schema = np.schema;
var options = _np$schema.options;
var config = _np$schema.config;
var adapter = np.schema.adapter({ options: options, config: config });
adapter.update({ element: this.map });
}
}
};
Folio.prototype.renderPlates = function renderPlates() {
var _this = this;
var dex = [];
if (!this.map) {
return dex;
}
var disabled = this.props.decks.filter(function (o) {
return o.config.enabled === false;
}).map(function (o) {
return o.config.name;
});
var enabledDecks = this.props.decks.filter(function (o) {
return o.config.enabled !== false;
}) // Filter out disabled decks
.filter(function (o) {
return o.config.belongsTo ? disabled.indexOf(o.config.belongsTo.name) === -1 : true;
}); // Filter out decks associated to disabled decks.
if (process.env.NODE_ENV !== 'production') {
(function () {
var enabledDeckNames = enabledDecks.map(function (o) {
return o.config.name;
});
var dupName = _utilsGetFirstDupInArray2['default'](enabledDeckNames);
enabledDeckNames.forEach(function (name) {
_tcombValidation2['default'].assert(_tcomb2['default'].String.is(name), '[folio] InvalidNameError. Decks names must be string. Name: ' + dupName);
});
_tcombValidation2['default'].assert(dupName === false, '[folio] DupNameError. Decks must have unique names. Repeated: ' + dupName + '.');
})();
}
enabledDecks.forEach(function (_ref) {
var adapter = _ref.adapter;
var config = _ref.config;
var options = _ref.options;
var on = _ref.on;
dex.push(_react2['default'].createElement(_Plate2['default'], { config: config, options: options, map: _this.map, adapter: adapter, key: config.name, on: on }));
});
return dex;
};
Folio.prototype.render = function render() {
var mapConfig = this.props.schema.config;
return _react2['default'].createElement(
'div',
{ className: 'folio' },
_react2['default'].createElement('div', { ref: 'map', style: mapConfig.style, className: mapConfig.className }),
_react2['default'].createElement(
'div',
null,
this.renderPlates()
)
);
};
var _Folio = Folio;
Folio = _tcombReact.props(_interfaces.IFolio)(Folio) || Folio;
return Folio;
})(_react.Component);
exports['default'] = Folio;
module.exports = exports['default'];
|
declare module 'bunyan' {
declare var TRACE: 10;
declare var DEBUG: 20;
declare var INFO: 30;
declare var WARN: 40;
declare var ERROR: 50;
declare var FATAL: 60;
declare type BunyanLogLevels =
| 60 // fatal
| 50 // error
| 40 // warn
| 30 // info
| 20 // debug
| 10; // info
declare type BunyanRecord = {
v: number,
level: BunyanLogLevels,
name: string,
hostname: string,
pid: string,
time: Date,
msg: string,
src: string,
err?: {
message: string,
name: string,
code: any,
signal: any,
stack: string,
},
[key: string]: any,
};
declare type Writable = {
write(rec: BunyanRecord): void,
};
declare class Logger extends events$EventEmitter {
constructor(options: LoggerOptions): any;
addStream(stream: Stream): void;
addSerializers(serializers: Serializers): void;
child(opts?: LoggerOptions, simple?: boolean): Logger;
reopenFileStreams(): void;
level(): string | number;
level(value: number | string): void;
levels(name: number | string, value: number | string): void;
fields: any;
trace(...params: Array<void>): boolean;
trace(error: Error, format?: any, ...params: Array<any>): void;
trace(buffer: Buffer, format?: any, ...params: Array<any>): void;
trace(obj: Object, format?: any, ...params: Array<any>): void;
trace(format: string, ...params: Array<any>): void;
debug(...params: Array<void>): boolean;
debug(error: Error, format?: any, ...params: Array<any>): void;
debug(buffer: Buffer, format?: any, ...params: Array<any>): void;
debug(obj: Object, format?: any, ...params: Array<any>): void;
debug(format: string, ...params: Array<any>): void;
info(...params: Array<void>): boolean;
info(error: Error, format?: any, ...params: Array<any>): void;
info(buffer: Buffer, format?: any, ...params: Array<any>): void;
info(obj: Object, format?: any, ...params: Array<any>): void;
info(format: string, ...params: Array<any>): void;
warn(...params: Array<void>): boolean;
warn(error: Error, format?: any, ...params: Array<any>): void;
warn(buffer: Buffer, format?: any, ...params: Array<any>): void;
warn(obj: Object, format?: any, ...params: Array<any>): void;
warn(format: string, ...params: Array<any>): void;
error(...params: Array<void>): boolean;
error(error: Error, format?: any, ...params: Array<any>): void;
error(buffer: Buffer, format?: any, ...params: Array<any>): void;
error(obj: Object, format?: any, ...params: Array<any>): void;
error(format: string, ...params: Array<any>): void;
fatal(...params: Array<void>): boolean;
fatal(error: Error, format?: any, ...params: Array<any>): void;
fatal(buffer: Buffer, format?: any, ...params: Array<any>): void;
fatal(obj: Object, format?: any, ...params: Array<any>): void;
fatal(format: string, ...params: Array<any>): void;
static stdSerializers: {
req: (
req: http$ClientRequest
) => {
method: string,
url: string,
headers: mixed,
remoteAddress: string,
remotePort: number,
},
res: (
res: http$IncomingMessage
) => { statusCode: number, header: string },
err: (
err: Error
) => {
message: string,
name: string,
stack: string,
code: string,
signal: string,
},
};
}
declare interface LoggerOptions {
streams?: Array<Stream>;
level?: BunyanLogLevels | string;
stream?: stream$Writable;
serializers?: Serializers;
src?: boolean;
}
declare type Serializers = {
[key: string]: (input: any) => mixed,
};
declare type Stream = {
type?: string,
level?: number | string,
path?: string,
stream?: stream$Writable | tty$WriteStream | Stream | Writable,
closeOnExit?: boolean,
period?: string,
count?: number,
};
declare var stdSerializers: Serializers;
declare function resolveLevel(value: number | string): number;
declare function createLogger(
options: LoggerOptions & { name: string }
): Logger;
declare class RingBuffer extends events$EventEmitter {
constructor(options: RingBufferOptions): any;
writable: boolean;
records: Array<any>;
write(record: BunyanRecord): void;
end(record?: any): void;
destroy(): void;
destroySoon(): void;
}
declare interface RingBufferOptions {
limit: number;
}
declare function safeCycles(): (key: string, value: any) => any;
declare class ConsoleRawStream {
write(rec: BunyanRecord): void;
}
declare var levelFromName: {
trace: typeof TRACE,
debug: typeof DEBUG,
info: typeof INFO,
warn: typeof WARN,
error: typeof ERROR,
fatal: typeof FATAL,
};
declare var nameFromLevel: {
[key: BunyanLogLevels]: string,
};
declare var VERSION: string;
declare var LOG_VERSION: string;
}
|
import React from 'react';
import classNames from 'classnames';
import PropTypes from 'prop-types';
import { withStyles } from 'material-ui/styles';
import List from 'material-ui/List';
import Drawer from 'material-ui/Drawer';
import SwipeableDrawer from 'material-ui/SwipeableDrawer';
import Typography from 'material-ui/Typography';
import Divider from 'material-ui/Divider';
import Hidden from 'material-ui/Hidden';
import AppDrawerNavItem from 'docs/src/modules/components/AppDrawerNavItem';
import Link from 'docs/src/modules/components/Link';
import { pageToTitle } from 'docs/src/modules/utils/helpers';
const styles = theme => ({
paper: {
width: 250,
backgroundColor: theme.palette.background.paper,
},
title: {
color: theme.palette.text.secondary,
marginBottom: theme.spacing.unit / 2,
'&:hover': {
color: theme.palette.primary.main,
},
},
// https://github.com/philipwalton/flexbugs#3-min-height-on-a-flex-container-wont-apply-to-its-flex-items
toolbarIe11: {
display: 'flex',
},
toolbar: {
...theme.mixins.toolbar,
paddingLeft: theme.spacing.unit * 3,
display: 'flex',
flexGrow: 1,
flexDirection: 'column',
alignItems: 'flex-start',
justifyContent: 'center',
},
anchor: {
color: theme.palette.text.secondary,
},
});
// eslint-disable-next-line react/prop-types
function renderNavItems({ pages, ...params }) {
return (
<List>
{pages.reduce(
// eslint-disable-next-line no-use-before-define
(items, page) => reduceChildRoutes({ items, page, ...params }),
[],
)}
</List>
);
}
function reduceChildRoutes({ props, activePage, items, page, depth }) {
if (page.displayNav === false) {
return items;
}
if (page.children && page.children.length > 1) {
const title = pageToTitle(page);
const openImmediately = activePage.pathname.indexOf(page.pathname) === 0;
items.push(
<AppDrawerNavItem depth={depth} key={title} openImmediately={openImmediately} title={title}>
{renderNavItems({ props, pages: page.children, activePage, depth: depth + 1 })}
</AppDrawerNavItem>,
);
} else {
const title = pageToTitle(page);
page = page.children && page.children.length === 1 ? page.children[0] : page;
items.push(
<AppDrawerNavItem
depth={depth}
key={title}
title={title}
href={page.pathname}
onClick={props.onClose}
/>,
);
}
return items;
}
// iOS is hosted on high-end devices. We can enable the backdrop transition without
// dropping frames. The performance will be good enough.
// So: <SwipeableDrawer disableBackdropTransition={false} />
const iOS = process.browser && /iPad|iPhone|iPod/.test(navigator.userAgent);
function AppDrawer(props, context) {
const { classes, className, disablePermanent, mobileOpen, onClose, onOpen } = props;
const drawer = (
<div className={classes.nav}>
<div className={classes.toolbarIe11}>
<div className={classes.toolbar}>
<Link className={classes.title} href="/" onClick={onClose}>
<Typography variant="title" color="inherit">
Material-UI
</Typography>
</Link>
{process.env.LIB_VERSION ? (
<Link className={classes.anchor} href="/versions">
<Typography variant="caption">{`v${process.env.LIB_VERSION}`}</Typography>
</Link>
) : null}
</div>
</div>
<Divider />
{renderNavItems({ props, pages: context.pages, activePage: context.activePage, depth: 0 })}
</div>
);
return (
<div className={className}>
<Hidden lgUp={!disablePermanent}>
<SwipeableDrawer
classes={{
paper: classNames(classes.paper, 'algolia-drawer'),
}}
disableBackdropTransition={!iOS}
variant="temporary"
open={mobileOpen}
onOpen={onOpen}
onClose={onClose}
ModalProps={{
keepMounted: true,
}}
>
{drawer}
</SwipeableDrawer>
</Hidden>
{disablePermanent ? null : (
<Hidden mdDown implementation="css">
<Drawer
classes={{
paper: classes.paper,
}}
variant="permanent"
open
>
{drawer}
</Drawer>
</Hidden>
)}
</div>
);
}
AppDrawer.propTypes = {
classes: PropTypes.object.isRequired,
className: PropTypes.string,
disablePermanent: PropTypes.bool.isRequired,
mobileOpen: PropTypes.bool.isRequired,
onClose: PropTypes.func.isRequired,
onOpen: PropTypes.func.isRequired,
};
AppDrawer.contextTypes = {
activePage: PropTypes.object.isRequired,
pages: PropTypes.array.isRequired,
};
export default withStyles(styles)(AppDrawer);
|
/**
* Success Criterion 2.4.4: Link Purpose (In Context)
*
* @see http://www.w3.org/TR/UNDERSTANDING-WCAG20/navigation-mechanisms-refs.html
*/
quail.guidelines.wcag.successCriteria['2.4.4'] = (function (quail) {
/**
* Determines if this Success Criteria applies to the document.
*/
function preEvaluator () {
return true;
}
// Create a new SuccessCriteria and pass it the evaluation callbacks.
var sc = quail.lib.SuccessCriteria({
name: 'wcag:2.4.4',
preEvaluator: preEvaluator
});
// Techniques
sc.techniques = {};
// Failures
sc.failures = {};
return sc;
}(quail));
|
'use strict';
var console = chrome.extension.getBackgroundPage().console;
var ajax = function (url) {
var xhr = new XMLHttpRequest(),
type = 'GET';
xhr.open(type, url);
xhr.send(null);
//return promise
return new Promise(function (resolve, reject) {
xhr.onload = function () {
if (xhr.status === 200) {
resolve(xhr.response);
} else {
reject(xhr.response);
}
};
});
};
var getResourceUrl = function (name, id) {
return ajax('http://bt2.bt87.cc/' + 'search/' + name + id + '_ctime_1.html');
};
var getMagnet = function (path) {
return ajax('http://bt2.bt87.cc' + path);
};
var isLoading = false;
var start = function (date) {
var searchId = window.localStorage.getItem('torrentFinderSearchTag') || 1;
var torrentName = window.localStorage.getItem('torrentName') || 'SMBD-';
var torrentId = searchId < 10 ? '0' + searchId : searchId;
var torrentSizeArr = [];
getResourceUrl(torrentName, torrentId)
.then(function (json) {
// var aReg = /(?!<a class="title".* href=")\/\w+\.html(?=">)/g;
// var res = json.match(aReg);
// var reqArr = [];
var reqArr = [];
var dom = document.createElement('div');
var ul = json.match(/<ul class="media-list media-list-set">[\s\S]*<\/ul>/);
if (ul) {
dom.innerHTML = ul;
var mediaBody = dom.querySelectorAll('.media-list .media-body');
mediaBody = Array.prototype.slice.call(mediaBody);
mediaBody.some(function (v, k) {
if (reqArr.length === 3) {
return true;
}
var size = v.querySelector('.label.label-warning').innerHTML;
//小于4G则允许去获取
if (size && size.indexOf('GB') > -1 && parseInt(size) < 4 ||
size && size.indexOf('MB') > -1 && parseInt(size) > 700) {
torrentSizeArr.push(size);
reqArr.push(getMagnet(v.querySelector('.title').getAttribute('href')));
}
});
if (reqArr.length > 0) {
return Promise.all(reqArr);
} else {
//当第二次请求正常或者第一次请求没有匹配到合适的资源,计数+1。
window.localStorage.setItem('torrentFinderSearchTag', + searchId + 1);
return Promise.reject('can not match suitable resource');
}
} else {
return Promise.reject('can not match ul dom');
}
}, function () {
return Promise.reject('getResourceUrl failed');
}).then(function (resArr) {
isLoading = false;
//查找magnet磁力链接并塞进localStorage里。
var magnetReg = /magnet:\??[^"|<]+/;
var res = '';
resArr.forEach(function (v, k) {
res += torrentSizeArr[k] + ':' + v.match(magnetReg)[0] + ';';
});
if (res) {
window.localStorage.setItem('torrentFinder-' + torrentName + torrentId, res);
} else {
console.log('can not match magnetReg');
}
//当第二次请求正常或者第一次请求没有匹配到合适的资源,计数+1。
window.localStorage.setItem('torrentFinderSearchTag', + searchId + 1);
}, function (res) {
console.log(res);
isLoading = false;
});
};
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if(tab.url != undefined && changeInfo.status == 'complete'){
if (!isLoading) {
isLoading = true;
start();
}
}
});
|
import EventEmitter from 'events';
import isUndefined from 'lodash.isundefined';
var ArrayProto = Array.prototype;
export default ArrayEmitter;
// Make the standard ES5 array transformations work as expected...
function ArrayEmitter(...args) {
// Need to generate an actual array here for proper behaviour (in a full ES6 environment we
// should be able to subclass array. But alas)
var arr = new Array(...args);
// Non enumerable so that we can send the array over postMessage
Object.defineProperty(arr, '$emitter', {
enumerable: false,
value: new EventEmitter()
});
// Generate our Array Emitter methods
var ArrayEmitterMethods = {};
['on', 'once', 'addListener', 'removeListener'].forEach(function(key) {
ArrayEmitterMethods[key] = {
enumerable: false,
value: function(...args) {
return this.$emitter[key](...args);
}
};
});
// These methods create new arrays
['reverse', 'sort', 'splice'].forEach(function(key) {
ArrayEmitterMethods[key] = {
enumerable: false,
value: function(...args) {
var _emitter = this.$emitter;
incrMaxListeners(_emitter);
_emitter.on('update', () => {
ArrayProto[key].apply(this, args);
});
ArrayProto[key].apply(this, args);
return this;
}
};
});
['filter', 'map', 'slice'].forEach(function(key) {
ArrayEmitterMethods[key] = {
enumerable: false,
value: function(...args) {
var newArr = new ArrayEmitter();
var _emitter = this.$emitter;
incrMaxListeners(_emitter);
_emitter.on('update', () => {
updateNewArr(ArrayProto[key].apply(this, args));
newArr.$emitter.emit('update', newArr);
});
updateNewArr(ArrayProto[key].apply(this, args));
function updateNewArr(arr) {
newArr.length = 0;
for (var i = 0; i < arr.length; i++) {
newArr.push(arr[i]);
}
}
return newArr;
}
};
});
ArrayEmitterMethods.concat = {
enumerable: false,
value: function(...args) {
var newArr = new ArrayEmitter();
var allArrs = [this, ...args];
var qries = allArrs.filter((obj) => (Array.isArray(obj) && obj.$emitter));
qries.forEach((_qry) => {
var _emitter = _qry.$emitter;
incrMaxListeners(_emitter);
_emitter.on('update', () => {
updateConcat();
newArr.$emitter.emit('update', newArr);
});
});
updateConcat();
return newArr;
function updateConcat() {
var concatted = ArrayProto.concat.call(...allArrs);
newArr.length = 0;
newArr.push(...concatted);
}
}
};
Object.defineProperties(arr, ArrayEmitterMethods);
return arr;
}
function getMaxListeners(emitter) {
if (emitter.getMaxListeners) {
return emitter.getMaxListeners();
}
if (isUndefined(emitter._maxListeners)) {
return EventEmitter.defaultMaxListeners;
}
return emitter._maxListeners;
}
function incrMaxListeners(emitter) {
var maxListeners = getMaxListeners(emitter);
// A maxListeners of 0 means infinite, We don't want to increment in that case
if (maxListeners) {
emitter.setMaxListeners(maxListeners + 1);
}
}
|
import { createSelector } from 'reselect'
export const getGame = state => state.game
export const getWhosTurn = createSelector(
[getGame],
game => game.whosTurn
)
export const getPlayers = createSelector(
[getGame],
game => game.players
)
|
import { isEqual, startsWith } from 'lodash-es'
import Coordinate from '../../model/Coordinate'
import IsolatedNodeComponent from '../isolated-node/IsolatedNodeComponent'
class InlineNodeComponent extends IsolatedNodeComponent {
get _isInlineNodeComponent() {
return true
}
// use spans everywhere
get __elementTag() {
return 'span'
}
get __slugChar() {
return "\uFEFF"
}
getClassNames() {
return 'sc-inline-node'
}
render($$) { // eslint-disable-line
let el = super.render($$)
el.attr('data-inline', '1')
return el
}
// TODO: this is almost the same as the super method. Try to consolidate.
_deriveStateFromSelectionState(selState) {
let sel = selState.getSelection()
let surfaceId = sel.surfaceId
if (!surfaceId) return
let id = this.getId()
let node = this.props.node
let parentId = this._getSurfaceParent().getId()
let inParentSurface = (surfaceId === parentId)
// detect cases where this node is selected or co-selected by inspecting the selection
if (inParentSurface) {
if (sel.isPropertySelection() && !sel.isCollapsed() && isEqual(sel.path, node.path)) {
let nodeSel = node.getSelection()
if(nodeSel.equals(sel)) {
return { mode: 'selected' }
}
if (sel.contains(nodeSel)) {
return { mode: 'co-selected' }
}
}
return
}
// for all other cases (focused / co-focused) the surface id prefix must match
if (!startsWith(surfaceId, id)) return
// Note: trying to distinguisd focused
// surfaceIds are a sequence of names joined with '/'
// a surface inside this node will have a path with length+1.
// a custom selection might just use the id of this IsolatedNode
let p1 = id.split('/')
let p2 = surfaceId.split('/')
if (p2.length >= p1.length && p2.length <= p1.length+1) {
return { mode: 'focused' }
} else {
return { mode: 'co-focused' }
}
}
_selectNode() {
// console.log('IsolatedNodeComponent: selecting node.');
let editorSession = this.context.editorSession
let surface = this.context.surface
let node = this.props.node
editorSession.setSelection({
type: 'property',
path: node.path,
startOffset: node.startOffset,
endOffset: node.endOffset,
containerId: surface.getContainerId(),
surfaceId: surface.id
})
}
}
InlineNodeComponent.getCoordinate = function(el) {
// special treatment for block-level isolated-nodes
let parent = el.getParent()
if (el.isTextNode() && parent.is('.se-slug')) {
let slug = parent
let nodeEl = slug.getParent()
if (nodeEl.is('.sc-inline-node')) {
let startOffset = Number(nodeEl.getAttribute('data-offset'))
let len = Number(nodeEl.getAttribute('data-length'))
let charPos = startOffset
if (slug.is('sm-after')) charPos += len
let path
while ( (nodeEl = nodeEl.getParent()) ) {
let pathStr = nodeEl.getAttribute('data-path')
if (pathStr) {
path = pathStr.split('.')
let coor = new Coordinate(path, charPos)
coor.__inInlineNode__ = true
coor.__startOffset__ = startOffset
coor.__endOffset__ = startOffset+len
return coor
}
}
}
}
return null
}
export default InlineNodeComponent
|
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'eval',
entry: [
'webpack-dev-server/client?http://localhost:5000',
'webpack/hot/only-dev-server',
'./src/index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin()
],
module: {
loaders: [{
test: /\.js$/,
loaders: ['react-hot', 'babel'],
include: path.join(__dirname, 'src')
}]
}
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:e40fc39c3be7cd4f6f523043fce5ad7b671ec46f107fac32da4a80700a70c41e
size 7881
|
version https://git-lfs.github.com/spec/v1
oid sha256:ef2c0ebe5ba1bd5f6c6544d417b9eb5dd95937879bc9f2892670bc4e4e3834c2
size 156883
|
version https://git-lfs.github.com/spec/v1
oid sha256:59f940586c1c735243394f70835ec840e043025a2d5397bc1efb6325263598ac
size 2011
|
var path = require('path')
var config = require('../config')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
exports.assetsPath = function (_path) {
var assetsSubDirectory = process.env.NODE_ENV === 'production'
? config.build.assetsSubDirectory
: config.dev.assetsSubDirectory
return path.posix.join(assetsSubDirectory, _path)
}
exports.cssLoaders = function (options) {
options = options || {}
var cssLoader = {
loader: 'css-loader',
options: {
minimize: process.env.NODE_ENV === 'production',
sourceMap: options.sourceMap
}
}
// generate loader string to be used with extract text plugin
function generateLoaders (loader, loaderOptions) {
var loaders = [cssLoader]
if (loader) {
loaders.push({
loader: loader + '-loader',
options: Object.assign({}, loaderOptions, {
sourceMap: options.sourceMap
})
})
}
// Extract CSS when that option is specified
// (which is the case during production build)
if (options.extract) {
return ExtractTextPlugin.extract({
use: loaders,
fallback: 'vue-style-loader'
})
} else {
return ['vue-style-loader'].concat(loaders)
}
}
// https://vue-loader.vuejs.org/en/configurations/extract-css.html
return {
css: generateLoaders(),
postcss: generateLoaders(),
less: generateLoaders('less'),
sass: generateLoaders('sass', { indentedSyntax: true }),
scss: generateLoaders('sass', {
data: '@import "./src/styles/theme.scss";'
}),
stylus: generateLoaders('stylus'),
styl: generateLoaders('stylus')
}
}
// Generate loaders for standalone style files (outside of .vue)
exports.styleLoaders = function (options) {
var output = []
var loaders = exports.cssLoaders(options)
for (var extension in loaders) {
var loader = loaders[extension]
output.push({
test: new RegExp('\\.' + extension + '$'),
use: loader
})
}
return output
}
|
export async function up(knex) {
await knex.schema.createTable('suggestions', table => {
table.increments('id')
table.integer('channel_id')
table.string('suggestion', 255)
table.string('hash', 48)
table.string('user')
table.integer('votes')
table.timestamps()
table.index('channel_id')
table.index(['channel_id', 'hash'])
})
}
export async function down(knex) {
await knex.schema.dropTable('suggestions')
}
|
YUI.add('alarmAPI', function(Y, NAME) {
Y.namespace('mojito.controllers')[NAME] = {
get: function(ac) {
ac.models.get("alarmAPIModelAlarms").get(function(err, data) {
if (err) {
ac.error(err);
return;
}
ac.done({
alarms: data
}, 'json');
});
},
set: function(ac) {
var params = ac.params.getFromUrl();
var message = params.message;
var time = params.time;
ac.models.get("alarmAPIModelAlarms").set(message, time, function(err) {
if (err) {
ac.error(err);
return;
}
ac.done({
success: true
}, 'json');
});
},
// BEGIN CODE CHANGES
// The delete API takes a single query string param: the message,
// which functions as the key of our alarm (one alarm per message).
// Easiest to copy the contents of the set function and just change
// to suit our needs.
del: function(ac) {
var params = ac.params.getFromUrl();
// Only look for one param.
var message = params.message;
// Correctly call the del function.
ac.models.get("alarmAPIModelAlarms").del(message, function(err) {
if (err) {
ac.error(err);
return;
}
ac.done({
success: true
}, 'json');
});
}
// END CODE CHANGES
};
}, '0.0.1', {requires: ['mojito', 'mojito-params-addon', 'mojito-assets-addon', 'mojito-models-addon', 'mojito-composite-addon']});
|
$().ready(function(){
$('button').on('click', changeDice);
});
// min~maxの整数をランダムに返す
rand = function (min, max) {
return Math.floor(Math.random() * (max - min+ 1)) + min;
};
// diceの画像をランダムなサイコロに変える
changeDice = function(){
// サイコロの目を決定
var diceNumber = rand(1, 6);
// サイコロの目からファイル名を作る
var filename = '../dice'+diceNumber+'.png';
// diceをそのファイルに変える
$('#dice').attr('src', filename);
// サイコロの目からメッセージを作る
var diceMessage = ''+diceNumber+'が出ました!';
// dice_messageをメッセージに変える
$('#dice_message').html(diceMessage);
};
|
// import fetch from 'isomorphic-fetch';
export default function request(obj) {
switch(obj.method) {
case 'get':
return fetch(obj.url)
.then(res => {
return res.json();
})
.then((res) => {
if(res.cod === '200') {
return Promise.resolve(res);
}
return Promise.reject(res);
});
// return new Promise((res) => {
// setTimeout(() => {
// res({
// title: 'data from mocked api'
// });
// }, 1000);
// });
default:
return fetch(obj.url).then(res => res.json());
}
}
|
import React from 'react';
import styled from 'react-emotion';
import ReactRouterPropTypes from 'react-router-prop-types';
import { router as routerService } from '../../services';
const Container = styled('div')`
position: relative;
height: 70px;
display: flex;
justify-content: center;
align-items: center;
`;
const IconContainer = styled('button')`
width: 50px;
height: 50px;
font-family: 'Roboto', sans-serif;
font-weight: lighter;
font-size: 20px;
outline: none;
background: none;
border: 3px solid rgba(56, 56, 56, 0.9);
border-radius: 50%;
color: rgba(56, 56, 56, 0.9);
display: flex;
justify-content: center;
align-items: center;
margin: 10px;
&:hover {
border-color: green;
color: green;
cursor: pointer;
}
// nav bar useage at width less than 800px
@media (max-width: 800px) {
border: none;
margin: 0px;
border-radius: 0px;
background-color: #8080801c;
margin-left: 2px;
height: 80px;
width: 80px;
color: #ffffff36;
}
@media (max-width: 500px) {
height: 50px;
width: 50px;
}
`;
class Component extends React.Component {
constructor(props) {
super(props);
this.handleExitClick = this.handleExitClick.bind(this);
this.handleNavtoHomeClick = this.handleNavtoHomeClick.bind(this);
}
handleExitClick() {
const { history } = this.props;
routerService.closeModal(history);
}
handleNavtoHomeClick() {
const { history } = this.props;
routerService.openIntroModal(history);
}
render() {
return (
<Container>
<IconContainer role="img" onClick={this.handleExitClick}>
<i className="fas fa-times" />
</IconContainer>
<IconContainer role="img" onClick={this.handleNavtoHomeClick}>
<i className="fas fa-home" />
</IconContainer>
</Container>
);
}
}
Component.propTypes = {
history: ReactRouterPropTypes.history.isRequired,
};
export default Component;
|
/**
* @name list.js
* @autor
* @description List module definition
*/
'use strict';
// Adds the requires for the module
var Backbone = require('Backbone'),
router = require('../router'),
urls = require('../services/urls'),
Scrolling = require('../mixins/scroll');
// Exports the header module
module.exports = Backbone.View.extend({
// Sets the template
tpl: require('../templates/list.tpl'),
// Sets the module class
className: 'booklist list',
// Sets the tag for the list
tagName: 'ul',
// Gets the events for the view
events: {
'tap li' : 'onTap'
},
// Initializes the view
initialize: function() {
var me = this;
// Adds the listener to the collection
me.listenTo(me.collection, 'reset', me.render);
// NOTE: In a real application, we need to add listeners to
// the 'add' and 'remove' collection events, in order to keep
// the list updated every time that the collection is fetched
//me.listenTo(me.collection, 'add', me.add);
//me.listenTo(me.collection, 'remove', me.remove);
},
// Renders the view
render: function() {
this.$el.html(this.tpl({ books: this.collection.toJSON() }));
return this;
},
// Function fired when a book is tapped
onTap: function(e) {
// Gets the node and it's id
var target = e.target,
node = target.classList.contains('book') ? target : target.parentNode,
id = node && node.getAttribute('data-id');
// Navigates to the view if the id was found
if (id) {
router.navigate(urls('book', id), { trigger: true });
}
}
// Adds the scroll mixin with the options to override, and exports the module
// when the parentWrap option is true, the module's element (this.el) is not taken as the scroll wrapper,
// instead, it's parent node is used as the wrapper (in this case the main div)
}).mixin(Scrolling, { parentWrap: true, click: false, tap: true });
|
import React from 'react';
import R from 'ramda';
class StatsTable extends React.Component {
render() {
return (
<table>
<thead>
<tr>
<th>HP</th>
<th>Str</th>
<th>Mag</th>
<th>Skl</th>
<th>Spd</th>
<th>Lck</th>
<th>Def</th>
<th>Res</th>
<th>Mov</th>
</tr>
</thead>
<tbody>
<tr>
<td>{this.props.hp }</td>
<td>{this.props.str}</td>
<td>{this.props.mag}</td>
<td>{this.props.skl}</td>
<td>{this.props.spd}</td>
<td>{this.props.lck}</td>
<td>{this.props.def}</td>
<td>{this.props.res}</td>
<td>{this.props.mov}</td>
</tr>
</tbody>
</table>
);
}
}
StatsTable.propTypes = {
hp: React.PropTypes.number,
str: React.PropTypes.number,
mag: React.PropTypes.number,
skl: React.PropTypes.number,
spd: React.PropTypes.number,
lck: React.PropTypes.number,
def: React.PropTypes.number,
res: React.PropTypes.number,
mov: React.PropTypes.number
};
StatsTable.defaultProps = {
hp: 0,
str: 0,
mag: 0,
skl: 0,
spd: 0,
lck: 0,
def: 0,
res: 0,
mov: 0
};
export default StatsTable;
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const state_mgmt_1 = require("../../state-mgmt");
exports.claims = {
/**
* Sets additional developer claims on an existing user identified by the provided uid,
* typically used to define user roles and levels of access.
*/
async setCustomUserClaims(uid, customUserClaims) {
state_mgmt_1.updateUser(uid, { customClaims: customUserClaims });
}
};
//# sourceMappingURL=claims.js.map
|
import angular from 'angular';
import ngResource from 'angular-resource';
import Users from './users.factory';
import UserProducts from './userproducts.factory';
import Products from './products.factory';
import Sessions from './sessions.factory';
export default angular.module('factories', [ngResource])
.factory('Users', Users)
.factory('UserProducts', UserProducts)
.factory('Products', Products)
.factory('Sessions', Sessions)
.name;
|
(function ($) {
$(document).ready(function () {
var hiddenInputs = $('*[data-hidden="true"]');
hiddenInputs.attr('aria-hidden','true');
hiddenInputs
.focus(function () {
$(this).attr('aria-hidden', 'false');
})
.blur(function () {
$(this).attr('aria-hidden', 'true');
});
});
})(jQuery);
|
"use strict";
var bodec = require('bodec');
var mine = require('mine');
var pathJoin = require('path').join;
var vm = require('vm');
module.exports = function* (load, url, code) {
var loaded = {};
var defs = {};
var modules = {};
code = bodec.toUnicode(code);
yield* prep(url, code);
var out = globalRequire(url);
if (typeof out === "function") {
if (/^function\s*\*/.test(out.toString())) {
return yield* out(load, url);
}
return yield out(load, url);
}
return out;
function globalRequire(url) {
if (url in modules) return modules[url].exports;
var exports = {};
var module = modules[url] = { exports: exports };
var dirname = pathJoin(url, "..");
var sandbox = {
console: console,
require: localRequire,
module: module,
exports: exports,
__dirname: dirname,
__filename: url
};
defs[url].runInNewContext(sandbox);
// if (ret !== undefined) module.exports = ret;
return sandbox.module.exports;
function localRequire(path) {
if (path[0] === ".") {
path = pathJoin(dirname, path);
if (!/\.js$/.test(path)) path += ".js";
return globalRequire(path);
}
return require(path);
}
}
function* prep(url, code) {
if (loaded[url]) return;
loaded[url] = true;
if (!code) {
var meta = yield* load(url);
if (!meta) {
throw new Error("No such module: " + url);
}
code = yield meta.repo.loadAs("blob", meta.hash);
code = bodec.toUnicode(code);
}
defs[url] = vm.createScript(code, "vfs:/" + url);
var deps = mine(code);
for (var i = 0, l = deps.length; i < l; i++) {
var name = deps[i].name;
if (name[0] !== ".") continue;
var dep = pathJoin(url, "..", name);
if (!/\.js$/.test(dep)) dep += ".js";
yield* prep(dep);
}
}
};
|
/* eslint-disable react/sort-comp */
/* @flow */
import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import type { Connector } from 'react-redux';
import Helmet from 'react-helmet';
import * as action from './action';
import type { Home as HomeType, Dispatch, Reducer } from '../../types';
import UserList from '../../components/UserList';
import styles from './Home.scss';
type Props = {
home: HomeType,
fetchUsersIfNeeded: () => void,
};
// Export this for unit testing more easily
export class Home extends PureComponent {
props: Props;
static defaultProps: {
home: {
readyStatus: 'USERS_INVALID',
list: null,
},
fetchUsersIfNeeded: () => {},
};
componentDidMount() {
this.props.fetchUsersIfNeeded();
}
renderUserList = () => {
const { home } = this.props;
if (home.loading) {
return <p>Loading...</p>;
}
if (home.err) {
return <p>Oops, Failed to load list!</p>;
}
return !!home.list && <UserList list={home.list} />;
}
render() {
return (
<div className={styles.Home}>
<Helmet title="Home" />
{this.renderUserList()}
</div>
);
}
}
const connector: Connector<{}, Props> = connect(
({ home }: Reducer) => ({ home }),
(dispatch: Dispatch) => ({
fetchUsersIfNeeded: () => dispatch(action.fetchUsersIfNeeded()),
}),
);
export default connector(Home);
|
define([
'./helpers', // pre-fetch, dep of ./deploy
'./deploy', // pre-fetch, dep of ./lang
'./lang',
'codemirror/lib/codemirror',
'codemirror/mode/smalltalk/smalltalk',
'codemirror/addon/hint/show-hint',
'css!codemirror/theme/ambiance',
'css!codemirror/lib/codemirror',
'css!codemirror/addon/hint/show-hint',
'jquery-ui',
'amber_core/IDE',
'amber_core/Examples',
'amber_core/Benchfib',
'css!amber/resources/amber'
], function (amber) { return amber; });
|
/**
* Created by zhang_000 on 2015/1/17.
*/
define(["modernizr"],function (require) {
require("modernizr");
/**
* MDNotification.js v1.0.0
* http://www.codrops.com
*
* Licensed under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*
* Copyright 2014, Codrops
* http://www.codrops.com
*/
(function (window) {
'use strict';
var docElem = window.document.documentElement,
support = {animations: Modernizr.cssanimations},
animEndEventNames = {
'WebkitAnimation': 'webkitAnimationEnd',
'OAnimation': 'oAnimationEnd',
'msAnimation': 'MSAnimationEnd',
'animation': 'animationend'
},
// animation end event name
animEndEventName = animEndEventNames[Modernizr.prefixed('animation')];
/**
* extend obj function
*/
function extend(a, b) {
for (var key in b) {
if (b.hasOwnProperty(key)) {
a[key] = b[key];
}
}
return a;
}
/**
* MDNotification function
*/
function MDNotification(options) {
this.options = $.extend({}, this.options, options);
this._init();
}
/**
* MDNotification options
*/
MDNotification.prototype.options = {
// element to which the notification will be appended
// defaults to the document.body
wrapper: document.body,
// the message
message: 'yo!',
// layout type: growl|attached|bar|other
layout: 'growl',
// effects for the specified layout:
// for growl layout: scale|slide|genie|jelly
// for attached layout: flip|bouncyflip
// for other layout: boxspinner|cornerexpand|loadingcircle|thumbslider
// ...
effect: 'slide',
// notice, warning, error, success
// will add class ns-type-warning, ns-type-error or ns-type-success
type: 'error',
// if the user doesn´t close the notification then we remove it
// after the following time
ttl: 6000,
// callbacks
onClose: function () {
return false;
},
onOpen: function () {
return false;
}
}
/**
* init function
* initialize and cache some vars
*/
MDNotification.prototype._init = function () {
// create HTML structure
this.ntf = document.createElement('div');
this.ntf.className = 'ns-box ns-' + this.options.layout + ' ns-effect-' + this.options.effect + ' ns-type-' + this.options.type;
var strinner = '<div class="ns-box-inner">';
strinner += this.options.message;
strinner += '</div>';
strinner += '<span class="ns-close"></span></div>';
this.ntf.innerHTML = strinner;
// append to body or the element specified in options.wrapper
this.options.wrapper.insertBefore(this.ntf, this.options.wrapper.firstChild);
// dismiss after [options.ttl]ms
var self = this;
this.dismissttl = setTimeout(function () {
if (self.active) {
self.dismiss();
}
}, this.options.ttl);
// init events
this._initEvents();
};
/**
* init events
*/
MDNotification.prototype._initEvents = function () {
var self = this;
// dismiss notification
$(this.ntf).on("click",".ns-close",function(){
self.dismiss();
});
};
/**
* show the notification
*/
MDNotification.prototype.show = function () {
this.active = true;
$(this.ntf).removeClass("ns-hide").addClass("ns-show");
//classie.remove( this.ntf, 'ns-hide' );
//classie.add( this.ntf, 'ns-show' );
this.options.onOpen();
};
/**
* dismiss the notification
*/
MDNotification.prototype.dismiss = function () {
var self = this;
this.active = false;
clearTimeout(this.dismissttl);
$(this.ntf).removeClass("ns-show");
//classie.remove( this.ntf, 'ns-show' );
setTimeout(function () {
$(self.ntf).addClass("ns-hide");
//classie.add( self.ntf, 'ns-hide' );
// callback
self.options.onClose();
}, 25);
// after animation ends remove ntf from the DOM
var onEndAnimationFn = function (ev) {
if (support.animations) {
if (ev.target !== self.ntf) return false;
this.removeEventListener(animEndEventName, onEndAnimationFn);
}
$(self.ntf).remove();
//self.options.wrapper.removeChild(this);
};
if (support.animations) {
this.ntf.addEventListener(animEndEventName, onEndAnimationFn);
}
else {
onEndAnimationFn();
}
};
/**
* add to global namespace
*/
window.MDNotification = MDNotification;
})(window);
});
|
'use strict';
var CreatePage = function() {
this.submitButton = element(by.id('classifierSubmitBtn'));
this.classnameEl = element(by.model('classifier.classname'));
this.classnameViewEl = element.all(by.binding('classifier.classname')).first();
this.constantEl = element(by.model('classifier.constant'));
this.constantViewEl = element.all(by.binding('classifier.constant')).first();
this.descriptionEl = element(by.model('classifier.description'));
this.descriptionViewEl = element.all(by.binding('classifier.description')).first();
this.propertynameEl = element(by.model('classifier.propertyname'));
this.propertynameViewEl = element.all(by.binding('classifier.propertyname')).first();
};
module.exports = new CreatePage();
|
module.exports = function (A) {
A.app({
entities: {
User: {
fields: function (Fields, $parentProperty) {
$parentProperty.email = Fields.text('Email').unique();
return $parentProperty;
}
}
}
})
};
|
import { Meteor } from 'meteor/meteor';
import { RocketChat } from 'meteor/rocketchat:lib';
import s from 'underscore.string';
Meteor.publish('customSounds', function(filter, limit) {
if (!this.userId) {
return this.ready();
}
const fields = {
name: 1,
extension: 1,
};
filter = s.trim(filter);
const options = {
fields,
limit,
sort: { name: 1 },
};
if (filter) {
const filterReg = new RegExp(s.escapeRegExp(filter), 'i');
return RocketChat.models.CustomSounds.findByName(filterReg, options);
}
return RocketChat.models.CustomSounds.find({}, options);
});
|
'use strict';
var moment = require('moment');
var Gerencianet = require('gn-api-sdk-node');
var options = require('../../credentials');
var tomorrow = moment()
.add(1, 'days')
.format('YYYY-MM-DD');
var params = {
id: 0
}
var body = {
payment: {
banking_billet: {
expire_at: tomorrow,
customer: {
name: 'Gorbadoc Oldbuck',
email: 'oldbuck@gerencianet.com.br',
cpf: '94271564656',
birth: '1977-01-15',
phone_number: '5144916523'
}
}
}
}
var gerencianet = new Gerencianet(options);
gerencianet
.payCharge(params, body)
.then((resposta) => {
console.log(resposta)
})
.catch((error) => {
console.log(error);
})
.done();
|
/*!
* @author Steven Masala [me@smasala.com]
*/
define([],function(){"use strict";return Firebrick.define("Firebrick.ui.common.mixins.Items",{defaults:1,itemsAlign:null,items:null,getItems:function(){var e=this,t=e._getItems(e.items);return e.items=t.items,t.html},getItemsProp:function(e){var t=this,n,r="";return e?(n=t._getItems(t[e]),t[e]=n.items,r=n.html):console.error("invalid function call getItemsProp():",e),r},_getItems:function(e){return Firebrick.ui._populate(e,this)}})});
|
// @flow
import * as React from 'react'
import { NavLink } from 'react-router-dom'
/* eslint-disable no-undef */
type PropsType = {
+onClick: Function,
+id: number,
+title:string,
+tooltip:string,
+url:string
}
/* eslint-enable no-undef */
const Navigation:React.StatelessFunctionalComponent<any> = ({ onClick, id, title, tooltip, url }:PropsType):React.Element<any> => (
<div onClick={onClick} alt={tooltip}>
<NavLink
to={url}
exact
activeStyle={{
fontWeight: 'bold',
color: 'red'
}}
>{title}</NavLink >
</div >
)
export default Navigation
|
'use strict';
/**
* @exports utils
* @author Chen Liang [code@chen.technology]
*/
/*!
* Module dependencies.
*/
var Promise = require('bluebird/js/main/promise')();
Promise.prototype.getTaskId = function() {
return this.taskId;
};
Promise.prototype.setTaskId = function(taskId) {
this.taskId = taskId;
};
var stringifyError = function(err) {
var plainObject = {};
Object.getOwnPropertyNames(err).forEach(function(key) {
plainObject[key] = err[key];
});
plainObject.name = err.name;
return plainObject;
};
var LocalStack = function() {
this.stack = [];
};
LocalStack.prototype.push = function() {
return this.stack.push.apply(this.stack, arguments);
};
LocalStack.prototype.pop = function(k) {
var stackLength = this.stack.length;
var l = k ? Math.min(k, stackLength) : 0;
return l ? this.stack.splice(stackLength - l, stackLength).reverse() : this.stack.pop();
};
LocalStack.prototype.top = function(k) {
var l = k ? (+k ? Math.abs(k) : 0) : 0;
var stack = this.stack;
var hpos = stack.length - l - 1;
return stack[hpos];
};
LocalStack.prototype.tail = function(k) {
var stack = this.stack;
var l = k ? (+k ? Math.abs(k) : 0) : 0;
return stack[l];
};
LocalStack.prototype.size = function() {
return this.stack.length;
};
LocalStack.prototype.indexOf = function(el, from) {
var stack = this.stack;
var r = stack.indexOf(el);
var len = stack.length - 1;
var f = len - (+from || 0);
return ~r ? (r <= f ? len - r : -1) : -1;
};
LocalStack.prototype.flush = function(evict) {
var stack = this.stack;
var slen = stack.length;
var empty = evict === undefined || evict === true;
return empty ? (stack.length = 0) || slen : 0;
};
module.exports = {
Promise: Promise,
stringifyError: stringifyError,
LocalStack: LocalStack,
};
|
if ( !Array.prototype.forEach ) {
Array.prototype.forEach = function(fn, scope) {
for(var i = 0, len = this.length; i < len; ++i) {
fn.call(scope, this[i], i, this);
}
}
}
|
function handleMostrar(args) {
if (args.mostrarJanela == true){
dialogUnidadeSlideTarefa.show();
}
}
function mapa() {
if (tabUnidadeSlideTarefa_activeIndex.value == "2")
inicializarMapa();
}
|
if (typeof(addon) != 'undefined') addon.port.on("execCode", function(code) {eval(code); } );
if (typeof(self) != 'undefined') self.port.on("execCode", function(code) {eval(code); } );
|
'use strict';
describe('personCollection list page', function() {
var page;
beforeEach(function() {
var mockModule = require('./personCollection.mocks');
browser.addMockModule('httpBackendMock', mockModule );
browser.get('/#/app/personCollection/list');
page = require('./personCollection.list.po');
});
afterEach(function() {
browser.clearMockModules();
});
it('should contain all search fields.', function() {
expect(page.ageEl).not.toBeNull()
expect(page.nameEl).not.toBeNull()
expect(page.divisionEl).not.toBeNull()
});
});
|
// @flow
import React from 'react'
import {Map} from 'react-leaflet'
import renderer from 'react-test-renderer'
import GeoJSON from '../geojson'
describe('Components > Map > GeoJSON', () => {
it('renders correctly', () => {
const geojson = {
type: 'FeatureCollection',
features: []
}
const tree = renderer
.create(
<Map>
<GeoJSON data={geojson} />
</Map>
)
.toJSON()
expect(tree).toMatchSnapshot()
// expect geojson to be added to map by intercepting call to Leaflet
// expect(Leaflet.geoJson.mock.calls[0][0]).toMatchSnapshot()
})
})
|
var gutil = require('gulp-util'),
parse = require('aster-parse')(),
sourceMapToAst = require('sourcemap-to-ast'),
generate = require('escodegen').generate,
Rx = require('rx'),
ObservableStream = require('./ObservableStream');
module.exports = function (asterTransform) {
'use strict';
return new ObservableStream(function (observable) {
var files = observable.map(function (file) {
if (file.isNull()) {
return {
path: file.relative,
contents: ''
};
}
if (file.isStream()) {
throw new gutil.PluginError('gulp-aster', 'Stream content is not supported');
}
if (file.isBuffer()) {
return {
path: file.relative,
contents: String(file.contents)
};
}
});
files = parse(files).zip(observable.pluck('sourceMap'), function (file, sourceMap) {
if (sourceMap) {
sourceMapToAst(file.program, sourceMap);
}
return file;
});
files = asterTransform(Rx.Observable.return(files)).single().concatAll();
files = files.map(function (file) {
var output = generate(file.program, {
sourceMap: true,
sourceMapWithCode: true
});
file = new gutil.File({
path: file.path,
contents: new Buffer(output.code)
});
file.sourceMap = JSON.parse(output.map.toString());
return file;
});
return files;
});
};
|
var sectionBtn = document.getElementById("landing-link");
sectionBtn.onclick = function() {
var el = document.getElementById("d4sd");
var offset = el.getBoundingClientRect();
TweenLite.to(window, 1, {scrollTo:offset});
}
var sectionBtn2 = document.getElementById("nav-port");
sectionBtn2.onclick = function() {
var offset = document.getElementById("d4sd").offsetTop;
TweenLite.to(window, 1, {scrollTo:offset});
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:9f26f90bdd972aae4b87258d3f928992d9ac72ed0fe0d0cbde297be026547b95
size 528
|
export default {
mainPosition (state) {
if (null !== state.elMain) {
return {
x: state.elMain.scrollLeft,
y: state.elMain.scrollTop
};
}
return { x: 0, y: 0 };
},
beforeMainPosition (state) {
return state.beforeMainPosition;
}
};
|
import React from 'react'
import ArticleActions from '../actions/ArticleActions'
import ArticleStore from '../stores/ArticleStore'
import Helpers from '../utilities/Helpers'
import {Link} from 'react-router'
export default class Home extends React.Component {
constructor (props) {
super(props)
this.state = ArticleStore.getState()
this.onChange = this.onChange.bind(this)
}
onChange (state) {
this.setState(state)
}
componentDidMount () {
ArticleStore.listen(this.onChange)
ArticleActions.getLatestNews()
}
componentWillUnmount () {
ArticleStore.unlisten(this.onChange)
}
render () {
let news = this.state.latestNews.map((article, index) => {
return (
<div className='single-article' key={index}>
<Link to={`/article/${article._id}`}>
<img src={article.image} alt='article' />
<h3>{article.title}</h3>
</Link>
<p>{Helpers.formatDate(article.dateCreated)}</p>
<p>{article.description.substr(0, 300)}</p>
</div>
)
})
return (
<div className='container'>
<h3 className='text-center'>Welcome to
<strong> Financial News</strong>
</h3>
<div className='list-group'>
{news}
</div>
</div>
)
}
}
|
"use strict";
var _ = require('./lodash');
var utils = require('./utils');
var $ = require('jquery');
var BlockReorder = require('./block-reorder');
var SimpleBlock = function(data, instance_id, mediator) {
this.createStore(data);
this.blockID = _.uniqueId('st-block-');
this.instanceID = instance_id;
this.mediator = mediator;
this._ensureElement();
this._bindFunctions();
this.initialize.apply(this, arguments);
};
Object.assign(SimpleBlock.prototype, require('./function-bind'), require('./events'), require('./renderable'), require('./block-store'), {
focus : function() {},
valid : function() { return true; },
className: 'st-block',
block_template: _.template(
"<div class='st-block__inner'><%= editor_html %></div>"
),
attributes: function() {
return {
'id': this.blockID,
'data-type': this.type,
'data-instance': this.instanceID
};
},
title: function() {
return utils.titleize(this.type.replace(/[\W_]/g, ' '));
},
blockCSSClass: function() {
this.blockCSSClass = utils.toSlug(this.type);
return this.blockCSSClass;
},
type: '',
class: function() {
return utils.classify(this.type);
},
editorHTML: '',
initialize: function() {},
onBlockRender: function(){},
beforeBlockRender: function(){},
_setBlockInner : function() {
var editor_html = _.result(this, 'editorHTML');
this.$el.append(
this.block_template({ editor_html: editor_html })
);
this.$inner = this.$el.find('.st-block__inner');
this.$inner.bind('click mouseover', function(e){ e.stopPropagation(); });
},
render: function() {
this.beforeBlockRender();
this._setBlockInner();
this._blockPrepare();
return this;
},
_blockPrepare : function() {
this._initUI();
this._initMessages();
this.checkAndLoadData();
this.$el.addClass('st-item-ready');
this.on("onRender", this.onBlockRender);
this.save();
},
_withUIComponent: function(component, className, callback) {
this.$ui.append(component.render().$el);
if (className && callback) {
this.$ui.on('click', className, callback);
}
},
_initUI : function() {
var ui_element = $("<div>", { 'class': 'st-block__ui' });
this.$inner.append(ui_element);
this.$ui = ui_element;
this._initUIComponents();
},
_initMessages: function() {
var msgs_element = $("<div>", { 'class': 'st-block__messages' });
this.$inner.prepend(msgs_element);
this.$messages = msgs_element;
},
addMessage: function(msg, additionalClass) {
var $msg = $("<span>", { html: msg, class: "st-msg " + additionalClass });
this.$messages.append($msg)
.addClass('st-block__messages--is-visible');
return $msg;
},
resetMessages: function() {
this.$messages.html('')
.removeClass('st-block__messages--is-visible');
},
_initUIComponents: function() {
this._withUIComponent(new BlockReorder(this.$el));
}
});
SimpleBlock.fn = SimpleBlock.prototype;
// Allow our Block to be extended.
SimpleBlock.extend = require('./helpers/extend');
module.exports = SimpleBlock;
|
exports.init = function(noderplate) {
var model = {},
mongoose = noderplate.imports.mongoose;
mongoose.connect('mongodb://localhost/test', function(err) {
if (err) { throw err; }
});
model.User = require('./model-user').init(noderplate);
return model;
};
|
import chai from 'chai'
import { CommentAssembler, ElementAssembler } from '../lib'
const { assert } = chai
const { Comment, XMLSerializer, document } = window
const serializer = new XMLSerializer
class TestElement extends ElementAssembler {
static get localName() {
return 'element'
}
}
describe('CommentAssembler', () => {
describe('new CommentAssembler', () => {
const test = new CommentAssembler
const node = test.node
it('node', () => {
assert.instanceOf(node, Comment)
})
it('node.data', () => {
assert.equal(node.data, '')
})
it('serializeToString(node)', () => {
assert.equal(serializer.serializeToString(node), '<!---->')
})
})
describe('new CommentAssembler({})', () => {
const test = new CommentAssembler({})
const node = test.node
it('node', () => {
assert.instanceOf(node, Comment)
})
it('node.data', () => {
assert.equal(node.data, '')
})
it('serializeToString(node)', () => {
assert.equal(serializer.serializeToString(node), '<!---->')
})
})
describe('new CommentAssembler(new String)', () => {
const test = new CommentAssembler('foobar')
const node = test.node
it('node.data', () => {
assert.equal(node.data, 'foobar')
})
it('serializeToString(node)', () => {
assert.equal(serializer.serializeToString(node), '<!--foobar-->')
})
})
describe('new CommentAssembler({ data })', () => {
const test = new CommentAssembler({ data : 'foobar' })
const node = test.node
it('node.data', () => {
assert.equal(node.data, 'foobar')
})
it('serializeToString(node)', () => {
assert.equal(serializer.serializeToString(node), '<!--foobar-->')
})
})
describe('new CommentAssembler({ node })', () => {
const node = document.createComment('foobar')
const test = new CommentAssembler({ node })
it('nodes equal', () => {
assert.equal(test.node, node)
})
})
describe('data = new String', () => {
const test = new CommentAssembler
const node = test.node
test.data = 'foobar'
it('node.data', () => {
assert.equal(node.data, 'foobar')
})
it('data', () => {
assert.equal(test.data, 'foobar')
})
it('serializeToString(node)', () => {
assert.equal(serializer.serializeToString(node), '<!--foobar-->')
})
})
describe('new CommentAssembler({ data, parentNode })', () => {
const parent = new TestElement
const test = new CommentAssembler({
data : 'foobar',
parentNode : parent
})
const node = test.node
it('node.parentNode', () => {
assert.equal(node.parentNode, parent.node)
})
it('parentNode', () => {
assert.equal(test.parentNode, parent)
})
it('serializeToString(element.node)', () => {
const xml = serializer.serializeToString(parent.node)
assert.equal(xml, '<element><!--foobar--></element>')
})
})
})
|
#!/usr/bin/env node
var util = require('util');
var PORT = 3420;
var logger = {
info: console.log,
error: console.log
};
var glh = {
port: PORT,
host: '0.0.0.0',
logger: logger
};
// With an additional callback function the "gitlabhook.conf" will be ignored.
var server = require('gitlabhook')(glh);
server.listen();
if (server.server) logger.info('webhook server listen (%d)\n', PORT);
/*
http://localhost:3420
*/
|
({
'loaded': "Template ".cyan+"'{path}'".yellow+" loaded".cyan,
'compileError': "Template load error ".red+"'{path}'".yellow,
'unknowEngine': "Unknow template engine".red+" '{path}'".yellow
})
|
// Javascript Document
(() => {
return {
data(){
return {
root: appui.plugins['appui-dashboard'] + '/test/',
widgets: this.source.widgets
}
},
methods: {
sortWidgets(){
let dab = this.getRef('dashboard');
if ( dab ){
this.post(this.root + '/actions/' + this.source.id + '/order', {
order: dab.currentOrder
}, d => {
if ( d.success ){
appui.success(bbn._('Sorting saved'));
}
else if (d.deleted ){
appui.success(bbn._('Sorting reset successfull'));
}
else{
appui.error();
}
})
}
}
}
};
})();
|
version https://git-lfs.github.com/spec/v1
oid sha256:5da91cd805917aa5a2cd319858eed954f7f6c615d90753a1a108b657d2bd4ec9
size 5871
|
/**
* Created by grahamclapham on 26/09/2014.
*/
DataCleanerTradeViz = function(data){
var _cleanData = data;
for(var i=0; i<_cleanData.DATES.length; i++){
var __date = TradeVizD3.stringToDate(_cleanData.DATES[i]);
_cleanData.DATES[i]= __date;
_cleanData.VOLUME[i]= {volume:_cleanData.VOLUME[i], date:__date};
_cleanData.TICKS[i]= {volume:_cleanData.TICKS[i], date:__date};
_cleanData.PRICE[i]= {volume:_cleanData.PRICE[i], date:__date};
}
_cleanData.DATES = mergeSort(_cleanData.DATES)
_cleanData.VOLUME = mergeSortObj(_cleanData.VOLUME, 'date')
_cleanData.TICKS = mergeSortObj(_cleanData.TICKS, 'date')
_cleanData.PRICE = mergeSortObj(_cleanData.PRICE, 'date')
return _cleanData;
}
|
const UI = require('../../ui').UI;
const CLIOptions = require('../../cli-options').CLIOptions;
const Container = require('aurelia-dependency-injection').Container;
const Project = require('../../project').Project;
const string = require('../../string');
const os = require('os');
module.exports = class {
static inject() { return [Container, UI, CLIOptions, Project]; }
constructor(container, ui, options, project) {
this.container = container;
this.ui = ui;
this.options = options;
this.project = project;
}
execute(args) {
if (args.length < 1) {
return this.displayGeneratorInfo('No Generator Specified. Available Generators:');
}
this.project.installTranspiler();
return this.project.resolveGenerator(args[0]).then(generatorPath => {
Object.assign(this.options, {
generatorPath: generatorPath,
args: args.slice(1)
});
if (generatorPath) {
let generator = this.project.getExport(require(generatorPath));
if (generator.inject) {
generator = this.container.get(generator);
generator = generator.execute.bind(generator);
}
return generator();
}
return this.displayGeneratorInfo(`Invalid Generator: ${args[0]}. Available Generators:`);
});
}
displayGeneratorInfo(message) {
return this.ui.displayLogo()
.then(() => this.ui.log(message + os.EOL))
.then(() => this.project.getGeneratorMetadata())
.then(metadata => string.buildFromMetadata(metadata, this.ui.getWidth()))
.then(str => this.ui.log(str));
}
};
|
/*
* Copyright (c) 2017. MIT-license for Jari Van Melckebeke
* Note that there was a lot of educational work in this project,
* this project was (or is) used for an assignment from Realdolmen in Belgium.
* Please just don't abuse my work
*/
JQVMap.prototype.resize = function () {
var curBaseScale = this.baseScale;
if (this.width / this.height > this.defaultWidth / this.defaultHeight) {
this.baseScale = this.height / this.defaultHeight;
this.baseTransX = Math.abs(this.width - this.defaultWidth * this.baseScale) / (2 * this.baseScale);
} else {
this.baseScale = this.width / this.defaultWidth;
this.baseTransY = Math.abs(this.height - this.defaultHeight * this.baseScale) / (2 * this.baseScale);
}
this.scale *= this.baseScale / curBaseScale;
this.transX *= this.baseScale / curBaseScale;
this.transY *= this.baseScale / curBaseScale;
};
|
/*
* The ActionPanels are used to display a list of actions. This class builds
* both the horizontal and vertical action panels used throughout the system.
* Each link in the links array can either be an action map or an action
* code. If the link is an action map the map should have the following
* link attributes:
*
* name: Required, Display Name for the link.
* (!)action: Action string passed to the Navigator.
* (!)handler: Function that will be called on click.
* id: Id of the generated link.
* attributes: Additional attributes to add to link element.
*
* (!)Either the action or handler is required. Never both though.
*/
function ActionPanel(links, options) {
if (options == null) { options = {}; }
this.links = this._buildLinks(links);
this.align = options.align || 'vertical';
}
ActionPanel.prototype = {
/*
* The buildPanel() function first creates all of the anchor elements that
* will be added to the panel, then calls the appropriate build method for
* the alignment.
*
* If the buildPanel() method is called after the page is loaded (and
* outside of an init() function) then the Loader.anchor() function will
* need to be called to link up the actions. Failure to do this will result
* in derp.
*/
buildPanel: function() {
if (this.getActionCount() == 0) {
return $('<div>');
}
var elements = [];
$.each(this.links, function() {
var anchor = $('<a>').append(this.name).disableTextSelect();
var hash = {anchor:anchor};
if (this.id) {
anchor.attr('id',this.id);
}
if (this.attributes) {
$.each(this.attributes, function(key, value) {
anchor.attr(key, value);
});
}
if (this.action) {
anchor.attr('href',this.action);
}
else if (this.handler) {
anchor.click(this.handler);
hash.handler = this.handler;
}
elements.push(hash);
});
return (this.align == 'horizontal') ?
this._buildHorizontalPanel(elements) :
this._buildVerticalPanel(elements);
},
/*
* This function returns the number of valid actions on the panel. It's
* useful when determining if the action panel is empty.
*/
getActionCount: function() {
return this.links.length;
},
/*
* The buildLinks() function is called when the ActionPanel is initialized in
* order to compile the list of available links.
*/
_buildLinks: function(links) {
var rawList = [];
var list = [];
$.each(links, function() {
if ($.isString(this)) {
rawList.push(ExitAction.buildActionMap(Data.getAction(this)));
}
else if (this.code) {
rawList.push(ExitAction.buildActionMap(this));
}
else if (this.name && (this.action || this.handler)) {
rawList.push(this);
}
else {
var error = "Bad Link, cannot add to action panel.";
Logger.error(error, this);
throw error
}
});
$.each(rawList, function() {
if (Resolver.meetsRequirements(this)) {
list.push(this);
}
});
return list;
},
/*
* The horizontal panels are simpler then the vertical. They just need a div
* container which all of the anchors are added to. CSS takes care of the
* rest.
*/
_buildHorizontalPanel: function(elements) {
var list = $('<div>').
addClass('actionPanel').
disableTextSelect();
if (elements.length > 0) {
elements[0].anchor.addClass('first');
}
$.each(elements, function() {
var anchor = this.anchor;
anchor.addClass('button');
list.append(anchor);
});
return list;
},
/*
* The vertical panels are more complicated because in order for the panels
* to style correctly the anchors need to be wrapped in divs, which are
* added to list elements which is added to the list.
*/
_buildVerticalPanel: function(elements) {
var first = true;
var list = $('<ul>');
list.addClass('actionPanel');
$.each(elements, function() {
var anchor = this.anchor;
var node = $('<div>').
append(anchor).
addClass('button').
disableTextSelect();
if (this.handler) {
node.click(this.handler);
}
if (first) {
node.addClass('first');
first = false;
}
list.append($('<li>').append(node));
});
return list;
}
};
|
"use strict";
let
_ = require('lodash'),
chai = require('chai')
,expect = chai.expect
;
let
jsodvcs = require("../../")
;
exports.spec = function(){
let Repository = jsodvcs.Repository;
describe('Repository#push()', function() {
context("when pushing all branches, some of which are ahead, behind and up-to-date", function(){
let origin = new jsodvcs.Repository();
origin
.add("foo/int", 42)
.commit()
.branch("to-be-rejected")
.add("four", 4)
.commit()
.checkout("master")
.branch("to-be-behind")
.add("one", 1)
.commit()
.checkout("master")
.branch("to-be-up2date")
.add("seven", 7)
.commit()
.checkout("master")
;
let local = origin.clone();
origin
.checkout("to-be-rejected")
.add("four", 44)
.commit()
.checkout("to-be-behind")
.add("one", 11)
.commit()
.checkout("master")
;
local
.branch("to-be-new")
.add("nine", 9)
.commit()
.checkout("to-be-rejected")
.add("four", 444)
.commit()
.checkout("master")
.add("foo/int", 84)
.commit()
;
let out = {};
let ret = local.push(origin, {out:out});
it('should return the repository', function() {
expect(ret).to.equal(local);
});
it('should have pushed branches that were new', function() {
expect(out.pushedBranches).to.include('refs/heads/to-be-new');
expect(origin.resolve_ref('refs/heads/to-be-new')).to.equal(local.resolve_ref('refs/heads/to-be-new'));
});
it('should have pushed branches that were ahead', function() {
expect(out.pushedBranches).to.include('refs/heads/master');
expect(origin.resolve_ref('refs/heads/master')).to.equal(local.resolve_ref('refs/heads/master'));
});
it('should have rejected branches that were behind (no local changes)', function() {
expect(out.rejectedBranches).to.include('refs/heads/to-be-behind');
expect(origin.resolve_ref('refs/heads/to-be-behind')).to.not.equal(local.resolve_ref('refs/heads/to-be-behind'));
});
it('should have rejected branches that were behind (local changes)', function() {
expect(out.rejectedBranches).to.include('refs/heads/to-be-rejected');
expect(origin.resolve_ref('refs/heads/to-be-rejected')).to.not.equal(local.resolve_ref('refs/heads/to-be-rejected'));
});
it('should have ignored branches that were up to date', function() {
expect(out.upToDateBranches).to.include('refs/heads/to-be-up2date');
expect(origin.resolve_ref('refs/heads/to-be-up2date')).to.equal(local.resolve_ref('refs/heads/to-be-up2date'));
});
it('should have checked out remote as it was on a pushed branch', function() {
expect(out.didRemoteCheckout).to.be.true;
});
});
context("when pushing to a non-repository", function(){
let repoA = new jsodvcs.Repository();
repoA
.add("foo/int", 42)
.add("foo/string", "foobar")
.add("foo/obj", {a:'a'})
.commit();
it('should throw a type error', function() {
expect(function(){repoA.push({})}).to.throw(TypeError);
});
});
});
};
|
/**
* Given a list of message ids, this function will return their
* corresponding message.
*
* @param connection the jdbc connection
* @param messageIds the message ids
* @returns {}
*/
function aggregateMessages(connection, messageIds) {
const startTime = System.currentTimeMillis();
print(' aggregateMessages() - started');
const messageIdsStr = messageIds.join(',');
const query = sqls['get-messages.prepared.sql'].replace('?', messageIdsStr);
const stmt = connection.createStatement();
const rs = stmt.executeQuery(query);
const messages = {};
while (rs.next()) {
messages[rs.getInt('ID')] = rs.getString('_Message');
}
stmt.close();
const durationTime = System.currentTimeMillis() - startTime;
print(" aggregateMessages() - completed in ${durationTime} ms");
return messages;
}
|
// Generated by CoffeeScript 1.4.0
(function() {
var Formattable, Mixin,
__slice = [].slice,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Mixin = require('./mixin');
Formattable = function() {
var ConcretFormattable, classname, properties;
classname = arguments[0], properties = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
return ConcretFormattable = (function(_super) {
__extends(ConcretFormattable, _super);
function ConcretFormattable() {
return ConcretFormattable.__super__.constructor.apply(this, arguments);
}
ConcretFormattable.prototype.toString = function() {
var formattedProperties, p;
if (properties.length === 0) {
return "[" + classname + "]";
} else {
formattedProperties = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = properties.length; _i < _len; _i++) {
p = properties[_i];
_results.push("" + p + "=" + this[p]);
}
return _results;
}).call(this);
return "[" + classname + "(" + (formattedProperties.join(', ')) + ")]";
}
};
ConcretFormattable.prototype.classname = function() {
return classname;
};
return ConcretFormattable;
})(Mixin);
};
module.exports = Formattable;
}).call(this);
|
/*The code below has been written using exprestify, a module by Ajith N N , you can find the module here:https://github.com/ajithnn/exprestify
The code below is going to used to send files to a server and saving them there.*/
var rest = require('exprestify') //Module required
/*The following code defines where will the file be saved,how will it be named etc */
var multiopt = {
FilePath: "./images/", //File is going to be saved at a folder called 'images'
PostType: "file", //Mulitpart post
Rename: function (fieldname, filename) {
return fieldname; //Field name is what you add to the file,you then control how the file will be saved in the folder
}
}
opt = {
extended: false
}
var options = {
contentType: "json",
config: opt
}
/*Cross origin resource sharing*/
var header ={
"Access-Control-Allow-Origin":"http://localhost:4000", //It can be restricted to any other domains by replacing the link and open for all domains, using *
"Access-Control-Allow-Methods":"GET,PUT,POST,DELETE",
"Access-Control-Allow-Headers":"Content-Type"
};
rest.setHeaders(header);
rest.multipost('/pagemulti', function (err, data) { //File will be posted at servername/pagemulti
if (!err) {
console.log(data); //You will be able to see whether the data is posted correctly.
} else {
console.log(err);
}
}, multiopt)
rest.getfile('/images', function (err, query) {
if (!err) {
if (query.value) {
return "./images/" + query.value;
} else {
return "";
}
} else {
console.log(err);
return err;
}
})
/*The following will be used for telling the processor to do something it will have both post and get functionalities */
var datafromApp = "none";
rest.get('/command', function (err) {
if (!err) {
console.log("Ret: " + datafromApp);
return datafromApp;
} else {
console.log(err);
return err;
}
});
rest.post('/command', function (err, data) {
if (!err) {
datafromApp = data.value;
console.log("Ret: "+data.value + "success");
return datafromApp;
} else {
console.log(err);
return err;
}
}, options);
/*The following will be used to receive an acknowlegement from the server when an activity is over. This will just need a post and get functionality */
var ackflag = "00";
var ackstatus = "nostatus";
rest.post('/ack', function (err, data) {
if (!err) {
ackstatus = data.value;
console.log("Ret: "+ackstatus);
return ackstatus;
} else {
return err;
}
}, options);
rest.get('/ack', function (err) {
if (!err) {
if (ackstatus == "success") {
ackflag = "1"; //success
}
else if (ackstatus == "failed") {
ackflag = "0"; //No success
}
else{
ackflag = "00";//Unexpected case
}
return ackflag;
console.log("Ret: "+ackstatus);
} else {
console.log(err);
return err;
}
});
rest.listen(3000, function () { //Running the server
console.log("Listening on port 0.0.0.0:%s", rest.port)
})
|
import firebase from 'firebase'
export const mustLoggedIn = (store) => (nextState, replace) => {
if (!store.getState().auth.user) {
console.log('must login!', nextState)
replace('/login')
}
}
export const mustLoggedOut = (store) => (nextState, replace) => {
console.log('checking must logout', firebase.auth().currentUser)
if (store.getState().auth.user) {
console.log('must logout!', nextState)
replace('/timeline')
}
}
|
'use strict';
// This file supports both iOS and Android
// Stop bluebird going nuts because it can't find "self"
if (typeof self === 'undefined') {
global.self = global;
}
var RNFSManager = require('react-native').NativeModules.RNFileManager;
var NativeAppEventEmitter = require('react-native').NativeAppEventEmitter; // iOS
var DeviceEventEmitter = require('react-native').DeviceEventEmitter; // Android
var Promise = require('bluebird');
var base64 = require('base-64');
var utf8 = require('utf8');
var _readDir = Promise.promisify(RNFSManager.readDir);
var _stat = Promise.promisify(RNFSManager.stat);
var _readFile = Promise.promisify(RNFSManager.readFile);
var _writeFile = Promise.promisify(RNFSManager.writeFile);
var _unlink = Promise.promisify(RNFSManager.unlink);
var _mkdir = Promise.promisify(RNFSManager.mkdir);
var _downloadFile = Promise.promisify(RNFSManager.downloadFile);
var _pathForBundle = Promise.promisify(RNFSManager.pathForBundle);
var _exists = Promise.promisify(RNFSManager.exists);
var _folderExists = Promise.promisify(RNFSManager.folderExists);
var _rename = Promise.promisify(RNFSManager.rename);
var _moveFile = Promise.promisify(RNFSManager.moveFile);
var convertError = (err) => {
if (err.isOperational && err.cause) {
err = err.cause;
}
var error = new Error(err.description || err.message);
error.code = err.code;
throw error;
};
var NSFileTypeRegular = RNFSManager.NSFileTypeRegular;
var NSFileTypeDirectory = RNFSManager.NSFileTypeDirectory;
var jobId = 0;
var getJobId = () => {
jobId += 1;
return jobId;
};
var RNFS = {
readDir(dirpath) {
return _readDir(dirpath)
.then(files => {
return files.map(file => ({
name: file.name,
path: file.path,
size: file.size,
isFile: () => file.type === NSFileTypeRegular,
isDirectory: () => file.type === NSFileTypeDirectory,
}));
})
.catch(convertError);
},
// Node style version (lowercase d). Returns just the names
readdir(dirpath) {
return RNFS.readDir(dirpath)
.then(files => {
return files.map(file => file.name);
});
},
stat(filepath) {
return _stat(filepath)
.then((result) => {
return {
'ctime': new Date(result.ctime*1000),
'mtime': new Date(result.mtime*1000),
'size': result.size,
'mode': result.mode,
isFile: () => result.type === NSFileTypeRegular,
isDirectory: () => result.type === NSFileTypeDirectory,
};
})
.catch(convertError);
},
readFile(filepath, encoding) {
if (!encoding) encoding = 'utf8';
return _readFile(filepath)
.then((b64) => {
var contents;
if (encoding === 'utf8') {
contents = utf8.decode(base64.decode(b64));
} else if (encoding === 'ascii') {
contents = base64.decode(b64);
} else if (encoding === 'base64') {
contents = b64;
} else {
throw new Error('Invalid encoding type "' + encoding + '"');
}
return contents;
})
.catch(convertError);
},
writeFile(filepath, contents, encoding, options) {
var b64;
if (!encoding) encoding = 'utf8';
if (encoding === 'utf8') {
b64 = base64.encode(utf8.encode(contents));
} else if (encoding === 'ascii') {
b64 = base64.encode(contents);
} else if (encoding === 'base64') {
b64 = contents;
} else {
throw new Error('Invalid encoding type "' + encoding + '"');
}
return _writeFile(filepath, b64, options)
.catch(convertError);
},
pathForBundle(bundleName) {
return _pathForBundle(bundleName);
},
unlink(filepath) {
return _unlink(filepath)
.catch(convertError);
},
mkdir(filepath, excludeFromBackup) {
excludeFromBackup = !!excludeFromBackup;
return _mkdir(filepath, excludeFromBackup)
.catch(convertError);
},
downloadFile(fromUrl, toFile, begin, progress) {
var jobId = getJobId();
var subscriptionIos, subscriptionAndroid;
if (!begin) begin = (info) => {
// console.log('Download begun:', info);
};
if (begin) {
// Two different styles of subscribing to events for different platforms, hmmm....
if (NativeAppEventEmitter.addListener)
subscriptionIos = NativeAppEventEmitter.addListener('DownloadBegin-' + jobId, begin);
if (DeviceEventEmitter.addListener)
subscriptionAndroid = DeviceEventEmitter.addListener('DownloadBegin-' + jobId, begin);
}
if (progress) {
if (NativeAppEventEmitter.addListener)
subscriptionIos = NativeAppEventEmitter.addListener('DownloadProgress-' + jobId, progress);
if (DeviceEventEmitter.addListener)
subscriptionAndroid = DeviceEventEmitter.addListener('DownloadProgress-' + jobId, progress);
}
return _downloadFile(fromUrl, toFile, jobId)
.then(res => {
if (subscriptionIos) subscriptionIos.remove();
if (subscriptionAndroid) subscriptionAndroid.remove();
return res;
})
.catch(convertError);
},
stopDownload(jobId) {
RNFSManager.stopDownload(jobId);
},
fileExistsAtPath(filepath) {
return _exists(filepath)
.catch(convertError);
},
folderExistsAtPath(path) {
return _folderExists(path)
.catch(convertError);
},
renameFile(filepath, newName) {
return _rename(filepath, newName)
.catch(convertError);
},
moveFile(filepath, newPath) {
return _moveFile(filepath, newPath)
.catch(convertError);
},
MainBundlePath: RNFSManager.MainBundlePath,
CachesDirectoryPath: RNFSManager.NSCachesDirectoryPath,
DocumentDirectoryPath: RNFSManager.NSDocumentDirectoryPath,
ApplicationSupportDirectoryPath: RNFSManager.NSApplicationSupportDirectoryPath
};
module.exports = RNFS;
|
var request = require('supertest'); // https://github.com/visionmedia/supertest
describe('oauthproxy server', function() {
var server;
before(function (done) {
// Add any setup routines here before calling done
// Create an instance of our server
server = require('./server.js').create();
done();
});
describe('/Connect', function() {
it('Should return a new client connection token', function(done) {
var post_data = "";
request(server)
.post('/Connect')
.type('form')
.send({a: 'aa', b: 'bb'})
.expect(200)
.end(function(err,res) {
if (err) throw err;
var token = res.text;
describe('/RequestToken', function() {
// TODO decide on delimeters - like query string?
it('Should return a new client connection token and a request token', function(done) {
var post_data = "";
request(server)
.post('/RequestToken')
.type('form')
.send({token: token, b: 'bb'})
.expect(501, done); // TODO write this!
});
});
done();
});
});
});
describe('/AccessToken', function() {
// TODO decide on delimeters - like query string?
it('Should return a new client connection token and an access token', function(done) {
var post_data = "";
request(server)
.post('/AccessToken')
.send(post_data)
.expect(501, done); // TODO write this!
});
});
});
|
System.register([], function (exports, module) {
'use strict';
return {
execute: function () {
function getStringA() {
return 'A';
}
console.log(getStringA());
console.log(false);
console.log(true);
function getStringD() {
return 'D';
}
console.log(getStringD());
}
};
});
|
/*
* Copyright (C) 2015 Thalassemia Interpreter Software
*
* This file is part of the Thalassemia Interpreter Software project.
*
* Unauthorized copying of this file, via any medium is strictly prohibited
*
* Thalassemia Interpreter Software project can not be copied and/or distributed without the express
* permission of National Science and Technology Development Agency,111 Thailand Science Park (TSP),
* Phahonyothin Road, Khlong Nueng, Khlong Luang, Pathum Thani 12120, Thailand
*/
'use strict';
//Calendars service used to communicate Calendars REST endpoints
angular.module('calendars').factory('Calendars', ['$resource',
function($resource) {
return $resource('calendars/:calendarId', { calendarId: '@_id'
}, {
update: {
method: 'PUT'
}
});
}
]);
|
'use strict';
import Cookies from 'js-cookie';
/**
* Class for storing/maintaining locale cookies
*/
export default class CookieStorage {
/**
* @constructor
* @param {String} defaultLanguage
*/
constructor(defaultLanguage) {
let cookie = Cookies.get('locale');
if (!cookie && arguments.length > 0) {
this.setCookie(defaultLanguage);
}
}
/**
* Returns cookie locale (if it exists)
* @returns {String|null}
*/
getCookie() {
let cookie = Cookies.get('locale');
if (cookie) {
return cookie;
}
}
/**
* Set the language locale via Cookies
* @param {String} language
*/
setCookie(language) {
Cookies.set('locale', language);
}
/**
* Remove the existing language cookie
*/
deleteCookie() {
let cookie = Cookies.get('locale');
if (cookie) {
Cookies.remove('locale');
}
}
}
|
/* eslint-disable no-console */
'use strict';
var convert = require('../src/convert');
convert({
host: process.env.TUMBLR_HOST || 'vaffelfest.tumblr.com',
apiKey: process.env.TUMBLR_API_KEY
}, function onConverted(err, posts) {
if (err) {
throw err;
}
console.log('===[ As PM node ]==========');
console.log(posts);
console.log('===========================');
});
convert({
host: process.env.TUMBLR_HOST || 'vaffelfest.tumblr.com',
apiKey: process.env.TUMBLR_API_KEY,
json: true
}, function onConverted(err, posts) {
if (err) {
throw err;
}
console.log('===[ As JSON ]==========');
console.log(posts);
console.log('===========================');
});
|
export const bounce = {
friction: 0, // Friction to use in the contact of these two materials.
restitution: 1, // Restitution (i.e. how bouncy it is!) to use in the contact of these two materials.
stiffness: 1e7, // Stiffness of the resulting ContactEquation that this ContactMaterial generate.
relaxation: 3, // Relaxation of the resulting ContactEquation that this ContactMaterial generate.
frictionStiffness: 1e7, // Stiffness of the resulting FrictionEquation that this ContactMaterial generate.
frictionRelaxation: 0, // Relaxation of the resulting FrictionEquation that this ContactMaterial generate.
surfaceVelocity: 0, // Will add surface velocity to this material. If bodyA rests on top if bodyB, and the surface velocity is positive, bodyA will slide to the right.
};
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2019 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* The Texture Load Event.
*
* This event is dispatched by the Texture Manager when a texture has finished loading on it.
* This only happens for base64 encoded textures. All other texture types are loaded via the Loader Plugin.
*
* Listen to this event from within a Scene using: `this.textures.on('onload', listener)`.
*
* This event is dispatched after the [ADD]{@linkcode Phaser.Textures.Events#event:ADD} event.
*
* @event Phaser.Textures.Events#LOAD
* @since 3.0.0
*
* @param {string} key - The key of the Texture that was loaded by the Texture Manager.
* @param {Phaser.Textures.Texture} texture - A reference to the Texture that was loaded by the Texture Manager.
*/
module.exports = 'onload';
|
"use strict";
exports.__esModule = true;
exports["default"] = void 0;
var createGetFormAsyncErrors = function createGetFormAsyncErrors(_ref) {
var getIn = _ref.getIn;
return function (form, getFormState) {
return function (state) {
var nonNullGetFormState = getFormState || function (state) {
return getIn(state, 'form');
};
return getIn(nonNullGetFormState(state), form + ".asyncErrors");
};
};
};
var _default = createGetFormAsyncErrors;
exports["default"] = _default;
|
'use strict'
let crypto = require('crypto')
let generateId = function () {
return crypto.createHash('md5')
.update((new Date()).getTime().toString(), 'utf8')
.digest('hex')
}
class SSEClient {
constructor (req, res) {
this.req = req
this.res = res
let self = this
res.on('close', function () {
self.emit('close')
})
}
initialize () {
this.req.socket.setNoDelay(true)
let origin = this.req.headers.referer !== undefined ? require('url').parse(this.req.headers.referer) : '*'
origin = typeof origin === 'object' ? origin.protocol + '\/\/' + origin.host : origin
this.res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'Access-Control-Allow-Origin': process.env.ALLOW_ORIGIN || origin
})
this.res.write(':ok\n\n')
}
send (payload) {
if (arguments.length === 0) return
// Construct the payload
if (typeof payload !== 'object') {
payload = {
data: payload
}
}
// If the data is a JSON object, convert to string
if (typeof payload.data === 'object') {
payload.data = JSON.stringify(payload.data)
}
// Make sure there is an ID (generate if necessary)
payload.id = payload.id || generateId()
// If an event is specified, write it.
if (payload.event) {
this.res.write('event: ' + payload.event + '\n')
}
// If a retry is specified, write it.
if (payload.retry) {
this.res.write('retry: ' + payload.retry + '\n')
}
// Write the ID
if (payload.id) {
this.res.write('id: ' + payload.id + '\n')
}
// Process each line of the data
let me = this
payload.data.replace(/(\r\n|\r|\n)/g, '\n').split(/\n/).forEach(function (line, index, a) {
me.res.write('data: ' + line + '\n' + (index === a.length - 1 ? '\n' : ''))
})
}
close () {
this.res.end()
}
}
// Inherit event emitter
Object.setPrototypeOf(SSEClient.prototype, require('events').EventEmitter.prototype)
module.exports = SSEClient
|
describe('countriesService', function() {
var httpBackend, service;
beforeEach(module('techassessement.pages.countries'));
beforeEach(inject(function($injector, countriesService) {
httpBackend = $injector.get('$httpBackend');
service = countriesService;
}));
afterEach(function() {
// Skipping the unnecessary $digest cycle because of the false param
httpBackend.verifyNoOutstandingExpectation(false);
httpBackend.verifyNoOutstandingRequest(false);
});
it('should be defined', function() {
expect(service).toBeDefined();
});
describe('selectedCountries()', function() {
it('send nothing', function() {
httpBackend.expect('POST','selectedCountries', { isoCodes: [] }).respond(400);
service
.selectedCountries([])
.catch(function(response) {
expect(response.status).toEqual(400);
});
httpBackend.flush();
});
it('send only one country', function() {
httpBackend.expect('POST','selectedCountries', { isoCodes: [ 'HUN' ] }).respond(200);
service
.selectedCountries([
{ name: 'Hungary', isoCode: 'HUN' }
])
.then(function(response) {
expect(response.status).toEqual(200);
});
httpBackend.flush();
});
it('send two countries', function() {
httpBackend.expect('POST','selectedCountries', { isoCodes: [ 'CHE', 'HUN' ] }).respond(200);
service
.selectedCountries([
{ name: 'Switzerland', isoCode: 'CHE' },
{ name: 'Hungary', isoCode: 'HUN' }
])
.then(function(response) {
expect(response.status).toEqual(200);
});
httpBackend.flush();
});
});
});
|
var Alert;
(function (Alert) {
/*
export function message(message: string, target) {
return build_notification( message, "", target );
}
*/
function success(message, target) {
return build_notification(message, "success", target);
}
Alert.success = success;
function info(message, target) {
return build_notification(message, "info", target);
}
Alert.info = info;
function warning(message, target) {
return build_notification(message, "warning", target);
}
Alert.warning = warning;
function danger(message, target) {
return build_notification(message, "danger", target);
}
Alert.danger = danger;
function build_notification(content, type, target) {
type = type || "warning";
var notification = document.createElement('div');
notification.className = "alert notify-" + type;
var message = document.createElement('span');
message.className = "notify-message";
if (typeof (content) == "string") {
message.innerHTML = content;
} else if (typeof (content) == "object" && content.nodeName) {
message.insertBefore(content, null);
}
notification.insertBefore(message, null);
if (target)
target.insertBefore(notification, null);
return notification;
}
})(Alert || (Alert = {}));
|
'use strict'
var Endpoint = require('./Endpoint'),
cheerio = require('cheerio'),
Error = require('../Responses/Error'),
responseCodes = require('../Responses/response_codes.json'),
errorMessages = require('../Responses/error_messages.json')
module.exports = class RunesEndpoint extends Endpoint {
Path() {
return '/summoner/rune/'
}
ErrorCheck($) {
if (!$) return false
if ($('.ErrorMessage').length) {
return new Error(errorMessages.NO_RESULTS, responseCodes.NO_RESULTS)
}
return false
}
Parse($$) {
var data = [],
runeTypes = ['mark','seal','glyph','quintessence'],
runeIndex = -1
$$('.RunePageWrap').each((index, item) => {
var $ = cheerio.load(item),
runeContainer = {},
runeType = {}
runeContainer.title = this.Strip($$('.RunePageList .Button').eq(index).find('.PageName').text())
$('.RunePageSummaryList .Title, .RunePageSummaryList .Item').each((index1, item1) => {
var title = runeTypes[runeIndex]
if (item1.attribs.class.indexOf('Title') > -1) {
runeIndex++
runeContainer[runeTypes[runeIndex]] = []
return
}
var $ = cheerio.load(item1),
rune = {}
rune.image = this.Strip($('.Image img').attr('src'))
rune.name = this.Strip($('.Image img').attr('alt'))
rune.effect = this.Strip($('.Name').text())
rune.count = parseInt($('.Count').text().replace('x',''))
runeContainer[title].push(rune)
})
runeIndex = -1
data.push(runeContainer)
})
var hasRunes = false
for (var runes in data) {
var rune = data[runes]
if (rune.mark.length || rune.seal.length || rune.glyph.length || rune.quintessence.length) {
hasRunes = true
break
}
}
return hasRunes ? data : new Error(errorMessages.NO_RESULTS, responseCodes.NO_RESULTS)
}
}
|
import React from 'react'
import { View, Text, StyleSheet } from 'react-native'
class AboutUs extends React.Component {
render() {
const { container } = styles
return (
<View style={container}>
<Text>About us</Text>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
}
})
export { AboutUs }
|
export default class Character extends Phaser.Sprite {
constructor(game, x, y, name, frame) {
name = name || 'ayeesha';
super(game, x, y, name, frame);
this.anchor.setTo(0.5, 0.5);
this.game.physics.arcade.enableBody(this);
this.body.allowGravity = false;
this.body.bounce.y = 0.2;
this.body.collideWorldBounds = true;
this.body.mass = 3;
}
}
|
angular.module('ionPress')
.directive('articleStub', function () {
return {
restrict: 'E',
templateUrl: 'views/directives/article-stub.html',
scope: {
article: '=',
wordLimit: '@'
},
require: '^articleList',
link: function postLink(scope, element, attrs, articleListDelegate) {
scope.articles = articleListDelegate.getArticles();
}
};
});
|
import React from 'react'
import PropTypes from 'prop-types'
import LoginAuth0 from './LoginAuth0'
import { graphql, gql } from 'react-apollo'
import { withRouter } from 'react-router-dom'
// import ListPage from './ListPage'
// import NewPostLink from './NewPostLink'
import GlobalNav from './GlobalNav';
const clientId = process.env.REACT_APP_AUTH0_CLIENTID
const domain = process.env.REACT_APP_AUTH0_DOMAIN
class App extends React.Component {
static propTypes = {
history: PropTypes.object
}
_isLoggedIn = () => {
return this.props.data.user
}
render () {
if (this.props.data.loading) {
return (<span className="pt-icon-standard pt-icon-exchangw"></span>)
}
if (this._isLoggedIn()) {
return this.renderLoggedIn()
} else {
return this.renderLoggedOut()
}
}
renderLoggedIn() {
return (
<div>
<GlobalNav />
<div>
<br />
<div className="pt-non-ideal-state">
<div className="pt-non-ideal-state-visual pt-non-ideal-state-icon">
<span className="pt-icon pt-icon-endorsed"></span>
</div>
<h4 className="pt-non-ideal-state-title">Welcome to Sprint, {this.props.data.user.name}</h4>
</div>
</div>
</div>
)
}
renderLoggedOut() {
return (
<div>
<div className='pv3'>
<LoginAuth0
clientId={clientId}
domain={domain}
/>
</div>
</div>
)
}
}
const userQuery = gql`
query userQuery {
user {
id,
name,
emailAddress
}
}
`
export default graphql(userQuery, { options: {fetchPolicy: 'network-only' }})(withRouter(App))
|
'use strict';
// FabricTransferRegister controller
angular.module('fabric-transfer-registers').controller('FabricTransferRegistersController', ['$scope', '$stateParams', '$location', 'Authentication', 'FabricTransferRegisters',
function($scope, $stateParams, $location, Authentication, FabricTransferRegisters) {
$scope.authentication = Authentication;
// Create new FabricTransferRegister
$scope.create = function() {
// Create new FabricTransferRegister object
var fabrictransferregister = new FabricTransferRegisters ({
transferNo: this.transferNo,
jobNo: this.jobNo,
party: this.party,
fabric: this.fabric,
count: this.count,
gsm: this.gsm,
dia: this.dia,
rolls: this.rolls,
kgs: this.kgs,
created: Date.now
});
// Redirect after save
fabrictransferregister.$save(function(response) {
$location.path('fabric-transfer-registers/' + response._id);
// Clear form fields
$scope.name = '';
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Remove existing FabricTransferRegister
$scope.remove = function(fabrictransferregister) {
if ( fabrictransferregister ) {
fabrictransferregister.$remove();
for (var i in $scope.FabricTransferRegisters) {
if ($scope.fabrictransferregisters [i] === fabrictransferregister) {
$scope.fabrictransferregisters.splice(i, 1);
}
}
} else {
$scope.fabrictransferregister.$remove(function() {
$location.path('fabric-transfer-registers');
});
}
};
// Update existing FabricTransferRegister
$scope.update = function() {
var fabrictransferregister = $scope.fabrictransferregister;
fabrictransferregister.$update(function() {
$location.path('fabric-transfer-registers/' + fabrictransferregister._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Find a list of FabricTransferRegister
$scope.find = function() {
$scope.fabrictransferregisters = FabricTransferRegisters.query();
};
// Find existing FabricTransferRegister
$scope.findOne = function() {
FabricTransferRegisters.get({
fabricTransferRegisterId: $stateParams.fabricTransferRegisterId
})
.$promise.then(function(data) {
$scope.fabrictransferregister = data;
}, function(reason) {
console.log('Failed: ' + reason);
});
};
}
]);
|
var Notifications = {
numberOfClicks: 0,
init: function() {
$('.notifications .close').live('click', function(event) {
var parent = $(this).parent();
parent.addClass('hidden');
setTimeout(function() { parent.remove(); }, 1000);
});
EventSystem.addEventListener('video_info_fetched', function(info) {
Notifications.append(info.title);
});
},
requestPermission: function() {
if (window.webkitNotifications) {
if (window.webkitNotifications.checkPermission() === 1) { // 0=OK, 1=Not Allowed, 2=Denied
try {
window.webkitNotifications.requestPermission();
} catch (e) {
// Safari 6.01 throws a TypeError when we do the
// requestPermission() call. Temp fixing by disallowing
// notifications for now.
}
}
}
},
append: function(message) {
if (window.webkitNotifications && window.webkitNotifications.checkPermission() < 2) {
Notifications._webkitAppend(message);
}
},
_webkitAppend: function(message) {
var announceFunction = function(message) {
try
{
var settings = new Settings();
var popup = window.webkitNotifications.createNotification(
'/images/logo/logo_32x32.png',
'Youtify',
message);
popup.show();
popup.onclick = function() {
window.focus();
popup.cancel();
};
setTimeout(function(){ popup.cancel(); }, settings.announceTimeout);
} catch(err) {
console.log(err.message);
}
};
if (window.webkitNotifications && window.webkitNotifications.checkPermission() === 0) {
// 0=OK, 1=Not Allowed, 2=Denied
announceFunction(message);
}
}
};
|
import React from 'react';
import PropTypes from 'prop-types';
import { withApollo } from 'react-apollo';
import LAST_REQUESTED from '../../utils/queries/LAST_REQUESTED';
import RequestBig from "./RequestBig";
class LastRequested extends React.Component {
constructor(props) {
super(props);
this.state = {
lastRequests: [],
}
}
componentWillMount() {
this.props.client.query({
query: LAST_REQUESTED,
variables: {
_id: this.props.user._id
}
})
.then(res => {
this.setState({lastRequests: res.data.lastRequests})
}
)
.catch(err => {
console.log(err);
})
}
render() {
let activeLength = 0;
this.state.lastRequests.forEach(item => {
if (item.active) {
activeLength ++;
}
});
if (activeLength > 0){
return(
<div className="ui-block">
<div className="ui-block-title">
<h6 className="title bold">
Last requests
</h6>
</div>
<div className="ui-block-content">
<ul className="single-request big">
{this.state.lastRequests.map((item, key) => {
if (item.active) {
return (
<li key={key}>
<a href={`/item/${item._id}`}>
<RequestBig item={item}/>
</a>
</li>
)
}
return null;
})}
</ul>
</div>
</div>
)
}
else {
return null
}
}
}
LastRequested.propTypes = {
user: PropTypes.object.isRequired
};
export default withApollo(LastRequested);
|
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var Registry = require('../../registry');
exports.name = 'pie';
exports.plot = function(gd) {
var Pie = Registry.getModule('pie');
var cdPie = getCdModule(gd.calcdata, Pie);
if(cdPie.length) Pie.plot(gd, cdPie);
};
exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
var hadPie = (oldFullLayout._has && oldFullLayout._has('pie'));
var hasPie = (newFullLayout._has && newFullLayout._has('pie'));
if(hadPie && !hasPie) {
oldFullLayout._pielayer.selectAll('g.trace').remove();
}
};
function getCdModule(calcdata, _module) {
var cdModule = [];
for(var i = 0; i < calcdata.length; i++) {
var cd = calcdata[i];
var trace = cd[0].trace;
if((trace._module === _module) && (trace.visible === true)) {
cdModule.push(cd);
}
}
return cdModule;
}
|
import MinContainer from './min.container';
export default MinContainer;
|
import { Huisnummers, Wegobjecten, Wegobject, Wegsegmenten, Wegsegment, Gebouwen, Gebouw,
Percelen, Perceel, Terreinobjecten, Terreinobject } from './CRAB';
import { log, error
} from './log';
const objects = { gebouwen: [], terreinen: [], wegobjecten: [], wegsegmenten: [], percelen: [] };
const Resolve = {
getList: id => x => x.list(id).then(Resolve[x.name]).catch(error),
Gebouw: x => Gebouw.get(x)
.then(({ polygon }) => objects.gebouwen.push(polygon)),
Terreinobject: x => Terreinobject.get(x)
.then(({ center, minimum, maximum }) => objects.terreinen.push({ center, minimum, maximum })),
Perceel: x => Perceel.get(x)
.then(({ center }) => objects.percelen.push(center)),
Huisnummer: x => Promise.all([Gebouwen, Terreinobjecten, Percelen]
.map(Resolve.getList({ huisnummerId: x.id }))),
Gebouwen: x => Promise.all(x.map(Resolve.Gebouw)),
Terreinobjecten: x => Promise.all(x.map(Resolve.Terreinobject)),
Percelen: x => Promise.all(x.map(Resolve.Perceel)),
Huisnummers: x => Promise.all(x.map(Resolve.Huisnummer)),
Wegobjecten: x => Promise.all(x.map(Resolve.Wegobject)),
Wegsegmenten: x => Promise.all(x.map(Resolve.Wegsegment)),
Wegobject: x => Wegobject.get(x)
.then(({ center, minimum, maximum }) => objects.wegobjecten.push({ center, minimum, maximum })),
Wegsegment: x => Wegsegment.get(x)
.then(({ lineString }) => objects.wegsegmenten.push(lineString)),
Straat: fn => straat => {
const id = { straatnaamId: straat.id };
Promise.all([
Huisnummers.list(id).then(Resolve.Huisnummers),
Wegobjecten.list(id).then(Resolve.Wegobjecten),
Wegsegmenten.list(id).then(Resolve.Wegsegmenten),
])
.then(() => fn(objects))
.catch(e => log(e));
},
};
export default Resolve;
|
import mixin from '../../../mixin/form/mixin/reference-behaviour';
export default mixin;
|
/*!
* Copyright 2013 Phil DeJarnett - http://www.overzealous.com
*
* 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.
*/
angular.module("naturalSort",[]).factory("naturalService",function(){"use strict";var a=function(a){return"00000000000000000000".slice(a.length)},b=function(a){return null===a||void 0===a?"":""+a},c=function(c){return b(c).replace(/(\d+)((\.\d+)+)?/g,function(b,c,d,e){return d!==e?b.replace(/(\d+)/g,function(b){return a(b)+b}):(d=d||".0",a(c)+c+d+a(d))})};return{naturalValue:c,naturalSort:function(a,b){return a=natVale(a),b=c(b),b>a?-1:a>b?1:0}}}).run(["$rootScope","naturalService",function(a,b){"use strict";a.natural=function(a){return function(c){return b.naturalValue(c[a])}}}]);
|
//Cargamos la libreria de johnny five
var five = require("johnny-five")
//Iniciamos las variables de los elementos
var board;
var button;
var ledRed;
var ledYellow;
var ledGreen;
//Creamos la board
board = new five.Board();
board.on("ready", function() {
//Creamos el botton instanciandolo de la clase johnny five
//Le asignamos el pin donde esta conectado el pulsador
button = new five.Button(2);
//Inyectamos el botton a la board
board.repl.inject({
button: button
});
//Creamos la instancia de los leds
var ledRed = new five.Led(5);
var ledYellow = new five.Led(6);
var ledGreen = new five.Led(7);
//Cramos los eventos del botton
//Evento al presionar el botton
button.on("down", function() {
console.log("down");
ledRed.on();//Se prende el led rojo
});
//Evento al dejar presionado el botton, por defecto despues de
//1/2 segundo
button.on("hold", function() {
console.log("hold");
ledRed.stop().off();//Se apaga el led rojo
ledYellow.on();//Se prende el led amarillo
});
//Evento al soltar el botton
button.on("up", function() {
console.log("up");
ledGreen.on();//Se prende el led verde
ledYellow.stop().off();//Se apaga el led amarillo
ledGreen.stop().off();//Se apaga el led verde
});
});
|
'use strict';
angular.module('mean.companies').controller('ProjectsController', ['$scope', '$state', '$stateParams', '$location', 'Global', 'Projects', 'Message',
function($scope, $state, $stateParams, $location, Global, Projects, Message) {
$scope.global = Global;
$scope.package = { name: 'projects' };
$scope.projects = {};
// $scope.showForm = false;
$scope.contentClass = 'with-sidebar';
$scope.sidebar = true;
$scope.settingsCollapsed = true;
$scope.create = function() {
var companyId = $stateParams.companyId ? $stateParams.companyId : '';
//set company properties to the request body
var project = new Projects({
companyId: companyId,
project : {
name: this.projectName
}
});
//call an ajax that saves the company on the server-side
project.$save(function(response) {
console.log(response);
$scope.company = response;
$scope.debug_message = response.debug_message ? response.debug_message : null;
console.log('function create() logs:');
console.log($scope.company);
// $state.go('project', { companySlug: company.data.slug, projectId: company.projectId });
});
$scope.projectName = '';
$scope.showForm = false;
};
$scope.find = function() {
console.log('$scope.find()');
console.log($stateParams);
var companyId = $stateParams.companyId ? $stateParams.companyId : '';
// send get request to the server api
Projects.get({
companyId: companyId,
}, function(response) {
if (response) {
console.log($scope.company);
$scope.company = response;
$scope = Message.set($scope, response);
}
});
};
$scope.findOne = function() {
console.log('$scope.findOne()');
var companyId = $stateParams.companyId ? $stateParams.companyId : '';
var projectId = $stateParams.projectId ? $stateParams.projectId : '';
// get it from the server api
Projects.get({
companyId: companyId,
projectId: projectId
}, function(response) {
if (response) {
$scope.project = response;
$scope = Message.set($scope, response);
console.log($scope.project);
} else {
$state.go('projects by company');
}
});
};
$scope.toggleSidebar = function() {
$scope.contentClass = $scope.contentClass === 'with-sidebar' ? 'without-sidebar' : 'with-sidebar';
$scope.sidebar = $scope.sidebar !== true;
};
}
]);
|
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-44445792-2', 'auto');
ga('send', 'pageview');
|
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule createRelayNetworkLogger
* @flow
* @format
*/
'use strict';
const RelayConcreteNode = require('RelayConcreteNode');
const {convertFetch, convertSubscribe} = require('ConvertToExecuteFunction');
import type {ConcreteRequest} from 'RelayConcreteNode';
import type {IRelayNetworkLoggerTransaction} from 'RelayNetworkLoggerTransaction';
import type {
ExecuteFunction,
FetchFunction,
SubscribeFunction,
} from 'RelayNetworkTypes';
import type {Variables} from 'react-relay/classic/tools/RelayTypes';
export type GraphiQLPrinter = (
request: ConcreteRequest,
variables: Variables,
) => string;
function createRelayNetworkLogger(
LoggerTransaction: Class<IRelayNetworkLoggerTransaction>,
): * {
return {
wrapFetch(
fetch: FetchFunction,
graphiQLPrinter?: GraphiQLPrinter,
): FetchFunction {
return (request, variables, cacheConfig, uploadables) => {
const wrapped = wrapExecute(
convertFetch(fetch),
LoggerTransaction,
graphiQLPrinter,
);
return wrapped(request, variables, cacheConfig, uploadables);
};
},
wrapSubscribe(
subscribe: SubscribeFunction,
graphiQLPrinter?: GraphiQLPrinter,
): SubscribeFunction {
return (request, variables, cacheConfig) => {
const wrapped = wrapExecute(
convertSubscribe(subscribe),
LoggerTransaction,
graphiQLPrinter,
);
return wrapped(request, variables, cacheConfig);
};
},
};
}
function wrapExecute(
execute: ExecuteFunction,
LoggerTransaction: Class<IRelayNetworkLoggerTransaction>,
graphiQLPrinter: ?GraphiQLPrinter,
): ExecuteFunction {
return (request, variables, cacheConfig, uploadables) => {
let transaction;
function addLogs(error, response, status) {
// Only print GraphiQL links for non-batch requests.
if (graphiQLPrinter && request.kind === RelayConcreteNode.REQUEST) {
transaction.addLog('GraphiQL', graphiQLPrinter(request, variables));
}
transaction.addLog('Cache Config', cacheConfig);
transaction.addLog('Variables', JSON.stringify(variables, null, 2));
if (status) {
transaction.addLog('Status', status);
}
if (error) {
transaction.addLog('Error', error);
}
if (response) {
transaction.addLog('Response', response);
}
}
function flushLogs(error, response, status) {
addLogs(error, response, status);
transaction.flushLogs(error, response, status);
}
function commitLogs(error, response, status) {
addLogs(error, response, status);
transaction.commitLogs(error, response, status);
}
const observable = execute(request, variables, cacheConfig, uploadables);
const isSubscription = request.operationKind === 'subscription';
return observable.do({
start: () => {
transaction = new LoggerTransaction({
request,
variables,
cacheConfig,
uploadables,
});
console.time && console.time(transaction.getIdentifier());
if (isSubscription) {
flushLogs(null, null, 'subscription is sent.');
}
},
next: payload => {
flushLogs(null, payload);
console.time && console.time(transaction.getIdentifier());
},
error: error => commitLogs(error, null, null),
complete: () => {
if (isSubscription) {
commitLogs(null, null, 'subscription was closed.');
} else {
// the last `next` already flushed the logs, just mark as committed
// without spamming the logs
transaction.markCommitted();
}
},
unsubscribe: () =>
commitLogs(
null,
null,
isSubscription
? 'subscription is unsubscribed.'
: 'execution is unsubscribed.',
),
});
};
}
module.exports = createRelayNetworkLogger;
|
(function() {
'use strict'
function pageLoad() {
// Check the current part of Mbot
let noBluetooth = document.getElementById("noBluetooth");
let stepConnect = document.getElementById("stepConnect");
let stepControl = document.getElementById("stepControl");
// Check if the bluetooth is available
if (navigator.bluetooth == undefined) {
console.error("No navigator.bluetooth found.");
stepConnect.style.display = "none";
noBluetooth.style.display = "flex";
} else {
// Display the connect button
stepConnect.style.display = "flex";
noBluetooth.style.display = "none";
let mBot = require("./mbot/mbot");
// Check the connection
document.getElementById("connectBtn").addEventListener('click', _ => {
// Request the device
mBot.request()
.then(_ => {
// Connect to the mbot
return mBot.connect();
})
.then(_ => {
// Connection is done, we show the controls
stepConnect.style.display = "none";
stepControl.style.display = "flex";
let partBtn = document.querySelector('.part-button');
// Control the robot by buttons
let btnUp = document.getElementById('btnUp');
let btnDown = document.getElementById('btnDown');
let btnLeft = document.getElementById('btnLeft');
let btnRight = document.getElementById('btnRight');
btnUp.addEventListener('touchstart', _ => { mBot.processMotor(-250, 250) });
btnDown.addEventListener('touchstart', _ => { mBot.processMotor(250, -250) });
btnLeft.addEventListener('touchstart', _ => { mBot.processMotor(250, 250) });
btnRight.addEventListener('touchstart', _ => { mBot.processMotor(-250, -250) });
btnUp.addEventListener('touchend', _ => { mBot.processMotor(0, 0) });
btnDown.addEventListener('touchend', _ => { mBot.processMotor(0, 0) });
btnLeft.addEventListener('touchend', _ => { mBot.processMotor(0, 0) });
btnRight.addEventListener('touchend', _ => { mBot.processMotor(0, 0) });
// Buzz the robot
let btnBuzz = document.getElementById('btnBuzz');
btnBuzz.addEventListener('click', _=>{ mBot.processBuzzer()});
// Color the robot
let ColorPicker = require('./components/colorpicker.js');
new ColorPicker((rgb) => {
mBot.processColor(rgb.red, rgb.blue, rgb.green);
});
})
});
}
}
window.addEventListener('load', pageLoad);
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./service-worker.js', {scope : location.pathname}).then(function(reg) {
console.log('Service Worker Register for scope : %s',reg.scope);
});
}
})();
|
jQuery(document).ready(function($) {
$.growl.settings.noticeCss = {
position: 'relative',
'background-color':'#000',
padding: '20px'
};
})
function doGrowl(title,body){
// $.growl(title,body);
}
|
(function () {
'use strict';
angular
.module('porttare.services')
.factory('NativeSessionService', NativeSessionService);
function NativeSessionService ($auth,
$http,
$rootScope,
$cordovaFacebook,
APP,
ENV) {
var service = {
logOut: logOut,
loginWithFB: loginWithFB
};
var deferred;
return service;
function logOut() {
return $cordovaFacebook.logout();
}
function loginWithFB() {
deferred = $auth.initDfd();
$cordovaFacebook.getLoginStatus()
.then(function(response) {
if (response.status === 'connected') {
return fbAuthorizationSuccess(response);
} else {
$cordovaFacebook.login(APP.fbAuthScope).then(
fbAuthorizationSuccess,
authorizationFailure
);
}
});
return deferred.promise;
}
function fbAuthorizationSuccess(credentials) {
var postData = {
provider: 'facebook',
access_token: credentials.authResponse.accessToken // jshint ignore:line
};
$http({
method: 'POST',
data: postData,
url: ENV.apiHost + '/api/auth/native_login',
headers: { 'Accept': 'application/json' }
}).then(
performLogin,
authorizationFailure
);
}
function performLogin(response) {
var authData = $auth.getConfig().handleLoginResponse(response.data);
$auth.handleValidAuth(authData, true); // this resolves the promise
$rootScope.$broadcast('auth:login-success', $auth.user);
}
function authorizationFailure(error) {
return deferred.reject(error);
}
}
})();
|
const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
const serveStatic = require('serve-static');
const logger = require('morgan');
const bodyParser = require('body-parser');
const compression = require('compression');
const routes = require('./routes');
const app = express();
const root = path.join(__dirname, '..');
app.set('port', process.env.PORT || 3003);
app.set('view engine', 'jade');
app.use(favicon(path.join(root, 'public', 'images', 'favicon.ico')));
const setupStatic = (...args) => {
app.use(serveStatic(path.join(root, ...args)));
};
setupStatic('public');
setupStatic('bower_components', 'bootstrap', 'dist');
setupStatic('bower_components', 'jquery', 'dist');
setupStatic('bower_components', 'confetti.js');
setupStatic('bower_components', 'lodash', 'dist');
app.use(logger('combined'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(compression());
const isDev = process.env.NODE_ENV !== 'production';
app.get('/', routes.retrieveIndex);
app.post('/', routes.authorizePayment);
app.get('/authorized', routes.handleAuthorizedPayment);
const port = app.get('port');
app.listen(port, function () {
console.log(`Listening on port ${port}...`);
});
app.use(function clientErrorHandler(err, req, res, next) {
console.error(err);
const locals = {
error: 'Uh oh! Something went unexpectedly wrong. I guess that means no pizza ... 😞'
};
res.status(500).render('index', locals);
});
|
/**
* Copyright (c) 2016 Ganesh Prasad Sahoo (GnsP)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
export default class IronSymbol {
constructor (str) {
this.symbol = str;
this.type = 'ironsymbol';
}
equal (sym) {
if (! sym instanceof IronSymbol ) return false;
return sym.symbol === this.symbol;
}
startsWith (ch) {
return this.symbol.startsWith(ch);
}
}
|
/* eslint-disable */
(function (App) {
'use strict';
var init = function () {
if (window.route) {
new App.View.HeaderView({
el: document.querySelector('.js-header')
})
var translate = false;
if (gon && gon.translations) {
translate = Object.keys(gon.translations).some(function (elem) {
return gon.translations[elem];
});
}
if (translate) {
// NOTE: because there's two language selectors in the webpage, we need to maintain them in sync
var desktopLanguageSelector = new App.View.LanguageSelectorView();
var mobileDesktopLanguageSelector = new App.View.LanguageSelectorView({
el: '.js-language-selector-mobile',
useShortName: false
});
// Here we listen to changes in one selector and manually update the other one.
desktopLanguageSelector.listenTo(mobileDesktopLanguageSelector, 'state:change', function (state) {
this.updateCurrentLanguage(state.currentLanguage);
});
mobileDesktopLanguageSelector.listenTo(desktopLanguageSelector, 'state:change', function (state) {
this.updateCurrentLanguage(state.currentLanguage);
});
}
if (window.route === 'Map') {
document.querySelector('body').classList.add('-wide');
}
}
};
// We need for the DOM to be ready
window.addEventListener('DOMContentLoaded', init);
}).call(this, this.App);
|
var ContactsShowRoute = Ember.Route.extend({
model: function(params) {
return this.store.find('contact', params.id);
}
});
export default ContactsShowRoute;
|
/* eslint-env browser */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Sign In Page - Index
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
import { connect } from 'react-redux';
import Component from './Component';
import { auth } from '../../../actions';
/**
* Connector
*/
export default connect(
() => ({}),
dispatch => ({
onSignIn: (email, password) => (
dispatch(auth.signInWithEmailAndPassword(email, password))
),
})
)(Component);
|
let ind = 0;
class Lines {
constructor(triangles, color) {
const trianglesRoot = new THREE.Object3D();
trianglesRoot.name = 'lines_container_' + ind;
ind++;
const lineMaterial = new THREE.LineBasicMaterial({color});
for (let i = 0; i < triangles.length; i += 4) {
const lineGeometry = new THREE.Geometry();
lineGeometry.vertices.push(
new THREE.Vector3(triangles[i], 1, triangles[i + 1]),
new THREE.Vector3(triangles[i + 2], 1, triangles[i + 3])
);
const lineMesh = new THREE.Line(lineGeometry, lineMaterial);
trianglesRoot.add(lineMesh);
}
return trianglesRoot;
}
}
export default Lines;
|
import { Component } from './component';
import { View } from './view';
import { Image } from './image';
import { Text } from './text';
import { RasterManager } from './rastermanager';
import { Utils } from './utils';
let callbacks = {};
/**
* Animated
*/
const animationComplete = function animationComplete(event) {
let eventAnimation = event.animation;
// android sends these over stringified on the bridge
if (typeof eventAnimation == 'string') {
eventAnimation = JSON.parse(event.animation).animation;
}
let callback = callbacks[eventAnimation.guid];
if (callback) callback(event);
};
class AnimatedView extends View {
animationComplete(event) {
animationComplete.call(this, event);
}
}
class AnimatedImage extends Image {
animationComplete(event) {
animationComplete.call(this, event);
}
}
class AnimatedText extends Text {
animationComplete(event) {
animationComplete.call(this, event);
}
}
/**
* Animated Class. Sets up and prepares animations to be transported over the bridge
*/
class animated extends Component {
constructor() {
super();
this.View = AnimatedView;
this.Image = AnimatedImage;
this.text = AnimatedText;
this.AnimationTargets = {};
}
/**
* Transform type of XY Value. Sets up an animation on the raster.
* @param {object} opts
*/
ValueXY(opts) {
this.x = opts.x;
this.y = opts.y;
this.setValue = newopts => {
this.x = newopts.x;
this.y = newopts.y;
};
this.guid = Utils.guid();
}
/**
* Sets up a interpolation animation from one value to another over a duration
* @param {int} value
*/
Value(value) {
this.value = value;
this.setValue = newValue => {
this.value = newValue;
};
this.guid = Utils.guid();
}
/**
* Setups an Animation from the that is ready to send to the bridge.
* @param {object} animation
* @param {object} opts
*/
timing(animation, opts) {
// convention so that these are not set
// before componentDidMount
if (animation instanceof Animated.ValueXY) {
animation.x2 = opts.toValue.x;
animation.y2 = opts.toValue.y;
} else if (animation instanceof Animated.Value) {
animation.toValue = opts.toValue;
}
animation.duration = opts.duration; // ms
this.animation = animation;
return this;
}
/**
* Chained to Animated.timing().start() , sends an `animation` event to the Native Layer
*/
start(callback) {
let animation = this.animation;
callbacks[animation.guid] = callback;
let cached = RasterManager.render.getInstance(
this.AnimationTargets[animation.guid]
);
if (typeof animation.x2 == 'number' || typeof animation.y2 == 'number') {
cached.state = cached.state || {};
cached.state.y = animation.y2;
cached.state.x = animation.x2;
}
RasterManager.getRaster().sendMessage('animation', {
guid: this.AnimationTargets[animation.guid],
animation: animation,
});
}
}
const Animated = new animated();
export { Animated };
|
function Editor(map) { this.map = map; this.tiles = map.tiles }
Editor.prototype = {
selected: null,
modified: false,
brushAt: function(point) {
var x = point.x >> TILE_SIZE_BITS, y = point.y >> TILE_SIZE_BITS;
var tile = this.selected
if (tile) {
if (tile.layer == 0) {
//if tile is surface, delete the object and place the tile
this.map.setSurface(x, y, tile)
this.map.setObject(x, y, this.tiles.defaultObject)
}
else
this.map.setObject(x, y, tile)
this.modified = true
}
},
cursorAt: function(point) {
},
load: function() {
if (localStorage['mapdata']) {
this.map.load(JSON.parse(localStorage['mapdata']));
this.modified = false
}
},
save: function() {
if (this.modified) {
localStorage['mapdata'] = JSON.stringify(this.map.save());
this.modified = false
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.