text
stringlengths 2
6.14k
|
|---|
import React from 'react';
import _ from 'lodash';
import { FlatButton, RaisedButton } from 'material-ui';
const DialogStandardButtons = ({
handleCancel,
handleConfirm,
submitLabel = 'Confirm',
cancelLabel = 'Cancel',
inverted,
disabled,
submitDisabled,
cancelDisabled,
...other
}) => {
const styles = {
rootInverted: {
display: 'flex',
flexDirection: 'row-reverse',
justifyContent: 'flex-end',
marginLeft: -10
},
button: {
marginLeft: 10,
borderRadius: '4px'
}
};
return (
<div style={inverted && styles.rootInverted}>
<FlatButton
key="cancel"
label={cancelLabel}
labelStyle={{ textTransform: 'none' }}
buttonStyle={{ borderRadius: '4px' }}
style={styles.button}
disabled={disabled || cancelDisabled}
onTouchTap={_.debounce(handleCancel, 500, { leading: true })}
data-e2e={other['data-e2e-cancel']}
/>
<RaisedButton
key="confirm"
label={submitLabel}
labelStyle={{ textTransform: 'none', color: '#436E1D' }}
buttonStyle={{ borderRadius: '4px' }}
backgroundColor="#B8E986"
style={styles.button}
disabled={disabled || submitDisabled}
onTouchTap={_.debounce(handleConfirm, 500, { leading: true })}
data-e2e={other['data-e2e-submit']}
/>
</div>
);
};
export default DialogStandardButtons;
|
var mongoose = require('mongoose');
var workLogSchema = mongoose.Schema({
startedAt: {
type: Date,
required: true,
default: Date.now
},
timeSpent: {
type: Number,
required: true,
validate: [ function (value) {
return value > 0;
}, 'Time spent must be greater than zero.' ]
},
task: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Task'
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
});
workLogSchema.static({
findById: function (id, callback) {
this.findOne({
_id: id
})
.select('-task -user -__v')
.exec(callback);
},
findByIdAndTaskId: function (options, callback) {
this.findOne({
_id: options.id,
task: options.taskId
})
.select('-task -user -__v')
.exec(callback);
},
findByTaskId: function (taskId, callback) {
this.find({
task: taskId
})
.select('-task -user -__v')
.exec(callback);
},
findByUserId: function (userId, callback) {
this.find({
user: userId
})
.select('-task -user -__v')
.exec(callback);
}
});
workLogSchema.set('toJSON', {
transform: function (doc, ret, options) {
ret.id = ret._id;
delete ret._id;
delete ret.__v;
}
});
module.exports = mongoose.model('WorkLog', workLogSchema);
|
import React, {Component} from 'react'
import {findDOMNode} from 'react-dom'
import styles from '../sass/Form'
import {Button, Form, Input, DatePicker, Select} from 'antd'
class FormComponent extends Component {
constructor() {
super()
this.handleSubmit = this.handleSubmit.bind(this)
}
handleSubmit(e) {
e.preventDefault()
const {form, actions} = this.props
form.validateFields((err, values) => {
if (!err) {
actions.getItems(values)
}
})
}
render() {
const {form, schools, cats} = this.props
return (
<Form onSubmit={this.handleSubmit}
className={styles.form}
inline>
<Form.Item
label="学校">
{form.getFieldDecorator('school',{initialValue: schools[0]?schools[0].id:''})(
<Select className={styles.select}>
{schools.map(school =>
<Select.Option key={school.id} value={school.id}>{school.schoolName}</Select.Option>
)}
</Select>
)}
</Form.Item>
<Form.Item
label="分类">
{form.getFieldDecorator('cat',{initialValue: ''})(
<Select className={styles.select}>
<Select.Option value="">全部</Select.Option>
{cats.map(cat =>
<Select.Option key={cat.id} value={cat.id}>{cat.catName}</Select.Option>
)}
</Select>
)}
</Form.Item>
<Form.Item>
<Button htmlType="submit" type="primary">查询</Button>
</Form.Item>
</Form>
)
}
}
export default Form.create()(FormComponent)
|
/**
* Core dependencies.
*/
var path = require('path');
var dirname = path.dirname;
/**
* Create path.
*
* @param {String} pattern
* @returns {Object}
* @api private
*/
function createPattern(pattern) {
return {
pattern: pattern,
included: true,
served: true,
watched: false
};
}
/**
* Insert hydro into the loaded files.
*
* @param {Array} files
* @api public
*/
function init(config) {
var hydroConfig = config.hydro || {};
var hydroJs = hydroConfig.path || dirname(dirname(require.resolve('hydro'))) + '/dist/hydro.js';
var before = hydroConfig.before || [];
config.files.unshift(createPattern(__dirname + '/adapter.js'));
config.files.unshift(createPattern(hydroJs));
before.reverse().forEach(function(file) {
config.files.unshift(createPattern(path.resolve(file)));
});
}
/**
* Inject.
*/
init.$inject = [ 'config' ];
/**
* Primary export.
*/
module.exports = {
'framework:hydro': [ 'factory', init ]
};
|
/*
* This class represent a game paddle
*/
'use strict';
import Vector from 'Vector.js';
export default class {
constructor(x, y, width, height, color = '#FFFFFF', speed = 3) {
this.width = width;
this.height = height;
this.color = color;
this.position = new Vector(x, y);
this.velocity = new Vector(speed, 0);
this.computer = false;
// Control keys.
this.rightPressed = false;
this.leftPressed = false;
}
// Setting the paddle to a specific position.
setPosition(x, y) {
this.position.setCoordinates(x, y);
}
move(doMove) {
if (this.rightPressed || this.leftPressed) {
if (this.rightPressed) {
this.velocity.x = Math.abs(this.velocity.x);
} else if (this.leftPressed) {
this.velocity.x = -Math.abs(this.velocity.x);
}
if (doMove) {
this.position.add(this.velocity);
}
}
}
// Returns relevant drawing information related to
// the paddle.
getDrawInfo() {
return {
drawType: 'rect',
color: this.color,
params: [
this.position.x,
this.position.y,
this.width,
this.height
]
};
}
}
|
var through = require('through2');
var escapeStr = require('js-string-escape');
var STYLE_HEADER = '!function(){var a="';
var STYLE_FOOTER = '",b=document.createElement("style");b.type="text/css",b.styleSheet?b.styleSheet.cssText=a:b.appendChild(document.createTextNode(a)),(document.head||document.getElementsByTagName("head")[0]).appendChild(b)}();';
function cssTojs() {
function transform(file, enc, callback) {
var css = file.contents.toString();
var content = STYLE_HEADER + escapeStr(css) + STYLE_FOOTER;
file.contents = new Buffer(content);
callback(null, file);
}
return through.obj(transform);
}
module.exports = cssTojs;
|
var angular = require('angular');
// import the hello UI component
require('./hello/main');
// compose the app and the routes
module.exports = angular
.module('myApp', [
'ngRoute',
'hello'
])
.config([
'$routeProvider', function ($routeProvider) {
$routeProvider.when(
'/',
{ templateUrl: 'app/hello/base.html', controller: 'HelloCtrl' }
);
$routeProvider.otherwise({ redirectTo: '/' });
}
]);
// start the application
angular.bootstrap(document, ['myApp']);
|
var URL = require('url');
var Pagination = function(request, model){
this.request = request;
this.model = model;
this.paginate = function(query, limit, sort, selected, onDataReception){
var url = URL.parse(this.request.url).pathname;
var page = this.request.param('page');
page = page === undefined ? 0 : page;
this.model.find(query).sort(sort).skip(page*limit).limit( (limit + 1) ).select( selected ).exec(function(err, members){
//Fetched more than the limit
members.splice(limit, 1);
var paginatedMembers = {
data : members
};
if(members.length >= limit ){
nextPage = parseInt(page) + 1;
paginatedMembers["next"] = url + "?page=" + nextPage;
}
if (page >= 1) {
prevPage = parseInt(page) - 1;
paginatedMembers["prev"] = url + "?page=" + prevPage;
};
onDataReception(paginatedMembers);
});
};
}
module.exports = function(request, model){
return new Pagination(request, model);
}
|
define(
[
'solarfield/lightship-js/src/Solarfield/Lightship/Environment',
'solarfield/ok-kit-js/src/Solarfield/Ok/ObjectUtils'
],
function (LightshipEnvironment, ObjectUtils) {
"use strict";
var Environment = ObjectUtils.extend(LightshipEnvironment, {
});
return Environment;
}
);
|
$(function(){
var InvitationForm = Backbone.View.extend({
el: $('fieldset[data-control=invitation]'),
events: {
},
initialize: function(){
if(!this.$el.length) return null;
this.listenTo(Backbone, 'showInvitationForm', this.showInvitationForm);
this.listenTo(Backbone, 'hideInvitationForm', this.hideInvitationForm);
},
showInvitationForm: function(){
this.$el.removeClass('hidden');
},
hideInvitationForm: function(){
this.$el.addClass('hidden');
}
});
var invitationForm = new InvitationForm();
});
|
import React, { PropTypes } from 'react';
class AutoFocus extends React.Component {
constructor( props ) {
super( props );
this.receiveRef = this.receiveRef.bind( this );
}
componentDidMount() {
if ( this.ref ) {
this.ref.focus();
}
}
receiveRef( node ) {
this.ref = node;
}
render() {
return this.props.children( this.receiveRef );
}
}
AutoFocus.propTypes = {
children: PropTypes.func.isRequired,
};
export default AutoFocus;
|
var DObject_8h =
[
[ "DObject", "classHelix_1_1Logic_1_1dev_1_1DObject.html", "classHelix_1_1Logic_1_1dev_1_1DObject" ],
[ "DObject_svect", "DObject_8h.html#a56460b28b8ab9b64a1aecf912b2f14ac", null ]
];
|
/*
* Sidebar toggle function
*/
(function(document) {
var toggle = document.querySelector('.sidebar-toggle');
var sidebar = document.querySelector('#sidebar');
var checkbox = document.querySelector('#sidebar-checkbox');
document.addEventListener('click', function(e) {
var target = e.target;
if(!checkbox.checked ||
sidebar.contains(target) ||
(target === checkbox || target === toggle)) return;
checkbox.checked = false;
}, false);
})(document);
/*global jQuery */
/*jshint browser:true */
/*!
* FitVids 1.1
*
* Copyright 2013, Chris Coyier - http://css-tricks.com + Dave Rupert - http://daverupert.com
* Credit to Thierry Koblentz - http://www.alistapart.com/articles/creating-intrinsic-ratios-for-video/
* Released under the WTFPL license - http://sam.zoy.org/wtfpl/
*
*/
;(function( $ ){
'use strict';
$.fn.fitVids = function( options ) {
var settings = {
customSelector: null,
ignore: null
};
if(!document.getElementById('fit-vids-style')) {
// appendStyles: https://github.com/toddmotto/fluidvids/blob/master/dist/fluidvids.js
var head = document.head || document.getElementsByTagName('head')[0];
var css = '.fluid-width-video-wrapper{width:100%;position:relative;padding:0;}.fluid-width-video-wrapper iframe,.fluid-width-video-wrapper object,.fluid-width-video-wrapper embed {position:absolute;top:0;left:0;width:100%;height:100%;}';
var div = document.createElement("div");
div.innerHTML = '<p>x</p><style id="fit-vids-style">' + css + '</style>';
head.appendChild(div.childNodes[1]);
}
if ( options ) {
$.extend( settings, options );
}
return this.each(function(){
var selectors = [
'iframe[src*="player.vimeo.com"]',
'iframe[src*="youtube.com"]',
'iframe[src*="youtube-nocookie.com"]',
'iframe[src*="kickstarter.com"][src*="video.html"]',
'object',
'embed'
];
if (settings.customSelector) {
selectors.push(settings.customSelector);
}
var ignoreList = '.fitvidsignore';
if(settings.ignore) {
ignoreList = ignoreList + ', ' + settings.ignore;
}
var $allVideos = $(this).find(selectors.join(','));
$allVideos = $allVideos.not('object object'); // SwfObj conflict patch
$allVideos = $allVideos.not(ignoreList); // Disable FitVids on this video.
$allVideos.each(function(){
var $this = $(this);
if($this.parents(ignoreList).length > 0) {
return; // Disable FitVids on this video.
}
if (this.tagName.toLowerCase() === 'embed' && $this.parent('object').length || $this.parent('.fluid-width-video-wrapper').length) { return; }
if ((!$this.css('height') && !$this.css('width')) && (isNaN($this.attr('height')) || isNaN($this.attr('width'))))
{
$this.attr('height', 9);
$this.attr('width', 16);
}
var height = ( this.tagName.toLowerCase() === 'object' || ($this.attr('height') && !isNaN(parseInt($this.attr('height'), 10))) ) ? parseInt($this.attr('height'), 10) : $this.height(),
width = !isNaN(parseInt($this.attr('width'), 10)) ? parseInt($this.attr('width'), 10) : $this.width(),
aspectRatio = height / width;
if(!$this.attr('id')){
var videoID = 'fitvid' + Math.floor(Math.random()*999999);
$this.attr('id', videoID);
}
$this.wrap('<div class="fluid-width-video-wrapper"></div>').parent('.fluid-width-video-wrapper').css('padding-top', (aspectRatio * 100)+'%');
$this.removeAttr('height').removeAttr('width');
});
});
};
// Works with either jQuery or Zepto
})( window.jQuery || window.Zepto );
/*
* Show disqus comments
*/
jQuery(document).ready(function() {
jQuery(".post").fitVids();
// Load discus comment
function initDisqusComments(){
if(config.disqus_shortname != '' && config.disqus_shortname != null && config.disqus_shortname != undefined) {
var disqus_shortname = config.disqus_shortname;
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
}else {
alert("Please check Disqus short name configuration on your _config.yml");
}
}
initDisqusComments();
$(this).fadeOut(200);
/*$('.load-view').click(function(){
initDisqusComments();
$(this).fadeOut(200);
});*/
});
/*
* Scroll to top button
*/
jQuery(document).ready(function($){
// browser window scroll (in pixels) after which the "back to top" link is shown
var offset = 300,
//browser window scroll (in pixels) after which the "back to top" link opacity is reduced
offset_opacity = 1200,
//duration of the top scrolling animation (in ms)
scroll_top_duration = 700,
//grab the "back to top" link
$back_to_top = $('.wc-top');
//hide or show the "back to top" link
$(window).scroll(function(){
( $(this).scrollTop() > offset ) ? $back_to_top.addClass('wc-is-visible') : $back_to_top.removeClass('wc-is-visible wc-fade-out');
if( $(this).scrollTop() > offset_opacity ) {
$back_to_top.addClass('wc-fade-out');
}
});
//smooth scroll to top
$back_to_top.on('click', function(event){
event.preventDefault();
$('body,html').animate({
scrollTop: 0 ,
}, scroll_top_duration
);
});
});
|
import React from 'react';
import PropTypes from 'prop-types';
import { reduxForm } from 'redux-form';
import { connect } from 'react-redux';
import compose from 'recompose/compose';
import getDefaultValues from './getDefaultValues';
import FormField from './FormField';
import Toolbar from './Toolbar';
const noop = () => {};
export const SimpleForm = ({ children, handleSubmit, invalid, record, resource, basePath, submitOnEnter }) => {
return (
<form onSubmit={ submitOnEnter ? handleSubmit : noop } className="simple-form">
<div style={{ padding: '0 1em 1em 1em' }}>
{React.Children.map(children, input => input && (
<div key={input.props.source} className={`aor-input-${input.props.source}`} style={input.props.style}>
<FormField input={input} resource={resource} record={record} basePath={basePath} />
</div>
))}
</div>
<Toolbar invalid={invalid} submitOnEnter={submitOnEnter} />
</form>
);
};
SimpleForm.propTypes = {
children: PropTypes.node,
defaultValue: PropTypes.oneOfType([
PropTypes.object,
PropTypes.func,
]),
handleSubmit: PropTypes.func,
invalid: PropTypes.bool,
record: PropTypes.object,
resource: PropTypes.string,
basePath: PropTypes.string,
validate: PropTypes.func,
submitOnEnter: PropTypes.bool,
};
SimpleForm.defaultProps = {
submitOnEnter: true,
};
const enhance = compose(
connect((state, props) => ({
initialValues: getDefaultValues(state, props),
})),
reduxForm({
form: 'record-form',
enableReinitialize: true,
}),
);
export default enhance(SimpleForm);
|
export function allDaysDisabledBefore (day, unit, { minDate, includeDates } = {}) {
const dateBefore = day.clone().subtract(1, unit)
return (minDate && dateBefore.isBefore(minDate, unit)) ||
(includeDates && includeDates.every(includeDate => dateBefore.isBefore(includeDate, unit))) ||
false
}
|
var util = require('util');
var fs = require('fs');
var path = require('path');
var ltrim = require('underscore.string/ltrim');
exports.isCommand = function (input) {
if (input.toLowerCase().substr(0, prefix.length) === prefix)
return true;
else
return false;
};
exports.isNumber = function (n) {
return !isNaN(parseFloat(n)) && isFinite(n);
};
exports.isURL = function (str) {
var pattern = new RedExp(
'^' +
'(?:(?:https?|ftp)://)' +
'(?:\\S+(?::\\S*)?@)?' +
'(?:' +
'(?!(?:10|127)(?:\\.\\d{1,3}){3})' +
'(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})' +
'(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})' +
'(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])' +
'(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}' +
'(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))' +
'|' +
'(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)' +
'(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*' +
'(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))' +
'\\.?' +
')' +
'(?::\\d{2,5})?' +
'(?:[/?#]\\S*)?' +
'$', 'i'
);
if (!pattern.test(str))
return false;
else
return true;
};
exports.getCommand = function (input) {
return input.replace(prefix, '').split(' ')[0];
};
exports.getFolders = function (SourcePath) {
return fs.readdirSync(SourcePath).filter(function (file) {
return fs.statSync(path.join(SourcePath, file)).isDirectory();
});
};
exports.getMessage = function (input) {
return input.replace(prefix, '');
};
exports.getParams = function (text) {
return text.split(' ').slice(1);
};
exports.normalizeChannel = function (channel) {
return util.format('#%s', ltrim(channel.toLowerCase() , '#'));
};
exports.numParams = function (text) {
return text.split(' ').length - 1;
};
exports.splitInput = function (splitAt, message, intSplit) {
var data = message.split(splitAt)[1];
return data.slice(0, data.length - intSplit);
};
|
//window.twttr=(function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],t=window.twttr||{};if(d.getElementById(id))return;js=d.createElement(s);js.id=id;js.src="https://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);t._e=[];t.ready=function(f){t._e.push(f);};return t;}(document,"script","twitter-wjs"));
function textchange(e) {
$('#twitter').attr({href: 'https://twitter.com/share?url=tw&text=' + encodeURIComponent($(this).val())});
// http://stackoverflow.com/a/2848483
length = $(this).val().length;
$('#length').text(140-length);
}
jQuery(document).ready(function($) {
$('#text').spellcheck({events: 'keyup', url: '/spellcheck.php'});
$('#text').change(textchange);
$('#text').keyup(textchange);
$( "#slider" ).slider({
value:1,
min: 1,
max: 5,
step: 1,
slide: function( event, ui ) {
$( "#depth" ).val( ui.value );
//$('#text').trigger('keyup');
}
});
});
|
function main() {
var N = 10000;
var lines = generateLines(N);
//timeCanvas2D(lines, N);
timeBatchDraw(lines, N);
}
function generateLines(N) {
var lines = new Array(N);
let canvas = document.getElementById("canvas");
let w = canvas.width;
let h = canvas.height;
// Create funky lines:
for (i=0; i<N; i++) {
lines[i] = {
fromX: (1.3*i/N) * w,
fromY: 0.5/(2*(i/N) + 1) * h,
toX: (0.1*i-1)/(N - i) * w,
toY: (0.3*N)/(5*(i*i)/N) * 0.5 * h
};
}
//console.log(lines);
return lines;
}
function timeBatchDraw(lines, N) {
let canvas = document.getElementById("canvas");
let params = {
maxLines: N,
clearColor: {r: 1, g: 1, b: 1, a: 1}
};
let batchDrawer = new BatchDrawer(canvas, params);
if (batchDrawer.error != null) {
console.log(batchDrawer.error);
return;
}
console.time("BatchDraw");
for (i=0; i<N; i++) {
batchDrawer.addLine(lines[i].fromX, lines[i].fromY, lines[i].toX, lines[i].toY, 0.001, 1, 0.5, 0.1, 1);
}
batchDrawer.draw(false);
console.timeEnd("BatchDraw");
}
function timeCanvas2D(lines, N) {
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
ctx.lineWidth = 0.01;
ctx.strokeStyle = '#ffa500';
ctx.fillStyle="#FFFFFF";
console.time("Canvas2D");
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (i=0; i<N; i++) {
ctx.beginPath();
ctx.moveTo(lines[i].fromX, lines[i].fromY);
ctx.lineTo(lines[i].toX, lines[i].toY);
ctx.stroke();
}
console.timeEnd("Canvas2D");
}
|
xdescribe('uiMask', function () {
var inputHtml = "<input ui-mask=\"'(9)9'\" ng-model='x'>";
var $compile, $rootScope, element;
beforeEach(module('ui.directives'));
beforeEach(inject(function (_$rootScope_, _$compile_) {
$rootScope = _$rootScope_;
$compile = _$compile_;
}));
describe('ui changes on model changes', function () {
it('should update ui valid model value', function () {
$rootScope.x = undefined;
element = $compile(inputHtml)($rootScope);
$rootScope.$digest();
expect(element.val()).toBe('');
$rootScope.$apply(function () {
$rootScope.x = 12;
});
expect(element.val()).toBe('(1)2');
});
it('should wipe out ui on invalid model value', function () {
$rootScope.x = 12;
element = $compile(inputHtml)($rootScope);
$rootScope.$digest();
expect(element.val()).toBe('(1)2');
$rootScope.$apply(function () {
$rootScope.x = 1;
});
expect(element.val()).toBe('');
});
});
describe('model binding on ui change', function () {
//TODO: was having har time writing those tests, will open a separate issue for those
});
describe('should fail', function() {
it('errors on missing quotes', function() {
$rootScope.x = 42;
var errorInputHtml = "<input ui-mask=\"(9)9\" ng-model='x'>";
element = $compile(errorInputHtml)($rootScope);
expect($rootScope.$digest).toThrow('The Mask widget is not correctly set up');
});
});
});
|
$(document).ready(function() {
///*определение ширины скролбара
// создадим элемент с прокруткой
var div = document.createElement('div');
div.style.overflowY = 'scroll';
div.style.width = '50px';
div.style.height = '50px';
div.style.position = 'absolute';
div.style.zIndex = '-1';
// при display:none размеры нельзя узнать
// нужно, чтобы элемент был видим,
// visibility:hidden - можно, т.к. сохраняет геометрию
div.style.visibility = 'hidden';
document.body.appendChild(div);
var scrollWidth = div.offsetWidth - div.clientWidth;
document.body.removeChild(div);
//*/
var fixedblock = $('#fixed');
var stick_state = false;
function fxm() {
if ($(window).width() > 640-scrollWidth) {
fixedblock.trigger("sticky_kit:detach");
fixedblock.stick_in_parent({
parent: '#main .columns',
offset_top: 30,
inner_scrolling: false
});
fixedblock.stick_in_parent()
.on("sticky_kit:stick", function(e) {
stick_state = true;
})
.on("sticky_kit:unstick", function(e) {
stick_state = false;
});
} else {
fixedblock.trigger("sticky_kit:detach");
}
}
fxm();
var navigation = document.getElementById('navigation');
if (navigation) {
var new_fix_elem = document.createElement('div');
new_fix_elem.setAttribute('class', 'nav__bounce__element');
navigation.parentNode.insertBefore(new_fix_elem, navigation);
}
var my__abs__list = document.querySelector('.my__abs__list');
var count_change = -1;
var fix_flag = false;
var navleft = navigation.querySelector('.block--left .menu');
/* шаг скролла */
var topless = 0;
var difference = 0;
function navig_fixit() {
var cont_top = window.pageYOffset ? window.pageYOffset : document.body.scrollTop;
var docHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
difference = cont_top - topless;
topless = cont_top;
if (navigation) {
if ($(window).width() > 768 - scrollWidth) {
var height = navigation.offsetHeight;
var rect = navigation.getBoundingClientRect();
var rect2 = new_fix_elem.getBoundingClientRect();
navigation.style.left = rect.left + 'px';
navigation.style.width = new_fix_elem.offsetWidth + 'px';
if (navleft.classList.contains('open') === true) {
var rectus = navleft.getBoundingClientRect();
console.log(rectus.height);
if (navigation.style.marginTop == '') {
navigation.style.marginTop = '0px';
}
var ms = parseInt(navigation.style.marginTop);
ms = Math.abs(ms);
ms += difference;
if (ms >= 0) {
var x_height = height + rectus.height - 50;
if (ms <= x_height - docHeight) {
navigation.style.marginTop = -ms+'px';
} else {
if (difference < 0) {
navigation.style.marginTop = -ms+'px';
}
}
}
/* navigation.classList.remove('fixed'); */
new_fix_elem.style.height = '0px';
return false;
}
if (fix_flag === false) {
if (rect2.top + height*2 < 0) {
if (rect2.top > count_change) {
navigation.classList.add('fixed');
new_fix_elem.style.height = height + 'px';
fix_flag = true;
fixedblock.css('margin-top', height + 'px');
if (stick_state === false) {
fixedblock.css('margin-top', '0px');
}
} else {
navigation.classList.remove('fixed');
new_fix_elem.style.height = '0px';
fix_flag = false;
my__abs__list.classList.remove('active');
fixedblock.css('margin-top', '0px');
}
}
} else {
if (rect2.top > count_change) {
navigation.classList.add('fixed');
new_fix_elem.style.height = height + 'px';
fix_flag = true;
fixedblock.css('margin-top', height + 'px');
if (stick_state === false) {
fixedblock.css('margin-top', '0px');
}
if (rect2.top > 0) {
navigation.classList.remove('fixed');
new_fix_elem.style.height = '0px';
fix_flag = false;
my__abs__list.classList.remove('active');
}
} else {
navigation.classList.remove('fixed');
new_fix_elem.style.height = '0px';
fix_flag = false;
my__abs__list.classList.remove('active');
fixedblock.css('margin-top', '0px');
}
}
count_change = rect2.top;
} else {
navigation.classList.remove('fixed');
navigation.style = '';
new_fix_elem.style.height = '0px';
my__abs__list.classList.remove('active');
}
}
}
navig_fixit();
//debounce
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
// Использование
var myEfficientFn = debounce(function() {
// All the taxing stuff you do
navig_fixit();
fxm();
if (navigation) {
navigation.classList.remove('active');
}
}, 200);
/* var myEfficientFn2 = debounce(function() {
// All the taxing stuff you do
fxm();
}, 250); */
window.addEventListener('resize', myEfficientFn);
/* window.addEventListener('scroll', myEfficientFn2); */
$(window).scroll(function() {
navig_fixit();
});
});
|
<script type="text/javascript">
//set the interval temporary variable
var setIntrVal = null;
var intrVal = 3000;
//lets get the slider elements
var slides = document.getElementById('slides'); //get the <ul id="slides">
var slide = document.getElementsByClassName('slide'); //get the <li class="slide">
var active = document.getElementsByClassName('active'); //get the <li class="slide active">
//lets set z-index properties to the slides
var j = 99; //lets initialize a higher value, change this if you need to
for (var i = 0; i < slide.length; i++) {
slide[i].style.zIndex = j;
j--;
}
var ywtSlider = {
init: function (newIntrVal) {
//pass the new interval value into the intrVal variable
if(newIntrVal) intrVal = newIntrVal;
//start cycle on init
ywtSlider.cycle();
},
cycle: function() {
//check if cycle is already started then clear the cycle
//this will clear the current interval
if(setIntrVal) clearInterval(setIntrVal);
//ok lets start another cycle
setIntrVal = setInterval(function () {
ywtSlider.slide('next');
}, intrVal);
//console.log(interVal);
},
slide: function (dir) {
//lets get the slide index number so we can set this to the slide
var nodeList = Array.prototype.slice.call(slides.children);
var itemIndex = nodeList.indexOf(active[active.length - 1]);
if (dir == 'back') {
//check and run if the direction is back
//if the direction is back
//lets remove the class starting from the current item to the last
for (k = itemIndex; k < slide.length; k++) {
slide[k].className = 'slide';
}
} else if (dir == 'next') {
//check and run if the direction is next
//lets check first the position of the current item
if (itemIndex + 1 < slide.length - 1) {
//if the next item index is not the last item lets set the 'active' class
//to the next item
slide[itemIndex + 1].className += ' active';
} else {
//if the next item supposed to be the last item, lets remove the 'active' class
//from all slide elements
for (var k = 0; k < slide.length; k++) {
slide[k].className = 'slide';
}
}
}
//continue the cycle
ywtSlider.cycle();
}
};
window.onload = function() {
ywtSlider.init(5000);
}
</script>
|
/**
* Created by Cai Kang Jie on 2017/7/31.
*/
import lazyLoading from './../../store/modules/routeConfig/lazyLoading'
export default {
name: 'UI Features',
expanded: false,
sidebarMeta: {
title: 'UI Features',
icon: 'ion-android-laptop',
order: 1
},
subMenu: [{
name: 'Panels',
path: '/ui/panels',
component: lazyLoading('ui/panels'),
sidebarMeta: {
title: 'Panels',
order: 100
}
}, {
name: 'Typography',
path: '/ui/typography',
component: lazyLoading('ui/typography'),
sidebarMeta: {
title: 'Typography',
order: 200
}
}, {
name: 'Grid',
path: '/ui/grid',
component: lazyLoading('ui/grid'),
sidebarMeta: {
title: 'Grid',
order: 400
}
}, {
name: 'Buttons',
path: '/ui/buttons',
component: lazyLoading('ui/buttons'),
sidebarMeta: {
title: 'Buttons',
order: 500
}
}, {
name: 'Progress Bars',
path: '/ui/progressBars',
component: lazyLoading('ui/progressBars'),
sidebarMeta: {
title: 'Progress Bars',
order: 600
}
}, {
name: 'Alerts',
path: '/ui/alerts',
component: lazyLoading('ui/alerts'),
sidebarMeta: {
title: 'Alerts',
order: 700
}
}]
}
|
'use strict';
function Memoized() {}
const memoize = (
// Create memoized function
fn // function, sync or async
// Returns: function, memoized
) => {
const cache = new Map();
const memoized = function(...args) {
const callback = args.pop();
const key = args[0];
const record = cache.get(key);
if (record) {
callback(record.err, record.data);
return;
}
fn(...args, (err, data) => {
memoized.add(key, err, data);
memoized.emit('memoize', key, err, data);
callback(err, data);
});
};
const fields = {
cache,
timeout: 0,
limit: 0,
size: 0,
maxSize: 0,
maxCount: 0,
events: {
timeout: null,
memoize: null,
overflow: null,
add: null,
del: null,
clear: null
}
};
Object.setPrototypeOf(memoized, Memoized.prototype);
return Object.assign(memoized, fields);
};
Memoized.prototype.clear = function() {
this.emit('clear');
this.cache.clear();
};
Memoized.prototype.add = function(key, err, data) {
this.emit('add', err, data);
this.cache.set(key, { err, data });
return this;
};
Memoized.prototype.del = function(key) {
this.emit('del', key);
this.cache.delete(key);
return this;
};
Memoized.prototype.get = function(key, callback) {
const record = this.cache.get(key);
callback(record.err, record.data);
return this;
};
Memoized.prototype.on = function(
eventName, // string
listener // function, handler
// on('memoize', function(err, data))
// on('add', function(key, err, data))
// on('del', function(key))
// on('clear', function())
) {
if (eventName in this.events) {
this.events[eventName] = listener;
}
};
Memoized.prototype.emit = function(
// Emit Collector events
eventName, // string
...args // rest arguments
) {
const event = this.events[eventName];
if (event) event(...args);
};
module.exports = {
memoize,
};
|
$(document).ready(function() {
$(".container").hide();
$(".container").fadeIn('5000');
$(".showcase-wrapper").hide();
$(".showcase-wrapper").fadeIn("slow");
});
/*
var toggle = false;
$('.nav-toggle').on('click', function () {
if (toggle == false) {
$('#sidebar-wrapper').stop().animate({
'left': '4px'
});
toggle = true;
} else {
$('#sidebar-wrapper').stop().animate({
'left': '250px'
});
toggle = false;
}
});
*/
$(function() {
$('.project-box>.row>.project-post').append('<span class="more-info">Click for more information</span>');
$('.project-box').click(function(e) {
if (e.target.tagName == "A" || e.target.tagName == "IMG") {
return true;
}
$(this).find('.more-info').toggle();
$(this).find('.post').slideToggle();
});
});
|
var jwt = require('jsonwebtoken');
/**
* Middleware
*/
module.exports = function(scullog){
return {
realIp: function* (next) {
this.req.ip = this.headers['x-forwarded-for'] || this.ip;
yield* next;
},
handelError: function* (next) {
try {
yield* next;
} catch (err) {
this.status = err.status || 500;
this.body = err.message;
C.logger.error(err.stack);
this.app.emit('error', err, this);
}
},
loadRealPath: function* (next) {
// router url format must be /api/(.*)
this.request.fPath = scullog.getFileManager().filePath(this.params[0], this.request.query.base);
C.logger.info(this.request.fPath);
yield* next;
},
checkPathExists: function* (next) {
// Must after loadRealPath
if (!(yield scullog.getFileManager().exists(this.request.fPath))) {
this.status = 404;
this.body = 'Path Not Exists!';
}
else {
yield* next;
}
},
checkBase: function* (next){
var base = this.request.query.base;
if (!!!base || scullog.getConfiguration().directory.indexOf(base) == -1) {
this.status = 400;
this.body = 'Invalid Base Location!';
} else {
yield* next;
}
},
checkPathNotExists: function* (next) {
// Must after loadRealPath
if (this.query.type != 'UPLOAD_FILE' && (yield scullog.getFileManager().exists(this.request.fPath))) {
this.status = 400;
this.body = 'Path Has Exists!';
}
else {
yield* next;
}
},
checkAccessCookie: function* (next) {
if (this.request.url.indexOf('/access') == -1) {
var accessJwt = this.cookies.get(scullog.getConfiguration().id);
if (accessJwt) {
try {
var decoded = jwt.verify(accessJwt, scullog.getConfiguration().secret);
} catch (e) {
this.append('access-expired', 'true');
}
} else if (this.request.header["access-role"] != "default") {
this.append('access-expired', 'true');
}
}
yield* next;
}
}
};
|
var Thermostat = function() {
this.temp = 20;
this.mode = 'power saving';
this.min = 10;
this.max = 25;
};
Thermostat.prototype.setPowerSaving = function(value) {
this.mode = (value ? 'power saving' : 'normal');
this.max = (value ? 25 : 32);
};
Thermostat.prototype.increase = function() {
if(this.temp < this.max) {this.temp++}
};
Thermostat.prototype.decrease = function() {
if(this.temp > this.min) {this.temp--}
};
Thermostat.prototype.resetTemp = function() {
this.temp = 20;
};
|
/* @flow */
import React from "react";
import PropTypes from "prop-types";
import {
Text,
TouchableOpacity,
Platform,
StyleSheet,
ScrollView,
PixelRatio,
View
} from "react-native";
import Modal from "react-native-modalbox";
type Props = {
styleContainer?: Object,
coverScreen?: boolean,
backButtonEnabled?: boolean,
height?: number,
title?: string,
options: Array<Object>,
refs: Function,
fontFamily?: string,
titleFontFamily?: string,
isOpen?: boolean,
cancelButtonIndex?: number,
itemDivider?: number
};
type State = void;
class BottomSheet extends React.PureComponent<Props, State> {
open: Function;
static propTypes = {
styleContainer: PropTypes.object,
coverScreen: PropTypes.bool,
backButtonEnabled: PropTypes.bool,
height: PropTypes.number,
title: PropTypes.string,
options: PropTypes.arrayOf(PropTypes.object).isRequired,
refs: PropTypes.func.isRequired,
fontFamily: PropTypes.string,
titleFontFamily: PropTypes.string,
isOpen: PropTypes.bool,
cancelButtonIndex: PropTypes.number,
itemDivider: PropTypes.number
};
renderOption = (options: Array<Object>) => {
return options.map((item, index) => {
return (
<View style={{ flexDirection: "column" }} key={index}>
<TouchableOpacity onPress={item.onPress}>
<View style={styles.item}>
{item.icon}
<Text
style={[styles.text, { fontFamily: this.props.fontFamily }]}
>
{item.title}
</Text>
</View>
</TouchableOpacity>
{this.props.itemDivider === index + 1 ? (
<View style={styles.separator} />
) : null}
</View>
);
});
};
renderTitle = () => {
if (!this.props.title) {
return;
}
return (
<Text style={[styles.title, { fontFamily: this.props.titleFontFamily }]}>
{this.props.title}
</Text>
);
};
render() {
return (
<Modal
style={[this.props.styleContainer, { height: this.props.height }]}
backButtonClose={this.props.backButtonEnabled}
position="bottom"
isOpen={this.props.isOpen}
ref={this.props.refs}
coverScreen={this.props.coverScreen}
>
<ScrollView style={styles.modal}>
{this.renderTitle()}
{this.renderOption(this.props.options)}
</ScrollView>
</Modal>
);
}
}
const styles = StyleSheet.create({
text: {
paddingHorizontal: 32,
fontFamily: "Roboto",
textAlignVertical: "center",
color: "#000",
opacity: 0.87
},
item: {
flexDirection: "row",
height: 48,
alignItems: "center",
paddingLeft: 16,
paddingRight: 16
},
title: {
height: 42,
color: "#000",
opacity: 0.54,
marginLeft: 16
},
modal: {
marginTop: 16
},
separator: {
height: 1 / PixelRatio.get(),
backgroundColor: "#CCCCCC",
marginTop: 7,
marginBottom: 8,
width: "100%"
}
});
export default BottomSheet;
|
var ParseIndex = require("../../index");
module.exports = function addRole(params) {
Parse.Cloud.define("addRole", (req, res) => {
if (req.params.masterKey === ParseIndex.config.masterKey) {
var roleName = req.params.roleName;
if (roleName.length > 2) {
var roleACL = new Parse.ACL();
roleACL.setPublicReadAccess(true);
var roleName = req.params.roleName;
var role = new Parse.Role(roleName, roleACL);
role.save().then(
ok => {
res.success(`Đã tạo thành công role : ${roleName} ! ✅`);
},
e => {
res.error(e.message);
}
);
} else {
res.error("⛔️ Tên role quá ngắn, yêu cần tối thiểu 3 ký tự ⛔️");
}
} else {
res.error("⛔️ Sai mật khẩu quản trị (masterKey) 🔑");
} //end check Masterkey
}); //end define
}; //end cloud
|
/* global describe, it, require */
'use strict';
// MODULES //
var // Expectation library:
chai = require( 'chai' ),
// Check whether an element is a finite number
isFiniteNumber = require( 'validate.io-finite' ),
// Module to be tested:
quantile = require( './../lib/array.js' );
// VARIABLES //
var expect = chai.expect,
assert = chai.assert;
// TESTS //
describe( 'array quantile', function tests() {
var validationData = require( './fixtures/array.json' ),
lambda = validationData.lambda;
it( 'should export a function', function test() {
expect( quantile ).to.be.a( 'function' );
});
it( 'should evaluate the quantile function', function test() {
var data, actual, expected, i;
data = validationData.data;
actual = new Array( data.length );
actual = quantile( actual, data, lambda );
expected = validationData.expected.map( function( d ) {
if (d === 'Inf' ) {
return Number.POSITIVE_INFINITY;
}
if ( d === '-Inf' ) {
return Number.NEGATIVE_INFINITY;
}
return d;
});
for ( i = 0; i < actual.length; i++ ) {
if ( isFiniteNumber( actual[ i ] ) && isFiniteNumber( expected[ i ] ) ) {
assert.closeTo( actual[ i ], expected[ i ], 1e-12 );
}
}
});
it( 'should return an empty array if provided an empty array', function test() {
assert.deepEqual( quantile( [], [], lambda ), [] );
});
it( 'should handle non-numeric values by setting the element to NaN', function test() {
var data, actual, expected;
data = [ true, null, [], {} ];
actual = new Array( data.length );
actual = quantile( actual, data, lambda );
expected = [ NaN, NaN, NaN, NaN ];
assert.deepEqual( actual, expected );
});
});
|
// JS specifically for the toolkit documentation
(function( $, window, document ) {
// Masthead
// -----------------------------------
var $window = $(window),
winTop = $window.scrollTop(),
$masthead = $('.masthead'),
$mastheadTitle = $masthead.find('.page-title'),
$pageTitle = $('.jumbotron h1'),
threshold = $pageTitle.offset().top - $masthead.outerHeight(),
fadeIn, fadeOut;
$window.scroll(function(){
winTop = $window.scrollTop();
fadeIn = -1 + ( winTop / threshold );
fadeOut = 2 - ( winTop / (threshold/2) );
// ^ OFFSET ^ FADESPEED
// Numbers further from Higher numbers increase
// zero will delay the the speed of the fade.
// opacity change.
$mastheadTitle.css( 'opacity', fadeIn );
$pageTitle.css( 'opacity', fadeOut );
});
}( window.jQuery, window, document ));
|
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'pagebreak', 'km', {
alt: 'បំបែកទំព័រ',
toolbar: 'បន្ថែមការបំបែកទំព័រមុនបោះពុម្ព'
} );
|
pinion.on("create.message.systemMessagesList", function(data) {
data.element.settings.data = pinion.messages.reverse();
});
pinion.backend.renderer.SystemMessageRenderer = (function($) {
var constr,
modules = pinion.php.modules;
// public API -- constructor
constr = function(settings, backend) {
var data = settings.data;
this.$element = $("<div class='pinion-backend-renderer-SystemMessageRenderer'></div>")
.append("<div class='pinion-colorfield-left'></div>")
.append("<div class='pinion-colorfield-right'></div>")
.addClass("pinion-"+data.type);
// ICON
if(data.module) {
$("<div class='pinion-moduleIcon'><img src='"+modules[data.module].icon+"' /></div>").appendTo(this.$element);
}
// MESSAGE
$("<div class='pinion-textWrapper'><div class='pinion-systemMessage'>"+data.text+"</div></div>").appendTo(this.$element);
}
// public API -- prototype
constr.prototype = {
constructor: pinion.backend.renderer.SystemMessageRenderer
}
return constr;
}(jQuery));
|
function solve(args){
var i,
array = [];
for(i = 0; i < args.length; i++){
array[i] = +args[i];
}
var sum = 0,
count = 0,
min = array[0],
max = array[0],
avg = 0;
for(i = 0; i < array.length; i++){
sum += array[i];
count++;
if(array[i] < min){
min = array[i];
}
if(array[i] > max){
max = array[i];
}
}
avg = sum / count;
console.log('min=' + Number(min).toFixed(2));
console.log('max=' + Number(max).toFixed(2));
console.log('sum=' + Number(sum).toFixed(2));
console.log('avg=' + Number(avg).toFixed(2));
}
solve(['2', '5', '1']);
|
define(["globals",
"ember",
"core_ext",
"ember-i18n",
"ember-bootstrap",
"select2",
"moment",
"mediaelement",
"jquery.highlight-search-results",
"jquery.autogrow-textarea",
"jquery.anchorlinks",
"jquery.hashtags",
"jquery.expander",
"bootstrap.file-input"], function(globals, Ember){
if (!globals.app) {
var options = {}
if (typeof DEBUG !== 'undefined') {
Ember.LOG_BINDINGS = true;
options = {
// log when Ember generates a controller or a route from a generic class
LOG_ACTIVE_GENERATION: true,
// log when Ember looks up a template or a view
LOG_VIEW_LOOKUPS: true,
LOG_TRANSITIONS: true
// LOG_TRANSITIONS_INTERNAL: true
}
}
App = Ember.Application.create(options);
// We need to delay initialization to load the rest of the application
App.deferReadiness()
globals.app = App
}
return globals.app;
});
|
import React from 'react';
import PropTypes from 'prop-types';
import './Todo.css';
const ARCHIVE_SHORTCUT_KEY_CODE = 65; // 'a'
const onArchiveShortcutPress = (handler, event) => {
if(event.keyCode === ARCHIVE_SHORTCUT_KEY_CODE) handler(event);
};
const Todo = ({text, completed, onClick, onDeleteClick}) => (
<li className={completed ? 'TodoList_Item-completed' : 'TodoList_Item'}>
<span
className={completed ? 'TodoList_Text-completed' : 'TodoList_Text'}
onClick={onClick}
onKeyDown={onArchiveShortcutPress.bind(null, onClick)}
role='button'
tabIndex='0'
>
{text}
</span>
<button className='Todo_Delete' onClick={onDeleteClick} style={{color: 'red'}}>
<svg width="26" height="26" viewBox="0 0 1024 1024">
<g style={{fill: '#b3b3b3'}}>
<path d="M640.35,91.169H536.971V23.991C536.971,10.469,526.064,0,512.543,0c-1.312,0-2.187,0.438-2.614,0.875
C509.491,0.438,508.616,0,508.179,0H265.212h-1.74h-1.75c-13.521,0-23.99,10.469-23.99,23.991v67.179H133.916
c-29.667,0-52.783,23.116-52.783,52.783v38.387v47.981h45.803v491.6c0,29.668,22.679,52.346,52.346,52.346h415.703
c29.667,0,52.782-22.678,52.782-52.346v-491.6h45.366v-47.981v-38.387C693.133,114.286,670.008,91.169,640.35,91.169z
M285.713,47.981h202.84v43.188h-202.84V47.981z M599.349,721.922c0,3.061-1.312,4.363-4.364,4.363H179.282
c-3.052,0-4.364-1.303-4.364-4.363V230.32h424.431V721.922z M644.715,182.339H129.551v-38.387c0-3.053,1.312-4.802,4.364-4.802
H640.35c3.053,0,4.365,1.749,4.365,4.802V182.339z"/>
<rect x="475.031" y="286.593" width="48.418" height="396.942"/>
<rect x="363.361" y="286.593" width="48.418" height="396.942"/>
<rect x="251.69" y="286.593" width="48.418" height="396.942"/>
</g>
</svg>
</button>
</li>
);
Todo.propTypes = {
text: PropTypes.string.isRequired,
completed: PropTypes.bool.isRequired,
onClick: PropTypes.func.isRequired,
onDeleteClick: PropTypes.func.isRequired
};
export default Todo;
|
module.exports = function(grunt){
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
watch: {
ctags: {
files: ['ctags'],
tasks: ['shell:ctags'],
options: {
nospawn: false,
},
}
},
shell: {
ctags: {
command: [
'cp ctags $HOME/.ctags',
'cp taglist.vim $HOME/.vim/bundle/taglist/plugin/taglist.vim',
'ctags -f - --format=2 --excmd=pattern --fields=nks '+
'--sort=no --language-force=css --css-types=cis test.css'
].join('&&')
},
release: {
command: 'cp ctags $HOME/.ctags',
},
options:{
stdout:true
}
},
});
grunt.loadNpmTasks('grunt-shell');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', ['watch']);
grunt.registerTask('release', ['shell:release']);
};
|
var TreeNode = require('../dist/treenode').TreeNode;
describe("TreeNode Class", function() {
var tree;
var data = [
{
name: 'I am ROOT',
status: 'initial'
},
{
name: 'Node 1',
status: 'initial'
},
{
name: 'Node 2',
status: 'initial'
},
{
name: 'Node 3',
status: 'initial'
}
];
beforeEach(function() {
tree = new TreeNode(data[0]);
});
it("should allow a child to be added and return as a TreeNode object", function() {
var leaf = tree.addChild(data[1]);
expect(leaf.data.name).toEqual(data[1].name);
});
it("should return its root", function() {
expect(tree.root().data.name).toEqual(data[0].name);
var leaf = tree.addChild(data[1]);
expect(leaf.root().data.name).toEqual(data[0].name)
});
it("should find data", function() {
tree.addChild(data[1]);
tree.addChild(data[2]);
expect(tree.find(data[1]).data).toEqual(data[1]);
expect(tree.find(data[2]).data).toEqual(data[2]);
expect(tree.find(data[3])).toBe(null);
});
it("should find leaves", function() {
tree.addChild(data[1]);
var intermediateNode = tree.addChild(data[2]);
intermediateNode.addChild(data[3]);
var leaves = tree.leaves();
// we've added 3 nodes, but only two are leaves
expect(leaves.length).toBe(2);
});
it("should execute forEach() callback on all child nodes", function() {
var intermediateNode = tree.addChild(data[1]);
var childNode = intermediateNode.addChild(data[2]);
var grandchildNode = childNode.addChild(data[3]);
intermediateNode.forEach(function(node) {
node.data.status = 'updated';
});
expect(tree.root().data.status).toBe('initial');
expect(intermediateNode.data.status).toBe('updated');
expect(childNode.data.status).toBe('updated');
expect(grandchildNode.data.status).toBe('updated');
});
it("should return the number of children", function() {
expect(tree.numChildren()).toBe(0);
tree.addChild(data[1]);
expect(tree.numChildren()).toBe(1);
var intermediateNode = tree.addChild(data[2]);
expect(tree.numChildren()).toBe(2);
intermediateNode.addChild(data[3]);
expect(tree.numChildren()).toBe(2);
expect(intermediateNode.numChildren()).toBe(1);
});
});
|
// inheritientence!!
function Pet() {
this.animal = "";
this.name="";
this.setAnimal = function(newAnimal){
this.animal = newAnimal;
}
this.setName = function(newName){
this.name = newName;
}
}
var myCat = new Pet();
myCat.setAnimal = "cat";
myCat.setName = "Sylvester";
function Dog(){
this.breed ="";
this.setBread = function(newBreed){
this.breed = newBreed;
}
}
Dog.prototype = new Pet();
// Now I can access the propertites and methods of Pet in addition to Dog
var myDog = new Dog();
myDog.setName("Alan");
myDog.setBreed("Greyhound");
alert(myDog.name + "is a " myDog.breed);
|
//= require fluent/admin/admin.js
|
'use strict'
import ObjectUtils from 'es-common-core/object-utils';
import Asset from 'rpgmv-asset-manager-core/datas/asset';
import AssetFileDeserializer from 'rpgmv-asset-manager-core/datas/asset-file-deserializer';
/**
* Asset Manager MV
* アセットデシリアライザ
*
* @since 2016/01/03
* @author RaTTiE
*/
export default class AssetDeserializer {
/**
* オブジェクトのデシリアライズを行う。
*
* @param data デシリアライズに使用するデータ。
* @return デシリアライズしたインスタンス。
*/
static deserialize(data) {
if (data == null) return null;
var asset = new Asset();
var files = [];
for (var i = 0; i < data.files.length; i++) {
files.push(AssetFileDeserializer.deserialize(data.files[i]));
}
ObjectUtils.setFields(asset, {
name: data.name,
type: data.type,
files: files,
using: data.using,
checked: data.checked,
selected: data.selected
});
return asset;
}
}
|
// Use require('arpjs') if youre running this example elsewhere.
var arp = require('../')
// arp.setInterface('en0');
arp.send({
'op': 'request',
'src_ip': '10.105.50.100',
'dst_ip': '10.105.50.1',
'src_mac': '8f:3f:20:33:54:44',
'dst_mac': 'ff:ff:ff:ff:ff:11'
})
|
class AddAktModalController{
constructor(API, $uibModal, $state,$timeout){
'ngInject';
let vm=this;
vm.API=API;
vm.program=vm.resolve.program;
vm.programs=vm.resolve.programs;
vm.data={
program:vm.program.id,
title:null,
date:new Date()
};
vm.dateOptions = {
altInputFormats: ['yyyy-MM-dd', 'dd.MM.yyyy'],
formatDay: 'dd',
formatMonth: 'MM',
formatYear: 'yyyy',
minDate: new Date(),
startingDay: 1
};
vm.date = {
opened: false
};
vm.openCalendar=()=>{
vm.date.opened=true;
};
vm.close=()=>{
this.modalInstance.dismiss('cancel');
};
vm.add=()=>{
let calendar = this.API.all('akt');
calendar.post({
program:vm.data.program,
title:vm.data.title,
date:moment(vm.data.date).format('YYYY-MM-DD'),
}).then((response) => {
vm.success=true;
$timeout( ()=>{
$state.reload();
}, 300);
$timeout(()=> {
vm.close();
}, 500);
},
(response) => {
vm.message=response.data.uniqemessage;
vm.errors=response.data.errors;
});
}
//
}
$onInit(){
}
}
export const AddAktModalComponent = {
templateUrl: './views/app/components/addAktModal/addAktModal.component.html',
controller: AddAktModalController,
controllerAs: 'vm',
bindings: {
modalInstance: "<",
resolve: "<"
}
}
|
// A DOM operation helper. Append an Element to a parent
export default function append(parent, ...children) {
// Always select the first item of a list, similarly to jQuery
if (Array.isArray(parent)) {
parent = parent[0]
}
children.forEach(parent.appendChild, parent)
return parent
}
|
///
// Dependencies
///
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import classNames from 'classnames';
import isString from 'lodash/isString';
import * as types from './types';
import Panel from 'react-bootstrap/lib/Panel';
import Button from 'react-bootstrap/lib/Button';
import ExpanderButton from '../elements/ExpanderButton';
import Icon from '../elements/Icon';
import Scrollable from '../elements/Scrollable';
import * as actions from './actions';
import * as formsActions from '../forms/actions';
///
// View
///
class OverviewPanelItemView extends Component {
///
// Construction / Hooks
///
constructor(props) {
super(props);
this.onToggle = this.onToggle.bind(this);
this.onSelect = this.onSelect.bind(this);
this.onShowForm = this.onShowForm.bind(this);
}
///
// Event handling
///
onToggle() {
this.props.toggleItem(this.props.name);
}
onSelect() {
this.props.selectItem(this.props.name);
}
onShowForm() {
this.props.clearForm(this.props.name);
this.props.showForm(this.props.name);
}
///
// Rendering
///
renderIcon(icon) {
if(! icon) return '';
if(isString(icon)) {
icon = (
<Icon name={icon} />
);
}
return (
<div className="item-icon">
{icon}
</div>
);
}
render() {
const isSelected = this.props.selected === this.props.name;
const isExpanded = isSelected || this.props.overview.getIn(
['panels', this.props.name, 'isExpanded']
);
const itemClassName = classNames('overview-panel-item', {
selected: isSelected,
expanded: isExpanded,
});
return (
<div className={itemClassName}>
<div className="item-header">
<ExpanderButton
expanded={isExpanded}
disabled={isSelected}
onClick={this.onToggle}
/>
<h4
className="item-title"
onClick={this.onSelect}
>
{this.renderIcon(this.props.icon)}
{this.props.title}
</h4>
<Button
className="add-button"
onClick={this.onShowForm}
>
<Icon name="plus" />
</Button>
</div>
<Panel
collapsible expanded={isExpanded}
className="item-content"
>
{this.props.notifications}
<Scrollable>
{this.props.children}
</Scrollable>
</Panel>
</div>
);
}
}
OverviewPanelItemView.propTypes = {
name: PropTypes.string.isRequired,
icon: PropTypes.node,
title: PropTypes.node.isRequired,
selected: PropTypes.string,
notifications: PropTypes.node,
overview: types.Overview.isRequired,
toggleItem: PropTypes.func.isRequired,
selectItem: PropTypes.func.isRequired,
clearForm: PropTypes.func.isRequired,
showForm: PropTypes.func.isRequired,
children: PropTypes.node,
};
export { OverviewPanelItemView };
///
// Container
///
function mapStateToProps(state) {
return {
selected: state.getIn(['overview', 'root', 'selected']),
overview: state.get('overview'),
};
}
function mapDispatchToProps(dispatch) {
return {
toggleItem: (name) => dispatch(actions.toggleItem(name)),
selectItem: (name) => dispatch(actions.selectItem(name)),
clearForm: (name) => dispatch(formsActions.clearForm(name)),
showForm: (name) => dispatch(formsActions.showForm(name)),
};
}
const connector = connect(
mapStateToProps,
mapDispatchToProps
);
export default connector(OverviewPanelItemView);
|
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h("path", {
d: "M19.5 3.5L18 2l-1.5 1.5L15 2l-1.5 1.5L12 2l-1.5 1.5L9 2 7.5 3.5 6 2 4.5 3.5 3 2v20l1.5-1.5L6 22l1.5-1.5L9 22l1.5-1.5L12 22l1.5-1.5L15 22l1.5-1.5L18 22l1.5-1.5L21 22V2l-1.5 1.5zM19 19.09H5V4.91h14v14.18zM6 15h12v2H6zm0-4h12v2H6zm0-4h12v2H6z"
}), 'ReceiptOutlined');
|
'use strict';
/* App Module */
var granuleApp = angular.module('granuleApp', [ 'ngRoute', 'angularBasicAuth', 'granuleControllers', 'granuleServices']);
granuleApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/login', {
templateUrl: 'partials/login.html',
controller: 'LoginCtrl'
}).
when('/activity', {
templateUrl: 'partials/activity-list.html',
controller: 'ActivityListCtrl'
}).
when('/activity/:activityId', {
templateUrl: 'partials/activity-detail.html',
controller: 'ActivityDetailCtrl'
}).
otherwise({
redirectTo: '/login'
});
}]);
|
import * as lamb from "../..";
import { nonFunctions, wannabeEmptyArrays } from "../../__tests__/commons";
describe("count / countBy", function () {
var getCity = lamb.getKey("city");
var persons = [
{ name: "Jane", surname: "Doe", age: 12, city: "New York" },
{ name: "John", surname: "Doe", age: 40, city: "New York" },
{ name: "Mario", surname: "Rossi", age: 18, city: "Rome" },
{ name: "Paolo", surname: "Bianchi", age: 15 }
];
var personsCityCount = {
"New York": 2,
Rome: 1,
undefined: 1
};
var personsAgeGroupCount = {
under20: 3,
over20: 1
};
var splitByAgeGroup = function (person, idx, list) {
expect(list).toBe(persons);
expect(persons[idx]).toBe(person);
return person.age > 20 ? "over20" : "under20";
};
it("should count the occurences of the key generated by the provided iteratee", function () {
expect(lamb.count(persons, getCity)).toEqual(personsCityCount);
expect(lamb.countBy(getCity)(persons)).toEqual(personsCityCount);
expect(lamb.count(persons, splitByAgeGroup)).toEqual(personsAgeGroupCount);
expect(lamb.countBy(splitByAgeGroup)(persons)).toEqual(personsAgeGroupCount);
});
it("should work with array-like objects", function () {
var result = {
h: 1, e: 1, l: 3, o: 2, " ": 1, w: 1, r: 1, d: 1
};
expect(lamb.count("hello world", lamb.identity)).toEqual(result);
expect(lamb.countBy(lamb.identity)("hello world")).toEqual(result);
});
it("should throw an exception if the iteratee isn't a function", function () {
nonFunctions.forEach(function (value) {
expect(function () { lamb.count(persons, value); }).toThrow();
expect(function () { lamb.countBy(value)(persons); }).toThrow();
});
expect(function () { lamb.count(persons); }).toThrow();
expect(function () { lamb.countBy()(persons); }).toThrow();
});
it("should consider deleted or unassigned indexes in sparse arrays as `undefined` values", function () {
var arr = [1, , 3, void 0, 5]; // eslint-disable-line no-sparse-arrays
var result = { false: 3, true: 2 };
expect(lamb.count(arr, lamb.isUndefined)).toEqual(result);
expect(lamb.countBy(lamb.isUndefined)(arr)).toEqual(result);
});
it("should throw an exception if called without the data argument", function () {
expect(lamb.count).toThrow();
expect(lamb.countBy(lamb.identity)).toThrow();
});
it("should throw an exception if supplied with `null` or `undefined`", function () {
expect(function () { lamb.count(null, lamb.identity); }).toThrow();
expect(function () { lamb.count(void 0, lamb.identity); }).toThrow();
expect(function () { lamb.countBy(lamb.identity)(null); }).toThrow();
expect(function () { lamb.countBy(lamb.identity)(void 0); }).toThrow();
});
it("should treat every other value as an empty array and return an empty object", function () {
wannabeEmptyArrays.forEach(function (value) {
expect(lamb.countBy(lamb.identity)(value)).toEqual({});
expect(lamb.count(value, lamb.identity)).toEqual({});
});
});
});
|
import React from 'react';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
// import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
export default class NewTaskDialog extends React.Component {
state = {
open: false,
valid: false,
title: '',
description: ''
};
handleOpen = () => {
this.setState({open: true});
};
handleClose = () => {
this.resetDialog();
this.setState({open: false});
};
resetDialog = () => {
this.setState({title: '', description: '', valid: false})
};
handleCreateTask = (e) => {
e.preventDefault();
this.props.onCreateTask({
title: this.state.title,
description: this.state.description
});
this.handleClose();
};
onTitleChange = (e) => {
this.setState({ title: e.target.value });
this.validate();
};
onDescriptionChange = (e) => {
this.setState({ description: e.target.value });
this.validate();
};
validate = () => {
if(this.state.title && this.state.description) {
this.setState({valid: true});
}
};
render() {
const actions = [
<FlatButton
label="Cancel"
primary={true}
onTouchTap={this.handleClose}
/>,
<FlatButton
label="Create Task"
primary={true}
disabled={!this.state.valid}
onTouchTap={this.handleCreateTask}
/>,
];
return (
<div>
<FlatButton label="New Task" onTouchTap={this.handleOpen} />
<Dialog
title="Create New Task"
actions={actions}
modal={true}
open={this.state.open}>
<TextField id="task-title"
hintText="Title"
value={this.state.title}
onChange={this.onTitleChange}/>
<br/>
<TextField id="task-description"
hintText="Description"
value={this.state.description}
onChange={this.onDescriptionChange}/>
<br/>
</Dialog>
</div>
);
}
}
|
/*globals describe, afterEach, beforeEach, it*/
var should = require('should'),
sinon = require('sinon'),
Promise = require('bluebird'),
// Stuff we're testing
db = require('../../server/data/db'),
errors = require('../../server/errors'),
exporter = require('../../server/data/export'),
schema = require('../../server/data/schema'),
settings = require('../../server/api/settings'),
schemaTables = Object.keys(schema.tables),
sandbox = sinon.sandbox.create();
require('should-sinon');
describe('Exporter', function () {
var versionStub, tablesStub, queryMock, knexMock, knexStub;
afterEach(function () {
sandbox.restore();
knexStub.restore();
});
describe('doExport', function () {
beforeEach(function () {
versionStub = sandbox.stub(schema.versioning, 'getDatabaseVersion').returns(new Promise.resolve('004'));
tablesStub = sandbox.stub(schema.commands, 'getTables').returns(schemaTables);
queryMock = {
select: sandbox.stub()
};
knexMock = sandbox.stub().returns(queryMock);
// this MUST use sinon, not sandbox, see sinonjs/sinon#781
knexStub = sinon.stub(db, 'knex', {get: function () { return knexMock; }});
});
it('should try to export all the correct tables', function (done) {
// Setup for success
queryMock.select.returns(new Promise.resolve({}));
// Execute
exporter.doExport().then(function (exportData) {
// No tables, less the number of excluded tables
var expectedCallCount = schemaTables.length - 4;
should.exist(exportData);
versionStub.should.be.calledOnce();
tablesStub.should.be.calledOnce();
knexStub.get.should.be.called();
knexMock.should.be.called();
queryMock.select.should.be.called();
knexMock.should.have.callCount(expectedCallCount);
queryMock.select.should.have.callCount(expectedCallCount);
knexMock.getCall(0).should.be.calledWith('posts');
knexMock.getCall(1).should.be.calledWith('users');
knexMock.getCall(2).should.be.calledWith('roles');
knexMock.getCall(3).should.be.calledWith('roles_users');
knexMock.getCall(4).should.be.calledWith('permissions');
knexMock.getCall(5).should.be.calledWith('permissions_users');
knexMock.getCall(6).should.be.calledWith('permissions_roles');
knexMock.getCall(7).should.be.calledWith('permissions_apps');
knexMock.getCall(8).should.be.calledWith('settings');
knexMock.getCall(9).should.be.calledWith('tags');
knexMock.getCall(10).should.be.calledWith('posts_tags');
knexMock.getCall(11).should.be.calledWith('apps');
knexMock.getCall(12).should.be.calledWith('app_settings');
knexMock.getCall(13).should.be.calledWith('app_fields');
knexMock.should.not.be.calledWith('clients');
knexMock.should.not.be.calledWith('client_trusted_domains');
knexMock.should.not.be.calledWith('refreshtokens');
knexMock.should.not.be.calledWith('accesstokens');
done();
}).catch(done);
});
it('should catch and log any errors', function (done) {
// Setup for failure
var errorStub = sandbox.stub(errors, 'logAndThrowError');
queryMock.select.returns(new Promise.reject({}));
// Execute
exporter.doExport().then(function (exportData) {
should.not.exist(exportData);
errorStub.should.be.calledOnce();
done();
}).catch(done);
});
});
describe('exportFileName', function () {
it('should return a correctly structured filename', function (done) {
var settingsStub = sandbox.stub(settings, 'read').returns(
new Promise.resolve({settings: [{value: 'testblog'}]})
);
exporter.fileName().then(function (result) {
should.exist(result);
settingsStub.should.be.calledOnce();
result.should.match(/^testblog\.ghost\.[0-9]{4}-[0-9]{2}-[0-9]{2}\.json$/);
done();
}).catch(done);
});
it('should return a correctly structured filename if settings is empty', function (done) {
var settingsStub = sandbox.stub(settings, 'read').returns(
new Promise.resolve()
);
exporter.fileName().then(function (result) {
should.exist(result);
settingsStub.should.be.calledOnce();
result.should.match(/^ghost\.[0-9]{4}-[0-9]{2}-[0-9]{2}\.json$/);
done();
}).catch(done);
});
it('should return a correctly structured filename if settings errors', function (done) {
var settingsStub = sandbox.stub(settings, 'read').returns(
new Promise.reject()
);
exporter.fileName().then(function (result) {
should.exist(result);
settingsStub.should.be.calledOnce();
result.should.match(/^ghost\.[0-9]{4}-[0-9]{2}-[0-9]{2}\.json$/);
done();
}).catch(done);
});
});
});
|
'use strict';
const Sites = require('./reducers/sites-list');
const Site = require('./reducers/site-form');
const User = require('./reducers/user');
const Delete = require('./reducers/delete');
const Count = require('./reducers/count');
const Redux = require('redux');
module.exports = Redux.createStore(
Redux.combineReducers({
delete: Delete,
sites: Sites,
site: Site,
count: Count,
user: User
})
);
|
/**
* Linked lists utilities
* Algorithm author: Harold Gonzalez
* Twitter: @haroldcng
* Questions: harold.gonzalez.tech@gmail.com
*/
'use strict';
/**
* Definition of Linked List Node Data Structure
*/
module.exports.ListNode = function(v){
this.val = v;
this.next = null;
};
/**
* Prints a linked list from the given node to the end
*/
module.exports.printLinkedList = (node) => {
while(node !== null){
process.stdout.write(node.val + " -> ");
node = node.next;
}
console.log("NULL");
};
|
'use strict';
const Support = require('../support');
const DataTypes = require('../../../lib/data-types');
const chai = require('chai');
const sinon = require('sinon');
const expect = chai.expect;
const current = Support.sequelize;
const _ = require('lodash');
describe(Support.getTestDialectTeaser('Model'), () => {
describe('update', () => {
beforeEach(async function() {
this.Account = this.sequelize.define('Account', {
ownerId: {
type: DataTypes.INTEGER,
allowNull: false,
field: 'owner_id'
},
name: {
type: DataTypes.STRING
}
});
await this.Account.sync({ force: true });
});
it('should only update the passed fields', async function() {
const account = await this.Account
.create({ ownerId: 2 });
await this.Account.update({
name: Math.random().toString()
}, {
where: {
id: account.get('id')
}
});
});
describe('skips update query', () => {
it('if no data to update', async function() {
const spy = sinon.spy();
await this.Account.create({ ownerId: 3 });
const result = await this.Account.update({
unknownField: 'haha'
}, {
where: {
ownerId: 3
},
logging: spy
});
expect(result[0]).to.equal(0);
expect(spy.called, 'Update query was issued when no data to update').to.be.false;
});
it('skips when timestamps disabled', async function() {
const Model = this.sequelize.define('Model', {
ownerId: {
type: DataTypes.INTEGER,
allowNull: false,
field: 'owner_id'
},
name: {
type: DataTypes.STRING
}
}, {
timestamps: false
});
const spy = sinon.spy();
await Model.sync({ force: true });
await Model.create({ ownerId: 3 });
const result = await Model.update({
unknownField: 'haha'
}, {
where: {
ownerId: 3
},
logging: spy
});
expect(result[0]).to.equal(0);
expect(spy.called, 'Update query was issued when no data to update').to.be.false;
});
});
it('changed should be false after reload', async function() {
const account0 = await this.Account.create({ ownerId: 2, name: 'foo' });
account0.name = 'bar';
expect(account0.changed()[0]).to.equal('name');
const account = await account0.reload();
expect(account.changed()).to.equal(false);
});
it('should ignore undefined values without throwing not null validation', async function() {
const ownerId = 2;
const account0 = await this.Account.create({
ownerId,
name: Math.random().toString()
});
await this.Account.update({
name: Math.random().toString(),
ownerId: undefined
}, {
where: {
id: account0.get('id')
}
});
const account = await this.Account.findOne();
expect(account.ownerId).to.be.equal(ownerId);
});
if (_.get(current.dialect.supports, 'returnValues.returning')) {
it('should return the updated record', async function() {
const account = await this.Account.create({ ownerId: 2 });
const [, accounts] = await this.Account.update({ name: 'FooBar' }, {
where: {
id: account.get('id')
},
returning: true
});
const firstAcc = accounts[0];
expect(firstAcc.ownerId).to.be.equal(2);
expect(firstAcc.name).to.be.equal('FooBar');
});
}
if (current.dialect.supports['LIMIT ON UPDATE']) {
it('should only update one row', async function() {
await this.Account.create({
ownerId: 2,
name: 'Account Name 1'
});
await this.Account.create({
ownerId: 2,
name: 'Account Name 2'
});
await this.Account.create({
ownerId: 2,
name: 'Account Name 3'
});
const options = {
where: {
ownerId: 2
},
limit: 1
};
const account = await this.Account.update({ name: 'New Name' }, options);
expect(account[0]).to.equal(1);
});
}
});
});
|
// @flow
import React, { Component } from 'react'
import { View, StatusBar } from 'react-native'
import NavigationRouter from '../Navigation/NavigationRouter'
import { connect } from 'react-redux'
import StartupActions from '../Redux/StartupRedux'
import ReduxPersist from '../Config/ReduxPersist'
// Styles
import styles from './Styles/RootContainerStyle'
class RootContainer extends Component {
componentDidMount () {
// if redux persist is not active fire startup action
if (!ReduxPersist.active) {
this.props.startup()
}
}
render () {
return (
<View style={styles.applicationView}>
<StatusBar barStyle='light-content' />
<NavigationRouter />
</View>
)
}
}
const mapStateToDispatch = (dispatch) => ({
startup: () => dispatch(StartupActions.startup())
})
export default connect(null, mapStateToDispatch)(RootContainer)
|
document.onmousemove = moveDefence;
var width = 1200;
var height = 600;
var ballPerSeconds = 1;
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var allBalls = new Array();
var defence = {
start: 0,
end: (Math.PI) / 3,
jiao: 0
};
var HP = 100;
var draw = drawInGame;
var score = 0;
function moveDefence(evt) {
if (!evt) {
evt = window.event
}
var xx = evt.clientX - width * 0.5;
var yy = evt.clientY - height * 0.5;
if (yy >= 0 && xx >= 0) {
defence.jiao = Math.atan(yy / xx)
}
if (yy >= 0 && xx < 0) {
defence.jiao = Math.PI + Math.atan(yy / xx)
}
if (yy < 0 && xx >= 0) {
defence.jiao = Math.atan(yy / xx)
}
if (yy < 0 && xx < 0) {
defence.jiao = Math.atan(yy / xx) - Math.PI
}
defence.start = defence.jiao - (Math.PI / 3);
defence.end = defence.jiao + (Math.PI / 3)
}
function Ball() {
if (Math.random() <= 0.25) {
this.x = 2;
this.y = height * Math.random()
}
if ((Math.random() > 0.25) && (Math.random() <= 0.5)) {
this.x = 998;
this.y = height * Math.random()
}
if ((Math.random() < 0.75) && (Math.random() > 0.5)) {
this.y = 798;
this.x = width * Math.random()
}
if (Math.random() >= 0.75) {
this.y = 2;
this.x = width * Math.random()
}
this.act = function() {
this.x = this.x + 10;
this.y = this.y + 10
}
}
function create() {
var cre;
for (cre = 0; cre < ballPerSeconds; cre++) {
var ball = new Ball();
allBalls.push(ball)
}
}
function drawEnd() {
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, width, height);
ctx.font = "Bold 60px Arial";
ctx.textAlign = "center";
ctx.fillStyle = "#FFFFFF";
ctx.fillText("游戏结束", width * 0.5, height * 0.5);
ctx.font = "Bold 40px Arial";
ctx.textAlign = "center";
ctx.fillStyle = "#FFFFFF";
ctx.fillText("得分:", width * 0.5, height * 0.5 + 60);
ctx.font = "Bold 40px Arial";
ctx.textAlign = "center";
ctx.fillStyle = "#FFFFFF";
ctx.fillText(score.toString(), width * 0.5, height * 0.5 + 100)
}
function drawInGame() {
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, width, height);
var i;
ctx.beginPath();
ctx.arc(width * 0.5, height * 0.5, 60, defence.start, defence.end, false);
ctx.fillStyle = "#00A67C";
ctx.fill();
ctx.beginPath();
ctx.arc(width * 0.5, height * 0.5, 56, 0, Math.PI * 2, true);
ctx.fillStyle = "#000000";
ctx.fill();
ctx.beginPath();
ctx.arc(width * 0.5, height * 0.5, 5, 0, Math.PI * 2, true);
ctx.fillStyle = "#B7F200";
ctx.fill();
for (i = 0; i < allBalls.length; i++) {
ctx.beginPath();
ctx.arc(allBalls[i].x, allBalls[i].y, 5, 0, Math.PI * 2, true);
ctx.fillStyle = "#EF002A";
ctx.fill()
}
ctx.fillStyle = "#DE0052";
ctx.fillRect(0, 0, HP * 3, 25);
ctx.font = "Bold 20px Arial";
ctx.textAlign = "left";
ctx.fillStyle = "#FFFFFF";
ctx.fillText(HP.toString(), 20, 20);
ctx.font = "Bold 20px Arial";
ctx.textAlign = "left";
ctx.fillStyle = "#EE6B9C";
scoretext = "得分:" + score.toString();
ctx.fillText(scoretext, 20, 50)
}
function act() {
for (var i = 0; i < allBalls.length; i++) {
var ax = width * 0.5 - allBalls[i].x;
var by = height * 0.5 - allBalls[i].y;
var movex = 1.5 * ax * (1.5 / Math.sqrt(ax * ax + by * by));
var movey = 1.5 * by * (1.5 / Math.sqrt(ax * ax + by * by));
allBalls[i].x = allBalls[i].x + movex;
allBalls[i].y = allBalls[i].y + movey
}
}
function check() {
for (var i = 0; i < allBalls.length; i++) {
var ax = allBalls[i].x - width * 0.5;
var by = allBalls[i].y - height * 0.5;
var distance = Math.sqrt(ax * ax + by * by);
var angel;
if (by >= 0 && ax >= 0) {
angel = Math.atan(by / ax)
}
if (by >= 0 && ax < 0) {
angel = Math.PI + Math.atan(by / ax)
}
if (by < 0 && ax >= 0) {
angel = Math.atan(by / ax)
}
if (by < 0 && ax < 0) {
angel = Math.atan(by / ax) - Math.PI
}
if (distance <= 63 && distance >= 57 && ((angel > defence.start && angel < defence.end) || (angel + 2 * Math.PI > defence.start && angel + 2 * Math.PI < defence.end) || (angel - 2 * Math.PI > defence.start && angel - 2 * Math.PI < defence.end))) {
allBalls.splice(i, 1);
if (HP < 100)
HP = HP + 2;
score = score + Math.floor(1000 / HP)
}
if (distance <= 5) {
allBalls.splice(i, 1);
HP = HP - 10;
if (HP < 0) {
draw = drawEnd;
window.clearInterval(int)
}
}
}
}
function start() {
act();
check();
draw()
}
var int = setInterval("start()", 30);
setInterval("create()", 500);
|
var socketio = require('socket.io');
exports.listen = function( server, Manager ) {
var io = socketio.listen(server);
Manager.findAllUsers(function ( err, data ) {
if(!err){
if(data.length === 0){
Manager.addUser({'login': 'madzia26', 'password': 'qwertyuiop', 'id': new Date().getTime() }, function ( err, data ) {
if(!err){
console.log('first user added');
}
});
}
}
});
io.sockets.on('connection', function ( client ) {
'use strict';
// console.log('socket.io connected');
// console.log(client.id);
//init
client.on('init', function () {
Manager.findAllUsers(function ( err, data ) {
if(!err){
var res = {
'users': [],
'categories': []
};
for(var i = 0; i < data.length; i++){
res.users.push({'login': data[i].login, "id": data[i].id});
}
Manager.findAllCategories( function ( err, data) {
if(!err){
res.categories = data;
Manager.findAllCds( function ( err, data) {
if(!err){
res.cds = data;
client.emit('init', res);
// console.log('init');
}
});
}
});
}
});
});
//users
client.on('addUser', function ( user ) {
Manager.addUser(user, function ( err, data ) {
if(!err){
// var token = new Date().getTime();
// User.signin(data.login, data.id, token);
client.emit('add', {'coll': 'users', 'data': {'login': data.login, 'id': data.id} });
client.broadcast.emit('add', {'coll': 'users', 'data': {'login': data.login, 'id': data.id} });
client.emit('auth', {'login': data.login, 'id': data.id });
}
});
});
//categories
client.on('addCategory', function ( data ) {
if( data.user.id === data.data.owner ) {
var category = { 'name': data.data.name, 'owner': data.data.owner };
Manager.addCategory(category, function ( err, data ) {
if(!err){
client.emit('add', {'coll': 'categories', 'data': category });
client.broadcast.emit('add', {'coll': 'categories', 'data': category });
}
});
}
});
client.on('editCategory', function ( data ) {
if( data.user.id === data.data.owner ) {
var category = data.data;
Manager.editCategory(category, function ( err, data ) {
if(!err){
client.emit('update', {'coll': 'categories', 'data': category });
client.broadcast.emit('update', {'coll': 'categories', 'data': category });
}
});
}
});
client.on('rmCategory', function ( data ) {
if( data.user.id === data.data.owner ) {
var category = data.data;
Manager.rmCategory(category, function ( err, data ) {
if(!err){
client.emit('remove', {'coll': 'categories', 'data': category });
client.broadcast.emit('remove', {'coll': 'categories', 'data': category });
}
});
}
});
//cds
client.on('addCd', function ( data ) {
if( data.user.id === data.data.owner ) {
var cd = { 'name': data.data.name, 'owner': data.data.owner,
'category': data.data.category, 'url': data.data.url };
Manager.addCd(cd, function ( err, data ) {
if(!err){
client.emit('add', {'coll': 'cds', 'data': cd });
client.broadcast.emit('add', {'coll': 'cds', 'data': cd });
}
});
}
});
client.on('editCd', function ( data ) {
if( data.user.id === data.data.owner ) {
var cd = data.data;
Manager.editCd(cd, function ( err, data ) {
if(!err){
client.emit('update', {'coll': 'cds', 'data': cd });
client.broadcast.emit('update', {'coll': 'cds', 'data': cd });
}
});
}
});
client.on('rmCd', function ( data ) {
if( data.user.id === data.data.owner ) {
var cd = data.data;
Manager.rmCd(cd, function ( err, data ) {
if(!err){
client.emit('remove', {'coll': 'cds', 'data': cd });
client.broadcast.emit('remove', {'coll': 'cds', 'data': cd });
}
});
}
});
});
};
|
var Document = require('pelias-model').Document;
var docs = {};
docs.named = new Document('item1',1);
docs.named.setName('default','poi1');
docs.unnamed = new Document('item2',2); // no name
docs.unnamedWithAddress = new Document('item3',3);
docs.unnamedWithAddress.setCentroid({lat:3,lon:3});
docs.unnamedWithAddress.address = {
number: '10', street: 'Mapzen pl'
};
docs.namedWithAddress = new Document('item4',4);
docs.namedWithAddress.setName('default','poi4');
docs.namedWithAddress.setCentroid({lat:4,lon:4});
docs.namedWithAddress.address = {
number: '11', street: 'Sesame st'
};
docs.invalidId = new Document('item5',5);
docs.invalidId._meta.id = undefined; // unset the id
docs.invalidId.setCentroid({lat:5,lon:5});
docs.invalidId.address = {
number: '12', street: 'Old st'
};
docs.completeDoc = new Document('item6',6);
docs.completeDoc.address = {
number: '13', street: 'Goldsmiths row', test: 'prop'
};
docs.completeDoc
.setName('default','item6')
.setName('alt','item six')
.setCentroid({lat:6,lon:6})
.setAlpha3('FOO')
.setAdmin('admin0','country')
.setAdmin('admin1','state')
.setAdmin('admin1_abbr','STA')
.setAdmin('admin2','city')
.setAdmin('local_admin','borough')
.setAdmin('locality','town')
.setAdmin('neighborhood','hood')
.setMeta('foo','bar')
.setMeta('bing','bang');
docs.osmNode1 = new Document('item7',7)
.setName('osmnode','node7')
.setCentroid({lat:7,lon:7});
docs.osmWay1 = new Document('osmway',8)
.setName('osmway','way8')
.setMeta('nodes', [
{ lat: 10, lon: 10 },
{ lat: 06, lon: 10 },
{ lat: 06, lon: 06 },
{ lat: 10, lon: 06 }
]);
docs.osmRelation1 = new Document('item9',9)
.setName('osmrelation','relation9')
.setCentroid({lat:9,lon:9});
// ref: https://github.com/pelias/openstreetmap/issues/21
docs.semicolonStreetNumbers = new Document('item10',10);
docs.semicolonStreetNumbers.setName('default','poi10');
docs.semicolonStreetNumbers.setCentroid({lat:10,lon:10});
docs.semicolonStreetNumbers.address = {
number: '1; 2 ;3', street: 'Pennine Road'
};
// has no 'nodes' and a preset centroid
docs.osmWay2 = new Document('osmway',11)
.setName('osmway','way11')
.setCentroid({lat:11,lon:11});
module.exports = docs;
|
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
//basePath: '../src/',
// frameworks to use
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'../src/**/*.js',
'../test/**/*.js'
],
// list of files to exclude
exclude: [
],
// test results reporter to use
reporters: ['progress', 'coverage'],
preprocessors: {
'../src/**/*.js': ['coverage']
},
// configure code coverage
coverageReporter: {
reporters: [
{type: 'html', dir: '../coverage/'},
{type: 'lcov', dir: '../coverage/'},
{type: 'text-summary'}
]
},
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// Start these browsers
browsers: ['PhantomJS'],
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 60000,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false
});
};
|
/* BBY261 */
/* Sayısal Loto Uygulaması */
//Çekiliş yapılacak sayıların dizisi
var rakamlar = new Array(49);
//Oynanacak kolonun dizisi
var loto = new Array(6);
document.write('<center><img src="sayisalloto.jpg" width=70% ></center>');
//Rakam havuzunun oluşturulması
for(var i=0; i<49; i++){
rakamlar[i]=i+1;
}
document.write('<table cellpadding="6" cellspacing="10" border="0" align="center">');
//6 kolonun ekrana yazdırılması
for(var i4=0; i4<6; i4++){
document.write('<tr>');
//Kolonun oluşturulması
for(var i2=0; i2<6; i2++){
var havuz = rakamlar.length;
var secilen = Math.floor(Math.random() * havuz);
loto[i2]=rakamlar[secilen];
rakamlar.splice(secilen,1);
}
loto.sort(function(a, b){return a-b});
//Tek kolonun yazdırılması
for(var i3=0; i3<6; i3++){
document.write('<td width=23 heigth=23 background="top.png" id="yazitipi">'+loto[i3]+'</td>');
}
document.write('</tr>');
}
document.write('</table>');
document.write('<p><center><img src="buton.png" onclick="yenile()" ></center></p>');
function yenile(){
window.location.href="index.html";
}
|
angular.module('tabss.controllers', [])
.controller('TabssCtrl', function($scope,$state) {
$scope.gotoTabs =function(){
$state.go('tabs')
}
$scope.gotoNearby =function(){
$state.go('app.nearby')
}
$scope.gotoEditProfile =function(){
$state.go('editprofile')
}
$scope.gotoQRCode =function(){
$state.go('qrcode')
}
$scope.gotoHome =function(){
$state.go('app.home')
}
$scope.gotoAddFavorite =function(){
$state.go('addfavorite')
}
$scope.gotoFavoriteMenu1 =function(){
$state.go('favoritemenu1')
}
$scope.gotoCoffeeShop1 =function(){
$state.go('coffeeshop1')
}
$scope.gotoNewsPromotion =function(){
$state.go('newspromotion')
}
$scope.gotoNews =function(){
$state.go('news')
}
})
|
'use strict';
var http = require('http');
var Pusher = require('pusher');
var Network = require('./model/network');
var Node = require('./model/node');
var Sensor = require('./model/sensor');
var Feature = require('./model/feature');
require('./model/relations');
// https://pusher.com/docs/server_api_guide/interact_rest_api
var pusher = new Pusher({
appId: process.env.PUSHER_ID,
key: process.env.PUSHER_KEY,
secret: process.env.PUSHER_SECRET
});
/**
* Reverse object keys and values.
*/
function reverse(o) {
console.log('[index.js] reverse');
console.time('[index.js] reverse');
var result = {};
for(var key in o) {
result[o[key]] = key;
}
console.timeEnd('[index.js] reverse');
return result;
}
/**
* Extract the base64 data encoded in the kinesis record to an object.
* @return {Object}
*/
function decode(record) {
console.log('[index.js] decode');
console.time('[index.js] decode');
var data = new Buffer(record.kinesis.data, 'base64').toString();
try {
return JSON.parse(data);
} catch (SyntaxError) {
return {};
}
console.timeEnd('[index.js] decode');
}
/**
* If the sensor maps to an available feature of interest, provide it, otherwise
* reject it as null.
* @return {Object}
*/
function format(record, networkMap) {
var network = record.network;
var node = record.node;
var sensor = record.sensor;
var networkMetadata = networkMap[network];
if (!networkMetadata) {
return null;
}
var nodeMetadata = networkMetadata[node];
if (!nodeMetadata) {
return null;
}
var sensorMetadata = nodeMetadata[sensor];
if (!sensorMetadata) {
return null;
}
var mapping = sensorMetadata;
var feature = '';
for (var property in record.data) {
if (!(property in mapping)) {
return null;
}
feature = mapping[property].split('.')[0];
var formalName = mapping[property].split('.')[1];
record.data[formalName] = record.data[property];
if (formalName != property) {
delete record.data[property];
}
}
record.feature = feature;
record.results = record.data;
delete record.data;
return record;
}
/**
* Determine if a record can be published to a channel.
* @return {Boolean}
*/
function match(record, channel) {
var prefix = channel.split('-')[0];
channel = channel.split('-')[1];
if (prefix != 'private') return false;
var channelParts = channel.split(';');
var network = channelParts[0];
var node = channelParts[1];
var sensor = channelParts[2];
var feature = channelParts[3];
if (network != record.network) return false;
if (node && record.node != node) return false;
if (sensor && record.sensor != sensor) return false;
if (feature && record.feature != feature) return false;
return true;
}
/**
* Iterate through incoming records and emit to the appropriate channels.
*/
function emit(records, channels) {
console.log('[index.js] emit');
console.time('[index.js] emit');
records.forEach((record) => {
if (!record) return;
channels.forEach((channel) => {
var message = { message: JSON.stringify(record) };
if (match(record, channel)) {
pusher.trigger(channel, 'data', message);
}
});
});
console.timeEnd('[index.js] emit');
}
/**
* Implementation of required handler for an incoming batch of kinesis records.
* http://docs.aws.amazon.com/lambda/latest/dg/with-kinesis-example-deployment-pkg.html#with-kinesis-example-deployment-pkg-nodejs
*/
function handler(event, context) {
console.log('[index.js] handler');
console.time('[index.js] handler');
var records = event.Records.map(decode);
var promise = getSensorNetworkTree().then((networkMap) => {
records = records.map((record) => format(record, networkMap));
var valids = records.filter(r => r);
pusher.get({path: '/channels'}, (error, request, response) => {
console.log(response.body);
var result = JSON.parse(response.body);
var channels = Object.keys(result.channels);
emit(records, channels);
});
console.timeEnd('[index.js] handler');
return [records.length, valids.length];
});
return promise;
}
exports.handler = handler;
function extractFeatures(sensors) {
console.log('[index.js] extractFeatures');
console.time('[index.js] extractFeatures');
var result = {};
for (var sensor of sensors) {
result[sensor.name] = sensor.observed_properties;
}
console.timeEnd('[index.js] extractFeatures');
return result;
}
function extractSensors(nodes) {
console.log('[index.js] extractSensors');
console.time('[index.js] extractSensors');
var result = {};
for (var node of nodes) {
result[node.name] = extractFeatures(node.sensor__sensor_metadata);
}
console.timeEnd('[index.js] extractSensors');
return result;
}
function getSensorNetworkTree() {
console.log('[index.js] getSensorNetworkTree');
console.time('[index.js] getSensorNetworkTree');
var networkNames = [];
var promises = [];
return Network.findAll().then( networks => {
for (var network of networks) {
networkNames.push(network.name);
promises.push(network.getNodes({ include: [{ model: Sensor }]}));
}
return Promise.all(promises);
}).then( results => {
var tree = {};
for (var i = 0; i < results.length; i++) {
tree[networkNames[i]] = extractSensors(results[i]);
}
console.timeEnd('[index.js] getSensorNetworkTree');
return tree;
});
}
|
define(['handlebars'], function (Handlebars) {
var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};
templates['ma-ecca-treenode'] = template(function (Handlebars,depth0,helpers,partials,data) {
this.compilerInfo = [4,'>= 1.0.0'];
helpers = this.merge(helpers, Handlebars.helpers); data = data || {};
var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression, self=this;
function program1(depth0,data) {
var stack1;
stack1 = helpers['if'].call(depth0, depth0.expanded, {hash:{},inverse:self.program(4, program4, data),fn:self.program(2, program2, data),data:data});
if(stack1 || stack1 === 0) { return stack1; }
else { return ''; }
}
function program2(depth0,data) {
var stack1;
if (stack1 = helpers.expandedClass) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
else { stack1 = depth0.expandedClass; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
return escapeExpression(stack1);
}
function program4(depth0,data) {
var stack1;
if (stack1 = helpers.collapsedClass) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
else { stack1 = depth0.collapsedClass; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
return escapeExpression(stack1);
}
function program6(depth0,data) {
return "display: none;";
}
buffer += "<ins class='ecca-tree-icon ";
stack1 = helpers['if'].call(depth0, depth0.childNodesAllowed, {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data});
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "'> </ins><a href='#' class='ecca-tree-node'><ins class='ecca-tree-icon-folder ";
stack1 = helpers['if'].call(depth0, depth0.expanded, {hash:{},inverse:self.program(4, program4, data),fn:self.program(2, program2, data),data:data});
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += " ";
if (stack1 = helpers.iconClass) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
else { stack1 = depth0.iconClass; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
buffer += escapeExpression(stack1)
+ "'> </ins><span>";
if (stack1 = helpers.title) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
else { stack1 = depth0.title; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
buffer += escapeExpression(stack1)
+ "</span></a><ul style='";
stack1 = helpers.unless.call(depth0, depth0.expanded, {hash:{},inverse:self.noop,fn:self.program(6, program6, data),data:data});
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "'></ul>";
return buffer;
});
});
|
import {combineEpics} from 'redux-observable';
import {combineReducers} from 'redux';
import {
disposePastebinEpic,
pastebinLayoutEpic,
pastebinEpic,
pastebinTokenEpic,
pastebinTokenRejectedEpic,
pastebinReducer,
pastebinContentEpic,
pastebinContentRejectedEpic,
} from './pastebin';
import {
firecoReducer,
firecoEditorsEpic,
firecoActivateEpic,
firecoEditorEpic,
firecoChatEpic,
firecoPersistableComponentEpic,
} from './fireco';
import {
configureMonacoModelsEpic,
updateMonacoModelsEpic,
configureMonacoThemeSwitchEpic,
monacoReducer,
} from './monaco';
import {
monacoEditorsEpic,
monacoEditorsReducer,
mountedEditorEpic,
} from './monacoEditor';
import {
updatePlaygroundReducer,
} from './playground';
import {updateBundleReducer} from './liveExpressionStore';
export const rootEpic = combineEpics(
disposePastebinEpic,
pastebinLayoutEpic,
pastebinEpic,
pastebinContentEpic,
pastebinContentRejectedEpic,
pastebinTokenEpic,
pastebinTokenRejectedEpic,
mountedEditorEpic,
configureMonacoModelsEpic,
updateMonacoModelsEpic,
configureMonacoThemeSwitchEpic,
monacoEditorsEpic,
// updatePlaygroundEpic,
// updatePlaygroundInstrumentationEpic,
firecoEditorsEpic,
firecoActivateEpic,
firecoEditorEpic,
firecoChatEpic,
firecoPersistableComponentEpic,
);
export const rootReducer = combineReducers({
pastebinReducer,
monacoReducer,
monacoEditorsReducer,
firecoReducer,
updateBundleReducer,
updatePlaygroundReducer,
});
|
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h(h.f, null, h("path", {
d: "M21.41 11.58l-9-9C12.05 2.22 11.55 2 11 2H4c-1.1 0-2 .9-2 2v7c0 .55.22 1.05.59 1.42l9 9c.36.36.86.58 1.41.58s1.05-.22 1.41-.59l7-7c.37-.36.59-.86.59-1.41s-.23-1.06-.59-1.42zM13 20.01L4 11V4h7v-.01l9 9-7 7.02z"
}), h("circle", {
cx: "6.5",
cy: "6.5",
r: "1.5"
}), h("path", {
d: "M8.9 12.55c0 .57.23 1.07.6 1.45l3.5 3.5 3.5-3.5c.37-.37.6-.89.6-1.45 0-1.13-.92-2.05-2.05-2.05-.57 0-1.08.23-1.45.6l-.6.6-.6-.59c-.37-.38-.89-.61-1.45-.61-1.13 0-2.05.92-2.05 2.05z"
})), 'LoyaltyOutlined');
|
export default function isSingleTextTree(treeList) {
return treeList.length === 1 && treeList[0].type === 'text';
}
|
const Comparator = require('../../util/comparator');
/**
* Swaps two elements in the array
*/
const swap = (array, x, y) => {
const tmp = array[y];
array[y] = array[x];
array[x] = tmp;
};
/**
* Chooses a pivot and makes every element that is
* lower than the pivot move to its left, and every
* greater element moves to its right
*
* @return Number the positon of the pivot
*/
const partition = (a, comparator, lo, hi) => {
// pick a random element, swap with the rightmost and
// use it as pivot
swap(a, Math.floor(Math.random() * (hi - lo)) + lo, hi);
const pivot = hi;
// dividerPosition keeps track of the position
// where the pivot should be inserted
let dividerPosition = lo;
for (let i = lo; i < hi; i++) {
if (comparator.lessThan(a[i], a[pivot])) {
swap(a, i, dividerPosition);
dividerPosition++;
}
}
swap(a, dividerPosition, pivot);
return dividerPosition;
};
/**
* Quicksort recursively sorts parts of the array in
* O(n.lg n)
*/
const quicksortInit = (array, comparatorFn) => {
const comparator = new Comparator(comparatorFn);
return (function quicksort(array, lo, hi) {
while (lo < hi) {
const p = partition(array, comparator, lo, hi);
// Chooses only the smallest partition to use recursion on and
// tail-optimize the other. This guarantees O(log n) space in worst case.
if (p - lo < hi - p) {
quicksort(array, lo, p - 1);
lo = p + 1;
} else {
quicksort(array, p + 1, hi);
hi = p - 1;
}
}
return array;
})(array, 0, array.length - 1);
};
module.exports = quicksortInit;
|
process.env.NODE_ENV = process.env.NODE_ENV || 'development'
let express = require('express');
let path = require('path');
let favicon = require('serve-favicon');
let logger = require('morgan');
let cookieParser = require('cookie-parser');
let bodyParser = require('body-parser');
let compression = require('compression');
let session = require('express-session');
let index = require('./routes/index');
let users = require('./routes/users');
let server = express();
server.set('views', path.join(__dirname, 'views'));
server.set('view engine', 'hbs');
// uncomment after placing your favicon in /public
//server.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
server.use(logger('dev'));
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: false }));
server.use(cookieParser());
server.use(express.static(path.join(__dirname, 'public')));
server.use(compression())
// express-sessions setup
server.use(session({
secret: 'blueberry pie',
resave: false,
saveUninitialized: true,
cookie: {
maxAge: 600000
}
// db: knex
}))
server.use('/', index);
server.use('/users', users);
// catch 404 and forward to error handler
server.use((req, res, next) => {
let err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (server.get('env') === 'development') {
server.use((err, req, res, next) => {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
server.use((err, req, res, next) => {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = server;
|
const landingText = (
``
)
const aboutText = (
`We are a team of expert web developers coming from diverse backgrounds who
are passionate about building a better web experience and delivering quality
code to our clients`
)
|
import React, { PropTypes } from 'react';
export default function ImageDesciption({desc, price}) {
return (
<div className="text">
<h3>{desc}</h3>
<p className="price">{price}</p>
</div>
);
}
|
var gulp = require("gulp");
var $ = require("gulp-load-plugins");
gulp.task("html", function () {
gulp.src("./src/index.html")
.pipe(gulp.dest("./.tmp"));
});
|
const _ = require('lodash');
module.exports = _.extend(
require('./users/users.authentication.server.controller'),
require('./users/users.authorization.server.controller'),
require('./users/users.password.server.controller'),
require('./users/users.profile.server.controller')
);
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Review Schema
*/
var ReviewSchema = new Schema({
content: {
type: String,
default: '',
trim: true
},
contentHTML: {
type: String,
default: ''
},
name: {
type: String,
default: '',
trim: true
},
score: {
type: Number,
default: 5,
required: 'Must rate the game out of 5',
min: [0, 'Score must be at least 0'],
max: [5, 'Score cannot be higher than 5']
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
},
gameId: {
type: String,
required: 'Game for review required'
},
game: {
type: Schema.ObjectId,
ref: 'Game'
},
triaged: {
type: Boolean,
default: false
},
liked: {
type: Number,
default: 0
},
disliked: {
type: Number,
default: 0
},
reports: [{
type: String,
enum: [
'Spam',
'Vote Manipulation',
'Personal Information',
'Troll',
'Harrassment'
]
}]
});
mongoose.model('Review', ReviewSchema);
|
$(document).ready(function(){
var $nomeInput = $('#nomeInput');
var $descricaoInput = $('#descricaoInput');
var $precoInput = $('#precoInput');
var $categoriaSelect = $('#categoriaSelect');
var $novidadeSelect = $('#novidadeSelect');
var $carregandoImg = $('#carregandoImg');
$carregandoImg.hide();
var $btnSalvar = $('#salvar');
var $btnFechar = $('#fechar');
var $listaProdutos = $('#listaProdutos');
$listaProdutos.hide();
function obterValoresdeProdutos(){
return {'nome' : $nomeInput.val() , 'descricao' : $descricaoInput.val(), 'preco': $precoInput.val() , 'categoria' : $categoriaSelect.val(), 'novidade' : $novidadeSelect.val()}
}
function limparValores(){
$('input[type="text"]').val('');
$novidadeSelect.val('');
}
$.get('/produtos/admin/rest/listar').success(function(produtos){
$.each(produtos,function(index, p){
adicionarProduto(p);
})
});
function adicionarProduto (produto) {
var msg = '<tr id="tr-produto_'+produto.id+'"><td>'+produto.id+'</td><td>'+produto.nome+'</td><td>'+produto.categoria+'</td><td>'+produto.descricao+'</td><td>'+produto.preco+'</td><td>'+(produto.novidade == "1" ? 'Sim' : 'Não')+'</td><td><a href="/produtos/admin/editar/'+produto.id+'" class="btn btn-warning glyphicon glyphicon-pencil"></a></td><td><button id="btn-deletar_'+produto.id+'" class="btn btn-danger"><i class="glyphicon glyphicon-trash"></i></button></td></tr>';
$listaProdutos.show();
$listaProdutos.append(msg);
$('#btn-deletar_'+produto.id).click(function(){
if (confirm("Deseja apagar esse registro? "))
{
var resp = $.post('/produtos/admin/rest/deletar' , {produto_id : produto.id});
resp.success(function(){
$('#tr-produto_'+produto.id).remove()
});
}
});
}
$btnSalvar.click(function(){
$('.has-error').removeClass('has-error');
$('.help-block').empty();
$btnSalvar.attr('disabled' , 'disabled');
$carregandoImg.fadeIn('fast');
var resp = $.post('/produtos/admin/rest/salvar', obterValoresdeProdutos());
resp.success(function(produto){
limparValores();
$btnFechar.click();
adicionarProduto(produto);
})
resp.error(function(erros){
for(campos in erros.responseJSON)
{
$('#'+campos+'Div').addClass('has-error');
$('#'+campos+'Span').text(erros.responseJSON[campos]);
}
}).always(function(){
$btnSalvar.removeAttr('disabled','disabled');
$carregandoImg.hide();
});
});
});
|
// Karma configuration
// Generated on Wed Jul 15 2015 09:44:02 GMT+0200 (Romance Daylight Time)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'node_modules/angular2/node_modules/zone.js/dist/zone-microtask.js',
'node_modules/angular2/node_modules/zone.js/dist/long-stack-trace-zone.js',
'node_modules/angular2/node_modules/zone.js/dist/jasmine-patch.js',
'node_modules/angular2/node_modules/traceur/bin/traceur-runtime.js',
'node_modules/es6-module-loader/dist/es6-module-loader-sans-promises.src.js',
'node_modules/systemjs/dist/system.src.js',
'node_modules/reflect-metadata/Reflect.js',
{ pattern: 'test/**/*.js', included: false, watched: true },
{ pattern: 'node_modules/angular2/**/*.js', included: false, watched: false },
'test-main.js',
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
})
}
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 15.5.4.20-4-55
description: >
String.prototype.trim handles whitepace and lineterminators
(\u000A\u000A)
includes: [runTestCase.js]
---*/
function testcase() {
if ("\u000A\u000A".trim() === "") {
return true;
}
}
runTestCase(testcase);
|
'use strict';
const os = require('os');
const cluster = require('cluster');
const DEFAULT_DEADLINE_MS = 30000;
function makeWorker(workerFunc) {
var server = workerFunc(cluster.worker.id);
server.on('close', function() {
process.exit();
});
process.on('SIGTERM', function() {
server.close();
});
return server;
}
const Regiment = function(workerFunc, options) {
if (cluster.isWorker) return makeWorker(workerFunc);
options = options || {};
const numCpus = os.cpus().length;
let running = true;
const deadline = options.deadline || DEFAULT_DEADLINE_MS;
const numWorkers = options.numWorkers || numCpus;
const logger = options.logger || console;
function messageHandler(msg) {
if (running && msg.cmd && msg.cmd === 'need_replacement') {
const workerId = msg.workerId;
const replacement = spawn();
logger.log(`Replacing worker ${workerId} with worker ${replacement.id}`);
replacement.on('listening', (address) => {
logger.log(`Replacement ${replacement.id} is listening, killing ${workerId}`);
kill(cluster.workers[workerId]);
})
}
}
function spawn() {
const worker = cluster.fork();
worker.on('message', messageHandler);
return worker;
}
function fork() {
for (var i=0; i<numWorkers; i++) {
spawn();
}
}
function kill(worker) {
logger.log(`Killing ${worker.id}`);
worker.process.kill();
ensureDeath(worker);
}
function ensureDeath(worker) {
setTimeout(() => {
logger.log(`Ensured death of ${worker.id}`);
worker.kill();
}, deadline).unref();
worker.disconnect();
}
function respawn(worker, code, signal) {
if (running && !worker.exitedAfterDisconnect) {
logger.log(`Respawning ${worker.id} after it exited`);
spawn();
}
}
function listen() {
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
cluster.on('exit', respawn);
}
function shutdown() {
running = false;
logger.log(`Shutting down!`);
for (var id in cluster.workers) {
kill(cluster.workers[id]);
}
}
listen();
fork();
}
Regiment.middleware = require('./middleware');
module.exports = Regiment;
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Button from 'react-bootstrap/lib/Button';
import Glyphicon from 'react-bootstrap/lib/Glyphicon';
import { post } from '../../api';
class PostActionButton extends Component {
static propTypes = {
bsStyle: PropTypes.string.isRequired,
children: PropTypes.node.isRequired,
hideContentOnAction: PropTypes.bool.isRequired,
action: PropTypes.string.isRequired,
body: PropTypes.object.isRequired,
onSuccess: PropTypes.func,
onError: PropTypes.func,
};
static defaultProps = {
body: {},
hideContentOnAction: false,
onSuccess: () => {},
onError: () => {},
};
constructor(props) {
super(props);
this.state = { isWorking: false };
}
onClick = () => {
this.setState({ isWorking: true });
const { body, action, onSuccess, onError } = this.props;
post(action, body).then(() => {
this.setState({ isWorking: false });
onSuccess();
}, (err) => {
console.error(err);
onError(err);
});
};
render() {
const { isWorking } = this.state;
const { hideContentOnAction, bsStyle, children } = this.props;
const renderChildren = !isWorking || (isWorking && !hideContentOnAction);
return (
<Button onClick={this.onClick} bsStyle={bsStyle}>
{isWorking &&
<Glyphicon glyph="refresh" className="glyphicon-spin" />
} {renderChildren && children}
</Button>
);
}
}
export default PostActionButton;
|
import $ from 'jquery'
const DURATION_MS = 400
export default function scrollToTop () {
const scrollTop = $('.auction-artworks-HeaderDesktop').offset().top - $('.mlh-navbar').height()
$('html,body').animate({ scrollTop }, DURATION_MS)
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:96c89faf399ad903c813617aca830b28b3330c35d8af37d08743722e06d9323d
size 84
|
module.exports = function(grunt) {
grunt.initConfig({
web_server: {
options: {
cors: true,
port: 8000,
nevercache: true,
logRequests: true
},
foo: 'bar'
},
uglify: {
my_target: {
files: {
'dist/ng-video-preview.min.js': ['video-preview.js']
}
}
},
jshint: {
files: ['Gruntfile.js', 'src/**/*.js', 'test/**/*.js'],
options: {
globals: {
jQuery: true
}
}
},
watch: {
files: ['<%= jshint.files %>'],
tasks: ['jshint']
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-web-server');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.registerTask('default', ['jshint']);
};
|
var model = require('./model');
var backbone = require('backbone');
var fs = require('fs');
var util = require('util');
var fpath = require('path');
var hive = require('./hive');
var EMPTY_FILE = '';
var exports = module.exports = model.extend({
initialize: function(attributes) {
var _self = this;
var path = this.get('path');
if(path) {
var name = fpath.basename(path);
if(name) {
this.set({name: name});
}
if(attributes.watch) {
fs.watchFile(path, function() {
_self.sync('read', _self);
_self.change();
});
}
}
return this;
},
ext: function() {
return fpath.extname(this.get('name'));
},
absolute: function() {
return fpath.resolve(this.get('path'));
},
dir: function() {
return fpath.dirname(this.absolute());
},
sync: function(method, model) {
model.syncing = true;
var path = model.absolute();
switch(method) {
case 'create':
case 'update':
hive.log(method + '-ing file @ ' + path);
fs.writeFile(path, model.get('data') || EMPTY_FILE, model.get('encoding'), function(err) {
hive.log(method + 'd file @ ' + path);
if(err) return model.error(err);
model.success({data: model.get('data'), exists: true}, true);
});
break;
case 'read':
hive.log(method + '-ing file @ ' + path);
fs.readFile(path, function(err, data) {
hive.log(method + 'd file @ ' + path);
if(err) return model.error(err);
model.success({data: data.toString(), exists: true});
});
break;
case 'delete':
hive.log(method + '-ing file @ ' + path);
fs.unlink(path, function(err) {
hive.log(method + 'd file @ ' + path);
if(err) return model.error(err);
model.success({data: null, exists: false});
});
break;
}
},
paste: function(destination, name) {
var _self = this;
_self.syncing = true;
if(typeof destination === 'string') {
destination = new hive.Dir({path: destination});
}
var name = name || _self.get('name'),
path = destination.get('path') + '/' + name;
if(!path) _self.error('Could not paste file to hive.Dir without a path');
var i = fs.createReadStream(_self.get('path')),
o = fs.createWriteStream(path);
util.pump(i, o, function() {
hive.log('wrote file @ ' + path);
_self.trigger('pasted');
_self.success({data: o});
});
return this;
},
update: function(callback, done) {
var _self = this;
hive.log('**UPDATING**', _self);
_self.fetch(function() {
hive.log('**UPDATING**', 'fetched');
hive.log('**UPDATING** data - ', _self.get('data'));
var changed = callback(_self.get('data') || '');
hive.log('**UPDATING** changed - ', changed);
_self.set({data: changed}, {silent: true});
_self.once('success', function() {
hive.log('**UPDATING**', 'done');
done && done();
});
_self.save();
});
}
});
|
/**
min任务
-------------
min脚本,样式,图片或html
### 用法
<min src='my.js' dest='my.min.js'/>
<min file='reset.css' destfile='reset.min.css'/>
@class min
**/
module.exports = function(bee) {
bee.register('min', function(options, callback) {
var path = require('path');
var minifier = require('node-minifier');
var src = options.src || options.file;
var destfile = options.destfile || options.dest;
if (!src || !destfile) {
return callback(new Error('src/file and dest/destfile are required in minify task.'));
}
var childNodes = options.childNodes;
var banner, footer;
options.childNodes.forEach(function(item){
if(item.name === 'banner' || item.name === 'header'){
banner = item.value.value;
}else if(item.name === 'footer'){
footer = item.value.value;
}
});
var readWrite = function(transform, input, output, callback) {
var encoding = options.encoding || 'utf-8';
var filecontent = bee.file.read(input, encoding);
filecontent = transform(filecontent, options);
bee.file.mkdir(path.dirname(output));
bee.file.write(output, filecontent, encoding);
callback();
}
var minifyJS = function(input, output, callback) {
bee.log('minify JS input:' + input + ' output: ' + output);
var remove = options.remove ? options.remove.split(',') : [];
readWrite(function(filecontent) {
return minifier.minifyJS(filecontent, {
remove: remove,
copyright: options.copyright || true,
banner: banner,
footer: footer
});
}, input, output, callback);
}
var minifyCSS = function(input, output, callback) {
bee.log('minify CSS input:' + input + ' output: ' + output);
readWrite(function(filecontent) {
return minifier.minifyCSS(filecontent, {
datauri: options.datauri,
banner: banner,
footer: footer
});
}, input, output, callback);
}
var minifyHTML = function(input, output, callback) {
bee.log('minify HTML input:' + input + ' output: ' + output);
options.banner = banner;
options.footer = footer;
readWrite(function(filecontent) {
return minifier.minifyHTML(filecontent, options);
}, input, output, callback);
}
var minifyImage = function(input, output, callback) {
bee.log('minify Image input:' + input + ' output: ' + output);
minifier.minifyImage(input, output, function(e, data) {
if (e) {
callback && callback(e);
} else {
callback(null);
}
}, {
service: options.service
})
}
var extname = options.type || bee.file.extname(src).toLowerCase();
var method;
if (extname == 'js') {
method = minifyJS;
} else if (extname == 'css') {
method = minifyCSS;
} else if (['html', 'htm'].indexOf(extname) >= 0) {
method = minifyHTML;
} else if (['png', 'jpg', 'jpeg', 'gif'].indexOf(extname) >= 0) {
method = minifyImage;
}
if(!method){
bee.warn('the filetype of ' + src + ' cannot be minified.')
return callback();
}
method(src, destfile, callback);
});
}
|
// Generated by CoffeeScript 1.10.0
(function() {
(function($) {
return $(".some_button").on("click", function(event) {
console.log("some_button clicked!");
return event.preventDefault();
});
})(jQuery);
}).call(this);
|
const mongoose = require('mongoose')
const TABLE_NAME = 'Post'
const Schema = mongoose.Schema
const ObjectId = Schema.Types.ObjectId
const escape = (require('../utils')).escape
const PostSchema = new Schema({
//类型
type: {
type: String,
default: 'post' // post | page
},
//标题
title: {
type: String,
trim: true,
set: escape
},
//别名
alias: {
type: String,
trim: true,
set: escape
},
//创建者
user: {
type: ObjectId,
ref: 'User'
},
//类别
category: {
type: ObjectId,
ref: 'Category'
},
//摘要
excerpt: {
type: String,
trim: true,
},
//内容
contents: {
type: String,
trim: true,
},
//markdown
markdown: {
type: String,
trim: true,
},
//标签
tags: Array,
//缩略图
thumbnail: {
type: String,
trim: true,
set: escape
},
//统计
count: {
//浏览次数
views: {
type: Number,
default: 1,
},
//评论数
comments: {
type: Number,
default: 0,
},
//点赞数
praises: {
type: Number,
default: 1
}
},
//状态
status: {
type: Number,
default: 1 // 1:发布, 0 :草稿, -1 :删除
},
//置顶
top: Boolean,
//允许评论
allowComment: {
type: Boolean,
default: true
},
//允许打赏
allowReward: Boolean,
//著名版权
license: Boolean,
//使用密码
usePassword: Boolean,
//密码
password: {
type: String,
trim: true
},
order: {
type: Number,
default: 1
},
//创建时间
createTime: {
type: Date,
default: Date.now()
},
//修改时间
updateTime: {
type: Date,
default: Date.now()
}
}, {
connection: TABLE_NAME,
versionKey: false,
})
module.exports = mongoose.model(TABLE_NAME, PostSchema)
|
var test = require("tape")
var mongo = require("continuable-mongo")
var uuid = require("node-uuid")
var setTimeout = require("timers").setTimeout
var eventLog = require("../index")
var client = mongo("mongodb://localhost:27017/colingo-group-tests")
var collectionName = uuid()
var col = client.collection(collectionName)
var rawCollection = client.collection(collectionName + "@")
var SECOND = 1000
var MINUTE = 60 * SECOND
var HOUR = 60 * MINUTE
test("ensure col is capped", function (assert) {
client(function (err, db) {
assert.ifError(err)
db.createCollection(collectionName, {
capped: true
, size: 100000
}, function (err, res) {
assert.ifError(err)
assert.end()
})
})
})
test("can add to eventLog", function (assert) {
var log = eventLog(col, {
timeToLive: HOUR
, rawCollection: rawCollection
})
var id = uuid()
log.add("add", {
id: id
, timestamp: Date.now()
, type: "some-event"
}, function (err, value) {
assert.ifError(err)
assert.equal(value.eventType, "add")
assert.ok(value._id)
assert.equal(value.value.id, id)
log.close()
assert.end()
})
})
test("can read from eventLog", function (assert) {
var log = eventLog(col, {
rawCollection: rawCollection
, timeToLive: HOUR
})
var stream = log.read(Date.now() - 1000)
setTimeout(function () {
log.add("add", {
id: uuid()
, timestamp: Date.now()
, type: "some-event"
, foo: "inserted after"
}, function (err, value) {
assert.ifError(err)
})
}, 20)
log.add("add", {
id: uuid()
, timestamp: Date.now()
, type: "some-event"
, foo: "inserted before"
}, function (err, value) {
assert.ifError(err)
var list = []
var cleanupCounter = 2
stream.on("data", function (chunk) {
list.push(chunk)
if (list.length === 3) {
next()
}
})
stream.resume()
function next() {
assert.equal(list.length, 3)
assert.equal(list[0].value.type, "some-event")
assert.equal(list[1].value.foo, "inserted before")
assert.equal(list[2].value.foo, "inserted after")
rawCollection(function (err, rawCollection) {
assert.ifError(err)
rawCollection.drop(function (err) {
assert.ifError(err)
if (--cleanupCounter === 0) {
cleanup()
}
})
})
col(function (err, col) {
assert.ifError(err)
col.drop(function (err) {
assert.ifError(err)
if (--cleanupCounter === 0) {
cleanup()
}
})
})
}
function cleanup() {
log.close()
client.close(function (err) {
assert.ifError(err)
assert.end()
})
}
})
})
|
version https://git-lfs.github.com/spec/v1
oid sha256:356614d2260c69b92680d59e99601dcd5e068f761756f22fb959b5562b9a7d62
size 17413
|
import * as React from 'react';
import {Row,Col,Table,Code,Items,Item} from 'yrui';
import thead from './thead';
let items=[{
key:'style',
expr:'设置items样式',
type:'object',
values:'-',
default:'-',
}];
let item=[{
key:'border',
expr:'设置border样式',
type:'string',
values:'-',
default:'-',
}];
const code=`
<Items>
<Item>
<h2>items配置</h2>
<Table thead={thead} tbody={items} />
</Item>
<Item>
<h2>item配置</h2>
<Table thead={thead} tbody={item} />
</Item>
</Items>
`;
export default class ItemsDemo extends React.Component{
render(){
return(
<Items>
<Item>
<h2>代码示例</h2>
<Code title="input" code={code} />
</Item>
<Item>
<Row gutter={8}>
<Col span={6} sm={12}>
<h2>参数说明</h2>
<Table thead={thead} tbody={items} noBorder={true} />
</Col>
<Col span={6} sm={12}>
<h2>参数说明</h2>
<Table thead={thead} tbody={item} noBorder={true} />
</Col>
</Row>
</Item>
</Items>
);
}
}
|
define(function() {
'use strict';
/* @ngInject */
var gameCtrl = function($scope, commoditySrvc, citySrvc, accountSrvc, gameSrvc, tutorialSrvc, $modal) {
//todo: find a better way to expose services to template
this.gameSrvc = gameSrvc;
this.commoditySrvc = commoditySrvc;
this.citySrvc = citySrvc;
this.accountSrvc = accountSrvc;
this.tutorialOptions = tutorialSrvc.options;
this.$modal = $modal;
this.$scope = $scope;
if (!citySrvc.currentCity) {
commoditySrvc.setCitySpecialty();
citySrvc.getRandomCity();
commoditySrvc.updatePrices();
}
//todo: figure out why this ctrl gets called twice on page load
if (gameSrvc.initialLoad) {
this.showModal('start');
gameSrvc.initialLoad = false;
}
};
gameCtrl.prototype.submitScore = function() {
this.showModal('gameOver', this.accountSrvc.netWorth);
this.gameSrvc.gameOver();
};
gameCtrl.prototype.goToCity = function(city) {
this.citySrvc.setCurrentCity(city);
this.commoditySrvc.updatePrices();
this.gameSrvc.reduceDaysLeft();
};
gameCtrl.prototype.buyItem = function(item, quantity) {
this.commoditySrvc.buyCommodity(item, quantity);
};
gameCtrl.prototype.sellItem = function(item) {
this.commoditySrvc.sellCommodity(item);
};
gameCtrl.prototype.setMarketHoverItem = function(item) {
this.marketHoverItem = item.name;
};
gameCtrl.prototype.resetMarketHoverItem = function() {
this.marketHoverItem = '';
};
gameCtrl.prototype.isCurrentCity = function(city) {
return city.name === this.citySrvc.currentCity.name;
};
gameCtrl.prototype.getPotentialProfit = function(item) {
var expectedProfit = 'unknown';
if (item.averageSellPrice) {
expectedProfit = ((item.averageSellPrice - item.currentPrice) * item.maxQuantityPurchasable) / 100;
}
return expectedProfit;
};
gameCtrl.prototype.openMenu = function() {
this.showModal('gameMenu');
};
gameCtrl.prototype.showModal = function(type, score) {
var templateUrl, self = this;
switch (type) {
case 'start':
templateUrl = 'components/game/gameModalStart.tmpl.html';
break;
case 'gameMenu':
templateUrl = 'components/game/gameModalGameMenu.tmpl.html';
break;
case 'gameOver':
templateUrl = 'components/game/gameModalGameOver.tmpl.html';
break;
}
var modalInstance = this.$modal.open({
templateUrl: templateUrl,
controller: 'gameModalInstanceCtrl',
size: 'sm',
resolve: {
type: function() {
return type;
},
score: function() {
return score;
}
}
});
modalInstance.result.then(function(action) {
switch (action) {
case 'startTutorial':
self.$scope.startTutorial();
break;
case 'resetGame':
self.gameSrvc.gameOver(true);
break;
}
}, function() {
});
};
return gameCtrl;
});
|
/**
* Module dependencies.
*/
var express = require('express');
var http = require('http');
var path = require('path');
var handlebars = require('express3-handlebars')
var index = require('./routes/index');
// Example route
// var user = require('./routes/user');
// below added by tommy
var login = require('./routes/login');
var messages = require('./routes/messages');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', handlebars());
app.set('view engine', 'handlebars');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('Intro HCI secret key'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
// Add routes here
app.get('/', index.view);
// Example route
// app.get('/users', user.list);
//below added by tommy
app.get('/login', login.view);
app.get('/messages', messages.view);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
|
import _jsx from "@babel/runtime/helpers/builtin/jsx";
import React from 'react';
import EditMediaDialog from '../../containers/EditMediaDialog';
import LoginDialog from '../../containers/LoginDialog';
import PreviewMediaDialog from '../../containers/PreviewMediaDialog';
var _ref =
/*#__PURE__*/
_jsx("div", {
className: "Dialogs"
}, void 0, _jsx(EditMediaDialog, {}), _jsx(LoginDialog, {}), _jsx(PreviewMediaDialog, {}));
var Dialogs = function Dialogs() {
return _ref;
};
export default Dialogs;
//# sourceMappingURL=index.js.map
|
import {
addClass,
removeClass,
EVENTS,
on,
off,
getViewportSize,
getClosest,
getParents
} from '../../utils/domUtils'
import {nodeListToArray} from '../../utils/arrayUtils'
function ScrollSpy (element, target = 'body', options = {}) {
this.el = element
this.opts = Object.assign({}, ScrollSpy.DEFAULTS, options)
this.opts.target = target
if (target === 'body') {
this.scrollElement = window
} else {
this.scrollElement = document.querySelector(`[id=${target}]`)
}
this.selector = 'li > a'
this.offsets = []
this.targets = []
this.activeTarget = null
this.scrollHeight = 0
if (this.scrollElement) {
this.refresh()
this.process()
}
}
ScrollSpy.DEFAULTS = {
offset: 10,
callback: (ele) => 0
}
ScrollSpy.prototype.getScrollHeight = function () {
return this.scrollElement.scrollHeight || Math.max(document.body.scrollHeight, document.documentElement.scrollHeight)
}
ScrollSpy.prototype.refresh = function () {
this.offsets = []
this.targets = []
this.scrollHeight = this.getScrollHeight()
let list = nodeListToArray(this.el.querySelectorAll(this.selector))
const isWindow = this.scrollElement === window
list
.map(ele => {
const href = ele.getAttribute('href')
if (/^#./.test(href)) {
const doc = document.documentElement
const rootEl = isWindow ? document : this.scrollElement
const hrefEl = rootEl.querySelector(`[id='${href.slice(1)}']`)
const windowScrollTop = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0)
const offset = isWindow ? hrefEl.getBoundingClientRect().top + windowScrollTop : hrefEl.offsetTop + this.scrollElement.scrollTop
return [offset, href]
} else {
return null
}
})
.filter(item => item)
.sort((a, b) => a[0] - b[0])
.forEach(item => {
this.offsets.push(item[0])
this.targets.push(item[1])
})
// console.log(this.offsets, this.targets)
}
ScrollSpy.prototype.process = function () {
const isWindow = this.scrollElement === window
const scrollTop = (isWindow ? window.pageYOffset : this.scrollElement.scrollTop) + this.opts.offset
const scrollHeight = this.getScrollHeight()
const scrollElementHeight = isWindow ? getViewportSize().height : this.scrollElement.getBoundingClientRect().height
const maxScroll = this.opts.offset + scrollHeight - scrollElementHeight
const offsets = this.offsets
const targets = this.targets
const activeTarget = this.activeTarget
let i
if (this.scrollHeight !== scrollHeight) {
this.refresh()
}
if (scrollTop >= maxScroll) {
return activeTarget !== (i = targets[targets.length - 1]) && this.activate(i)
}
if (activeTarget && scrollTop < offsets[0]) {
this.activeTarget = null
return this.clear()
}
for (i = offsets.length; i--;) {
activeTarget !== targets[i] &&
scrollTop >= offsets[i] &&
(offsets[i + 1] === undefined || scrollTop < offsets[i + 1]) &&
this.activate(targets[i])
}
}
ScrollSpy.prototype.activate = function (target) {
this.activeTarget = target
this.clear()
const selector = this.selector +
'[data-target="' + target + '"],' +
this.selector + '[href="' + target + '"]'
const activeCallback = this.opts.callback
let active = nodeListToArray(this.el.querySelectorAll(selector))
active.forEach(ele => {
getParents(ele, 'li')
.forEach(item => {
addClass(item, 'active')
activeCallback(item)
})
if (getParents(ele, '.dropdown-menu').length) {
addClass(getClosest(ele, 'li.dropdown'), 'active')
}
})
}
ScrollSpy.prototype.clear = function () {
let list = nodeListToArray(this.el.querySelectorAll(this.selector))
list.forEach(ele => {
getParents(ele, '.active', this.opts.target).forEach(item => {
removeClass(item, 'active')
})
})
}
const INSTANCE = '_uiv_scrollspy_instance'
const events = [EVENTS.RESIZE, EVENTS.SCROLL]
const bind = (el, binding) => {
// console.log('bind')
unbind(el)
}
const inserted = (el, binding) => {
// console.log('inserted')
const scrollSpy = new ScrollSpy(el, binding.arg, binding.value)
if (scrollSpy.scrollElement) {
scrollSpy.handler = () => {
scrollSpy.process()
}
events.forEach(event => {
on(scrollSpy.scrollElement, event, scrollSpy.handler)
})
}
el[INSTANCE] = scrollSpy
}
const unbind = (el) => {
// console.log('unbind')
let instance = el[INSTANCE]
if (instance && instance.scrollElement) {
events.forEach(event => {
off(instance.scrollElement, event, instance.handler)
})
delete el[INSTANCE]
}
}
const update = (el, binding) => {
// console.log('update')
const isArgUpdated = binding.arg !== binding.oldArg
const isValueUpdated = binding.value !== binding.oldValue
if (isArgUpdated || isValueUpdated) {
bind(el, binding)
inserted(el, binding)
}
}
export default {bind, unbind, update, inserted}
|
import { red } from "./colors.js";
export default `body { background: url("${
new URL("./file.png" + __resourceQuery, import.meta.url).href
}"); color: ${red}; }`;
|
angular.module('app').directive('ngReallyClick', [function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('click', function() {
var message = attrs.ngReallyMessage;
if (message && confirm(message)) {
scope.$apply(attrs.ngReallyClick);
}
});
}
}
}]);
|
// New Spotify object
function Spotify(tab){
this.tab = tab;
}
// search for a song
// open spotify if theres a match
Spotify.prototype.search = function(title, artist, album){
var query = 'title:"' + title + '"';
query += 'artist:"' + artist + '"';
if(album){
query += 'album:"' + album + '"';
}
$.ajax(
{
'url': constants.SPOTIFY.SEARCH,
'type': 'GET',
'data': {
'q': query
}
}
).then(
this.determineSearch.bind(this),
function(){
this.tab.sendServiceAction(
false,
'Error searching for song on Spotify',
'open',
'Spotify'
);
}.bind(this)
)
}
// does the search result match what we provided it?
// If so open Spotify app
Spotify.prototype.determineSearch = function(json){
if(json.tracks.length > 0){
this.tab.openThenClose(json.tracks[0].href);
this.tab.sendServiceAction(
true,
'Song opened on Spotify',
'open',
'Spotify'
);
}
else{
this.tab.sendServiceAction(
false,
'Song not found on Spotify',
'open',
'Spotify'
);
}
}
|
(function($){
$.fn.extend({
inputNumberFormat: function(options) {
this.defaultOptions = {
'decimal': 2,
'decimalAuto': 2,
'separator': '.',
'separatorAuthorized': ['.', ','],
'allowNegative': false
};
var settings = $.extend({}, this.defaultOptions, options);
var matchValue = function(value, options) {
var found = [];
var regexp = "^[0-9]+";
if (options.allowNegative){
regexp = "^-{0,1}[0-9]*";
}
if(options.decimal) {
regexp += "["+options.separatorAuthorized.join("")+"]?[0-9]{0," + options.decimal + "}";
regexp = new RegExp(regexp + "$");
found = value.match(regexp);
if(!found){
regexp = "^["+options.separatorAuthorized.join("")+"][0-9]{0," + options.decimal + "}";
regexp = new RegExp(regexp + "$");
found = value.match(regexp);
}
}else{
regexp = new RegExp(regexp + "$");
found = value.match(regexp);
}
return found;
}
var formatValue = function(value, options) {
var formatedValue = value;
if(!formatedValue) {
return formatedValue;
}
if(formatedValue == "-") {
return "";
}
formatedValue = formatedValue.replace(",", options.separator);
if(options.decimal && options.decimalAuto) {
formatedValue = Math.round(formatedValue*Math.pow(10,options.decimal))/(Math.pow(10,options.decimal))+"";
if(formatedValue.indexOf(options.separator) === -1) {
formatedValue += options.separator;
}
var nbDecimalToAdd = options.decimalAuto - formatedValue.split(options.separator)[1].length;
for(var i=1; i <= nbDecimalToAdd; i++) {
formatedValue += "0";
}
}
return formatedValue;
}
return this.each(function() {
var $this = $(this);
$this.on('keypress', function(e) {
if(e.ctrlKey) {
return;
}
if(e.key.length > 1) {
return;
}
var options = $.extend({}, settings, $(this).data());
var beginVal = $(this).val().substr(0, e.target.selectionStart);
var endVal = $(this).val().substr(e.target.selectionEnd, $(this).val().length - 1);
var val = beginVal + e.key + endVal;
if(!matchValue(val, options)) {
e.preventDefault();
return;
}
});
$this.on('blur', function(e) {
var options = $.extend({}, settings, $(this).data());
$(this).val(formatValue($(this).val(), options));
});
$this.on('change', function(e) {
var options = $.extend({}, settings, $(this).data());
$(this).val(formatValue($(this).val(), options));
});
});
}
});
})(jQuery);
|
describe("Image", function() {
beforeEach(function() {
$("body").append($('<div id="sandbox"></div>'));
});
afterEach(function() {
$('#sandbox').remove();
$('.ui-dialog').remove();
});
it("add image into item content by factory", function() {
$('#sandbox').wikimate({});
$('#sandbox').wikimate('newItem', {type: 'factory'});
$('.new-image').click();
var image = "data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub//ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcppV0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7";
$('.image_url_input').val(image);
var done = $('.ui-button').filter(function(i, button) {
return $(button).text() == "Done";
});
done.click();
expect($('#sandbox .item').prop('class')).toEqual('item image');
expect($('#sandbox .item img').length).toEqual(1);
expect($('#sandbox .item img').prop('src')).toEqual(image);
expect($('#sandbox .item').story_item('data').type).toEqual('image');
expect($('#sandbox .item').story_item('data').text).toEqual(image);
});
it("should not add image when image url is blank", function() {
$('#sandbox').wikimate({});
$('#sandbox').wikimate('newItem', {type: 'factory'});
$('.new-image').click();
var done = $('.ui-button').filter(function(i, button) {
return $(button).text() == "Done";
});
done.click();
expect($('#sandbox .item').length).toEqual(0);
});
});
|
var dogVideos = [
"http://media.giphy.com/media/l2JHZ7CDZa6jp1rAQ/giphy.mp4",
"http://media.giphy.com/media/26tnmOjq7uQ98qxZC/giphy.mp4",
"http://media.giphy.com/media/26tnazn9Fm4V3VUMU/giphy.mp4",
"http://media.giphy.com/media/26tnhrpR1B6iOnUgo/giphy.mp4",
"http://media.giphy.com/media/26tn2A11Cgd3xvIqc/giphy.mp4",
"http://media.giphy.com/media/l2JHTMc51UdCYCn2o/giphy.mp4",
"http://media.giphy.com/media/l2JI9XQlqkRLYIWCA/giphy.mp4",
"http://media.giphy.com/media/26tn4dAvXHkHcHncQ/giphy.mp4",
"http://media.giphy.com/media/26tn956W5qLmbO9YQ/giphy.mp4",
"http://media.giphy.com/media/l2JHQGY0SoanXpvck/giphy.mp4",
"http://media.giphy.com/media/l2JIcb3CvvjMZ9akU/giphy.mp4",
"http://media.giphy.com/media/26tmZGflCf82PGbjq/giphy.mp4",
"http://media.giphy.com/media/26tn5ZBO276MhXjiw/giphy.mp4",
"http://media.giphy.com/media/26tncxLvZXWff0FlS/giphy.mp4",
"http://media.giphy.com/media/l2JHSUA0chBuwY63e/giphy.mp4",
"http://media.giphy.com/media/l2JIkLzS2M9c5XD0I/giphy.mp4"
];
function displayRandomVideo() {
var randomIndex = Math.floor((Math.random() * dogVideos.length));
$("#dog-video").attr("src", dogVideos[randomIndex]);
$("#video")[0].load();
}
$(document).ready(function(){
displayRandomVideo();
});
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require jquery.serializejson
//= require jquery.transit
//= require underscore
//= require moment
//= require backbone
//= require_tree ./utils
//= require maildog
//= require_tree ../templates
//= require_tree ./mixins
//= require_tree ./models
//= require_tree ./collections
//= require_tree ./views
//= require_tree ./routers
//= require_tree .
|
angular.module('resource.magacinska', ['ngResource'])
.factory('Kartica', function ($resource) {
return $resource('http://localhost:8080/xws/api/magacinska-karticaK/:idMagacinskaKartica', { idMagacinskaKartica: '@idMagacinskaKartica' }, {
'update': { method:'PUT' }
});
})
|
/*
---
name: Element.Data.Specs
description: n/a
requires: [Behavior/Element.Data]
provides: [Element.Data.Specs]
...
*/
(function(){
var target = new Element('div', {
'data-filters': 'Test1 Test2',
'data-json':'{"foo": "bar", "nine": 9, "arr": [1, 2, 3]}'
});
describe('Element.Data', function(){
it('should get a data property from an element', function(){
expect(target.getData('filters')).toBe('Test1 Test2');
});
it('should set a data property on an element', function(){
target.setData('foo', 'bar');
expect(target.getData('foo')).toBe('bar');
});
it('should read a property as JSON', function(){
var json = target.getJSONData('json');
expect(json.foo).toBe('bar');
expect(json.nine).toBe(9);
expect(json.arr).toEqual([1,2,3]);
});
it('should set a property as JSON', function(){
target.setJSONData('json2', {
foo: 'bar', nine: 9, arr: [1,2,3]
});
var json = target.getJSONData('json2');
expect(json.foo).toBe('bar');
expect(json.nine).toBe(9);
expect(json.arr).toEqual([1,2,3]);
});
it('should return null for a non-defined property', function(){
expect(target.getData('baz')).toBeNull();
});
});
})();
|
/*
*
* apiView
*
*/
import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import { FormattedMessage } from 'react-intl'
import { connect } from 'react-redux'
import ReadMargin from 'components/ReadMargin'
import View from 'components/View'
import P from 'components/P'
import messages from './messages'
class WorldView extends PureComponent {
componentDidMount() {
}
render() {
return (
<div>
<View left={true}>
<ReadMargin>
<P><FormattedMessage {...messages.arasaacInWorld} /></P>
</ReadMargin>
</View>
<iframe src="https://www.google.com/maps/d/u/0/embed?mid=1EBR3psLxK-G_WujU93NMWkfisTYK4HwY" width="100%" height="800"></iframe>
</div>
)
}
}
WorldView.propTypes = {
theme: PropTypes.string.isRequired
}
const mapStateToProps = (state) => ({
theme: state.get('theme')
})
export default connect(mapStateToProps)(WorldView)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.